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