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