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