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