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