xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-agent.c (revision 796c32c94f6e154afc9de0f63da35c91bb739b45)
1 /*	$NetBSD: ssh-agent.c,v 1.21 2017/10/07 19:39:19 christos Exp $	*/
2 /* $OpenBSD: ssh-agent.c,v 1.224 2017/07/24 04:34:28 djm Exp $ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * The authentication agent program.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include "includes.h"
39 __RCSID("$NetBSD: ssh-agent.c,v 1.21 2017/10/07 19:39:19 christos Exp $");
40 
41 #include <sys/param.h>	/* MIN MAX */
42 #include <sys/types.h>
43 #include <sys/time.h>
44 #include <sys/queue.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <sys/stat.h>
48 #include <sys/un.h>
49 
50 #ifdef WITH_OPENSSL
51 #include <openssl/evp.h>
52 #endif
53 
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <paths.h>
57 #include <poll.h>
58 #include <signal.h>
59 #include <stdlib.h>
60 #include <stdio.h>
61 #include <string.h>
62 #include <limits.h>
63 #include <time.h>
64 #include <unistd.h>
65 #include <util.h>
66 
67 #include "xmalloc.h"
68 #include "ssh.h"
69 #include "sshbuf.h"
70 #include "sshkey.h"
71 #include "authfd.h"
72 #include "compat.h"
73 #include "log.h"
74 #include "misc.h"
75 #include "getpeereid.h"
76 #include "digest.h"
77 #include "ssherr.h"
78 #include "match.h"
79 
80 #ifdef ENABLE_PKCS11
81 #include "ssh-pkcs11.h"
82 #endif
83 
84 #ifndef DEFAULT_PKCS11_WHITELIST
85 # define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
86 #endif
87 
88 /* Maximum accepted message length */
89 #define AGENT_MAX_LEN	(256*1024)
90 
91 typedef enum {
92 	AUTH_UNUSED,
93 	AUTH_SOCKET,
94 	AUTH_CONNECTION
95 } sock_type;
96 
97 typedef struct {
98 	int fd;
99 	sock_type type;
100 	struct sshbuf *input;
101 	struct sshbuf *output;
102 	struct sshbuf *request;
103 } SocketEntry;
104 
105 u_int sockets_alloc = 0;
106 SocketEntry *sockets = NULL;
107 
108 typedef struct identity {
109 	TAILQ_ENTRY(identity) next;
110 	struct sshkey *key;
111 	char *comment;
112 	char *provider;
113 	time_t death;
114 	u_int confirm;
115 } Identity;
116 
117 struct idtable {
118 	int nentries;
119 	TAILQ_HEAD(idqueue, identity) idlist;
120 };
121 
122 /* private key table */
123 struct idtable *idtab;
124 
125 int max_fd = 0;
126 
127 /* pid of shell == parent of agent */
128 pid_t parent_pid = -1;
129 time_t parent_alive_interval = 0;
130 
131 /* pid of process for which cleanup_socket is applicable */
132 pid_t cleanup_pid = 0;
133 
134 /* pathname and directory for AUTH_SOCKET */
135 char socket_name[PATH_MAX];
136 char socket_dir[PATH_MAX];
137 
138 /* PKCS#11 path whitelist */
139 static char *pkcs11_whitelist;
140 
141 /* locking */
142 #define LOCK_SIZE	32
143 #define LOCK_SALT_SIZE	16
144 #define LOCK_ROUNDS	1
145 int locked = 0;
146 u_char lock_pwhash[LOCK_SIZE];
147 u_char lock_salt[LOCK_SALT_SIZE];
148 
149 extern char *__progname;
150 
151 /* Default lifetime in seconds (0 == forever) */
152 static long lifetime = 0;
153 
154 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
155 
156 static void
157 close_socket(SocketEntry *e)
158 {
159 	close(e->fd);
160 	e->fd = -1;
161 	e->type = AUTH_UNUSED;
162 	sshbuf_free(e->input);
163 	sshbuf_free(e->output);
164 	sshbuf_free(e->request);
165 }
166 
167 static void
168 idtab_init(void)
169 {
170 	idtab = xcalloc(1, sizeof(*idtab));
171 	TAILQ_INIT(&idtab->idlist);
172 	idtab->nentries = 0;
173 }
174 
175 static void
176 free_identity(Identity *id)
177 {
178 	sshkey_free(id->key);
179 	free(id->provider);
180 	free(id->comment);
181 	free(id);
182 }
183 
184 /* return matching private key for given public key */
185 static Identity *
186 lookup_identity(struct sshkey *key)
187 {
188 	Identity *id;
189 
190 	TAILQ_FOREACH(id, &idtab->idlist, next) {
191 		if (sshkey_equal(key, id->key))
192 			return (id);
193 	}
194 	return (NULL);
195 }
196 
197 /* Check confirmation of keysign request */
198 static int
199 confirm_key(Identity *id)
200 {
201 	char *p;
202 	int ret = -1;
203 
204 	p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
205 	if (p != NULL &&
206 	    ask_permission("Allow use of key %s?\nKey fingerprint %s.",
207 	    id->comment, p))
208 		ret = 0;
209 	free(p);
210 
211 	return (ret);
212 }
213 
214 static void
215 send_status(SocketEntry *e, int success)
216 {
217 	int r;
218 
219 	if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
220 	    (r = sshbuf_put_u8(e->output, success ?
221 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
222 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
223 }
224 
225 /* send list of supported public keys to 'client' */
226 static void
227 process_request_identities(SocketEntry *e)
228 {
229 	Identity *id;
230 	struct sshbuf *msg;
231 	int r;
232 
233 	if ((msg = sshbuf_new()) == NULL)
234 		fatal("%s: sshbuf_new failed", __func__);
235 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
236 	    (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
237 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
238 	TAILQ_FOREACH(id, &idtab->idlist, next) {
239 		if ((r = sshkey_puts(id->key, msg)) != 0 ||
240 		    (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
241 			error("%s: put key/comment: %s", __func__,
242 			    ssh_err(r));
243 			continue;
244 		}
245 	}
246 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
247 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
248 	sshbuf_free(msg);
249 }
250 
251 
252 static const char *
253 agent_decode_alg(struct sshkey *key, u_int flags)
254 {
255 	if (key->type == KEY_RSA) {
256 		if (flags & SSH_AGENT_RSA_SHA2_256)
257 			return "rsa-sha2-256";
258 		else if (flags & SSH_AGENT_RSA_SHA2_512)
259 			return "rsa-sha2-512";
260 	}
261 	return NULL;
262 }
263 
264 /* ssh2 only */
265 static void
266 process_sign_request2(SocketEntry *e)
267 {
268 	const u_char *data;
269 	u_char *signature = NULL;
270 	size_t dlen, slen = 0;
271 	u_int compat = 0, flags;
272 	int r, ok = -1;
273 	struct sshbuf *msg;
274 	struct sshkey *key = NULL;
275 	struct identity *id;
276 
277 	if ((msg = sshbuf_new()) == NULL)
278 		fatal("%s: sshbuf_new failed", __func__);
279 	if ((r = sshkey_froms(e->request, &key)) != 0 ||
280 	    (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
281 	    (r = sshbuf_get_u32(e->request, &flags)) != 0)
282 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
283 	if (flags & SSH_AGENT_OLD_SIGNATURE)
284 		compat = SSH_BUG_SIGBLOB;
285 	if ((id = lookup_identity(key)) == NULL) {
286 		verbose("%s: %s key not found", __func__, sshkey_type(key));
287 		goto send;
288 	}
289 	if (id->confirm && confirm_key(id) != 0) {
290 		verbose("%s: user refused key", __func__);
291 		goto send;
292 	}
293 	if ((r = sshkey_sign(id->key, &signature, &slen,
294 	    data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
295 		error("%s: sshkey_sign: %s", __func__, ssh_err(r));
296 		goto send;
297 	}
298 	/* Success */
299 	ok = 0;
300  send:
301 	sshkey_free(key);
302 	if (ok == 0) {
303 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
304 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
305 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
306 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
307 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
308 
309 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
310 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
311 
312 	sshbuf_free(msg);
313 	free(signature);
314 }
315 
316 /* shared */
317 static void
318 process_remove_identity(SocketEntry *e)
319 {
320 	int r, success = 0;
321 	struct sshkey *key = NULL;
322 	Identity *id;
323 
324 	if ((r = sshkey_froms(e->request, &key)) != 0) {
325 		error("%s: get key: %s", __func__, ssh_err(r));
326 		goto done;
327 	}
328 	if ((id = lookup_identity(key)) == NULL) {
329 		debug("%s: key not found", __func__);
330 		goto done;
331 	}
332 	/* We have this key, free it. */
333 	if (idtab->nentries < 1)
334 		fatal("%s: internal error: nentries %d",
335 		    __func__, idtab->nentries);
336 	TAILQ_REMOVE(&idtab->idlist, id, next);
337 	free_identity(id);
338 	idtab->nentries--;
339 	sshkey_free(key);
340 	success = 1;
341  done:
342 	send_status(e, success);
343 }
344 
345 static void
346 process_remove_all_identities(SocketEntry *e)
347 {
348 	Identity *id;
349 
350 	/* Loop over all identities and clear the keys. */
351 	for (id = TAILQ_FIRST(&idtab->idlist); id;
352 	    id = TAILQ_FIRST(&idtab->idlist)) {
353 		TAILQ_REMOVE(&idtab->idlist, id, next);
354 		free_identity(id);
355 	}
356 
357 	/* Mark that there are no identities. */
358 	idtab->nentries = 0;
359 
360 	/* Send success. */
361 	send_status(e, 1);
362 }
363 
364 /* removes expired keys and returns number of seconds until the next expiry */
365 static time_t
366 reaper(void)
367 {
368 	time_t deadline = 0, now = monotime();
369 	Identity *id, *nxt;
370 
371 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
372 		nxt = TAILQ_NEXT(id, next);
373 		if (id->death == 0)
374 			continue;
375 		if (now >= id->death) {
376 			debug("expiring key '%s'", id->comment);
377 			TAILQ_REMOVE(&idtab->idlist, id, next);
378 			free_identity(id);
379 			idtab->nentries--;
380 		} else
381 			deadline = (deadline == 0) ? id->death :
382 			    MINIMUM(deadline, id->death);
383 	}
384 	if (deadline == 0 || deadline <= now)
385 		return 0;
386 	else
387 		return (deadline - now);
388 }
389 
390 static void
391 process_add_identity(SocketEntry *e)
392 {
393 	Identity *id;
394 	int success = 0, confirm = 0;
395 	u_int seconds;
396 	char *comment = NULL;
397 	time_t death = 0;
398 	struct sshkey *k = NULL;
399 	u_char ctype;
400 	int r = SSH_ERR_INTERNAL_ERROR;
401 
402 	if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
403 	    k == NULL ||
404 	    (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
405 		error("%s: decode private key: %s", __func__, ssh_err(r));
406 		goto err;
407 	}
408 
409 	while (sshbuf_len(e->request)) {
410 		if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
411 			error("%s: buffer error: %s", __func__, ssh_err(r));
412 			goto err;
413 		}
414 		switch (ctype) {
415 		case SSH_AGENT_CONSTRAIN_LIFETIME:
416 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
417 				error("%s: bad lifetime constraint: %s",
418 				    __func__, ssh_err(r));
419 				goto err;
420 			}
421 			death = monotime() + seconds;
422 			break;
423 		case SSH_AGENT_CONSTRAIN_CONFIRM:
424 			confirm = 1;
425 			break;
426 		default:
427 			error("%s: Unknown constraint %d", __func__, ctype);
428  err:
429 			sshbuf_reset(e->request);
430 			free(comment);
431 			sshkey_free(k);
432 			goto send;
433 		}
434 	}
435 
436 	success = 1;
437 	if (lifetime && !death)
438 		death = monotime() + lifetime;
439 	if ((id = lookup_identity(k)) == NULL) {
440 		id = xcalloc(1, sizeof(Identity));
441 		id->key = k;
442 		TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
443 		/* Increment the number of identities. */
444 		idtab->nentries++;
445 	} else {
446 		sshkey_free(k);
447 		free(id->comment);
448 	}
449 	id->comment = comment;
450 	id->death = death;
451 	id->confirm = confirm;
452 send:
453 	send_status(e, success);
454 }
455 
456 /* XXX todo: encrypt sensitive data with passphrase */
457 static void
458 process_lock_agent(SocketEntry *e, int lock)
459 {
460 	int r, success = 0, delay;
461 	char *passwd;
462 	u_char passwdhash[LOCK_SIZE];
463 	static u_int fail_count = 0;
464 	size_t pwlen;
465 
466 	if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
467 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
468 	if (pwlen == 0) {
469 		debug("empty password not supported");
470 	} else if (locked && !lock) {
471 		if (bcrypt_pbkdf(passwd, pwlen, (uint8_t *)lock_salt, sizeof(lock_salt),
472 		    (uint8_t *)passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
473 			fatal("bcrypt_pbkdf");
474 		if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
475 			debug("agent unlocked");
476 			locked = 0;
477 			fail_count = 0;
478 			explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
479 			success = 1;
480 		} else {
481 			/* delay in 0.1s increments up to 10s */
482 			if (fail_count < 100)
483 				fail_count++;
484 			delay = 100000 * fail_count;
485 			debug("unlock failed, delaying %0.1lf seconds",
486 			    (double)delay/1000000);
487 			usleep(delay);
488 		}
489 		explicit_bzero(passwdhash, sizeof(passwdhash));
490 	} else if (!locked && lock) {
491 		debug("agent locked");
492 		locked = 1;
493 		arc4random_buf(lock_salt, sizeof(lock_salt));
494 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
495 		    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
496 			fatal("bcrypt_pbkdf");
497 		success = 1;
498 	}
499 	explicit_bzero(passwd, pwlen);
500 	free(passwd);
501 	send_status(e, success);
502 }
503 
504 static void
505 no_identities(SocketEntry *e)
506 {
507 	struct sshbuf *msg;
508 	int r;
509 
510 	if ((msg = sshbuf_new()) == NULL)
511 		fatal("%s: sshbuf_new failed", __func__);
512 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
513 	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
514 	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
515 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
516 	sshbuf_free(msg);
517 }
518 
519 #ifdef ENABLE_PKCS11
520 static void
521 process_add_smartcard_key(SocketEntry *e)
522 {
523 	char *provider = NULL, *pin, canonical_provider[PATH_MAX];
524 	int r, i, count = 0, success = 0, confirm = 0;
525 	u_int seconds;
526 	time_t death = 0;
527 	u_char type;
528 	struct sshkey **keys = NULL, *k;
529 	Identity *id;
530 
531 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
532 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
533 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
534 
535 	while (sshbuf_len(e->request)) {
536 		if ((r = sshbuf_get_u8(e->request, &type)) != 0)
537 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
538 		switch (type) {
539 		case SSH_AGENT_CONSTRAIN_LIFETIME:
540 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
541 				fatal("%s: buffer error: %s",
542 				    __func__, ssh_err(r));
543 			death = monotime() + seconds;
544 			break;
545 		case SSH_AGENT_CONSTRAIN_CONFIRM:
546 			confirm = 1;
547 			break;
548 		default:
549 			error("%s: Unknown constraint type %d", __func__, type);
550 			goto send;
551 		}
552 	}
553 	if (realpath(provider, canonical_provider) == NULL) {
554 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
555 		    provider, strerror(errno));
556 		goto send;
557 	}
558 	if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
559 		verbose("refusing PKCS#11 add of \"%.100s\": "
560 		    "provider not whitelisted", canonical_provider);
561 		goto send;
562 	}
563 	debug("%s: add %.100s", __func__, canonical_provider);
564 	if (lifetime && !death)
565 		death = monotime() + lifetime;
566 
567 	count = pkcs11_add_provider(canonical_provider, pin, &keys);
568 	for (i = 0; i < count; i++) {
569 		k = keys[i];
570 		if (lookup_identity(k) == NULL) {
571 			id = xcalloc(1, sizeof(Identity));
572 			id->key = k;
573 			id->provider = xstrdup(canonical_provider);
574 			id->comment = xstrdup(canonical_provider); /* XXX */
575 			id->death = death;
576 			id->confirm = confirm;
577 			TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
578 			idtab->nentries++;
579 			success = 1;
580 		} else {
581 			sshkey_free(k);
582 		}
583 		keys[i] = NULL;
584 	}
585 send:
586 	free(pin);
587 	free(provider);
588 	free(keys);
589 	send_status(e, success);
590 }
591 
592 static void
593 process_remove_smartcard_key(SocketEntry *e)
594 {
595 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
596 	int r, success = 0;
597 	Identity *id, *nxt;
598 
599 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
600 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
601 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
602 	free(pin);
603 
604 	if (realpath(provider, canonical_provider) == NULL) {
605 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
606 		    provider, strerror(errno));
607 		goto send;
608 	}
609 
610 	debug("%s: remove %.100s", __func__, canonical_provider);
611 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
612 		nxt = TAILQ_NEXT(id, next);
613 		/* Skip file--based keys */
614 		if (id->provider == NULL)
615 			continue;
616 		if (!strcmp(canonical_provider, id->provider)) {
617 			TAILQ_REMOVE(&idtab->idlist, id, next);
618 			free_identity(id);
619 			idtab->nentries--;
620 		}
621 	}
622 	if (pkcs11_del_provider(canonical_provider) == 0)
623 		success = 1;
624 	else
625 		error("%s: pkcs11_del_provider failed", __func__);
626 send:
627 	free(provider);
628 	send_status(e, success);
629 }
630 #endif /* ENABLE_PKCS11 */
631 
632 /* dispatch incoming messages */
633 
634 static int
635 process_message(u_int socknum)
636 {
637 	u_int msg_len;
638 	u_char type;
639 	const u_char *cp;
640 	int r;
641 	SocketEntry *e;
642 
643 	if (socknum >= sockets_alloc) {
644 		fatal("%s: socket number %u >= allocated %u",
645 		    __func__, socknum, sockets_alloc);
646 	}
647 	e = &sockets[socknum];
648 
649 	if (sshbuf_len(e->input) < 5)
650 		return 0;		/* Incomplete message header. */
651 	cp = sshbuf_ptr(e->input);
652 	msg_len = PEEK_U32(cp);
653 	if (msg_len > AGENT_MAX_LEN) {
654 		debug("%s: socket %u (fd=%d) message too long %u > %u",
655 		    __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
656 		return -1;
657 	}
658 	if (sshbuf_len(e->input) < msg_len + 4)
659 		return 0;		/* Incomplete message body. */
660 
661 	/* move the current input to e->request */
662 	sshbuf_reset(e->request);
663 	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
664 	    (r = sshbuf_get_u8(e->request, &type)) != 0) {
665 		if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
666 		    r == SSH_ERR_STRING_TOO_LARGE) {
667 			debug("%s: buffer error: %s", __func__, ssh_err(r));
668 			return -1;
669 		}
670 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
671 	}
672 
673 	debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
674 
675 	/* check wheter agent is locked */
676 	if (locked && type != SSH_AGENTC_UNLOCK) {
677 		sshbuf_reset(e->request);
678 		switch (type) {
679 		case SSH2_AGENTC_REQUEST_IDENTITIES:
680 			/* send empty lists */
681 			no_identities(e);
682 			break;
683 		default:
684 			/* send a fail message for all other request types */
685 			send_status(e, 0);
686 		}
687 		return 0;
688 	}
689 
690 	switch (type) {
691 	case SSH_AGENTC_LOCK:
692 	case SSH_AGENTC_UNLOCK:
693 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
694 		break;
695 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
696 		process_remove_all_identities(e); /* safe for !WITH_SSH1 */
697 		break;
698 	/* ssh2 */
699 	case SSH2_AGENTC_SIGN_REQUEST:
700 		process_sign_request2(e);
701 		break;
702 	case SSH2_AGENTC_REQUEST_IDENTITIES:
703 		process_request_identities(e);
704 		break;
705 	case SSH2_AGENTC_ADD_IDENTITY:
706 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
707 		process_add_identity(e);
708 		break;
709 	case SSH2_AGENTC_REMOVE_IDENTITY:
710 		process_remove_identity(e);
711 		break;
712 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
713 		process_remove_all_identities(e);
714 		break;
715 #ifdef ENABLE_PKCS11
716 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
717 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
718 		process_add_smartcard_key(e);
719 		break;
720 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
721 		process_remove_smartcard_key(e);
722 		break;
723 #endif /* ENABLE_PKCS11 */
724 	default:
725 		/* Unknown message.  Respond with failure. */
726 		error("Unknown message %d", type);
727 		sshbuf_reset(e->request);
728 		send_status(e, 0);
729 		break;
730 	}
731 	return 0;
732 }
733 
734 static void
735 new_socket(sock_type type, int fd)
736 {
737 	u_int i, old_alloc, new_alloc;
738 
739 	set_nonblock(fd);
740 
741 	if (fd > max_fd)
742 		max_fd = fd;
743 
744 	for (i = 0; i < sockets_alloc; i++)
745 		if (sockets[i].type == AUTH_UNUSED) {
746 			sockets[i].fd = fd;
747 			if ((sockets[i].input = sshbuf_new()) == NULL)
748 				fatal("%s: sshbuf_new failed", __func__);
749 			if ((sockets[i].output = sshbuf_new()) == NULL)
750 				fatal("%s: sshbuf_new failed", __func__);
751 			if ((sockets[i].request = sshbuf_new()) == NULL)
752 				fatal("%s: sshbuf_new failed", __func__);
753 			sockets[i].type = type;
754 			return;
755 		}
756 	old_alloc = sockets_alloc;
757 	new_alloc = sockets_alloc + 10;
758 	sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
759 	for (i = old_alloc; i < new_alloc; i++)
760 		sockets[i].type = AUTH_UNUSED;
761 	sockets_alloc = new_alloc;
762 	sockets[old_alloc].fd = fd;
763 	if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
764 		fatal("%s: sshbuf_new failed", __func__);
765 	if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
766 		fatal("%s: sshbuf_new failed", __func__);
767 	if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
768 		fatal("%s: sshbuf_new failed", __func__);
769 	sockets[old_alloc].type = type;
770 }
771 
772 static int
773 handle_socket_read(u_int socknum)
774 {
775 	struct sockaddr_un sunaddr;
776 	socklen_t slen;
777 	uid_t euid;
778 	gid_t egid;
779 	int fd;
780 
781 	slen = sizeof(sunaddr);
782 	fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
783 	if (fd < 0) {
784 		error("accept from AUTH_SOCKET: %s", strerror(errno));
785 		return -1;
786 	}
787 	if (getpeereid(fd, &euid, &egid) < 0) {
788 		error("getpeereid %d failed: %s", fd, strerror(errno));
789 		close(fd);
790 		return -1;
791 	}
792 	if ((euid != 0) && (getuid() != euid)) {
793 		error("uid mismatch: peer euid %u != uid %u",
794 		    (u_int) euid, (u_int) getuid());
795 		close(fd);
796 		return -1;
797 	}
798 	new_socket(AUTH_CONNECTION, fd);
799 	return 0;
800 }
801 
802 static int
803 handle_conn_read(u_int socknum)
804 {
805 	char buf[1024];
806 	ssize_t len;
807 	int r;
808 
809 	if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
810 		if (len == -1) {
811 			if (errno == EAGAIN || errno == EINTR)
812 				return 0;
813 			error("%s: read error on socket %u (fd %d): %s",
814 			    __func__, socknum, sockets[socknum].fd,
815 			    strerror(errno));
816 		}
817 		return -1;
818 	}
819 	if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
820 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
821 	explicit_bzero(buf, sizeof(buf));
822 	process_message(socknum);
823 	return 0;
824 }
825 
826 static int
827 handle_conn_write(u_int socknum)
828 {
829 	ssize_t len;
830 	int r;
831 
832 	if (sshbuf_len(sockets[socknum].output) == 0)
833 		return 0; /* shouldn't happen */
834 	if ((len = write(sockets[socknum].fd,
835 	    sshbuf_ptr(sockets[socknum].output),
836 	    sshbuf_len(sockets[socknum].output))) <= 0) {
837 		if (len == -1) {
838 			if (errno == EAGAIN || errno == EINTR)
839 				return 0;
840 			error("%s: read error on socket %u (fd %d): %s",
841 			    __func__, socknum, sockets[socknum].fd,
842 			    strerror(errno));
843 		}
844 		return -1;
845 	}
846 	if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
847 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
848 	return 0;
849 }
850 
851 static void
852 after_poll(struct pollfd *pfd, size_t npfd)
853 {
854 	size_t i;
855 	u_int socknum;
856 
857 	for (i = 0; i < npfd; i++) {
858 		if (pfd[i].revents == 0)
859 			continue;
860 		/* Find sockets entry */
861 		for (socknum = 0; socknum < sockets_alloc; socknum++) {
862 			if (sockets[socknum].type != AUTH_SOCKET &&
863 			    sockets[socknum].type != AUTH_CONNECTION)
864 				continue;
865 			if (pfd[i].fd == sockets[socknum].fd)
866 				break;
867 		}
868 		if (socknum >= sockets_alloc) {
869 			error("%s: no socket for fd %d", __func__, pfd[i].fd);
870 			continue;
871 		}
872 		/* Process events */
873 		switch (sockets[socknum].type) {
874 		case AUTH_SOCKET:
875 			if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
876 			    handle_socket_read(socknum) != 0)
877 				close_socket(&sockets[socknum]);
878 			break;
879 		case AUTH_CONNECTION:
880 			if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
881 			    handle_conn_read(socknum) != 0) {
882 				close_socket(&sockets[socknum]);
883 				break;
884 			}
885 			if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
886 			    handle_conn_write(socknum) != 0)
887 				close_socket(&sockets[socknum]);
888 			break;
889 		default:
890 			break;
891 		}
892 	}
893 }
894 
895 static int
896 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp)
897 {
898 	struct pollfd *pfd = *pfdp;
899 	size_t i, j, npfd = 0;
900 	time_t deadline;
901 
902 	/* Count active sockets */
903 	for (i = 0; i < sockets_alloc; i++) {
904 		switch (sockets[i].type) {
905 		case AUTH_SOCKET:
906 		case AUTH_CONNECTION:
907 			npfd++;
908 			break;
909 		case AUTH_UNUSED:
910 			break;
911 		default:
912 			fatal("Unknown socket type %d", sockets[i].type);
913 			break;
914 		}
915 	}
916 	if (npfd != *npfdp &&
917 	    (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
918 		fatal("%s: recallocarray failed", __func__);
919 	*pfdp = pfd;
920 	*npfdp = npfd;
921 
922 	for (i = j = 0; i < sockets_alloc; i++) {
923 		switch (sockets[i].type) {
924 		case AUTH_SOCKET:
925 		case AUTH_CONNECTION:
926 			pfd[j].fd = sockets[i].fd;
927 			pfd[j].revents = 0;
928 			/* XXX backoff when input buffer full */
929 			pfd[j].events = POLLIN;
930 			if (sshbuf_len(sockets[i].output) > 0)
931 				pfd[j].events |= POLLOUT;
932 			j++;
933 			break;
934 		default:
935 			break;
936 		}
937 	}
938 	deadline = reaper();
939 	if (parent_alive_interval != 0)
940 		deadline = (deadline == 0) ? parent_alive_interval :
941 		    MINIMUM(deadline, parent_alive_interval);
942 	if (deadline == 0) {
943 		*timeoutp = -1; /* INFTIM */
944 	} else {
945 		if (deadline > INT_MAX / 1000)
946 			*timeoutp = INT_MAX / 1000;
947 		else
948 			*timeoutp = deadline * 1000;
949 	}
950 	return (1);
951 }
952 
953 static void
954 cleanup_socket(void)
955 {
956 	if (cleanup_pid != 0 && getpid() != cleanup_pid)
957 		return;
958 	debug("%s: cleanup", __func__);
959 	if (socket_name[0])
960 		unlink(socket_name);
961 	if (socket_dir[0])
962 		rmdir(socket_dir);
963 }
964 
965 void
966 cleanup_exit(int i)
967 {
968 	cleanup_socket();
969 	_exit(i);
970 }
971 
972 /*ARGSUSED*/
973 __dead static void
974 cleanup_handler(int sig)
975 {
976 	cleanup_socket();
977 #ifdef ENABLE_PKCS11
978 	pkcs11_terminate();
979 #endif
980 	_exit(2);
981 }
982 
983 static void
984 check_parent_exists(void)
985 {
986 	/*
987 	 * If our parent has exited then getppid() will return (pid_t)1,
988 	 * so testing for that should be safe.
989 	 */
990 	if (parent_pid != -1 && getppid() != parent_pid) {
991 		/* printf("Parent has died - Authentication agent exiting.\n"); */
992 		cleanup_socket();
993 		_exit(2);
994 	}
995 }
996 
997 __dead static void
998 usage(void)
999 {
1000 	fprintf(stderr,
1001 	    "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1002 	    "                 [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1003 	    "       ssh-agent [-c | -s] -k\n");
1004 	exit(1);
1005 }
1006 
1007 static void
1008 csh_setenv(const char *name, const char *value)
1009 {
1010 	printf("setenv %s %s;\n", name, value);
1011 }
1012 
1013 static void
1014 csh_unsetenv(const char *name)
1015 {
1016 	printf("unsetenv %s;\n", name);
1017 }
1018 
1019 static void
1020 sh_setenv(const char *name, const char *value)
1021 {
1022 	printf("%s=%s; export %s;\n", name, value, name);
1023 }
1024 
1025 static void
1026 sh_unsetenv(const char *name)
1027 {
1028 	printf("unset %s;\n", name);
1029 }
1030 int
1031 main(int ac, char **av)
1032 {
1033 	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1034 	int sock, fd, ch, result, saved_errno;
1035 	char *shell, *pidstr, *agentsocket = NULL;
1036 	struct rlimit rlim;
1037 	void (*f_setenv)(const char *, const char *);
1038 	void (*f_unsetenv)(const char *);
1039 	extern int optind;
1040 	extern char *optarg;
1041 	pid_t pid;
1042 	char pidstrbuf[1 + 3 * sizeof pid];
1043 	size_t len;
1044 	mode_t prev_mask;
1045 	int timeout = -1; /* INFTIM */
1046 	struct pollfd *pfd = NULL;
1047 	size_t npfd = 0;
1048 
1049 	ssh_malloc_init();	/* must be called before any mallocs */
1050 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1051 	sanitise_stdfd();
1052 
1053 	/* drop */
1054 	setegid(getgid());
1055 	setgid(getgid());
1056 
1057 #ifdef WITH_OPENSSL
1058 	OpenSSL_add_all_algorithms();
1059 #endif
1060 
1061 	while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1062 		switch (ch) {
1063 		case 'E':
1064 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
1065 			if (fingerprint_hash == -1)
1066 				fatal("Invalid hash algorithm \"%s\"", optarg);
1067 			break;
1068 		case 'c':
1069 			if (s_flag)
1070 				usage();
1071 			c_flag++;
1072 			break;
1073 		case 'k':
1074 			k_flag++;
1075 			break;
1076 		case 'P':
1077 			if (pkcs11_whitelist != NULL)
1078 				fatal("-P option already specified");
1079 			pkcs11_whitelist = xstrdup(optarg);
1080 			break;
1081 		case 's':
1082 			if (c_flag)
1083 				usage();
1084 			s_flag++;
1085 			break;
1086 		case 'd':
1087 			if (d_flag || D_flag)
1088 				usage();
1089 			d_flag++;
1090 			break;
1091 		case 'D':
1092 			if (d_flag || D_flag)
1093 				usage();
1094 			D_flag++;
1095 			break;
1096 		case 'a':
1097 			agentsocket = optarg;
1098 			break;
1099 		case 't':
1100 			if ((lifetime = convtime(optarg)) == -1) {
1101 				fprintf(stderr, "Invalid lifetime\n");
1102 				usage();
1103 			}
1104 			break;
1105 		default:
1106 			usage();
1107 		}
1108 	}
1109 	ac -= optind;
1110 	av += optind;
1111 
1112 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1113 		usage();
1114 
1115 	if (pkcs11_whitelist == NULL)
1116 		pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1117 
1118 	if (ac == 0 && !c_flag && !s_flag) {
1119 		shell = getenv("SHELL");
1120 		if (shell != NULL && (len = strlen(shell)) > 2 &&
1121 		    strncmp(shell + len - 3, "csh", 3) == 0)
1122 			c_flag = 1;
1123 	}
1124 	if (c_flag) {
1125 		f_setenv = csh_setenv;
1126 		f_unsetenv = csh_unsetenv;
1127 	} else {
1128 		f_setenv = sh_setenv;
1129 		f_unsetenv = sh_unsetenv;
1130 	}
1131 	if (k_flag) {
1132 		const char *errstr = NULL;
1133 
1134 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1135 		if (pidstr == NULL) {
1136 			fprintf(stderr, "%s not set, cannot kill agent\n",
1137 			    SSH_AGENTPID_ENV_NAME);
1138 			exit(1);
1139 		}
1140 		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1141 		if (errstr) {
1142 			fprintf(stderr,
1143 			    "%s=\"%s\", which is not a good PID: %s\n",
1144 			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1145 			exit(1);
1146 		}
1147 		if (kill(pid, SIGTERM) == -1) {
1148 			perror("kill");
1149 			exit(1);
1150 		}
1151 		(*f_unsetenv)(SSH_AUTHSOCKET_ENV_NAME);
1152 		(*f_unsetenv)(SSH_AGENTPID_ENV_NAME);
1153 		printf("echo Agent pid %ld killed;\n", (long)pid);
1154 		exit(0);
1155 	}
1156 	parent_pid = getpid();
1157 
1158 	if (agentsocket == NULL) {
1159 		/* Create private directory for agent socket */
1160 		mktemp_proto(socket_dir, sizeof(socket_dir));
1161 		if (mkdtemp(socket_dir) == NULL) {
1162 			perror("mkdtemp: private socket dir");
1163 			exit(1);
1164 		}
1165 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1166 		    (long)parent_pid);
1167 	} else {
1168 		/* Try to use specified agent socket */
1169 		socket_dir[0] = '\0';
1170 		strlcpy(socket_name, agentsocket, sizeof socket_name);
1171 	}
1172 
1173 	/*
1174 	 * Create socket early so it will exist before command gets run from
1175 	 * the parent.
1176 	 */
1177 	prev_mask = umask(0177);
1178 	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1179 	if (sock < 0) {
1180 		/* XXX - unix_listener() calls error() not perror() */
1181 		*socket_name = '\0'; /* Don't unlink any existing file */
1182 		cleanup_exit(1);
1183 	}
1184 	umask(prev_mask);
1185 
1186 	/*
1187 	 * Fork, and have the parent execute the command, if any, or present
1188 	 * the socket data.  The child continues as the authentication agent.
1189 	 */
1190 	if (D_flag || d_flag) {
1191 		log_init(__progname,
1192 		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1193 		    SYSLOG_FACILITY_AUTH, 1);
1194 		if (c_flag)
1195 			printf("setenv %s %s;\n",
1196 			    SSH_AUTHSOCKET_ENV_NAME, socket_name);
1197 		else
1198 			printf("%s=%s; export %s;\n",
1199 			    SSH_AUTHSOCKET_ENV_NAME, socket_name,
1200 			    SSH_AUTHSOCKET_ENV_NAME);
1201 		printf("echo Agent pid %ld;\n", (long)parent_pid);
1202 		fflush(stdout);
1203 		goto skip;
1204 	}
1205 	pid = fork();
1206 	if (pid == -1) {
1207 		perror("fork");
1208 		cleanup_exit(1);
1209 	}
1210 	if (pid != 0) {		/* Parent - execute the given command. */
1211 		close(sock);
1212 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1213 		if (ac == 0) {
1214 			(*f_setenv)(SSH_AUTHSOCKET_ENV_NAME, socket_name);
1215 			(*f_setenv)(SSH_AGENTPID_ENV_NAME, pidstrbuf);
1216 			printf("echo Agent pid %ld;\n", (long)pid);
1217 			exit(0);
1218 		}
1219 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1220 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1221 			perror("setenv");
1222 			exit(1);
1223 		}
1224 		execvp(av[0], av);
1225 		perror(av[0]);
1226 		exit(1);
1227 	}
1228 	/* child */
1229 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1230 
1231 	if (setsid() == -1) {
1232 		error("setsid: %s", strerror(errno));
1233 		cleanup_exit(1);
1234 	}
1235 
1236 	(void)chdir("/");
1237 
1238 	if (sock != STDERR_FILENO + 1) {
1239 		if (dup2(sock, STDERR_FILENO + 1) == -1) {
1240 			error("dup2: %s", strerror(errno));
1241 			cleanup_exit(1);
1242 		}
1243 		close(sock);
1244 		sock = STDERR_FILENO + 1;
1245 	}
1246 #if defined(F_CLOSEM)
1247 	if (fcntl(sock + 1, F_CLOSEM, 0) == -1) {
1248 		error("fcntl F_CLOSEM: %s", strerror(errno));
1249 		cleanup_exit(1);
1250 	}
1251 #else
1252 	{
1253 		int nfiles;
1254 #if defined(_SC_OPEN_MAX)
1255 		nfiles = sysconf(_SC_OPEN_MAX);
1256 #elif defined(RLIMIT_NOFILE)
1257 		if (getrlimit(RLIMIT_CORE, &rlim) < 0) {
1258 			error("getrlimit RLIMIT_NOFILE: %s", strerror(errno));
1259 			cleanup_exit(1);
1260 		}
1261 		nfiles = rlim.rlim_cur;
1262 #elif defined(OPEN_MAX)
1263 		nfiles = OPEN_MAX;
1264 #elif defined(NOFILE)
1265 		nfiles = NOFILE;
1266 #else
1267 		nfiles = 1024;
1268 #endif
1269 		for (fd = sock + 1; fd < nfiles; fd++)
1270 			close(fd);
1271 	}
1272 #endif
1273 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1274 		if (dup2(fd, STDIN_FILENO) == -1 ||
1275 		    dup2(fd, STDOUT_FILENO) == -1 ||
1276 		    dup2(fd, STDERR_FILENO) == -1) {
1277 			error("dup2: %s", strerror(errno));
1278 			cleanup_exit(1);
1279 		}
1280 		if (fd > STDERR_FILENO)
1281 			close(fd);
1282 	}
1283 
1284 	/* deny core dumps, since memory contains unencrypted private keys */
1285 	rlim.rlim_cur = rlim.rlim_max = 0;
1286 	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1287 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1288 		cleanup_exit(1);
1289 	}
1290 
1291 skip:
1292 
1293 	cleanup_pid = getpid();
1294 
1295 #ifdef ENABLE_PKCS11
1296 	pkcs11_init(0);
1297 #endif
1298 	new_socket(AUTH_SOCKET, sock);
1299 	if (ac > 0)
1300 		parent_alive_interval = 10;
1301 	idtab_init();
1302 	signal(SIGPIPE, SIG_IGN);
1303 	signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1304 	signal(SIGHUP, cleanup_handler);
1305 	signal(SIGTERM, cleanup_handler);
1306 
1307 #ifdef __OpenBSD__
1308 	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1309 		fatal("%s: pledge: %s", __progname, strerror(errno));
1310 #endif
1311 
1312 	while (1) {
1313 		prepare_poll(&pfd, &npfd, &timeout);
1314 		result = poll(pfd, npfd, timeout);
1315 		saved_errno = errno;
1316 		if (parent_alive_interval != 0)
1317 			check_parent_exists();
1318 		(void) reaper();	/* remove expired keys */
1319 		if (result < 0) {
1320 			if (saved_errno == EINTR)
1321 				continue;
1322 			fatal("poll: %s", strerror(saved_errno));
1323 		} else if (result > 0)
1324 			after_poll(pfd, npfd);
1325 	}
1326 	/* NOTREACHED */
1327 }
1328