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