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