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