xref: /freebsd/crypto/openssh/ssh-agent.c (revision 2b833162)
1 /* $OpenBSD: ssh-agent.c,v 1.297 2023/03/09 21:06:24 jcs Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * The authentication agent program.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  *
14  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36 
37 #include "includes.h"
38 
39 #include <sys/types.h>
40 #include <sys/resource.h>
41 #include <sys/stat.h>
42 #include <sys/socket.h>
43 #include <sys/wait.h>
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
46 #endif
47 #ifdef HAVE_SYS_UN_H
48 # include <sys/un.h>
49 #endif
50 #include "openbsd-compat/sys-queue.h"
51 
52 #ifdef WITH_OPENSSL
53 #include <openssl/evp.h>
54 #include "openbsd-compat/openssl-compat.h"
55 #endif
56 
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <limits.h>
60 #ifdef HAVE_PATHS_H
61 # include <paths.h>
62 #endif
63 #ifdef HAVE_POLL_H
64 # include <poll.h>
65 #endif
66 #include <signal.h>
67 #include <stdarg.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <time.h>
71 #include <string.h>
72 #include <unistd.h>
73 #ifdef HAVE_UTIL_H
74 # include <util.h>
75 #endif
76 
77 #include "xmalloc.h"
78 #include "ssh.h"
79 #include "ssh2.h"
80 #include "sshbuf.h"
81 #include "sshkey.h"
82 #include "authfd.h"
83 #include "log.h"
84 #include "misc.h"
85 #include "digest.h"
86 #include "ssherr.h"
87 #include "match.h"
88 #include "msg.h"
89 #include "pathnames.h"
90 #include "ssh-pkcs11.h"
91 #include "sk-api.h"
92 #include "myproposal.h"
93 
94 #ifndef DEFAULT_ALLOWED_PROVIDERS
95 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
96 #endif
97 
98 /* Maximum accepted message length */
99 #define AGENT_MAX_LEN		(256*1024)
100 /* Maximum bytes to read from client socket */
101 #define AGENT_RBUF_LEN		(4096)
102 /* Maximum number of recorded session IDs/hostkeys per connection */
103 #define AGENT_MAX_SESSION_IDS		16
104 /* Maximum size of session ID */
105 #define AGENT_MAX_SID_LEN		128
106 /* Maximum number of destination constraints to accept on a key */
107 #define AGENT_MAX_DEST_CONSTRAINTS	1024
108 
109 /* XXX store hostkey_sid in a refcounted tree */
110 
111 typedef enum {
112 	AUTH_UNUSED = 0,
113 	AUTH_SOCKET = 1,
114 	AUTH_CONNECTION = 2,
115 } sock_type;
116 
117 struct hostkey_sid {
118 	struct sshkey *key;
119 	struct sshbuf *sid;
120 	int forwarded;
121 };
122 
123 typedef struct socket_entry {
124 	int fd;
125 	sock_type type;
126 	struct sshbuf *input;
127 	struct sshbuf *output;
128 	struct sshbuf *request;
129 	size_t nsession_ids;
130 	struct hostkey_sid *session_ids;
131 } SocketEntry;
132 
133 u_int sockets_alloc = 0;
134 SocketEntry *sockets = NULL;
135 
136 typedef struct identity {
137 	TAILQ_ENTRY(identity) next;
138 	struct sshkey *key;
139 	char *comment;
140 	char *provider;
141 	time_t death;
142 	u_int confirm;
143 	char *sk_provider;
144 	struct dest_constraint *dest_constraints;
145 	size_t ndest_constraints;
146 } Identity;
147 
148 struct idtable {
149 	int nentries;
150 	TAILQ_HEAD(idqueue, identity) idlist;
151 };
152 
153 /* private key table */
154 struct idtable *idtab;
155 
156 int max_fd = 0;
157 
158 /* pid of shell == parent of agent */
159 pid_t parent_pid = -1;
160 time_t parent_alive_interval = 0;
161 
162 /* pid of process for which cleanup_socket is applicable */
163 pid_t cleanup_pid = 0;
164 
165 /* pathname and directory for AUTH_SOCKET */
166 char socket_name[PATH_MAX];
167 char socket_dir[PATH_MAX];
168 
169 /* Pattern-list of allowed PKCS#11/Security key paths */
170 static char *allowed_providers;
171 
172 /* locking */
173 #define LOCK_SIZE	32
174 #define LOCK_SALT_SIZE	16
175 #define LOCK_ROUNDS	1
176 int locked = 0;
177 u_char lock_pwhash[LOCK_SIZE];
178 u_char lock_salt[LOCK_SALT_SIZE];
179 
180 extern char *__progname;
181 
182 /* Default lifetime in seconds (0 == forever) */
183 static int lifetime = 0;
184 
185 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
186 
187 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
188 static int restrict_websafe = 1;
189 
190 /*
191  * Client connection count; incremented in new_socket() and decremented in
192  * close_socket().  When it reaches 0, ssh-agent will exit.  Since it is
193  * normally initialized to 1, it will never reach 0.  However, if the -x
194  * option is specified, it is initialized to 0 in main(); in that case,
195  * ssh-agent will exit as soon as it has had at least one client but no
196  * longer has any.
197  */
198 static int xcount = 1;
199 
200 static void
201 close_socket(SocketEntry *e)
202 {
203 	size_t i;
204 	int last = 0;
205 
206 	if (e->type == AUTH_CONNECTION) {
207 		debug("xcount %d -> %d", xcount, xcount - 1);
208 		if (--xcount == 0)
209 			last = 1;
210 	}
211 	close(e->fd);
212 	sshbuf_free(e->input);
213 	sshbuf_free(e->output);
214 	sshbuf_free(e->request);
215 	for (i = 0; i < e->nsession_ids; i++) {
216 		sshkey_free(e->session_ids[i].key);
217 		sshbuf_free(e->session_ids[i].sid);
218 	}
219 	free(e->session_ids);
220 	memset(e, '\0', sizeof(*e));
221 	e->fd = -1;
222 	e->type = AUTH_UNUSED;
223 	if (last)
224 		cleanup_exit(0);
225 }
226 
227 static void
228 idtab_init(void)
229 {
230 	idtab = xcalloc(1, sizeof(*idtab));
231 	TAILQ_INIT(&idtab->idlist);
232 	idtab->nentries = 0;
233 }
234 
235 static void
236 free_dest_constraint_hop(struct dest_constraint_hop *dch)
237 {
238 	u_int i;
239 
240 	if (dch == NULL)
241 		return;
242 	free(dch->user);
243 	free(dch->hostname);
244 	for (i = 0; i < dch->nkeys; i++)
245 		sshkey_free(dch->keys[i]);
246 	free(dch->keys);
247 	free(dch->key_is_ca);
248 }
249 
250 static void
251 free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
252 {
253 	size_t i;
254 
255 	for (i = 0; i < ndcs; i++) {
256 		free_dest_constraint_hop(&dcs[i].from);
257 		free_dest_constraint_hop(&dcs[i].to);
258 	}
259 	free(dcs);
260 }
261 
262 static void
263 free_identity(Identity *id)
264 {
265 	sshkey_free(id->key);
266 	free(id->provider);
267 	free(id->comment);
268 	free(id->sk_provider);
269 	free_dest_constraints(id->dest_constraints, id->ndest_constraints);
270 	free(id);
271 }
272 
273 /*
274  * Match 'key' against the key/CA list in a destination constraint hop
275  * Returns 0 on success or -1 otherwise.
276  */
277 static int
278 match_key_hop(const char *tag, const struct sshkey *key,
279     const struct dest_constraint_hop *dch)
280 {
281 	const char *reason = NULL;
282 	const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
283 	u_int i;
284 	char *fp;
285 
286 	if (key == NULL)
287 		return -1;
288 	/* XXX logspam */
289 	if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
290 	    SSH_FP_DEFAULT)) == NULL)
291 		fatal_f("fingerprint failed");
292 	debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
293 	    tag, hostname, sshkey_type(key), fp, dch->nkeys);
294 	free(fp);
295 	for (i = 0; i < dch->nkeys; i++) {
296 		if (dch->keys[i] == NULL)
297 			return -1;
298 		/* XXX logspam */
299 		if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
300 		    SSH_FP_DEFAULT)) == NULL)
301 			fatal_f("fingerprint failed");
302 		debug3_f("%s: key %u: %s%s %s", tag, i,
303 		    dch->key_is_ca[i] ? "CA " : "",
304 		    sshkey_type(dch->keys[i]), fp);
305 		free(fp);
306 		if (!sshkey_is_cert(key)) {
307 			/* plain key */
308 			if (dch->key_is_ca[i] ||
309 			    !sshkey_equal(key, dch->keys[i]))
310 				continue;
311 			return 0;
312 		}
313 		/* certificate */
314 		if (!dch->key_is_ca[i])
315 			continue;
316 		if (key->cert == NULL || key->cert->signature_key == NULL)
317 			return -1; /* shouldn't happen */
318 		if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
319 			continue;
320 		if (sshkey_cert_check_host(key, hostname, 1,
321 		    SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
322 			debug_f("cert %s / hostname %s rejected: %s",
323 			    key->cert->key_id, hostname, reason);
324 			continue;
325 		}
326 		return 0;
327 	}
328 	return -1;
329 }
330 
331 /* Check destination constraints on an identity against the hostkey/user */
332 static int
333 permitted_by_dest_constraints(const struct sshkey *fromkey,
334     const struct sshkey *tokey, Identity *id, const char *user,
335     const char **hostnamep)
336 {
337 	size_t i;
338 	struct dest_constraint *d;
339 
340 	if (hostnamep != NULL)
341 		*hostnamep = NULL;
342 	for (i = 0; i < id->ndest_constraints; i++) {
343 		d = id->dest_constraints + i;
344 		/* XXX remove logspam */
345 		debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
346 		    i, d->from.user ? d->from.user : "",
347 		    d->from.user ? "@" : "",
348 		    d->from.hostname ? d->from.hostname : "(ORIGIN)",
349 		    d->from.nkeys,
350 		    d->to.user ? d->to.user : "", d->to.user ? "@" : "",
351 		    d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
352 
353 		/* Match 'from' key */
354 		if (fromkey == NULL) {
355 			/* We are matching the first hop */
356 			if (d->from.hostname != NULL || d->from.nkeys != 0)
357 				continue;
358 		} else if (match_key_hop("from", fromkey, &d->from) != 0)
359 			continue;
360 
361 		/* Match 'to' key */
362 		if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
363 			continue;
364 
365 		/* Match user if specified */
366 		if (d->to.user != NULL && user != NULL &&
367 		    !match_pattern(user, d->to.user))
368 			continue;
369 
370 		/* successfully matched this constraint */
371 		if (hostnamep != NULL)
372 			*hostnamep = d->to.hostname;
373 		debug2_f("allowed for hostname %s",
374 		    d->to.hostname == NULL ? "*" : d->to.hostname);
375 		return 0;
376 	}
377 	/* no match */
378 	debug2_f("%s identity \"%s\" not permitted for this destination",
379 	    sshkey_type(id->key), id->comment);
380 	return -1;
381 }
382 
383 /*
384  * Check whether hostkeys on a SocketEntry and the optionally specified user
385  * are permitted by the destination constraints on the Identity.
386  * Returns 0 on success or -1 otherwise.
387  */
388 static int
389 identity_permitted(Identity *id, SocketEntry *e, char *user,
390     const char **forward_hostnamep, const char **last_hostnamep)
391 {
392 	size_t i;
393 	const char **hp;
394 	struct hostkey_sid *hks;
395 	const struct sshkey *fromkey = NULL;
396 	const char *test_user;
397 	char *fp1, *fp2;
398 
399 	/* XXX remove logspam */
400 	debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
401 	    "%zu constraints", sshkey_type(id->key), id->comment,
402 	    e->nsession_ids, id->ndest_constraints);
403 	if (id->ndest_constraints == 0)
404 		return 0; /* unconstrained */
405 	if (e->nsession_ids == 0)
406 		return 0; /* local use */
407 	/*
408 	 * Walk through the hops recorded by session_id and try to find a
409 	 * constraint that satisfies each.
410 	 */
411 	for (i = 0; i < e->nsession_ids; i++) {
412 		hks = e->session_ids + i;
413 		if (hks->key == NULL)
414 			fatal_f("internal error: no bound key");
415 		/* XXX remove logspam */
416 		fp1 = fp2 = NULL;
417 		if (fromkey != NULL &&
418 		    (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
419 		    SSH_FP_DEFAULT)) == NULL)
420 			fatal_f("fingerprint failed");
421 		if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
422 		    SSH_FP_DEFAULT)) == NULL)
423 			fatal_f("fingerprint failed");
424 		debug3_f("socketentry fd=%d, entry %zu %s, "
425 		    "from hostkey %s %s to user %s hostkey %s %s",
426 		    e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
427 		    fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
428 		    fromkey ? fp1 : "", user ? user : "(ANY)",
429 		    sshkey_type(hks->key), fp2);
430 		free(fp1);
431 		free(fp2);
432 		/*
433 		 * Record the hostnames for the initial forwarding and
434 		 * the final destination.
435 		 */
436 		hp = NULL;
437 		if (i == e->nsession_ids - 1)
438 			hp = last_hostnamep;
439 		else if (i == 0)
440 			hp = forward_hostnamep;
441 		/* Special handling for final recorded binding */
442 		test_user = NULL;
443 		if (i == e->nsession_ids - 1) {
444 			/* Can only check user at final hop */
445 			test_user = user;
446 			/*
447 			 * user is only presented for signature requests.
448 			 * If this is the case, make sure last binding is not
449 			 * for a forwarding.
450 			 */
451 			if (hks->forwarded && user != NULL) {
452 				error_f("tried to sign on forwarding hop");
453 				return -1;
454 			}
455 		} else if (!hks->forwarded) {
456 			error_f("tried to forward though signing bind");
457 			return -1;
458 		}
459 		if (permitted_by_dest_constraints(fromkey, hks->key, id,
460 		    test_user, hp) != 0)
461 			return -1;
462 		fromkey = hks->key;
463 	}
464 	/*
465 	 * Another special case: if the last bound session ID was for a
466 	 * forwarding, and this function is not being called to check a sign
467 	 * request (i.e. no 'user' supplied), then only permit the key if
468 	 * there is a permission that would allow it to be used at another
469 	 * destination. This hides keys that are allowed to be used to
470 	 * authenticate *to* a host but not permitted for *use* beyond it.
471 	 */
472 	hks = &e->session_ids[e->nsession_ids - 1];
473 	if (hks->forwarded && user == NULL &&
474 	    permitted_by_dest_constraints(hks->key, NULL, id,
475 	    NULL, NULL) != 0) {
476 		debug3_f("key permitted at host but not after");
477 		return -1;
478 	}
479 
480 	/* success */
481 	return 0;
482 }
483 
484 /* return matching private key for given public key */
485 static Identity *
486 lookup_identity(struct sshkey *key)
487 {
488 	Identity *id;
489 
490 	TAILQ_FOREACH(id, &idtab->idlist, next) {
491 		if (sshkey_equal(key, id->key))
492 			return (id);
493 	}
494 	return (NULL);
495 }
496 
497 /* Check confirmation of keysign request */
498 static int
499 confirm_key(Identity *id, const char *extra)
500 {
501 	char *p;
502 	int ret = -1;
503 
504 	p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
505 	if (p != NULL &&
506 	    ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
507 	    id->comment, p,
508 	    extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
509 		ret = 0;
510 	free(p);
511 
512 	return (ret);
513 }
514 
515 static void
516 send_status(SocketEntry *e, int success)
517 {
518 	int r;
519 
520 	if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
521 	    (r = sshbuf_put_u8(e->output, success ?
522 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
523 		fatal_fr(r, "compose");
524 }
525 
526 /* send list of supported public keys to 'client' */
527 static void
528 process_request_identities(SocketEntry *e)
529 {
530 	Identity *id;
531 	struct sshbuf *msg, *keys;
532 	int r;
533 	u_int nentries = 0;
534 
535 	debug2_f("entering");
536 
537 	if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
538 		fatal_f("sshbuf_new failed");
539 	TAILQ_FOREACH(id, &idtab->idlist, next) {
540 		/* identity not visible, don't include in response */
541 		if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
542 			continue;
543 		if ((r = sshkey_puts_opts(id->key, keys,
544 		    SSHKEY_SERIALIZE_INFO)) != 0 ||
545 		    (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
546 			error_fr(r, "compose key/comment");
547 			continue;
548 		}
549 		nentries++;
550 	}
551 	debug2_f("replying with %u allowed of %u available keys",
552 	    nentries, idtab->nentries);
553 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
554 	    (r = sshbuf_put_u32(msg, nentries)) != 0 ||
555 	    (r = sshbuf_putb(msg, keys)) != 0)
556 		fatal_fr(r, "compose");
557 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
558 		fatal_fr(r, "enqueue");
559 	sshbuf_free(msg);
560 	sshbuf_free(keys);
561 }
562 
563 
564 static char *
565 agent_decode_alg(struct sshkey *key, u_int flags)
566 {
567 	if (key->type == KEY_RSA) {
568 		if (flags & SSH_AGENT_RSA_SHA2_256)
569 			return "rsa-sha2-256";
570 		else if (flags & SSH_AGENT_RSA_SHA2_512)
571 			return "rsa-sha2-512";
572 	} else if (key->type == KEY_RSA_CERT) {
573 		if (flags & SSH_AGENT_RSA_SHA2_256)
574 			return "rsa-sha2-256-cert-v01@openssh.com";
575 		else if (flags & SSH_AGENT_RSA_SHA2_512)
576 			return "rsa-sha2-512-cert-v01@openssh.com";
577 	}
578 	return NULL;
579 }
580 
581 /*
582  * Attempt to parse the contents of a buffer as a SSH publickey userauth
583  * request, checking its contents for consistency and matching the embedded
584  * key against the one that is being used for signing.
585  * Note: does not modify msg buffer.
586  * Optionally extract the username, session ID and/or hostkey from the request.
587  */
588 static int
589 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
590     char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
591 {
592 	struct sshbuf *b = NULL, *sess_id = NULL;
593 	char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
594 	int r;
595 	u_char t, sig_follows;
596 	struct sshkey *mkey = NULL, *hostkey = NULL;
597 
598 	if (userp != NULL)
599 		*userp = NULL;
600 	if (sess_idp != NULL)
601 		*sess_idp = NULL;
602 	if (hostkeyp != NULL)
603 		*hostkeyp = NULL;
604 	if ((b = sshbuf_fromb(msg)) == NULL)
605 		fatal_f("sshbuf_fromb");
606 
607 	/* SSH userauth request */
608 	if ((r = sshbuf_froms(b, &sess_id)) != 0)
609 		goto out;
610 	if (sshbuf_len(sess_id) == 0) {
611 		r = SSH_ERR_INVALID_FORMAT;
612 		goto out;
613 	}
614 	if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
615 	    (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
616 	    (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
617 	    (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
618 	    (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
619 	    (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
620 	    (r = sshkey_froms(b, &mkey)) != 0) /* key */
621 		goto out;
622 	if (t != SSH2_MSG_USERAUTH_REQUEST ||
623 	    sig_follows != 1 ||
624 	    strcmp(service, "ssh-connection") != 0 ||
625 	    !sshkey_equal(expected_key, mkey) ||
626 	    sshkey_type_from_name(pkalg) != expected_key->type) {
627 		r = SSH_ERR_INVALID_FORMAT;
628 		goto out;
629 	}
630 	if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
631 		if ((r = sshkey_froms(b, &hostkey)) != 0)
632 			goto out;
633 	} else if (strcmp(method, "publickey") != 0) {
634 		r = SSH_ERR_INVALID_FORMAT;
635 		goto out;
636 	}
637 	if (sshbuf_len(b) != 0) {
638 		r = SSH_ERR_INVALID_FORMAT;
639 		goto out;
640 	}
641 	/* success */
642 	r = 0;
643 	debug3_f("well formed userauth");
644 	if (userp != NULL) {
645 		*userp = user;
646 		user = NULL;
647 	}
648 	if (sess_idp != NULL) {
649 		*sess_idp = sess_id;
650 		sess_id = NULL;
651 	}
652 	if (hostkeyp != NULL) {
653 		*hostkeyp = hostkey;
654 		hostkey = NULL;
655 	}
656  out:
657 	sshbuf_free(b);
658 	sshbuf_free(sess_id);
659 	free(user);
660 	free(service);
661 	free(method);
662 	free(pkalg);
663 	sshkey_free(mkey);
664 	sshkey_free(hostkey);
665 	return r;
666 }
667 
668 /*
669  * Attempt to parse the contents of a buffer as a SSHSIG signature request.
670  * Note: does not modify buffer.
671  */
672 static int
673 parse_sshsig_request(struct sshbuf *msg)
674 {
675 	int r;
676 	struct sshbuf *b;
677 
678 	if ((b = sshbuf_fromb(msg)) == NULL)
679 		fatal_f("sshbuf_fromb");
680 
681 	if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
682 	    (r = sshbuf_consume(b, 6)) != 0 ||
683 	    (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
684 	    (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
685 	    (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
686 	    (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
687 		goto out;
688 	if (sshbuf_len(b) != 0) {
689 		r = SSH_ERR_INVALID_FORMAT;
690 		goto out;
691 	}
692 	/* success */
693 	r = 0;
694  out:
695 	sshbuf_free(b);
696 	return r;
697 }
698 
699 /*
700  * This function inspects a message to be signed by a FIDO key that has a
701  * web-like application string (i.e. one that does not begin with "ssh:".
702  * It checks that the message is one of those expected for SSH operations
703  * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
704  * for the web.
705  */
706 static int
707 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
708 {
709 	if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
710 		debug_f("signed data matches public key userauth request");
711 		return 1;
712 	}
713 	if (parse_sshsig_request(data) == 0) {
714 		debug_f("signed data matches SSHSIG signature request");
715 		return 1;
716 	}
717 
718 	/* XXX check CA signature operation */
719 
720 	error("web-origin key attempting to sign non-SSH message");
721 	return 0;
722 }
723 
724 static int
725 buf_equal(const struct sshbuf *a, const struct sshbuf *b)
726 {
727 	if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
728 		return SSH_ERR_INVALID_ARGUMENT;
729 	if (sshbuf_len(a) != sshbuf_len(b))
730 		return SSH_ERR_INVALID_FORMAT;
731 	if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
732 		return SSH_ERR_INVALID_FORMAT;
733 	return 0;
734 }
735 
736 /* ssh2 only */
737 static void
738 process_sign_request2(SocketEntry *e)
739 {
740 	u_char *signature = NULL;
741 	size_t slen = 0;
742 	u_int compat = 0, flags;
743 	int r, ok = -1, retried = 0;
744 	char *fp = NULL, *pin = NULL, *prompt = NULL;
745 	char *user = NULL, *sig_dest = NULL;
746 	const char *fwd_host = NULL, *dest_host = NULL;
747 	struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
748 	struct sshkey *key = NULL, *hostkey = NULL;
749 	struct identity *id;
750 	struct notifier_ctx *notifier = NULL;
751 
752 	debug_f("entering");
753 
754 	if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
755 		fatal_f("sshbuf_new failed");
756 	if ((r = sshkey_froms(e->request, &key)) != 0 ||
757 	    (r = sshbuf_get_stringb(e->request, data)) != 0 ||
758 	    (r = sshbuf_get_u32(e->request, &flags)) != 0) {
759 		error_fr(r, "parse");
760 		goto send;
761 	}
762 
763 	if ((id = lookup_identity(key)) == NULL) {
764 		verbose_f("%s key not found", sshkey_type(key));
765 		goto send;
766 	}
767 	if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
768 	    SSH_FP_DEFAULT)) == NULL)
769 		fatal_f("fingerprint failed");
770 
771 	if (id->ndest_constraints != 0) {
772 		if (e->nsession_ids == 0) {
773 			logit_f("refusing use of destination-constrained key "
774 			    "to sign on unbound connection");
775 			goto send;
776 		}
777 		if (parse_userauth_request(data, key, &user, &sid,
778 		    &hostkey) != 0) {
779 			logit_f("refusing use of destination-constrained key "
780 			   "to sign an unidentified signature");
781 			goto send;
782 		}
783 		/* XXX logspam */
784 		debug_f("user=%s", user);
785 		if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
786 			goto send;
787 		/* XXX display fwd_host/dest_host in askpass UI */
788 		/*
789 		 * Ensure that the session ID is the most recent one
790 		 * registered on the socket - it should have been bound by
791 		 * ssh immediately before userauth.
792 		 */
793 		if (buf_equal(sid,
794 		    e->session_ids[e->nsession_ids - 1].sid) != 0) {
795 			error_f("unexpected session ID (%zu listed) on "
796 			    "signature request for target user %s with "
797 			    "key %s %s", e->nsession_ids, user,
798 			    sshkey_type(id->key), fp);
799 			goto send;
800 		}
801 		/*
802 		 * Ensure that the hostkey embedded in the signature matches
803 		 * the one most recently bound to the socket. An exception is
804 		 * made for the initial forwarding hop.
805 		 */
806 		if (e->nsession_ids > 1 && hostkey == NULL) {
807 			error_f("refusing use of destination-constrained key: "
808 			    "no hostkey recorded in signature for forwarded "
809 			    "connection");
810 			goto send;
811 		}
812 		if (hostkey != NULL && !sshkey_equal(hostkey,
813 		    e->session_ids[e->nsession_ids - 1].key)) {
814 			error_f("refusing use of destination-constrained key: "
815 			    "mismatch between hostkey in request and most "
816 			    "recently bound session");
817 			goto send;
818 		}
819 		xasprintf(&sig_dest, "public key authentication request for "
820 		    "user \"%s\" to listed host", user);
821 	}
822 	if (id->confirm && confirm_key(id, sig_dest) != 0) {
823 		verbose_f("user refused key");
824 		goto send;
825 	}
826 	if (sshkey_is_sk(id->key)) {
827 		if (restrict_websafe &&
828 		    strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
829 		    !check_websafe_message_contents(key, data)) {
830 			/* error already logged */
831 			goto send;
832 		}
833 		if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
834 			notifier = notify_start(0,
835 			    "Confirm user presence for key %s %s%s%s",
836 			    sshkey_type(id->key), fp,
837 			    sig_dest == NULL ? "" : "\n",
838 			    sig_dest == NULL ? "" : sig_dest);
839 		}
840 	}
841  retry_pin:
842 	if ((r = sshkey_sign(id->key, &signature, &slen,
843 	    sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
844 	    id->sk_provider, pin, compat)) != 0) {
845 		debug_fr(r, "sshkey_sign");
846 		if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
847 		    r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
848 			notify_complete(notifier, NULL);
849 			notifier = NULL;
850 			/* XXX include sig_dest */
851 			xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
852 			    (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
853 			    " and confirm user presence " : " ",
854 			    sshkey_type(id->key), fp);
855 			pin = read_passphrase(prompt, RP_USE_ASKPASS);
856 			retried = 1;
857 			goto retry_pin;
858 		}
859 		error_fr(r, "sshkey_sign");
860 		goto send;
861 	}
862 	/* Success */
863 	ok = 0;
864  send:
865 	debug_f("good signature");
866 	notify_complete(notifier, "User presence confirmed");
867 
868 	if (ok == 0) {
869 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
870 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
871 			fatal_fr(r, "compose");
872 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
873 		fatal_fr(r, "compose failure");
874 
875 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
876 		fatal_fr(r, "enqueue");
877 
878 	sshbuf_free(sid);
879 	sshbuf_free(data);
880 	sshbuf_free(msg);
881 	sshkey_free(key);
882 	sshkey_free(hostkey);
883 	free(fp);
884 	free(signature);
885 	free(sig_dest);
886 	free(user);
887 	free(prompt);
888 	if (pin != NULL)
889 		freezero(pin, strlen(pin));
890 }
891 
892 /* shared */
893 static void
894 process_remove_identity(SocketEntry *e)
895 {
896 	int r, success = 0;
897 	struct sshkey *key = NULL;
898 	Identity *id;
899 
900 	debug2_f("entering");
901 	if ((r = sshkey_froms(e->request, &key)) != 0) {
902 		error_fr(r, "parse key");
903 		goto done;
904 	}
905 	if ((id = lookup_identity(key)) == NULL) {
906 		debug_f("key not found");
907 		goto done;
908 	}
909 	/* identity not visible, cannot be removed */
910 	if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
911 		goto done; /* error already logged */
912 	/* We have this key, free it. */
913 	if (idtab->nentries < 1)
914 		fatal_f("internal error: nentries %d", idtab->nentries);
915 	TAILQ_REMOVE(&idtab->idlist, id, next);
916 	free_identity(id);
917 	idtab->nentries--;
918 	success = 1;
919  done:
920 	sshkey_free(key);
921 	send_status(e, success);
922 }
923 
924 static void
925 process_remove_all_identities(SocketEntry *e)
926 {
927 	Identity *id;
928 
929 	debug2_f("entering");
930 	/* Loop over all identities and clear the keys. */
931 	for (id = TAILQ_FIRST(&idtab->idlist); id;
932 	    id = TAILQ_FIRST(&idtab->idlist)) {
933 		TAILQ_REMOVE(&idtab->idlist, id, next);
934 		free_identity(id);
935 	}
936 
937 	/* Mark that there are no identities. */
938 	idtab->nentries = 0;
939 
940 	/* Send success. */
941 	send_status(e, 1);
942 }
943 
944 /* removes expired keys and returns number of seconds until the next expiry */
945 static time_t
946 reaper(void)
947 {
948 	time_t deadline = 0, now = monotime();
949 	Identity *id, *nxt;
950 
951 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
952 		nxt = TAILQ_NEXT(id, next);
953 		if (id->death == 0)
954 			continue;
955 		if (now >= id->death) {
956 			debug("expiring key '%s'", id->comment);
957 			TAILQ_REMOVE(&idtab->idlist, id, next);
958 			free_identity(id);
959 			idtab->nentries--;
960 		} else
961 			deadline = (deadline == 0) ? id->death :
962 			    MINIMUM(deadline, id->death);
963 	}
964 	if (deadline == 0 || deadline <= now)
965 		return 0;
966 	else
967 		return (deadline - now);
968 }
969 
970 static int
971 parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
972 {
973 	u_char key_is_ca;
974 	size_t elen = 0;
975 	int r;
976 	struct sshkey *k = NULL;
977 	char *fp;
978 
979 	memset(dch, '\0', sizeof(*dch));
980 	if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
981 	    (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
982 	    (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
983 		error_fr(r, "parse");
984 		goto out;
985 	}
986 	if (elen != 0) {
987 		error_f("unsupported extensions (len %zu)", elen);
988 		r = SSH_ERR_FEATURE_UNSUPPORTED;
989 		goto out;
990 	}
991 	if (*dch->hostname == '\0') {
992 		free(dch->hostname);
993 		dch->hostname = NULL;
994 	}
995 	if (*dch->user == '\0') {
996 		free(dch->user);
997 		dch->user = NULL;
998 	}
999 	while (sshbuf_len(b) != 0) {
1000 		dch->keys = xrecallocarray(dch->keys, dch->nkeys,
1001 		    dch->nkeys + 1, sizeof(*dch->keys));
1002 		dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
1003 		    dch->nkeys + 1, sizeof(*dch->key_is_ca));
1004 		if ((r = sshkey_froms(b, &k)) != 0 ||
1005 		    (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
1006 			goto out;
1007 		if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1008 		    SSH_FP_DEFAULT)) == NULL)
1009 			fatal_f("fingerprint failed");
1010 		debug3_f("%s%s%s: adding %skey %s %s",
1011 		    dch->user == NULL ? "" : dch->user,
1012 		    dch->user == NULL ? "" : "@",
1013 		    dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
1014 		free(fp);
1015 		dch->keys[dch->nkeys] = k;
1016 		dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
1017 		dch->nkeys++;
1018 		k = NULL; /* transferred */
1019 	}
1020 	/* success */
1021 	r = 0;
1022  out:
1023 	sshkey_free(k);
1024 	return r;
1025 }
1026 
1027 static int
1028 parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1029 {
1030 	struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1031 	int r;
1032 	size_t elen = 0;
1033 
1034 	debug3_f("entering");
1035 
1036 	memset(dc, '\0', sizeof(*dc));
1037 	if ((r = sshbuf_froms(m, &b)) != 0 ||
1038 	    (r = sshbuf_froms(b, &frombuf)) != 0 ||
1039 	    (r = sshbuf_froms(b, &tobuf)) != 0 ||
1040 	    (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1041 		error_fr(r, "parse");
1042 		goto out;
1043 	}
1044 	if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
1045 	    (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
1046 		goto out; /* already logged */
1047 	if (elen != 0) {
1048 		error_f("unsupported extensions (len %zu)", elen);
1049 		r = SSH_ERR_FEATURE_UNSUPPORTED;
1050 		goto out;
1051 	}
1052 	debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1053 	    dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1054 	    dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1055 	    dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1056 	/* check consistency */
1057 	if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1058 	    dc->from.user != NULL) {
1059 		error_f("inconsistent \"from\" specification");
1060 		r = SSH_ERR_INVALID_FORMAT;
1061 		goto out;
1062 	}
1063 	if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1064 		error_f("incomplete \"to\" specification");
1065 		r = SSH_ERR_INVALID_FORMAT;
1066 		goto out;
1067 	}
1068 	/* success */
1069 	r = 0;
1070  out:
1071 	sshbuf_free(b);
1072 	sshbuf_free(frombuf);
1073 	sshbuf_free(tobuf);
1074 	return r;
1075 }
1076 
1077 static int
1078 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1079     struct dest_constraint **dcsp, size_t *ndcsp)
1080 {
1081 	char *ext_name = NULL;
1082 	int r;
1083 	struct sshbuf *b = NULL;
1084 
1085 	if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1086 		error_fr(r, "parse constraint extension");
1087 		goto out;
1088 	}
1089 	debug_f("constraint ext %s", ext_name);
1090 	if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1091 		if (sk_providerp == NULL) {
1092 			error_f("%s not valid here", ext_name);
1093 			r = SSH_ERR_INVALID_FORMAT;
1094 			goto out;
1095 		}
1096 		if (*sk_providerp != NULL) {
1097 			error_f("%s already set", ext_name);
1098 			r = SSH_ERR_INVALID_FORMAT;
1099 			goto out;
1100 		}
1101 		if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1102 			error_fr(r, "parse %s", ext_name);
1103 			goto out;
1104 		}
1105 	} else if (strcmp(ext_name,
1106 	    "restrict-destination-v00@openssh.com") == 0) {
1107 		if (*dcsp != NULL) {
1108 			error_f("%s already set", ext_name);
1109 			goto out;
1110 		}
1111 		if ((r = sshbuf_froms(m, &b)) != 0) {
1112 			error_fr(r, "parse %s outer", ext_name);
1113 			goto out;
1114 		}
1115 		while (sshbuf_len(b) != 0) {
1116 			if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1117 				error_f("too many %s constraints", ext_name);
1118 				goto out;
1119 			}
1120 			*dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1121 			    sizeof(**dcsp));
1122 			if ((r = parse_dest_constraint(b,
1123 			    *dcsp + (*ndcsp)++)) != 0)
1124 				goto out; /* error already logged */
1125 		}
1126 	} else {
1127 		error_f("unsupported constraint \"%s\"", ext_name);
1128 		r = SSH_ERR_FEATURE_UNSUPPORTED;
1129 		goto out;
1130 	}
1131 	/* success */
1132 	r = 0;
1133  out:
1134 	free(ext_name);
1135 	sshbuf_free(b);
1136 	return r;
1137 }
1138 
1139 static int
1140 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1141     u_int *secondsp, int *confirmp, char **sk_providerp,
1142     struct dest_constraint **dcsp, size_t *ndcsp)
1143 {
1144 	u_char ctype;
1145 	int r;
1146 	u_int seconds, maxsign = 0;
1147 
1148 	while (sshbuf_len(m)) {
1149 		if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1150 			error_fr(r, "parse constraint type");
1151 			goto out;
1152 		}
1153 		switch (ctype) {
1154 		case SSH_AGENT_CONSTRAIN_LIFETIME:
1155 			if (*deathp != 0) {
1156 				error_f("lifetime already set");
1157 				r = SSH_ERR_INVALID_FORMAT;
1158 				goto out;
1159 			}
1160 			if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1161 				error_fr(r, "parse lifetime constraint");
1162 				goto out;
1163 			}
1164 			*deathp = monotime() + seconds;
1165 			*secondsp = seconds;
1166 			break;
1167 		case SSH_AGENT_CONSTRAIN_CONFIRM:
1168 			if (*confirmp != 0) {
1169 				error_f("confirm already set");
1170 				r = SSH_ERR_INVALID_FORMAT;
1171 				goto out;
1172 			}
1173 			*confirmp = 1;
1174 			break;
1175 		case SSH_AGENT_CONSTRAIN_MAXSIGN:
1176 			if (k == NULL) {
1177 				error_f("maxsign not valid here");
1178 				r = SSH_ERR_INVALID_FORMAT;
1179 				goto out;
1180 			}
1181 			if (maxsign != 0) {
1182 				error_f("maxsign already set");
1183 				r = SSH_ERR_INVALID_FORMAT;
1184 				goto out;
1185 			}
1186 			if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
1187 				error_fr(r, "parse maxsign constraint");
1188 				goto out;
1189 			}
1190 			if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
1191 				error_fr(r, "enable maxsign");
1192 				goto out;
1193 			}
1194 			break;
1195 		case SSH_AGENT_CONSTRAIN_EXTENSION:
1196 			if ((r = parse_key_constraint_extension(m,
1197 			    sk_providerp, dcsp, ndcsp)) != 0)
1198 				goto out; /* error already logged */
1199 			break;
1200 		default:
1201 			error_f("Unknown constraint %d", ctype);
1202 			r = SSH_ERR_FEATURE_UNSUPPORTED;
1203 			goto out;
1204 		}
1205 	}
1206 	/* success */
1207 	r = 0;
1208  out:
1209 	return r;
1210 }
1211 
1212 static void
1213 process_add_identity(SocketEntry *e)
1214 {
1215 	Identity *id;
1216 	int success = 0, confirm = 0;
1217 	char *fp, *comment = NULL, *sk_provider = NULL;
1218 	char canonical_provider[PATH_MAX];
1219 	time_t death = 0;
1220 	u_int seconds = 0;
1221 	struct dest_constraint *dest_constraints = NULL;
1222 	size_t ndest_constraints = 0;
1223 	struct sshkey *k = NULL;
1224 	int r = SSH_ERR_INTERNAL_ERROR;
1225 
1226 	debug2_f("entering");
1227 	if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1228 	    k == NULL ||
1229 	    (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1230 		error_fr(r, "parse");
1231 		goto out;
1232 	}
1233 	if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1234 	    &sk_provider, &dest_constraints, &ndest_constraints) != 0) {
1235 		error_f("failed to parse constraints");
1236 		sshbuf_reset(e->request);
1237 		goto out;
1238 	}
1239 
1240 	if (sk_provider != NULL) {
1241 		if (!sshkey_is_sk(k)) {
1242 			error("Cannot add provider: %s is not an "
1243 			    "authenticator-hosted key", sshkey_type(k));
1244 			goto out;
1245 		}
1246 		if (strcasecmp(sk_provider, "internal") == 0) {
1247 			debug_f("internal provider");
1248 		} else {
1249 			if (realpath(sk_provider, canonical_provider) == NULL) {
1250 				verbose("failed provider \"%.100s\": "
1251 				    "realpath: %s", sk_provider,
1252 				    strerror(errno));
1253 				goto out;
1254 			}
1255 			free(sk_provider);
1256 			sk_provider = xstrdup(canonical_provider);
1257 			if (match_pattern_list(sk_provider,
1258 			    allowed_providers, 0) != 1) {
1259 				error("Refusing add key: "
1260 				    "provider %s not allowed", sk_provider);
1261 				goto out;
1262 			}
1263 		}
1264 	}
1265 	if ((r = sshkey_shield_private(k)) != 0) {
1266 		error_fr(r, "shield private");
1267 		goto out;
1268 	}
1269 	if (lifetime && !death)
1270 		death = monotime() + lifetime;
1271 	if ((id = lookup_identity(k)) == NULL) {
1272 		id = xcalloc(1, sizeof(Identity));
1273 		TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1274 		/* Increment the number of identities. */
1275 		idtab->nentries++;
1276 	} else {
1277 		/* identity not visible, do not update */
1278 		if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1279 			goto out; /* error already logged */
1280 		/* key state might have been updated */
1281 		sshkey_free(id->key);
1282 		free(id->comment);
1283 		free(id->sk_provider);
1284 		free_dest_constraints(id->dest_constraints,
1285 		    id->ndest_constraints);
1286 	}
1287 	/* success */
1288 	id->key = k;
1289 	id->comment = comment;
1290 	id->death = death;
1291 	id->confirm = confirm;
1292 	id->sk_provider = sk_provider;
1293 	id->dest_constraints = dest_constraints;
1294 	id->ndest_constraints = ndest_constraints;
1295 
1296 	if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1297 	    SSH_FP_DEFAULT)) == NULL)
1298 		fatal_f("sshkey_fingerprint failed");
1299 	debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1300 	    "(provider: %s) (destination constraints: %zu)",
1301 	    sshkey_ssh_name(k), fp, comment, seconds, confirm,
1302 	    sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1303 	free(fp);
1304 	/* transferred */
1305 	k = NULL;
1306 	comment = NULL;
1307 	sk_provider = NULL;
1308 	dest_constraints = NULL;
1309 	ndest_constraints = 0;
1310 	success = 1;
1311  out:
1312 	free(sk_provider);
1313 	free(comment);
1314 	sshkey_free(k);
1315 	free_dest_constraints(dest_constraints, ndest_constraints);
1316 	send_status(e, success);
1317 }
1318 
1319 /* XXX todo: encrypt sensitive data with passphrase */
1320 static void
1321 process_lock_agent(SocketEntry *e, int lock)
1322 {
1323 	int r, success = 0, delay;
1324 	char *passwd;
1325 	u_char passwdhash[LOCK_SIZE];
1326 	static u_int fail_count = 0;
1327 	size_t pwlen;
1328 
1329 	debug2_f("entering");
1330 	/*
1331 	 * This is deliberately fatal: the user has requested that we lock,
1332 	 * but we can't parse their request properly. The only safe thing to
1333 	 * do is abort.
1334 	 */
1335 	if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1336 		fatal_fr(r, "parse");
1337 	if (pwlen == 0) {
1338 		debug("empty password not supported");
1339 	} else if (locked && !lock) {
1340 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1341 		    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1342 			fatal("bcrypt_pbkdf");
1343 		if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1344 			debug("agent unlocked");
1345 			locked = 0;
1346 			fail_count = 0;
1347 			explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1348 			success = 1;
1349 		} else {
1350 			/* delay in 0.1s increments up to 10s */
1351 			if (fail_count < 100)
1352 				fail_count++;
1353 			delay = 100000 * fail_count;
1354 			debug("unlock failed, delaying %0.1lf seconds",
1355 			    (double)delay/1000000);
1356 			usleep(delay);
1357 		}
1358 		explicit_bzero(passwdhash, sizeof(passwdhash));
1359 	} else if (!locked && lock) {
1360 		debug("agent locked");
1361 		locked = 1;
1362 		arc4random_buf(lock_salt, sizeof(lock_salt));
1363 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1364 		    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1365 			fatal("bcrypt_pbkdf");
1366 		success = 1;
1367 	}
1368 	freezero(passwd, pwlen);
1369 	send_status(e, success);
1370 }
1371 
1372 static void
1373 no_identities(SocketEntry *e)
1374 {
1375 	struct sshbuf *msg;
1376 	int r;
1377 
1378 	if ((msg = sshbuf_new()) == NULL)
1379 		fatal_f("sshbuf_new failed");
1380 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1381 	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
1382 	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
1383 		fatal_fr(r, "compose");
1384 	sshbuf_free(msg);
1385 }
1386 
1387 #ifdef ENABLE_PKCS11
1388 static void
1389 process_add_smartcard_key(SocketEntry *e)
1390 {
1391 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1392 	char **comments = NULL;
1393 	int r, i, count = 0, success = 0, confirm = 0;
1394 	u_int seconds = 0;
1395 	time_t death = 0;
1396 	struct sshkey **keys = NULL, *k;
1397 	Identity *id;
1398 	struct dest_constraint *dest_constraints = NULL;
1399 	size_t ndest_constraints = 0;
1400 
1401 	debug2_f("entering");
1402 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1403 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1404 		error_fr(r, "parse");
1405 		goto send;
1406 	}
1407 	if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1408 	    NULL, &dest_constraints, &ndest_constraints) != 0) {
1409 		error_f("failed to parse constraints");
1410 		goto send;
1411 	}
1412 	if (realpath(provider, canonical_provider) == NULL) {
1413 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1414 		    provider, strerror(errno));
1415 		goto send;
1416 	}
1417 	if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1418 		verbose("refusing PKCS#11 add of \"%.100s\": "
1419 		    "provider not allowed", canonical_provider);
1420 		goto send;
1421 	}
1422 	debug_f("add %.100s", canonical_provider);
1423 	if (lifetime && !death)
1424 		death = monotime() + lifetime;
1425 
1426 	count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1427 	for (i = 0; i < count; i++) {
1428 		k = keys[i];
1429 		if (lookup_identity(k) == NULL) {
1430 			id = xcalloc(1, sizeof(Identity));
1431 			id->key = k;
1432 			keys[i] = NULL; /* transferred */
1433 			id->provider = xstrdup(canonical_provider);
1434 			if (*comments[i] != '\0') {
1435 				id->comment = comments[i];
1436 				comments[i] = NULL; /* transferred */
1437 			} else {
1438 				id->comment = xstrdup(canonical_provider);
1439 			}
1440 			id->death = death;
1441 			id->confirm = confirm;
1442 			id->dest_constraints = dest_constraints;
1443 			id->ndest_constraints = ndest_constraints;
1444 			dest_constraints = NULL; /* transferred */
1445 			ndest_constraints = 0;
1446 			TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1447 			idtab->nentries++;
1448 			success = 1;
1449 		}
1450 		/* XXX update constraints for existing keys */
1451 		sshkey_free(keys[i]);
1452 		free(comments[i]);
1453 	}
1454 send:
1455 	free(pin);
1456 	free(provider);
1457 	free(keys);
1458 	free(comments);
1459 	free_dest_constraints(dest_constraints, ndest_constraints);
1460 	send_status(e, success);
1461 }
1462 
1463 static void
1464 process_remove_smartcard_key(SocketEntry *e)
1465 {
1466 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1467 	int r, success = 0;
1468 	Identity *id, *nxt;
1469 
1470 	debug2_f("entering");
1471 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1472 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1473 		error_fr(r, "parse");
1474 		goto send;
1475 	}
1476 	free(pin);
1477 
1478 	if (realpath(provider, canonical_provider) == NULL) {
1479 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1480 		    provider, strerror(errno));
1481 		goto send;
1482 	}
1483 
1484 	debug_f("remove %.100s", canonical_provider);
1485 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1486 		nxt = TAILQ_NEXT(id, next);
1487 		/* Skip file--based keys */
1488 		if (id->provider == NULL)
1489 			continue;
1490 		if (!strcmp(canonical_provider, id->provider)) {
1491 			TAILQ_REMOVE(&idtab->idlist, id, next);
1492 			free_identity(id);
1493 			idtab->nentries--;
1494 		}
1495 	}
1496 	if (pkcs11_del_provider(canonical_provider) == 0)
1497 		success = 1;
1498 	else
1499 		error_f("pkcs11_del_provider failed");
1500 send:
1501 	free(provider);
1502 	send_status(e, success);
1503 }
1504 #endif /* ENABLE_PKCS11 */
1505 
1506 static int
1507 process_ext_session_bind(SocketEntry *e)
1508 {
1509 	int r, sid_match, key_match;
1510 	struct sshkey *key = NULL;
1511 	struct sshbuf *sid = NULL, *sig = NULL;
1512 	char *fp = NULL;
1513 	size_t i;
1514 	u_char fwd = 0;
1515 
1516 	debug2_f("entering");
1517 	if ((r = sshkey_froms(e->request, &key)) != 0 ||
1518 	    (r = sshbuf_froms(e->request, &sid)) != 0 ||
1519 	    (r = sshbuf_froms(e->request, &sig)) != 0 ||
1520 	    (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1521 		error_fr(r, "parse");
1522 		goto out;
1523 	}
1524 	if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1525 	    SSH_FP_DEFAULT)) == NULL)
1526 		fatal_f("fingerprint failed");
1527 	/* check signature with hostkey on session ID */
1528 	if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1529 	    sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1530 		error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1531 		goto out;
1532 	}
1533 	/* check whether sid/key already recorded */
1534 	for (i = 0; i < e->nsession_ids; i++) {
1535 		if (!e->session_ids[i].forwarded) {
1536 			error_f("attempt to bind session ID to socket "
1537 			    "previously bound for authentication attempt");
1538 			r = -1;
1539 			goto out;
1540 		}
1541 		sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1542 		key_match = sshkey_equal(key, e->session_ids[i].key);
1543 		if (sid_match && key_match) {
1544 			debug_f("session ID already recorded for %s %s",
1545 			    sshkey_type(key), fp);
1546 			r = 0;
1547 			goto out;
1548 		} else if (sid_match) {
1549 			error_f("session ID recorded against different key "
1550 			    "for %s %s", sshkey_type(key), fp);
1551 			r = -1;
1552 			goto out;
1553 		}
1554 		/*
1555 		 * new sid with previously-seen key can happen, e.g. multiple
1556 		 * connections to the same host.
1557 		 */
1558 	}
1559 	/* record new key/sid */
1560 	if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1561 		error_f("too many session IDs recorded");
1562 		goto out;
1563 	}
1564 	e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1565 	    e->nsession_ids + 1, sizeof(*e->session_ids));
1566 	i = e->nsession_ids++;
1567 	debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1568 	    AGENT_MAX_SESSION_IDS);
1569 	e->session_ids[i].key = key;
1570 	e->session_ids[i].forwarded = fwd != 0;
1571 	key = NULL; /* transferred */
1572 	/* can't transfer sid; it's refcounted and scoped to request's life */
1573 	if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1574 		fatal_f("sshbuf_new");
1575 	if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1576 		fatal_fr(r, "sshbuf_putb session ID");
1577 	/* success */
1578 	r = 0;
1579  out:
1580 	free(fp);
1581 	sshkey_free(key);
1582 	sshbuf_free(sid);
1583 	sshbuf_free(sig);
1584 	return r == 0 ? 1 : 0;
1585 }
1586 
1587 static void
1588 process_extension(SocketEntry *e)
1589 {
1590 	int r, success = 0;
1591 	char *name;
1592 
1593 	debug2_f("entering");
1594 	if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1595 		error_fr(r, "parse");
1596 		goto send;
1597 	}
1598 	if (strcmp(name, "session-bind@openssh.com") == 0)
1599 		success = process_ext_session_bind(e);
1600 	else
1601 		debug_f("unsupported extension \"%s\"", name);
1602 	free(name);
1603 send:
1604 	send_status(e, success);
1605 }
1606 /*
1607  * dispatch incoming message.
1608  * returns 1 on success, 0 for incomplete messages or -1 on error.
1609  */
1610 static int
1611 process_message(u_int socknum)
1612 {
1613 	u_int msg_len;
1614 	u_char type;
1615 	const u_char *cp;
1616 	int r;
1617 	SocketEntry *e;
1618 
1619 	if (socknum >= sockets_alloc)
1620 		fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1621 	e = &sockets[socknum];
1622 
1623 	if (sshbuf_len(e->input) < 5)
1624 		return 0;		/* Incomplete message header. */
1625 	cp = sshbuf_ptr(e->input);
1626 	msg_len = PEEK_U32(cp);
1627 	if (msg_len > AGENT_MAX_LEN) {
1628 		debug_f("socket %u (fd=%d) message too long %u > %u",
1629 		    socknum, e->fd, msg_len, AGENT_MAX_LEN);
1630 		return -1;
1631 	}
1632 	if (sshbuf_len(e->input) < msg_len + 4)
1633 		return 0;		/* Incomplete message body. */
1634 
1635 	/* move the current input to e->request */
1636 	sshbuf_reset(e->request);
1637 	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1638 	    (r = sshbuf_get_u8(e->request, &type)) != 0) {
1639 		if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1640 		    r == SSH_ERR_STRING_TOO_LARGE) {
1641 			error_fr(r, "parse");
1642 			return -1;
1643 		}
1644 		fatal_fr(r, "parse");
1645 	}
1646 
1647 	debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1648 
1649 	/* check whether agent is locked */
1650 	if (locked && type != SSH_AGENTC_UNLOCK) {
1651 		sshbuf_reset(e->request);
1652 		switch (type) {
1653 		case SSH2_AGENTC_REQUEST_IDENTITIES:
1654 			/* send empty lists */
1655 			no_identities(e);
1656 			break;
1657 		default:
1658 			/* send a fail message for all other request types */
1659 			send_status(e, 0);
1660 		}
1661 		return 1;
1662 	}
1663 
1664 	switch (type) {
1665 	case SSH_AGENTC_LOCK:
1666 	case SSH_AGENTC_UNLOCK:
1667 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
1668 		break;
1669 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1670 		process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1671 		break;
1672 	/* ssh2 */
1673 	case SSH2_AGENTC_SIGN_REQUEST:
1674 		process_sign_request2(e);
1675 		break;
1676 	case SSH2_AGENTC_REQUEST_IDENTITIES:
1677 		process_request_identities(e);
1678 		break;
1679 	case SSH2_AGENTC_ADD_IDENTITY:
1680 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1681 		process_add_identity(e);
1682 		break;
1683 	case SSH2_AGENTC_REMOVE_IDENTITY:
1684 		process_remove_identity(e);
1685 		break;
1686 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1687 		process_remove_all_identities(e);
1688 		break;
1689 #ifdef ENABLE_PKCS11
1690 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
1691 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1692 		process_add_smartcard_key(e);
1693 		break;
1694 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1695 		process_remove_smartcard_key(e);
1696 		break;
1697 #endif /* ENABLE_PKCS11 */
1698 	case SSH_AGENTC_EXTENSION:
1699 		process_extension(e);
1700 		break;
1701 	default:
1702 		/* Unknown message.  Respond with failure. */
1703 		error("Unknown message %d", type);
1704 		sshbuf_reset(e->request);
1705 		send_status(e, 0);
1706 		break;
1707 	}
1708 	return 1;
1709 }
1710 
1711 static void
1712 new_socket(sock_type type, int fd)
1713 {
1714 	u_int i, old_alloc, new_alloc;
1715 
1716 	debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1717 	    (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1718 	if (type == AUTH_CONNECTION) {
1719 		debug("xcount %d -> %d", xcount, xcount + 1);
1720 		++xcount;
1721 	}
1722 	set_nonblock(fd);
1723 
1724 	if (fd > max_fd)
1725 		max_fd = fd;
1726 
1727 	for (i = 0; i < sockets_alloc; i++)
1728 		if (sockets[i].type == AUTH_UNUSED) {
1729 			sockets[i].fd = fd;
1730 			if ((sockets[i].input = sshbuf_new()) == NULL ||
1731 			    (sockets[i].output = sshbuf_new()) == NULL ||
1732 			    (sockets[i].request = sshbuf_new()) == NULL)
1733 				fatal_f("sshbuf_new failed");
1734 			sockets[i].type = type;
1735 			return;
1736 		}
1737 	old_alloc = sockets_alloc;
1738 	new_alloc = sockets_alloc + 10;
1739 	sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1740 	    sizeof(sockets[0]));
1741 	for (i = old_alloc; i < new_alloc; i++)
1742 		sockets[i].type = AUTH_UNUSED;
1743 	sockets_alloc = new_alloc;
1744 	sockets[old_alloc].fd = fd;
1745 	if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1746 	    (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1747 	    (sockets[old_alloc].request = sshbuf_new()) == NULL)
1748 		fatal_f("sshbuf_new failed");
1749 	sockets[old_alloc].type = type;
1750 }
1751 
1752 static int
1753 handle_socket_read(u_int socknum)
1754 {
1755 	struct sockaddr_un sunaddr;
1756 	socklen_t slen;
1757 	uid_t euid;
1758 	gid_t egid;
1759 	int fd;
1760 
1761 	slen = sizeof(sunaddr);
1762 	fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1763 	if (fd == -1) {
1764 		error("accept from AUTH_SOCKET: %s", strerror(errno));
1765 		return -1;
1766 	}
1767 	if (getpeereid(fd, &euid, &egid) == -1) {
1768 		error("getpeereid %d failed: %s", fd, strerror(errno));
1769 		close(fd);
1770 		return -1;
1771 	}
1772 	if ((euid != 0) && (getuid() != euid)) {
1773 		error("uid mismatch: peer euid %u != uid %u",
1774 		    (u_int) euid, (u_int) getuid());
1775 		close(fd);
1776 		return -1;
1777 	}
1778 	new_socket(AUTH_CONNECTION, fd);
1779 	return 0;
1780 }
1781 
1782 static int
1783 handle_conn_read(u_int socknum)
1784 {
1785 	char buf[AGENT_RBUF_LEN];
1786 	ssize_t len;
1787 	int r;
1788 
1789 	if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1790 		if (len == -1) {
1791 			if (errno == EAGAIN || errno == EINTR)
1792 				return 0;
1793 			error_f("read error on socket %u (fd %d): %s",
1794 			    socknum, sockets[socknum].fd, strerror(errno));
1795 		}
1796 		return -1;
1797 	}
1798 	if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1799 		fatal_fr(r, "compose");
1800 	explicit_bzero(buf, sizeof(buf));
1801 	for (;;) {
1802 		if ((r = process_message(socknum)) == -1)
1803 			return -1;
1804 		else if (r == 0)
1805 			break;
1806 	}
1807 	return 0;
1808 }
1809 
1810 static int
1811 handle_conn_write(u_int socknum)
1812 {
1813 	ssize_t len;
1814 	int r;
1815 
1816 	if (sshbuf_len(sockets[socknum].output) == 0)
1817 		return 0; /* shouldn't happen */
1818 	if ((len = write(sockets[socknum].fd,
1819 	    sshbuf_ptr(sockets[socknum].output),
1820 	    sshbuf_len(sockets[socknum].output))) <= 0) {
1821 		if (len == -1) {
1822 			if (errno == EAGAIN || errno == EINTR)
1823 				return 0;
1824 			error_f("read error on socket %u (fd %d): %s",
1825 			    socknum, sockets[socknum].fd, strerror(errno));
1826 		}
1827 		return -1;
1828 	}
1829 	if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1830 		fatal_fr(r, "consume");
1831 	return 0;
1832 }
1833 
1834 static void
1835 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1836 {
1837 	size_t i;
1838 	u_int socknum, activefds = npfd;
1839 
1840 	for (i = 0; i < npfd; i++) {
1841 		if (pfd[i].revents == 0)
1842 			continue;
1843 		/* Find sockets entry */
1844 		for (socknum = 0; socknum < sockets_alloc; socknum++) {
1845 			if (sockets[socknum].type != AUTH_SOCKET &&
1846 			    sockets[socknum].type != AUTH_CONNECTION)
1847 				continue;
1848 			if (pfd[i].fd == sockets[socknum].fd)
1849 				break;
1850 		}
1851 		if (socknum >= sockets_alloc) {
1852 			error_f("no socket for fd %d", pfd[i].fd);
1853 			continue;
1854 		}
1855 		/* Process events */
1856 		switch (sockets[socknum].type) {
1857 		case AUTH_SOCKET:
1858 			if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1859 				break;
1860 			if (npfd > maxfds) {
1861 				debug3("out of fds (active %u >= limit %u); "
1862 				    "skipping accept", activefds, maxfds);
1863 				break;
1864 			}
1865 			if (handle_socket_read(socknum) == 0)
1866 				activefds++;
1867 			break;
1868 		case AUTH_CONNECTION:
1869 			if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
1870 			    handle_conn_read(socknum) != 0)
1871 				goto close_sock;
1872 			if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1873 			    handle_conn_write(socknum) != 0) {
1874  close_sock:
1875 				if (activefds == 0)
1876 					fatal("activefds == 0 at close_sock");
1877 				close_socket(&sockets[socknum]);
1878 				activefds--;
1879 				break;
1880 			}
1881 			break;
1882 		default:
1883 			break;
1884 		}
1885 	}
1886 }
1887 
1888 static int
1889 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1890 {
1891 	struct pollfd *pfd = *pfdp;
1892 	size_t i, j, npfd = 0;
1893 	time_t deadline;
1894 	int r;
1895 
1896 	/* Count active sockets */
1897 	for (i = 0; i < sockets_alloc; i++) {
1898 		switch (sockets[i].type) {
1899 		case AUTH_SOCKET:
1900 		case AUTH_CONNECTION:
1901 			npfd++;
1902 			break;
1903 		case AUTH_UNUSED:
1904 			break;
1905 		default:
1906 			fatal("Unknown socket type %d", sockets[i].type);
1907 			break;
1908 		}
1909 	}
1910 	if (npfd != *npfdp &&
1911 	    (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1912 		fatal_f("recallocarray failed");
1913 	*pfdp = pfd;
1914 	*npfdp = npfd;
1915 
1916 	for (i = j = 0; i < sockets_alloc; i++) {
1917 		switch (sockets[i].type) {
1918 		case AUTH_SOCKET:
1919 			if (npfd > maxfds) {
1920 				debug3("out of fds (active %zu >= limit %u); "
1921 				    "skipping arming listener", npfd, maxfds);
1922 				break;
1923 			}
1924 			pfd[j].fd = sockets[i].fd;
1925 			pfd[j].revents = 0;
1926 			pfd[j].events = POLLIN;
1927 			j++;
1928 			break;
1929 		case AUTH_CONNECTION:
1930 			pfd[j].fd = sockets[i].fd;
1931 			pfd[j].revents = 0;
1932 			/*
1933 			 * Only prepare to read if we can handle a full-size
1934 			 * input read buffer and enqueue a max size reply..
1935 			 */
1936 			if ((r = sshbuf_check_reserve(sockets[i].input,
1937 			    AGENT_RBUF_LEN)) == 0 &&
1938 			    (r = sshbuf_check_reserve(sockets[i].output,
1939 			    AGENT_MAX_LEN)) == 0)
1940 				pfd[j].events = POLLIN;
1941 			else if (r != SSH_ERR_NO_BUFFER_SPACE)
1942 				fatal_fr(r, "reserve");
1943 			if (sshbuf_len(sockets[i].output) > 0)
1944 				pfd[j].events |= POLLOUT;
1945 			j++;
1946 			break;
1947 		default:
1948 			break;
1949 		}
1950 	}
1951 	deadline = reaper();
1952 	if (parent_alive_interval != 0)
1953 		deadline = (deadline == 0) ? parent_alive_interval :
1954 		    MINIMUM(deadline, parent_alive_interval);
1955 	if (deadline == 0) {
1956 		*timeoutp = -1; /* INFTIM */
1957 	} else {
1958 		if (deadline > INT_MAX / 1000)
1959 			*timeoutp = INT_MAX / 1000;
1960 		else
1961 			*timeoutp = deadline * 1000;
1962 	}
1963 	return (1);
1964 }
1965 
1966 static void
1967 cleanup_socket(void)
1968 {
1969 	if (cleanup_pid != 0 && getpid() != cleanup_pid)
1970 		return;
1971 	debug_f("cleanup");
1972 	if (socket_name[0])
1973 		unlink(socket_name);
1974 	if (socket_dir[0])
1975 		rmdir(socket_dir);
1976 }
1977 
1978 void
1979 cleanup_exit(int i)
1980 {
1981 	cleanup_socket();
1982 	_exit(i);
1983 }
1984 
1985 static void
1986 cleanup_handler(int sig)
1987 {
1988 	cleanup_socket();
1989 #ifdef ENABLE_PKCS11
1990 	pkcs11_terminate();
1991 #endif
1992 	_exit(2);
1993 }
1994 
1995 static void
1996 check_parent_exists(void)
1997 {
1998 	/*
1999 	 * If our parent has exited then getppid() will return (pid_t)1,
2000 	 * so testing for that should be safe.
2001 	 */
2002 	if (parent_pid != -1 && getppid() != parent_pid) {
2003 		/* printf("Parent has died - Authentication agent exiting.\n"); */
2004 		cleanup_socket();
2005 		_exit(2);
2006 	}
2007 }
2008 
2009 static void
2010 usage(void)
2011 {
2012 	fprintf(stderr,
2013 	    "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
2014 	    "                 [-O option] [-P allowed_providers] [-t life]\n"
2015 	    "       ssh-agent [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2016 	    "                 [-P allowed_providers] [-t life] command [arg ...]\n"
2017 	    "       ssh-agent [-c | -s] -k\n");
2018 	exit(1);
2019 }
2020 
2021 int
2022 main(int ac, char **av)
2023 {
2024 	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
2025 	int sock, ch, result, saved_errno;
2026 	char *shell, *format, *pidstr, *agentsocket = NULL;
2027 #ifdef HAVE_SETRLIMIT
2028 	struct rlimit rlim;
2029 #endif
2030 	extern int optind;
2031 	extern char *optarg;
2032 	pid_t pid;
2033 	char pidstrbuf[1 + 3 * sizeof pid];
2034 	size_t len;
2035 	mode_t prev_mask;
2036 	int timeout = -1; /* INFTIM */
2037 	struct pollfd *pfd = NULL;
2038 	size_t npfd = 0;
2039 	u_int maxfds;
2040 
2041 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2042 	sanitise_stdfd();
2043 
2044 	/* drop */
2045 	setegid(getgid());
2046 	setgid(getgid());
2047 	setuid(geteuid());
2048 
2049 	platform_disable_tracing(0);	/* strict=no */
2050 
2051 #ifdef RLIMIT_NOFILE
2052 	if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2053 		fatal("%s: getrlimit: %s", __progname, strerror(errno));
2054 #endif
2055 
2056 	__progname = ssh_get_progname(av[0]);
2057 	seed_rng();
2058 
2059 	while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:x")) != -1) {
2060 		switch (ch) {
2061 		case 'E':
2062 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
2063 			if (fingerprint_hash == -1)
2064 				fatal("Invalid hash algorithm \"%s\"", optarg);
2065 			break;
2066 		case 'c':
2067 			if (s_flag)
2068 				usage();
2069 			c_flag++;
2070 			break;
2071 		case 'k':
2072 			k_flag++;
2073 			break;
2074 		case 'O':
2075 			if (strcmp(optarg, "no-restrict-websafe") == 0)
2076 				restrict_websafe  = 0;
2077 			else
2078 				fatal("Unknown -O option");
2079 			break;
2080 		case 'P':
2081 			if (allowed_providers != NULL)
2082 				fatal("-P option already specified");
2083 			allowed_providers = xstrdup(optarg);
2084 			break;
2085 		case 's':
2086 			if (c_flag)
2087 				usage();
2088 			s_flag++;
2089 			break;
2090 		case 'd':
2091 			if (d_flag || D_flag)
2092 				usage();
2093 			d_flag++;
2094 			break;
2095 		case 'D':
2096 			if (d_flag || D_flag)
2097 				usage();
2098 			D_flag++;
2099 			break;
2100 		case 'a':
2101 			agentsocket = optarg;
2102 			break;
2103 		case 't':
2104 			if ((lifetime = convtime(optarg)) == -1) {
2105 				fprintf(stderr, "Invalid lifetime\n");
2106 				usage();
2107 			}
2108 			break;
2109 		case 'x':
2110 			xcount = 0;
2111 			break;
2112 		default:
2113 			usage();
2114 		}
2115 	}
2116 	ac -= optind;
2117 	av += optind;
2118 
2119 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
2120 		usage();
2121 
2122 	if (allowed_providers == NULL)
2123 		allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2124 
2125 	if (ac == 0 && !c_flag && !s_flag) {
2126 		shell = getenv("SHELL");
2127 		if (shell != NULL && (len = strlen(shell)) > 2 &&
2128 		    strncmp(shell + len - 3, "csh", 3) == 0)
2129 			c_flag = 1;
2130 	}
2131 	if (k_flag) {
2132 		const char *errstr = NULL;
2133 
2134 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2135 		if (pidstr == NULL) {
2136 			fprintf(stderr, "%s not set, cannot kill agent\n",
2137 			    SSH_AGENTPID_ENV_NAME);
2138 			exit(1);
2139 		}
2140 		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2141 		if (errstr) {
2142 			fprintf(stderr,
2143 			    "%s=\"%s\", which is not a good PID: %s\n",
2144 			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2145 			exit(1);
2146 		}
2147 		if (kill(pid, SIGTERM) == -1) {
2148 			perror("kill");
2149 			exit(1);
2150 		}
2151 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
2152 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
2153 		printf(format, SSH_AGENTPID_ENV_NAME);
2154 		printf("echo Agent pid %ld killed;\n", (long)pid);
2155 		exit(0);
2156 	}
2157 
2158 	/*
2159 	 * Minimum file descriptors:
2160 	 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2161 	 * a few spare for libc / stack protectors / sanitisers, etc.
2162 	 */
2163 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2164 	if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2165 		fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2166 		    __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2167 	maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2168 
2169 	parent_pid = getpid();
2170 
2171 	if (agentsocket == NULL) {
2172 		/* Create private directory for agent socket */
2173 		mktemp_proto(socket_dir, sizeof(socket_dir));
2174 		if (mkdtemp(socket_dir) == NULL) {
2175 			perror("mkdtemp: private socket dir");
2176 			exit(1);
2177 		}
2178 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
2179 		    (long)parent_pid);
2180 	} else {
2181 		/* Try to use specified agent socket */
2182 		socket_dir[0] = '\0';
2183 		strlcpy(socket_name, agentsocket, sizeof socket_name);
2184 	}
2185 
2186 	/*
2187 	 * Create socket early so it will exist before command gets run from
2188 	 * the parent.
2189 	 */
2190 	prev_mask = umask(0177);
2191 	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2192 	if (sock < 0) {
2193 		/* XXX - unix_listener() calls error() not perror() */
2194 		*socket_name = '\0'; /* Don't unlink any existing file */
2195 		cleanup_exit(1);
2196 	}
2197 	umask(prev_mask);
2198 
2199 	/*
2200 	 * Fork, and have the parent execute the command, if any, or present
2201 	 * the socket data.  The child continues as the authentication agent.
2202 	 */
2203 	if (D_flag || d_flag) {
2204 		log_init(__progname,
2205 		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2206 		    SYSLOG_FACILITY_AUTH, 1);
2207 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2208 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2209 		    SSH_AUTHSOCKET_ENV_NAME);
2210 		printf("echo Agent pid %ld;\n", (long)parent_pid);
2211 		fflush(stdout);
2212 		goto skip;
2213 	}
2214 	pid = fork();
2215 	if (pid == -1) {
2216 		perror("fork");
2217 		cleanup_exit(1);
2218 	}
2219 	if (pid != 0) {		/* Parent - execute the given command. */
2220 		close(sock);
2221 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2222 		if (ac == 0) {
2223 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2224 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2225 			    SSH_AUTHSOCKET_ENV_NAME);
2226 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
2227 			    SSH_AGENTPID_ENV_NAME);
2228 			printf("echo Agent pid %ld;\n", (long)pid);
2229 			exit(0);
2230 		}
2231 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2232 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2233 			perror("setenv");
2234 			exit(1);
2235 		}
2236 		execvp(av[0], av);
2237 		perror(av[0]);
2238 		exit(1);
2239 	}
2240 	/* child */
2241 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2242 
2243 	if (setsid() == -1) {
2244 		error("setsid: %s", strerror(errno));
2245 		cleanup_exit(1);
2246 	}
2247 
2248 	(void)chdir("/");
2249 	if (stdfd_devnull(1, 1, 1) == -1)
2250 		error_f("stdfd_devnull failed");
2251 
2252 #ifdef HAVE_SETRLIMIT
2253 	/* deny core dumps, since memory contains unencrypted private keys */
2254 	rlim.rlim_cur = rlim.rlim_max = 0;
2255 	if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2256 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2257 		cleanup_exit(1);
2258 	}
2259 #endif
2260 
2261 skip:
2262 
2263 	cleanup_pid = getpid();
2264 
2265 #ifdef ENABLE_PKCS11
2266 	pkcs11_init(0);
2267 #endif
2268 	new_socket(AUTH_SOCKET, sock);
2269 	if (ac > 0)
2270 		parent_alive_interval = 10;
2271 	idtab_init();
2272 	ssh_signal(SIGPIPE, SIG_IGN);
2273 	ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2274 	ssh_signal(SIGHUP, cleanup_handler);
2275 	ssh_signal(SIGTERM, cleanup_handler);
2276 
2277 	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
2278 		fatal("%s: pledge: %s", __progname, strerror(errno));
2279 	platform_pledge_agent();
2280 
2281 	while (1) {
2282 		prepare_poll(&pfd, &npfd, &timeout, maxfds);
2283 		result = poll(pfd, npfd, timeout);
2284 		saved_errno = errno;
2285 		if (parent_alive_interval != 0)
2286 			check_parent_exists();
2287 		(void) reaper();	/* remove expired keys */
2288 		if (result == -1) {
2289 			if (saved_errno == EINTR)
2290 				continue;
2291 			fatal("poll: %s", strerror(saved_errno));
2292 		} else if (result > 0)
2293 			after_poll(pfd, npfd, maxfds);
2294 	}
2295 	/* NOTREACHED */
2296 }
2297