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