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