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