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