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