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