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