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