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