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