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