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