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