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