xref: /freebsd/crypto/openssh/ssh-agent.c (revision ee2ea5ceafed78a5bd9810beb9e3ca927180c226)
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.82 2002/03/04 17:27:39 stevesk 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 
55 #ifdef SMARTCARD
56 #include <openssl/engine.h>
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 } 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 } Identity;
81 
82 typedef struct {
83 	int nentries;
84 	TAILQ_HEAD(idqueue, identity) idlist;
85 } Idtab;
86 
87 /* private key table, one per protocol version */
88 Idtab idtable[3];
89 
90 int max_fd = 0;
91 
92 /* pid of shell == parent of agent */
93 pid_t parent_pid = -1;
94 
95 /* pathname and directory for AUTH_SOCKET */
96 char socket_name[1024];
97 char socket_dir[1024];
98 
99 extern char *__progname;
100 
101 static void
102 idtab_init(void)
103 {
104 	int i;
105 	for (i = 0; i <=2; i++) {
106 		TAILQ_INIT(&idtable[i].idlist);
107 		idtable[i].nentries = 0;
108 	}
109 }
110 
111 /* return private key table for requested protocol version */
112 static Idtab *
113 idtab_lookup(int version)
114 {
115 	if (version < 1 || version > 2)
116 		fatal("internal error, bad protocol version %d", version);
117 	return &idtable[version];
118 }
119 
120 /* return matching private key for given public key */
121 static Identity *
122 lookup_identity(Key *key, int version)
123 {
124 	Identity *id;
125 
126 	Idtab *tab = idtab_lookup(version);
127 	TAILQ_FOREACH(id, &tab->idlist, next) {
128 		if (key_equal(key, id->key))
129 			return (id);
130 	}
131 	return (NULL);
132 }
133 
134 static void
135 free_identity(Identity *id)
136 {
137 	key_free(id->key);
138 	xfree(id->comment);
139 	xfree(id);
140 }
141 
142 /* send list of supported public keys to 'client' */
143 static void
144 process_request_identities(SocketEntry *e, int version)
145 {
146 	Idtab *tab = idtab_lookup(version);
147 	Buffer msg;
148 	Identity *id;
149 
150 	buffer_init(&msg);
151 	buffer_put_char(&msg, (version == 1) ?
152 	    SSH_AGENT_RSA_IDENTITIES_ANSWER : SSH2_AGENT_IDENTITIES_ANSWER);
153 	buffer_put_int(&msg, tab->nentries);
154 	TAILQ_FOREACH(id, &tab->idlist, next) {
155 		if (id->key->type == KEY_RSA1) {
156 			buffer_put_int(&msg, BN_num_bits(id->key->rsa->n));
157 			buffer_put_bignum(&msg, id->key->rsa->e);
158 			buffer_put_bignum(&msg, id->key->rsa->n);
159 		} else {
160 			u_char *blob;
161 			u_int blen;
162 			key_to_blob(id->key, &blob, &blen);
163 			buffer_put_string(&msg, blob, blen);
164 			xfree(blob);
165 		}
166 		buffer_put_cstring(&msg, id->comment);
167 	}
168 	buffer_put_int(&e->output, buffer_len(&msg));
169 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
170 	buffer_free(&msg);
171 }
172 
173 /* ssh1 only */
174 static void
175 process_authentication_challenge1(SocketEntry *e)
176 {
177 	Identity *id;
178 	Key *key;
179 	BIGNUM *challenge;
180 	int i, len;
181 	Buffer msg;
182 	MD5_CTX md;
183 	u_char buf[32], mdbuf[16], session_id[16];
184 	u_int response_type;
185 
186 	buffer_init(&msg);
187 	key = key_new(KEY_RSA1);
188 	if ((challenge = BN_new()) == NULL)
189 		fatal("process_authentication_challenge1: BN_new failed");
190 
191 	buffer_get_int(&e->input);				/* ignored */
192 	buffer_get_bignum(&e->input, key->rsa->e);
193 	buffer_get_bignum(&e->input, key->rsa->n);
194 	buffer_get_bignum(&e->input, challenge);
195 
196 	/* Only protocol 1.1 is supported */
197 	if (buffer_len(&e->input) == 0)
198 		goto failure;
199 	buffer_get(&e->input, session_id, 16);
200 	response_type = buffer_get_int(&e->input);
201 	if (response_type != 1)
202 		goto failure;
203 
204 	id = lookup_identity(key, 1);
205 	if (id != NULL) {
206 		Key *private = id->key;
207 		/* Decrypt the challenge using the private key. */
208 		if (rsa_private_decrypt(challenge, challenge, private->rsa) <= 0)
209 			goto failure;
210 
211 		/* The response is MD5 of decrypted challenge plus session id. */
212 		len = BN_num_bytes(challenge);
213 		if (len <= 0 || len > 32) {
214 			log("process_authentication_challenge: bad challenge length %d", len);
215 			goto failure;
216 		}
217 		memset(buf, 0, 32);
218 		BN_bn2bin(challenge, buf + 32 - len);
219 		MD5_Init(&md);
220 		MD5_Update(&md, buf, 32);
221 		MD5_Update(&md, session_id, 16);
222 		MD5_Final(mdbuf, &md);
223 
224 		/* Send the response. */
225 		buffer_put_char(&msg, SSH_AGENT_RSA_RESPONSE);
226 		for (i = 0; i < 16; i++)
227 			buffer_put_char(&msg, mdbuf[i]);
228 		goto send;
229 	}
230 
231 failure:
232 	/* Unknown identity or protocol error.  Send failure. */
233 	buffer_put_char(&msg, SSH_AGENT_FAILURE);
234 send:
235 	buffer_put_int(&e->output, buffer_len(&msg));
236 	buffer_append(&e->output, buffer_ptr(&msg), buffer_len(&msg));
237 	key_free(key);
238 	BN_clear_free(challenge);
239 	buffer_free(&msg);
240 }
241 
242 /* ssh2 only */
243 static void
244 process_sign_request2(SocketEntry *e)
245 {
246 	extern int datafellows;
247 	Key *key;
248 	u_char *blob, *data, *signature = NULL;
249 	u_int blen, dlen, slen = 0;
250 	int flags;
251 	Buffer msg;
252 	int ok = -1;
253 
254 	datafellows = 0;
255 
256 	blob = buffer_get_string(&e->input, &blen);
257 	data = buffer_get_string(&e->input, &dlen);
258 
259 	flags = buffer_get_int(&e->input);
260 	if (flags & SSH_AGENT_OLD_SIGNATURE)
261 		datafellows = SSH_BUG_SIGBLOB;
262 
263 	key = key_from_blob(blob, blen);
264 	if (key != NULL) {
265 		Identity *id = lookup_identity(key, 2);
266 		if (id != NULL)
267 			ok = key_sign(id->key, &signature, &slen, data, dlen);
268 	}
269 	key_free(key);
270 	buffer_init(&msg);
271 	if (ok == 0) {
272 		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
273 		buffer_put_string(&msg, signature, slen);
274 	} else {
275 		buffer_put_char(&msg, SSH_AGENT_FAILURE);
276 	}
277 	buffer_put_int(&e->output, buffer_len(&msg));
278 	buffer_append(&e->output, buffer_ptr(&msg),
279 	    buffer_len(&msg));
280 	buffer_free(&msg);
281 	xfree(data);
282 	xfree(blob);
283 	if (signature != NULL)
284 		xfree(signature);
285 }
286 
287 /* shared */
288 static void
289 process_remove_identity(SocketEntry *e, int version)
290 {
291 	Key *key = NULL;
292 	u_char *blob;
293 	u_int blen;
294 	u_int bits;
295 	int success = 0;
296 
297 	switch (version) {
298 	case 1:
299 		key = key_new(KEY_RSA1);
300 		bits = buffer_get_int(&e->input);
301 		buffer_get_bignum(&e->input, key->rsa->e);
302 		buffer_get_bignum(&e->input, key->rsa->n);
303 
304 		if (bits != key_size(key))
305 			log("Warning: identity keysize mismatch: actual %d, announced %d",
306 			    key_size(key), bits);
307 		break;
308 	case 2:
309 		blob = buffer_get_string(&e->input, &blen);
310 		key = key_from_blob(blob, blen);
311 		xfree(blob);
312 		break;
313 	}
314 	if (key != NULL) {
315 		Identity *id = lookup_identity(key, version);
316 		if (id != NULL) {
317 			/*
318 			 * We have this key.  Free the old key.  Since we
319 			 * don\'t want to leave empty slots in the middle of
320 			 * the array, we actually free the key there and move
321 			 * all the entries between the empty slot and the end
322 			 * of the array.
323 			 */
324 			Idtab *tab = idtab_lookup(version);
325 			if (tab->nentries < 1)
326 				fatal("process_remove_identity: "
327 				    "internal error: tab->nentries %d",
328 				    tab->nentries);
329 			TAILQ_REMOVE(&tab->idlist, id, next);
330 			free_identity(id);
331 			tab->nentries--;
332 			success = 1;
333 		}
334 		key_free(key);
335 	}
336 	buffer_put_int(&e->output, 1);
337 	buffer_put_char(&e->output,
338 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
339 }
340 
341 static void
342 process_remove_all_identities(SocketEntry *e, int version)
343 {
344 	Idtab *tab = idtab_lookup(version);
345 	Identity *id;
346 
347 	/* Loop over all identities and clear the keys. */
348 	for (id = TAILQ_FIRST(&tab->idlist); id;
349 	    id = TAILQ_FIRST(&tab->idlist)) {
350 		TAILQ_REMOVE(&tab->idlist, id, next);
351 		free_identity(id);
352 	}
353 
354 	/* Mark that there are no identities. */
355 	tab->nentries = 0;
356 
357 	/* Send success. */
358 	buffer_put_int(&e->output, 1);
359 	buffer_put_char(&e->output, SSH_AGENT_SUCCESS);
360 	return;
361 }
362 
363 static void
364 process_add_identity(SocketEntry *e, int version)
365 {
366 	Key *k = NULL;
367 	char *type_name;
368 	char *comment;
369 	int type, success = 0;
370 	Idtab *tab = idtab_lookup(version);
371 
372 	switch (version) {
373 	case 1:
374 		k = key_new_private(KEY_RSA1);
375 		buffer_get_int(&e->input);			/* ignored */
376 		buffer_get_bignum(&e->input, k->rsa->n);
377 		buffer_get_bignum(&e->input, k->rsa->e);
378 		buffer_get_bignum(&e->input, k->rsa->d);
379 		buffer_get_bignum(&e->input, k->rsa->iqmp);
380 
381 		/* SSH and SSL have p and q swapped */
382 		buffer_get_bignum(&e->input, k->rsa->q);	/* p */
383 		buffer_get_bignum(&e->input, k->rsa->p);	/* q */
384 
385 		/* Generate additional parameters */
386 		rsa_generate_additional_parameters(k->rsa);
387 		break;
388 	case 2:
389 		type_name = buffer_get_string(&e->input, NULL);
390 		type = key_type_from_name(type_name);
391 		xfree(type_name);
392 		switch (type) {
393 		case KEY_DSA:
394 			k = key_new_private(type);
395 			buffer_get_bignum2(&e->input, k->dsa->p);
396 			buffer_get_bignum2(&e->input, k->dsa->q);
397 			buffer_get_bignum2(&e->input, k->dsa->g);
398 			buffer_get_bignum2(&e->input, k->dsa->pub_key);
399 			buffer_get_bignum2(&e->input, k->dsa->priv_key);
400 			break;
401 		case KEY_RSA:
402 			k = key_new_private(type);
403 			buffer_get_bignum2(&e->input, k->rsa->n);
404 			buffer_get_bignum2(&e->input, k->rsa->e);
405 			buffer_get_bignum2(&e->input, k->rsa->d);
406 			buffer_get_bignum2(&e->input, k->rsa->iqmp);
407 			buffer_get_bignum2(&e->input, k->rsa->p);
408 			buffer_get_bignum2(&e->input, k->rsa->q);
409 
410 			/* Generate additional parameters */
411 			rsa_generate_additional_parameters(k->rsa);
412 			break;
413 		default:
414 			buffer_clear(&e->input);
415 			goto send;
416 		}
417 		break;
418 	}
419 	comment = buffer_get_string(&e->input, NULL);
420 	if (k == NULL) {
421 		xfree(comment);
422 		goto send;
423 	}
424 	success = 1;
425 	if (lookup_identity(k, version) == NULL) {
426 		Identity *id = xmalloc(sizeof(Identity));
427 		id->key = k;
428 		id->comment = comment;
429 		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
430 		/* Increment the number of identities. */
431 		tab->nentries++;
432 	} else {
433 		key_free(k);
434 		xfree(comment);
435 	}
436 send:
437 	buffer_put_int(&e->output, 1);
438 	buffer_put_char(&e->output,
439 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
440 }
441 
442 
443 #ifdef SMARTCARD
444 static void
445 process_add_smartcard_key (SocketEntry *e)
446 {
447 	Idtab *tab;
448 	Key *n = NULL, *k = NULL;
449 	char *sc_reader_id = NULL;
450 	int success = 0;
451 
452 	sc_reader_id = buffer_get_string(&e->input, NULL);
453 	k = sc_get_key(sc_reader_id);
454 	xfree(sc_reader_id);
455 
456 	if (k == NULL) {
457 		error("sc_get_pubkey failed");
458 		goto send;
459 	}
460 	success = 1;
461 
462 	tab = idtab_lookup(1);
463 	k->type = KEY_RSA1;
464 	if (lookup_identity(k, 1) == NULL) {
465 		Identity *id = xmalloc(sizeof(Identity));
466 		n = key_new(KEY_RSA1);
467 		BN_copy(n->rsa->n, k->rsa->n);
468 		BN_copy(n->rsa->e, k->rsa->e);
469 		RSA_set_method(n->rsa, sc_get_engine());
470 		id->key = n;
471 		id->comment = xstrdup("rsa1 smartcard");
472 		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
473 		tab->nentries++;
474 	}
475 	k->type = KEY_RSA;
476 	tab = idtab_lookup(2);
477 	if (lookup_identity(k, 2) == NULL) {
478 		Identity *id = xmalloc(sizeof(Identity));
479 		n = key_new(KEY_RSA);
480 		BN_copy(n->rsa->n, k->rsa->n);
481 		BN_copy(n->rsa->e, k->rsa->e);
482 		RSA_set_method(n->rsa, sc_get_engine());
483 		id->key = n;
484 		id->comment = xstrdup("rsa smartcard");
485 		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
486 		tab->nentries++;
487 	}
488 	key_free(k);
489 send:
490 	buffer_put_int(&e->output, 1);
491 	buffer_put_char(&e->output,
492 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
493 }
494 
495 static void
496 process_remove_smartcard_key(SocketEntry *e)
497 {
498 	Key *k = NULL;
499 	int success = 0;
500 	char *sc_reader_id = NULL;
501 
502 	sc_reader_id = buffer_get_string(&e->input, NULL);
503 	k = sc_get_key(sc_reader_id);
504 	xfree(sc_reader_id);
505 
506 	if (k == NULL) {
507 		error("sc_get_pubkey failed");
508 	} else {
509 		Identity *id;
510 		k->type = KEY_RSA1;
511 		id = lookup_identity(k, 1);
512 		if (id != NULL) {
513 			Idtab *tab = idtab_lookup(1);
514 			TAILQ_REMOVE(&tab->idlist, id, next);
515 			free_identity(id);
516 			tab->nentries--;
517 			success = 1;
518 		}
519 		k->type = KEY_RSA;
520 		id = lookup_identity(k, 2);
521 		if (id != NULL) {
522 			Idtab *tab = idtab_lookup(2);
523 			TAILQ_REMOVE(&tab->idlist, id, next);
524 			free_identity(id);
525 			tab->nentries--;
526 			success = 1;
527 		}
528 		key_free(k);
529 	}
530 
531 	buffer_put_int(&e->output, 1);
532 	buffer_put_char(&e->output,
533 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
534 }
535 #endif /* SMARTCARD */
536 
537 /* dispatch incoming messages */
538 
539 static void
540 process_message(SocketEntry *e)
541 {
542 	u_int msg_len;
543 	u_int type;
544 	u_char *cp;
545 	if (buffer_len(&e->input) < 5)
546 		return;		/* Incomplete message. */
547 	cp = buffer_ptr(&e->input);
548 	msg_len = GET_32BIT(cp);
549 	if (msg_len > 256 * 1024) {
550 		shutdown(e->fd, SHUT_RDWR);
551 		close(e->fd);
552 		e->type = AUTH_UNUSED;
553 		return;
554 	}
555 	if (buffer_len(&e->input) < msg_len + 4)
556 		return;
557 	buffer_consume(&e->input, 4);
558 	type = buffer_get_char(&e->input);
559 
560 	debug("type %d", type);
561 	switch (type) {
562 	/* ssh1 */
563 	case SSH_AGENTC_RSA_CHALLENGE:
564 		process_authentication_challenge1(e);
565 		break;
566 	case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
567 		process_request_identities(e, 1);
568 		break;
569 	case SSH_AGENTC_ADD_RSA_IDENTITY:
570 		process_add_identity(e, 1);
571 		break;
572 	case SSH_AGENTC_REMOVE_RSA_IDENTITY:
573 		process_remove_identity(e, 1);
574 		break;
575 	case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
576 		process_remove_all_identities(e, 1);
577 		break;
578 	/* ssh2 */
579 	case SSH2_AGENTC_SIGN_REQUEST:
580 		process_sign_request2(e);
581 		break;
582 	case SSH2_AGENTC_REQUEST_IDENTITIES:
583 		process_request_identities(e, 2);
584 		break;
585 	case SSH2_AGENTC_ADD_IDENTITY:
586 		process_add_identity(e, 2);
587 		break;
588 	case SSH2_AGENTC_REMOVE_IDENTITY:
589 		process_remove_identity(e, 2);
590 		break;
591 	case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
592 		process_remove_all_identities(e, 2);
593 		break;
594 #ifdef SMARTCARD
595 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
596 		process_add_smartcard_key(e);
597 		break;
598 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
599 		process_remove_smartcard_key(e);
600 		break;
601 #endif /* SMARTCARD */
602 	default:
603 		/* Unknown message.  Respond with failure. */
604 		error("Unknown message %d", type);
605 		buffer_clear(&e->input);
606 		buffer_put_int(&e->output, 1);
607 		buffer_put_char(&e->output, SSH_AGENT_FAILURE);
608 		break;
609 	}
610 }
611 
612 static void
613 new_socket(sock_type type, int fd)
614 {
615 	u_int i, old_alloc;
616 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
617 		error("fcntl O_NONBLOCK: %s", strerror(errno));
618 
619 	if (fd > max_fd)
620 		max_fd = fd;
621 
622 	for (i = 0; i < sockets_alloc; i++)
623 		if (sockets[i].type == AUTH_UNUSED) {
624 			sockets[i].fd = fd;
625 			sockets[i].type = type;
626 			buffer_init(&sockets[i].input);
627 			buffer_init(&sockets[i].output);
628 			return;
629 		}
630 	old_alloc = sockets_alloc;
631 	sockets_alloc += 10;
632 	if (sockets)
633 		sockets = xrealloc(sockets, sockets_alloc * sizeof(sockets[0]));
634 	else
635 		sockets = xmalloc(sockets_alloc * sizeof(sockets[0]));
636 	for (i = old_alloc; i < sockets_alloc; i++)
637 		sockets[i].type = AUTH_UNUSED;
638 	sockets[old_alloc].type = type;
639 	sockets[old_alloc].fd = fd;
640 	buffer_init(&sockets[old_alloc].input);
641 	buffer_init(&sockets[old_alloc].output);
642 }
643 
644 static int
645 prepare_select(fd_set **fdrp, fd_set **fdwp, int *fdl, int *nallocp)
646 {
647 	u_int i, sz;
648 	int n = 0;
649 
650 	for (i = 0; i < sockets_alloc; i++) {
651 		switch (sockets[i].type) {
652 		case AUTH_SOCKET:
653 		case AUTH_CONNECTION:
654 			n = MAX(n, sockets[i].fd);
655 			break;
656 		case AUTH_UNUSED:
657 			break;
658 		default:
659 			fatal("Unknown socket type %d", sockets[i].type);
660 			break;
661 		}
662 	}
663 
664 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
665 	if (*fdrp == NULL || sz > *nallocp) {
666 		if (*fdrp)
667 			xfree(*fdrp);
668 		if (*fdwp)
669 			xfree(*fdwp);
670 		*fdrp = xmalloc(sz);
671 		*fdwp = xmalloc(sz);
672 		*nallocp = sz;
673 	}
674 	if (n < *fdl)
675 		debug("XXX shrink: %d < %d", n, *fdl);
676 	*fdl = n;
677 	memset(*fdrp, 0, sz);
678 	memset(*fdwp, 0, sz);
679 
680 	for (i = 0; i < sockets_alloc; i++) {
681 		switch (sockets[i].type) {
682 		case AUTH_SOCKET:
683 		case AUTH_CONNECTION:
684 			FD_SET(sockets[i].fd, *fdrp);
685 			if (buffer_len(&sockets[i].output) > 0)
686 				FD_SET(sockets[i].fd, *fdwp);
687 			break;
688 		default:
689 			break;
690 		}
691 	}
692 	return (1);
693 }
694 
695 static void
696 after_select(fd_set *readset, fd_set *writeset)
697 {
698 	u_int i;
699 	int len, sock;
700 	socklen_t slen;
701 	char buf[1024];
702 	struct sockaddr_un sunaddr;
703 
704 	for (i = 0; i < sockets_alloc; i++)
705 		switch (sockets[i].type) {
706 		case AUTH_UNUSED:
707 			break;
708 		case AUTH_SOCKET:
709 			if (FD_ISSET(sockets[i].fd, readset)) {
710 				slen = sizeof(sunaddr);
711 				sock = accept(sockets[i].fd,
712 				    (struct sockaddr *) &sunaddr, &slen);
713 				if (sock < 0) {
714 					error("accept from AUTH_SOCKET: %s",
715 					    strerror(errno));
716 					break;
717 				}
718 				new_socket(AUTH_CONNECTION, sock);
719 			}
720 			break;
721 		case AUTH_CONNECTION:
722 			if (buffer_len(&sockets[i].output) > 0 &&
723 			    FD_ISSET(sockets[i].fd, writeset)) {
724 				do {
725 					len = write(sockets[i].fd,
726 					    buffer_ptr(&sockets[i].output),
727 					    buffer_len(&sockets[i].output));
728 					if (len == -1 && (errno == EAGAIN ||
729 					    errno == EINTR))
730 						continue;
731 					break;
732 				} while (1);
733 				if (len <= 0) {
734 					shutdown(sockets[i].fd, SHUT_RDWR);
735 					close(sockets[i].fd);
736 					sockets[i].type = AUTH_UNUSED;
737 					buffer_free(&sockets[i].input);
738 					buffer_free(&sockets[i].output);
739 					break;
740 				}
741 				buffer_consume(&sockets[i].output, len);
742 			}
743 			if (FD_ISSET(sockets[i].fd, readset)) {
744 				do {
745 					len = read(sockets[i].fd, buf, sizeof(buf));
746 					if (len == -1 && (errno == EAGAIN ||
747 					    errno == EINTR))
748 						continue;
749 					break;
750 				} while (1);
751 				if (len <= 0) {
752 					shutdown(sockets[i].fd, SHUT_RDWR);
753 					close(sockets[i].fd);
754 					sockets[i].type = AUTH_UNUSED;
755 					buffer_free(&sockets[i].input);
756 					buffer_free(&sockets[i].output);
757 					break;
758 				}
759 				buffer_append(&sockets[i].input, buf, len);
760 				process_message(&sockets[i]);
761 			}
762 			break;
763 		default:
764 			fatal("Unknown type %d", sockets[i].type);
765 		}
766 }
767 
768 static void
769 cleanup_socket(void *p)
770 {
771 	if (socket_name[0])
772 		unlink(socket_name);
773 	if (socket_dir[0])
774 		rmdir(socket_dir);
775 }
776 
777 static void
778 cleanup_exit(int i)
779 {
780 	cleanup_socket(NULL);
781 	exit(i);
782 }
783 
784 static void
785 cleanup_handler(int sig)
786 {
787 	cleanup_socket(NULL);
788 	_exit(2);
789 }
790 
791 static void
792 check_parent_exists(int sig)
793 {
794 	int save_errno = errno;
795 
796 	if (parent_pid != -1 && kill(parent_pid, 0) < 0) {
797 		/* printf("Parent has died - Authentication agent exiting.\n"); */
798 		cleanup_handler(sig); /* safe */
799 	}
800 	signal(SIGALRM, check_parent_exists);
801 	alarm(10);
802 	errno = save_errno;
803 }
804 
805 static void
806 usage(void)
807 {
808 	fprintf(stderr, "Usage: %s [options] [command [args ...]]\n",
809 	    __progname);
810 	fprintf(stderr, "Options:\n");
811 	fprintf(stderr, "  -c          Generate C-shell commands on stdout.\n");
812 	fprintf(stderr, "  -s          Generate Bourne shell commands on stdout.\n");
813 	fprintf(stderr, "  -k          Kill the current agent.\n");
814 	fprintf(stderr, "  -d          Debug mode.\n");
815 	exit(1);
816 }
817 
818 int
819 main(int ac, char **av)
820 {
821 	int sock, c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0, ch, nalloc;
822 	struct sockaddr_un sunaddr;
823 	struct rlimit rlim;
824 	pid_t pid;
825 	char *shell, *format, *pidstr, pidstrbuf[1 + 3 * sizeof pid];
826 	extern int optind;
827 	fd_set *readsetp = NULL, *writesetp = NULL;
828 
829 	SSLeay_add_all_algorithms();
830 
831 	while ((ch = getopt(ac, av, "cdks")) != -1) {
832 		switch (ch) {
833 		case 'c':
834 			if (s_flag)
835 				usage();
836 			c_flag++;
837 			break;
838 		case 'k':
839 			k_flag++;
840 			break;
841 		case 's':
842 			if (c_flag)
843 				usage();
844 			s_flag++;
845 			break;
846 		case 'd':
847 			if (d_flag)
848 				usage();
849 			d_flag++;
850 			break;
851 		default:
852 			usage();
853 		}
854 	}
855 	ac -= optind;
856 	av += optind;
857 
858 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
859 		usage();
860 
861 	if (ac == 0 && !c_flag && !k_flag && !s_flag && !d_flag) {
862 		shell = getenv("SHELL");
863 		if (shell != NULL && strncmp(shell + strlen(shell) - 3, "csh", 3) == 0)
864 			c_flag = 1;
865 	}
866 	if (k_flag) {
867 		pidstr = getenv(SSH_AGENTPID_ENV_NAME);
868 		if (pidstr == NULL) {
869 			fprintf(stderr, "%s not set, cannot kill agent\n",
870 			    SSH_AGENTPID_ENV_NAME);
871 			exit(1);
872 		}
873 		pid = atoi(pidstr);
874 		if (pid < 1) {
875 			fprintf(stderr, "%s=\"%s\", which is not a good PID\n",
876 			    SSH_AGENTPID_ENV_NAME, pidstr);
877 			exit(1);
878 		}
879 		if (kill(pid, SIGTERM) == -1) {
880 			perror("kill");
881 			exit(1);
882 		}
883 		format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
884 		printf(format, SSH_AUTHSOCKET_ENV_NAME);
885 		printf(format, SSH_AGENTPID_ENV_NAME);
886 		printf("echo Agent pid %d killed;\n", pid);
887 		exit(0);
888 	}
889 	parent_pid = getpid();
890 
891 	/* Create private directory for agent socket */
892 	strlcpy(socket_dir, "/tmp/ssh-XXXXXXXX", sizeof socket_dir);
893 	if (mkdtemp(socket_dir) == NULL) {
894 		perror("mkdtemp: private socket dir");
895 		exit(1);
896 	}
897 	snprintf(socket_name, sizeof socket_name, "%s/agent.%d", socket_dir,
898 	    parent_pid);
899 
900 	/*
901 	 * Create socket early so it will exist before command gets run from
902 	 * the parent.
903 	 */
904 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
905 	if (sock < 0) {
906 		perror("socket");
907 		cleanup_exit(1);
908 	}
909 	memset(&sunaddr, 0, sizeof(sunaddr));
910 	sunaddr.sun_family = AF_UNIX;
911 	strlcpy(sunaddr.sun_path, socket_name, sizeof(sunaddr.sun_path));
912 	sunaddr.sun_len = SUN_LEN(&sunaddr) + 1;
913 	if (bind(sock, (struct sockaddr *)&sunaddr, sunaddr.sun_len) < 0) {
914 		perror("bind");
915 		cleanup_exit(1);
916 	}
917 	if (listen(sock, 5) < 0) {
918 		perror("listen");
919 		cleanup_exit(1);
920 	}
921 
922 	/*
923 	 * Fork, and have the parent execute the command, if any, or present
924 	 * the socket data.  The child continues as the authentication agent.
925 	 */
926 	if (d_flag) {
927 		log_init(__progname, SYSLOG_LEVEL_DEBUG1, SYSLOG_FACILITY_AUTH, 1);
928 		format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
929 		printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
930 		    SSH_AUTHSOCKET_ENV_NAME);
931 		printf("echo Agent pid %d;\n", parent_pid);
932 		goto skip;
933 	}
934 	pid = fork();
935 	if (pid == -1) {
936 		perror("fork");
937 		cleanup_exit(1);
938 	}
939 	if (pid != 0) {		/* Parent - execute the given command. */
940 		close(sock);
941 		snprintf(pidstrbuf, sizeof pidstrbuf, "%d", pid);
942 		if (ac == 0) {
943 			format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
944 			printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
945 			    SSH_AUTHSOCKET_ENV_NAME);
946 			printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
947 			    SSH_AGENTPID_ENV_NAME);
948 			printf("echo Agent pid %d;\n", pid);
949 			exit(0);
950 		}
951 		if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
952 		    setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
953 			perror("setenv");
954 			exit(1);
955 		}
956 		execvp(av[0], av);
957 		perror(av[0]);
958 		exit(1);
959 	}
960 	/* child */
961 	log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
962 
963 	if (setsid() == -1) {
964 		error("setsid: %s", strerror(errno));
965 		cleanup_exit(1);
966 	}
967 
968 	(void)chdir("/");
969 	close(0);
970 	close(1);
971 	close(2);
972 
973 	/* deny core dumps, since memory contains unencrypted private keys */
974 	rlim.rlim_cur = rlim.rlim_max = 0;
975 	if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
976 		error("setrlimit RLIMIT_CORE: %s", strerror(errno));
977 		cleanup_exit(1);
978 	}
979 
980 skip:
981 	fatal_add_cleanup(cleanup_socket, NULL);
982 	new_socket(AUTH_SOCKET, sock);
983 	if (ac > 0) {
984 		signal(SIGALRM, check_parent_exists);
985 		alarm(10);
986 	}
987 	idtab_init();
988 	if (!d_flag)
989 		signal(SIGINT, SIG_IGN);
990 	signal(SIGPIPE, SIG_IGN);
991 	signal(SIGHUP, cleanup_handler);
992 	signal(SIGTERM, cleanup_handler);
993 	nalloc = 0;
994 
995 	while (1) {
996 		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc);
997 		if (select(max_fd + 1, readsetp, writesetp, NULL, NULL) < 0) {
998 			if (errno == EINTR)
999 				continue;
1000 			fatal("select: %s", strerror(errno));
1001 		}
1002 		after_select(readsetp, writesetp);
1003 	}
1004 	/* NOTREACHED */
1005 }
1006