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