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