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