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