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