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