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