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