xref: /openbsd-src/usr.bin/ssh/ssh-agent.c (revision 11efff7f3ac2b3cfeff0c0cddc14294d9b3aca4f)
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * The authentication agent program.
6  *
7  * As far as I am concerned, the code I have written for this software
8  * can be used freely for any purpose.  Any derived versions of this
9  * software must be clearly marked as such, and if the derived work is
10  * incompatible with the protocol description in the RFC file, it must be
11  * called by a name other than "ssh" or "Secure Shell".
12  *
13  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 #include "includes.h"
37 #include <sys/queue.h>
38 RCSID("$OpenBSD: ssh-agent.c,v 1.122 2004/10/29 22:53:56 djm Exp $");
39 
40 #include <openssl/evp.h>
41 #include <openssl/md5.h>
42 
43 #include "ssh.h"
44 #include "rsa.h"
45 #include "buffer.h"
46 #include "bufaux.h"
47 #include "xmalloc.h"
48 #include "getput.h"
49 #include "key.h"
50 #include "authfd.h"
51 #include "compat.h"
52 #include "log.h"
53 #include "misc.h"
54 
55 #ifdef SMARTCARD
56 #include "scard.h"
57 #endif
58 
59 typedef enum {
60 	AUTH_UNUSED,
61 	AUTH_SOCKET,
62 	AUTH_CONNECTION
63 } sock_type;
64 
65 typedef struct {
66 	int fd;
67 	sock_type type;
68 	Buffer input;
69 	Buffer output;
70 	Buffer request;
71 } SocketEntry;
72 
73 u_int sockets_alloc = 0;
74 SocketEntry *sockets = NULL;
75 
76 typedef struct identity {
77 	TAILQ_ENTRY(identity) next;
78 	Key *key;
79 	char *comment;
80 	u_int death;
81 	u_int confirm;
82 } Identity;
83 
84 typedef struct {
85 	int nentries;
86 	TAILQ_HEAD(idqueue, identity) idlist;
87 } Idtab;
88 
89 /* private key table, one per protocol version */
90 Idtab idtable[3];
91 
92 int max_fd = 0;
93 
94 /* pid of shell == parent of agent */
95 pid_t parent_pid = -1;
96 
97 /* pathname and directory for AUTH_SOCKET */
98 char socket_name[1024];
99 char socket_dir[1024];
100 
101 /* locking */
102 int locked = 0;
103 char *lock_passwd = NULL;
104 
105 extern char *__progname;
106 
107 /* Default lifetime (0 == forever) */
108 static int lifetime = 0;
109 
110 static void
111 close_socket(SocketEntry *e)
112 {
113 	close(e->fd);
114 	e->fd = -1;
115 	e->type = AUTH_UNUSED;
116 	buffer_free(&e->input);
117 	buffer_free(&e->output);
118 	buffer_free(&e->request);
119 }
120 
121 static void
122 idtab_init(void)
123 {
124 	int i;
125 
126 	for (i = 0; i <=2; i++) {
127 		TAILQ_INIT(&idtable[i].idlist);
128 		idtable[i].nentries = 0;
129 	}
130 }
131 
132 /* return private key table for requested protocol version */
133 static Idtab *
134 idtab_lookup(int version)
135 {
136 	if (version < 1 || version > 2)
137 		fatal("internal error, bad protocol version %d", version);
138 	return &idtable[version];
139 }
140 
141 static void
142 free_identity(Identity *id)
143 {
144 	key_free(id->key);
145 	xfree(id->comment);
146 	xfree(id);
147 }
148 
149 /* return matching private key for given public key */
150 static Identity *
151 lookup_identity(Key *key, int version)
152 {
153 	Identity *id;
154 
155 	Idtab *tab = idtab_lookup(version);
156 	TAILQ_FOREACH(id, &tab->idlist, next) {
157 		if (key_equal(key, id->key))
158 			return (id);
159 	}
160 	return (NULL);
161 }
162 
163 /* Check confirmation of keysign request */
164 static int
165 confirm_key(Identity *id)
166 {
167 	char *p;
168 	int ret = -1;
169 
170 	p = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
171 	if (ask_permission("Allow use of key %s?\nKey fingerprint %s.",
172 	    id->comment, p))
173 		ret = 0;
174 	xfree(p);
175 
176 	return (ret);
177 }
178 
179 /* send list of supported public keys to 'client' */
180 static void
181 process_request_identities(SocketEntry *e, int version)
182 {
183 	Idtab *tab = idtab_lookup(version);
184 	Identity *id;
185 	Buffer msg;
186 
187 	buffer_init(&msg);
188 	buffer_put_char(&msg, (version == 1) ?
189 	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
190 	buffer_put_int(&msg, tab->nentries);
191 	TAILQ_FOREACH(id, &tab->idlist, next) {
192 		if (id->key->type == KEY_RSA1) {
193 			buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
194 			buffer_put_bignum(&msg, id->key->rsa->e);
195 			buffer_put_bignum(&msg, id->key->rsa->n);
196 		} else {
197 			u_char *blob;
198 			u_int blen;
199 			key_to_blob(id->key, &blob, &blen);
200 			buffer_put_string(&msg, blob, blen);
201 			xfree(blob);
202 		}
203 		buffer_put_cstring(&msg, id->comment);
204 	}
205 	buffer_put_int(&e->output, buffer_len(&msg));
206 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
207 	buffer_free(&msg);
208 }
209 
210 /* ssh1 only */
211 static void
212 process_authentication_challenge1(SocketEntry *e)
213 {
214 	u_char buf[32], mdbuf[16], session_id[16];
215 	u_int response_type;
216 	BIGNUM *challenge;
217 	Identity *id;
218 	int i, len;
219 	Buffer msg;
220 	MD5_CTX md;
221 	Key *key;
222 
223 	buffer_init(&msg);
224 	key = key_new(KEY_RSA1);
225 	if ((challenge = BN_new()) == NULL)
226 		fatal("process_authentication_challenge1: BN_new failed");
227 
228 	(void) buffer_get_int(&e->request);			/* ignored */
229 	buffer_get_bignum(&e->request, key->rsa->e);
230 	buffer_get_bignum(&e->request, key->rsa->n);
231 	buffer_get_bignum(&e->request, challenge);
232 
233 	/* Only protocol 1.1 is supported */
234 	if (buffer_len(&e->request) == 0)
235 		goto failure;
236 	buffer_get(&e->request, session_id, 16);
237 	response_type = buffer_get_int(&e->request);
238 	if (response_type != 1)
239 		goto failure;
240 
241 	id = lookup_identity(key, 1);
242 	if (id != NULL && (!id->confirm || confirm_key(id) == 0)) {
243 		Key *private = id->key;
244 		/* Decrypt the challenge using the private key. */
245 		if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
246 			goto failure;
247 
248 		/* The response is MD5 of decrypted challenge plus session id. */
249 		len = BN_num_bytes(challenge);
250 		if (len <= 0 || len > 32) {
251 			logit("process_authentication_challenge: bad challenge length %d", len);
252 			goto failure;
253 		}
254 		memset(buf, 0, 32);
255 		BN_bn2bin(challenge, buf + 32 - len);
256 		MD5_Init(&md);
257 		MD5_Update(&md, buf, 32);
258 		MD5_Update(&md, session_id, 16);
259 		MD5_Final(mdbuf, &md);
260 
261 		/* Send the response. */
262 		buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
263 		for (i = 0; i < 16; i++)
264 			buffer_put_char(&msg, mdbuf[i]);
265 		goto send;
266 	}
267 
268 failure:
269 	/* Unknown identity or protocol error.  Send failure. */
270 	buffer_put_char(&msg, SSH_AGENT_FAILURE);
271 send:
272 	buffer_put_int(&e->output, buffer_len(&msg));
273 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
274 	key_free(key);
275 	BN_clear_free(challenge);
276 	buffer_free(&msg);
277 }
278 
279 /* ssh2 only */
280 static void
281 process_sign_request2(SocketEntry *e)
282 {
283 	u_char *blob, *data, *signature = NULL;
284 	u_int blen, dlen, slen = 0;
285 	extern int datafellows;
286 	int ok = -1, flags;
287 	Buffer msg;
288 	Key *key;
289 
290 	datafellows = 0;
291 
292 	blob = buffer_get_string(&e->request, &blen);
293 	data = buffer_get_string(&e->request, &dlen);
294 
295 	flags = buffer_get_int(&e->request);
296 	if (flags & SSH_AGENT_OLD_SIGNATURE)
297 		datafellows = SSH_BUG_SIGBLOB;
298 
299 	key = key_from_blob(blob, blen);
300 	if (key != NULL) {
301 		Identity *id = lookup_identity(key, 2);
302 		if (id != NULL && (!id->confirm || confirm_key(id) == 0))
303 			ok = key_sign(id->key, &signature, &slen, data, dlen);
304 	}
305 	key_free(key);
306 	buffer_init(&msg);
307 	if (ok == 0) {
308 		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
309 		buffer_put_string(&msg, signature, slen);
310 	} else {
311 		buffer_put_char(&msg, SSH_AGENT_FAILURE);
312 	}
313 	buffer_put_int(&e->output, buffer_len(&msg));
314 	buffer_append(&e->output, buffer_ptr(&msg),
315 	    buffer_len(&msg));
316 	buffer_free(&msg);
317 	xfree(data);
318 	xfree(blob);
319 	if (signature != NULL)
320 		xfree(signature);
321 }
322 
323 /* shared */
324 static void
325 process_remove_identity(SocketEntry *e, int version)
326 {
327 	u_int blen, bits;
328 	int success = 0;
329 	Key *key = NULL;
330 	u_char *blob;
331 
332 	switch (version) {
333 	case 1:
334 		key = key_new(KEY_RSA1);
335 		bits = buffer_get_int(&e->request);
336 		buffer_get_bignum(&e->request, key->rsa->e);
337 		buffer_get_bignum(&e->request, key->rsa->n);
338 
339 		if (bits != key_size(key))
340 			logit("Warning: identity keysize mismatch: actual %u, announced %u",
341 			    key_size(key), bits);
342 		break;
343 	case 2:
344 		blob = buffer_get_string(&e->request, &blen);
345 		key = key_from_blob(blob, blen);
346 		xfree(blob);
347 		break;
348 	}
349 	if (key != NULL) {
350 		Identity *id = lookup_identity(key, version);
351 		if (id != NULL) {
352 			/*
353 			 * We have this key.  Free the old key.  Since we
354 			 * don\'t want to leave empty slots in the middle of
355 			 * the array, we actually free the key there and move
356 			 * all the entries between the empty slot and the end
357 			 * of the array.
358 			 */
359 			Idtab *tab = idtab_lookup(version);
360 			if (tab->nentries < 1)
361 				fatal("process_remove_identity: "
362 				    "internal error: tab->nentries %d",
363 				    tab->nentries);
364 			TAILQ_REMOVE(&tab->idlist, id, next);
365 			free_identity(id);
366 			tab->nentries--;
367 			success = 1;
368 		}
369 		key_free(key);
370 	}
371 	buffer_put_int(&e->output, 1);
372 	buffer_put_char(&e->output,
373 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
374 }
375 
376 static void
377 process_remove_all_identities(SocketEntry *e, int version)
378 {
379 	Idtab *tab = idtab_lookup(version);
380 	Identity *id;
381 
382 	/* Loop over all identities and clear the keys. */
383 	for (id = TAILQ_FIRST(&tab->idlist); id;
384 	    id = TAILQ_FIRST(&tab->idlist)) {
385 		TAILQ_REMOVE(&tab->idlist, id, next);
386 		free_identity(id);
387 	}
388 
389 	/* Mark that there are no identities. */
390 	tab->nentries = 0;
391 
392 	/* Send success. */
393 	buffer_put_int(&e->output, 1);
394 	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
395 }
396 
397 static void
398 reaper(void)
399 {
400 	u_int now = time(NULL);
401 	Identity *id, *nxt;
402 	int version;
403 	Idtab *tab;
404 
405 	for (version = 1; version < 3; version++) {
406 		tab = idtab_lookup(version);
407 		for (id = TAILQ_FIRST(&tab->idlist); id; id = nxt) {
408 			nxt = TAILQ_NEXT(id, next);
409 			if (id->death != 0 && now >= id->death) {
410 				TAILQ_REMOVE(&tab->idlist, id, next);
411 				free_identity(id);
412 				tab->nentries--;
413 			}
414 		}
415 	}
416 }
417 
418 static void
419 process_add_identity(SocketEntry *e, int version)
420 {
421 	Idtab *tab = idtab_lookup(version);
422 	int type, success = 0, death = 0, confirm = 0;
423 	char *type_name, *comment;
424 	Key *k = NULL;
425 
426 	switch (version) {
427 	case 1:
428 		k = key_new_private(KEY_RSA1);
429 		(void) buffer_get_int(&e->request);		/* ignored */
430 		buffer_get_bignum(&e->request, k->rsa->n);
431 		buffer_get_bignum(&e->request, k->rsa->e);
432 		buffer_get_bignum(&e->request, k->rsa->d);
433 		buffer_get_bignum(&e->request, k->rsa->iqmp);
434 
435 		/* SSH and SSL have p and q swapped */
436 		buffer_get_bignum(&e->request, k->rsa->q);	/* p */
437 		buffer_get_bignum(&e->request, k->rsa->p);	/* q */
438 
439 		/* Generate additional parameters */
440 		rsa_generate_additional_parameters(k->rsa);
441 		break;
442 	case 2:
443 		type_name = buffer_get_string(&e->request, NULL);
444 		type = key_type_from_name(type_name);
445 		xfree(type_name);
446 		switch (type) {
447 		case KEY_DSA:
448 			k = key_new_private(type);
449 			buffer_get_bignum2(&e->request, k->dsa->p);
450 			buffer_get_bignum2(&e->request, k->dsa->q);
451 			buffer_get_bignum2(&e->request, k->dsa->g);
452 			buffer_get_bignum2(&e->request, k->dsa->pub_key);
453 			buffer_get_bignum2(&e->request, k->dsa->priv_key);
454 			break;
455 		case KEY_RSA:
456 			k = key_new_private(type);
457 			buffer_get_bignum2(&e->request, k->rsa->n);
458 			buffer_get_bignum2(&e->request, k->rsa->e);
459 			buffer_get_bignum2(&e->request, k->rsa->d);
460 			buffer_get_bignum2(&e->request, k->rsa->iqmp);
461 			buffer_get_bignum2(&e->request, k->rsa->p);
462 			buffer_get_bignum2(&e->request, k->rsa->q);
463 
464 			/* Generate additional parameters */
465 			rsa_generate_additional_parameters(k->rsa);
466 			break;
467 		default:
468 			buffer_clear(&e->request);
469 			goto send;
470 		}
471 		break;
472 	}
473 	/* enable blinding */
474 	switch (k->type) {
475 	case KEY_RSA:
476 	case KEY_RSA1:
477 		if (RSA_blinding_on(k->rsa, NULL) != 1) {
478 			error("process_add_identity: RSA_blinding_on failed");
479 			key_free(k);
480 			goto send;
481 		}
482 		break;
483 	}
484 	comment = buffer_get_string(&e->request, NULL);
485 	if (k == NULL) {
486 		xfree(comment);
487 		goto send;
488 	}
489 	success = 1;
490 	while (buffer_len(&e->request)) {
491 		switch (buffer_get_char(&e->request)) {
492 		case SSH_AGENT_CONSTRAIN_LIFETIME:
493 			death = time(NULL) + buffer_get_int(&e->request);
494 			break;
495 		case SSH_AGENT_CONSTRAIN_CONFIRM:
496 			confirm = 1;
497 			break;
498 		default:
499 			break;
500 		}
501 	}
502 	if (lifetime && !death)
503 		death = time(NULL) + lifetime;
504 	if (lookup_identity(k, version) == NULL) {
505 		Identity *id = xmalloc(sizeof(Identity));
506 		id->key = k;
507 		id->comment = comment;
508 		id->death = death;
509 		id->confirm = confirm;
510 		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
511 		/* Increment the number of identities. */
512 		tab->nentries++;
513 	} else {
514 		key_free(k);
515 		xfree(comment);
516 	}
517 send:
518 	buffer_put_int(&e->output, 1);
519 	buffer_put_char(&e->output,
520 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
521 }
522 
523 /* XXX todo: encrypt sensitive data with passphrase */
524 static void
525 process_lock_agent(SocketEntry *e, int lock)
526 {
527 	int success = 0;
528 	char *passwd;
529 
530 	passwd = buffer_get_string(&e->request, NULL);
531 	if (locked && !lock && strcmp(passwd, lock_passwd) == 0) {
532 		locked = 0;
533 		memset(lock_passwd, 0, strlen(lock_passwd));
534 		xfree(lock_passwd);
535 		lock_passwd = NULL;
536 		success = 1;
537 	} else if (!locked && lock) {
538 		locked = 1;
539 		lock_passwd = xstrdup(passwd);
540 		success = 1;
541 	}
542 	memset(passwd, 0, strlen(passwd));
543 	xfree(passwd);
544 
545 	buffer_put_int(&e->output, 1);
546 	buffer_put_char(&e->output,
547 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
548 }
549 
550 static void
551 no_identities(SocketEntry *e, u_int type)
552 {
553 	Buffer msg;
554 
555 	buffer_init(&msg);
556 	buffer_put_char(&msg,
557 	    (type == SSH_AGENTC_REQUEST_RSA_IDENTITIES) ?
558 	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
559 	buffer_put_int(&msg, 0);
560 	buffer_put_int(&e->output, buffer_len(&msg));
561 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
562 	buffer_free(&msg);
563 }
564 
565 #ifdef SMARTCARD
566 static void
567 process_add_smartcard_key (SocketEntry *e)
568 {
569 	char *sc_reader_id = NULL, *pin;
570 	int i, version, success = 0, death = 0, confirm = 0;
571 	Key **keys, *k;
572 	Identity *id;
573 	Idtab *tab;
574 
575 	sc_reader_id = buffer_get_string(&e->request, NULL);
576 	pin = buffer_get_string(&e->request, NULL);
577 
578 	while (buffer_len(&e->request)) {
579 		switch (buffer_get_char(&e->request)) {
580 		case SSH_AGENT_CONSTRAIN_LIFETIME:
581 			death = time(NULL) + buffer_get_int(&e->request);
582 			break;
583 		case SSH_AGENT_CONSTRAIN_CONFIRM:
584 			confirm = 1;
585 			break;
586 		default:
587 			break;
588 		}
589 	}
590 	if (lifetime && !death)
591 		death = time(NULL) + lifetime;
592 
593 	keys = sc_get_keys(sc_reader_id, pin);
594 	xfree(sc_reader_id);
595 	xfree(pin);
596 
597 	if (keys == NULL || keys[0] == NULL) {
598 		error("sc_get_keys failed");
599 		goto send;
600 	}
601 	for (i = 0; keys[i] != NULL; i++) {
602 		k = keys[i];
603 		version = k->type == KEY_RSA1 ? 1 : 2;
604 		tab = idtab_lookup(version);
605 		if (lookup_identity(k, version) == NULL) {
606 			id = xmalloc(sizeof(Identity));
607 			id->key = k;
608 			id->comment = sc_get_key_label(k);
609 			id->death = death;
610 			id->confirm = confirm;
611 			TAILQ_INSERT_TAIL(&tab->idlist, id, next);
612 			tab->nentries++;
613 			success = 1;
614 		} else {
615 			key_free(k);
616 		}
617 		keys[i] = NULL;
618 	}
619 	xfree(keys);
620 send:
621 	buffer_put_int(&e->output, 1);
622 	buffer_put_char(&e->output,
623 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
624 }
625 
626 static void
627 process_remove_smartcard_key(SocketEntry *e)
628 {
629 	char *sc_reader_id = NULL, *pin;
630 	int i, version, success = 0;
631 	Key **keys, *k = NULL;
632 	Identity *id;
633 	Idtab *tab;
634 
635 	sc_reader_id = buffer_get_string(&e->request, NULL);
636 	pin = buffer_get_string(&e->request, NULL);
637 	keys = sc_get_keys(sc_reader_id, pin);
638 	xfree(sc_reader_id);
639 	xfree(pin);
640 
641 	if (keys == NULL || keys[0] == NULL) {
642 		error("sc_get_keys failed");
643 		goto send;
644 	}
645 	for (i = 0; keys[i] != NULL; i++) {
646 		k = keys[i];
647 		version = k->type == KEY_RSA1 ? 1 : 2;
648 		if ((id = lookup_identity(k, version)) != NULL) {
649 			tab = idtab_lookup(version);
650 			TAILQ_REMOVE(&tab->idlist, id, next);
651 			tab->nentries--;
652 			free_identity(id);
653 			success = 1;
654 		}
655 		key_free(k);
656 		keys[i] = NULL;
657 	}
658 	xfree(keys);
659 send:
660 	buffer_put_int(&e->output, 1);
661 	buffer_put_char(&e->output,
662 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
663 }
664 #endif /* SMARTCARD */
665 
666 /* dispatch incoming messages */
667 
668 static void
669 process_message(SocketEntry *e)
670 {
671 	u_int msg_len, type;
672 	u_char *cp;
673 
674 	/* kill dead keys */
675 	reaper();
676 
677 	if (buffer_len(&e->input) < 5)
678 		return;		/* Incomplete message. */
679 	cp = buffer_ptr(&e->input);
680 	msg_len = GET_32BIT(cp);
681 	if (msg_len > 256 * 1024) {
682 		close_socket(e);
683 		return;
684 	}
685 	if (buffer_len(&e->input) < msg_len + 4)
686 		return;
687 
688 	/* move the current input to e->request */
689 	buffer_consume(&e->input, 4);
690 	buffer_clear(&e->request);
691 	buffer_append(&e->request, buffer_ptr(&e->input), msg_len);
692 	buffer_consume(&e->input, msg_len);
693 	type = buffer_get_char(&e->request);
694 
695 	/* check wheter agent is locked */
696 	if (locked && type != SSH_AGENTC_UNLOCK) {
697 		buffer_clear(&e->request);
698 		switch (type) {
699 		case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
700 		case SSH2_AGENTC_REQUEST_IDENTITIES:
701 			/* send empty lists */
702 			no_identities(e, type);
703 			break;
704 		default:
705 			/* send a fail message for all other request types */
706 			buffer_put_int(&e->output, 1);
707 			buffer_put_char(&e->output, SSH_AGENT_FAILURE);
708 		}
709 		return;
710 	}
711 
712 	debug("type %d", type);
713 	switch (type) {
714 	case SSH_AGENTC_LOCK:
715 	case SSH_AGENTC_UNLOCK:
716 		process_lock_agent(e, type == SSH_AGENTC_LOCK);
717 		break;
718 	/* ssh1 */
719 	case SSH_AGENTC_RSA_CHALLENGE:
720 		process_authentication_challenge1(e);
721 		break;
722 	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
723 		process_request_identities(e, 1);
724 		break;
725 	case SSH_AGENTC_ADD_RSA_IDENTITY:
726 	case SSH_AGENTC_ADD_RSA_ID_CONSTRAINED:
727 		process_add_identity(e, 1);
728 		break;
729 	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
730 		process_remove_identity(e, 1);
731 		break;
732 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
733 		process_remove_all_identities(e, 1);
734 		break;
735 	/* ssh2 */
736 	case SSH2_AGENTC_SIGN_REQUEST:
737 		process_sign_request2(e);
738 		break;
739 	case SSH2_AGENTC_REQUEST_IDENTITIES:
740 		process_request_identities(e, 2);
741 		break;
742 	case SSH2_AGENTC_ADD_IDENTITY:
743 	case SSH2_AGENTC_ADD_ID_CONSTRAINED:
744 		process_add_identity(e, 2);
745 		break;
746 	case SSH2_AGENTC_REMOVE_IDENTITY:
747 		process_remove_identity(e, 2);
748 		break;
749 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
750 		process_remove_all_identities(e, 2);
751 		break;
752 #ifdef SMARTCARD
753 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
754 	case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
755 		process_add_smartcard_key(e);
756 		break;
757 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
758 		process_remove_smartcard_key(e);
759 		break;
760 #endif /* SMARTCARD */
761 	default:
762 		/* Unknown message.  Respond with failure. */
763 		error("Unknown message %d", type);
764 		buffer_clear(&e->request);
765 		buffer_put_int(&e->output, 1);
766 		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
767 		break;
768 	}
769 }
770 
771 static void
772 new_socket(sock_type type, int fd)
773 {
774 	u_int i, old_alloc, new_alloc;
775 
776 	set_nonblock(fd);
777 
778 	if (fd > max_fd)
779 		max_fd = fd;
780 
781 	for (i = 0; i < sockets_alloc; i++)
782 		if (sockets[i].type == AUTH_UNUSED) {
783 			sockets[i].fd = fd;
784 			buffer_init(&sockets[i].input);
785 			buffer_init(&sockets[i].output);
786 			buffer_init(&sockets[i].request);
787 			sockets[i].type = type;
788 			return;
789 		}
790 	old_alloc = sockets_alloc;
791 	new_alloc = sockets_alloc + 10;
792 	if (sockets)
793 		sockets = xrealloc(sockets, new_alloc * sizeof(sockets[0]));
794 	else
795 		sockets = xmalloc(new_alloc * sizeof(sockets[0]));
796 	for (i = old_alloc; i < new_alloc; i++)
797 		sockets[i].type = AUTH_UNUSED;
798 	sockets_alloc = new_alloc;
799 	sockets[old_alloc].fd = fd;
800 	buffer_init(&sockets[old_alloc].input);
801 	buffer_init(&sockets[old_alloc].output);
802 	buffer_init(&sockets[old_alloc].request);
803 	sockets[old_alloc].type = type;
804 }
805 
806 static int
807 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, u_int *nallocp)
808 {
809 	u_int i, sz;
810 	int n = 0;
811 
812 	for (i = 0; i < sockets_alloc; i++) {
813 		switch (sockets[i].type) {
814 		case AUTH_SOCKET:
815 		case AUTH_CONNECTION:
816 			n = MAX(n, sockets[i].fd);
817 			break;
818 		case AUTH_UNUSED:
819 			break;
820 		default:
821 			fatal("Unknown socket type %d", sockets[i].type);
822 			break;
823 		}
824 	}
825 
826 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
827 	if (*fdrp == NULL || sz > *nallocp) {
828 		if (*fdrp)
829 			xfree(*fdrp);
830 		if (*fdwp)
831 			xfree(*fdwp);
832 		*fdrp = xmalloc(sz);
833 		*fdwp = xmalloc(sz);
834 		*nallocp = sz;
835 	}
836 	if (n < *fdl)
837 		debug("XXX shrink: %d < %d", n, *fdl);
838 	*fdl = n;
839 	memset(*fdrp, 0, sz);
840 	memset(*fdwp, 0, sz);
841 
842 	for (i = 0; i < sockets_alloc; i++) {
843 		switch (sockets[i].type) {
844 		case AUTH_SOCKET:
845 		case AUTH_CONNECTION:
846 			FD_SET(sockets[i].fd, *fdrp);
847 			if (buffer_len(&sockets[i].output) > 0)
848 				FD_SET(sockets[i].fd, *fdwp);
849 			break;
850 		default:
851 			break;
852 		}
853 	}
854 	return (1);
855 }
856 
857 static void
858 after_select(fd_set *readset, fd_set *writeset)
859 {
860 	struct sockaddr_un sunaddr;
861 	socklen_t slen;
862 	char buf[1024];
863 	int len, sock;
864 	u_int i;
865 	uid_t euid;
866 	gid_t egid;
867 
868 	for (i = 0; i < sockets_alloc; i++)
869 		switch (sockets[i].type) {
870 		case AUTH_UNUSED:
871 			break;
872 		case AUTH_SOCKET:
873 			if (FD_ISSET(sockets[i].fd, readset)) {
874 				slen = sizeof(sunaddr);
875 				sock = accept(sockets[i].fd,
876 				    (struct sockaddr *) &sunaddr, &slen);
877 				if (sock < 0) {
878 					error("accept from AUTH_SOCKET: %s",
879 					    strerror(errno));
880 					break;
881 				}
882 				if (getpeereid(sock, &euid, &egid) < 0) {
883 					error("getpeereid %d failed: %s",
884 					    sock, strerror(errno));
885 					close(sock);
886 					break;
887 				}
888 				if ((euid != 0) && (getuid() != euid)) {
889 					error("uid mismatch: "
890 					    "peer euid %u != uid %u",
891 					    (u_int) euid, (u_int) getuid());
892 					close(sock);
893 					break;
894 				}
895 				new_socket(AUTH_CONNECTION, sock);
896 			}
897 			break;
898 		case AUTH_CONNECTION:
899 			if (buffer_len(&sockets[i].output) > 0 &&
900 			    FD_ISSET(sockets[i].fd, writeset)) {
901 				do {
902 					len = write(sockets[i].fd,
903 					    buffer_ptr(&sockets[i].output),
904 					    buffer_len(&sockets[i].output));
905 					if (len == -1 && (errno == EAGAIN ||
906 					    errno == EINTR))
907 						continue;
908 					break;
909 				} while (1);
910 				if (len <= 0) {
911 					close_socket(&sockets[i]);
912 					break;
913 				}
914 				buffer_consume(&sockets[i].output, len);
915 			}
916 			if (FD_ISSET(sockets[i].fd, readset)) {
917 				do {
918 					len = read(sockets[i].fd, buf, sizeof(buf));
919 					if (len == -1 && (errno == EAGAIN ||
920 					    errno == EINTR))
921 						continue;
922 					break;
923 				} while (1);
924 				if (len <= 0) {
925 					close_socket(&sockets[i]);
926 					break;
927 				}
928 				buffer_append(&sockets[i].input, buf, len);
929 				process_message(&sockets[i]);
930 			}
931 			break;
932 		default:
933 			fatal("Unknown type %d", sockets[i].type);
934 		}
935 }
936 
937 static void
938 cleanup_socket(void)
939 {
940 	if (socket_name[0])
941 		unlink(socket_name);
942 	if (socket_dir[0])
943 		rmdir(socket_dir);
944 }
945 
946 void
947 cleanup_exit(int i)
948 {
949 	cleanup_socket();
950 	_exit(i);
951 }
952 
953 static void
954 cleanup_handler(int sig)
955 {
956 	cleanup_socket();
957 	_exit(2);
958 }
959 
960 static void
961 check_parent_exists(int sig)
962 {
963 	int save_errno = errno;
964 
965 	if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
966 		/* printf("Parent has died - Authentication agent exiting.\n"); */
967 		cleanup_handler(sig); /* safe */
968 	}
969 	signal(SIGALRM, check_parent_exists);
970 	alarm(10);
971 	errno = save_errno;
972 }
973 
974 static void
975 usage(void)
976 {
977 	fprintf(stderr, "Usage: %s [options] [command [args ...]]\n",
978 	    __progname);
979 	fprintf(stderr, "Options:\n");
980 	fprintf(stderr, "  -c          Generate C-shell commands on stdout.\n");
981 	fprintf(stderr, "  -s          Generate Bourne shell commands on stdout.\n");
982 	fprintf(stderr, "  -k          Kill the current agent.\n");
983 	fprintf(stderr, "  -d          Debug mode.\n");
984 	fprintf(stderr, "  -a socket   Bind agent socket to given name.\n");
985 	fprintf(stderr, "  -t life     Default identity lifetime (seconds).\n");
986 	exit(1);
987 }
988 
989 int
990 main(int ac, char **av)
991 {
992 	int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
993 	int sock, fd,  ch;
994 	u_int nalloc;
995 	char *shell, *format, *pidstr, *agentsocket = NULL;
996 	fd_set *readsetp = NULL, *writesetp = NULL;
997 	struct sockaddr_un sunaddr;
998 	struct rlimit rlim;
999 	extern int optind;
1000 	extern char *optarg;
1001 	pid_t pid;
1002 	char pidstrbuf[1 + 3 * sizeof pid];
1003 
1004 	/* drop */
1005 	setegid(getgid());
1006 	setgid(getgid());
1007 
1008 	SSLeay_add_all_algorithms();
1009 
1010 	while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
1011 		switch (ch) {
1012 		case 'c':
1013 			if (s_flag)
1014 				usage();
1015 			c_flag++;
1016 			break;
1017 		case 'k':
1018 			k_flag++;
1019 			break;
1020 		case 's':
1021 			if (c_flag)
1022 				usage();
1023 			s_flag++;
1024 			break;
1025 		case 'd':
1026 			if (d_flag)
1027 				usage();
1028 			d_flag++;
1029 			break;
1030 		case 'a':
1031 			agentsocket = optarg;
1032 			break;
1033 		case 't':
1034 			if ((lifetime = convtime(optarg)) == -1) {
1035 				fprintf(stderr, "Invalid lifetime\n");
1036 				usage();
1037 			}
1038 			break;
1039 		default:
1040 			usage();
1041 		}
1042 	}
1043 	ac -= optind;
1044 	av += optind;
1045 
1046 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
1047 		usage();
1048 
1049 	if (ac == 0 && !c_flag && !s_flag) {
1050 		shell = getenv("SHELL");
1051 		if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
1052 			c_flag = 1;
1053 	}
1054 	if (k_flag) {
1055 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1056 		if (pidstr == NULL) {
1057 			fprintf(stderr, "%s not set, cannot kill agent\n",
1058 			    SSH_AGENTPID_ENV_NAME);
1059 			exit(1);
1060 		}
1061 		pid = atoi(pidstr);
1062 		if (pid < 1) {
1063 			fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
1064 			    SSH_AGENTPID_ENV_NAME, pidstr);
1065 			exit(1);
1066 		}
1067 		if (kill(pid, SIGTERM) == -1) {
1068 			perror("kill");
1069 			exit(1);
1070 		}
1071 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1072 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
1073 		printf(format, SSH_AGENTPID_ENV_NAME);
1074 		printf("echo Agent pid %ld killed;\n", (long)pid);
1075 		exit(0);
1076 	}
1077 	parent_pid = getpid();
1078 
1079 	if (agentsocket == NULL) {
1080 		/* Create private directory for agent socket */
1081 		strlcpy(socket_dir, "/tmp/ssh-XXXXXXXXXX", sizeof socket_dir);
1082 		if (mkdtemp(socket_dir) == NULL) {
1083 			perror("mkdtemp: private socket dir");
1084 			exit(1);
1085 		}
1086 		snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1087 		    (long)parent_pid);
1088 	} else {
1089 		/* Try to use specified agent socket */
1090 		socket_dir[0] = '\0';
1091 		strlcpy(socket_name, agentsocket, sizeof socket_name);
1092 	}
1093 
1094 	/*
1095 	 * Create socket early so it will exist before command gets run from
1096 	 * the parent.
1097 	 */
1098 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
1099 	if (sock < 0) {
1100 		perror("socket");
1101 		*socket_name = '\0'; /* Don't unlink any existing file */
1102 		cleanup_exit(1);
1103 	}
1104 	memset(&sunaddr, 0, sizeof(sunaddr));
1105 	sunaddr.sun_family = AF_UNIX;
1106 	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
1107 	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) {
1108 		perror("bind");
1109 		*socket_name = '\0'; /* Don't unlink any existing file */
1110 		cleanup_exit(1);
1111 	}
1112 	if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
1113 		perror("listen");
1114 		cleanup_exit(1);
1115 	}
1116 
1117 	/*
1118 	 * Fork, and have the parent execute the command, if any, or present
1119 	 * the socket data.  The child continues as the authentication agent.
1120 	 */
1121 	if (d_flag) {
1122 		log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
1123 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1124 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1125 		    SSH_AUTHSOCKET_ENV_NAME);
1126 		printf("echo Agent pid %ld;\n", (long)parent_pid);
1127 		goto skip;
1128 	}
1129 	pid = fork();
1130 	if (pid == -1) {
1131 		perror("fork");
1132 		cleanup_exit(1);
1133 	}
1134 	if (pid != 0) {		/* Parent - execute the given command. */
1135 		close(sock);
1136 		snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1137 		if (ac == 0) {
1138 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1139 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1140 			    SSH_AUTHSOCKET_ENV_NAME);
1141 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1142 			    SSH_AGENTPID_ENV_NAME);
1143 			printf("echo Agent pid %ld;\n", (long)pid);
1144 			exit(0);
1145 		}
1146 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1147 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1148 			perror("setenv");
1149 			exit(1);
1150 		}
1151 		execvp(av[0], av);
1152 		perror(av[0]);
1153 		exit(1);
1154 	}
1155 	/* child */
1156 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1157 
1158 	if (setsid() == -1) {
1159 		error("setsid: %s", strerror(errno));
1160 		cleanup_exit(1);
1161 	}
1162 
1163 	(void)chdir("/");
1164 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1165 		/* XXX might close listen socket */
1166 		(void)dup2(fd, STDIN_FILENO);
1167 		(void)dup2(fd, STDOUT_FILENO);
1168 		(void)dup2(fd, STDERR_FILENO);
1169 		if (fd > 2)
1170 			close(fd);
1171 	}
1172 
1173 	/* deny core dumps, since memory contains unencrypted private keys */
1174 	rlim.rlim_cur = rlim.rlim_max = 0;
1175 	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1176 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1177 		cleanup_exit(1);
1178 	}
1179 
1180 skip:
1181 	new_socket(AUTH_SOCKET, sock);
1182 	if (ac > 0) {
1183 		signal(SIGALRM, check_parent_exists);
1184 		alarm(10);
1185 	}
1186 	idtab_init();
1187 	if (!d_flag)
1188 		signal(SIGINT, SIG_IGN);
1189 	signal(SIGPIPE, SIG_IGN);
1190 	signal(SIGHUP, cleanup_handler);
1191 	signal(SIGTERM, cleanup_handler);
1192 	nalloc = 0;
1193 
1194 	while (1) {
1195 		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
1196 		if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
1197 			if (errno == EINTR)
1198 				continue;
1199 			fatal("select: %s", strerror(errno));
1200 		}
1201 		after_select(readsetp, writesetp);
1202 	}
1203 	/* NOTREACHED */
1204 }
1205