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