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