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