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