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