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