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