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