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