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