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