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