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