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