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