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