xref: /freebsd/crypto/openssh/sshconnect2.c (revision 716fd348)
1 /* $OpenBSD: sshconnect2.c,v 1.356 2022/02/01 23:32:51 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 "includes.h"
28 
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h>
33 
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <limits.h>
37 #include <netdb.h>
38 #include <pwd.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <stdarg.h>
43 #include <unistd.h>
44 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
45 #include <vis.h>
46 #endif
47 
48 #include "openbsd-compat/sys-queue.h"
49 
50 #include "xmalloc.h"
51 #include "ssh.h"
52 #include "ssh2.h"
53 #include "sshbuf.h"
54 #include "packet.h"
55 #include "compat.h"
56 #include "cipher.h"
57 #include "sshkey.h"
58 #include "kex.h"
59 #include "myproposal.h"
60 #include "sshconnect.h"
61 #include "authfile.h"
62 #include "dh.h"
63 #include "authfd.h"
64 #include "log.h"
65 #include "misc.h"
66 #include "readconf.h"
67 #include "match.h"
68 #include "dispatch.h"
69 #include "canohost.h"
70 #include "msg.h"
71 #include "pathnames.h"
72 #include "uidswap.h"
73 #include "hostfile.h"
74 #include "ssherr.h"
75 #include "utf8.h"
76 #include "ssh-sk.h"
77 #include "sk-api.h"
78 
79 #ifdef GSSAPI
80 #include "ssh-gss.h"
81 #endif
82 
83 /* import */
84 extern char *client_version_string;
85 extern char *server_version_string;
86 extern Options options;
87 
88 /*
89  * SSH2 key exchange
90  */
91 
92 static char *xxx_host;
93 static struct sockaddr *xxx_hostaddr;
94 static const struct ssh_conn_info *xxx_conn_info;
95 
96 static int
97 verify_host_key_callback(struct sshkey *hostkey, struct ssh *ssh)
98 {
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 	int r, use_known_hosts_order = 0;
222 
223 	xxx_host = host;
224 	xxx_hostaddr = hostaddr;
225 	xxx_conn_info = cinfo;
226 
227 	/*
228 	 * If the user has not specified HostkeyAlgorithms, or has only
229 	 * appended or removed algorithms from that list then prefer algorithms
230 	 * that are in the list that are supported by known_hosts keys.
231 	 */
232 	if (options.hostkeyalgorithms == NULL ||
233 	    options.hostkeyalgorithms[0] == '-' ||
234 	    options.hostkeyalgorithms[0] == '+')
235 		use_known_hosts_order = 1;
236 
237 	/* Expand or fill in HostkeyAlgorithms */
238 	all_key = sshkey_alg_list(0, 0, 1, ',');
239 	if ((r = kex_assemble_names(&options.hostkeyalgorithms,
240 	    kex_default_pk_alg(), all_key)) != 0)
241 		fatal_fr(r, "kex_assemble_namelist");
242 	free(all_key);
243 
244 	if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
245 		fatal_f("kex_names_cat");
246 	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(ssh, s);
247 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
248 	    compat_cipher_proposal(ssh, options.ciphers);
249 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
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] =
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] =
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 # ifdef OPENSSL_HAS_ECC
283 	ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
284 # endif
285 #endif
286 	ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
287 	ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
288 	ssh->kex->verify_host_key=&verify_host_key_callback;
289 
290 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &ssh->kex->done);
291 
292 	/* remove ext-info from the KEX proposals for rekeying */
293 	myproposal[PROPOSAL_KEX_ALGS] =
294 	    compat_kex_proposal(ssh, options.kex_algorithms);
295 	if ((r = kex_prop2buf(ssh->kex->my, myproposal)) != 0)
296 		fatal_r(r, "kex_prop2buf");
297 
298 #ifdef DEBUG_KEXDH
299 	/* send 1st encrypted/maced/compressed message */
300 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
301 	    (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
302 	    (r = sshpkt_send(ssh)) != 0 ||
303 	    (r = ssh_packet_write_wait(ssh)) != 0)
304 		fatal_fr(r, "send packet");
305 #endif
306 }
307 
308 /*
309  * Authenticate user
310  */
311 
312 typedef struct cauthctxt Authctxt;
313 typedef struct cauthmethod Authmethod;
314 typedef struct identity Identity;
315 typedef struct idlist Idlist;
316 
317 struct identity {
318 	TAILQ_ENTRY(identity) next;
319 	int	agent_fd;		/* >=0 if agent supports key */
320 	struct sshkey	*key;		/* public/private key */
321 	char	*filename;		/* comment for agent-only keys */
322 	int	tried;
323 	int	isprivate;		/* key points to the private key */
324 	int	userprovided;
325 };
326 TAILQ_HEAD(idlist, identity);
327 
328 struct cauthctxt {
329 	const char *server_user;
330 	const char *local_user;
331 	const char *host;
332 	const char *service;
333 	struct cauthmethod *method;
334 	sig_atomic_t success;
335 	char *authlist;
336 #ifdef GSSAPI
337 	/* gssapi */
338 	gss_OID_set gss_supported_mechs;
339 	u_int mech_tried;
340 #endif
341 	/* pubkey */
342 	struct idlist keys;
343 	int agent_fd;
344 	/* hostbased */
345 	Sensitive *sensitive;
346 	char *oktypes, *ktypes;
347 	const char *active_ktype;
348 	/* kbd-interactive */
349 	int info_req_seen;
350 	int attempt_kbdint;
351 	/* password */
352 	int attempt_passwd;
353 	/* generic */
354 	void *methoddata;
355 };
356 
357 struct cauthmethod {
358 	char	*name;		/* string to compare against server's list */
359 	int	(*userauth)(struct ssh *ssh);
360 	void	(*cleanup)(struct ssh *ssh);
361 	int	*enabled;	/* flag in option struct that enables method */
362 	int	*batch_flag;	/* flag in option struct that disables method */
363 };
364 
365 static int input_userauth_service_accept(int, u_int32_t, struct ssh *);
366 static int input_userauth_ext_info(int, u_int32_t, struct ssh *);
367 static int input_userauth_success(int, u_int32_t, struct ssh *);
368 static int input_userauth_failure(int, u_int32_t, struct ssh *);
369 static int input_userauth_banner(int, u_int32_t, struct ssh *);
370 static int input_userauth_error(int, u_int32_t, struct ssh *);
371 static int input_userauth_info_req(int, u_int32_t, struct ssh *);
372 static int input_userauth_pk_ok(int, u_int32_t, struct ssh *);
373 static int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *);
374 
375 static int userauth_none(struct ssh *);
376 static int userauth_pubkey(struct ssh *);
377 static int userauth_passwd(struct ssh *);
378 static int userauth_kbdint(struct ssh *);
379 static int userauth_hostbased(struct ssh *);
380 
381 #ifdef GSSAPI
382 static int userauth_gssapi(struct ssh *);
383 static void userauth_gssapi_cleanup(struct ssh *);
384 static int input_gssapi_response(int type, u_int32_t, struct ssh *);
385 static int input_gssapi_token(int type, u_int32_t, struct ssh *);
386 static int input_gssapi_error(int, u_int32_t, struct ssh *);
387 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
388 #endif
389 
390 void	userauth(struct ssh *, char *);
391 
392 static void pubkey_cleanup(struct ssh *);
393 static int sign_and_send_pubkey(struct ssh *ssh, Identity *);
394 static void pubkey_prepare(struct ssh *, Authctxt *);
395 static void pubkey_reset(Authctxt *);
396 static struct sshkey *load_identity_file(Identity *);
397 
398 static Authmethod *authmethod_get(char *authlist);
399 static Authmethod *authmethod_lookup(const char *name);
400 static char *authmethods_get(void);
401 
402 Authmethod authmethods[] = {
403 #ifdef GSSAPI
404 	{"gssapi-with-mic",
405 		userauth_gssapi,
406 		userauth_gssapi_cleanup,
407 		&options.gss_authentication,
408 		NULL},
409 #endif
410 	{"hostbased",
411 		userauth_hostbased,
412 		NULL,
413 		&options.hostbased_authentication,
414 		NULL},
415 	{"publickey",
416 		userauth_pubkey,
417 		NULL,
418 		&options.pubkey_authentication,
419 		NULL},
420 	{"keyboard-interactive",
421 		userauth_kbdint,
422 		NULL,
423 		&options.kbd_interactive_authentication,
424 		&options.batch_mode},
425 	{"password",
426 		userauth_passwd,
427 		NULL,
428 		&options.password_authentication,
429 		&options.batch_mode},
430 	{"none",
431 		userauth_none,
432 		NULL,
433 		NULL,
434 		NULL},
435 	{NULL, NULL, NULL, NULL, NULL}
436 };
437 
438 void
439 ssh_userauth2(struct ssh *ssh, const char *local_user,
440     const char *server_user, char *host, Sensitive *sensitive)
441 {
442 	Authctxt authctxt;
443 	int r;
444 
445 	if (options.preferred_authentications == NULL)
446 		options.preferred_authentications = authmethods_get();
447 
448 	/* setup authentication context */
449 	memset(&authctxt, 0, sizeof(authctxt));
450 	authctxt.server_user = server_user;
451 	authctxt.local_user = local_user;
452 	authctxt.host = host;
453 	authctxt.service = "ssh-connection";		/* service name */
454 	authctxt.success = 0;
455 	authctxt.method = authmethod_lookup("none");
456 	authctxt.authlist = NULL;
457 	authctxt.methoddata = NULL;
458 	authctxt.sensitive = sensitive;
459 	authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
460 	authctxt.info_req_seen = 0;
461 	authctxt.attempt_kbdint = 0;
462 	authctxt.attempt_passwd = 0;
463 #if GSSAPI
464 	authctxt.gss_supported_mechs = NULL;
465 	authctxt.mech_tried = 0;
466 #endif
467 	authctxt.agent_fd = -1;
468 	pubkey_prepare(ssh, &authctxt);
469 	if (authctxt.method == NULL) {
470 		fatal_f("internal error: cannot send userauth none request");
471 	}
472 
473 	if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
474 	    (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
475 	    (r = sshpkt_send(ssh)) != 0)
476 		fatal_fr(r, "send packet");
477 
478 	ssh->authctxt = &authctxt;
479 	ssh_dispatch_init(ssh, &input_userauth_error);
480 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info);
481 	ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
482 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success);	/* loop until success */
483 	pubkey_cleanup(ssh);
484 	ssh->authctxt = NULL;
485 
486 	ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
487 
488 	if (!authctxt.success)
489 		fatal("Authentication failed.");
490 	if (ssh_packet_connection_is_on_socket(ssh)) {
491 		verbose("Authenticated to %s ([%s]:%d) using \"%s\".", host,
492 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
493 		    authctxt.method->name);
494 	} else {
495 		verbose("Authenticated to %s (via proxy) using \"%s\".", host,
496 		    authctxt.method->name);
497 	}
498 }
499 
500 /* ARGSUSED */
501 static int
502 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
503 {
504 	int r;
505 
506 	if (ssh_packet_remaining(ssh) > 0) {
507 		char *reply;
508 
509 		if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
510 			goto out;
511 		debug2("service_accept: %s", reply);
512 		free(reply);
513 	} else {
514 		debug2("buggy server: service_accept w/o service");
515 	}
516 	if ((r = sshpkt_get_end(ssh)) != 0)
517 		goto out;
518 	debug("SSH2_MSG_SERVICE_ACCEPT received");
519 
520 	/* initial userauth request */
521 	userauth_none(ssh);
522 
523 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
524 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
525 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
526 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
527 	r = 0;
528  out:
529 	return r;
530 }
531 
532 /* ARGSUSED */
533 static int
534 input_userauth_ext_info(int type, u_int32_t seqnr, struct ssh *ssh)
535 {
536 	return kex_input_ext_info(type, seqnr, ssh);
537 }
538 
539 void
540 userauth(struct ssh *ssh, char *authlist)
541 {
542 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
543 
544 	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
545 		authctxt->method->cleanup(ssh);
546 
547 	free(authctxt->methoddata);
548 	authctxt->methoddata = NULL;
549 	if (authlist == NULL) {
550 		authlist = authctxt->authlist;
551 	} else {
552 		free(authctxt->authlist);
553 		authctxt->authlist = authlist;
554 	}
555 	for (;;) {
556 		Authmethod *method = authmethod_get(authlist);
557 		if (method == NULL)
558 			fatal("%s@%s: Permission denied (%s).",
559 			    authctxt->server_user, authctxt->host, authlist);
560 		authctxt->method = method;
561 
562 		/* reset the per method handler */
563 		ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_PER_METHOD_MIN,
564 		    SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
565 
566 		/* and try new method */
567 		if (method->userauth(ssh) != 0) {
568 			debug2("we sent a %s packet, wait for reply", method->name);
569 			break;
570 		} else {
571 			debug2("we did not send a packet, disable method");
572 			method->enabled = NULL;
573 		}
574 	}
575 }
576 
577 /* ARGSUSED */
578 static int
579 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
580 {
581 	fatal_f("bad message during authentication: type %d", type);
582 	return 0;
583 }
584 
585 /* ARGSUSED */
586 static int
587 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
588 {
589 	char *msg = NULL;
590 	size_t len;
591 	int r;
592 
593 	debug3_f("entering");
594 	if ((r = sshpkt_get_cstring(ssh, &msg, &len)) != 0 ||
595 	    (r = sshpkt_get_cstring(ssh, NULL, NULL)) != 0)
596 		goto out;
597 	if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
598 		fmprintf(stderr, "%s", msg);
599 	r = 0;
600  out:
601 	free(msg);
602 	return r;
603 }
604 
605 /* ARGSUSED */
606 static int
607 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh)
608 {
609 	Authctxt *authctxt = ssh->authctxt;
610 
611 	if (authctxt == NULL)
612 		fatal_f("no authentication context");
613 	free(authctxt->authlist);
614 	authctxt->authlist = NULL;
615 	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
616 		authctxt->method->cleanup(ssh);
617 	free(authctxt->methoddata);
618 	authctxt->methoddata = NULL;
619 	authctxt->success = 1;			/* break out */
620 	return 0;
621 }
622 
623 #if 0
624 static int
625 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh)
626 {
627 	Authctxt *authctxt = ssh->authctxt;
628 
629 	if (authctxt == NULL)
630 		fatal_f("no authentication context");
631 
632 	fatal("Unexpected authentication success during %s.",
633 	    authctxt->method->name);
634 	return 0;
635 }
636 #endif
637 
638 /* ARGSUSED */
639 static int
640 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
641 {
642 	Authctxt *authctxt = ssh->authctxt;
643 	char *authlist = NULL;
644 	u_char partial;
645 
646 	if (authctxt == NULL)
647 		fatal("input_userauth_failure: no authentication context");
648 
649 	if (sshpkt_get_cstring(ssh, &authlist, NULL) != 0 ||
650 	    sshpkt_get_u8(ssh, &partial) != 0 ||
651 	    sshpkt_get_end(ssh) != 0)
652 		goto out;
653 
654 	if (partial != 0) {
655 		verbose("Authenticated using \"%s\" with partial success.",
656 		    authctxt->method->name);
657 		/* reset state */
658 		pubkey_reset(authctxt);
659 	}
660 	debug("Authentications that can continue: %s", authlist);
661 
662 	userauth(ssh, authlist);
663 	authlist = NULL;
664  out:
665 	free(authlist);
666 	return 0;
667 }
668 
669 /*
670  * Format an identity for logging including filename, key type, fingerprint
671  * and location (agent, etc.). Caller must free.
672  */
673 static char *
674 format_identity(Identity *id)
675 {
676 	char *fp = NULL, *ret = NULL;
677 	const char *note = "";
678 
679 	if (id->key != NULL) {
680 		fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
681 		    SSH_FP_DEFAULT);
682 	}
683 	if (id->key) {
684 		if ((id->key->flags & SSHKEY_FLAG_EXT) != 0)
685 			note = " token";
686 		else if (sshkey_is_sk(id->key))
687 			note = " authenticator";
688 	}
689 	xasprintf(&ret, "%s %s%s%s%s%s%s",
690 	    id->filename,
691 	    id->key ? sshkey_type(id->key) : "", id->key ? " " : "",
692 	    fp ? fp : "",
693 	    id->userprovided ? " explicit" : "", note,
694 	    id->agent_fd != -1 ? " agent" : "");
695 	free(fp);
696 	return ret;
697 }
698 
699 /* ARGSUSED */
700 static int
701 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
702 {
703 	Authctxt *authctxt = ssh->authctxt;
704 	struct sshkey *key = NULL;
705 	Identity *id = NULL;
706 	int pktype, found = 0, sent = 0;
707 	size_t blen;
708 	char *pkalg = NULL, *fp = NULL, *ident = NULL;
709 	u_char *pkblob = NULL;
710 	int r;
711 
712 	if (authctxt == NULL)
713 		fatal("input_userauth_pk_ok: no authentication context");
714 
715 	if ((r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
716 	    (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
717 	    (r = sshpkt_get_end(ssh)) != 0)
718 		goto done;
719 
720 	if ((pktype = sshkey_type_from_name(pkalg)) == KEY_UNSPEC) {
721 		debug_f("server sent unknown pkalg %s", pkalg);
722 		goto done;
723 	}
724 	if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
725 		debug_r(r, "no key from blob. pkalg %s", pkalg);
726 		goto done;
727 	}
728 	if (key->type != pktype) {
729 		error("input_userauth_pk_ok: type mismatch "
730 		    "for decoded key (received %d, expected %d)",
731 		    key->type, pktype);
732 		goto done;
733 	}
734 
735 	/*
736 	 * search keys in the reverse order, because last candidate has been
737 	 * moved to the end of the queue.  this also avoids confusion by
738 	 * duplicate keys
739 	 */
740 	TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
741 		if (sshkey_equal(key, id->key)) {
742 			found = 1;
743 			break;
744 		}
745 	}
746 	if (!found || id == NULL) {
747 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
748 		    SSH_FP_DEFAULT);
749 		error_f("server replied with unknown key: %s %s",
750 		    sshkey_type(key), fp == NULL ? "<ERROR>" : fp);
751 		goto done;
752 	}
753 	ident = format_identity(id);
754 	debug("Server accepts key: %s", ident);
755 	sent = sign_and_send_pubkey(ssh, id);
756 	r = 0;
757  done:
758 	sshkey_free(key);
759 	free(ident);
760 	free(fp);
761 	free(pkalg);
762 	free(pkblob);
763 
764 	/* try another method if we did not send a packet */
765 	if (r == 0 && sent == 0)
766 		userauth(ssh, NULL);
767 	return r;
768 }
769 
770 #ifdef GSSAPI
771 static int
772 userauth_gssapi(struct ssh *ssh)
773 {
774 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
775 	Gssctxt *gssctxt = NULL;
776 	OM_uint32 min;
777 	int r, ok = 0;
778 	gss_OID mech = NULL;
779 
780 	/* Try one GSSAPI method at a time, rather than sending them all at
781 	 * once. */
782 
783 	if (authctxt->gss_supported_mechs == NULL)
784 		gss_indicate_mechs(&min, &authctxt->gss_supported_mechs);
785 
786 	/* Check to see whether the mechanism is usable before we offer it */
787 	while (authctxt->mech_tried < authctxt->gss_supported_mechs->count &&
788 	    !ok) {
789 		mech = &authctxt->gss_supported_mechs->
790 		    elements[authctxt->mech_tried];
791 		/* My DER encoding requires length<128 */
792 		if (mech->length < 128 && ssh_gssapi_check_mechanism(&gssctxt,
793 		    mech, authctxt->host)) {
794 			ok = 1; /* Mechanism works */
795 		} else {
796 			authctxt->mech_tried++;
797 		}
798 	}
799 
800 	if (!ok || mech == NULL)
801 		return 0;
802 
803 	authctxt->methoddata=(void *)gssctxt;
804 
805 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
806 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
807 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
808 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
809 	    (r = sshpkt_put_u32(ssh, 1)) != 0 ||
810 	    (r = sshpkt_put_u32(ssh, (mech->length) + 2)) != 0 ||
811 	    (r = sshpkt_put_u8(ssh, SSH_GSS_OIDTYPE)) != 0 ||
812 	    (r = sshpkt_put_u8(ssh, mech->length)) != 0 ||
813 	    (r = sshpkt_put(ssh, mech->elements, mech->length)) != 0 ||
814 	    (r = sshpkt_send(ssh)) != 0)
815 		fatal_fr(r, "send packet");
816 
817 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
818 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
819 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
820 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
821 
822 	authctxt->mech_tried++; /* Move along to next candidate */
823 
824 	return 1;
825 }
826 
827 static void
828 userauth_gssapi_cleanup(struct ssh *ssh)
829 {
830 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
831 	Gssctxt *gssctxt = (Gssctxt *)authctxt->methoddata;
832 
833 	ssh_gssapi_delete_ctx(&gssctxt);
834 	authctxt->methoddata = NULL;
835 
836 	free(authctxt->gss_supported_mechs);
837 	authctxt->gss_supported_mechs = NULL;
838 }
839 
840 static OM_uint32
841 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
842 {
843 	Authctxt *authctxt = ssh->authctxt;
844 	Gssctxt *gssctxt = authctxt->methoddata;
845 	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
846 	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
847 	gss_buffer_desc gssbuf;
848 	OM_uint32 status, ms, flags;
849 	int r;
850 
851 	status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
852 	    recv_tok, &send_tok, &flags);
853 
854 	if (send_tok.length > 0) {
855 		u_char type = GSS_ERROR(status) ?
856 		    SSH2_MSG_USERAUTH_GSSAPI_ERRTOK :
857 		    SSH2_MSG_USERAUTH_GSSAPI_TOKEN;
858 
859 		if ((r = sshpkt_start(ssh, type)) != 0 ||
860 		    (r = sshpkt_put_string(ssh, send_tok.value,
861 		    send_tok.length)) != 0 ||
862 		    (r = sshpkt_send(ssh)) != 0)
863 			fatal_fr(r, "send %u packet", type);
864 
865 		gss_release_buffer(&ms, &send_tok);
866 	}
867 
868 	if (status == GSS_S_COMPLETE) {
869 		/* send either complete or MIC, depending on mechanism */
870 		if (!(flags & GSS_C_INTEG_FLAG)) {
871 			if ((r = sshpkt_start(ssh,
872 			    SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)) != 0 ||
873 			    (r = sshpkt_send(ssh)) != 0)
874 				fatal_fr(r, "send completion");
875 		} else {
876 			struct sshbuf *b;
877 
878 			if ((b = sshbuf_new()) == NULL)
879 				fatal_f("sshbuf_new failed");
880 			ssh_gssapi_buildmic(b, authctxt->server_user,
881 			    authctxt->service, "gssapi-with-mic",
882 			    ssh->kex->session_id);
883 
884 			if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
885 				fatal_f("sshbuf_mutable_ptr failed");
886 			gssbuf.length = sshbuf_len(b);
887 
888 			status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
889 
890 			if (!GSS_ERROR(status)) {
891 				if ((r = sshpkt_start(ssh,
892 				    SSH2_MSG_USERAUTH_GSSAPI_MIC)) != 0 ||
893 				    (r = sshpkt_put_string(ssh, mic.value,
894 				    mic.length)) != 0 ||
895 				    (r = sshpkt_send(ssh)) != 0)
896 					fatal_fr(r, "send MIC");
897 			}
898 
899 			sshbuf_free(b);
900 			gss_release_buffer(&ms, &mic);
901 		}
902 	}
903 
904 	return status;
905 }
906 
907 /* ARGSUSED */
908 static int
909 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
910 {
911 	Authctxt *authctxt = ssh->authctxt;
912 	Gssctxt *gssctxt;
913 	size_t oidlen;
914 	u_char *oidv = NULL;
915 	int r;
916 
917 	if (authctxt == NULL)
918 		fatal("input_gssapi_response: no authentication context");
919 	gssctxt = authctxt->methoddata;
920 
921 	/* Setup our OID */
922 	if ((r = sshpkt_get_string(ssh, &oidv, &oidlen)) != 0)
923 		goto done;
924 
925 	if (oidlen <= 2 ||
926 	    oidv[0] != SSH_GSS_OIDTYPE ||
927 	    oidv[1] != oidlen - 2) {
928 		debug("Badly encoded mechanism OID received");
929 		userauth(ssh, NULL);
930 		goto ok;
931 	}
932 
933 	if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
934 		fatal("Server returned different OID than expected");
935 
936 	if ((r = sshpkt_get_end(ssh)) != 0)
937 		goto done;
938 
939 	if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
940 		/* Start again with next method on list */
941 		debug("Trying to start again");
942 		userauth(ssh, NULL);
943 		goto ok;
944 	}
945  ok:
946 	r = 0;
947  done:
948 	free(oidv);
949 	return r;
950 }
951 
952 /* ARGSUSED */
953 static int
954 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
955 {
956 	Authctxt *authctxt = ssh->authctxt;
957 	gss_buffer_desc recv_tok;
958 	u_char *p = NULL;
959 	size_t len;
960 	OM_uint32 status;
961 	int r;
962 
963 	if (authctxt == NULL)
964 		fatal("input_gssapi_response: no authentication context");
965 
966 	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
967 	    (r = sshpkt_get_end(ssh)) != 0)
968 		goto out;
969 
970 	recv_tok.value = p;
971 	recv_tok.length = len;
972 	status = process_gssapi_token(ssh, &recv_tok);
973 
974 	/* Start again with the next method in the list */
975 	if (GSS_ERROR(status)) {
976 		userauth(ssh, NULL);
977 		/* ok */
978 	}
979 	r = 0;
980  out:
981 	free(p);
982 	return r;
983 }
984 
985 /* ARGSUSED */
986 static int
987 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
988 {
989 	Authctxt *authctxt = ssh->authctxt;
990 	Gssctxt *gssctxt;
991 	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
992 	gss_buffer_desc recv_tok;
993 	OM_uint32 ms;
994 	u_char *p = NULL;
995 	size_t len;
996 	int r;
997 
998 	if (authctxt == NULL)
999 		fatal("input_gssapi_response: no authentication context");
1000 	gssctxt = authctxt->methoddata;
1001 
1002 	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
1003 	    (r = sshpkt_get_end(ssh)) != 0) {
1004 		free(p);
1005 		return r;
1006 	}
1007 
1008 	/* Stick it into GSSAPI and see what it says */
1009 	recv_tok.value = p;
1010 	recv_tok.length = len;
1011 	(void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
1012 	    &recv_tok, &send_tok, NULL);
1013 	free(p);
1014 	gss_release_buffer(&ms, &send_tok);
1015 
1016 	/* Server will be returning a failed packet after this one */
1017 	return 0;
1018 }
1019 
1020 /* ARGSUSED */
1021 static int
1022 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
1023 {
1024 	char *msg = NULL;
1025 	char *lang = NULL;
1026 	int r;
1027 
1028 	if ((r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* maj */
1029 	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* min */
1030 	    (r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
1031 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1032 		goto out;
1033 	r = sshpkt_get_end(ssh);
1034 	debug("Server GSSAPI Error:\n%s", msg);
1035  out:
1036 	free(msg);
1037 	free(lang);
1038 	return r;
1039 }
1040 #endif /* GSSAPI */
1041 
1042 static int
1043 userauth_none(struct ssh *ssh)
1044 {
1045 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1046 	int r;
1047 
1048 	/* initial userauth request */
1049 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1050 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1051 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1052 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1053 	    (r = sshpkt_send(ssh)) != 0)
1054 		fatal_fr(r, "send packet");
1055 	return 1;
1056 }
1057 
1058 static int
1059 userauth_passwd(struct ssh *ssh)
1060 {
1061 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1062 	char *password, *prompt = NULL;
1063 	const char *host = options.host_key_alias ?  options.host_key_alias :
1064 	    authctxt->host;
1065 	int r;
1066 
1067 	if (authctxt->attempt_passwd++ >= options.number_of_password_prompts)
1068 		return 0;
1069 
1070 	if (authctxt->attempt_passwd != 1)
1071 		error("Permission denied, please try again.");
1072 
1073 	xasprintf(&prompt, "%s@%s's password: ", authctxt->server_user, host);
1074 	password = read_passphrase(prompt, 0);
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_put_u8(ssh, 0)) != 0 ||
1080 	    (r = sshpkt_put_cstring(ssh, password)) != 0 ||
1081 	    (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1082 	    (r = sshpkt_send(ssh)) != 0)
1083 		fatal_fr(r, "send packet");
1084 
1085 	free(prompt);
1086 	if (password != NULL)
1087 		freezero(password, strlen(password));
1088 
1089 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1090 	    &input_userauth_passwd_changereq);
1091 
1092 	return 1;
1093 }
1094 
1095 /*
1096  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
1097  */
1098 /* ARGSUSED */
1099 static int
1100 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
1101 {
1102 	Authctxt *authctxt = ssh->authctxt;
1103 	char *info = NULL, *lang = NULL, *password = NULL, *retype = NULL;
1104 	char prompt[256];
1105 	const char *host;
1106 	int r;
1107 
1108 	debug2("input_userauth_passwd_changereq");
1109 
1110 	if (authctxt == NULL)
1111 		fatal("input_userauth_passwd_changereq: "
1112 		    "no authentication context");
1113 	host = options.host_key_alias ? options.host_key_alias : authctxt->host;
1114 
1115 	if ((r = sshpkt_get_cstring(ssh, &info, NULL)) != 0 ||
1116 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1117 		goto out;
1118 	if (strlen(info) > 0)
1119 		logit("%s", info);
1120 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1121 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1122 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1123 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1124 	    (r = sshpkt_put_u8(ssh, 1)) != 0)	/* additional info */
1125 		goto out;
1126 
1127 	snprintf(prompt, sizeof(prompt),
1128 	    "Enter %.30s@%.128s's old password: ",
1129 	    authctxt->server_user, host);
1130 	password = read_passphrase(prompt, 0);
1131 	if ((r = sshpkt_put_cstring(ssh, password)) != 0)
1132 		goto out;
1133 
1134 	freezero(password, strlen(password));
1135 	password = NULL;
1136 	while (password == NULL) {
1137 		snprintf(prompt, sizeof(prompt),
1138 		    "Enter %.30s@%.128s's new password: ",
1139 		    authctxt->server_user, host);
1140 		password = read_passphrase(prompt, RP_ALLOW_EOF);
1141 		if (password == NULL) {
1142 			/* bail out */
1143 			r = 0;
1144 			goto out;
1145 		}
1146 		snprintf(prompt, sizeof(prompt),
1147 		    "Retype %.30s@%.128s's new password: ",
1148 		    authctxt->server_user, host);
1149 		retype = read_passphrase(prompt, 0);
1150 		if (strcmp(password, retype) != 0) {
1151 			freezero(password, strlen(password));
1152 			logit("Mismatch; try again, EOF to quit.");
1153 			password = NULL;
1154 		}
1155 		freezero(retype, strlen(retype));
1156 	}
1157 	if ((r = sshpkt_put_cstring(ssh, password)) != 0 ||
1158 	    (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1159 	    (r = sshpkt_send(ssh)) != 0)
1160 		goto out;
1161 
1162 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1163 	    &input_userauth_passwd_changereq);
1164 	r = 0;
1165  out:
1166 	if (password)
1167 		freezero(password, strlen(password));
1168 	free(info);
1169 	free(lang);
1170 	return r;
1171 }
1172 
1173 /*
1174  * Select an algorithm for publickey signatures.
1175  * Returns algorithm (caller must free) or NULL if no mutual algorithm found.
1176  *
1177  * Call with ssh==NULL to ignore server-sig-algs extension list and
1178  * only attempt with the key's base signature type.
1179  */
1180 static char *
1181 key_sig_algorithm(struct ssh *ssh, const struct sshkey *key)
1182 {
1183 	char *allowed, *oallowed, *cp, *tmp, *alg = NULL;
1184 	const char *server_sig_algs;
1185 
1186 	/*
1187 	 * The signature algorithm will only differ from the key algorithm
1188 	 * for RSA keys/certs and when the server advertises support for
1189 	 * newer (SHA2) algorithms.
1190 	 */
1191 	if (ssh == NULL || ssh->kex->server_sig_algs == NULL ||
1192 	    (key->type != KEY_RSA && key->type != KEY_RSA_CERT) ||
1193 	    (key->type == KEY_RSA_CERT && (ssh->compat & SSH_BUG_SIGTYPE))) {
1194 		/* Filter base key signature alg against our configuration */
1195 		return match_list(sshkey_ssh_name(key),
1196 		    options.pubkey_accepted_algos, NULL);
1197 	}
1198 
1199 	/*
1200 	 * Workaround OpenSSH 7.4 bug: this version supports RSA/SHA-2 but
1201 	 * fails to advertise it via SSH2_MSG_EXT_INFO.
1202 	 */
1203 	server_sig_algs = ssh->kex->server_sig_algs;
1204 	if (key->type == KEY_RSA && (ssh->compat & SSH_BUG_SIGTYPE74))
1205 		server_sig_algs = "rsa-sha2-256,rsa-sha2-512";
1206 
1207 	/*
1208 	 * For RSA keys/certs, since these might have a different sig type:
1209 	 * find the first entry in PubkeyAcceptedAlgorithms of the right type
1210 	 * that also appears in the supported signature algorithms list from
1211 	 * the server.
1212 	 */
1213 	oallowed = allowed = xstrdup(options.pubkey_accepted_algos);
1214 	while ((cp = strsep(&allowed, ",")) != NULL) {
1215 		if (sshkey_type_from_name(cp) != key->type)
1216 			continue;
1217 		tmp = match_list(sshkey_sigalg_by_name(cp),
1218 		    server_sig_algs, NULL);
1219 		if (tmp != NULL)
1220 			alg = xstrdup(cp);
1221 		free(tmp);
1222 		if (alg != NULL)
1223 			break;
1224 	}
1225 	free(oallowed);
1226 	return alg;
1227 }
1228 
1229 static int
1230 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1231     const u_char *data, size_t datalen, u_int compat, const char *alg)
1232 {
1233 	struct sshkey *sign_key = NULL, *prv = NULL;
1234 	int retried = 0, r = SSH_ERR_INTERNAL_ERROR;
1235 	struct notifier_ctx *notifier = NULL;
1236 	char *fp = NULL, *pin = NULL, *prompt = NULL;
1237 
1238 	*sigp = NULL;
1239 	*lenp = 0;
1240 
1241 	/* The agent supports this key. */
1242 	if (id->key != NULL && id->agent_fd != -1) {
1243 		return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1244 		    data, datalen, alg, compat);
1245 	}
1246 
1247 	/*
1248 	 * We have already loaded the private key or the private key is
1249 	 * stored in external hardware.
1250 	 */
1251 	if (id->key != NULL &&
1252 	    (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) {
1253 		sign_key = id->key;
1254 	} else {
1255 		/* Load the private key from the file. */
1256 		if ((prv = load_identity_file(id)) == NULL)
1257 			return SSH_ERR_KEY_NOT_FOUND;
1258 		if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1259 			error_f("private key %s contents do not match public",
1260 			    id->filename);
1261 			r = SSH_ERR_KEY_NOT_FOUND;
1262 			goto out;
1263 		}
1264 		sign_key = prv;
1265 		if (sshkey_is_sk(sign_key)) {
1266 			if ((sign_key->sk_flags &
1267 			    SSH_SK_USER_VERIFICATION_REQD)) {
1268  retry_pin:
1269 				xasprintf(&prompt, "Enter PIN for %s key %s: ",
1270 				    sshkey_type(sign_key), id->filename);
1271 				pin = read_passphrase(prompt, 0);
1272 			}
1273 			if ((sign_key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1274 				/* XXX should batch mode just skip these? */
1275 				if ((fp = sshkey_fingerprint(sign_key,
1276 				    options.fingerprint_hash,
1277 				    SSH_FP_DEFAULT)) == NULL)
1278 					fatal_f("fingerprint failed");
1279 				notifier = notify_start(options.batch_mode,
1280 				    "Confirm user presence for key %s %s",
1281 				    sshkey_type(sign_key), fp);
1282 				free(fp);
1283 			}
1284 		}
1285 	}
1286 	if ((r = sshkey_sign(sign_key, sigp, lenp, data, datalen,
1287 	    alg, options.sk_provider, pin, compat)) != 0) {
1288 		debug_fr(r, "sshkey_sign");
1289 		if (pin == NULL && !retried && sshkey_is_sk(sign_key) &&
1290 		    r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1291 			notify_complete(notifier, NULL);
1292 			notifier = NULL;
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 && private != NULL && id->agent_fd == -1 &&
1608 		    !(id->key && id->isprivate))
1609 			maybe_add_key_to_agent(id->filename, private, comment,
1610 			    passphrase);
1611 		if (i > 0)
1612 			freezero(passphrase, strlen(passphrase));
1613 		free(comment);
1614 		if (private != NULL || quit)
1615 			break;
1616 	}
1617 	return private;
1618 }
1619 
1620 static int
1621 key_type_allowed_by_config(struct sshkey *key)
1622 {
1623 	if (match_pattern_list(sshkey_ssh_name(key),
1624 	    options.pubkey_accepted_algos, 0) == 1)
1625 		return 1;
1626 
1627 	/* RSA keys/certs might be allowed by alternate signature types */
1628 	switch (key->type) {
1629 	case KEY_RSA:
1630 		if (match_pattern_list("rsa-sha2-512",
1631 		    options.pubkey_accepted_algos, 0) == 1)
1632 			return 1;
1633 		if (match_pattern_list("rsa-sha2-256",
1634 		    options.pubkey_accepted_algos, 0) == 1)
1635 			return 1;
1636 		break;
1637 	case KEY_RSA_CERT:
1638 		if (match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
1639 		    options.pubkey_accepted_algos, 0) == 1)
1640 			return 1;
1641 		if (match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
1642 		    options.pubkey_accepted_algos, 0) == 1)
1643 			return 1;
1644 		break;
1645 	}
1646 	return 0;
1647 }
1648 
1649 /* obtain a list of keys from the agent */
1650 static int
1651 get_agent_identities(struct ssh *ssh, int *agent_fdp,
1652     struct ssh_identitylist **idlistp)
1653 {
1654 	int r, agent_fd;
1655 	struct ssh_identitylist *idlist;
1656 
1657 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1658 		if (r != SSH_ERR_AGENT_NOT_PRESENT)
1659 			debug_fr(r, "ssh_get_authentication_socket");
1660 		return r;
1661 	}
1662 	if ((r = ssh_agent_bind_hostkey(agent_fd, ssh->kex->initial_hostkey,
1663 	    ssh->kex->session_id, ssh->kex->initial_sig, 0)) == 0)
1664 		debug_f("bound agent to hostkey");
1665 	else
1666 		debug2_fr(r, "ssh_agent_bind_hostkey");
1667 
1668 	if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1669 		debug_fr(r, "ssh_fetch_identitylist");
1670 		close(agent_fd);
1671 		return r;
1672 	}
1673 	/* success */
1674 	*agent_fdp = agent_fd;
1675 	*idlistp = idlist;
1676 	debug_f("agent returned %zu keys", idlist->nkeys);
1677 	return 0;
1678 }
1679 
1680 /*
1681  * try keys in the following order:
1682  *	1. certificates listed in the config file
1683  *	2. other input certificates
1684  *	3. agent keys that are found in the config file
1685  *	4. other agent keys
1686  *	5. keys that are only listed in the config file
1687  */
1688 static void
1689 pubkey_prepare(struct ssh *ssh, Authctxt *authctxt)
1690 {
1691 	struct identity *id, *id2, *tmp;
1692 	struct idlist agent, files, *preferred;
1693 	struct sshkey *key;
1694 	int agent_fd = -1, i, r, found;
1695 	size_t j;
1696 	struct ssh_identitylist *idlist;
1697 	char *ident;
1698 
1699 	TAILQ_INIT(&agent);	/* keys from the agent */
1700 	TAILQ_INIT(&files);	/* keys from the config file */
1701 	preferred = &authctxt->keys;
1702 	TAILQ_INIT(preferred);	/* preferred order of keys */
1703 
1704 	/* list of keys stored in the filesystem and PKCS#11 */
1705 	for (i = 0; i < options.num_identity_files; i++) {
1706 		key = options.identity_keys[i];
1707 		if (key && key->cert &&
1708 		    key->cert->type != SSH2_CERT_TYPE_USER) {
1709 			debug_f("ignoring certificate %s: not a user "
1710 			    "certificate", options.identity_files[i]);
1711 			continue;
1712 		}
1713 		if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1714 			debug_f("ignoring authenticator-hosted key %s as no "
1715 			    "SecurityKeyProvider has been specified",
1716 			    options.identity_files[i]);
1717 			continue;
1718 		}
1719 		options.identity_keys[i] = NULL;
1720 		id = xcalloc(1, sizeof(*id));
1721 		id->agent_fd = -1;
1722 		id->key = key;
1723 		id->filename = xstrdup(options.identity_files[i]);
1724 		id->userprovided = options.identity_file_userprovided[i];
1725 		TAILQ_INSERT_TAIL(&files, id, next);
1726 	}
1727 	/* list of certificates specified by user */
1728 	for (i = 0; i < options.num_certificate_files; i++) {
1729 		key = options.certificates[i];
1730 		if (!sshkey_is_cert(key) || key->cert == NULL ||
1731 		    key->cert->type != SSH2_CERT_TYPE_USER) {
1732 			debug_f("ignoring certificate %s: not a user "
1733 			    "certificate", options.identity_files[i]);
1734 			continue;
1735 		}
1736 		if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1737 			debug_f("ignoring authenticator-hosted key "
1738 			    "certificate %s as no "
1739 			    "SecurityKeyProvider has been specified",
1740 			    options.identity_files[i]);
1741 			continue;
1742 		}
1743 		id = xcalloc(1, sizeof(*id));
1744 		id->agent_fd = -1;
1745 		id->key = key;
1746 		id->filename = xstrdup(options.certificate_files[i]);
1747 		id->userprovided = options.certificate_file_userprovided[i];
1748 		TAILQ_INSERT_TAIL(preferred, id, next);
1749 	}
1750 	/* list of keys supported by the agent */
1751 	if ((r = get_agent_identities(ssh, &agent_fd, &idlist)) == 0) {
1752 		for (j = 0; j < idlist->nkeys; j++) {
1753 			found = 0;
1754 			TAILQ_FOREACH(id, &files, next) {
1755 				/*
1756 				 * agent keys from the config file are
1757 				 * preferred
1758 				 */
1759 				if (sshkey_equal(idlist->keys[j], id->key)) {
1760 					TAILQ_REMOVE(&files, id, next);
1761 					TAILQ_INSERT_TAIL(preferred, id, next);
1762 					id->agent_fd = agent_fd;
1763 					found = 1;
1764 					break;
1765 				}
1766 			}
1767 			if (!found && !options.identities_only) {
1768 				id = xcalloc(1, sizeof(*id));
1769 				/* XXX "steals" key/comment from idlist */
1770 				id->key = idlist->keys[j];
1771 				id->filename = idlist->comments[j];
1772 				idlist->keys[j] = NULL;
1773 				idlist->comments[j] = NULL;
1774 				id->agent_fd = agent_fd;
1775 				TAILQ_INSERT_TAIL(&agent, id, next);
1776 			}
1777 		}
1778 		ssh_free_identitylist(idlist);
1779 		/* append remaining agent keys */
1780 		TAILQ_CONCAT(preferred, &agent, next);
1781 		authctxt->agent_fd = agent_fd;
1782 	}
1783 	/* Prefer PKCS11 keys that are explicitly listed */
1784 	TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1785 		if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1786 			continue;
1787 		found = 0;
1788 		TAILQ_FOREACH(id2, &files, next) {
1789 			if (id2->key == NULL ||
1790 			    (id2->key->flags & SSHKEY_FLAG_EXT) != 0)
1791 				continue;
1792 			if (sshkey_equal(id->key, id2->key)) {
1793 				TAILQ_REMOVE(&files, id, next);
1794 				TAILQ_INSERT_TAIL(preferred, id, next);
1795 				found = 1;
1796 				break;
1797 			}
1798 		}
1799 		/* If IdentitiesOnly set and key not found then don't use it */
1800 		if (!found && options.identities_only) {
1801 			TAILQ_REMOVE(&files, id, next);
1802 			freezero(id, sizeof(*id));
1803 		}
1804 	}
1805 	/* append remaining keys from the config file */
1806 	TAILQ_CONCAT(preferred, &files, next);
1807 	/* finally, filter by PubkeyAcceptedAlgorithms */
1808 	TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1809 		if (id->key != NULL && !key_type_allowed_by_config(id->key)) {
1810 			debug("Skipping %s key %s - "
1811 			    "corresponding algo not in PubkeyAcceptedAlgorithms",
1812 			    sshkey_ssh_name(id->key), id->filename);
1813 			TAILQ_REMOVE(preferred, id, next);
1814 			sshkey_free(id->key);
1815 			free(id->filename);
1816 			memset(id, 0, sizeof(*id));
1817 			continue;
1818 		}
1819 	}
1820 	/* List the keys we plan on using */
1821 	TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1822 		ident = format_identity(id);
1823 		debug("Will attempt key: %s", ident);
1824 		free(ident);
1825 	}
1826 	debug2_f("done");
1827 }
1828 
1829 static void
1830 pubkey_cleanup(struct ssh *ssh)
1831 {
1832 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1833 	Identity *id;
1834 
1835 	if (authctxt->agent_fd != -1) {
1836 		ssh_close_authentication_socket(authctxt->agent_fd);
1837 		authctxt->agent_fd = -1;
1838 	}
1839 	for (id = TAILQ_FIRST(&authctxt->keys); id;
1840 	    id = TAILQ_FIRST(&authctxt->keys)) {
1841 		TAILQ_REMOVE(&authctxt->keys, id, next);
1842 		sshkey_free(id->key);
1843 		free(id->filename);
1844 		free(id);
1845 	}
1846 }
1847 
1848 static void
1849 pubkey_reset(Authctxt *authctxt)
1850 {
1851 	Identity *id;
1852 
1853 	TAILQ_FOREACH(id, &authctxt->keys, next)
1854 		id->tried = 0;
1855 }
1856 
1857 static int
1858 try_identity(struct ssh *ssh, Identity *id)
1859 {
1860 	if (!id->key)
1861 		return (0);
1862 	if (sshkey_type_plain(id->key->type) == KEY_RSA &&
1863 	    (ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
1864 		debug("Skipped %s key %s for RSA/MD5 server",
1865 		    sshkey_type(id->key), id->filename);
1866 		return (0);
1867 	}
1868 	return 1;
1869 }
1870 
1871 static int
1872 userauth_pubkey(struct ssh *ssh)
1873 {
1874 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1875 	Identity *id;
1876 	int sent = 0;
1877 	char *ident;
1878 
1879 	while ((id = TAILQ_FIRST(&authctxt->keys))) {
1880 		if (id->tried++)
1881 			return (0);
1882 		/* move key to the end of the queue */
1883 		TAILQ_REMOVE(&authctxt->keys, id, next);
1884 		TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1885 		/*
1886 		 * send a test message if we have the public key. for
1887 		 * encrypted keys we cannot do this and have to load the
1888 		 * private key instead
1889 		 */
1890 		if (id->key != NULL) {
1891 			if (try_identity(ssh, id)) {
1892 				ident = format_identity(id);
1893 				debug("Offering public key: %s", ident);
1894 				free(ident);
1895 				sent = send_pubkey_test(ssh, id);
1896 			}
1897 		} else {
1898 			debug("Trying private key: %s", id->filename);
1899 			id->key = load_identity_file(id);
1900 			if (id->key != NULL) {
1901 				if (try_identity(ssh, id)) {
1902 					id->isprivate = 1;
1903 					sent = sign_and_send_pubkey(ssh, id);
1904 				}
1905 				sshkey_free(id->key);
1906 				id->key = NULL;
1907 				id->isprivate = 0;
1908 			}
1909 		}
1910 		if (sent)
1911 			return (sent);
1912 	}
1913 	return (0);
1914 }
1915 
1916 /*
1917  * Send userauth request message specifying keyboard-interactive method.
1918  */
1919 static int
1920 userauth_kbdint(struct ssh *ssh)
1921 {
1922 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1923 	int r;
1924 
1925 	if (authctxt->attempt_kbdint++ >= options.number_of_password_prompts)
1926 		return 0;
1927 	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1928 	if (authctxt->attempt_kbdint > 1 && !authctxt->info_req_seen) {
1929 		debug3("userauth_kbdint: disable: no info_req_seen");
1930 		ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1931 		return 0;
1932 	}
1933 
1934 	debug2("userauth_kbdint");
1935 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1936 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1937 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1938 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1939 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||		/* lang */
1940 	    (r = sshpkt_put_cstring(ssh, options.kbd_interactive_devices ?
1941 	    options.kbd_interactive_devices : "")) != 0 ||
1942 	    (r = sshpkt_send(ssh)) != 0)
1943 		fatal_fr(r, "send packet");
1944 
1945 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1946 	return 1;
1947 }
1948 
1949 /*
1950  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1951  */
1952 static int
1953 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1954 {
1955 	Authctxt *authctxt = ssh->authctxt;
1956 	char *name = NULL, *inst = NULL, *lang = NULL, *prompt = NULL;
1957 	char *display_prompt = NULL, *response = NULL;
1958 	u_char echo = 0;
1959 	u_int num_prompts, i;
1960 	int r;
1961 
1962 	debug2_f("entering");
1963 
1964 	if (authctxt == NULL)
1965 		fatal_f("no authentication context");
1966 
1967 	authctxt->info_req_seen = 1;
1968 
1969 	if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
1970 	    (r = sshpkt_get_cstring(ssh, &inst, NULL)) != 0 ||
1971 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1972 		goto out;
1973 	if (strlen(name) > 0)
1974 		logit("%s", name);
1975 	if (strlen(inst) > 0)
1976 		logit("%s", inst);
1977 
1978 	if ((r = sshpkt_get_u32(ssh, &num_prompts)) != 0)
1979 		goto out;
1980 	/*
1981 	 * Begin to build info response packet based on prompts requested.
1982 	 * We commit to providing the correct number of responses, so if
1983 	 * further on we run into a problem that prevents this, we have to
1984 	 * be sure and clean this up and send a correct error response.
1985 	 */
1986 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE)) != 0 ||
1987 	    (r = sshpkt_put_u32(ssh, num_prompts)) != 0)
1988 		goto out;
1989 
1990 	debug2_f("num_prompts %d", num_prompts);
1991 	for (i = 0; i < num_prompts; i++) {
1992 		if ((r = sshpkt_get_cstring(ssh, &prompt, NULL)) != 0 ||
1993 		    (r = sshpkt_get_u8(ssh, &echo)) != 0)
1994 			goto out;
1995 		if (asmprintf(&display_prompt, INT_MAX, NULL, "(%s@%s) %s",
1996 		    authctxt->server_user, options.host_key_alias ?
1997 		    options.host_key_alias : authctxt->host, prompt) == -1)
1998 			fatal_f("asmprintf failed");
1999 		response = read_passphrase(display_prompt, echo ? RP_ECHO : 0);
2000 		if ((r = sshpkt_put_cstring(ssh, response)) != 0)
2001 			goto out;
2002 		freezero(response, strlen(response));
2003 		free(prompt);
2004 		free(display_prompt);
2005 		display_prompt = response = prompt = NULL;
2006 	}
2007 	/* done with parsing incoming message. */
2008 	if ((r = sshpkt_get_end(ssh)) != 0 ||
2009 	    (r = sshpkt_add_padding(ssh, 64)) != 0)
2010 		goto out;
2011 	r = sshpkt_send(ssh);
2012  out:
2013 	if (response)
2014 		freezero(response, strlen(response));
2015 	free(prompt);
2016 	free(display_prompt);
2017 	free(name);
2018 	free(inst);
2019 	free(lang);
2020 	return r;
2021 }
2022 
2023 static int
2024 ssh_keysign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp,
2025     const u_char *data, size_t datalen)
2026 {
2027 	struct sshbuf *b;
2028 	struct stat st;
2029 	pid_t pid;
2030 	int r, to[2], from[2], status;
2031 	int sock = ssh_packet_get_connection_in(ssh);
2032 	u_char rversion = 0, version = 2;
2033 	void (*osigchld)(int);
2034 
2035 	*sigp = NULL;
2036 	*lenp = 0;
2037 
2038 	if (stat(_PATH_SSH_KEY_SIGN, &st) == -1) {
2039 		error_f("not installed: %s", strerror(errno));
2040 		return -1;
2041 	}
2042 	if (fflush(stdout) != 0) {
2043 		error_f("fflush: %s", strerror(errno));
2044 		return -1;
2045 	}
2046 	if (pipe(to) == -1) {
2047 		error_f("pipe: %s", strerror(errno));
2048 		return -1;
2049 	}
2050 	if (pipe(from) == -1) {
2051 		error_f("pipe: %s", strerror(errno));
2052 		return -1;
2053 	}
2054 	if ((pid = fork()) == -1) {
2055 		error_f("fork: %s", strerror(errno));
2056 		return -1;
2057 	}
2058 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
2059 	if (pid == 0) {
2060 		close(from[0]);
2061 		if (dup2(from[1], STDOUT_FILENO) == -1)
2062 			fatal_f("dup2: %s", strerror(errno));
2063 		close(to[1]);
2064 		if (dup2(to[0], STDIN_FILENO) == -1)
2065 			fatal_f("dup2: %s", strerror(errno));
2066 		close(from[1]);
2067 		close(to[0]);
2068 
2069 		if (dup2(sock, STDERR_FILENO + 1) == -1)
2070 			fatal_f("dup2: %s", strerror(errno));
2071 		sock = STDERR_FILENO + 1;
2072 		fcntl(sock, F_SETFD, 0);	/* keep the socket on exec */
2073 		closefrom(sock + 1);
2074 
2075 		debug3_f("[child] pid=%ld, exec %s",
2076 		    (long)getpid(), _PATH_SSH_KEY_SIGN);
2077 		execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
2078 		fatal_f("exec(%s): %s", _PATH_SSH_KEY_SIGN,
2079 		    strerror(errno));
2080 	}
2081 	close(from[1]);
2082 	close(to[0]);
2083 	sock = STDERR_FILENO + 1;
2084 
2085 	if ((b = sshbuf_new()) == NULL)
2086 		fatal_f("sshbuf_new failed");
2087 	/* send # of sock, data to be signed */
2088 	if ((r = sshbuf_put_u32(b, sock)) != 0 ||
2089 	    (r = sshbuf_put_string(b, data, datalen)) != 0)
2090 		fatal_fr(r, "buffer error");
2091 	if (ssh_msg_send(to[1], version, b) == -1)
2092 		fatal_f("couldn't send request");
2093 	sshbuf_reset(b);
2094 	r = ssh_msg_recv(from[0], b);
2095 	close(from[0]);
2096 	close(to[1]);
2097 	if (r < 0) {
2098 		error_f("no reply");
2099 		goto fail;
2100 	}
2101 
2102 	errno = 0;
2103 	while (waitpid(pid, &status, 0) == -1) {
2104 		if (errno != EINTR) {
2105 			error_f("waitpid %ld: %s", (long)pid, strerror(errno));
2106 			goto fail;
2107 		}
2108 	}
2109 	if (!WIFEXITED(status)) {
2110 		error_f("exited abnormally");
2111 		goto fail;
2112 	}
2113 	if (WEXITSTATUS(status) != 0) {
2114 		error_f("exited with status %d", WEXITSTATUS(status));
2115 		goto fail;
2116 	}
2117 	if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
2118 		error_fr(r, "buffer error");
2119 		goto fail;
2120 	}
2121 	if (rversion != version) {
2122 		error_f("bad version");
2123 		goto fail;
2124 	}
2125 	if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
2126 		error_fr(r, "buffer error");
2127  fail:
2128 		ssh_signal(SIGCHLD, osigchld);
2129 		sshbuf_free(b);
2130 		return -1;
2131 	}
2132 	ssh_signal(SIGCHLD, osigchld);
2133 	sshbuf_free(b);
2134 
2135 	return 0;
2136 }
2137 
2138 static int
2139 userauth_hostbased(struct ssh *ssh)
2140 {
2141 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
2142 	struct sshkey *private = NULL;
2143 	struct sshbuf *b = NULL;
2144 	u_char *sig = NULL, *keyblob = NULL;
2145 	char *fp = NULL, *chost = NULL, *lname = NULL;
2146 	size_t siglen = 0, keylen = 0;
2147 	int i, r, success = 0;
2148 
2149 	if (authctxt->ktypes == NULL) {
2150 		authctxt->oktypes = xstrdup(options.hostbased_accepted_algos);
2151 		authctxt->ktypes = authctxt->oktypes;
2152 	}
2153 
2154 	/*
2155 	 * Work through each listed type pattern in HostbasedAcceptedAlgorithms,
2156 	 * trying each hostkey that matches the type in turn.
2157 	 */
2158 	for (;;) {
2159 		if (authctxt->active_ktype == NULL)
2160 			authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
2161 		if (authctxt->active_ktype == NULL ||
2162 		    *authctxt->active_ktype == '\0')
2163 			break;
2164 		debug3_f("trying key type %s", authctxt->active_ktype);
2165 
2166 		/* check for a useful key */
2167 		private = NULL;
2168 		for (i = 0; i < authctxt->sensitive->nkeys; i++) {
2169 			if (authctxt->sensitive->keys[i] == NULL ||
2170 			    authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
2171 				continue;
2172 			if (!sshkey_match_keyname_to_sigalgs(
2173 			    sshkey_ssh_name(authctxt->sensitive->keys[i]),
2174 			    authctxt->active_ktype))
2175 				continue;
2176 			/* we take and free the key */
2177 			private = authctxt->sensitive->keys[i];
2178 			authctxt->sensitive->keys[i] = NULL;
2179 			break;
2180 		}
2181 		/* Found one */
2182 		if (private != NULL)
2183 			break;
2184 		/* No more keys of this type; advance */
2185 		authctxt->active_ktype = NULL;
2186 	}
2187 	if (private == NULL) {
2188 		free(authctxt->oktypes);
2189 		authctxt->oktypes = authctxt->ktypes = NULL;
2190 		authctxt->active_ktype = NULL;
2191 		debug("No more client hostkeys for hostbased authentication.");
2192 		goto out;
2193 	}
2194 
2195 	if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
2196 	    SSH_FP_DEFAULT)) == NULL) {
2197 		error_f("sshkey_fingerprint failed");
2198 		goto out;
2199 	}
2200 	debug_f("trying hostkey %s %s using sigalg %s",
2201 	    sshkey_ssh_name(private), fp, authctxt->active_ktype);
2202 
2203 	/* figure out a name for the client host */
2204 	lname = get_local_name(ssh_packet_get_connection_in(ssh));
2205 	if (lname == NULL) {
2206 		error_f("cannot get local ipaddr/name");
2207 		goto out;
2208 	}
2209 
2210 	/* XXX sshbuf_put_stringf? */
2211 	xasprintf(&chost, "%s.", lname);
2212 	debug2_f("chost %s", chost);
2213 
2214 	/* construct data */
2215 	if ((b = sshbuf_new()) == NULL) {
2216 		error_f("sshbuf_new failed");
2217 		goto out;
2218 	}
2219 	if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
2220 		error_fr(r, "sshkey_to_blob");
2221 		goto out;
2222 	}
2223 	if ((r = sshbuf_put_stringb(b, ssh->kex->session_id)) != 0 ||
2224 	    (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2225 	    (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
2226 	    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
2227 	    (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
2228 	    (r = sshbuf_put_cstring(b, authctxt->active_ktype)) != 0 ||
2229 	    (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
2230 	    (r = sshbuf_put_cstring(b, chost)) != 0 ||
2231 	    (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
2232 		error_fr(r, "buffer error");
2233 		goto out;
2234 	}
2235 
2236 #ifdef DEBUG_PK
2237 	sshbuf_dump(b, stderr);
2238 #endif
2239 	if ((r = ssh_keysign(ssh, private, &sig, &siglen,
2240 	    sshbuf_ptr(b), sshbuf_len(b))) != 0) {
2241 		error("sign using hostkey %s %s failed",
2242 		    sshkey_ssh_name(private), fp);
2243 		goto out;
2244 	}
2245 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2246 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
2247 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
2248 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
2249 	    (r = sshpkt_put_cstring(ssh, authctxt->active_ktype)) != 0 ||
2250 	    (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
2251 	    (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
2252 	    (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
2253 	    (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
2254 	    (r = sshpkt_send(ssh)) != 0) {
2255 		error_fr(r, "packet error");
2256 		goto out;
2257 	}
2258 	success = 1;
2259 
2260  out:
2261 	if (sig != NULL)
2262 		freezero(sig, siglen);
2263 	free(keyblob);
2264 	free(lname);
2265 	free(fp);
2266 	free(chost);
2267 	sshkey_free(private);
2268 	sshbuf_free(b);
2269 
2270 	return success;
2271 }
2272 
2273 /* find auth method */
2274 
2275 /*
2276  * given auth method name, if configurable options permit this method fill
2277  * in auth_ident field and return true, otherwise return false.
2278  */
2279 static int
2280 authmethod_is_enabled(Authmethod *method)
2281 {
2282 	if (method == NULL)
2283 		return 0;
2284 	/* return false if options indicate this method is disabled */
2285 	if  (method->enabled == NULL || *method->enabled == 0)
2286 		return 0;
2287 	/* return false if batch mode is enabled but method needs interactive mode */
2288 	if  (method->batch_flag != NULL && *method->batch_flag != 0)
2289 		return 0;
2290 	return 1;
2291 }
2292 
2293 static Authmethod *
2294 authmethod_lookup(const char *name)
2295 {
2296 	Authmethod *method = NULL;
2297 	if (name != NULL)
2298 		for (method = authmethods; method->name != NULL; method++)
2299 			if (strcmp(name, method->name) == 0)
2300 				return method;
2301 	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
2302 	return NULL;
2303 }
2304 
2305 /* XXX internal state */
2306 static Authmethod *current = NULL;
2307 static char *supported = NULL;
2308 static char *preferred = NULL;
2309 
2310 /*
2311  * Given the authentication method list sent by the server, return the
2312  * next method we should try.  If the server initially sends a nil list,
2313  * use a built-in default list.
2314  */
2315 static Authmethod *
2316 authmethod_get(char *authlist)
2317 {
2318 	char *name = NULL;
2319 	u_int next;
2320 
2321 	/* Use a suitable default if we're passed a nil list.  */
2322 	if (authlist == NULL || strlen(authlist) == 0)
2323 		authlist = options.preferred_authentications;
2324 
2325 	if (supported == NULL || strcmp(authlist, supported) != 0) {
2326 		debug3("start over, passed a different list %s", authlist);
2327 		free(supported);
2328 		supported = xstrdup(authlist);
2329 		preferred = options.preferred_authentications;
2330 		debug3("preferred %s", preferred);
2331 		current = NULL;
2332 	} else if (current != NULL && authmethod_is_enabled(current))
2333 		return current;
2334 
2335 	for (;;) {
2336 		if ((name = match_list(preferred, supported, &next)) == NULL) {
2337 			debug("No more authentication methods to try.");
2338 			current = NULL;
2339 			return NULL;
2340 		}
2341 		preferred += next;
2342 		debug3("authmethod_lookup %s", name);
2343 		debug3("remaining preferred: %s", preferred);
2344 		if ((current = authmethod_lookup(name)) != NULL &&
2345 		    authmethod_is_enabled(current)) {
2346 			debug3("authmethod_is_enabled %s", name);
2347 			debug("Next authentication method: %s", name);
2348 			free(name);
2349 			return current;
2350 		}
2351 		free(name);
2352 	}
2353 }
2354 
2355 static char *
2356 authmethods_get(void)
2357 {
2358 	Authmethod *method = NULL;
2359 	struct sshbuf *b;
2360 	char *list;
2361 	int r;
2362 
2363 	if ((b = sshbuf_new()) == NULL)
2364 		fatal_f("sshbuf_new failed");
2365 	for (method = authmethods; method->name != NULL; method++) {
2366 		if (authmethod_is_enabled(method)) {
2367 			if ((r = sshbuf_putf(b, "%s%s",
2368 			    sshbuf_len(b) ? "," : "", method->name)) != 0)
2369 				fatal_fr(r, "buffer error");
2370 		}
2371 	}
2372 	if ((list = sshbuf_dup_string(b)) == NULL)
2373 		fatal_f("sshbuf_dup_string failed");
2374 	sshbuf_free(b);
2375 	return list;
2376 }
2377