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