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