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