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