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