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