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