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