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