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