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