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