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