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