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