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