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