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