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