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