xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-agent.c (revision ed75d7a867996c84cfa88e3b8906816277e957f7)
1 /*	$NetBSD: ssh-agent.c,v 1.28 2020/02/27 00:24:40 christos Exp $	*/
2 /* $OpenBSD: ssh-agent.c,v 1.255 2020/02/06 22:30:54 naddy 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.28 2020/02/27 00:24:40 christos Exp $");
40 
41 #include <sys/param.h>	/* MIN MAX */
42 #include <sys/types.h>
43 #include <sys/time.h>
44 #include <sys/queue.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <sys/stat.h>
48 #include <sys/un.h>
49 #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, 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 	explicit_bzero(passwd, pwlen);
616 	free(passwd);
617 	send_status(e, success);
618 }
619 
620 static void
621 no_identities(SocketEntry *e)
622 {
623 	struct sshbuf *msg;
624 	int r;
625 
626 	if ((msg = sshbuf_new()) == NULL)
627 		fatal("%s: sshbuf_new failed", __func__);
628 	if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
629 	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
630 	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
631 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
632 	sshbuf_free(msg);
633 }
634 
635 #ifdef ENABLE_PKCS11
636 static void
637 process_add_smartcard_key(SocketEntry *e)
638 {
639 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
640 	char **comments = NULL;
641 	int r, i, count = 0, success = 0, confirm = 0;
642 	u_int seconds;
643 	time_t death = 0;
644 	u_char type;
645 	struct sshkey **keys = NULL, *k;
646 	Identity *id;
647 
648 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
649 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
650 		error("%s: buffer error: %s", __func__, ssh_err(r));
651 		goto send;
652 	}
653 
654 	while (sshbuf_len(e->request)) {
655 		if ((r = sshbuf_get_u8(e->request, &type)) != 0) {
656 			error("%s: buffer error: %s", __func__, ssh_err(r));
657 			goto send;
658 		}
659 		switch (type) {
660 		case SSH_AGENT_CONSTRAIN_LIFETIME:
661 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
662 				error("%s: buffer error: %s",
663 				    __func__, ssh_err(r));
664 				goto send;
665 			}
666 			death = monotime() + seconds;
667 			break;
668 		case SSH_AGENT_CONSTRAIN_CONFIRM:
669 			confirm = 1;
670 			break;
671 		default:
672 			error("%s: Unknown constraint type %d", __func__, type);
673 			goto send;
674 		}
675 	}
676 	if (realpath(provider, canonical_provider) == NULL) {
677 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
678 		    provider, strerror(errno));
679 		goto send;
680 	}
681 	if (match_pattern_list(canonical_provider, provider_whitelist, 0) != 1) {
682 		verbose("refusing PKCS#11 add of \"%.100s\": "
683 		    "provider not whitelisted", canonical_provider);
684 		goto send;
685 	}
686 	debug("%s: add %.100s", __func__, canonical_provider);
687 	if (lifetime && !death)
688 		death = monotime() + lifetime;
689 
690 	count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
691 	for (i = 0; i < count; i++) {
692 		k = keys[i];
693 		if (lookup_identity(k) == NULL) {
694 			id = xcalloc(1, sizeof(Identity));
695 			id->key = k;
696 			keys[i] = NULL; /* transferred */
697 			id->provider = xstrdup(canonical_provider);
698 			if (*comments[i] != '\0') {
699 				id->comment = comments[i];
700 				comments[i] = NULL; /* transferred */
701 			} else {
702 				id->comment = xstrdup(canonical_provider);
703 			}
704 			id->death = death;
705 			id->confirm = confirm;
706 			TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
707 			idtab->nentries++;
708 			success = 1;
709 		}
710 		sshkey_free(keys[i]);
711 		free(comments[i]);
712 	}
713 send:
714 	free(pin);
715 	free(provider);
716 	free(keys);
717 	free(comments);
718 	send_status(e, success);
719 }
720 
721 static void
722 process_remove_smartcard_key(SocketEntry *e)
723 {
724 	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
725 	int r, success = 0;
726 	Identity *id, *nxt;
727 
728 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
729 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
730 		error("%s: buffer error: %s", __func__, ssh_err(r));
731 		goto send;
732 	}
733 	free(pin);
734 
735 	if (realpath(provider, canonical_provider) == NULL) {
736 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
737 		    provider, strerror(errno));
738 		goto send;
739 	}
740 
741 	debug("%s: remove %.100s", __func__, canonical_provider);
742 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
743 		nxt = TAILQ_NEXT(id, next);
744 		/* Skip file--based keys */
745 		if (id->provider == NULL)
746 			continue;
747 		if (!strcmp(canonical_provider, id->provider)) {
748 			TAILQ_REMOVE(&idtab->idlist, id, next);
749 			free_identity(id);
750 			idtab->nentries--;
751 		}
752 	}
753 	if (pkcs11_del_provider(canonical_provider) == 0)
754 		success = 1;
755 	else
756 		error("%s: pkcs11_del_provider failed", __func__);
757 send:
758 	free(provider);
759 	send_status(e, success);
760 }
761 #endif /* ENABLE_PKCS11 */
762 
763 /* dispatch incoming messages */
764 
765 static int
766 process_message(u_int socknum)
767 {
768 	u_int msg_len;
769 	u_char type;
770 	const u_char *cp;
771 	int r;
772 	SocketEntry *e;
773 
774 	if (socknum >= sockets_alloc) {
775 		fatal("%s: socket number %u >= allocated %u",
776 		    __func__, socknum, sockets_alloc);
777 	}
778 	e = &sockets[socknum];
779 
780 	if (sshbuf_len(e->input) < 5)
781 		return 0;		/* Incomplete message header. */
782 	cp = sshbuf_ptr(e->input);
783 	msg_len = PEEK_U32(cp);
784 	if (msg_len > AGENT_MAX_LEN) {
785 		debug("%s: socket %u (fd=%d) message too long %u > %u",
786 		    __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
787 		return -1;
788 	}
789 	if (sshbuf_len(e->input) < msg_len + 4)
790 		return 0;		/* Incomplete message body. */
791 
792 	/* move the current input to e->request */
793 	sshbuf_reset(e->request);
794 	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
795 	    (r = sshbuf_get_u8(e->request, &type)) != 0) {
796 		if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
797 		    r == SSH_ERR_STRING_TOO_LARGE) {
798 			debug("%s: buffer error: %s", __func__, ssh_err(r));
799 			return -1;
800 		}
801 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
802 	}
803 
804 	debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
805 
806 	/* check whether agent is locked */
807 	if (locked && type != SSH_AGENTC_UNLOCK) {
808 		sshbuf_reset(e->request);
809 		switch (type) {
810 		case SSH2_AGENTC_REQUEST_IDENTITIES:
811 			/* send empty lists */
812 			no_identities(e);
813 			break;
814 		default:
815 			/* send a fail message for all other request types */
816 			send_status(e, 0);
817 		}
818 		return 0;
819 	}
820 
821 	switch (type) {
822 	case SSH_AGENTC_LOCK:
823 	case SSH_AGENTC_UNLOCK:
824 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
825 		break;
826 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
827 		process_remove_all_identities(e); /* safe for !WITH_SSH1 */
828 		break;
829 	/* ssh2 */
830 	case SSH2_AGENTC_SIGN_REQUEST:
831 		process_sign_request2(e);
832 		break;
833 	case SSH2_AGENTC_REQUEST_IDENTITIES:
834 		process_request_identities(e);
835 		break;
836 	case SSH2_AGENTC_ADD_IDENTITY:
837 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
838 		process_add_identity(e);
839 		break;
840 	case SSH2_AGENTC_REMOVE_IDENTITY:
841 		process_remove_identity(e);
842 		break;
843 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
844 		process_remove_all_identities(e);
845 		break;
846 #ifdef ENABLE_PKCS11
847 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
848 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
849 		process_add_smartcard_key(e);
850 		break;
851 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
852 		process_remove_smartcard_key(e);
853 		break;
854 #endif /* ENABLE_PKCS11 */
855 	default:
856 		/* Unknown message.  Respond with failure. */
857 		error("Unknown message %d", type);
858 		sshbuf_reset(e->request);
859 		send_status(e, 0);
860 		break;
861 	}
862 	return 0;
863 }
864 
865 static void
866 new_socket(sock_type type, int fd)
867 {
868 	u_int i, old_alloc, new_alloc;
869 
870 	set_nonblock(fd);
871 
872 	if (fd > max_fd)
873 		max_fd = fd;
874 
875 	for (i = 0; i < sockets_alloc; i++)
876 		if (sockets[i].type == AUTH_UNUSED) {
877 			sockets[i].fd = fd;
878 			if ((sockets[i].input = sshbuf_new()) == NULL)
879 				fatal("%s: sshbuf_new failed", __func__);
880 			if ((sockets[i].output = sshbuf_new()) == NULL)
881 				fatal("%s: sshbuf_new failed", __func__);
882 			if ((sockets[i].request = sshbuf_new()) == NULL)
883 				fatal("%s: sshbuf_new failed", __func__);
884 			sockets[i].type = type;
885 			return;
886 		}
887 	old_alloc = sockets_alloc;
888 	new_alloc = sockets_alloc + 10;
889 	sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
890 	for (i = old_alloc; i < new_alloc; i++)
891 		sockets[i].type = AUTH_UNUSED;
892 	sockets_alloc = new_alloc;
893 	sockets[old_alloc].fd = fd;
894 	if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
895 		fatal("%s: sshbuf_new failed", __func__);
896 	if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
897 		fatal("%s: sshbuf_new failed", __func__);
898 	if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
899 		fatal("%s: sshbuf_new failed", __func__);
900 	sockets[old_alloc].type = type;
901 }
902 
903 static int
904 handle_socket_read(u_int socknum)
905 {
906 	struct sockaddr_un sunaddr;
907 	socklen_t slen;
908 	uid_t euid;
909 	gid_t egid;
910 	int fd;
911 
912 	slen = sizeof(sunaddr);
913 	fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
914 	if (fd == -1) {
915 		error("accept from AUTH_SOCKET: %s", strerror(errno));
916 		return -1;
917 	}
918 	if (getpeereid(fd, &euid, &egid) == -1) {
919 		error("getpeereid %d failed: %s", fd, strerror(errno));
920 		close(fd);
921 		return -1;
922 	}
923 	if ((euid != 0) && (getuid() != euid)) {
924 		error("uid mismatch: peer euid %u != uid %u",
925 		    (u_int) euid, (u_int) getuid());
926 		close(fd);
927 		return -1;
928 	}
929 	new_socket(AUTH_CONNECTION, fd);
930 	return 0;
931 }
932 
933 static int
934 handle_conn_read(u_int socknum)
935 {
936 	char buf[AGENT_RBUF_LEN];
937 	ssize_t len;
938 	int r;
939 
940 	if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
941 		if (len == -1) {
942 			if (errno == EAGAIN || errno == EINTR)
943 				return 0;
944 			error("%s: read error on socket %u (fd %d): %s",
945 			    __func__, socknum, sockets[socknum].fd,
946 			    strerror(errno));
947 		}
948 		return -1;
949 	}
950 	if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
951 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
952 	explicit_bzero(buf, sizeof(buf));
953 	process_message(socknum);
954 	return 0;
955 }
956 
957 static int
958 handle_conn_write(u_int socknum)
959 {
960 	ssize_t len;
961 	int r;
962 
963 	if (sshbuf_len(sockets[socknum].output) == 0)
964 		return 0; /* shouldn't happen */
965 	if ((len = write(sockets[socknum].fd,
966 	    sshbuf_ptr(sockets[socknum].output),
967 	    sshbuf_len(sockets[socknum].output))) <= 0) {
968 		if (len == -1) {
969 			if (errno == EAGAIN || errno == EINTR)
970 				return 0;
971 			error("%s: read error on socket %u (fd %d): %s",
972 			    __func__, socknum, sockets[socknum].fd,
973 			    strerror(errno));
974 		}
975 		return -1;
976 	}
977 	if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
978 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
979 	return 0;
980 }
981 
982 static void
983 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
984 {
985 	size_t i;
986 	u_int socknum, activefds = npfd;
987 
988 	for (i = 0; i < npfd; i++) {
989 		if (pfd[i].revents == 0)
990 			continue;
991 		/* Find sockets entry */
992 		for (socknum = 0; socknum < sockets_alloc; socknum++) {
993 			if (sockets[socknum].type != AUTH_SOCKET &&
994 			    sockets[socknum].type != AUTH_CONNECTION)
995 				continue;
996 			if (pfd[i].fd == sockets[socknum].fd)
997 				break;
998 		}
999 		if (socknum >= sockets_alloc) {
1000 			error("%s: no socket for fd %d", __func__, pfd[i].fd);
1001 			continue;
1002 		}
1003 		/* Process events */
1004 		switch (sockets[socknum].type) {
1005 		case AUTH_SOCKET:
1006 			if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1007 				break;
1008 			if (npfd > maxfds) {
1009 				debug3("out of fds (active %u >= limit %u); "
1010 				    "skipping accept", activefds, maxfds);
1011 				break;
1012 			}
1013 			if (handle_socket_read(socknum) == 0)
1014 				activefds++;
1015 			break;
1016 		case AUTH_CONNECTION:
1017 			if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
1018 			    handle_conn_read(socknum) != 0) {
1019 				goto close_sock;
1020 			}
1021 			if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1022 			    handle_conn_write(socknum) != 0) {
1023  close_sock:
1024 				if (activefds == 0)
1025 					fatal("activefds == 0 at close_sock");
1026 				close_socket(&sockets[socknum]);
1027 				activefds--;
1028 				break;
1029 			}
1030 			break;
1031 		default:
1032 			break;
1033 		}
1034 	}
1035 }
1036 
1037 static int
1038 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1039 {
1040 	struct pollfd *pfd = *pfdp;
1041 	size_t i, j, npfd = 0;
1042 	time_t deadline;
1043 	int r;
1044 
1045 	/* Count active sockets */
1046 	for (i = 0; i < sockets_alloc; i++) {
1047 		switch (sockets[i].type) {
1048 		case AUTH_SOCKET:
1049 		case AUTH_CONNECTION:
1050 			npfd++;
1051 			break;
1052 		case AUTH_UNUSED:
1053 			break;
1054 		default:
1055 			fatal("Unknown socket type %d", sockets[i].type);
1056 			break;
1057 		}
1058 	}
1059 	if (npfd != *npfdp &&
1060 	    (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1061 		fatal("%s: recallocarray failed", __func__);
1062 	*pfdp = pfd;
1063 	*npfdp = npfd;
1064 
1065 	for (i = j = 0; i < sockets_alloc; i++) {
1066 		switch (sockets[i].type) {
1067 		case AUTH_SOCKET:
1068 			if (npfd > maxfds) {
1069 				debug3("out of fds (active %zu >= limit %u); "
1070 				    "skipping arming listener", npfd, maxfds);
1071 				break;
1072 			}
1073 			pfd[j].fd = sockets[i].fd;
1074 			pfd[j].revents = 0;
1075 			pfd[j].events = POLLIN;
1076 			j++;
1077 			break;
1078 		case AUTH_CONNECTION:
1079 			pfd[j].fd = sockets[i].fd;
1080 			pfd[j].revents = 0;
1081 			/*
1082 			 * Only prepare to read if we can handle a full-size
1083 			 * input read buffer and enqueue a max size reply..
1084 			 */
1085 			if ((r = sshbuf_check_reserve(sockets[i].input,
1086 			    AGENT_RBUF_LEN)) == 0 &&
1087 			    (r = sshbuf_check_reserve(sockets[i].output,
1088 			     AGENT_MAX_LEN)) == 0)
1089 				pfd[j].events = POLLIN;
1090 			else if (r != SSH_ERR_NO_BUFFER_SPACE) {
1091 				fatal("%s: buffer error: %s",
1092 				    __func__, ssh_err(r));
1093 			}
1094 			if (sshbuf_len(sockets[i].output) > 0)
1095 				pfd[j].events |= POLLOUT;
1096 			j++;
1097 			break;
1098 		default:
1099 			break;
1100 		}
1101 	}
1102 	deadline = reaper();
1103 	if (parent_alive_interval != 0)
1104 		deadline = (deadline == 0) ? parent_alive_interval :
1105 		    MINIMUM(deadline, parent_alive_interval);
1106 	if (deadline == 0) {
1107 		*timeoutp = -1; /* INFTIM */
1108 	} else {
1109 		if (deadline > INT_MAX / 1000)
1110 			*timeoutp = INT_MAX / 1000;
1111 		else
1112 			*timeoutp = deadline * 1000;
1113 	}
1114 	return (1);
1115 }
1116 
1117 static void
1118 cleanup_socket(void)
1119 {
1120 	if (cleanup_pid != 0 && getpid() != cleanup_pid)
1121 		return;
1122 	debug("%s: cleanup", __func__);
1123 	if (socket_name[0])
1124 		unlink(socket_name);
1125 	if (socket_dir[0])
1126 		rmdir(socket_dir);
1127 }
1128 
1129 void
1130 cleanup_exit(int i)
1131 {
1132 	cleanup_socket();
1133 	_exit(i);
1134 }
1135 
1136 /*ARGSUSED*/
1137 __dead static void
1138 cleanup_handler(int sig)
1139 {
1140 	cleanup_socket();
1141 #ifdef ENABLE_PKCS11
1142 	pkcs11_terminate();
1143 #endif
1144 	_exit(2);
1145 }
1146 
1147 static void
1148 check_parent_exists(void)
1149 {
1150 	/*
1151 	 * If our parent has exited then getppid() will return (pid_t)1,
1152 	 * so testing for that should be safe.
1153 	 */
1154 	if (parent_pid != -1 && getppid() != parent_pid) {
1155 		/* printf("Parent has died - Authentication agent exiting.\n"); */
1156 		cleanup_socket();
1157 		_exit(2);
1158 	}
1159 }
1160 
1161 __dead static void
1162 usage(void)
1163 {
1164 	fprintf(stderr,
1165 	    "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1166 	    "                 [-P provider_whitelist] [-t life] [command [arg ...]]\n"
1167 	    "       ssh-agent [-c | -s] -k\n");
1168 	exit(1);
1169 }
1170 
1171 static void
1172 csh_setenv(const char *name, const char *value)
1173 {
1174 	printf("setenv %s %s;\n", name, value);
1175 }
1176 
1177 static void
1178 csh_unsetenv(const char *name)
1179 {
1180 	printf("unsetenv %s;\n", name);
1181 }
1182 
1183 static void
1184 sh_setenv(const char *name, const char *value)
1185 {
1186 	printf("%s=%s; export %s;\n", name, value, name);
1187 }
1188 
1189 static void
1190 sh_unsetenv(const char *name)
1191 {
1192 	printf("unset %s;\n", name);
1193 }
1194 int
1195 main(int ac, char **av)
1196 {
1197 	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1198 	int sock, fd, ch, result, saved_errno;
1199 	char *shell, *pidstr, *agentsocket = NULL;
1200 	struct rlimit rlim;
1201 	void (*f_setenv)(const char *, const char *);
1202 	void (*f_unsetenv)(const char *);
1203 	extern int optind;
1204 	extern char *optarg;
1205 	pid_t pid;
1206 	char pidstrbuf[1 + 3 * sizeof pid];
1207 	size_t len;
1208 	mode_t prev_mask;
1209 	int timeout = -1; /* INFTIM */
1210 	struct pollfd *pfd = NULL;
1211 	size_t npfd = 0;
1212 	u_int maxfds;
1213 
1214 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1215 	sanitise_stdfd();
1216 
1217 	/* drop */
1218 	setegid(getgid());
1219 	setgid(getgid());
1220 
1221 	if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1222 		fatal("%s: getrlimit: %s", __progname, strerror(errno));
1223 
1224 #ifdef WITH_OPENSSL
1225 	OpenSSL_add_all_algorithms();
1226 #endif
1227 
1228 	while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1229 		switch (ch) {
1230 		case 'E':
1231 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
1232 			if (fingerprint_hash == -1)
1233 				fatal("Invalid hash algorithm \"%s\"", optarg);
1234 			break;
1235 		case 'c':
1236 			if (s_flag)
1237 				usage();
1238 			c_flag++;
1239 			break;
1240 		case 'k':
1241 			k_flag++;
1242 			break;
1243 		case 'P':
1244 			if (provider_whitelist != NULL)
1245 				fatal("-P option already specified");
1246 			provider_whitelist = xstrdup(optarg);
1247 			break;
1248 		case 's':
1249 			if (c_flag)
1250 				usage();
1251 			s_flag++;
1252 			break;
1253 		case 'd':
1254 			if (d_flag || D_flag)
1255 				usage();
1256 			d_flag++;
1257 			break;
1258 		case 'D':
1259 			if (d_flag || D_flag)
1260 				usage();
1261 			D_flag++;
1262 			break;
1263 		case 'a':
1264 			agentsocket = optarg;
1265 			break;
1266 		case 't':
1267 			if ((lifetime = convtime(optarg)) == -1) {
1268 				fprintf(stderr, "Invalid lifetime\n");
1269 				usage();
1270 			}
1271 			break;
1272 		default:
1273 			usage();
1274 		}
1275 	}
1276 	ac -= optind;
1277 	av += optind;
1278 
1279 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1280 		usage();
1281 
1282 	if (provider_whitelist == NULL)
1283 		provider_whitelist = xstrdup(DEFAULT_PROVIDER_WHITELIST);
1284 
1285 	if (ac == 0 && !c_flag && !s_flag) {
1286 		shell = getenv("SHELL");
1287 		if (shell != NULL && (len = strlen(shell)) > 2 &&
1288 		    strncmp(shell + len - 3, "csh", 3) == 0)
1289 			c_flag = 1;
1290 	}
1291 	if (c_flag) {
1292 		f_setenv = csh_setenv;
1293 		f_unsetenv = csh_unsetenv;
1294 	} else {
1295 		f_setenv = sh_setenv;
1296 		f_unsetenv = sh_unsetenv;
1297 	}
1298 	if (k_flag) {
1299 		const char *errstr = NULL;
1300 
1301 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1302 		if (pidstr == NULL) {
1303 			fprintf(stderr, "%s not set, cannot kill agent\n",
1304 			    SSH_AGENTPID_ENV_NAME);
1305 			exit(1);
1306 		}
1307 		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1308 		if (errstr) {
1309 			fprintf(stderr,
1310 			    "%s=\"%s\", which is not a good PID: %s\n",
1311 			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1312 			exit(1);
1313 		}
1314 		if (kill(pid, SIGTERM) == -1) {
1315 			perror("kill");
1316 			exit(1);
1317 		}
1318 		(*f_unsetenv)(SSH_AUTHSOCKET_ENV_NAME);
1319 		(*f_unsetenv)(SSH_AGENTPID_ENV_NAME);
1320 		printf("echo Agent pid %ld killed;\n", (long)pid);
1321 		exit(0);
1322 	}
1323 
1324 	/*
1325 	 * Minimum file descriptors:
1326 	 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1327 	 * a few spare for libc / stack protectors / sanitisers, etc.
1328 	 */
1329 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1330 	if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1331 		fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
1332 		    __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1333 	maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1334 
1335 	parent_pid = getpid();
1336 
1337 	if (agentsocket == NULL) {
1338 		/* Create private directory for agent socket */
1339 		mktemp_proto(socket_dir, sizeof(socket_dir));
1340 		if (mkdtemp(socket_dir) == NULL) {
1341 			perror("mkdtemp: private socket dir");
1342 			exit(1);
1343 		}
1344 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1345 		    (long)parent_pid);
1346 	} else {
1347 		/* Try to use specified agent socket */
1348 		socket_dir[0] = '\0';
1349 		strlcpy(socket_name, agentsocket, sizeof socket_name);
1350 	}
1351 
1352 	/*
1353 	 * Create socket early so it will exist before command gets run from
1354 	 * the parent.
1355 	 */
1356 	prev_mask = umask(0177);
1357 	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1358 	if (sock < 0) {
1359 		/* XXX - unix_listener() calls error() not perror() */
1360 		*socket_name = '\0'; /* Don't unlink any existing file */
1361 		cleanup_exit(1);
1362 	}
1363 	umask(prev_mask);
1364 
1365 	/*
1366 	 * Fork, and have the parent execute the command, if any, or present
1367 	 * the socket data.  The child continues as the authentication agent.
1368 	 */
1369 	if (D_flag || d_flag) {
1370 		log_init(__progname,
1371 		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1372 		    SYSLOG_FACILITY_AUTH, 1);
1373 		if (c_flag)
1374 			printf("setenv %s %s;\n",
1375 			    SSH_AUTHSOCKET_ENV_NAME, socket_name);
1376 		else
1377 			printf("%s=%s; export %s;\n",
1378 			    SSH_AUTHSOCKET_ENV_NAME, socket_name,
1379 			    SSH_AUTHSOCKET_ENV_NAME);
1380 		printf("echo Agent pid %ld;\n", (long)parent_pid);
1381 		fflush(stdout);
1382 		goto skip;
1383 	}
1384 	pid = fork();
1385 	if (pid == -1) {
1386 		perror("fork");
1387 		cleanup_exit(1);
1388 	}
1389 	if (pid != 0) {		/* Parent - execute the given command. */
1390 		close(sock);
1391 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1392 		if (ac == 0) {
1393 			(*f_setenv)(SSH_AUTHSOCKET_ENV_NAME, socket_name);
1394 			(*f_setenv)(SSH_AGENTPID_ENV_NAME, pidstrbuf);
1395 			printf("echo Agent pid %ld;\n", (long)pid);
1396 			exit(0);
1397 		}
1398 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1399 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1400 			perror("setenv");
1401 			exit(1);
1402 		}
1403 		execvp(av[0], av);
1404 		perror(av[0]);
1405 		exit(1);
1406 	}
1407 	/* child */
1408 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1409 
1410 	if (setsid() == -1) {
1411 		error("setsid: %s", strerror(errno));
1412 		cleanup_exit(1);
1413 	}
1414 
1415 	(void)chdir("/");
1416 
1417 	if (sock != STDERR_FILENO + 1) {
1418 		if (dup2(sock, STDERR_FILENO + 1) == -1) {
1419 			error("dup2: %s", strerror(errno));
1420 			cleanup_exit(1);
1421 		}
1422 		close(sock);
1423 		sock = STDERR_FILENO + 1;
1424 	}
1425 #if defined(F_CLOSEM)
1426 	if (fcntl(sock + 1, F_CLOSEM, 0) == -1) {
1427 		error("fcntl F_CLOSEM: %s", strerror(errno));
1428 		cleanup_exit(1);
1429 	}
1430 #else
1431 	{
1432 		int nfiles;
1433 #if defined(_SC_OPEN_MAX)
1434 		nfiles = sysconf(_SC_OPEN_MAX);
1435 #elif defined(RLIMIT_NOFILE)
1436 		if (getrlimit(RLIMIT_CORE, &rlim) < 0) {
1437 			error("getrlimit RLIMIT_NOFILE: %s", strerror(errno));
1438 			cleanup_exit(1);
1439 		}
1440 		nfiles = rlim.rlim_cur;
1441 #elif defined(OPEN_MAX)
1442 		nfiles = OPEN_MAX;
1443 #elif defined(NOFILE)
1444 		nfiles = NOFILE;
1445 #else
1446 		nfiles = 1024;
1447 #endif
1448 		for (fd = sock + 1; fd < nfiles; fd++)
1449 			close(fd);
1450 	}
1451 #endif
1452 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1453 		if (dup2(fd, STDIN_FILENO) == -1 ||
1454 		    dup2(fd, STDOUT_FILENO) == -1 ||
1455 		    dup2(fd, STDERR_FILENO) == -1) {
1456 			error("dup2: %s", strerror(errno));
1457 			cleanup_exit(1);
1458 		}
1459 		if (fd > STDERR_FILENO)
1460 			close(fd);
1461 	}
1462 
1463 	/* deny core dumps, since memory contains unencrypted private keys */
1464 	rlim.rlim_cur = rlim.rlim_max = 0;
1465 	if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
1466 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1467 		cleanup_exit(1);
1468 	}
1469 
1470 skip:
1471 
1472 	cleanup_pid = getpid();
1473 
1474 #ifdef ENABLE_PKCS11
1475 	pkcs11_init(0);
1476 #endif
1477 	new_socket(AUTH_SOCKET, sock);
1478 	if (ac > 0)
1479 		parent_alive_interval = 10;
1480 	idtab_init();
1481 	ssh_signal(SIGPIPE, SIG_IGN);
1482 	ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1483 	ssh_signal(SIGHUP, cleanup_handler);
1484 	ssh_signal(SIGTERM, cleanup_handler);
1485 
1486 #ifdef __OpenBSD__
1487 	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1488 		fatal("%s: pledge: %s", __progname, strerror(errno));
1489 #endif
1490 
1491 	while (1) {
1492 		prepare_poll(&pfd, &npfd, &timeout, maxfds);
1493 		result = poll(pfd, npfd, timeout);
1494 		saved_errno = errno;
1495 		if (parent_alive_interval != 0)
1496 			check_parent_exists();
1497 		(void) reaper();	/* remove expired keys */
1498 		if (result == -1) {
1499 			if (saved_errno == EINTR)
1500 				continue;
1501 			fatal("poll: %s", strerror(saved_errno));
1502 		} else if (result > 0)
1503 			after_poll(pfd, npfd, maxfds);
1504 	}
1505 	/* NOTREACHED */
1506 }
1507