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