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