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