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