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