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