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