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