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