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