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