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