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