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