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