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