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