sshconnect2.c revision 263691
1/* $OpenBSD: sshconnect2.c,v 1.201 2014/01/09 23:20:00 djm Exp $ */
2/* $FreeBSD: head/crypto/openssh/sshconnect2.c 263691 2014-03-24 19:15:13Z des $ */
3/*
4 * Copyright (c) 2000 Markus Friedl.  All rights reserved.
5 * Copyright (c) 2008 Damien Miller.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "includes.h"
29__RCSID("$FreeBSD: head/crypto/openssh/sshconnect2.c 263691 2014-03-24 19:15:13Z des $");
30
31#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/wait.h>
34#include <sys/stat.h>
35
36#include <errno.h>
37#include <fcntl.h>
38#include <netdb.h>
39#include <pwd.h>
40#include <signal.h>
41#include <stdarg.h>
42#include <stdio.h>
43#include <string.h>
44#include <unistd.h>
45#if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
46#include <vis.h>
47#endif
48
49#include "openbsd-compat/sys-queue.h"
50
51#include "xmalloc.h"
52#include "ssh.h"
53#include "ssh2.h"
54#include "buffer.h"
55#include "packet.h"
56#include "compat.h"
57#include "cipher.h"
58#include "key.h"
59#include "kex.h"
60#include "myproposal.h"
61#include "sshconnect.h"
62#include "authfile.h"
63#include "dh.h"
64#include "authfd.h"
65#include "log.h"
66#include "readconf.h"
67#include "misc.h"
68#include "match.h"
69#include "dispatch.h"
70#include "canohost.h"
71#include "msg.h"
72#include "pathnames.h"
73#include "uidswap.h"
74#include "hostfile.h"
75#include "schnorr.h"
76#include "jpake.h"
77
78#ifdef GSSAPI
79#include "ssh-gss.h"
80#endif
81
82/* import */
83extern char *client_version_string;
84extern char *server_version_string;
85extern Options options;
86#ifdef	NONE_CIPHER_ENABLED
87extern Kex *xxx_kex;
88
89/*
90 * tty_flag is set in ssh.c so we can use it here.  If set then prevent
91 * the switch to the null cipher.
92 */
93
94extern int tty_flag;
95#endif
96
97/*
98 * SSH2 key exchange
99 */
100
101u_char *session_id2 = NULL;
102u_int session_id2_len = 0;
103
104char *xxx_host;
105struct sockaddr *xxx_hostaddr;
106
107Kex *xxx_kex = NULL;
108
109static int
110verify_host_key_callback(Key *hostkey)
111{
112	if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
113		fatal("Host key verification failed.");
114	return 0;
115}
116
117static char *
118order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port)
119{
120	char *oavail, *avail, *first, *last, *alg, *hostname, *ret;
121	size_t maxlen;
122	struct hostkeys *hostkeys;
123	int ktype;
124	u_int i;
125
126	/* Find all hostkeys for this hostname */
127	get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
128	hostkeys = init_hostkeys();
129	for (i = 0; i < options.num_user_hostfiles; i++)
130		load_hostkeys(hostkeys, hostname, options.user_hostfiles[i]);
131	for (i = 0; i < options.num_system_hostfiles; i++)
132		load_hostkeys(hostkeys, hostname, options.system_hostfiles[i]);
133
134	oavail = avail = xstrdup(KEX_DEFAULT_PK_ALG);
135	maxlen = strlen(avail) + 1;
136	first = xmalloc(maxlen);
137	last = xmalloc(maxlen);
138	*first = *last = '\0';
139
140#define ALG_APPEND(to, from) \
141	do { \
142		if (*to != '\0') \
143			strlcat(to, ",", maxlen); \
144		strlcat(to, from, maxlen); \
145	} while (0)
146
147	while ((alg = strsep(&avail, ",")) && *alg != '\0') {
148		if ((ktype = key_type_from_name(alg)) == KEY_UNSPEC)
149			fatal("%s: unknown alg %s", __func__, alg);
150		if (lookup_key_in_hostkeys_by_type(hostkeys,
151		    key_type_plain(ktype), NULL))
152			ALG_APPEND(first, alg);
153		else
154			ALG_APPEND(last, alg);
155	}
156#undef ALG_APPEND
157	xasprintf(&ret, "%s%s%s", first, *first == '\0' ? "" : ",", last);
158	if (*first != '\0')
159		debug3("%s: prefer hostkeyalgs: %s", __func__, first);
160
161	free(first);
162	free(last);
163	free(hostname);
164	free(oavail);
165	free_hostkeys(hostkeys);
166
167	return ret;
168}
169
170void
171ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
172{
173	Kex *kex;
174
175	xxx_host = host;
176	xxx_hostaddr = hostaddr;
177
178	if (options.ciphers == (char *)-1) {
179		logit("No valid ciphers for protocol version 2 given, using defaults.");
180		options.ciphers = NULL;
181	}
182	if (options.ciphers != NULL) {
183		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
184		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
185	}
186	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
187	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
188	myproposal[PROPOSAL_ENC_ALGS_STOC] =
189	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
190	if (options.compression) {
191		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
192		myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib@openssh.com,zlib,none";
193	} else {
194		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
195		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com,zlib";
196	}
197	if (options.macs != NULL) {
198		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
199		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
200	}
201	if (options.hostkeyalgorithms != NULL)
202		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
203		    compat_pkalg_proposal(options.hostkeyalgorithms);
204	else {
205		/* Prefer algorithms that we already have keys for */
206		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
207		    compat_pkalg_proposal(
208		    order_hostkeyalgs(host, hostaddr, port));
209	}
210	if (options.kex_algorithms != NULL)
211		myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
212
213	if (options.rekey_limit || options.rekey_interval)
214		packet_set_rekey_limits((u_int32_t)options.rekey_limit,
215		    (time_t)options.rekey_interval);
216
217	/* start key exchange */
218	kex = kex_setup(myproposal);
219	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
220	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
221	kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
222	kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
223	kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
224	kex->kex[KEX_C25519_SHA256] = kexc25519_client;
225	kex->client_version_string=client_version_string;
226	kex->server_version_string=server_version_string;
227	kex->verify_host_key=&verify_host_key_callback;
228
229	xxx_kex = kex;
230
231	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
232
233	if (options.use_roaming && !kex->roaming) {
234		debug("Roaming not allowed by server");
235		options.use_roaming = 0;
236	}
237
238	session_id2 = kex->session_id;
239	session_id2_len = kex->session_id_len;
240
241#ifdef DEBUG_KEXDH
242	/* send 1st encrypted/maced/compressed message */
243	packet_start(SSH2_MSG_IGNORE);
244	packet_put_cstring("markus");
245	packet_send();
246	packet_write_wait();
247#endif
248}
249
250/*
251 * Authenticate user
252 */
253
254typedef struct Authctxt Authctxt;
255typedef struct Authmethod Authmethod;
256typedef struct identity Identity;
257typedef struct idlist Idlist;
258
259struct identity {
260	TAILQ_ENTRY(identity) next;
261	AuthenticationConnection *ac;	/* set if agent supports key */
262	Key	*key;			/* public/private key */
263	char	*filename;		/* comment for agent-only keys */
264	int	tried;
265	int	isprivate;		/* key points to the private key */
266	int	userprovided;
267};
268TAILQ_HEAD(idlist, identity);
269
270struct Authctxt {
271	const char *server_user;
272	const char *local_user;
273	const char *host;
274	const char *service;
275	Authmethod *method;
276	sig_atomic_t success;
277	char *authlist;
278	/* pubkey */
279	Idlist keys;
280	AuthenticationConnection *agent;
281	/* hostbased */
282	Sensitive *sensitive;
283	/* kbd-interactive */
284	int info_req_seen;
285	/* generic */
286	void *methoddata;
287};
288struct Authmethod {
289	char	*name;		/* string to compare against server's list */
290	int	(*userauth)(Authctxt *authctxt);
291	void	(*cleanup)(Authctxt *authctxt);
292	int	*enabled;	/* flag in option struct that enables method */
293	int	*batch_flag;	/* flag in option struct that disables method */
294};
295
296void	input_userauth_success(int, u_int32_t, void *);
297void	input_userauth_success_unexpected(int, u_int32_t, void *);
298void	input_userauth_failure(int, u_int32_t, void *);
299void	input_userauth_banner(int, u_int32_t, void *);
300void	input_userauth_error(int, u_int32_t, void *);
301void	input_userauth_info_req(int, u_int32_t, void *);
302void	input_userauth_pk_ok(int, u_int32_t, void *);
303void	input_userauth_passwd_changereq(int, u_int32_t, void *);
304void	input_userauth_jpake_server_step1(int, u_int32_t, void *);
305void	input_userauth_jpake_server_step2(int, u_int32_t, void *);
306void	input_userauth_jpake_server_confirm(int, u_int32_t, void *);
307
308int	userauth_none(Authctxt *);
309int	userauth_pubkey(Authctxt *);
310int	userauth_passwd(Authctxt *);
311int	userauth_kbdint(Authctxt *);
312int	userauth_hostbased(Authctxt *);
313int	userauth_jpake(Authctxt *);
314
315void	userauth_jpake_cleanup(Authctxt *);
316
317#ifdef GSSAPI
318int	userauth_gssapi(Authctxt *authctxt);
319void	input_gssapi_response(int type, u_int32_t, void *);
320void	input_gssapi_token(int type, u_int32_t, void *);
321void	input_gssapi_hash(int type, u_int32_t, void *);
322void	input_gssapi_error(int, u_int32_t, void *);
323void	input_gssapi_errtok(int, u_int32_t, void *);
324#endif
325
326void	userauth(Authctxt *, char *);
327
328static int sign_and_send_pubkey(Authctxt *, Identity *);
329static void pubkey_prepare(Authctxt *);
330static void pubkey_cleanup(Authctxt *);
331static Key *load_identity_file(char *, int);
332
333static Authmethod *authmethod_get(char *authlist);
334static Authmethod *authmethod_lookup(const char *name);
335static char *authmethods_get(void);
336
337Authmethod authmethods[] = {
338#ifdef GSSAPI
339	{"gssapi-with-mic",
340		userauth_gssapi,
341		NULL,
342		&options.gss_authentication,
343		NULL},
344#endif
345	{"hostbased",
346		userauth_hostbased,
347		NULL,
348		&options.hostbased_authentication,
349		NULL},
350	{"publickey",
351		userauth_pubkey,
352		NULL,
353		&options.pubkey_authentication,
354		NULL},
355#ifdef JPAKE
356	{"jpake-01@openssh.com",
357		userauth_jpake,
358		userauth_jpake_cleanup,
359		&options.zero_knowledge_password_authentication,
360		&options.batch_mode},
361#endif
362	{"keyboard-interactive",
363		userauth_kbdint,
364		NULL,
365		&options.kbd_interactive_authentication,
366		&options.batch_mode},
367	{"password",
368		userauth_passwd,
369		NULL,
370		&options.password_authentication,
371		&options.batch_mode},
372	{"none",
373		userauth_none,
374		NULL,
375		NULL,
376		NULL},
377	{NULL, NULL, NULL, NULL, NULL}
378};
379
380void
381ssh_userauth2(const char *local_user, const char *server_user, char *host,
382    Sensitive *sensitive)
383{
384	Authctxt authctxt;
385	int type;
386
387	if (options.challenge_response_authentication)
388		options.kbd_interactive_authentication = 1;
389
390	packet_start(SSH2_MSG_SERVICE_REQUEST);
391	packet_put_cstring("ssh-userauth");
392	packet_send();
393	debug("SSH2_MSG_SERVICE_REQUEST sent");
394	packet_write_wait();
395	type = packet_read();
396	if (type != SSH2_MSG_SERVICE_ACCEPT)
397		fatal("Server denied authentication request: %d", type);
398	if (packet_remaining() > 0) {
399		char *reply = packet_get_string(NULL);
400		debug2("service_accept: %s", reply);
401		free(reply);
402	} else {
403		debug2("buggy server: service_accept w/o service");
404	}
405	packet_check_eom();
406	debug("SSH2_MSG_SERVICE_ACCEPT received");
407
408	if (options.preferred_authentications == NULL)
409		options.preferred_authentications = authmethods_get();
410
411	/* setup authentication context */
412	memset(&authctxt, 0, sizeof(authctxt));
413	pubkey_prepare(&authctxt);
414	authctxt.server_user = server_user;
415	authctxt.local_user = local_user;
416	authctxt.host = host;
417	authctxt.service = "ssh-connection";		/* service name */
418	authctxt.success = 0;
419	authctxt.method = authmethod_lookup("none");
420	authctxt.authlist = NULL;
421	authctxt.methoddata = NULL;
422	authctxt.sensitive = sensitive;
423	authctxt.info_req_seen = 0;
424	if (authctxt.method == NULL)
425		fatal("ssh_userauth2: internal error: cannot send userauth none request");
426
427	/* initial userauth request */
428	userauth_none(&authctxt);
429
430	dispatch_init(&input_userauth_error);
431	dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
432	dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
433	dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
434	dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt);	/* loop until success */
435
436	pubkey_cleanup(&authctxt);
437	dispatch_range(SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
438
439#ifdef	NONE_CIPHER_ENABLED
440	/*
441	 * If the user explicitly requests to use the none cipher enable it
442	 * post authentication and only if the right conditions are met: both
443	 * of the NONE switches must be true and there must be no tty allocated.
444	 */
445	if (options.none_switch == 1 && options.none_enabled == 1) {
446		if (!tty_flag) {
447			debug("Requesting none cipher re-keying...");
448			myproposal[PROPOSAL_ENC_ALGS_STOC] = "none";
449			myproposal[PROPOSAL_ENC_ALGS_CTOS] = "none";
450			kex_prop2buf(&xxx_kex->my, myproposal);
451			packet_request_rekeying();
452			fprintf(stderr, "WARNING: enabled NONE cipher\n");
453		} else {
454			/* Requested NONE cipher on an interactive session. */
455			debug("Cannot switch to NONE cipher with tty "
456			    "allocated");
457			fprintf(stderr, "NONE cipher switch disabled given "
458			    "a TTY is allocated\n");
459		}
460	}
461#endif
462	debug("Authentication succeeded (%s).", authctxt.method->name);
463}
464
465void
466userauth(Authctxt *authctxt, char *authlist)
467{
468	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
469		authctxt->method->cleanup(authctxt);
470
471	free(authctxt->methoddata);
472	authctxt->methoddata = NULL;
473	if (authlist == NULL) {
474		authlist = authctxt->authlist;
475	} else {
476		free(authctxt->authlist);
477		authctxt->authlist = authlist;
478	}
479	for (;;) {
480		Authmethod *method = authmethod_get(authlist);
481		if (method == NULL)
482			fatal("Permission denied (%s).", authlist);
483		authctxt->method = method;
484
485		/* reset the per method handler */
486		dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
487		    SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
488
489		/* and try new method */
490		if (method->userauth(authctxt) != 0) {
491			debug2("we sent a %s packet, wait for reply", method->name);
492			break;
493		} else {
494			debug2("we did not send a packet, disable method");
495			method->enabled = NULL;
496		}
497	}
498}
499
500/* ARGSUSED */
501void
502input_userauth_error(int type, u_int32_t seq, void *ctxt)
503{
504	fatal("input_userauth_error: bad message during authentication: "
505	    "type %d", type);
506}
507
508/* ARGSUSED */
509void
510input_userauth_banner(int type, u_int32_t seq, void *ctxt)
511{
512	char *msg, *raw, *lang;
513	u_int len;
514
515	debug3("input_userauth_banner");
516	raw = packet_get_string(&len);
517	lang = packet_get_string(NULL);
518	if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) {
519		if (len > 65536)
520			len = 65536;
521		msg = xmalloc(len * 4 + 1); /* max expansion from strnvis() */
522		strnvis(msg, raw, len * 4 + 1, VIS_SAFE|VIS_OCTAL|VIS_NOSLASH);
523		fprintf(stderr, "%s", msg);
524		free(msg);
525	}
526	free(raw);
527	free(lang);
528}
529
530/* ARGSUSED */
531void
532input_userauth_success(int type, u_int32_t seq, void *ctxt)
533{
534	Authctxt *authctxt = ctxt;
535
536	if (authctxt == NULL)
537		fatal("input_userauth_success: no authentication context");
538	free(authctxt->authlist);
539	authctxt->authlist = NULL;
540	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
541		authctxt->method->cleanup(authctxt);
542	free(authctxt->methoddata);
543	authctxt->methoddata = NULL;
544	authctxt->success = 1;			/* break out */
545}
546
547void
548input_userauth_success_unexpected(int type, u_int32_t seq, void *ctxt)
549{
550	Authctxt *authctxt = ctxt;
551
552	if (authctxt == NULL)
553		fatal("%s: no authentication context", __func__);
554
555	fatal("Unexpected authentication success during %s.",
556	    authctxt->method->name);
557}
558
559/* ARGSUSED */
560void
561input_userauth_failure(int type, u_int32_t seq, void *ctxt)
562{
563	Authctxt *authctxt = ctxt;
564	char *authlist = NULL;
565	int partial;
566
567	if (authctxt == NULL)
568		fatal("input_userauth_failure: no authentication context");
569
570	authlist = packet_get_string(NULL);
571	partial = packet_get_char();
572	packet_check_eom();
573
574	if (partial != 0) {
575		logit("Authenticated with partial success.");
576		/* reset state */
577		pubkey_cleanup(authctxt);
578		pubkey_prepare(authctxt);
579	}
580	debug("Authentications that can continue: %s", authlist);
581
582	userauth(authctxt, authlist);
583}
584
585/* ARGSUSED */
586void
587input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
588{
589	Authctxt *authctxt = ctxt;
590	Key *key = NULL;
591	Identity *id = NULL;
592	Buffer b;
593	int pktype, sent = 0;
594	u_int alen, blen;
595	char *pkalg, *fp;
596	u_char *pkblob;
597
598	if (authctxt == NULL)
599		fatal("input_userauth_pk_ok: no authentication context");
600	if (datafellows & SSH_BUG_PKOK) {
601		/* this is similar to SSH_BUG_PKAUTH */
602		debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
603		pkblob = packet_get_string(&blen);
604		buffer_init(&b);
605		buffer_append(&b, pkblob, blen);
606		pkalg = buffer_get_string(&b, &alen);
607		buffer_free(&b);
608	} else {
609		pkalg = packet_get_string(&alen);
610		pkblob = packet_get_string(&blen);
611	}
612	packet_check_eom();
613
614	debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
615
616	if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
617		debug("unknown pkalg %s", pkalg);
618		goto done;
619	}
620	if ((key = key_from_blob(pkblob, blen)) == NULL) {
621		debug("no key from blob. pkalg %s", pkalg);
622		goto done;
623	}
624	if (key->type != pktype) {
625		error("input_userauth_pk_ok: type mismatch "
626		    "for decoded key (received %d, expected %d)",
627		    key->type, pktype);
628		goto done;
629	}
630	fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
631	debug2("input_userauth_pk_ok: fp %s", fp);
632	free(fp);
633
634	/*
635	 * search keys in the reverse order, because last candidate has been
636	 * moved to the end of the queue.  this also avoids confusion by
637	 * duplicate keys
638	 */
639	TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
640		if (key_equal(key, id->key)) {
641			sent = sign_and_send_pubkey(authctxt, id);
642			break;
643		}
644	}
645done:
646	if (key != NULL)
647		key_free(key);
648	free(pkalg);
649	free(pkblob);
650
651	/* try another method if we did not send a packet */
652	if (sent == 0)
653		userauth(authctxt, NULL);
654}
655
656#ifdef GSSAPI
657int
658userauth_gssapi(Authctxt *authctxt)
659{
660	Gssctxt *gssctxt = NULL;
661	static gss_OID_set gss_supported = NULL;
662	static u_int mech = 0;
663	OM_uint32 min;
664	int ok = 0;
665
666	/* Try one GSSAPI method at a time, rather than sending them all at
667	 * once. */
668
669	if (gss_supported == NULL)
670		gss_indicate_mechs(&min, &gss_supported);
671
672	/* Check to see if the mechanism is usable before we offer it */
673	while (mech < gss_supported->count && !ok) {
674		/* My DER encoding requires length<128 */
675		if (gss_supported->elements[mech].length < 128 &&
676		    ssh_gssapi_check_mechanism(&gssctxt,
677		    &gss_supported->elements[mech], authctxt->host)) {
678			ok = 1; /* Mechanism works */
679		} else {
680			mech++;
681		}
682	}
683
684	if (!ok)
685		return 0;
686
687	authctxt->methoddata=(void *)gssctxt;
688
689	packet_start(SSH2_MSG_USERAUTH_REQUEST);
690	packet_put_cstring(authctxt->server_user);
691	packet_put_cstring(authctxt->service);
692	packet_put_cstring(authctxt->method->name);
693
694	packet_put_int(1);
695
696	packet_put_int((gss_supported->elements[mech].length) + 2);
697	packet_put_char(SSH_GSS_OIDTYPE);
698	packet_put_char(gss_supported->elements[mech].length);
699	packet_put_raw(gss_supported->elements[mech].elements,
700	    gss_supported->elements[mech].length);
701
702	packet_send();
703
704	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
705	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
706	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
707	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
708
709	mech++; /* Move along to next candidate */
710
711	return 1;
712}
713
714static OM_uint32
715process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
716{
717	Authctxt *authctxt = ctxt;
718	Gssctxt *gssctxt = authctxt->methoddata;
719	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
720	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
721	gss_buffer_desc gssbuf;
722	OM_uint32 status, ms, flags;
723	Buffer b;
724
725	status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
726	    recv_tok, &send_tok, &flags);
727
728	if (send_tok.length > 0) {
729		if (GSS_ERROR(status))
730			packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
731		else
732			packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
733
734		packet_put_string(send_tok.value, send_tok.length);
735		packet_send();
736		gss_release_buffer(&ms, &send_tok);
737	}
738
739	if (status == GSS_S_COMPLETE) {
740		/* send either complete or MIC, depending on mechanism */
741		if (!(flags & GSS_C_INTEG_FLAG)) {
742			packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
743			packet_send();
744		} else {
745			ssh_gssapi_buildmic(&b, authctxt->server_user,
746			    authctxt->service, "gssapi-with-mic");
747
748			gssbuf.value = buffer_ptr(&b);
749			gssbuf.length = buffer_len(&b);
750
751			status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
752
753			if (!GSS_ERROR(status)) {
754				packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
755				packet_put_string(mic.value, mic.length);
756
757				packet_send();
758			}
759
760			buffer_free(&b);
761			gss_release_buffer(&ms, &mic);
762		}
763	}
764
765	return status;
766}
767
768/* ARGSUSED */
769void
770input_gssapi_response(int type, u_int32_t plen, void *ctxt)
771{
772	Authctxt *authctxt = ctxt;
773	Gssctxt *gssctxt;
774	int oidlen;
775	char *oidv;
776
777	if (authctxt == NULL)
778		fatal("input_gssapi_response: no authentication context");
779	gssctxt = authctxt->methoddata;
780
781	/* Setup our OID */
782	oidv = packet_get_string(&oidlen);
783
784	if (oidlen <= 2 ||
785	    oidv[0] != SSH_GSS_OIDTYPE ||
786	    oidv[1] != oidlen - 2) {
787		free(oidv);
788		debug("Badly encoded mechanism OID received");
789		userauth(authctxt, NULL);
790		return;
791	}
792
793	if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
794		fatal("Server returned different OID than expected");
795
796	packet_check_eom();
797
798	free(oidv);
799
800	if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
801		/* Start again with next method on list */
802		debug("Trying to start again");
803		userauth(authctxt, NULL);
804		return;
805	}
806}
807
808/* ARGSUSED */
809void
810input_gssapi_token(int type, u_int32_t plen, void *ctxt)
811{
812	Authctxt *authctxt = ctxt;
813	gss_buffer_desc recv_tok;
814	OM_uint32 status;
815	u_int slen;
816
817	if (authctxt == NULL)
818		fatal("input_gssapi_response: no authentication context");
819
820	recv_tok.value = packet_get_string(&slen);
821	recv_tok.length = slen;	/* safe typecast */
822
823	packet_check_eom();
824
825	status = process_gssapi_token(ctxt, &recv_tok);
826
827	free(recv_tok.value);
828
829	if (GSS_ERROR(status)) {
830		/* Start again with the next method in the list */
831		userauth(authctxt, NULL);
832		return;
833	}
834}
835
836/* ARGSUSED */
837void
838input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
839{
840	Authctxt *authctxt = ctxt;
841	Gssctxt *gssctxt;
842	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
843	gss_buffer_desc recv_tok;
844	OM_uint32 ms;
845	u_int len;
846
847	if (authctxt == NULL)
848		fatal("input_gssapi_response: no authentication context");
849	gssctxt = authctxt->methoddata;
850
851	recv_tok.value = packet_get_string(&len);
852	recv_tok.length = len;
853
854	packet_check_eom();
855
856	/* Stick it into GSSAPI and see what it says */
857	(void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
858	    &recv_tok, &send_tok, NULL);
859
860	free(recv_tok.value);
861	gss_release_buffer(&ms, &send_tok);
862
863	/* Server will be returning a failed packet after this one */
864}
865
866/* ARGSUSED */
867void
868input_gssapi_error(int type, u_int32_t plen, void *ctxt)
869{
870	char *msg;
871	char *lang;
872
873	/* maj */(void)packet_get_int();
874	/* min */(void)packet_get_int();
875	msg=packet_get_string(NULL);
876	lang=packet_get_string(NULL);
877
878	packet_check_eom();
879
880	debug("Server GSSAPI Error:\n%s", msg);
881	free(msg);
882	free(lang);
883}
884#endif /* GSSAPI */
885
886int
887userauth_none(Authctxt *authctxt)
888{
889	/* initial userauth request */
890	packet_start(SSH2_MSG_USERAUTH_REQUEST);
891	packet_put_cstring(authctxt->server_user);
892	packet_put_cstring(authctxt->service);
893	packet_put_cstring(authctxt->method->name);
894	packet_send();
895	return 1;
896}
897
898int
899userauth_passwd(Authctxt *authctxt)
900{
901	static int attempt = 0;
902	char prompt[150];
903	char *password;
904	const char *host = options.host_key_alias ?  options.host_key_alias :
905	    authctxt->host;
906
907	if (attempt++ >= options.number_of_password_prompts)
908		return 0;
909
910	if (attempt != 1)
911		error("Permission denied, please try again.");
912
913	snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
914	    authctxt->server_user, host);
915	password = read_passphrase(prompt, 0);
916	packet_start(SSH2_MSG_USERAUTH_REQUEST);
917	packet_put_cstring(authctxt->server_user);
918	packet_put_cstring(authctxt->service);
919	packet_put_cstring(authctxt->method->name);
920	packet_put_char(0);
921	packet_put_cstring(password);
922	memset(password, 0, strlen(password));
923	free(password);
924	packet_add_padding(64);
925	packet_send();
926
927	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
928	    &input_userauth_passwd_changereq);
929
930	return 1;
931}
932
933/*
934 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
935 */
936/* ARGSUSED */
937void
938input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
939{
940	Authctxt *authctxt = ctxt;
941	char *info, *lang, *password = NULL, *retype = NULL;
942	char prompt[150];
943	const char *host = options.host_key_alias ? options.host_key_alias :
944	    authctxt->host;
945
946	debug2("input_userauth_passwd_changereq");
947
948	if (authctxt == NULL)
949		fatal("input_userauth_passwd_changereq: "
950		    "no authentication context");
951
952	info = packet_get_string(NULL);
953	lang = packet_get_string(NULL);
954	if (strlen(info) > 0)
955		logit("%s", info);
956	free(info);
957	free(lang);
958	packet_start(SSH2_MSG_USERAUTH_REQUEST);
959	packet_put_cstring(authctxt->server_user);
960	packet_put_cstring(authctxt->service);
961	packet_put_cstring(authctxt->method->name);
962	packet_put_char(1);			/* additional info */
963	snprintf(prompt, sizeof(prompt),
964	    "Enter %.30s@%.128s's old password: ",
965	    authctxt->server_user, host);
966	password = read_passphrase(prompt, 0);
967	packet_put_cstring(password);
968	memset(password, 0, strlen(password));
969	free(password);
970	password = NULL;
971	while (password == NULL) {
972		snprintf(prompt, sizeof(prompt),
973		    "Enter %.30s@%.128s's new password: ",
974		    authctxt->server_user, host);
975		password = read_passphrase(prompt, RP_ALLOW_EOF);
976		if (password == NULL) {
977			/* bail out */
978			return;
979		}
980		snprintf(prompt, sizeof(prompt),
981		    "Retype %.30s@%.128s's new password: ",
982		    authctxt->server_user, host);
983		retype = read_passphrase(prompt, 0);
984		if (strcmp(password, retype) != 0) {
985			memset(password, 0, strlen(password));
986			free(password);
987			logit("Mismatch; try again, EOF to quit.");
988			password = NULL;
989		}
990		memset(retype, 0, strlen(retype));
991		free(retype);
992	}
993	packet_put_cstring(password);
994	memset(password, 0, strlen(password));
995	free(password);
996	packet_add_padding(64);
997	packet_send();
998
999	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1000	    &input_userauth_passwd_changereq);
1001}
1002
1003#ifdef JPAKE
1004static char *
1005pw_encrypt(const char *password, const char *crypt_scheme, const char *salt)
1006{
1007	/* OpenBSD crypt(3) handles all of these */
1008	if (strcmp(crypt_scheme, "crypt") == 0 ||
1009	    strcmp(crypt_scheme, "bcrypt") == 0 ||
1010	    strcmp(crypt_scheme, "md5crypt") == 0 ||
1011	    strcmp(crypt_scheme, "crypt-extended") == 0)
1012		return xstrdup(crypt(password, salt));
1013	error("%s: unsupported password encryption scheme \"%.100s\"",
1014	    __func__, crypt_scheme);
1015	return NULL;
1016}
1017
1018static BIGNUM *
1019jpake_password_to_secret(Authctxt *authctxt, const char *crypt_scheme,
1020    const char *salt)
1021{
1022	char prompt[256], *password, *crypted;
1023	u_char *secret;
1024	u_int secret_len;
1025	BIGNUM *ret;
1026
1027	snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password (JPAKE): ",
1028	    authctxt->server_user, authctxt->host);
1029	password = read_passphrase(prompt, 0);
1030
1031	if ((crypted = pw_encrypt(password, crypt_scheme, salt)) == NULL) {
1032		logit("Disabling %s authentication", authctxt->method->name);
1033		authctxt->method->enabled = NULL;
1034		/* Continue with an empty password to fail gracefully */
1035		crypted = xstrdup("");
1036	}
1037
1038#ifdef JPAKE_DEBUG
1039	debug3("%s: salt = %s", __func__, salt);
1040	debug3("%s: scheme = %s", __func__, crypt_scheme);
1041	debug3("%s: crypted = %s", __func__, crypted);
1042#endif
1043
1044	if (hash_buffer(crypted, strlen(crypted), SSH_DIGEST_SHA1,
1045	    &secret, &secret_len) != 0)
1046		fatal("%s: hash_buffer", __func__);
1047
1048	bzero(password, strlen(password));
1049	bzero(crypted, strlen(crypted));
1050	free(password);
1051	free(crypted);
1052
1053	if ((ret = BN_bin2bn(secret, secret_len, NULL)) == NULL)
1054		fatal("%s: BN_bin2bn (secret)", __func__);
1055	bzero(secret, secret_len);
1056	free(secret);
1057
1058	return ret;
1059}
1060
1061/* ARGSUSED */
1062void
1063input_userauth_jpake_server_step1(int type, u_int32_t seq, void *ctxt)
1064{
1065	Authctxt *authctxt = ctxt;
1066	struct jpake_ctx *pctx = authctxt->methoddata;
1067	u_char *x3_proof, *x4_proof, *x2_s_proof;
1068	u_int x3_proof_len, x4_proof_len, x2_s_proof_len;
1069	char *crypt_scheme, *salt;
1070
1071	/* Disable this message */
1072	dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP1, NULL);
1073
1074	if ((pctx->g_x3 = BN_new()) == NULL ||
1075	    (pctx->g_x4 = BN_new()) == NULL)
1076		fatal("%s: BN_new", __func__);
1077
1078	/* Fetch step 1 values */
1079	crypt_scheme = packet_get_string(NULL);
1080	salt = packet_get_string(NULL);
1081	pctx->server_id = packet_get_string(&pctx->server_id_len);
1082	packet_get_bignum2(pctx->g_x3);
1083	packet_get_bignum2(pctx->g_x4);
1084	x3_proof = packet_get_string(&x3_proof_len);
1085	x4_proof = packet_get_string(&x4_proof_len);
1086	packet_check_eom();
1087
1088	JPAKE_DEBUG_CTX((pctx, "step 1 received in %s", __func__));
1089
1090	/* Obtain password and derive secret */
1091	pctx->s = jpake_password_to_secret(authctxt, crypt_scheme, salt);
1092	bzero(crypt_scheme, strlen(crypt_scheme));
1093	bzero(salt, strlen(salt));
1094	free(crypt_scheme);
1095	free(salt);
1096	JPAKE_DEBUG_BN((pctx->s, "%s: s = ", __func__));
1097
1098	/* Calculate step 2 values */
1099	jpake_step2(pctx->grp, pctx->s, pctx->g_x1,
1100	    pctx->g_x3, pctx->g_x4, pctx->x2,
1101	    pctx->server_id, pctx->server_id_len,
1102	    pctx->client_id, pctx->client_id_len,
1103	    x3_proof, x3_proof_len,
1104	    x4_proof, x4_proof_len,
1105	    &pctx->a,
1106	    &x2_s_proof, &x2_s_proof_len);
1107
1108	bzero(x3_proof, x3_proof_len);
1109	bzero(x4_proof, x4_proof_len);
1110	free(x3_proof);
1111	free(x4_proof);
1112
1113	JPAKE_DEBUG_CTX((pctx, "step 2 sending in %s", __func__));
1114
1115	/* Send values for step 2 */
1116	packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_STEP2);
1117	packet_put_bignum2(pctx->a);
1118	packet_put_string(x2_s_proof, x2_s_proof_len);
1119	packet_send();
1120
1121	bzero(x2_s_proof, x2_s_proof_len);
1122	free(x2_s_proof);
1123
1124	/* Expect step 2 packet from peer */
1125	dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP2,
1126	    input_userauth_jpake_server_step2);
1127}
1128
1129/* ARGSUSED */
1130void
1131input_userauth_jpake_server_step2(int type, u_int32_t seq, void *ctxt)
1132{
1133	Authctxt *authctxt = ctxt;
1134	struct jpake_ctx *pctx = authctxt->methoddata;
1135	u_char *x4_s_proof;
1136	u_int x4_s_proof_len;
1137
1138	/* Disable this message */
1139	dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP2, NULL);
1140
1141	if ((pctx->b = BN_new()) == NULL)
1142		fatal("%s: BN_new", __func__);
1143
1144	/* Fetch step 2 values */
1145	packet_get_bignum2(pctx->b);
1146	x4_s_proof = packet_get_string(&x4_s_proof_len);
1147	packet_check_eom();
1148
1149	JPAKE_DEBUG_CTX((pctx, "step 2 received in %s", __func__));
1150
1151	/* Derive shared key and calculate confirmation hash */
1152	jpake_key_confirm(pctx->grp, pctx->s, pctx->b,
1153	    pctx->x2, pctx->g_x1, pctx->g_x2, pctx->g_x3, pctx->g_x4,
1154	    pctx->client_id, pctx->client_id_len,
1155	    pctx->server_id, pctx->server_id_len,
1156	    session_id2, session_id2_len,
1157	    x4_s_proof, x4_s_proof_len,
1158	    &pctx->k,
1159	    &pctx->h_k_cid_sessid, &pctx->h_k_cid_sessid_len);
1160
1161	bzero(x4_s_proof, x4_s_proof_len);
1162	free(x4_s_proof);
1163
1164	JPAKE_DEBUG_CTX((pctx, "confirm sending in %s", __func__));
1165
1166	/* Send key confirmation proof */
1167	packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_CONFIRM);
1168	packet_put_string(pctx->h_k_cid_sessid, pctx->h_k_cid_sessid_len);
1169	packet_send();
1170
1171	/* Expect confirmation from peer */
1172	dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_CONFIRM,
1173	    input_userauth_jpake_server_confirm);
1174}
1175
1176/* ARGSUSED */
1177void
1178input_userauth_jpake_server_confirm(int type, u_int32_t seq, void *ctxt)
1179{
1180	Authctxt *authctxt = ctxt;
1181	struct jpake_ctx *pctx = authctxt->methoddata;
1182
1183	/* Disable this message */
1184	dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_CONFIRM, NULL);
1185
1186	pctx->h_k_sid_sessid = packet_get_string(&pctx->h_k_sid_sessid_len);
1187	packet_check_eom();
1188
1189	JPAKE_DEBUG_CTX((pctx, "confirm received in %s", __func__));
1190
1191	/* Verify expected confirmation hash */
1192	if (jpake_check_confirm(pctx->k,
1193	    pctx->server_id, pctx->server_id_len,
1194	    session_id2, session_id2_len,
1195	    pctx->h_k_sid_sessid, pctx->h_k_sid_sessid_len) == 1)
1196		debug("%s: %s success", __func__, authctxt->method->name);
1197	else {
1198		debug("%s: confirmation mismatch", __func__);
1199		/* XXX stash this so if auth succeeds then we can warn/kill */
1200	}
1201
1202	userauth_jpake_cleanup(authctxt);
1203}
1204#endif /* JPAKE */
1205
1206static int
1207identity_sign(Identity *id, u_char **sigp, u_int *lenp,
1208    u_char *data, u_int datalen)
1209{
1210	Key *prv;
1211	int ret;
1212
1213	/* the agent supports this key */
1214	if (id->ac)
1215		return (ssh_agent_sign(id->ac, id->key, sigp, lenp,
1216		    data, datalen));
1217	/*
1218	 * we have already loaded the private key or
1219	 * the private key is stored in external hardware
1220	 */
1221	if (id->isprivate || (id->key->flags & KEY_FLAG_EXT))
1222		return (key_sign(id->key, sigp, lenp, data, datalen));
1223	/* load the private key from the file */
1224	if ((prv = load_identity_file(id->filename, id->userprovided)) == NULL)
1225		return (-1);
1226	ret = key_sign(prv, sigp, lenp, data, datalen);
1227	key_free(prv);
1228	return (ret);
1229}
1230
1231static int
1232sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1233{
1234	Buffer b;
1235	u_char *blob, *signature;
1236	u_int bloblen, slen;
1237	u_int skip = 0;
1238	int ret = -1;
1239	int have_sig = 1;
1240	char *fp;
1241
1242	fp = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
1243	debug3("sign_and_send_pubkey: %s %s", key_type(id->key), fp);
1244	free(fp);
1245
1246	if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1247		/* we cannot handle this key */
1248		debug3("sign_and_send_pubkey: cannot handle key");
1249		return 0;
1250	}
1251	/* data to be signed */
1252	buffer_init(&b);
1253	if (datafellows & SSH_OLD_SESSIONID) {
1254		buffer_append(&b, session_id2, session_id2_len);
1255		skip = session_id2_len;
1256	} else {
1257		buffer_put_string(&b, session_id2, session_id2_len);
1258		skip = buffer_len(&b);
1259	}
1260	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1261	buffer_put_cstring(&b, authctxt->server_user);
1262	buffer_put_cstring(&b,
1263	    datafellows & SSH_BUG_PKSERVICE ?
1264	    "ssh-userauth" :
1265	    authctxt->service);
1266	if (datafellows & SSH_BUG_PKAUTH) {
1267		buffer_put_char(&b, have_sig);
1268	} else {
1269		buffer_put_cstring(&b, authctxt->method->name);
1270		buffer_put_char(&b, have_sig);
1271		buffer_put_cstring(&b, key_ssh_name(id->key));
1272	}
1273	buffer_put_string(&b, blob, bloblen);
1274
1275	/* generate signature */
1276	ret = identity_sign(id, &signature, &slen,
1277	    buffer_ptr(&b), buffer_len(&b));
1278	if (ret == -1) {
1279		free(blob);
1280		buffer_free(&b);
1281		return 0;
1282	}
1283#ifdef DEBUG_PK
1284	buffer_dump(&b);
1285#endif
1286	if (datafellows & SSH_BUG_PKSERVICE) {
1287		buffer_clear(&b);
1288		buffer_append(&b, session_id2, session_id2_len);
1289		skip = session_id2_len;
1290		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1291		buffer_put_cstring(&b, authctxt->server_user);
1292		buffer_put_cstring(&b, authctxt->service);
1293		buffer_put_cstring(&b, authctxt->method->name);
1294		buffer_put_char(&b, have_sig);
1295		if (!(datafellows & SSH_BUG_PKAUTH))
1296			buffer_put_cstring(&b, key_ssh_name(id->key));
1297		buffer_put_string(&b, blob, bloblen);
1298	}
1299	free(blob);
1300
1301	/* append signature */
1302	buffer_put_string(&b, signature, slen);
1303	free(signature);
1304
1305	/* skip session id and packet type */
1306	if (buffer_len(&b) < skip + 1)
1307		fatal("userauth_pubkey: internal error");
1308	buffer_consume(&b, skip + 1);
1309
1310	/* put remaining data from buffer into packet */
1311	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1312	packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1313	buffer_free(&b);
1314	packet_send();
1315
1316	return 1;
1317}
1318
1319static int
1320send_pubkey_test(Authctxt *authctxt, Identity *id)
1321{
1322	u_char *blob;
1323	u_int bloblen, have_sig = 0;
1324
1325	debug3("send_pubkey_test");
1326
1327	if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1328		/* we cannot handle this key */
1329		debug3("send_pubkey_test: cannot handle key");
1330		return 0;
1331	}
1332	/* register callback for USERAUTH_PK_OK message */
1333	dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1334
1335	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1336	packet_put_cstring(authctxt->server_user);
1337	packet_put_cstring(authctxt->service);
1338	packet_put_cstring(authctxt->method->name);
1339	packet_put_char(have_sig);
1340	if (!(datafellows & SSH_BUG_PKAUTH))
1341		packet_put_cstring(key_ssh_name(id->key));
1342	packet_put_string(blob, bloblen);
1343	free(blob);
1344	packet_send();
1345	return 1;
1346}
1347
1348static Key *
1349load_identity_file(char *filename, int userprovided)
1350{
1351	Key *private;
1352	char prompt[300], *passphrase;
1353	int perm_ok = 0, quit, i;
1354	struct stat st;
1355
1356	if (stat(filename, &st) < 0) {
1357		(userprovided ? logit : debug3)("no such identity: %s: %s",
1358		    filename, strerror(errno));
1359		return NULL;
1360	}
1361	private = key_load_private_type(KEY_UNSPEC, filename, "", NULL, &perm_ok);
1362	if (!perm_ok) {
1363		if (private != NULL)
1364			key_free(private);
1365		return NULL;
1366	}
1367	if (private == NULL) {
1368		if (options.batch_mode)
1369			return NULL;
1370		snprintf(prompt, sizeof prompt,
1371		    "Enter passphrase for key '%.100s': ", filename);
1372		for (i = 0; i < options.number_of_password_prompts; i++) {
1373			passphrase = read_passphrase(prompt, 0);
1374			if (strcmp(passphrase, "") != 0) {
1375				private = key_load_private_type(KEY_UNSPEC,
1376				    filename, passphrase, NULL, NULL);
1377				quit = 0;
1378			} else {
1379				debug2("no passphrase given, try next key");
1380				quit = 1;
1381			}
1382			memset(passphrase, 0, strlen(passphrase));
1383			free(passphrase);
1384			if (private != NULL || quit)
1385				break;
1386			debug2("bad passphrase given, try again...");
1387		}
1388	}
1389	return private;
1390}
1391
1392/*
1393 * try keys in the following order:
1394 *	1. agent keys that are found in the config file
1395 *	2. other agent keys
1396 *	3. keys that are only listed in the config file
1397 */
1398static void
1399pubkey_prepare(Authctxt *authctxt)
1400{
1401	Identity *id, *id2, *tmp;
1402	Idlist agent, files, *preferred;
1403	Key *key;
1404	AuthenticationConnection *ac;
1405	char *comment;
1406	int i, found;
1407
1408	TAILQ_INIT(&agent);	/* keys from the agent */
1409	TAILQ_INIT(&files);	/* keys from the config file */
1410	preferred = &authctxt->keys;
1411	TAILQ_INIT(preferred);	/* preferred order of keys */
1412
1413	/* list of keys stored in the filesystem and PKCS#11 */
1414	for (i = 0; i < options.num_identity_files; i++) {
1415		key = options.identity_keys[i];
1416		if (key && key->type == KEY_RSA1)
1417			continue;
1418		if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1419			continue;
1420		options.identity_keys[i] = NULL;
1421		id = xcalloc(1, sizeof(*id));
1422		id->key = key;
1423		id->filename = xstrdup(options.identity_files[i]);
1424		id->userprovided = options.identity_file_userprovided[i];
1425		TAILQ_INSERT_TAIL(&files, id, next);
1426	}
1427	/* Prefer PKCS11 keys that are explicitly listed */
1428	TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1429		if (id->key == NULL || (id->key->flags & KEY_FLAG_EXT) == 0)
1430			continue;
1431		found = 0;
1432		TAILQ_FOREACH(id2, &files, next) {
1433			if (id2->key == NULL ||
1434			    (id2->key->flags & KEY_FLAG_EXT) != 0)
1435				continue;
1436			if (key_equal(id->key, id2->key)) {
1437				TAILQ_REMOVE(&files, id, next);
1438				TAILQ_INSERT_TAIL(preferred, id, next);
1439				found = 1;
1440				break;
1441			}
1442		}
1443		/* If IdentitiesOnly set and key not found then don't use it */
1444		if (!found && options.identities_only) {
1445			TAILQ_REMOVE(&files, id, next);
1446			bzero(id, sizeof(*id));
1447			free(id);
1448		}
1449	}
1450	/* list of keys supported by the agent */
1451	if ((ac = ssh_get_authentication_connection())) {
1452		for (key = ssh_get_first_identity(ac, &comment, 2);
1453		    key != NULL;
1454		    key = ssh_get_next_identity(ac, &comment, 2)) {
1455			found = 0;
1456			TAILQ_FOREACH(id, &files, next) {
1457				/* agent keys from the config file are preferred */
1458				if (key_equal(key, id->key)) {
1459					key_free(key);
1460					free(comment);
1461					TAILQ_REMOVE(&files, id, next);
1462					TAILQ_INSERT_TAIL(preferred, id, next);
1463					id->ac = ac;
1464					found = 1;
1465					break;
1466				}
1467			}
1468			if (!found && !options.identities_only) {
1469				id = xcalloc(1, sizeof(*id));
1470				id->key = key;
1471				id->filename = comment;
1472				id->ac = ac;
1473				TAILQ_INSERT_TAIL(&agent, id, next);
1474			}
1475		}
1476		/* append remaining agent keys */
1477		for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1478			TAILQ_REMOVE(&agent, id, next);
1479			TAILQ_INSERT_TAIL(preferred, id, next);
1480		}
1481		authctxt->agent = ac;
1482	}
1483	/* append remaining keys from the config file */
1484	for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1485		TAILQ_REMOVE(&files, id, next);
1486		TAILQ_INSERT_TAIL(preferred, id, next);
1487	}
1488	TAILQ_FOREACH(id, preferred, next) {
1489		debug2("key: %s (%p),%s", id->filename, id->key,
1490		    id->userprovided ? " explicit" : "");
1491	}
1492}
1493
1494static void
1495pubkey_cleanup(Authctxt *authctxt)
1496{
1497	Identity *id;
1498
1499	if (authctxt->agent != NULL)
1500		ssh_close_authentication_connection(authctxt->agent);
1501	for (id = TAILQ_FIRST(&authctxt->keys); id;
1502	    id = TAILQ_FIRST(&authctxt->keys)) {
1503		TAILQ_REMOVE(&authctxt->keys, id, next);
1504		if (id->key)
1505			key_free(id->key);
1506		free(id->filename);
1507		free(id);
1508	}
1509}
1510
1511int
1512userauth_pubkey(Authctxt *authctxt)
1513{
1514	Identity *id;
1515	int sent = 0;
1516
1517	while ((id = TAILQ_FIRST(&authctxt->keys))) {
1518		if (id->tried++)
1519			return (0);
1520		/* move key to the end of the queue */
1521		TAILQ_REMOVE(&authctxt->keys, id, next);
1522		TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1523		/*
1524		 * send a test message if we have the public key. for
1525		 * encrypted keys we cannot do this and have to load the
1526		 * private key instead
1527		 */
1528		if (id->key != NULL) {
1529			if (key_type_plain(id->key->type) == KEY_RSA &&
1530			    (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1531				debug("Skipped %s key %s for RSA/MD5 server",
1532				    key_type(id->key), id->filename);
1533			} else if (id->key->type != KEY_RSA1) {
1534				debug("Offering %s public key: %s",
1535				    key_type(id->key), id->filename);
1536				sent = send_pubkey_test(authctxt, id);
1537			}
1538		} else {
1539			debug("Trying private key: %s", id->filename);
1540			id->key = load_identity_file(id->filename,
1541			    id->userprovided);
1542			if (id->key != NULL) {
1543				id->isprivate = 1;
1544				if (key_type_plain(id->key->type) == KEY_RSA &&
1545				    (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1546					debug("Skipped %s key %s for RSA/MD5 "
1547					    "server", key_type(id->key),
1548					    id->filename);
1549				} else {
1550					sent = sign_and_send_pubkey(
1551					    authctxt, id);
1552				}
1553				key_free(id->key);
1554				id->key = NULL;
1555			}
1556		}
1557		if (sent)
1558			return (sent);
1559	}
1560	return (0);
1561}
1562
1563/*
1564 * Send userauth request message specifying keyboard-interactive method.
1565 */
1566int
1567userauth_kbdint(Authctxt *authctxt)
1568{
1569	static int attempt = 0;
1570
1571	if (attempt++ >= options.number_of_password_prompts)
1572		return 0;
1573	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1574	if (attempt > 1 && !authctxt->info_req_seen) {
1575		debug3("userauth_kbdint: disable: no info_req_seen");
1576		dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1577		return 0;
1578	}
1579
1580	debug2("userauth_kbdint");
1581	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1582	packet_put_cstring(authctxt->server_user);
1583	packet_put_cstring(authctxt->service);
1584	packet_put_cstring(authctxt->method->name);
1585	packet_put_cstring("");					/* lang */
1586	packet_put_cstring(options.kbd_interactive_devices ?
1587	    options.kbd_interactive_devices : "");
1588	packet_send();
1589
1590	dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1591	return 1;
1592}
1593
1594/*
1595 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1596 */
1597void
1598input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1599{
1600	Authctxt *authctxt = ctxt;
1601	char *name, *inst, *lang, *prompt, *response;
1602	u_int num_prompts, i;
1603	int echo = 0;
1604
1605	debug2("input_userauth_info_req");
1606
1607	if (authctxt == NULL)
1608		fatal("input_userauth_info_req: no authentication context");
1609
1610	authctxt->info_req_seen = 1;
1611
1612	name = packet_get_string(NULL);
1613	inst = packet_get_string(NULL);
1614	lang = packet_get_string(NULL);
1615	if (strlen(name) > 0)
1616		logit("%s", name);
1617	if (strlen(inst) > 0)
1618		logit("%s", inst);
1619	free(name);
1620	free(inst);
1621	free(lang);
1622
1623	num_prompts = packet_get_int();
1624	/*
1625	 * Begin to build info response packet based on prompts requested.
1626	 * We commit to providing the correct number of responses, so if
1627	 * further on we run into a problem that prevents this, we have to
1628	 * be sure and clean this up and send a correct error response.
1629	 */
1630	packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1631	packet_put_int(num_prompts);
1632
1633	debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1634	for (i = 0; i < num_prompts; i++) {
1635		prompt = packet_get_string(NULL);
1636		echo = packet_get_char();
1637
1638		response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1639
1640		packet_put_cstring(response);
1641		memset(response, 0, strlen(response));
1642		free(response);
1643		free(prompt);
1644	}
1645	packet_check_eom(); /* done with parsing incoming message. */
1646
1647	packet_add_padding(64);
1648	packet_send();
1649}
1650
1651static int
1652ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
1653    u_char *data, u_int datalen)
1654{
1655	Buffer b;
1656	struct stat st;
1657	pid_t pid;
1658	int to[2], from[2], status, version = 2;
1659
1660	debug2("ssh_keysign called");
1661
1662	if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1663		error("ssh_keysign: not installed: %s", strerror(errno));
1664		return -1;
1665	}
1666	if (fflush(stdout) != 0)
1667		error("ssh_keysign: fflush: %s", strerror(errno));
1668	if (pipe(to) < 0) {
1669		error("ssh_keysign: pipe: %s", strerror(errno));
1670		return -1;
1671	}
1672	if (pipe(from) < 0) {
1673		error("ssh_keysign: pipe: %s", strerror(errno));
1674		return -1;
1675	}
1676	if ((pid = fork()) < 0) {
1677		error("ssh_keysign: fork: %s", strerror(errno));
1678		return -1;
1679	}
1680	if (pid == 0) {
1681		/* keep the socket on exec */
1682		fcntl(packet_get_connection_in(), F_SETFD, 0);
1683		permanently_drop_suid(getuid());
1684		close(from[0]);
1685		if (dup2(from[1], STDOUT_FILENO) < 0)
1686			fatal("ssh_keysign: dup2: %s", strerror(errno));
1687		close(to[1]);
1688		if (dup2(to[0], STDIN_FILENO) < 0)
1689			fatal("ssh_keysign: dup2: %s", strerror(errno));
1690		close(from[1]);
1691		close(to[0]);
1692		execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
1693		fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
1694		    strerror(errno));
1695	}
1696	close(from[1]);
1697	close(to[0]);
1698
1699	buffer_init(&b);
1700	buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
1701	buffer_put_string(&b, data, datalen);
1702	if (ssh_msg_send(to[1], version, &b) == -1)
1703		fatal("ssh_keysign: couldn't send request");
1704
1705	if (ssh_msg_recv(from[0], &b) < 0) {
1706		error("ssh_keysign: no reply");
1707		buffer_free(&b);
1708		return -1;
1709	}
1710	close(from[0]);
1711	close(to[1]);
1712
1713	while (waitpid(pid, &status, 0) < 0)
1714		if (errno != EINTR)
1715			break;
1716
1717	if (buffer_get_char(&b) != version) {
1718		error("ssh_keysign: bad version");
1719		buffer_free(&b);
1720		return -1;
1721	}
1722	*sigp = buffer_get_string(&b, lenp);
1723	buffer_free(&b);
1724
1725	return 0;
1726}
1727
1728int
1729userauth_hostbased(Authctxt *authctxt)
1730{
1731	Key *private = NULL;
1732	Sensitive *sensitive = authctxt->sensitive;
1733	Buffer b;
1734	u_char *signature, *blob;
1735	char *chost, *pkalg, *p;
1736	const char *service;
1737	u_int blen, slen;
1738	int ok, i, found = 0;
1739
1740	/* check for a useful key */
1741	for (i = 0; i < sensitive->nkeys; i++) {
1742		private = sensitive->keys[i];
1743		if (private && private->type != KEY_RSA1) {
1744			found = 1;
1745			/* we take and free the key */
1746			sensitive->keys[i] = NULL;
1747			break;
1748		}
1749	}
1750	if (!found) {
1751		debug("No more client hostkeys for hostbased authentication.");
1752		return 0;
1753	}
1754	if (key_to_blob(private, &blob, &blen) == 0) {
1755		key_free(private);
1756		return 0;
1757	}
1758	/* figure out a name for the client host */
1759	p = get_local_name(packet_get_connection_in());
1760	if (p == NULL) {
1761		error("userauth_hostbased: cannot get local ipaddr/name");
1762		key_free(private);
1763		free(blob);
1764		return 0;
1765	}
1766	xasprintf(&chost, "%s.", p);
1767	debug2("userauth_hostbased: chost %s", chost);
1768	free(p);
1769
1770	service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1771	    authctxt->service;
1772	pkalg = xstrdup(key_ssh_name(private));
1773	buffer_init(&b);
1774	/* construct data */
1775	buffer_put_string(&b, session_id2, session_id2_len);
1776	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1777	buffer_put_cstring(&b, authctxt->server_user);
1778	buffer_put_cstring(&b, service);
1779	buffer_put_cstring(&b, authctxt->method->name);
1780	buffer_put_cstring(&b, pkalg);
1781	buffer_put_string(&b, blob, blen);
1782	buffer_put_cstring(&b, chost);
1783	buffer_put_cstring(&b, authctxt->local_user);
1784#ifdef DEBUG_PK
1785	buffer_dump(&b);
1786#endif
1787	if (sensitive->external_keysign)
1788		ok = ssh_keysign(private, &signature, &slen,
1789		    buffer_ptr(&b), buffer_len(&b));
1790	else
1791		ok = key_sign(private, &signature, &slen,
1792		    buffer_ptr(&b), buffer_len(&b));
1793	key_free(private);
1794	buffer_free(&b);
1795	if (ok != 0) {
1796		error("key_sign failed");
1797		free(chost);
1798		free(pkalg);
1799		free(blob);
1800		return 0;
1801	}
1802	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1803	packet_put_cstring(authctxt->server_user);
1804	packet_put_cstring(authctxt->service);
1805	packet_put_cstring(authctxt->method->name);
1806	packet_put_cstring(pkalg);
1807	packet_put_string(blob, blen);
1808	packet_put_cstring(chost);
1809	packet_put_cstring(authctxt->local_user);
1810	packet_put_string(signature, slen);
1811	memset(signature, 's', slen);
1812	free(signature);
1813	free(chost);
1814	free(pkalg);
1815	free(blob);
1816
1817	packet_send();
1818	return 1;
1819}
1820
1821#ifdef JPAKE
1822int
1823userauth_jpake(Authctxt *authctxt)
1824{
1825	struct jpake_ctx *pctx;
1826	u_char *x1_proof, *x2_proof;
1827	u_int x1_proof_len, x2_proof_len;
1828	static int attempt = 0; /* XXX share with userauth_password's? */
1829
1830	if (attempt++ >= options.number_of_password_prompts)
1831		return 0;
1832	if (attempt != 1)
1833		error("Permission denied, please try again.");
1834
1835	if (authctxt->methoddata != NULL)
1836		fatal("%s: authctxt->methoddata already set (%p)",
1837		    __func__, authctxt->methoddata);
1838
1839	authctxt->methoddata = pctx = jpake_new();
1840
1841	/*
1842	 * Send request immediately, to get the protocol going while
1843	 * we do the initial computations.
1844	 */
1845	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1846	packet_put_cstring(authctxt->server_user);
1847	packet_put_cstring(authctxt->service);
1848	packet_put_cstring(authctxt->method->name);
1849	packet_send();
1850	packet_write_wait();
1851
1852	jpake_step1(pctx->grp,
1853	    &pctx->client_id, &pctx->client_id_len,
1854	    &pctx->x1, &pctx->x2, &pctx->g_x1, &pctx->g_x2,
1855	    &x1_proof, &x1_proof_len,
1856	    &x2_proof, &x2_proof_len);
1857
1858	JPAKE_DEBUG_CTX((pctx, "step 1 sending in %s", __func__));
1859
1860	packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_STEP1);
1861	packet_put_string(pctx->client_id, pctx->client_id_len);
1862	packet_put_bignum2(pctx->g_x1);
1863	packet_put_bignum2(pctx->g_x2);
1864	packet_put_string(x1_proof, x1_proof_len);
1865	packet_put_string(x2_proof, x2_proof_len);
1866	packet_send();
1867
1868	bzero(x1_proof, x1_proof_len);
1869	bzero(x2_proof, x2_proof_len);
1870	free(x1_proof);
1871	free(x2_proof);
1872
1873	/* Expect step 1 packet from peer */
1874	dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP1,
1875	    input_userauth_jpake_server_step1);
1876	dispatch_set(SSH2_MSG_USERAUTH_SUCCESS,
1877	    &input_userauth_success_unexpected);
1878
1879	return 1;
1880}
1881
1882void
1883userauth_jpake_cleanup(Authctxt *authctxt)
1884{
1885	debug3("%s: clean up", __func__);
1886	if (authctxt->methoddata != NULL) {
1887		jpake_free(authctxt->methoddata);
1888		authctxt->methoddata = NULL;
1889	}
1890	dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
1891}
1892#endif /* JPAKE */
1893
1894/* find auth method */
1895
1896/*
1897 * given auth method name, if configurable options permit this method fill
1898 * in auth_ident field and return true, otherwise return false.
1899 */
1900static int
1901authmethod_is_enabled(Authmethod *method)
1902{
1903	if (method == NULL)
1904		return 0;
1905	/* return false if options indicate this method is disabled */
1906	if  (method->enabled == NULL || *method->enabled == 0)
1907		return 0;
1908	/* return false if batch mode is enabled but method needs interactive mode */
1909	if  (method->batch_flag != NULL && *method->batch_flag != 0)
1910		return 0;
1911	return 1;
1912}
1913
1914static Authmethod *
1915authmethod_lookup(const char *name)
1916{
1917	Authmethod *method = NULL;
1918	if (name != NULL)
1919		for (method = authmethods; method->name != NULL; method++)
1920			if (strcmp(name, method->name) == 0)
1921				return method;
1922	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1923	return NULL;
1924}
1925
1926/* XXX internal state */
1927static Authmethod *current = NULL;
1928static char *supported = NULL;
1929static char *preferred = NULL;
1930
1931/*
1932 * Given the authentication method list sent by the server, return the
1933 * next method we should try.  If the server initially sends a nil list,
1934 * use a built-in default list.
1935 */
1936static Authmethod *
1937authmethod_get(char *authlist)
1938{
1939	char *name = NULL;
1940	u_int next;
1941
1942	/* Use a suitable default if we're passed a nil list.  */
1943	if (authlist == NULL || strlen(authlist) == 0)
1944		authlist = options.preferred_authentications;
1945
1946	if (supported == NULL || strcmp(authlist, supported) != 0) {
1947		debug3("start over, passed a different list %s", authlist);
1948		free(supported);
1949		supported = xstrdup(authlist);
1950		preferred = options.preferred_authentications;
1951		debug3("preferred %s", preferred);
1952		current = NULL;
1953	} else if (current != NULL && authmethod_is_enabled(current))
1954		return current;
1955
1956	for (;;) {
1957		if ((name = match_list(preferred, supported, &next)) == NULL) {
1958			debug("No more authentication methods to try.");
1959			current = NULL;
1960			return NULL;
1961		}
1962		preferred += next;
1963		debug3("authmethod_lookup %s", name);
1964		debug3("remaining preferred: %s", preferred);
1965		if ((current = authmethod_lookup(name)) != NULL &&
1966		    authmethod_is_enabled(current)) {
1967			debug3("authmethod_is_enabled %s", name);
1968			debug("Next authentication method: %s", name);
1969			free(name);
1970			return current;
1971		}
1972		free(name);
1973	}
1974}
1975
1976static char *
1977authmethods_get(void)
1978{
1979	Authmethod *method = NULL;
1980	Buffer b;
1981	char *list;
1982
1983	buffer_init(&b);
1984	for (method = authmethods; method->name != NULL; method++) {
1985		if (authmethod_is_enabled(method)) {
1986			if (buffer_len(&b) > 0)
1987				buffer_append(&b, ",", 1);
1988			buffer_append(&b, method->name, strlen(method->name));
1989		}
1990	}
1991	buffer_append(&b, "\0", 1);
1992	list = xstrdup(buffer_ptr(&b));
1993	buffer_free(&b);
1994	return list;
1995}
1996
1997