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