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