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