xref: /netbsd-src/crypto/external/bsd/openssh/dist/sshconnect2.c (revision d16b7486a53dcb8072b60ec6fcb4373a2d0c27b7)
1 /*	$NetBSD: sshconnect2.c,v 1.44 2023/07/26 17:58:16 christos Exp $	*/
2 /* $OpenBSD: sshconnect2.c,v 1.366 2023/03/09 07:11:05 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.44 2023/07/26 17:58:16 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 <limits.h>
39 #include <netdb.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <stdarg.h>
43 #include <signal.h>
44 #include <pwd.h>
45 #include <unistd.h>
46 #include <vis.h>
47 
48 #ifdef KRB5
49 #include <krb5.h>
50 #endif
51 
52 #include "xmalloc.h"
53 #include "ssh.h"
54 #include "ssh2.h"
55 #include "sshbuf.h"
56 #include "packet.h"
57 #include "compat.h"
58 #include "cipher.h"
59 #include "sshkey.h"
60 #include "kex.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 #include "ssh-sk.h"
78 #include "sk-api.h"
79 /* XXX */
80 struct sshauthopt *auth_opts;
81 const char     *auth_get_canonical_hostname(struct ssh *, int);
82 
83 #ifdef GSSAPI
84 #include "ssh-gss.h"
85 #endif
86 #ifdef KRB5
87 static int userauth_kerberos(struct ssh *);
88 #endif
89 
90 /* import */
91 extern char *client_version_string;
92 extern char *server_version_string;
93 extern Options options;
94 
95 /* tty_flag is set in ssh.c. use this in ssh_userauth2 */
96 /* if it is set then prevent the switch to the null cipher */
97 
98 extern int tty_flag;
99 
100 /*
101  * SSH2 key exchange
102  */
103 
104 static char *xxx_host;
105 static struct sockaddr *xxx_hostaddr;
106 static const struct ssh_conn_info *xxx_conn_info;
107 
108 static int
109 verify_host_key_callback(struct sshkey *hostkey, struct ssh *ssh)
110 {
111 	int r;
112 
113 	if ((r = sshkey_check_rsa_length(hostkey,
114 	    options.required_rsa_size)) != 0)
115 		fatal_r(r, "Bad server host key");
116 	if (verify_host_key(xxx_host, xxx_hostaddr, hostkey,
117 	    xxx_conn_info) == -1)
118 		fatal("Host key verification failed.");
119 	return 0;
120 }
121 
122 /* Returns the first item from a comma-separated algorithm list */
123 static char *
124 first_alg(const char *algs)
125 {
126 	char *ret, *cp;
127 
128 	ret = xstrdup(algs);
129 	if ((cp = strchr(ret, ',')) != NULL)
130 		*cp = '\0';
131 	return ret;
132 }
133 
134 static char *
135 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port,
136     const struct ssh_conn_info *cinfo)
137 {
138 	char *oavail = NULL, *avail = NULL, *first = NULL, *last = NULL;
139 	char *alg = NULL, *hostname = NULL, *ret = NULL, *best = NULL;
140 	size_t maxlen;
141 	struct hostkeys *hostkeys = NULL;
142 	int ktype;
143 	u_int i;
144 
145 	/* Find all hostkeys for this hostname */
146 	get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
147 	hostkeys = init_hostkeys();
148 	for (i = 0; i < options.num_user_hostfiles; i++)
149 		load_hostkeys(hostkeys, hostname, options.user_hostfiles[i], 0);
150 	for (i = 0; i < options.num_system_hostfiles; i++) {
151 		load_hostkeys(hostkeys, hostname,
152 		    options.system_hostfiles[i], 0);
153 	}
154 	if (options.known_hosts_command != NULL) {
155 		load_hostkeys_command(hostkeys, options.known_hosts_command,
156 		    "ORDER", cinfo, NULL, host);
157 	}
158 	/*
159 	 * If a plain public key exists that matches the type of the best
160 	 * preference HostkeyAlgorithms, then use the whole list as is.
161 	 * Note that we ignore whether the best preference algorithm is a
162 	 * certificate type, as sshconnect.c will downgrade certs to
163 	 * plain keys if necessary.
164 	 */
165 	best = first_alg(options.hostkeyalgorithms);
166 	if (lookup_key_in_hostkeys_by_type(hostkeys,
167 	    sshkey_type_plain(sshkey_type_from_name(best)),
168 	    sshkey_ecdsa_nid_from_name(best), NULL)) {
169 		debug3_f("have matching best-preference key type %s, "
170 		    "using HostkeyAlgorithms verbatim", best);
171 		ret = xstrdup(options.hostkeyalgorithms);
172 		goto out;
173 	}
174 
175 	/*
176 	 * Otherwise, prefer the host key algorithms that match known keys
177 	 * while keeping the ordering of HostkeyAlgorithms as much as possible.
178 	 */
179 	oavail = avail = xstrdup(options.hostkeyalgorithms);
180 	maxlen = strlen(avail) + 1;
181 	first = xmalloc(maxlen);
182 	last = xmalloc(maxlen);
183 	*first = *last = '\0';
184 
185 #define ALG_APPEND(to, from) \
186 	do { \
187 		if (*to != '\0') \
188 			strlcat(to, ",", maxlen); \
189 		strlcat(to, from, maxlen); \
190 	} while (0)
191 
192 	while ((alg = strsep(&avail, ",")) && *alg != '\0') {
193 		if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
194 			fatal_f("unknown alg %s", alg);
195 		/*
196 		 * If we have a @cert-authority marker in known_hosts then
197 		 * prefer all certificate algorithms.
198 		 */
199 		if (sshkey_type_is_cert(ktype) &&
200 		    lookup_marker_in_hostkeys(hostkeys, MRK_CA)) {
201 			ALG_APPEND(first, alg);
202 			continue;
203 		}
204 		/* If the key appears in known_hosts then prefer it */
205 		if (lookup_key_in_hostkeys_by_type(hostkeys,
206 		    sshkey_type_plain(ktype),
207 		    sshkey_ecdsa_nid_from_name(alg), NULL)) {
208 			ALG_APPEND(first, alg);
209 			continue;
210 		}
211 		/* Otherwise, put it last */
212 		ALG_APPEND(last, alg);
213 	}
214 #undef ALG_APPEND
215 	xasprintf(&ret, "%s%s%s", first,
216 	    (*first == '\0' || *last == '\0') ? "" : ",", last);
217 	if (*first != '\0')
218 		debug3_f("prefer hostkeyalgs: %s", first);
219 	else
220 		debug3_f("no algorithms matched; accept original");
221  out:
222 	free(best);
223 	free(first);
224 	free(last);
225 	free(hostname);
226 	free(oavail);
227 	free_hostkeys(hostkeys);
228 
229 	return ret;
230 }
231 
232 void
233 ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port,
234     const struct ssh_conn_info *cinfo)
235 {
236 	char *myproposal[PROPOSAL_MAX];
237 	char *s, *all_key, *hkalgs = NULL;
238 	int r, use_known_hosts_order = 0;
239 
240 	xxx_host = host;
241 	xxx_hostaddr = hostaddr;
242 	xxx_conn_info = cinfo;
243 
244 	if (options.rekey_limit || options.rekey_interval)
245 		ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
246 		    options.rekey_interval);
247 
248 	/*
249 	 * If the user has not specified HostkeyAlgorithms, or has only
250 	 * appended or removed algorithms from that list then prefer algorithms
251 	 * that are in the list that are supported by known_hosts keys.
252 	 */
253 	if (options.hostkeyalgorithms == NULL ||
254 	    options.hostkeyalgorithms[0] == '-' ||
255 	    options.hostkeyalgorithms[0] == '+')
256 		use_known_hosts_order = 1;
257 
258 	/* Expand or fill in HostkeyAlgorithms */
259 	all_key = sshkey_alg_list(0, 0, 1, ',');
260 	if ((r = kex_assemble_names(&options.hostkeyalgorithms,
261 	    kex_default_pk_alg(), all_key)) != 0)
262 		fatal_fr(r, "kex_assemble_namelist");
263 	free(all_key);
264 
265 	if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
266 		fatal_f("kex_names_cat");
267 
268 	if (use_known_hosts_order)
269 		hkalgs = order_hostkeyalgs(host, hostaddr, port, cinfo);
270 
271 	kex_proposal_populate_entries(ssh, myproposal, s, options.ciphers,
272 	    options.macs, compression_alg_list(options.compression),
273 	    hkalgs ? hkalgs : options.hostkeyalgorithms);
274 
275 	free(hkalgs);
276 
277 	/* start key exchange */
278 	if ((r = kex_setup(ssh, myproposal)) != 0)
279 		fatal_r(r, "kex_setup");
280 #ifdef WITH_OPENSSL
281 	ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
282 	ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
283 	ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
284 	ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
285 	ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
286 	ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
287 	ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
288 	ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
289 #endif
290 	ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
291 	ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
292 	ssh->kex->verify_host_key=&verify_host_key_callback;
293 
294 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &ssh->kex->done);
295 
296 	/* remove ext-info from the KEX proposals for rekeying */
297 	free(myproposal[PROPOSAL_KEX_ALGS]);
298 	myproposal[PROPOSAL_KEX_ALGS] =
299 	    compat_kex_proposal(ssh, options.kex_algorithms);
300 	if ((r = kex_prop2buf(ssh->kex->my, myproposal)) != 0)
301 		fatal_r(r, "kex_prop2buf");
302 
303 #ifdef DEBUG_KEXDH
304 	/* send 1st encrypted/maced/compressed message */
305 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
306 	    (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
307 	    (r = sshpkt_send(ssh)) != 0 ||
308 	    (r = ssh_packet_write_wait(ssh)) < 0)
309 		fatal_fr(r, "send packet");
310 #endif
311 	kex_proposal_free_entries(myproposal);
312 }
313 
314 /*
315  * Authenticate user
316  */
317 
318 typedef struct cauthctxt Authctxt;
319 typedef struct cauthmethod Authmethod;
320 typedef struct identity Identity;
321 typedef struct idlist Idlist;
322 
323 struct identity {
324 	TAILQ_ENTRY(identity) next;
325 	int	agent_fd;		/* >=0 if agent supports key */
326 	struct sshkey	*key;		/* public/private key */
327 	char	*filename;		/* comment for agent-only keys */
328 	int	tried;
329 	int	isprivate;		/* key points to the private key */
330 	int	userprovided;
331 };
332 TAILQ_HEAD(idlist, identity);
333 
334 struct cauthctxt {
335 	const char *server_user;
336 	const char *local_user;
337 	const char *host;
338 	const char *service;
339 	struct cauthmethod *method;
340 	sig_atomic_t success;
341 	char *authlist;
342 #ifdef GSSAPI
343 	/* gssapi */
344 	gss_OID_set gss_supported_mechs;
345 	u_int mech_tried;
346 #endif
347 	/* pubkey */
348 	struct idlist keys;
349 	int agent_fd;
350 	/* hostbased */
351 	Sensitive *sensitive;
352 	char *oktypes, *ktypes;
353 	const char *active_ktype;
354 	/* kbd-interactive */
355 	int info_req_seen;
356 	int attempt_kbdint;
357 	/* password */
358 	int attempt_passwd;
359 	/* generic */
360 	void *methoddata;
361 };
362 
363 struct cauthmethod {
364 	const char	*name;	/* string to compare against server's list */
365 	int	(*userauth)(struct ssh *ssh);
366 	void	(*cleanup)(struct ssh *ssh);
367 	int	*enabled;	/* flag in option struct that enables method */
368 	int	*batch_flag;	/* flag in option struct that disables method */
369 };
370 
371 static int input_userauth_service_accept(int, u_int32_t, struct ssh *);
372 static int input_userauth_ext_info(int, u_int32_t, struct ssh *);
373 static int input_userauth_success(int, u_int32_t, struct ssh *);
374 static int input_userauth_failure(int, u_int32_t, struct ssh *);
375 static int input_userauth_banner(int, u_int32_t, struct ssh *);
376 static int input_userauth_error(int, u_int32_t, struct ssh *);
377 static int input_userauth_info_req(int, u_int32_t, struct ssh *);
378 static int input_userauth_pk_ok(int, u_int32_t, struct ssh *);
379 static int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *);
380 
381 static int userauth_none(struct ssh *);
382 static int userauth_pubkey(struct ssh *);
383 static int userauth_passwd(struct ssh *);
384 static int userauth_kbdint(struct ssh *);
385 static int userauth_hostbased(struct ssh *);
386 
387 #ifdef GSSAPI
388 static int userauth_gssapi(struct ssh *);
389 static void userauth_gssapi_cleanup(struct ssh *);
390 static int input_gssapi_response(int type, u_int32_t, struct ssh *);
391 static int input_gssapi_token(int type, u_int32_t, struct ssh *);
392 static int input_gssapi_error(int, u_int32_t, struct ssh *);
393 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
394 #endif
395 
396 void	userauth(struct ssh *, char *);
397 
398 static void pubkey_cleanup(struct ssh *);
399 static int sign_and_send_pubkey(struct ssh *ssh, Identity *);
400 static void pubkey_prepare(struct ssh *, Authctxt *);
401 static void pubkey_reset(Authctxt *);
402 static struct sshkey *load_identity_file(Identity *);
403 
404 static Authmethod *authmethod_get(char *authlist);
405 static Authmethod *authmethod_lookup(const char *name);
406 static char *authmethods_get(void);
407 
408 Authmethod authmethods[] = {
409 #ifdef GSSAPI
410 	{"gssapi-with-mic",
411 		userauth_gssapi,
412 		userauth_gssapi_cleanup,
413 		&options.gss_authentication,
414 		NULL},
415 #endif
416 	{"hostbased",
417 		userauth_hostbased,
418 		NULL,
419 		&options.hostbased_authentication,
420 		NULL},
421 #if KRB5
422 	{"kerberos-2@ssh.com",
423 		userauth_kerberos,
424 		NULL,
425 		&options.kerberos_authentication,
426 		NULL},
427 #endif
428 	{"publickey",
429 		userauth_pubkey,
430 		NULL,
431 		&options.pubkey_authentication,
432 		NULL},
433 	{"keyboard-interactive",
434 		userauth_kbdint,
435 		NULL,
436 		&options.kbd_interactive_authentication,
437 		&options.batch_mode},
438 	{"password",
439 		userauth_passwd,
440 		NULL,
441 		&options.password_authentication,
442 		&options.batch_mode},
443 	{"none",
444 		userauth_none,
445 		NULL,
446 		NULL,
447 		NULL},
448 	{NULL, NULL, NULL, NULL, NULL}
449 };
450 
451 void
452 ssh_userauth2(struct ssh *ssh, const char *local_user,
453     const char *server_user, char *host, Sensitive *sensitive)
454 {
455 	Authctxt authctxt;
456 	int r;
457 
458 	if (options.preferred_authentications == NULL)
459 		options.preferred_authentications = authmethods_get();
460 
461 	/* setup authentication context */
462 	memset(&authctxt, 0, sizeof(authctxt));
463 	authctxt.server_user = server_user;
464 	authctxt.local_user = local_user;
465 	authctxt.host = host;
466 	authctxt.service = "ssh-connection";		/* service name */
467 	authctxt.success = 0;
468 	authctxt.method = authmethod_lookup("none");
469 	authctxt.authlist = NULL;
470 	authctxt.methoddata = NULL;
471 	authctxt.sensitive = sensitive;
472 	authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
473 	authctxt.info_req_seen = 0;
474 	authctxt.attempt_kbdint = 0;
475 	authctxt.attempt_passwd = 0;
476 #if GSSAPI
477 	authctxt.gss_supported_mechs = NULL;
478 	authctxt.mech_tried = 0;
479 #endif
480 	authctxt.agent_fd = -1;
481 	pubkey_prepare(ssh, &authctxt);
482 	if (authctxt.method == NULL) {
483 		fatal_f("internal error: cannot send userauth none request");
484 	}
485 
486 	if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
487 	    (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
488 	    (r = sshpkt_send(ssh)) != 0)
489 		fatal_fr(r, "send packet");
490 
491 	ssh->authctxt = &authctxt;
492 	ssh_dispatch_init(ssh, &input_userauth_error);
493 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info);
494 	ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
495 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success);	/* loop until success */
496 	pubkey_cleanup(ssh);
497 	ssh->authctxt = NULL;
498 
499 	ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
500 
501 	/* if the user wants to use the none cipher do it */
502 	/* post authentication and only if the right conditions are met */
503 	/* both of the NONE commands must be true and there must be no */
504 	/* tty allocated */
505 	if ((options.none_switch == 1) && (options.none_enabled == 1))
506 	{
507 		if (tty_flag) /* no null on tty sessions */
508 		{
509 			/* requested NONE cipher when in a tty */
510 			debug("Cannot switch to NONE cipher with tty allocated");
511 			fprintf(stderr, "NONE cipher switch disabled when a TTY is allocated\n");
512 		}
513 	}
514 	if (!authctxt.success)
515 		fatal("Authentication failed.");
516 
517 	if (ssh_packet_connection_is_on_socket(ssh)) {
518 		verbose("Authenticated to %s ([%s]:%d) using \"%s\".", host,
519 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
520 		    authctxt.method->name);
521 	} else {
522 		verbose("Authenticated to %s (via proxy) using \"%s\".", host,
523 		    authctxt.method->name);
524 	}
525 }
526 
527 static int
528 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
529 {
530 	int r;
531 
532 	if (ssh_packet_remaining(ssh) > 0) {
533 		char *reply;
534 
535 		if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
536 			goto out;
537 		debug2("service_accept: %s", reply);
538 		free(reply);
539 	} else {
540 		debug2("buggy server: service_accept w/o service");
541 	}
542 	if ((r = sshpkt_get_end(ssh)) != 0)
543 		goto out;
544 	debug("SSH2_MSG_SERVICE_ACCEPT received");
545 
546 	/* initial userauth request */
547 	userauth_none(ssh);
548 
549 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
550 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
551 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
552 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
553 	r = 0;
554  out:
555 	return r;
556 }
557 
558 static int
559 input_userauth_ext_info(int type, u_int32_t seqnr, struct ssh *ssh)
560 {
561 	return kex_input_ext_info(type, seqnr, ssh);
562 }
563 
564 void
565 userauth(struct ssh *ssh, char *authlist)
566 {
567 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
568 
569 	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
570 		authctxt->method->cleanup(ssh);
571 
572 	free(authctxt->methoddata);
573 	authctxt->methoddata = NULL;
574 	if (authlist == NULL) {
575 		authlist = authctxt->authlist;
576 	} else {
577 		free(authctxt->authlist);
578 		authctxt->authlist = authlist;
579 	}
580 	for (;;) {
581 		Authmethod *method = authmethod_get(authlist);
582 		if (method == NULL)
583 			fatal("%s@%s: Permission denied (%s).",
584 			    authctxt->server_user, authctxt->host, authlist);
585 		authctxt->method = method;
586 
587 		/* reset the per method handler */
588 		ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_PER_METHOD_MIN,
589 		    SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
590 
591 		/* and try new method */
592 		if (method->userauth(ssh) != 0) {
593 			debug2("we sent a %s packet, wait for reply", method->name);
594 			break;
595 		} else {
596 			debug2("we did not send a packet, disable method");
597 			method->enabled = NULL;
598 		}
599 	}
600 }
601 
602 static int
603 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
604 {
605 	fatal_f("bad message during authentication: type %d", type);
606 	return 0;
607 }
608 
609 static int
610 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
611 {
612 	char *msg = NULL;
613 	size_t len;
614 	int r;
615 
616 	debug3_f("entering");
617 	if ((r = sshpkt_get_cstring(ssh, &msg, &len)) != 0 ||
618 	    (r = sshpkt_get_cstring(ssh, NULL, NULL)) != 0)
619 		goto out;
620 	if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
621 		fmprintf(stderr, "%s", msg);
622 	r = 0;
623  out:
624 	free(msg);
625 	return r;
626 }
627 
628 static int
629 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh)
630 {
631 	Authctxt *authctxt = ssh->authctxt;
632 
633 	if (authctxt == NULL)
634 		fatal_f("no authentication context");
635 	free(authctxt->authlist);
636 	authctxt->authlist = NULL;
637 	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
638 		authctxt->method->cleanup(ssh);
639 	free(authctxt->methoddata);
640 	authctxt->methoddata = NULL;
641 	authctxt->success = 1;			/* break out */
642 	return 0;
643 }
644 
645 #if 0
646 static int
647 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh)
648 {
649 	Authctxt *authctxt = ssh->authctxt;
650 
651 	if (authctxt == NULL)
652 		fatal_f("no authentication context");
653 
654 	fatal("Unexpected authentication success during %s.",
655 	    authctxt->method->name);
656 	return 0;
657 }
658 #endif
659 
660 static int
661 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
662 {
663 	Authctxt *authctxt = ssh->authctxt;
664 	char *authlist = NULL;
665 	u_char partial;
666 
667 	if (authctxt == NULL)
668 		fatal("input_userauth_failure: no authentication context");
669 
670 	if (sshpkt_get_cstring(ssh, &authlist, NULL) != 0 ||
671 	    sshpkt_get_u8(ssh, &partial) != 0 ||
672 	    sshpkt_get_end(ssh) != 0)
673 		goto out;
674 
675 	if (partial != 0) {
676 		verbose("Authenticated using \"%s\" with partial success.",
677 		    authctxt->method->name);
678 		/* reset state */
679 		pubkey_reset(authctxt);
680 	}
681 	debug("Authentications that can continue: %s", authlist);
682 
683 	userauth(ssh, authlist);
684 	authlist = NULL;
685  out:
686 	free(authlist);
687 	return 0;
688 }
689 
690 /*
691  * Format an identity for logging including filename, key type, fingerprint
692  * and location (agent, etc.). Caller must free.
693  */
694 static char *
695 format_identity(Identity *id)
696 {
697 	char *fp = NULL, *ret = NULL;
698 	const char *note = "";
699 
700 	if (id->key != NULL) {
701 		fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
702 		    SSH_FP_DEFAULT);
703 	}
704 	if (id->key) {
705 		if ((id->key->flags & SSHKEY_FLAG_EXT) != 0)
706 			note = " token";
707 		else if (sshkey_is_sk(id->key))
708 			note = " authenticator";
709 	}
710 	xasprintf(&ret, "%s %s%s%s%s%s%s",
711 	    id->filename,
712 	    id->key ? sshkey_type(id->key) : "", id->key ? " " : "",
713 	    fp ? fp : "",
714 	    id->userprovided ? " explicit" : "", note,
715 	    id->agent_fd != -1 ? " agent" : "");
716 	free(fp);
717 	return ret;
718 }
719 
720 static int
721 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
722 {
723 	Authctxt *authctxt = ssh->authctxt;
724 	struct sshkey *key = NULL;
725 	Identity *id = NULL;
726 	int pktype, found = 0, sent = 0;
727 	size_t blen;
728 	char *pkalg = NULL, *fp = NULL, *ident = NULL;
729 	u_char *pkblob = NULL;
730 	int r;
731 
732 	if (authctxt == NULL)
733 		fatal("input_userauth_pk_ok: no authentication context");
734 
735 	if ((r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
736 	    (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
737 	    (r = sshpkt_get_end(ssh)) != 0)
738 		goto done;
739 
740 	if ((pktype = sshkey_type_from_name(pkalg)) == KEY_UNSPEC) {
741 		debug_f("server sent unknown pkalg %s", pkalg);
742 		goto done;
743 	}
744 	if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
745 		debug_r(r, "no key from blob. pkalg %s", pkalg);
746 		goto done;
747 	}
748 	if (key->type != pktype) {
749 		error("input_userauth_pk_ok: type mismatch "
750 		    "for decoded key (received %d, expected %d)",
751 		    key->type, pktype);
752 		goto done;
753 	}
754 
755 	/*
756 	 * search keys in the reverse order, because last candidate has been
757 	 * moved to the end of the queue.  this also avoids confusion by
758 	 * duplicate keys
759 	 */
760 	TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
761 		if (sshkey_equal(key, id->key)) {
762 			found = 1;
763 			break;
764 		}
765 	}
766 	if (!found || id == NULL) {
767 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
768 		    SSH_FP_DEFAULT);
769 		error_f("server replied with unknown key: %s %s",
770 		    sshkey_type(key), fp == NULL ? "<ERROR>" : fp);
771 		goto done;
772 	}
773 	ident = format_identity(id);
774 	debug("Server accepts key: %s", ident);
775 	sent = sign_and_send_pubkey(ssh, id);
776 	r = 0;
777  done:
778 	sshkey_free(key);
779 	free(ident);
780 	free(fp);
781 	free(pkalg);
782 	free(pkblob);
783 
784 	/* try another method if we did not send a packet */
785 	if (r == 0 && sent == 0)
786 		userauth(ssh, NULL);
787 	return r;
788 }
789 
790 #ifdef GSSAPI
791 static int
792 userauth_gssapi(struct ssh *ssh)
793 {
794 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
795 	Gssctxt *gssctxt = NULL;
796 	OM_uint32 min;
797 	int r, ok = 0;
798 	gss_OID mech = NULL;
799 
800 	/* Try one GSSAPI method at a time, rather than sending them all at
801 	 * once. */
802 
803 	if (authctxt->gss_supported_mechs == NULL)
804 		gss_indicate_mechs(&min, &authctxt->gss_supported_mechs);
805 
806 	/* Check to see whether the mechanism is usable before we offer it */
807 	while (authctxt->mech_tried < authctxt->gss_supported_mechs->count &&
808 	    !ok) {
809 		mech = &authctxt->gss_supported_mechs->
810 		    elements[authctxt->mech_tried];
811 		/* My DER encoding requires length<128 */
812 		if (mech->length < 128 && ssh_gssapi_check_mechanism(&gssctxt,
813 		    mech, authctxt->host)) {
814 			ok = 1; /* Mechanism works */
815 		} else {
816 			authctxt->mech_tried++;
817 		}
818 	}
819 
820 	if (!ok || mech == NULL)
821 		return 0;
822 
823 	authctxt->methoddata=(void *)gssctxt;
824 
825 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
826 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
827 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
828 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
829 	    (r = sshpkt_put_u32(ssh, 1)) != 0 ||
830 	    (r = sshpkt_put_u32(ssh, (mech->length) + 2)) != 0 ||
831 	    (r = sshpkt_put_u8(ssh, SSH_GSS_OIDTYPE)) != 0 ||
832 	    (r = sshpkt_put_u8(ssh, mech->length)) != 0 ||
833 	    (r = sshpkt_put(ssh, mech->elements, mech->length)) != 0 ||
834 	    (r = sshpkt_send(ssh)) != 0)
835 		fatal_fr(r, "send packet");
836 
837 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
838 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
839 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
840 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
841 
842 	authctxt->mech_tried++; /* Move along to next candidate */
843 
844 	return 1;
845 }
846 
847 static void
848 userauth_gssapi_cleanup(struct ssh *ssh)
849 {
850 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
851 	Gssctxt *gssctxt = (Gssctxt *)authctxt->methoddata;
852 
853 	ssh_gssapi_delete_ctx(&gssctxt);
854 	authctxt->methoddata = NULL;
855 
856 	free(authctxt->gss_supported_mechs);
857 	authctxt->gss_supported_mechs = NULL;
858 }
859 
860 static OM_uint32
861 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
862 {
863 	Authctxt *authctxt = ssh->authctxt;
864 	Gssctxt *gssctxt = authctxt->methoddata;
865 	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
866 	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
867 	gss_buffer_desc gssbuf;
868 	OM_uint32 status, ms, flags;
869 	int r;
870 
871 	status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
872 	    recv_tok, &send_tok, &flags);
873 
874 	if (send_tok.length > 0) {
875 		u_char type = GSS_ERROR(status) ?
876 		    SSH2_MSG_USERAUTH_GSSAPI_ERRTOK :
877 		    SSH2_MSG_USERAUTH_GSSAPI_TOKEN;
878 
879 		if ((r = sshpkt_start(ssh, type)) != 0 ||
880 		    (r = sshpkt_put_string(ssh, send_tok.value,
881 		    send_tok.length)) != 0 ||
882 		    (r = sshpkt_send(ssh)) != 0)
883 			fatal_fr(r, "send %u packet", type);
884 
885 		gss_release_buffer(&ms, &send_tok);
886 	}
887 
888 	if (status == GSS_S_COMPLETE) {
889 		/* send either complete or MIC, depending on mechanism */
890 		if (!(flags & GSS_C_INTEG_FLAG)) {
891 			if ((r = sshpkt_start(ssh,
892 			    SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)) != 0 ||
893 			    (r = sshpkt_send(ssh)) != 0)
894 				fatal_fr(r, "send completion");
895 		} else {
896 			struct sshbuf *b;
897 
898 			if ((b = sshbuf_new()) == NULL)
899 				fatal_f("sshbuf_new failed");
900 			ssh_gssapi_buildmic(b, authctxt->server_user,
901 			    authctxt->service, "gssapi-with-mic",
902 			    ssh->kex->session_id);
903 
904 			if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
905 				fatal_f("sshbuf_mutable_ptr failed");
906 			gssbuf.length = sshbuf_len(b);
907 
908 			status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
909 
910 			if (!GSS_ERROR(status)) {
911 				if ((r = sshpkt_start(ssh,
912 				    SSH2_MSG_USERAUTH_GSSAPI_MIC)) != 0 ||
913 				    (r = sshpkt_put_string(ssh, mic.value,
914 				    mic.length)) != 0 ||
915 				    (r = sshpkt_send(ssh)) != 0)
916 					fatal_fr(r, "send MIC");
917 			}
918 
919 			sshbuf_free(b);
920 			gss_release_buffer(&ms, &mic);
921 		}
922 	}
923 
924 	return status;
925 }
926 
927 static int
928 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
929 {
930 	Authctxt *authctxt = ssh->authctxt;
931 	Gssctxt *gssctxt;
932 	size_t oidlen;
933 	u_char *oidv = NULL;
934 	int r;
935 
936 	if (authctxt == NULL)
937 		fatal("input_gssapi_response: no authentication context");
938 	gssctxt = authctxt->methoddata;
939 
940 	/* Setup our OID */
941 	if ((r = sshpkt_get_string(ssh, &oidv, &oidlen)) != 0)
942 		goto done;
943 
944 	if (oidlen <= 2 ||
945 	    oidv[0] != SSH_GSS_OIDTYPE ||
946 	    oidv[1] != oidlen - 2) {
947 		debug("Badly encoded mechanism OID received");
948 		userauth(ssh, NULL);
949 		goto ok;
950 	}
951 
952 	if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
953 		fatal("Server returned different OID than expected");
954 
955 	if ((r = sshpkt_get_end(ssh)) != 0)
956 		goto done;
957 
958 	if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
959 		/* Start again with next method on list */
960 		debug("Trying to start again");
961 		userauth(ssh, NULL);
962 		goto ok;
963 	}
964  ok:
965 	r = 0;
966  done:
967 	free(oidv);
968 	return r;
969 }
970 
971 static int
972 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
973 {
974 	Authctxt *authctxt = ssh->authctxt;
975 	gss_buffer_desc recv_tok;
976 	u_char *p = NULL;
977 	size_t len;
978 	OM_uint32 status;
979 	int r;
980 
981 	if (authctxt == NULL)
982 		fatal("input_gssapi_response: no authentication context");
983 
984 	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
985 	    (r = sshpkt_get_end(ssh)) != 0)
986 		goto out;
987 
988 	recv_tok.value = p;
989 	recv_tok.length = len;
990 	status = process_gssapi_token(ssh, &recv_tok);
991 
992 	/* Start again with the next method in the list */
993 	if (GSS_ERROR(status)) {
994 		userauth(ssh, NULL);
995 		/* ok */
996 	}
997 	r = 0;
998  out:
999 	free(p);
1000 	return r;
1001 }
1002 
1003 static int
1004 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
1005 {
1006 	Authctxt *authctxt = ssh->authctxt;
1007 	Gssctxt *gssctxt;
1008 	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
1009 	gss_buffer_desc recv_tok;
1010 	OM_uint32 ms;
1011 	u_char *p = NULL;
1012 	size_t len;
1013 	int r;
1014 
1015 	if (authctxt == NULL)
1016 		fatal("input_gssapi_response: no authentication context");
1017 	gssctxt = authctxt->methoddata;
1018 
1019 	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
1020 	    (r = sshpkt_get_end(ssh)) != 0) {
1021 		free(p);
1022 		return r;
1023 	}
1024 
1025 	/* Stick it into GSSAPI and see what it says */
1026 	recv_tok.value = p;
1027 	recv_tok.length = len;
1028 	(void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
1029 	    &recv_tok, &send_tok, NULL);
1030 	free(p);
1031 	gss_release_buffer(&ms, &send_tok);
1032 
1033 	/* Server will be returning a failed packet after this one */
1034 	return 0;
1035 }
1036 
1037 static int
1038 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
1039 {
1040 	char *msg = NULL;
1041 	char *lang = NULL;
1042 	int r;
1043 
1044 	if ((r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* maj */
1045 	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* min */
1046 	    (r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
1047 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1048 		goto out;
1049 	r = sshpkt_get_end(ssh);
1050 	debug("Server GSSAPI Error:\n%s", msg);
1051  out:
1052 	free(msg);
1053 	free(lang);
1054 	return r;
1055 }
1056 #endif /* GSSAPI */
1057 
1058 static int
1059 userauth_none(struct ssh *ssh)
1060 {
1061 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1062 	int r;
1063 
1064 	/* initial userauth request */
1065 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1066 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1067 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1068 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1069 	    (r = sshpkt_send(ssh)) != 0)
1070 		fatal_fr(r, "send packet");
1071 	return 1;
1072 }
1073 
1074 static int
1075 userauth_passwd(struct ssh *ssh)
1076 {
1077 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1078 	char *password, *prompt = NULL;
1079 	const char *host = options.host_key_alias ?  options.host_key_alias :
1080 	    authctxt->host;
1081 	int r;
1082 
1083 	if (authctxt->attempt_passwd++ >= options.number_of_password_prompts)
1084 		return 0;
1085 
1086 	if (authctxt->attempt_passwd != 1)
1087 		error("Permission denied, please try again.");
1088 
1089 	xasprintf(&prompt, "%s@%s's password: ", authctxt->server_user, host);
1090 	password = read_passphrase(prompt, 0);
1091 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1092 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1093 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1094 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1095 	    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
1096 	    (r = sshpkt_put_cstring(ssh, password)) != 0 ||
1097 	    (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1098 	    (r = sshpkt_send(ssh)) != 0)
1099 		fatal_fr(r, "send packet");
1100 
1101 	free(prompt);
1102 	if (password != NULL)
1103 		freezero(password, strlen(password));
1104 
1105 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1106 	    &input_userauth_passwd_changereq);
1107 
1108 	return 1;
1109 }
1110 
1111 /*
1112  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
1113  */
1114 static int
1115 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
1116 {
1117 	Authctxt *authctxt = ssh->authctxt;
1118 	char *info = NULL, *lang = NULL, *password = NULL, *retype = NULL;
1119 	char prompt[256];
1120 	const char *host;
1121 	int r;
1122 
1123 	debug2("input_userauth_passwd_changereq");
1124 
1125 	if (authctxt == NULL)
1126 		fatal("input_userauth_passwd_changereq: "
1127 		    "no authentication context");
1128 	host = options.host_key_alias ? options.host_key_alias : authctxt->host;
1129 
1130 	if ((r = sshpkt_get_cstring(ssh, &info, NULL)) != 0 ||
1131 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1132 		goto out;
1133 	if (strlen(info) > 0)
1134 		logit("%s", info);
1135 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1136 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1137 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1138 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1139 	    (r = sshpkt_put_u8(ssh, 1)) != 0)	/* additional info */
1140 		goto out;
1141 
1142 	snprintf(prompt, sizeof(prompt),
1143 	    "Enter %.30s@%.128s's old password: ",
1144 	    authctxt->server_user, host);
1145 	password = read_passphrase(prompt, 0);
1146 	if ((r = sshpkt_put_cstring(ssh, password)) != 0)
1147 		goto out;
1148 
1149 	freezero(password, strlen(password));
1150 	password = NULL;
1151 	while (password == NULL) {
1152 		snprintf(prompt, sizeof(prompt),
1153 		    "Enter %.30s@%.128s's new password: ",
1154 		    authctxt->server_user, host);
1155 		password = read_passphrase(prompt, RP_ALLOW_EOF);
1156 		if (password == NULL) {
1157 			/* bail out */
1158 			r = 0;
1159 			goto out;
1160 		}
1161 		snprintf(prompt, sizeof(prompt),
1162 		    "Retype %.30s@%.128s's new password: ",
1163 		    authctxt->server_user, host);
1164 		retype = read_passphrase(prompt, 0);
1165 		if (strcmp(password, retype) != 0) {
1166 			freezero(password, strlen(password));
1167 			logit("Mismatch; try again, EOF to quit.");
1168 			password = NULL;
1169 		}
1170 		freezero(retype, strlen(retype));
1171 	}
1172 	if ((r = sshpkt_put_cstring(ssh, password)) != 0 ||
1173 	    (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1174 	    (r = sshpkt_send(ssh)) != 0)
1175 		goto out;
1176 
1177 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1178 	    &input_userauth_passwd_changereq);
1179 	r = 0;
1180  out:
1181 	if (password)
1182 		freezero(password, strlen(password));
1183 	free(info);
1184 	free(lang);
1185 	return r;
1186 }
1187 
1188 /*
1189  * Select an algorithm for publickey signatures.
1190  * Returns algorithm (caller must free) or NULL if no mutual algorithm found.
1191  *
1192  * Call with ssh==NULL to ignore server-sig-algs extension list and
1193  * only attempt with the key's base signature type.
1194  */
1195 static char *
1196 key_sig_algorithm(struct ssh *ssh, const struct sshkey *key)
1197 {
1198 	char *allowed, *oallowed, *cp, *tmp, *alg = NULL;
1199 	const char *server_sig_algs;
1200 
1201 	/*
1202 	 * The signature algorithm will only differ from the key algorithm
1203 	 * for RSA keys/certs and when the server advertises support for
1204 	 * newer (SHA2) algorithms.
1205 	 */
1206 	if (ssh == NULL || ssh->kex->server_sig_algs == NULL ||
1207 	    (key->type != KEY_RSA && key->type != KEY_RSA_CERT) ||
1208 	    (key->type == KEY_RSA_CERT && (ssh->compat & SSH_BUG_SIGTYPE))) {
1209 		/* Filter base key signature alg against our configuration */
1210 		return match_list(sshkey_ssh_name(key),
1211 		    options.pubkey_accepted_algos, NULL);
1212 	}
1213 
1214 	/*
1215 	 * Workaround OpenSSH 7.4 bug: this version supports RSA/SHA-2 but
1216 	 * fails to advertise it via SSH2_MSG_EXT_INFO.
1217 	 */
1218 	server_sig_algs = ssh->kex->server_sig_algs;
1219 	if (key->type == KEY_RSA && (ssh->compat & SSH_BUG_SIGTYPE74))
1220 		server_sig_algs = "rsa-sha2-256,rsa-sha2-512";
1221 
1222 	/*
1223 	 * For RSA keys/certs, since these might have a different sig type:
1224 	 * find the first entry in PubkeyAcceptedAlgorithms of the right type
1225 	 * that also appears in the supported signature algorithms list from
1226 	 * the server.
1227 	 */
1228 	oallowed = allowed = xstrdup(options.pubkey_accepted_algos);
1229 	while ((cp = strsep(&allowed, ",")) != NULL) {
1230 		if (sshkey_type_from_name(cp) != key->type)
1231 			continue;
1232 		tmp = match_list(sshkey_sigalg_by_name(cp),
1233 		    server_sig_algs, NULL);
1234 		if (tmp != NULL)
1235 			alg = xstrdup(cp);
1236 		free(tmp);
1237 		if (alg != NULL)
1238 			break;
1239 	}
1240 	free(oallowed);
1241 	return alg;
1242 }
1243 
1244 static int
1245 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1246     const u_char *data, size_t datalen, u_int compat, const char *alg)
1247 {
1248 	struct sshkey *sign_key = NULL, *prv = NULL;
1249 	int is_agent = 0, retried = 0, r = SSH_ERR_INTERNAL_ERROR;
1250 	struct notifier_ctx *notifier = NULL;
1251 	char *fp = NULL, *pin = NULL, *prompt = NULL;
1252 
1253 	*sigp = NULL;
1254 	*lenp = 0;
1255 
1256 	/* The agent supports this key. */
1257 	if (id->key != NULL && id->agent_fd != -1) {
1258 		return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1259 		    data, datalen, alg, compat);
1260 	}
1261 
1262 	/*
1263 	 * We have already loaded the private key or the private key is
1264 	 * stored in external hardware.
1265 	 */
1266 	if (id->key != NULL &&
1267 	    (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) {
1268 		sign_key = id->key;
1269 		is_agent = 1;
1270 	} else {
1271 		/* Load the private key from the file. */
1272 		if ((prv = load_identity_file(id)) == NULL)
1273 			return SSH_ERR_KEY_NOT_FOUND;
1274 		if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1275 			error_f("private key %s contents do not match public",
1276 			    id->filename);
1277 			r = SSH_ERR_KEY_NOT_FOUND;
1278 			goto out;
1279 		}
1280 		sign_key = prv;
1281 	}
1282  retry_pin:
1283 	/* Prompt for touch for non-agent FIDO keys that request UP */
1284 	if (!is_agent && sshkey_is_sk(sign_key) &&
1285 	    (sign_key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1286 		/* XXX should batch mode just skip these? */
1287 		if ((fp = sshkey_fingerprint(sign_key,
1288 		    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1289 			fatal_f("fingerprint failed");
1290 		notifier = notify_start(options.batch_mode,
1291 		    "Confirm user presence for key %s %s",
1292 		    sshkey_type(sign_key), fp);
1293 		free(fp);
1294 	}
1295 	if ((r = sshkey_sign(sign_key, sigp, lenp, data, datalen,
1296 	    alg, options.sk_provider, pin, compat)) != 0) {
1297 		debug_fr(r, "sshkey_sign");
1298 		if (!retried && pin == NULL && !is_agent &&
1299 		    sshkey_is_sk(sign_key) &&
1300 		    r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1301 			notify_complete(notifier, NULL);
1302 			notifier = NULL;
1303 			xasprintf(&prompt, "Enter PIN for %s key %s: ",
1304 			    sshkey_type(sign_key), id->filename);
1305 			pin = read_passphrase(prompt, 0);
1306 			retried = 1;
1307 			goto retry_pin;
1308 		}
1309 		goto out;
1310 	}
1311 
1312 	/*
1313 	 * PKCS#11 tokens may not support all signature algorithms,
1314 	 * so check what we get back.
1315 	 */
1316 	if ((r = sshkey_check_sigtype(*sigp, *lenp, alg)) != 0) {
1317 		debug_fr(r, "sshkey_check_sigtype");
1318 		goto out;
1319 	}
1320 	/* success */
1321 	r = 0;
1322  out:
1323 	free(prompt);
1324 	if (pin != NULL)
1325 		freezero(pin, strlen(pin));
1326 	notify_complete(notifier, r == 0 ? "User presence confirmed" : NULL);
1327 	sshkey_free(prv);
1328 	return r;
1329 }
1330 
1331 static int
1332 id_filename_matches(Identity *id, Identity *private_id)
1333 {
1334 	static const char * const suffixes[] = { ".pub", "-cert.pub", NULL };
1335 	size_t len = strlen(id->filename), plen = strlen(private_id->filename);
1336 	size_t i, slen;
1337 
1338 	if (strcmp(id->filename, private_id->filename) == 0)
1339 		return 1;
1340 	for (i = 0; suffixes[i]; i++) {
1341 		slen = strlen(suffixes[i]);
1342 		if (len > slen && plen == len - slen &&
1343 		    strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
1344 		    memcmp(id->filename, private_id->filename, plen) == 0)
1345 			return 1;
1346 	}
1347 	return 0;
1348 }
1349 
1350 static int
1351 sign_and_send_pubkey(struct ssh *ssh, Identity *id)
1352 {
1353 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1354 	struct sshbuf *b = NULL;
1355 	Identity *private_id, *sign_id = NULL;
1356 	u_char *signature = NULL;
1357 	size_t slen = 0, skip = 0;
1358 	int r, fallback_sigtype, sent = 0;
1359 	char *alg = NULL, *fp = NULL;
1360 	const char *loc = "", *method = "publickey";
1361 	int hostbound = 0;
1362 
1363 	/* prefer host-bound pubkey signatures if supported by server */
1364 	if ((ssh->kex->flags & KEX_HAS_PUBKEY_HOSTBOUND) != 0 &&
1365 	    (options.pubkey_authentication & SSH_PUBKEY_AUTH_HBOUND) != 0) {
1366 		hostbound = 1;
1367 		method = "publickey-hostbound-v00@openssh.com";
1368 	}
1369 
1370 	if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1371 	    SSH_FP_DEFAULT)) == NULL)
1372 		return 0;
1373 
1374 	debug3_f("using %s with %s %s", method, sshkey_type(id->key), fp);
1375 
1376 	/*
1377 	 * If the key is an certificate, try to find a matching private key
1378 	 * and use it to complete the signature.
1379 	 * If no such private key exists, fall back to trying the certificate
1380 	 * key itself in case it has a private half already loaded.
1381 	 * This will try to set sign_id to the private key that will perform
1382 	 * the signature.
1383 	 */
1384 	if (sshkey_is_cert(id->key)) {
1385 		TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1386 			if (sshkey_equal_public(id->key, private_id->key) &&
1387 			    id->key->type != private_id->key->type) {
1388 				sign_id = private_id;
1389 				break;
1390 			}
1391 		}
1392 		/*
1393 		 * Exact key matches are preferred, but also allow
1394 		 * filename matches for non-PKCS#11/agent keys that
1395 		 * didn't load public keys. This supports the case
1396 		 * of keeping just a private key file and public
1397 		 * certificate on disk.
1398 		 */
1399 		if (sign_id == NULL &&
1400 		    !id->isprivate && id->agent_fd == -1 &&
1401 		    (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
1402 			TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1403 				if (private_id->key == NULL &&
1404 				    id_filename_matches(id, private_id)) {
1405 					sign_id = private_id;
1406 					break;
1407 				}
1408 			}
1409 		}
1410 		if (sign_id != NULL) {
1411 			debug2_f("using private key \"%s\"%s for "
1412 			    "certificate", sign_id->filename,
1413 			    sign_id->agent_fd != -1 ? " from agent" : "");
1414 		} else {
1415 			debug_f("no separate private key for certificate "
1416 			    "\"%s\"", id->filename);
1417 		}
1418 	}
1419 
1420 	/*
1421 	 * If the above didn't select another identity to do the signing
1422 	 * then default to the one we started with.
1423 	 */
1424 	if (sign_id == NULL)
1425 		sign_id = id;
1426 
1427 	/* assemble and sign data */
1428 	for (fallback_sigtype = 0; fallback_sigtype <= 1; fallback_sigtype++) {
1429 		free(alg);
1430 		slen = 0;
1431 		signature = NULL;
1432 		if ((alg = key_sig_algorithm(fallback_sigtype ? NULL : ssh,
1433 		    id->key)) == NULL) {
1434 			error_f("no mutual signature supported");
1435 			goto out;
1436 		}
1437 		debug3_f("signing using %s %s", alg, fp);
1438 
1439 		sshbuf_free(b);
1440 		if ((b = sshbuf_new()) == NULL)
1441 			fatal_f("sshbuf_new failed");
1442 		if (ssh->compat & SSH_OLD_SESSIONID) {
1443 			if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
1444 				fatal_fr(r, "sshbuf_putb");
1445 		} else {
1446 			if ((r = sshbuf_put_stringb(b,
1447 			    ssh->kex->session_id)) != 0)
1448 				fatal_fr(r, "sshbuf_put_stringb");
1449 		}
1450 		skip = sshbuf_len(b);
1451 		if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1452 		    (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1453 		    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
1454 		    (r = sshbuf_put_cstring(b, method)) != 0 ||
1455 		    (r = sshbuf_put_u8(b, 1)) != 0 ||
1456 		    (r = sshbuf_put_cstring(b, alg)) != 0 ||
1457 		    (r = sshkey_puts(id->key, b)) != 0) {
1458 			fatal_fr(r, "assemble signed data");
1459 		}
1460 		if (hostbound) {
1461 			if (ssh->kex->initial_hostkey == NULL) {
1462 				fatal_f("internal error: initial hostkey "
1463 				    "not recorded");
1464 			}
1465 			if ((r = sshkey_puts(ssh->kex->initial_hostkey, b)) != 0)
1466 				fatal_fr(r, "assemble %s hostkey", method);
1467 		}
1468 		/* generate signature */
1469 		r = identity_sign(sign_id, &signature, &slen,
1470 		    sshbuf_ptr(b), sshbuf_len(b), ssh->compat, alg);
1471 		if (r == 0)
1472 			break;
1473 		else if (r == SSH_ERR_KEY_NOT_FOUND)
1474 			goto out; /* soft failure */
1475 		else if (r == SSH_ERR_SIGN_ALG_UNSUPPORTED &&
1476 		    !fallback_sigtype) {
1477 			if (sign_id->agent_fd != -1)
1478 				loc = "agent ";
1479 			else if ((sign_id->key->flags & SSHKEY_FLAG_EXT) != 0)
1480 				loc = "token ";
1481 			logit("%skey %s %s returned incorrect signature type",
1482 			    loc, sshkey_type(id->key), fp);
1483 			continue;
1484 		}
1485 		error_fr(r, "signing failed for %s \"%s\"%s",
1486 		    sshkey_type(sign_id->key), sign_id->filename,
1487 		    id->agent_fd != -1 ? " from agent" : "");
1488 		goto out;
1489 	}
1490 	if (slen == 0 || signature == NULL) /* shouldn't happen */
1491 		fatal_f("no signature");
1492 
1493 	/* append signature */
1494 	if ((r = sshbuf_put_string(b, signature, slen)) != 0)
1495 		fatal_fr(r, "append signature");
1496 
1497 #ifdef DEBUG_PK
1498 	sshbuf_dump(b, stderr);
1499 #endif
1500 	/* skip session id and packet type */
1501 	if ((r = sshbuf_consume(b, skip + 1)) != 0)
1502 		fatal_fr(r, "consume");
1503 
1504 	/* put remaining data from buffer into packet */
1505 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1506 	    (r = sshpkt_putb(ssh, b)) != 0 ||
1507 	    (r = sshpkt_send(ssh)) != 0)
1508 		fatal_fr(r, "enqueue request");
1509 
1510 	/* success */
1511 	sent = 1;
1512 
1513  out:
1514 	free(fp);
1515 	free(alg);
1516 	sshbuf_free(b);
1517 	freezero(signature, slen);
1518 	return sent;
1519 }
1520 
1521 static int
1522 send_pubkey_test(struct ssh *ssh, Identity *id)
1523 {
1524 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1525 	u_char *blob = NULL;
1526 	char *alg = NULL;
1527 	size_t bloblen;
1528 	u_int have_sig = 0;
1529 	int sent = 0, r;
1530 
1531 	if ((alg = key_sig_algorithm(ssh, id->key)) == NULL) {
1532 		debug_f("no mutual signature algorithm");
1533 		goto out;
1534 	}
1535 
1536 	if ((r = sshkey_to_blob(id->key, &blob, &bloblen)) != 0) {
1537 		/* we cannot handle this key */
1538 		debug3_f("cannot handle key");
1539 		goto out;
1540 	}
1541 	/* register callback for USERAUTH_PK_OK message */
1542 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1543 
1544 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1545 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1546 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1547 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1548 	    (r = sshpkt_put_u8(ssh, have_sig)) != 0 ||
1549 	    (r = sshpkt_put_cstring(ssh, alg)) != 0 ||
1550 	    (r = sshpkt_put_string(ssh, blob, bloblen)) != 0 ||
1551 	    (r = sshpkt_send(ssh)) != 0)
1552 		fatal_fr(r, "send packet");
1553 	sent = 1;
1554 
1555  out:
1556 	free(alg);
1557 	free(blob);
1558 	return sent;
1559 }
1560 
1561 static struct sshkey *
1562 load_identity_file(Identity *id)
1563 {
1564 	struct sshkey *private = NULL;
1565 	char prompt[300], *passphrase, *comment;
1566 	int r, quit = 0, i;
1567 	struct stat st;
1568 
1569 	if (stat(id->filename, &st) == -1) {
1570 		do_log2(id->userprovided ?
1571 		    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_DEBUG3,
1572 		    "no such identity: %s: %s", id->filename, strerror(errno));
1573 		return NULL;
1574 	}
1575 	snprintf(prompt, sizeof prompt,
1576 	    "Enter passphrase for key '%.100s': ", id->filename);
1577 	for (i = 0; i <= options.number_of_password_prompts; i++) {
1578 		if (i == 0)
1579 			passphrase = xstrdup("");
1580 		else {
1581 			passphrase = read_passphrase(prompt, 0);
1582 			if (*passphrase == '\0') {
1583 				debug2("no passphrase given, try next key");
1584 				free(passphrase);
1585 				break;
1586 			}
1587 		}
1588 		switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1589 		    passphrase, &private, &comment))) {
1590 		case 0:
1591 			break;
1592 		case SSH_ERR_KEY_WRONG_PASSPHRASE:
1593 			if (options.batch_mode) {
1594 				quit = 1;
1595 				break;
1596 			}
1597 			if (i != 0)
1598 				debug2("bad passphrase given, try again...");
1599 			break;
1600 		case SSH_ERR_SYSTEM_ERROR:
1601 			if (errno == ENOENT) {
1602 				debug2_r(r, "Load key \"%s\"", id->filename);
1603 				quit = 1;
1604 				break;
1605 			}
1606 			/* FALLTHROUGH */
1607 		default:
1608 			error_r(r, "Load key \"%s\"", id->filename);
1609 			quit = 1;
1610 			break;
1611 		}
1612 		if (private != NULL && sshkey_is_sk(private) &&
1613 		    options.sk_provider == NULL) {
1614 			debug("key \"%s\" is an authenticator-hosted key, "
1615 			    "but no provider specified", id->filename);
1616 			sshkey_free(private);
1617 			private = NULL;
1618 			quit = 1;
1619 		}
1620 		if (!quit && (r = sshkey_check_rsa_length(private,
1621 		    options.required_rsa_size)) != 0) {
1622 			debug_fr(r, "Skipping key %s", id->filename);
1623 			sshkey_free(private);
1624 			private = NULL;
1625 			quit = 1;
1626 		}
1627 		if (!quit && private != NULL && id->agent_fd == -1 &&
1628 		    !(id->key && id->isprivate))
1629 			maybe_add_key_to_agent(id->filename, private, comment,
1630 			    passphrase);
1631 		if (i > 0)
1632 			freezero(passphrase, strlen(passphrase));
1633 		free(comment);
1634 		if (private != NULL || quit)
1635 			break;
1636 	}
1637 	return private;
1638 }
1639 
1640 static int
1641 key_type_allowed_by_config(struct sshkey *key)
1642 {
1643 	if (match_pattern_list(sshkey_ssh_name(key),
1644 	    options.pubkey_accepted_algos, 0) == 1)
1645 		return 1;
1646 
1647 	/* RSA keys/certs might be allowed by alternate signature types */
1648 	switch (key->type) {
1649 	case KEY_RSA:
1650 		if (match_pattern_list("rsa-sha2-512",
1651 		    options.pubkey_accepted_algos, 0) == 1)
1652 			return 1;
1653 		if (match_pattern_list("rsa-sha2-256",
1654 		    options.pubkey_accepted_algos, 0) == 1)
1655 			return 1;
1656 		break;
1657 	case KEY_RSA_CERT:
1658 		if (match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
1659 		    options.pubkey_accepted_algos, 0) == 1)
1660 			return 1;
1661 		if (match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
1662 		    options.pubkey_accepted_algos, 0) == 1)
1663 			return 1;
1664 		break;
1665 	}
1666 	return 0;
1667 }
1668 
1669 /* obtain a list of keys from the agent */
1670 static int
1671 get_agent_identities(struct ssh *ssh, int *agent_fdp,
1672     struct ssh_identitylist **idlistp)
1673 {
1674 	int r, agent_fd;
1675 	struct ssh_identitylist *idlist;
1676 
1677 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1678 		if (r != SSH_ERR_AGENT_NOT_PRESENT)
1679 			debug_fr(r, "ssh_get_authentication_socket");
1680 		return r;
1681 	}
1682 	if ((r = ssh_agent_bind_hostkey(agent_fd, ssh->kex->initial_hostkey,
1683 	    ssh->kex->session_id, ssh->kex->initial_sig, 0)) == 0)
1684 		debug_f("bound agent to hostkey");
1685 	else
1686 		debug2_fr(r, "ssh_agent_bind_hostkey");
1687 
1688 	if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1689 		debug_fr(r, "ssh_fetch_identitylist");
1690 		close(agent_fd);
1691 		return r;
1692 	}
1693 	/* success */
1694 	*agent_fdp = agent_fd;
1695 	*idlistp = idlist;
1696 	debug_f("agent returned %zu keys", idlist->nkeys);
1697 	return 0;
1698 }
1699 
1700 /*
1701  * try keys in the following order:
1702  *	1. certificates listed in the config file
1703  *	2. other input certificates
1704  *	3. agent keys that are found in the config file
1705  *	4. other agent keys
1706  *	5. keys that are only listed in the config file
1707  */
1708 static void
1709 pubkey_prepare(struct ssh *ssh, Authctxt *authctxt)
1710 {
1711 	struct identity *id, *id2, *tmp;
1712 	struct idlist agent, files, *preferred;
1713 	struct sshkey *key;
1714 	int agent_fd = -1, i, r, found;
1715 	size_t j;
1716 	struct ssh_identitylist *idlist;
1717 	char *ident;
1718 
1719 	TAILQ_INIT(&agent);	/* keys from the agent */
1720 	TAILQ_INIT(&files);	/* keys from the config file */
1721 	preferred = &authctxt->keys;
1722 	TAILQ_INIT(preferred);	/* preferred order of keys */
1723 
1724 	/* list of keys stored in the filesystem and PKCS#11 */
1725 	for (i = 0; i < options.num_identity_files; i++) {
1726 		key = options.identity_keys[i];
1727 		if (key && key->cert &&
1728 		    key->cert->type != SSH2_CERT_TYPE_USER) {
1729 			debug_f("ignoring certificate %s: not a user "
1730 			    "certificate", options.identity_files[i]);
1731 			continue;
1732 		}
1733 		if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1734 			debug_f("ignoring authenticator-hosted key %s as no "
1735 			    "SecurityKeyProvider has been specified",
1736 			    options.identity_files[i]);
1737 			continue;
1738 		}
1739 		options.identity_keys[i] = NULL;
1740 		id = xcalloc(1, sizeof(*id));
1741 		id->agent_fd = -1;
1742 		id->key = key;
1743 		id->filename = xstrdup(options.identity_files[i]);
1744 		id->userprovided = options.identity_file_userprovided[i];
1745 		TAILQ_INSERT_TAIL(&files, id, next);
1746 	}
1747 	/* list of certificates specified by user */
1748 	for (i = 0; i < options.num_certificate_files; i++) {
1749 		key = options.certificates[i];
1750 		if (!sshkey_is_cert(key) || key->cert == NULL ||
1751 		    key->cert->type != SSH2_CERT_TYPE_USER) {
1752 			debug_f("ignoring certificate %s: not a user "
1753 			    "certificate", options.identity_files[i]);
1754 			continue;
1755 		}
1756 		if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1757 			debug_f("ignoring authenticator-hosted key "
1758 			    "certificate %s as no "
1759 			    "SecurityKeyProvider has been specified",
1760 			    options.identity_files[i]);
1761 			continue;
1762 		}
1763 		id = xcalloc(1, sizeof(*id));
1764 		id->agent_fd = -1;
1765 		id->key = key;
1766 		id->filename = xstrdup(options.certificate_files[i]);
1767 		id->userprovided = options.certificate_file_userprovided[i];
1768 		TAILQ_INSERT_TAIL(preferred, id, next);
1769 	}
1770 	/* list of keys supported by the agent */
1771 	if ((r = get_agent_identities(ssh, &agent_fd, &idlist)) == 0) {
1772 		for (j = 0; j < idlist->nkeys; j++) {
1773 			if ((r = sshkey_check_rsa_length(idlist->keys[j],
1774 			    options.required_rsa_size)) != 0) {
1775 				debug_fr(r, "ignoring %s agent key",
1776 				    sshkey_ssh_name(idlist->keys[j]));
1777 				continue;
1778 			}
1779 			found = 0;
1780 			TAILQ_FOREACH(id, &files, next) {
1781 				/*
1782 				 * agent keys from the config file are
1783 				 * preferred
1784 				 */
1785 				if (sshkey_equal(idlist->keys[j], id->key)) {
1786 					TAILQ_REMOVE(&files, id, next);
1787 					TAILQ_INSERT_TAIL(preferred, id, next);
1788 					id->agent_fd = agent_fd;
1789 					found = 1;
1790 					break;
1791 				}
1792 			}
1793 			if (!found && !options.identities_only) {
1794 				id = xcalloc(1, sizeof(*id));
1795 				/* XXX "steals" key/comment from idlist */
1796 				id->key = idlist->keys[j];
1797 				id->filename = idlist->comments[j];
1798 				idlist->keys[j] = NULL;
1799 				idlist->comments[j] = NULL;
1800 				id->agent_fd = agent_fd;
1801 				TAILQ_INSERT_TAIL(&agent, id, next);
1802 			}
1803 		}
1804 		ssh_free_identitylist(idlist);
1805 		/* append remaining agent keys */
1806 		TAILQ_CONCAT(preferred, &agent, next);
1807 		authctxt->agent_fd = agent_fd;
1808 	}
1809 	/* Prefer PKCS11 keys that are explicitly listed */
1810 	TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1811 		if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1812 			continue;
1813 		found = 0;
1814 		TAILQ_FOREACH(id2, &files, next) {
1815 			if (id2->key == NULL ||
1816 			    (id2->key->flags & SSHKEY_FLAG_EXT) != 0)
1817 				continue;
1818 			if (sshkey_equal(id->key, id2->key)) {
1819 				TAILQ_REMOVE(&files, id, next);
1820 				TAILQ_INSERT_TAIL(preferred, id, next);
1821 				found = 1;
1822 				break;
1823 			}
1824 		}
1825 		/* If IdentitiesOnly set and key not found then don't use it */
1826 		if (!found && options.identities_only) {
1827 			TAILQ_REMOVE(&files, id, next);
1828 			freezero(id, sizeof(*id));
1829 		}
1830 	}
1831 	/* append remaining keys from the config file */
1832 	TAILQ_CONCAT(preferred, &files, next);
1833 	/* finally, filter by PubkeyAcceptedAlgorithms */
1834 	TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1835 		if (id->key != NULL && !key_type_allowed_by_config(id->key)) {
1836 			debug("Skipping %s key %s - "
1837 			    "corresponding algo not in PubkeyAcceptedAlgorithms",
1838 			    sshkey_ssh_name(id->key), id->filename);
1839 			TAILQ_REMOVE(preferred, id, next);
1840 			sshkey_free(id->key);
1841 			free(id->filename);
1842 			memset(id, 0, sizeof(*id));
1843 			continue;
1844 		}
1845 	}
1846 	/* List the keys we plan on using */
1847 	TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1848 		ident = format_identity(id);
1849 		debug("Will attempt key: %s", ident);
1850 		free(ident);
1851 	}
1852 	debug2_f("done");
1853 }
1854 
1855 static void
1856 pubkey_cleanup(struct ssh *ssh)
1857 {
1858 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1859 	Identity *id;
1860 
1861 	if (authctxt->agent_fd != -1) {
1862 		ssh_close_authentication_socket(authctxt->agent_fd);
1863 		authctxt->agent_fd = -1;
1864 	}
1865 	for (id = TAILQ_FIRST(&authctxt->keys); id;
1866 	    id = TAILQ_FIRST(&authctxt->keys)) {
1867 		TAILQ_REMOVE(&authctxt->keys, id, next);
1868 		sshkey_free(id->key);
1869 		free(id->filename);
1870 		free(id);
1871 	}
1872 }
1873 
1874 static void
1875 pubkey_reset(Authctxt *authctxt)
1876 {
1877 	Identity *id;
1878 
1879 	TAILQ_FOREACH(id, &authctxt->keys, next)
1880 		id->tried = 0;
1881 }
1882 
1883 static int
1884 userauth_pubkey(struct ssh *ssh)
1885 {
1886 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1887 	Identity *id;
1888 	int sent = 0;
1889 	char *ident;
1890 
1891 	while ((id = TAILQ_FIRST(&authctxt->keys))) {
1892 		if (id->tried++)
1893 			return (0);
1894 		/* move key to the end of the queue */
1895 		TAILQ_REMOVE(&authctxt->keys, id, next);
1896 		TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1897 		/*
1898 		 * send a test message if we have the public key. for
1899 		 * encrypted keys we cannot do this and have to load the
1900 		 * private key instead
1901 		 */
1902 		if (id->key != NULL) {
1903 			if (id->key != NULL) {
1904 				ident = format_identity(id);
1905 				debug("Offering public key: %s", ident);
1906 				free(ident);
1907 				sent = send_pubkey_test(ssh, id);
1908 			}
1909 		} else {
1910 			debug("Trying private key: %s", id->filename);
1911 			id->key = load_identity_file(id);
1912 			if (id->key != NULL) {
1913 				if (id->key != NULL) {
1914 					id->isprivate = 1;
1915 					sent = sign_and_send_pubkey(ssh, id);
1916 				}
1917 				sshkey_free(id->key);
1918 				id->key = NULL;
1919 				id->isprivate = 0;
1920 			}
1921 		}
1922 		if (sent)
1923 			return (sent);
1924 	}
1925 	return (0);
1926 }
1927 
1928 /*
1929  * Send userauth request message specifying keyboard-interactive method.
1930  */
1931 static int
1932 userauth_kbdint(struct ssh *ssh)
1933 {
1934 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1935 	int r;
1936 
1937 	if (authctxt->attempt_kbdint++ >= options.number_of_password_prompts)
1938 		return 0;
1939 	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1940 	if (authctxt->attempt_kbdint > 1 && !authctxt->info_req_seen) {
1941 		debug3("userauth_kbdint: disable: no info_req_seen");
1942 		ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1943 		return 0;
1944 	}
1945 
1946 	debug2("userauth_kbdint");
1947 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1948 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1949 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1950 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1951 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||		/* lang */
1952 	    (r = sshpkt_put_cstring(ssh, options.kbd_interactive_devices ?
1953 	    options.kbd_interactive_devices : "")) != 0 ||
1954 	    (r = sshpkt_send(ssh)) != 0)
1955 		fatal_fr(r, "send packet");
1956 
1957 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1958 	return 1;
1959 }
1960 
1961 /*
1962  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1963  */
1964 static int
1965 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1966 {
1967 	Authctxt *authctxt = ssh->authctxt;
1968 	char *name = NULL, *inst = NULL, *lang = NULL, *prompt = NULL;
1969 	char *display_prompt = NULL, *response = NULL;
1970 	u_char echo = 0;
1971 	u_int num_prompts, i;
1972 	int r;
1973 
1974 	debug2_f("entering");
1975 
1976 	if (authctxt == NULL)
1977 		fatal_f("no authentication context");
1978 
1979 	authctxt->info_req_seen = 1;
1980 
1981 	if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
1982 	    (r = sshpkt_get_cstring(ssh, &inst, NULL)) != 0 ||
1983 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1984 		goto out;
1985 	if (strlen(name) > 0)
1986 		logit("%s", name);
1987 	if (strlen(inst) > 0)
1988 		logit("%s", inst);
1989 
1990 	if ((r = sshpkt_get_u32(ssh, &num_prompts)) != 0)
1991 		goto out;
1992 	/*
1993 	 * Begin to build info response packet based on prompts requested.
1994 	 * We commit to providing the correct number of responses, so if
1995 	 * further on we run into a problem that prevents this, we have to
1996 	 * be sure and clean this up and send a correct error response.
1997 	 */
1998 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE)) != 0 ||
1999 	    (r = sshpkt_put_u32(ssh, num_prompts)) != 0)
2000 		goto out;
2001 
2002 	debug2_f("num_prompts %d", num_prompts);
2003 	for (i = 0; i < num_prompts; i++) {
2004 		if ((r = sshpkt_get_cstring(ssh, &prompt, NULL)) != 0 ||
2005 		    (r = sshpkt_get_u8(ssh, &echo)) != 0)
2006 			goto out;
2007 		if (asmprintf(&display_prompt, INT_MAX, NULL, "(%s@%s) %s",
2008 		    authctxt->server_user, options.host_key_alias ?
2009 		    options.host_key_alias : authctxt->host, prompt) == -1)
2010 			fatal_f("asmprintf failed");
2011 		response = read_passphrase(display_prompt, echo ? RP_ECHO : 0);
2012 		if ((r = sshpkt_put_cstring(ssh, response)) != 0)
2013 			goto out;
2014 		freezero(response, strlen(response));
2015 		free(prompt);
2016 		free(display_prompt);
2017 		display_prompt = response = prompt = NULL;
2018 	}
2019 	/* done with parsing incoming message. */
2020 	if ((r = sshpkt_get_end(ssh)) != 0 ||
2021 	    (r = sshpkt_add_padding(ssh, 64)) != 0)
2022 		goto out;
2023 	r = sshpkt_send(ssh);
2024  out:
2025 	if (response)
2026 		freezero(response, strlen(response));
2027 	free(prompt);
2028 	free(display_prompt);
2029 	free(name);
2030 	free(inst);
2031 	free(lang);
2032 	return r;
2033 }
2034 
2035 static int
2036 ssh_keysign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp,
2037     const u_char *data, size_t datalen)
2038 {
2039 	struct sshbuf *b;
2040 	struct stat st;
2041 	pid_t pid;
2042 	int r, to[2], from[2], status;
2043 	int sock = ssh_packet_get_connection_in(ssh);
2044 	u_char rversion = 0, version = 2;
2045 	void (*osigchld)(int);
2046 
2047 	*sigp = NULL;
2048 	*lenp = 0;
2049 
2050 	if (stat(_PATH_SSH_KEY_SIGN, &st) == -1) {
2051 		error_f("not installed: %s", strerror(errno));
2052 		return -1;
2053 	}
2054 	if (fflush(stdout) != 0) {
2055 		error_f("fflush: %s", strerror(errno));
2056 		return -1;
2057 	}
2058 	if (pipe(to) == -1) {
2059 		error_f("pipe: %s", strerror(errno));
2060 		return -1;
2061 	}
2062 	if (pipe(from) == -1) {
2063 		error_f("pipe: %s", strerror(errno));
2064 		return -1;
2065 	}
2066 	if ((pid = fork()) == -1) {
2067 		error_f("fork: %s", strerror(errno));
2068 		return -1;
2069 	}
2070 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
2071 	if (pid == 0) {
2072 		close(from[0]);
2073 		if (dup2(from[1], STDOUT_FILENO) == -1)
2074 			fatal_f("dup2: %s", strerror(errno));
2075 		close(to[1]);
2076 		if (dup2(to[0], STDIN_FILENO) == -1)
2077 			fatal_f("dup2: %s", strerror(errno));
2078 		close(from[1]);
2079 		close(to[0]);
2080 		if (dup2(sock, STDERR_FILENO + 1) == -1)
2081 			fatal_f("dup2: %s", strerror(errno));
2082 		sock = STDERR_FILENO + 1;
2083 		if (fcntl(sock, F_SETFD, 0) == -1) /* keep the socket on exec */
2084 			debug3_f("fcntl F_SETFD: %s", strerror(errno));
2085 		closefrom(sock + 1);
2086 
2087 		debug3_f("[child] pid=%ld, exec %s",
2088 		    (long)getpid(), _PATH_SSH_KEY_SIGN);
2089 		execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
2090 		fatal_f("exec(%s): %s", _PATH_SSH_KEY_SIGN,
2091 		    strerror(errno));
2092 	}
2093 	close(from[1]);
2094 	close(to[0]);
2095 	sock = STDERR_FILENO + 1;
2096 
2097 	if ((b = sshbuf_new()) == NULL)
2098 		fatal_f("sshbuf_new failed");
2099 	/* send # of sock, data to be signed */
2100 	if ((r = sshbuf_put_u32(b, sock)) != 0 ||
2101 	    (r = sshbuf_put_string(b, data, datalen)) != 0)
2102 		fatal_fr(r, "buffer error");
2103 	if (ssh_msg_send(to[1], version, b) == -1)
2104 		fatal_f("couldn't send request");
2105 	sshbuf_reset(b);
2106 	r = ssh_msg_recv(from[0], b);
2107 	close(from[0]);
2108 	close(to[1]);
2109 	if (r < 0) {
2110 		error_f("no reply");
2111 		goto fail;
2112 	}
2113 
2114 	errno = 0;
2115 	while (waitpid(pid, &status, 0) == -1) {
2116 		if (errno != EINTR) {
2117 			error_f("waitpid %ld: %s", (long)pid, strerror(errno));
2118 			goto fail;
2119 		}
2120 	}
2121 	if (!WIFEXITED(status)) {
2122 		error_f("exited abnormally");
2123 		goto fail;
2124 	}
2125 	if (WEXITSTATUS(status) != 0) {
2126 		error_f("exited with status %d", WEXITSTATUS(status));
2127 		goto fail;
2128 	}
2129 	if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
2130 		error_fr(r, "buffer error");
2131 		goto fail;
2132 	}
2133 	if (rversion != version) {
2134 		error_f("bad version");
2135 		goto fail;
2136 	}
2137 	if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
2138 		error_fr(r, "buffer error");
2139  fail:
2140 		ssh_signal(SIGCHLD, osigchld);
2141 		sshbuf_free(b);
2142 		return -1;
2143 	}
2144 	ssh_signal(SIGCHLD, osigchld);
2145 	sshbuf_free(b);
2146 
2147 	return 0;
2148 }
2149 
2150 static int
2151 userauth_hostbased(struct ssh *ssh)
2152 {
2153 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
2154 	struct sshkey *private = NULL;
2155 	struct sshbuf *b = NULL;
2156 	u_char *sig = NULL, *keyblob = NULL;
2157 	char *fp = NULL, *chost = NULL, *lname = NULL;
2158 	size_t siglen = 0, keylen = 0;
2159 	int i, r, success = 0;
2160 
2161 	if (authctxt->ktypes == NULL) {
2162 		authctxt->oktypes = xstrdup(options.hostbased_accepted_algos);
2163 		authctxt->ktypes = authctxt->oktypes;
2164 	}
2165 
2166 	/*
2167 	 * Work through each listed type pattern in HostbasedAcceptedAlgorithms,
2168 	 * trying each hostkey that matches the type in turn.
2169 	 */
2170 	for (;;) {
2171 		if (authctxt->active_ktype == NULL)
2172 			authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
2173 		if (authctxt->active_ktype == NULL ||
2174 		    *authctxt->active_ktype == '\0')
2175 			break;
2176 		debug3_f("trying key type %s", authctxt->active_ktype);
2177 
2178 		/* check for a useful key */
2179 		private = NULL;
2180 		for (i = 0; i < authctxt->sensitive->nkeys; i++) {
2181 			if (authctxt->sensitive->keys[i] == NULL ||
2182 			    authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
2183 				continue;
2184 			if (!sshkey_match_keyname_to_sigalgs(
2185 			    sshkey_ssh_name(authctxt->sensitive->keys[i]),
2186 			    authctxt->active_ktype))
2187 				continue;
2188 			/* we take and free the key */
2189 			private = authctxt->sensitive->keys[i];
2190 			authctxt->sensitive->keys[i] = NULL;
2191 			break;
2192 		}
2193 		/* Found one */
2194 		if (private != NULL)
2195 			break;
2196 		/* No more keys of this type; advance */
2197 		authctxt->active_ktype = NULL;
2198 	}
2199 	if (private == NULL) {
2200 		free(authctxt->oktypes);
2201 		authctxt->oktypes = authctxt->ktypes = NULL;
2202 		authctxt->active_ktype = NULL;
2203 		debug("No more client hostkeys for hostbased authentication.");
2204 		goto out;
2205 	}
2206 
2207 	if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
2208 	    SSH_FP_DEFAULT)) == NULL) {
2209 		error_f("sshkey_fingerprint failed");
2210 		goto out;
2211 	}
2212 	debug_f("trying hostkey %s %s using sigalg %s",
2213 	    sshkey_ssh_name(private), fp, authctxt->active_ktype);
2214 
2215 	/* figure out a name for the client host */
2216 	lname = get_local_name(ssh_packet_get_connection_in(ssh));
2217 	if (lname == NULL) {
2218 		error_f("cannot get local ipaddr/name");
2219 		goto out;
2220 	}
2221 
2222 	/* XXX sshbuf_put_stringf? */
2223 	xasprintf(&chost, "%s.", lname);
2224 	debug2_f("chost %s", chost);
2225 
2226 	/* construct data */
2227 	if ((b = sshbuf_new()) == NULL) {
2228 		error_f("sshbuf_new failed");
2229 		goto out;
2230 	}
2231 	if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
2232 		error_fr(r, "sshkey_to_blob");
2233 		goto out;
2234 	}
2235 	if ((r = sshbuf_put_stringb(b, ssh->kex->session_id)) != 0 ||
2236 	    (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2237 	    (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
2238 	    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
2239 	    (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
2240 	    (r = sshbuf_put_cstring(b, authctxt->active_ktype)) != 0 ||
2241 	    (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
2242 	    (r = sshbuf_put_cstring(b, chost)) != 0 ||
2243 	    (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
2244 		error_fr(r, "buffer error");
2245 		goto out;
2246 	}
2247 
2248 #ifdef DEBUG_PK
2249 	sshbuf_dump(b, stderr);
2250 #endif
2251 	if ((r = ssh_keysign(ssh, private, &sig, &siglen,
2252 	    sshbuf_ptr(b), sshbuf_len(b))) != 0) {
2253 		error("sign using hostkey %s %s failed",
2254 		    sshkey_ssh_name(private), fp);
2255 		goto out;
2256 	}
2257 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2258 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
2259 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
2260 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
2261 	    (r = sshpkt_put_cstring(ssh, authctxt->active_ktype)) != 0 ||
2262 	    (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
2263 	    (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
2264 	    (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
2265 	    (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
2266 	    (r = sshpkt_send(ssh)) != 0) {
2267 		error_fr(r, "packet error");
2268 		goto out;
2269 	}
2270 	success = 1;
2271 
2272  out:
2273 	if (sig != NULL)
2274 		freezero(sig, siglen);
2275 	free(keyblob);
2276 	free(lname);
2277 	free(fp);
2278 	free(chost);
2279 	sshkey_free(private);
2280 	sshbuf_free(b);
2281 
2282 	return success;
2283 }
2284 
2285 #if KRB5
2286 static int
2287 ssh_krb5_helper(struct ssh *ssh, krb5_data *ap)
2288 {
2289 	krb5_context xcontext = NULL;	/* XXX share with ssh1 */
2290 	krb5_auth_context xauth_context = NULL;
2291 
2292 	krb5_context *context;
2293 	krb5_auth_context *auth_context;
2294 	krb5_error_code problem;
2295 	const char *tkfile;
2296 	struct stat buf;
2297 	krb5_ccache ccache = NULL;
2298 	const char *remotehost;
2299 	int ret;
2300 	const char *errtxt;
2301 
2302 	memset(ap, 0, sizeof(*ap));
2303 
2304 	context = &xcontext;
2305 	auth_context = &xauth_context;
2306 
2307 	problem = krb5_init_context(context);
2308 	if (problem) {
2309 		debug("Kerberos v5: krb5_init_context failed");
2310 		ret = 0;
2311 		goto out;
2312 	}
2313 
2314 	tkfile = krb5_cc_default_name(*context);
2315 	if (strncmp(tkfile, "FILE:", 5) == 0)
2316 		tkfile += 5;
2317 
2318 	if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
2319 		debug("Kerberos v5: could not get default ccache (permission denied).");
2320 		ret = 0;
2321 		goto out;
2322 	}
2323 
2324 	problem = krb5_cc_default(*context, &ccache);
2325 	if (problem) {
2326 		errtxt = krb5_get_error_message(*context, problem);
2327 		if (errtxt != NULL) {
2328 			debug("Kerberos v5: krb5_cc_default failed: %s",
2329 			    errtxt);
2330 			krb5_free_error_message(*context, errtxt);
2331 		} else
2332 			debug("Kerberos v5: krb5_cc_default failed: %d",
2333 			    problem);
2334 		ret = 0;
2335 		goto out;
2336 	}
2337 
2338 	remotehost = auth_get_canonical_hostname(ssh, 1);
2339 
2340 	problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
2341 	    "host", remotehost, NULL, ccache, ap);
2342 	if (problem) {
2343 		errtxt = krb5_get_error_message(*context, problem);
2344 		if (errtxt != NULL) {
2345 			debug("Kerberos v5: krb5_mk_req failed: %s", errtxt);
2346 			krb5_free_error_message(*context, errtxt);
2347 		} else
2348 			debug("Kerberos v5: krb5_mk_req failed: %d", problem);
2349 		ret = 0;
2350 		goto out;
2351 	}
2352 	ret = 1;
2353 
2354  out:
2355 	if (ccache != NULL)
2356 		krb5_cc_close(*context, ccache);
2357 	if (*auth_context)
2358 		krb5_auth_con_free(*context, *auth_context);
2359 	if (*context)
2360 		krb5_free_context(*context);
2361 	return (ret);
2362 }
2363 
2364 static int
2365 userauth_kerberos(struct ssh *ssh)
2366 {
2367 	krb5_data ap;
2368 	int r;
2369 	Authctxt *authctxt = ssh->authctxt;
2370 
2371 	if (ssh_krb5_helper(ssh, &ap) == 0)
2372 		return (0);
2373 
2374 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2375 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
2376 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
2377 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
2378 	    (r = sshpkt_put_string(ssh, ap.data, ap.length)) != 0 ||
2379 	    (r = sshpkt_send(ssh)) != 0 ||
2380 	    (r = ssh_packet_write_wait(ssh)) < 0)
2381 		fatal("%s: %s", __func__, ssh_err(r));
2382 
2383 	krb5_data_free(&ap);
2384 	return (1);
2385 }
2386 #endif
2387 
2388 /* find auth method */
2389 
2390 /*
2391  * given auth method name, if configurable options permit this method fill
2392  * in auth_ident field and return true, otherwise return false.
2393  */
2394 static int
2395 authmethod_is_enabled(Authmethod *method)
2396 {
2397 	if (method == NULL)
2398 		return 0;
2399 	/* return false if options indicate this method is disabled */
2400 	if  (method->enabled == NULL || *method->enabled == 0)
2401 		return 0;
2402 	/* return false if batch mode is enabled but method needs interactive mode */
2403 	if  (method->batch_flag != NULL && *method->batch_flag != 0)
2404 		return 0;
2405 	return 1;
2406 }
2407 
2408 static Authmethod *
2409 authmethod_lookup(const char *name)
2410 {
2411 	Authmethod *method = NULL;
2412 	if (name != NULL)
2413 		for (method = authmethods; method->name != NULL; method++)
2414 			if (strcmp(name, method->name) == 0)
2415 				return method;
2416 	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
2417 	return NULL;
2418 }
2419 
2420 /* XXX internal state */
2421 static Authmethod *current = NULL;
2422 static char *supported = NULL;
2423 static char *preferred = NULL;
2424 
2425 /*
2426  * Given the authentication method list sent by the server, return the
2427  * next method we should try.  If the server initially sends a nil list,
2428  * use a built-in default list.
2429  */
2430 static Authmethod *
2431 authmethod_get(char *authlist)
2432 {
2433 	char *name = NULL;
2434 	u_int next;
2435 
2436 	/* Use a suitable default if we're passed a nil list.  */
2437 	if (authlist == NULL || strlen(authlist) == 0)
2438 		authlist = options.preferred_authentications;
2439 
2440 	if (supported == NULL || strcmp(authlist, supported) != 0) {
2441 		debug3("start over, passed a different list %s", authlist);
2442 		free(supported);
2443 		supported = xstrdup(authlist);
2444 		preferred = options.preferred_authentications;
2445 		debug3("preferred %s", preferred);
2446 		current = NULL;
2447 	} else if (current != NULL && authmethod_is_enabled(current))
2448 		return current;
2449 
2450 	for (;;) {
2451 		if ((name = match_list(preferred, supported, &next)) == NULL) {
2452 			debug("No more authentication methods to try.");
2453 			current = NULL;
2454 			return NULL;
2455 		}
2456 		preferred += next;
2457 		debug3("authmethod_lookup %s", name);
2458 		debug3("remaining preferred: %s", preferred);
2459 		if ((current = authmethod_lookup(name)) != NULL &&
2460 		    authmethod_is_enabled(current)) {
2461 			debug3("authmethod_is_enabled %s", name);
2462 			debug("Next authentication method: %s", name);
2463 			free(name);
2464 			return current;
2465 		}
2466 		free(name);
2467 	}
2468 }
2469 
2470 static char *
2471 authmethods_get(void)
2472 {
2473 	Authmethod *method = NULL;
2474 	struct sshbuf *b;
2475 	char *list;
2476 	int r;
2477 
2478 	if ((b = sshbuf_new()) == NULL)
2479 		fatal_f("sshbuf_new failed");
2480 	for (method = authmethods; method->name != NULL; method++) {
2481 		if (authmethod_is_enabled(method)) {
2482 			if ((r = sshbuf_putf(b, "%s%s",
2483 			    sshbuf_len(b) ? "," : "", method->name)) != 0)
2484 				fatal_fr(r, "buffer error");
2485 		}
2486 	}
2487 	if ((list = sshbuf_dup_string(b)) == NULL)
2488 		fatal_f("sshbuf_dup_string failed");
2489 	sshbuf_free(b);
2490 	return list;
2491 }
2492