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