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