xref: /freebsd/crypto/openssh/ssh-agent.c (revision d6b92ffa)
1 /* $OpenBSD: ssh-agent.c,v 1.215 2016/11/30 03:07:37 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * The authentication agent program.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  *
14  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36 
37 #include "includes.h"
38 __RCSID("$FreeBSD$");
39 
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/resource.h>
43 #include <sys/stat.h>
44 #include <sys/socket.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
47 #endif
48 #ifdef HAVE_SYS_UN_H
49 # include <sys/un.h>
50 #endif
51 #include "openbsd-compat/sys-queue.h"
52 
53 #ifdef WITH_OPENSSL
54 #include <openssl/evp.h>
55 #include "openbsd-compat/openssl-compat.h"
56 #endif
57 
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <limits.h>
61 #ifdef HAVE_PATHS_H
62 # include <paths.h>
63 #endif
64 #include <signal.h>
65 #include <stdarg.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <time.h>
69 #include <string.h>
70 #include <unistd.h>
71 #ifdef HAVE_UTIL_H
72 # include <util.h>
73 #endif
74 
75 #include "xmalloc.h"
76 #include "ssh.h"
77 #include "rsa.h"
78 #include "sshbuf.h"
79 #include "sshkey.h"
80 #include "authfd.h"
81 #include "compat.h"
82 #include "log.h"
83 #include "misc.h"
84 #include "digest.h"
85 #include "ssherr.h"
86 #include "match.h"
87 
88 #ifdef ENABLE_PKCS11
89 #include "ssh-pkcs11.h"
90 #endif
91 
92 #ifndef DEFAULT_PKCS11_WHITELIST
93 # define DEFAULT_PKCS11_WHITELIST "/usr/lib/*,/usr/local/lib/*"
94 #endif
95 
96 typedef enum {
97 	AUTH_UNUSED,
98 	AUTH_SOCKET,
99 	AUTH_CONNECTION
100 } sock_type;
101 
102 typedef struct {
103 	int fd;
104 	sock_type type;
105 	struct sshbuf *input;
106 	struct sshbuf *output;
107 	struct sshbuf *request;
108 } SocketEntry;
109 
110 u_int sockets_alloc = 0;
111 SocketEntry *sockets = NULL;
112 
113 typedef struct identity {
114 	TAILQ_ENTRY(identity) next;
115 	struct sshkey *key;
116 	char *comment;
117 	char *provider;
118 	time_t death;
119 	u_int confirm;
120 } Identity;
121 
122 typedef struct {
123 	int nentries;
124 	TAILQ_HEAD(idqueue, identity) idlist;
125 } Idtab;
126 
127 /* private key table, one per protocol version */
128 Idtab idtable[3];
129 
130 int max_fd = 0;
131 
132 /* pid of shell == parent of agent */
133 pid_t parent_pid = -1;
134 time_t parent_alive_interval = 0;
135 
136 /* pid of process for which cleanup_socket is applicable */
137 pid_t cleanup_pid = 0;
138 
139 /* pathname and directory for AUTH_SOCKET */
140 char socket_name[PATH_MAX];
141 char socket_dir[PATH_MAX];
142 
143 /* PKCS#11 path whitelist */
144 static char *pkcs11_whitelist;
145 
146 /* locking */
147 #define LOCK_SIZE	32
148 #define LOCK_SALT_SIZE	16
149 #define LOCK_ROUNDS	1
150 int locked = 0;
151 u_char lock_pwhash[LOCK_SIZE];
152 u_char lock_salt[LOCK_SALT_SIZE];
153 
154 extern char *__progname;
155 
156 /* Default lifetime in seconds (0 == forever) */
157 static long lifetime = 0;
158 
159 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
160 
161 /*
162  * Client connection count; incremented in new_socket() and decremented in
163  * close_socket().  When it reaches 0, ssh-agent will exit.  Since it is
164  * normally initialized to 1, it will never reach 0.  However, if the -x
165  * option is specified, it is initialized to 0 in main(); in that case,
166  * ssh-agent will exit as soon as it has had at least one client but no
167  * longer has any.
168  */
169 static int xcount = 1;
170 
171 static void
172 close_socket(SocketEntry *e)
173 {
174 	int last = 0;
175 
176 	if (e->type == AUTH_CONNECTION) {
177 		debug("xcount %d -> %d", xcount, xcount - 1);
178 		if (--xcount == 0)
179 			last = 1;
180 	}
181 	close(e->fd);
182 	e->fd = -1;
183 	e->type = AUTH_UNUSED;
184 	sshbuf_free(e->input);
185 	sshbuf_free(e->output);
186 	sshbuf_free(e->request);
187 	if (last)
188 		cleanup_exit(0);
189 }
190 
191 static void
192 idtab_init(void)
193 {
194 	int i;
195 
196 	for (i = 0; i <=2; i++) {
197 		TAILQ_INIT(&idtable[i].idlist);
198 		idtable[i].nentries = 0;
199 	}
200 }
201 
202 /* return private key table for requested protocol version */
203 static Idtab *
204 idtab_lookup(int version)
205 {
206 	if (version < 1 || version > 2)
207 		fatal("internal error, bad protocol version %d", version);
208 	return &idtable[version];
209 }
210 
211 static void
212 free_identity(Identity *id)
213 {
214 	sshkey_free(id->key);
215 	free(id->provider);
216 	free(id->comment);
217 	free(id);
218 }
219 
220 /* return matching private key for given public key */
221 static Identity *
222 lookup_identity(struct sshkey *key, int version)
223 {
224 	Identity *id;
225 
226 	Idtab *tab = idtab_lookup(version);
227 	TAILQ_FOREACH(id, &tab->idlist, next) {
228 		if (sshkey_equal(key, id->key))
229 			return (id);
230 	}
231 	return (NULL);
232 }
233 
234 /* Check confirmation of keysign request */
235 static int
236 confirm_key(Identity *id)
237 {
238 	char *p;
239 	int ret = -1;
240 
241 	p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
242 	if (p != NULL &&
243 	    ask_permission("Allow use of key %s?\nKey fingerprint %s.",
244 	    id->comment, p))
245 		ret = 0;
246 	free(p);
247 
248 	return (ret);
249 }
250 
251 static void
252 send_status(SocketEntry *e, int success)
253 {
254 	int r;
255 
256 	if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
257 	    (r = sshbuf_put_u8(e->output, success ?
258 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
259 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
260 }
261 
262 /* send list of supported public keys to 'client' */
263 static void
264 process_request_identities(SocketEntry *e, int version)
265 {
266 	Idtab *tab = idtab_lookup(version);
267 	Identity *id;
268 	struct sshbuf *msg;
269 	int r;
270 
271 	if ((msg = sshbuf_new()) == NULL)
272 		fatal("%s: sshbuf_new failed", __func__);
273 	if ((r = sshbuf_put_u8(msg, (version == 1) ?
274 	    SSH_AGENT_RSA_IDENTITIES_ANSWER :
275 	    SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
276 	    (r = sshbuf_put_u32(msg, tab->nentries)) != 0)
277 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
278 	TAILQ_FOREACH(id, &tab->idlist, next) {
279 		if (id->key->type == KEY_RSA1) {
280 #ifdef WITH_SSH1
281 			if ((r = sshbuf_put_u32(msg,
282 			    BN_num_bits(id->key->rsa->n))) != 0 ||
283 			    (r = sshbuf_put_bignum1(msg,
284 			    id->key->rsa->e)) != 0 ||
285 			    (r = sshbuf_put_bignum1(msg,
286 			    id->key->rsa->n)) != 0)
287 				fatal("%s: buffer error: %s",
288 				    __func__, ssh_err(r));
289 #endif
290 		} else {
291 			u_char *blob;
292 			size_t blen;
293 
294 			if ((r = sshkey_to_blob(id->key, &blob, &blen)) != 0) {
295 				error("%s: sshkey_to_blob: %s", __func__,
296 				    ssh_err(r));
297 				continue;
298 			}
299 			if ((r = sshbuf_put_string(msg, blob, blen)) != 0)
300 				fatal("%s: buffer error: %s",
301 				    __func__, ssh_err(r));
302 			free(blob);
303 		}
304 		if ((r = sshbuf_put_cstring(msg, id->comment)) != 0)
305 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
306 	}
307 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
308 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
309 	sshbuf_free(msg);
310 }
311 
312 #ifdef WITH_SSH1
313 /* ssh1 only */
314 static void
315 process_authentication_challenge1(SocketEntry *e)
316 {
317 	u_char buf[32], mdbuf[16], session_id[16];
318 	u_int response_type;
319 	BIGNUM *challenge;
320 	Identity *id;
321 	int r, len;
322 	struct sshbuf *msg;
323 	struct ssh_digest_ctx *md;
324 	struct sshkey *key;
325 
326 	if ((msg = sshbuf_new()) == NULL)
327 		fatal("%s: sshbuf_new failed", __func__);
328 	if ((key = sshkey_new(KEY_RSA1)) == NULL)
329 		fatal("%s: sshkey_new failed", __func__);
330 	if ((challenge = BN_new()) == NULL)
331 		fatal("%s: BN_new failed", __func__);
332 
333 	if ((r = sshbuf_get_u32(e->request, NULL)) != 0 || /* ignored */
334 	    (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
335 	    (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0 ||
336 	    (r = sshbuf_get_bignum1(e->request, challenge)))
337 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
338 
339 	/* Only protocol 1.1 is supported */
340 	if (sshbuf_len(e->request) == 0)
341 		goto failure;
342 	if ((r = sshbuf_get(e->request, session_id, sizeof(session_id))) != 0 ||
343 	    (r = sshbuf_get_u32(e->request, &response_type)) != 0)
344 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
345 	if (response_type != 1)
346 		goto failure;
347 
348 	id = lookup_identity(key, 1);
349 	if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
350 		struct sshkey *private = id->key;
351 		/* Decrypt the challenge using the private key. */
352 		if ((r = rsa_private_decrypt(challenge, challenge,
353 		    private->rsa) != 0)) {
354 			fatal("%s: rsa_public_encrypt: %s", __func__,
355 			    ssh_err(r));
356 			goto failure;	/* XXX ? */
357 		}
358 
359 		/* The response is MD5 of decrypted challenge plus session id */
360 		len = BN_num_bytes(challenge);
361 		if (len <= 0 || len > 32) {
362 			logit("%s: bad challenge length %d", __func__, len);
363 			goto failure;
364 		}
365 		memset(buf, 0, 32);
366 		BN_bn2bin(challenge, buf + 32 - len);
367 		if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
368 		    ssh_digest_update(md, buf, 32) < 0 ||
369 		    ssh_digest_update(md, session_id, 16) < 0 ||
370 		    ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
371 			fatal("%s: md5 failed", __func__);
372 		ssh_digest_free(md);
373 
374 		/* Send the response. */
375 		if ((r = sshbuf_put_u8(msg, SSH_AGENT_RSA_RESPONSE)) != 0 ||
376 		    (r = sshbuf_put(msg, mdbuf, sizeof(mdbuf))) != 0)
377 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
378 		goto send;
379 	}
380 
381  failure:
382 	/* Unknown identity or protocol error.  Send failure. */
383 	if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
384 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
385  send:
386 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
387 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
388 	sshkey_free(key);
389 	BN_clear_free(challenge);
390 	sshbuf_free(msg);
391 }
392 #endif
393 
394 static char *
395 agent_decode_alg(struct sshkey *key, u_int flags)
396 {
397 	if (key->type == KEY_RSA) {
398 		if (flags & SSH_AGENT_RSA_SHA2_256)
399 			return "rsa-sha2-256";
400 		else if (flags & SSH_AGENT_RSA_SHA2_512)
401 			return "rsa-sha2-512";
402 	}
403 	return NULL;
404 }
405 
406 /* ssh2 only */
407 static void
408 process_sign_request2(SocketEntry *e)
409 {
410 	u_char *blob, *data, *signature = NULL;
411 	size_t blen, dlen, slen = 0;
412 	u_int compat = 0, flags;
413 	int r, ok = -1;
414 	struct sshbuf *msg;
415 	struct sshkey *key;
416 	struct identity *id;
417 
418 	if ((msg = sshbuf_new()) == NULL)
419 		fatal("%s: sshbuf_new failed", __func__);
420 	if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0 ||
421 	    (r = sshbuf_get_string(e->request, &data, &dlen)) != 0 ||
422 	    (r = sshbuf_get_u32(e->request, &flags)) != 0)
423 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
424 	if (flags & SSH_AGENT_OLD_SIGNATURE)
425 		compat = SSH_BUG_SIGBLOB;
426 	if ((r = sshkey_from_blob(blob, blen, &key)) != 0) {
427 		error("%s: cannot parse key blob: %s", __func__, ssh_err(r));
428 		goto send;
429 	}
430 	if ((id = lookup_identity(key, 2)) == NULL) {
431 		verbose("%s: %s key not found", __func__, sshkey_type(key));
432 		goto send;
433 	}
434 	if (id->confirm && confirm_key(id) != 0) {
435 		verbose("%s: user refused key", __func__);
436 		goto send;
437 	}
438 	if ((r = sshkey_sign(id->key, &signature, &slen,
439 	    data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
440 		error("%s: sshkey_sign: %s", __func__, ssh_err(r));
441 		goto send;
442 	}
443 	/* Success */
444 	ok = 0;
445  send:
446 	sshkey_free(key);
447 	if (ok == 0) {
448 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
449 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
450 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
451 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
452 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
453 
454 	if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
455 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
456 
457 	sshbuf_free(msg);
458 	free(data);
459 	free(blob);
460 	free(signature);
461 }
462 
463 /* shared */
464 static void
465 process_remove_identity(SocketEntry *e, int version)
466 {
467 	size_t blen;
468 	int r, success = 0;
469 	struct sshkey *key = NULL;
470 	u_char *blob;
471 #ifdef WITH_SSH1
472 	u_int bits;
473 #endif /* WITH_SSH1 */
474 
475 	switch (version) {
476 #ifdef WITH_SSH1
477 	case 1:
478 		if ((key = sshkey_new(KEY_RSA1)) == NULL) {
479 			error("%s: sshkey_new failed", __func__);
480 			return;
481 		}
482 		if ((r = sshbuf_get_u32(e->request, &bits)) != 0 ||
483 		    (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 ||
484 		    (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0)
485 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
486 
487 		if (bits != sshkey_size(key))
488 			logit("Warning: identity keysize mismatch: "
489 			    "actual %u, announced %u",
490 			    sshkey_size(key), bits);
491 		break;
492 #endif /* WITH_SSH1 */
493 	case 2:
494 		if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0)
495 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
496 		if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
497 			error("%s: sshkey_from_blob failed: %s",
498 			    __func__, ssh_err(r));
499 		free(blob);
500 		break;
501 	}
502 	if (key != NULL) {
503 		Identity *id = lookup_identity(key, version);
504 		if (id != NULL) {
505 			/*
506 			 * We have this key.  Free the old key.  Since we
507 			 * don't want to leave empty slots in the middle of
508 			 * the array, we actually free the key there and move
509 			 * all the entries between the empty slot and the end
510 			 * of the array.
511 			 */
512 			Idtab *tab = idtab_lookup(version);
513 			if (tab->nentries < 1)
514 				fatal("process_remove_identity: "
515 				    "internal error: tab->nentries %d",
516 				    tab->nentries);
517 			TAILQ_REMOVE(&tab->idlist, id, next);
518 			free_identity(id);
519 			tab->nentries--;
520 			success = 1;
521 		}
522 		sshkey_free(key);
523 	}
524 	send_status(e, success);
525 }
526 
527 static void
528 process_remove_all_identities(SocketEntry *e, int version)
529 {
530 	Idtab *tab = idtab_lookup(version);
531 	Identity *id;
532 
533 	/* Loop over all identities and clear the keys. */
534 	for (id = TAILQ_FIRST(&tab->idlist); id;
535 	    id = TAILQ_FIRST(&tab->idlist)) {
536 		TAILQ_REMOVE(&tab->idlist, id, next);
537 		free_identity(id);
538 	}
539 
540 	/* Mark that there are no identities. */
541 	tab->nentries = 0;
542 
543 	/* Send success. */
544 	send_status(e, 1);
545 }
546 
547 /* removes expired keys and returns number of seconds until the next expiry */
548 static time_t
549 reaper(void)
550 {
551 	time_t deadline = 0, now = monotime();
552 	Identity *id, *nxt;
553 	int version;
554 	Idtab *tab;
555 
556 	for (version = 1; version < 3; version++) {
557 		tab = idtab_lookup(version);
558 		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
559 			nxt = TAILQ_NEXT(id, next);
560 			if (id->death == 0)
561 				continue;
562 			if (now >= id->death) {
563 				debug("expiring key '%s'", id->comment);
564 				TAILQ_REMOVE(&tab->idlist, id, next);
565 				free_identity(id);
566 				tab->nentries--;
567 			} else
568 				deadline = (deadline == 0) ? id->death :
569 				    MINIMUM(deadline, id->death);
570 		}
571 	}
572 	if (deadline == 0 || deadline <= now)
573 		return 0;
574 	else
575 		return (deadline - now);
576 }
577 
578 /*
579  * XXX this and the corresponding serialisation function probably belongs
580  * in key.c
581  */
582 #ifdef WITH_SSH1
583 static int
584 agent_decode_rsa1(struct sshbuf *m, struct sshkey **kp)
585 {
586 	struct sshkey *k = NULL;
587 	int r = SSH_ERR_INTERNAL_ERROR;
588 
589 	*kp = NULL;
590 	if ((k = sshkey_new_private(KEY_RSA1)) == NULL)
591 		return SSH_ERR_ALLOC_FAIL;
592 
593 	if ((r = sshbuf_get_u32(m, NULL)) != 0 ||		/* ignored */
594 	    (r = sshbuf_get_bignum1(m, k->rsa->n)) != 0 ||
595 	    (r = sshbuf_get_bignum1(m, k->rsa->e)) != 0 ||
596 	    (r = sshbuf_get_bignum1(m, k->rsa->d)) != 0 ||
597 	    (r = sshbuf_get_bignum1(m, k->rsa->iqmp)) != 0 ||
598 	    /* SSH1 and SSL have p and q swapped */
599 	    (r = sshbuf_get_bignum1(m, k->rsa->q)) != 0 ||	/* p */
600 	    (r = sshbuf_get_bignum1(m, k->rsa->p)) != 0) 	/* q */
601 		goto out;
602 
603 	/* Generate additional parameters */
604 	if ((r = rsa_generate_additional_parameters(k->rsa)) != 0)
605 		goto out;
606 	/* enable blinding */
607 	if (RSA_blinding_on(k->rsa, NULL) != 1) {
608 		r = SSH_ERR_LIBCRYPTO_ERROR;
609 		goto out;
610 	}
611 
612 	r = 0; /* success */
613  out:
614 	if (r == 0)
615 		*kp = k;
616 	else
617 		sshkey_free(k);
618 	return r;
619 }
620 #endif /* WITH_SSH1 */
621 
622 static void
623 process_add_identity(SocketEntry *e, int version)
624 {
625 	Idtab *tab = idtab_lookup(version);
626 	Identity *id;
627 	int success = 0, confirm = 0;
628 	u_int seconds;
629 	char *comment = NULL;
630 	time_t death = 0;
631 	struct sshkey *k = NULL;
632 	u_char ctype;
633 	int r = SSH_ERR_INTERNAL_ERROR;
634 
635 	switch (version) {
636 #ifdef WITH_SSH1
637 	case 1:
638 		r = agent_decode_rsa1(e->request, &k);
639 		break;
640 #endif /* WITH_SSH1 */
641 	case 2:
642 		r = sshkey_private_deserialize(e->request, &k);
643 		break;
644 	}
645 	if (r != 0 || k == NULL ||
646 	    (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
647 		error("%s: decode private key: %s", __func__, ssh_err(r));
648 		goto err;
649 	}
650 
651 	while (sshbuf_len(e->request)) {
652 		if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
653 			error("%s: buffer error: %s", __func__, ssh_err(r));
654 			goto err;
655 		}
656 		switch (ctype) {
657 		case SSH_AGENT_CONSTRAIN_LIFETIME:
658 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
659 				error("%s: bad lifetime constraint: %s",
660 				    __func__, ssh_err(r));
661 				goto err;
662 			}
663 			death = monotime() + seconds;
664 			break;
665 		case SSH_AGENT_CONSTRAIN_CONFIRM:
666 			confirm = 1;
667 			break;
668 		default:
669 			error("%s: Unknown constraint %d", __func__, ctype);
670  err:
671 			sshbuf_reset(e->request);
672 			free(comment);
673 			sshkey_free(k);
674 			goto send;
675 		}
676 	}
677 
678 	success = 1;
679 	if (lifetime && !death)
680 		death = monotime() + lifetime;
681 	if ((id = lookup_identity(k, version)) == NULL) {
682 		id = xcalloc(1, sizeof(Identity));
683 		id->key = k;
684 		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
685 		/* Increment the number of identities. */
686 		tab->nentries++;
687 	} else {
688 		sshkey_free(k);
689 		free(id->comment);
690 	}
691 	id->comment = comment;
692 	id->death = death;
693 	id->confirm = confirm;
694 send:
695 	send_status(e, success);
696 }
697 
698 /* XXX todo: encrypt sensitive data with passphrase */
699 static void
700 process_lock_agent(SocketEntry *e, int lock)
701 {
702 	int r, success = 0, delay;
703 	char *passwd;
704 	u_char passwdhash[LOCK_SIZE];
705 	static u_int fail_count = 0;
706 	size_t pwlen;
707 
708 	if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
709 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
710 	if (pwlen == 0) {
711 		debug("empty password not supported");
712 	} else if (locked && !lock) {
713 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
714 		    passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
715 			fatal("bcrypt_pbkdf");
716 		if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
717 			debug("agent unlocked");
718 			locked = 0;
719 			fail_count = 0;
720 			explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
721 			success = 1;
722 		} else {
723 			/* delay in 0.1s increments up to 10s */
724 			if (fail_count < 100)
725 				fail_count++;
726 			delay = 100000 * fail_count;
727 			debug("unlock failed, delaying %0.1lf seconds",
728 			    (double)delay/1000000);
729 			usleep(delay);
730 		}
731 		explicit_bzero(passwdhash, sizeof(passwdhash));
732 	} else if (!locked && lock) {
733 		debug("agent locked");
734 		locked = 1;
735 		arc4random_buf(lock_salt, sizeof(lock_salt));
736 		if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
737 		    lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
738 			fatal("bcrypt_pbkdf");
739 		success = 1;
740 	}
741 	explicit_bzero(passwd, pwlen);
742 	free(passwd);
743 	send_status(e, success);
744 }
745 
746 static void
747 no_identities(SocketEntry *e, u_int type)
748 {
749 	struct sshbuf *msg;
750 	int r;
751 
752 	if ((msg = sshbuf_new()) == NULL)
753 		fatal("%s: sshbuf_new failed", __func__);
754 	if ((r = sshbuf_put_u8(msg,
755 	    (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
756 	    SSH_AGENT_RSA_IDENTITIES_ANSWER :
757 	    SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
758 	    (r = sshbuf_put_u32(msg, 0)) != 0 ||
759 	    (r = sshbuf_put_stringb(e->output, msg)) != 0)
760 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
761 	sshbuf_free(msg);
762 }
763 
764 #ifdef ENABLE_PKCS11
765 static void
766 process_add_smartcard_key(SocketEntry *e)
767 {
768 	char *provider = NULL, *pin, canonical_provider[PATH_MAX];
769 	int r, i, version, count = 0, success = 0, confirm = 0;
770 	u_int seconds;
771 	time_t death = 0;
772 	u_char type;
773 	struct sshkey **keys = NULL, *k;
774 	Identity *id;
775 	Idtab *tab;
776 
777 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
778 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
779 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
780 
781 	while (sshbuf_len(e->request)) {
782 		if ((r = sshbuf_get_u8(e->request, &type)) != 0)
783 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
784 		switch (type) {
785 		case SSH_AGENT_CONSTRAIN_LIFETIME:
786 			if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
787 				fatal("%s: buffer error: %s",
788 				    __func__, ssh_err(r));
789 			death = monotime() + seconds;
790 			break;
791 		case SSH_AGENT_CONSTRAIN_CONFIRM:
792 			confirm = 1;
793 			break;
794 		default:
795 			error("process_add_smartcard_key: "
796 			    "Unknown constraint type %d", type);
797 			goto send;
798 		}
799 	}
800 	if (realpath(provider, canonical_provider) == NULL) {
801 		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
802 		    provider, strerror(errno));
803 		goto send;
804 	}
805 	if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
806 		verbose("refusing PKCS#11 add of \"%.100s\": "
807 		    "provider not whitelisted", canonical_provider);
808 		goto send;
809 	}
810 	debug("%s: add %.100s", __func__, canonical_provider);
811 	if (lifetime && !death)
812 		death = monotime() + lifetime;
813 
814 	count = pkcs11_add_provider(canonical_provider, pin, &keys);
815 	for (i = 0; i < count; i++) {
816 		k = keys[i];
817 		version = k->type == KEY_RSA1 ? 1 : 2;
818 		tab = idtab_lookup(version);
819 		if (lookup_identity(k, version) == NULL) {
820 			id = xcalloc(1, sizeof(Identity));
821 			id->key = k;
822 			id->provider = xstrdup(canonical_provider);
823 			id->comment = xstrdup(canonical_provider); /* XXX */
824 			id->death = death;
825 			id->confirm = confirm;
826 			TAILQ_INSERT_TAIL(&tab->idlist, id, next);
827 			tab->nentries++;
828 			success = 1;
829 		} else {
830 			sshkey_free(k);
831 		}
832 		keys[i] = NULL;
833 	}
834 send:
835 	free(pin);
836 	free(provider);
837 	free(keys);
838 	send_status(e, success);
839 }
840 
841 static void
842 process_remove_smartcard_key(SocketEntry *e)
843 {
844 	char *provider = NULL, *pin = NULL;
845 	int r, version, success = 0;
846 	Identity *id, *nxt;
847 	Idtab *tab;
848 
849 	if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
850 	    (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
851 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
852 	free(pin);
853 
854 	for (version = 1; version < 3; version++) {
855 		tab = idtab_lookup(version);
856 		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
857 			nxt = TAILQ_NEXT(id, next);
858 			/* Skip file--based keys */
859 			if (id->provider == NULL)
860 				continue;
861 			if (!strcmp(provider, id->provider)) {
862 				TAILQ_REMOVE(&tab->idlist, id, next);
863 				free_identity(id);
864 				tab->nentries--;
865 			}
866 		}
867 	}
868 	if (pkcs11_del_provider(provider) == 0)
869 		success = 1;
870 	else
871 		error("process_remove_smartcard_key:"
872 		    " pkcs11_del_provider failed");
873 	free(provider);
874 	send_status(e, success);
875 }
876 #endif /* ENABLE_PKCS11 */
877 
878 /* dispatch incoming messages */
879 
880 static void
881 process_message(SocketEntry *e)
882 {
883 	u_int msg_len;
884 	u_char type;
885 	const u_char *cp;
886 	int r;
887 
888 	if (sshbuf_len(e->input) < 5)
889 		return;		/* Incomplete message. */
890 	cp = sshbuf_ptr(e->input);
891 	msg_len = PEEK_U32(cp);
892 	if (msg_len > 256 * 1024) {
893 		close_socket(e);
894 		return;
895 	}
896 	if (sshbuf_len(e->input) < msg_len + 4)
897 		return;
898 
899 	/* move the current input to e->request */
900 	sshbuf_reset(e->request);
901 	if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
902 	    (r = sshbuf_get_u8(e->request, &type)) != 0)
903 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
904 
905 	/* check wheter agent is locked */
906 	if (locked && type != SSH_AGENTC_UNLOCK) {
907 		sshbuf_reset(e->request);
908 		switch (type) {
909 		case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
910 		case SSH2_AGENTC_REQUEST_IDENTITIES:
911 			/* send empty lists */
912 			no_identities(e, type);
913 			break;
914 		default:
915 			/* send a fail message for all other request types */
916 			send_status(e, 0);
917 		}
918 		return;
919 	}
920 
921 	debug("type %d", type);
922 	switch (type) {
923 	case SSH_AGENTC_LOCK:
924 	case SSH_AGENTC_UNLOCK:
925 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
926 		break;
927 #ifdef WITH_SSH1
928 	/* ssh1 */
929 	case SSH_AGENTC_RSA_CHALLENGE:
930 		process_authentication_challenge1(e);
931 		break;
932 	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
933 		process_request_identities(e, 1);
934 		break;
935 	case SSH_AGENTC_ADD_RSA_IDENTITY:
936 	case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
937 		process_add_identity(e, 1);
938 		break;
939 	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
940 		process_remove_identity(e, 1);
941 		break;
942 #endif
943 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
944 		process_remove_all_identities(e, 1); /* safe for !WITH_SSH1 */
945 		break;
946 	/* ssh2 */
947 	case SSH2_AGENTC_SIGN_REQUEST:
948 		process_sign_request2(e);
949 		break;
950 	case SSH2_AGENTC_REQUEST_IDENTITIES:
951 		process_request_identities(e, 2);
952 		break;
953 	case SSH2_AGENTC_ADD_IDENTITY:
954 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
955 		process_add_identity(e, 2);
956 		break;
957 	case SSH2_AGENTC_REMOVE_IDENTITY:
958 		process_remove_identity(e, 2);
959 		break;
960 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
961 		process_remove_all_identities(e, 2);
962 		break;
963 #ifdef ENABLE_PKCS11
964 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
965 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
966 		process_add_smartcard_key(e);
967 		break;
968 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
969 		process_remove_smartcard_key(e);
970 		break;
971 #endif /* ENABLE_PKCS11 */
972 	default:
973 		/* Unknown message.  Respond with failure. */
974 		error("Unknown message %d", type);
975 		sshbuf_reset(e->request);
976 		send_status(e, 0);
977 		break;
978 	}
979 }
980 
981 static void
982 new_socket(sock_type type, int fd)
983 {
984 	u_int i, old_alloc, new_alloc;
985 
986 	if (type == AUTH_CONNECTION) {
987 		debug("xcount %d -> %d", xcount, xcount + 1);
988 		++xcount;
989 	}
990 	set_nonblock(fd);
991 
992 	if (fd > max_fd)
993 		max_fd = fd;
994 
995 	for (i = 0; i < sockets_alloc; i++)
996 		if (sockets[i].type == AUTH_UNUSED) {
997 			sockets[i].fd = fd;
998 			if ((sockets[i].input = sshbuf_new()) == NULL)
999 				fatal("%s: sshbuf_new failed", __func__);
1000 			if ((sockets[i].output = sshbuf_new()) == NULL)
1001 				fatal("%s: sshbuf_new failed", __func__);
1002 			if ((sockets[i].request = sshbuf_new()) == NULL)
1003 				fatal("%s: sshbuf_new failed", __func__);
1004 			sockets[i].type = type;
1005 			return;
1006 		}
1007 	old_alloc = sockets_alloc;
1008 	new_alloc = sockets_alloc + 10;
1009 	sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
1010 	for (i = old_alloc; i < new_alloc; i++)
1011 		sockets[i].type = AUTH_UNUSED;
1012 	sockets_alloc = new_alloc;
1013 	sockets[old_alloc].fd = fd;
1014 	if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
1015 		fatal("%s: sshbuf_new failed", __func__);
1016 	if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
1017 		fatal("%s: sshbuf_new failed", __func__);
1018 	if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
1019 		fatal("%s: sshbuf_new failed", __func__);
1020 	sockets[old_alloc].type = type;
1021 }
1022 
1023 static int
1024 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp,
1025     struct timeval **tvpp)
1026 {
1027 	u_int i, sz;
1028 	int n = 0;
1029 	static struct timeval tv;
1030 	time_t deadline;
1031 
1032 	for (i = 0; i < sockets_alloc; i++) {
1033 		switch (sockets[i].type) {
1034 		case AUTH_SOCKET:
1035 		case AUTH_CONNECTION:
1036 			n = MAXIMUM(n, sockets[i].fd);
1037 			break;
1038 		case AUTH_UNUSED:
1039 			break;
1040 		default:
1041 			fatal("Unknown socket type %d", sockets[i].type);
1042 			break;
1043 		}
1044 	}
1045 
1046 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1047 	if (*fdrp == NULL || sz > *nallocp) {
1048 		free(*fdrp);
1049 		free(*fdwp);
1050 		*fdrp = xmalloc(sz);
1051 		*fdwp = xmalloc(sz);
1052 		*nallocp = sz;
1053 	}
1054 	if (n < *fdl)
1055 		debug("XXX shrink: %d < %d", n, *fdl);
1056 	*fdl = n;
1057 	memset(*fdrp, 0, sz);
1058 	memset(*fdwp, 0, sz);
1059 
1060 	for (i = 0; i < sockets_alloc; i++) {
1061 		switch (sockets[i].type) {
1062 		case AUTH_SOCKET:
1063 		case AUTH_CONNECTION:
1064 			FD_SET(sockets[i].fd, *fdrp);
1065 			if (sshbuf_len(sockets[i].output) > 0)
1066 				FD_SET(sockets[i].fd, *fdwp);
1067 			break;
1068 		default:
1069 			break;
1070 		}
1071 	}
1072 	deadline = reaper();
1073 	if (parent_alive_interval != 0)
1074 		deadline = (deadline == 0) ? parent_alive_interval :
1075 		    MINIMUM(deadline, parent_alive_interval);
1076 	if (deadline == 0) {
1077 		*tvpp = NULL;
1078 	} else {
1079 		tv.tv_sec = deadline;
1080 		tv.tv_usec = 0;
1081 		*tvpp = &tv;
1082 	}
1083 	return (1);
1084 }
1085 
1086 static void
1087 after_select(fd_set *readset, fd_set *writeset)
1088 {
1089 	struct sockaddr_un sunaddr;
1090 	socklen_t slen;
1091 	char buf[1024];
1092 	int len, sock, r;
1093 	u_int i, orig_alloc;
1094 	uid_t euid;
1095 	gid_t egid;
1096 
1097 	for (i = 0, orig_alloc = sockets_alloc; i < orig_alloc; i++)
1098 		switch (sockets[i].type) {
1099 		case AUTH_UNUSED:
1100 			break;
1101 		case AUTH_SOCKET:
1102 			if (FD_ISSET(sockets[i].fd, readset)) {
1103 				slen = sizeof(sunaddr);
1104 				sock = accept(sockets[i].fd,
1105 				    (struct sockaddr *)&sunaddr, &slen);
1106 				if (sock < 0) {
1107 					error("accept from AUTH_SOCKET: %s",
1108 					    strerror(errno));
1109 					break;
1110 				}
1111 				if (getpeereid(sock, &euid, &egid) < 0) {
1112 					error("getpeereid %d failed: %s",
1113 					    sock, strerror(errno));
1114 					close(sock);
1115 					break;
1116 				}
1117 				if ((euid != 0) && (getuid() != euid)) {
1118 					error("uid mismatch: "
1119 					    "peer euid %u != uid %u",
1120 					    (u_int) euid, (u_int) getuid());
1121 					close(sock);
1122 					break;
1123 				}
1124 				new_socket(AUTH_CONNECTION, sock);
1125 			}
1126 			break;
1127 		case AUTH_CONNECTION:
1128 			if (sshbuf_len(sockets[i].output) > 0 &&
1129 			    FD_ISSET(sockets[i].fd, writeset)) {
1130 				len = write(sockets[i].fd,
1131 				    sshbuf_ptr(sockets[i].output),
1132 				    sshbuf_len(sockets[i].output));
1133 				if (len == -1 && (errno == EAGAIN ||
1134 				    errno == EWOULDBLOCK ||
1135 				    errno == EINTR))
1136 					continue;
1137 				if (len <= 0) {
1138 					close_socket(&sockets[i]);
1139 					break;
1140 				}
1141 				if ((r = sshbuf_consume(sockets[i].output,
1142 				    len)) != 0)
1143 					fatal("%s: buffer error: %s",
1144 					    __func__, ssh_err(r));
1145 			}
1146 			if (FD_ISSET(sockets[i].fd, readset)) {
1147 				len = read(sockets[i].fd, buf, sizeof(buf));
1148 				if (len == -1 && (errno == EAGAIN ||
1149 				    errno == EWOULDBLOCK ||
1150 				    errno == EINTR))
1151 					continue;
1152 				if (len <= 0) {
1153 					close_socket(&sockets[i]);
1154 					break;
1155 				}
1156 				if ((r = sshbuf_put(sockets[i].input,
1157 				    buf, len)) != 0)
1158 					fatal("%s: buffer error: %s",
1159 					    __func__, ssh_err(r));
1160 				explicit_bzero(buf, sizeof(buf));
1161 				process_message(&sockets[i]);
1162 			}
1163 			break;
1164 		default:
1165 			fatal("Unknown type %d", sockets[i].type);
1166 		}
1167 }
1168 
1169 static void
1170 cleanup_socket(void)
1171 {
1172 	if (cleanup_pid != 0 && getpid() != cleanup_pid)
1173 		return;
1174 	debug("%s: cleanup", __func__);
1175 	if (socket_name[0])
1176 		unlink(socket_name);
1177 	if (socket_dir[0])
1178 		rmdir(socket_dir);
1179 }
1180 
1181 void
1182 cleanup_exit(int i)
1183 {
1184 	cleanup_socket();
1185 	_exit(i);
1186 }
1187 
1188 /*ARGSUSED*/
1189 static void
1190 cleanup_handler(int sig)
1191 {
1192 	cleanup_socket();
1193 #ifdef ENABLE_PKCS11
1194 	pkcs11_terminate();
1195 #endif
1196 	_exit(2);
1197 }
1198 
1199 static void
1200 check_parent_exists(void)
1201 {
1202 	/*
1203 	 * If our parent has exited then getppid() will return (pid_t)1,
1204 	 * so testing for that should be safe.
1205 	 */
1206 	if (parent_pid != -1 && getppid() != parent_pid) {
1207 		/* printf("Parent has died - Authentication agent exiting.\n"); */
1208 		cleanup_socket();
1209 		_exit(2);
1210 	}
1211 }
1212 
1213 static void
1214 usage(void)
1215 {
1216 	fprintf(stderr,
1217 	    "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1218 	    "                 [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1219 	    "       ssh-agent [-c | -s] -k\n");
1220 	fprintf(stderr, "  -x          Exit when the last client disconnects.\n");
1221 	exit(1);
1222 }
1223 
1224 int
1225 main(int ac, char **av)
1226 {
1227 	int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1228 	int sock, fd, ch, result, saved_errno;
1229 	u_int nalloc;
1230 	char *shell, *format, *pidstr, *agentsocket = NULL;
1231 	fd_set *readsetp = NULL, *writesetp = NULL;
1232 #ifdef HAVE_SETRLIMIT
1233 	struct rlimit rlim;
1234 #endif
1235 	extern int optind;
1236 	extern char *optarg;
1237 	pid_t pid;
1238 	char pidstrbuf[1 + 3 * sizeof pid];
1239 	struct timeval *tvp = NULL;
1240 	size_t len;
1241 	mode_t prev_mask;
1242 
1243 	ssh_malloc_init();	/* must be called before any mallocs */
1244 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1245 	sanitise_stdfd();
1246 
1247 	/* drop */
1248 	setegid(getgid());
1249 	setgid(getgid());
1250 	setuid(geteuid());
1251 
1252 	platform_disable_tracing(0);	/* strict=no */
1253 
1254 #ifdef WITH_OPENSSL
1255 	OpenSSL_add_all_algorithms();
1256 #endif
1257 
1258 	__progname = ssh_get_progname(av[0]);
1259 	seed_rng();
1260 
1261 	while ((ch = getopt(ac, av, "cDdksE:a:P:t:x")) != -1) {
1262 		switch (ch) {
1263 		case 'E':
1264 			fingerprint_hash = ssh_digest_alg_by_name(optarg);
1265 			if (fingerprint_hash == -1)
1266 				fatal("Invalid hash algorithm \"%s\"", optarg);
1267 			break;
1268 		case 'c':
1269 			if (s_flag)
1270 				usage();
1271 			c_flag++;
1272 			break;
1273 		case 'k':
1274 			k_flag++;
1275 			break;
1276 		case 'P':
1277 			if (pkcs11_whitelist != NULL)
1278 				fatal("-P option already specified");
1279 			pkcs11_whitelist = xstrdup(optarg);
1280 			break;
1281 		case 's':
1282 			if (c_flag)
1283 				usage();
1284 			s_flag++;
1285 			break;
1286 		case 'd':
1287 			if (d_flag || D_flag)
1288 				usage();
1289 			d_flag++;
1290 			break;
1291 		case 'D':
1292 			if (d_flag || D_flag)
1293 				usage();
1294 			D_flag++;
1295 			break;
1296 		case 'a':
1297 			agentsocket = optarg;
1298 			break;
1299 		case 't':
1300 			if ((lifetime = convtime(optarg)) == -1) {
1301 				fprintf(stderr, "Invalid lifetime\n");
1302 				usage();
1303 			}
1304 			break;
1305 		case 'x':
1306 			xcount = 0;
1307 			break;
1308 		default:
1309 			usage();
1310 		}
1311 	}
1312 	ac -= optind;
1313 	av += optind;
1314 
1315 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1316 		usage();
1317 
1318 	if (pkcs11_whitelist == NULL)
1319 		pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1320 
1321 	if (ac == 0 && !c_flag && !s_flag) {
1322 		shell = getenv("SHELL");
1323 		if (shell != NULL && (len = strlen(shell)) > 2 &&
1324 		    strncmp(shell + len - 3, "csh", 3) == 0)
1325 			c_flag = 1;
1326 	}
1327 	if (k_flag) {
1328 		const char *errstr = NULL;
1329 
1330 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1331 		if (pidstr == NULL) {
1332 			fprintf(stderr, "%s not set, cannot kill agent\n",
1333 			    SSH_AGENTPID_ENV_NAME);
1334 			exit(1);
1335 		}
1336 		pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1337 		if (errstr) {
1338 			fprintf(stderr,
1339 			    "%s=\"%s\", which is not a good PID: %s\n",
1340 			    SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1341 			exit(1);
1342 		}
1343 		if (kill(pid, SIGTERM) == -1) {
1344 			perror("kill");
1345 			exit(1);
1346 		}
1347 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1348 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
1349 		printf(format, SSH_AGENTPID_ENV_NAME);
1350 		printf("echo Agent pid %ld killed;\n", (long)pid);
1351 		exit(0);
1352 	}
1353 	parent_pid = getpid();
1354 
1355 	if (agentsocket == NULL) {
1356 		/* Create private directory for agent socket */
1357 		mktemp_proto(socket_dir, sizeof(socket_dir));
1358 		if (mkdtemp(socket_dir) == NULL) {
1359 			perror("mkdtemp: private socket dir");
1360 			exit(1);
1361 		}
1362 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1363 		    (long)parent_pid);
1364 	} else {
1365 		/* Try to use specified agent socket */
1366 		socket_dir[0] = '\0';
1367 		strlcpy(socket_name, agentsocket, sizeof socket_name);
1368 	}
1369 
1370 	/*
1371 	 * Create socket early so it will exist before command gets run from
1372 	 * the parent.
1373 	 */
1374 	prev_mask = umask(0177);
1375 	sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1376 	if (sock < 0) {
1377 		/* XXX - unix_listener() calls error() not perror() */
1378 		*socket_name = '\0'; /* Don't unlink any existing file */
1379 		cleanup_exit(1);
1380 	}
1381 	umask(prev_mask);
1382 
1383 	/*
1384 	 * Fork, and have the parent execute the command, if any, or present
1385 	 * the socket data.  The child continues as the authentication agent.
1386 	 */
1387 	if (D_flag || d_flag) {
1388 		log_init(__progname,
1389 		    d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1390 		    SYSLOG_FACILITY_AUTH, 1);
1391 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1392 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1393 		    SSH_AUTHSOCKET_ENV_NAME);
1394 		printf("echo Agent pid %ld;\n", (long)parent_pid);
1395 		fflush(stdout);
1396 		goto skip;
1397 	}
1398 	pid = fork();
1399 	if (pid == -1) {
1400 		perror("fork");
1401 		cleanup_exit(1);
1402 	}
1403 	if (pid != 0) {		/* Parent - execute the given command. */
1404 		close(sock);
1405 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1406 		if (ac == 0) {
1407 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1408 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1409 			    SSH_AUTHSOCKET_ENV_NAME);
1410 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1411 			    SSH_AGENTPID_ENV_NAME);
1412 			printf("echo Agent pid %ld;\n", (long)pid);
1413 			exit(0);
1414 		}
1415 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1416 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1417 			perror("setenv");
1418 			exit(1);
1419 		}
1420 		execvp(av[0], av);
1421 		perror(av[0]);
1422 		exit(1);
1423 	}
1424 	/* child */
1425 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1426 
1427 	if (setsid() == -1) {
1428 		error("setsid: %s", strerror(errno));
1429 		cleanup_exit(1);
1430 	}
1431 
1432 	(void)chdir("/");
1433 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1434 		/* XXX might close listen socket */
1435 		(void)dup2(fd, STDIN_FILENO);
1436 		(void)dup2(fd, STDOUT_FILENO);
1437 		(void)dup2(fd, STDERR_FILENO);
1438 		if (fd > 2)
1439 			close(fd);
1440 	}
1441 
1442 #ifdef HAVE_SETRLIMIT
1443 	/* deny core dumps, since memory contains unencrypted private keys */
1444 	rlim.rlim_cur = rlim.rlim_max = 0;
1445 	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1446 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1447 		cleanup_exit(1);
1448 	}
1449 #endif
1450 
1451 skip:
1452 
1453 	cleanup_pid = getpid();
1454 
1455 #ifdef ENABLE_PKCS11
1456 	pkcs11_init(0);
1457 #endif
1458 	new_socket(AUTH_SOCKET, sock);
1459 	if (ac > 0)
1460 		parent_alive_interval = 10;
1461 	idtab_init();
1462 	signal(SIGPIPE, SIG_IGN);
1463 	signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1464 	signal(SIGHUP, cleanup_handler);
1465 	signal(SIGTERM, cleanup_handler);
1466 	nalloc = 0;
1467 
1468 	if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1469 		fatal("%s: pledge: %s", __progname, strerror(errno));
1470 	platform_pledge_agent();
1471 
1472 	while (1) {
1473 		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
1474 		result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
1475 		saved_errno = errno;
1476 		if (parent_alive_interval != 0)
1477 			check_parent_exists();
1478 		(void) reaper();	/* remove expired keys */
1479 		if (result < 0) {
1480 			if (saved_errno == EINTR)
1481 				continue;
1482 			fatal("select: %s", strerror(saved_errno));
1483 		} else if (result > 0)
1484 			after_select(readsetp, writesetp);
1485 	}
1486 	/* NOTREACHED */
1487 }
1488