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