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