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