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