Home | History | Annotate | Download | only in openssh
      1 /* $OpenBSD: sshconnect2.c,v 1.255 2017/03/11 23:40:26 djm Exp $ */
      2 /*
      3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
      4  * Copyright (c) 2008 Damien Miller.  All rights reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  * 1. Redistributions of source code must retain the above copyright
     10  *    notice, this list of conditions and the following disclaimer.
     11  * 2. Redistributions in binary form must reproduce the above copyright
     12  *    notice, this list of conditions and the following disclaimer in the
     13  *    documentation and/or other materials provided with the distribution.
     14  *
     15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     25  */
     26 
     27 #include "includes.h"
     28 
     29 #include <sys/types.h>
     30 #include <sys/socket.h>
     31 #include <sys/wait.h>
     32 #include <sys/stat.h>
     33 
     34 #include <errno.h>
     35 #include <fcntl.h>
     36 #include <netdb.h>
     37 #include <pwd.h>
     38 #include <signal.h>
     39 #include <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 "buffer.h"
     53 #include "packet.h"
     54 #include "compat.h"
     55 #include "cipher.h"
     56 #include "key.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
     96 verify_host_key_callback(Key *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 *
    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
    158 ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
    159 {
    160 	char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
    161 	char *s;
    162 	struct kex *kex;
    163 	int r;
    164 
    165 	xxx_host = host;
    166 	xxx_hostaddr = hostaddr;
    167 
    168 	if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
    169 		fatal("%s: kex_names_cat", __func__);
    170 	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s);
    171 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
    172 	    compat_cipher_proposal(options.ciphers);
    173 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
    174 	    compat_cipher_proposal(options.ciphers);
    175 	myproposal[PROPOSAL_COMP_ALGS_CTOS] =
    176 	    myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ?
    177 	    "zlib (at) openssh.com,zlib,none" : "none,zlib (at) openssh.com,zlib";
    178 	myproposal[PROPOSAL_MAC_ALGS_CTOS] =
    179 	    myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
    180 	if (options.hostkeyalgorithms != NULL) {
    181 		if (kex_assemble_names(KEX_DEFAULT_PK_ALG,
    182 		    &options.hostkeyalgorithms) != 0)
    183 			fatal("%s: kex_assemble_namelist", __func__);
    184 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
    185 		    compat_pkalg_proposal(options.hostkeyalgorithms);
    186 	} else {
    187 		/* Enforce default */
    188 		options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG);
    189 		/* Prefer algorithms that we already have keys for */
    190 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
    191 		    compat_pkalg_proposal(
    192 		    order_hostkeyalgs(host, hostaddr, port));
    193 	}
    194 
    195 	if (options.rekey_limit || options.rekey_interval)
    196 		packet_set_rekey_limits(options.rekey_limit,
    197 		    options.rekey_interval);
    198 
    199 	/* start key exchange */
    200 	if ((r = kex_setup(active_state, myproposal)) != 0)
    201 		fatal("kex_setup: %s", ssh_err(r));
    202 	kex = active_state->kex;
    203 #ifdef WITH_OPENSSL
    204 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
    205 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
    206 	kex->kex[KEX_DH_GRP14_SHA256] = kexdh_client;
    207 	kex->kex[KEX_DH_GRP16_SHA512] = kexdh_client;
    208 	kex->kex[KEX_DH_GRP18_SHA512] = kexdh_client;
    209 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
    210 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
    211 # ifdef OPENSSL_HAS_ECC
    212 	kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
    213 # endif
    214 #endif
    215 	kex->kex[KEX_C25519_SHA256] = kexc25519_client;
    216 	kex->client_version_string=client_version_string;
    217 	kex->server_version_string=server_version_string;
    218 	kex->verify_host_key=&verify_host_key_callback;
    219 
    220 	dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
    221 
    222 	/* remove ext-info from the KEX proposals for rekeying */
    223 	myproposal[PROPOSAL_KEX_ALGS] =
    224 	    compat_kex_proposal(options.kex_algorithms);
    225 	if ((r = kex_prop2buf(kex->my, myproposal)) != 0)
    226 		fatal("kex_prop2buf: %s", ssh_err(r));
    227 
    228 	session_id2 = kex->session_id;
    229 	session_id2_len = kex->session_id_len;
    230 
    231 #ifdef DEBUG_KEXDH
    232 	/* send 1st encrypted/maced/compressed message */
    233 	packet_start(SSH2_MSG_IGNORE);
    234 	packet_put_cstring("markus");
    235 	packet_send();
    236 	packet_write_wait();
    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 	int attempt;
    269 	/* pubkey */
    270 	struct idlist keys;
    271 	int agent_fd;
    272 	/* hostbased */
    273 	Sensitive *sensitive;
    274 	char *oktypes, *ktypes;
    275 	const char *active_ktype;
    276 	/* kbd-interactive */
    277 	int info_req_seen;
    278 	/* generic */
    279 	void *methoddata;
    280 };
    281 
    282 struct cauthmethod {
    283 	char	*name;		/* string to compare against server's list */
    284 	int	(*userauth)(Authctxt *authctxt);
    285 	void	(*cleanup)(Authctxt *authctxt);
    286 	int	*enabled;	/* flag in option struct that enables method */
    287 	int	*batch_flag;	/* flag in option struct that disables method */
    288 };
    289 
    290 int	input_userauth_service_accept(int, u_int32_t, void *);
    291 int	input_userauth_ext_info(int, u_int32_t, void *);
    292 int	input_userauth_success(int, u_int32_t, void *);
    293 int	input_userauth_success_unexpected(int, u_int32_t, void *);
    294 int	input_userauth_failure(int, u_int32_t, void *);
    295 int	input_userauth_banner(int, u_int32_t, void *);
    296 int	input_userauth_error(int, u_int32_t, void *);
    297 int	input_userauth_info_req(int, u_int32_t, void *);
    298 int	input_userauth_pk_ok(int, u_int32_t, void *);
    299 int	input_userauth_passwd_changereq(int, u_int32_t, void *);
    300 
    301 int	userauth_none(Authctxt *);
    302 int	userauth_pubkey(Authctxt *);
    303 int	userauth_passwd(Authctxt *);
    304 int	userauth_kbdint(Authctxt *);
    305 int	userauth_hostbased(Authctxt *);
    306 
    307 #ifdef GSSAPI
    308 int	userauth_gssapi(Authctxt *authctxt);
    309 int	input_gssapi_response(int type, u_int32_t, void *);
    310 int	input_gssapi_token(int type, u_int32_t, void *);
    311 int	input_gssapi_hash(int type, u_int32_t, void *);
    312 int	input_gssapi_error(int, u_int32_t, void *);
    313 int	input_gssapi_errtok(int, u_int32_t, void *);
    314 #endif
    315 
    316 void	userauth(Authctxt *, char *);
    317 
    318 static int sign_and_send_pubkey(Authctxt *, Identity *);
    319 static void pubkey_prepare(Authctxt *);
    320 static void pubkey_cleanup(Authctxt *);
    321 static void pubkey_reset(Authctxt *);
    322 static Key *load_identity_file(Identity *);
    323 
    324 static Authmethod *authmethod_get(char *authlist);
    325 static Authmethod *authmethod_lookup(const char *name);
    326 static char *authmethods_get(void);
    327 
    328 Authmethod authmethods[] = {
    329 #ifdef GSSAPI
    330 	{"gssapi-with-mic",
    331 		userauth_gssapi,
    332 		NULL,
    333 		&options.gss_authentication,
    334 		NULL},
    335 #endif
    336 	{"hostbased",
    337 		userauth_hostbased,
    338 		NULL,
    339 		&options.hostbased_authentication,
    340 		NULL},
    341 	{"publickey",
    342 		userauth_pubkey,
    343 		NULL,
    344 		&options.pubkey_authentication,
    345 		NULL},
    346 	{"keyboard-interactive",
    347 		userauth_kbdint,
    348 		NULL,
    349 		&options.kbd_interactive_authentication,
    350 		&options.batch_mode},
    351 	{"password",
    352 		userauth_passwd,
    353 		NULL,
    354 		&options.password_authentication,
    355 		&options.batch_mode},
    356 	{"none",
    357 		userauth_none,
    358 		NULL,
    359 		NULL,
    360 		NULL},
    361 	{NULL, NULL, NULL, NULL, NULL}
    362 };
    363 
    364 void
    365 ssh_userauth2(const char *local_user, const char *server_user, char *host,
    366     Sensitive *sensitive)
    367 {
    368 	struct ssh *ssh = active_state;
    369 	Authctxt authctxt;
    370 	int r;
    371 
    372 	if (options.challenge_response_authentication)
    373 		options.kbd_interactive_authentication = 1;
    374 	if (options.preferred_authentications == NULL)
    375 		options.preferred_authentications = authmethods_get();
    376 
    377 	/* setup authentication context */
    378 	memset(&authctxt, 0, sizeof(authctxt));
    379 	pubkey_prepare(&authctxt);
    380 	authctxt.server_user = server_user;
    381 	authctxt.local_user = local_user;
    382 	authctxt.host = host;
    383 	authctxt.service = "ssh-connection";		/* service name */
    384 	authctxt.success = 0;
    385 	authctxt.method = authmethod_lookup("none");
    386 	authctxt.authlist = NULL;
    387 	authctxt.methoddata = NULL;
    388 	authctxt.sensitive = sensitive;
    389 	authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
    390 	authctxt.info_req_seen = 0;
    391 	authctxt.agent_fd = -1;
    392 	if (authctxt.method == NULL)
    393 		fatal("ssh_userauth2: internal error: cannot send userauth none request");
    394 
    395 	if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
    396 	    (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
    397 	    (r = sshpkt_send(ssh)) != 0)
    398 		fatal("%s: %s", __func__, ssh_err(r));
    399 
    400 	ssh_dispatch_init(ssh, &input_userauth_error);
    401 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info);
    402 	ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
    403 	ssh_dispatch_run(ssh, DISPATCH_BLOCK, &authctxt.success, &authctxt);	/* loop until success */
    404 
    405 	pubkey_cleanup(&authctxt);
    406 	ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
    407 
    408 	if (!authctxt.success)
    409 		fatal("Authentication failed.");
    410 	debug("Authentication succeeded (%s).", authctxt.method->name);
    411 }
    412 
    413 /* ARGSUSED */
    414 int
    415 input_userauth_service_accept(int type, u_int32_t seqnr, void *ctxt)
    416 {
    417 	Authctxt *authctxt = ctxt;
    418 	struct ssh *ssh = active_state;
    419 	int r;
    420 
    421 	if (ssh_packet_remaining(ssh) > 0) {
    422 		char *reply;
    423 
    424 		if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
    425 			goto out;
    426 		debug2("service_accept: %s", reply);
    427 		free(reply);
    428 	} else {
    429 		debug2("buggy server: service_accept w/o service");
    430 	}
    431 	if ((r = sshpkt_get_end(ssh)) != 0)
    432 		goto out;
    433 	debug("SSH2_MSG_SERVICE_ACCEPT received");
    434 
    435 	/* initial userauth request */
    436 	userauth_none(authctxt);
    437 
    438 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
    439 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
    440 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
    441 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
    442 	r = 0;
    443  out:
    444 	return r;
    445 }
    446 
    447 /* ARGSUSED */
    448 int
    449 input_userauth_ext_info(int type, u_int32_t seqnr, void *ctxt)
    450 {
    451 	return kex_input_ext_info(type, seqnr, active_state);
    452 }
    453 
    454 void
    455 userauth(Authctxt *authctxt, char *authlist)
    456 {
    457 	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
    458 		authctxt->method->cleanup(authctxt);
    459 
    460 	free(authctxt->methoddata);
    461 	authctxt->methoddata = NULL;
    462 	if (authlist == NULL) {
    463 		authlist = authctxt->authlist;
    464 	} else {
    465 		free(authctxt->authlist);
    466 		authctxt->authlist = authlist;
    467 	}
    468 	for (;;) {
    469 		Authmethod *method = authmethod_get(authlist);
    470 		if (method == NULL)
    471 			fatal("Permission denied (%s).", authlist);
    472 		authctxt->method = method;
    473 
    474 		/* reset the per method handler */
    475 		dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
    476 		    SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
    477 
    478 		/* and try new method */
    479 		if (method->userauth(authctxt) != 0) {
    480 			debug2("we sent a %s packet, wait for reply", method->name);
    481 			break;
    482 		} else {
    483 			debug2("we did not send a packet, disable method");
    484 			method->enabled = NULL;
    485 		}
    486 	}
    487 }
    488 
    489 /* ARGSUSED */
    490 int
    491 input_userauth_error(int type, u_int32_t seq, void *ctxt)
    492 {
    493 	fatal("input_userauth_error: bad message during authentication: "
    494 	    "type %d", type);
    495 	return 0;
    496 }
    497 
    498 /* ARGSUSED */
    499 int
    500 input_userauth_banner(int type, u_int32_t seq, void *ctxt)
    501 {
    502 	char *msg, *lang;
    503 	u_int len;
    504 
    505 	debug3("%s", __func__);
    506 	msg = packet_get_string(&len);
    507 	lang = packet_get_string(NULL);
    508 	if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
    509 		fmprintf(stderr, "%s", msg);
    510 	free(msg);
    511 	free(lang);
    512 	return 0;
    513 }
    514 
    515 /* ARGSUSED */
    516 int
    517 input_userauth_success(int type, u_int32_t seq, void *ctxt)
    518 {
    519 	Authctxt *authctxt = ctxt;
    520 
    521 	if (authctxt == NULL)
    522 		fatal("input_userauth_success: no authentication context");
    523 	free(authctxt->authlist);
    524 	authctxt->authlist = NULL;
    525 	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
    526 		authctxt->method->cleanup(authctxt);
    527 	free(authctxt->methoddata);
    528 	authctxt->methoddata = NULL;
    529 	authctxt->success = 1;			/* break out */
    530 	return 0;
    531 }
    532 
    533 int
    534 input_userauth_success_unexpected(int type, u_int32_t seq, void *ctxt)
    535 {
    536 	Authctxt *authctxt = ctxt;
    537 
    538 	if (authctxt == NULL)
    539 		fatal("%s: no authentication context", __func__);
    540 
    541 	fatal("Unexpected authentication success during %s.",
    542 	    authctxt->method->name);
    543 	return 0;
    544 }
    545 
    546 /* ARGSUSED */
    547 int
    548 input_userauth_failure(int type, u_int32_t seq, void *ctxt)
    549 {
    550 	Authctxt *authctxt = ctxt;
    551 	char *authlist = NULL;
    552 	int partial;
    553 
    554 	if (authctxt == NULL)
    555 		fatal("input_userauth_failure: no authentication context");
    556 
    557 	authlist = packet_get_string(NULL);
    558 	partial = packet_get_char();
    559 	packet_check_eom();
    560 
    561 	if (partial != 0) {
    562 		verbose("Authenticated with partial success.");
    563 		/* reset state */
    564 		pubkey_reset(authctxt);
    565 	}
    566 	debug("Authentications that can continue: %s", authlist);
    567 
    568 	userauth(authctxt, authlist);
    569 	return 0;
    570 }
    571 
    572 /* ARGSUSED */
    573 int
    574 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
    575 {
    576 	Authctxt *authctxt = ctxt;
    577 	Key *key = NULL;
    578 	Identity *id = NULL;
    579 	Buffer b;
    580 	int pktype, sent = 0;
    581 	u_int alen, blen;
    582 	char *pkalg, *fp;
    583 	u_char *pkblob;
    584 
    585 	if (authctxt == NULL)
    586 		fatal("input_userauth_pk_ok: no authentication context");
    587 	if (datafellows & SSH_BUG_PKOK) {
    588 		/* this is similar to SSH_BUG_PKAUTH */
    589 		debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
    590 		pkblob = packet_get_string(&blen);
    591 		buffer_init(&b);
    592 		buffer_append(&b, pkblob, blen);
    593 		pkalg = buffer_get_string(&b, &alen);
    594 		buffer_free(&b);
    595 	} else {
    596 		pkalg = packet_get_string(&alen);
    597 		pkblob = packet_get_string(&blen);
    598 	}
    599 	packet_check_eom();
    600 
    601 	debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
    602 
    603 	if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
    604 		debug("unknown pkalg %s", pkalg);
    605 		goto done;
    606 	}
    607 	if ((key = key_from_blob(pkblob, blen)) == NULL) {
    608 		debug("no key from blob. pkalg %s", pkalg);
    609 		goto done;
    610 	}
    611 	if (key->type != pktype) {
    612 		error("input_userauth_pk_ok: type mismatch "
    613 		    "for decoded key (received %d, expected %d)",
    614 		    key->type, pktype);
    615 		goto done;
    616 	}
    617 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
    618 	    SSH_FP_DEFAULT)) == NULL)
    619 		goto done;
    620 	debug2("input_userauth_pk_ok: fp %s", fp);
    621 	free(fp);
    622 
    623 	/*
    624 	 * search keys in the reverse order, because last candidate has been
    625 	 * moved to the end of the queue.  this also avoids confusion by
    626 	 * duplicate keys
    627 	 */
    628 	TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
    629 		if (key_equal(key, id->key)) {
    630 			sent = sign_and_send_pubkey(authctxt, id);
    631 			break;
    632 		}
    633 	}
    634 done:
    635 	if (key != NULL)
    636 		key_free(key);
    637 	free(pkalg);
    638 	free(pkblob);
    639 
    640 	/* try another method if we did not send a packet */
    641 	if (sent == 0)
    642 		userauth(authctxt, NULL);
    643 	return 0;
    644 }
    645 
    646 #ifdef GSSAPI
    647 int
    648 userauth_gssapi(Authctxt *authctxt)
    649 {
    650 	Gssctxt *gssctxt = NULL;
    651 	static gss_OID_set gss_supported = NULL;
    652 	static u_int mech = 0;
    653 	OM_uint32 min;
    654 	int ok = 0;
    655 
    656 	/* Try one GSSAPI method at a time, rather than sending them all at
    657 	 * once. */
    658 
    659 	if (gss_supported == NULL)
    660 		gss_indicate_mechs(&min, &gss_supported);
    661 
    662 	/* Check to see if the mechanism is usable before we offer it */
    663 	while (mech < gss_supported->count && !ok) {
    664 		/* My DER encoding requires length<128 */
    665 		if (gss_supported->elements[mech].length < 128 &&
    666 		    ssh_gssapi_check_mechanism(&gssctxt,
    667 		    &gss_supported->elements[mech], authctxt->host)) {
    668 			ok = 1; /* Mechanism works */
    669 		} else {
    670 			mech++;
    671 		}
    672 	}
    673 
    674 	if (!ok)
    675 		return 0;
    676 
    677 	authctxt->methoddata=(void *)gssctxt;
    678 
    679 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
    680 	packet_put_cstring(authctxt->server_user);
    681 	packet_put_cstring(authctxt->service);
    682 	packet_put_cstring(authctxt->method->name);
    683 
    684 	packet_put_int(1);
    685 
    686 	packet_put_int((gss_supported->elements[mech].length) + 2);
    687 	packet_put_char(SSH_GSS_OIDTYPE);
    688 	packet_put_char(gss_supported->elements[mech].length);
    689 	packet_put_raw(gss_supported->elements[mech].elements,
    690 	    gss_supported->elements[mech].length);
    691 
    692 	packet_send();
    693 
    694 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
    695 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
    696 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
    697 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
    698 
    699 	mech++; /* Move along to next candidate */
    700 
    701 	return 1;
    702 }
    703 
    704 static OM_uint32
    705 process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
    706 {
    707 	Authctxt *authctxt = ctxt;
    708 	Gssctxt *gssctxt = authctxt->methoddata;
    709 	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
    710 	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
    711 	gss_buffer_desc gssbuf;
    712 	OM_uint32 status, ms, flags;
    713 	Buffer b;
    714 
    715 	status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
    716 	    recv_tok, &send_tok, &flags);
    717 
    718 	if (send_tok.length > 0) {
    719 		if (GSS_ERROR(status))
    720 			packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
    721 		else
    722 			packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
    723 
    724 		packet_put_string(send_tok.value, send_tok.length);
    725 		packet_send();
    726 		gss_release_buffer(&ms, &send_tok);
    727 	}
    728 
    729 	if (status == GSS_S_COMPLETE) {
    730 		/* send either complete or MIC, depending on mechanism */
    731 		if (!(flags & GSS_C_INTEG_FLAG)) {
    732 			packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
    733 			packet_send();
    734 		} else {
    735 			ssh_gssapi_buildmic(&b, authctxt->server_user,
    736 			    authctxt->service, "gssapi-with-mic");
    737 
    738 			gssbuf.value = buffer_ptr(&b);
    739 			gssbuf.length = buffer_len(&b);
    740 
    741 			status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
    742 
    743 			if (!GSS_ERROR(status)) {
    744 				packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
    745 				packet_put_string(mic.value, mic.length);
    746 
    747 				packet_send();
    748 			}
    749 
    750 			buffer_free(&b);
    751 			gss_release_buffer(&ms, &mic);
    752 		}
    753 	}
    754 
    755 	return status;
    756 }
    757 
    758 /* ARGSUSED */
    759 int
    760 input_gssapi_response(int type, u_int32_t plen, void *ctxt)
    761 {
    762 	Authctxt *authctxt = ctxt;
    763 	Gssctxt *gssctxt;
    764 	int oidlen;
    765 	char *oidv;
    766 
    767 	if (authctxt == NULL)
    768 		fatal("input_gssapi_response: no authentication context");
    769 	gssctxt = authctxt->methoddata;
    770 
    771 	/* Setup our OID */
    772 	oidv = packet_get_string(&oidlen);
    773 
    774 	if (oidlen <= 2 ||
    775 	    oidv[0] != SSH_GSS_OIDTYPE ||
    776 	    oidv[1] != oidlen - 2) {
    777 		free(oidv);
    778 		debug("Badly encoded mechanism OID received");
    779 		userauth(authctxt, NULL);
    780 		return 0;
    781 	}
    782 
    783 	if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
    784 		fatal("Server returned different OID than expected");
    785 
    786 	packet_check_eom();
    787 
    788 	free(oidv);
    789 
    790 	if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
    791 		/* Start again with next method on list */
    792 		debug("Trying to start again");
    793 		userauth(authctxt, NULL);
    794 		return 0;
    795 	}
    796 	return 0;
    797 }
    798 
    799 /* ARGSUSED */
    800 int
    801 input_gssapi_token(int type, u_int32_t plen, void *ctxt)
    802 {
    803 	Authctxt *authctxt = ctxt;
    804 	gss_buffer_desc recv_tok;
    805 	OM_uint32 status;
    806 	u_int slen;
    807 
    808 	if (authctxt == NULL)
    809 		fatal("input_gssapi_response: no authentication context");
    810 
    811 	recv_tok.value = packet_get_string(&slen);
    812 	recv_tok.length = slen;	/* safe typecast */
    813 
    814 	packet_check_eom();
    815 
    816 	status = process_gssapi_token(ctxt, &recv_tok);
    817 
    818 	free(recv_tok.value);
    819 
    820 	if (GSS_ERROR(status)) {
    821 		/* Start again with the next method in the list */
    822 		userauth(authctxt, NULL);
    823 		return 0;
    824 	}
    825 	return 0;
    826 }
    827 
    828 /* ARGSUSED */
    829 int
    830 input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
    831 {
    832 	Authctxt *authctxt = ctxt;
    833 	Gssctxt *gssctxt;
    834 	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
    835 	gss_buffer_desc recv_tok;
    836 	OM_uint32 ms;
    837 	u_int len;
    838 
    839 	if (authctxt == NULL)
    840 		fatal("input_gssapi_response: no authentication context");
    841 	gssctxt = authctxt->methoddata;
    842 
    843 	recv_tok.value = packet_get_string(&len);
    844 	recv_tok.length = len;
    845 
    846 	packet_check_eom();
    847 
    848 	/* Stick it into GSSAPI and see what it says */
    849 	(void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
    850 	    &recv_tok, &send_tok, NULL);
    851 
    852 	free(recv_tok.value);
    853 	gss_release_buffer(&ms, &send_tok);
    854 
    855 	/* Server will be returning a failed packet after this one */
    856 	return 0;
    857 }
    858 
    859 /* ARGSUSED */
    860 int
    861 input_gssapi_error(int type, u_int32_t plen, void *ctxt)
    862 {
    863 	char *msg;
    864 	char *lang;
    865 
    866 	/* maj */(void)packet_get_int();
    867 	/* min */(void)packet_get_int();
    868 	msg=packet_get_string(NULL);
    869 	lang=packet_get_string(NULL);
    870 
    871 	packet_check_eom();
    872 
    873 	debug("Server GSSAPI Error:\n%s", msg);
    874 	free(msg);
    875 	free(lang);
    876 	return 0;
    877 }
    878 #endif /* GSSAPI */
    879 
    880 int
    881 userauth_none(Authctxt *authctxt)
    882 {
    883 	/* initial userauth request */
    884 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
    885 	packet_put_cstring(authctxt->server_user);
    886 	packet_put_cstring(authctxt->service);
    887 	packet_put_cstring(authctxt->method->name);
    888 	packet_send();
    889 	return 1;
    890 }
    891 
    892 int
    893 userauth_passwd(Authctxt *authctxt)
    894 {
    895 	static int attempt = 0;
    896 	char prompt[150];
    897 	char *password;
    898 	const char *host = options.host_key_alias ?  options.host_key_alias :
    899 	    authctxt->host;
    900 
    901 	if (attempt++ >= options.number_of_password_prompts)
    902 		return 0;
    903 
    904 	if (attempt != 1)
    905 		error("Permission denied, please try again.");
    906 
    907 	snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
    908 	    authctxt->server_user, host);
    909 	password = read_passphrase(prompt, 0);
    910 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
    911 	packet_put_cstring(authctxt->server_user);
    912 	packet_put_cstring(authctxt->service);
    913 	packet_put_cstring(authctxt->method->name);
    914 	packet_put_char(0);
    915 	packet_put_cstring(password);
    916 	explicit_bzero(password, strlen(password));
    917 	free(password);
    918 	packet_add_padding(64);
    919 	packet_send();
    920 
    921 	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
    922 	    &input_userauth_passwd_changereq);
    923 
    924 	return 1;
    925 }
    926 
    927 /*
    928  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
    929  */
    930 /* ARGSUSED */
    931 int
    932 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
    933 {
    934 	Authctxt *authctxt = ctxt;
    935 	char *info, *lang, *password = NULL, *retype = NULL;
    936 	char prompt[150];
    937 	const char *host;
    938 
    939 	debug2("input_userauth_passwd_changereq");
    940 
    941 	if (authctxt == NULL)
    942 		fatal("input_userauth_passwd_changereq: "
    943 		    "no authentication context");
    944 	host = options.host_key_alias ? options.host_key_alias : authctxt->host;
    945 
    946 	info = packet_get_string(NULL);
    947 	lang = packet_get_string(NULL);
    948 	if (strlen(info) > 0)
    949 		logit("%s", info);
    950 	free(info);
    951 	free(lang);
    952 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
    953 	packet_put_cstring(authctxt->server_user);
    954 	packet_put_cstring(authctxt->service);
    955 	packet_put_cstring(authctxt->method->name);
    956 	packet_put_char(1);			/* additional info */
    957 	snprintf(prompt, sizeof(prompt),
    958 	    "Enter %.30s@%.128s's old password: ",
    959 	    authctxt->server_user, host);
    960 	password = read_passphrase(prompt, 0);
    961 	packet_put_cstring(password);
    962 	explicit_bzero(password, strlen(password));
    963 	free(password);
    964 	password = NULL;
    965 	while (password == NULL) {
    966 		snprintf(prompt, sizeof(prompt),
    967 		    "Enter %.30s@%.128s's new password: ",
    968 		    authctxt->server_user, host);
    969 		password = read_passphrase(prompt, RP_ALLOW_EOF);
    970 		if (password == NULL) {
    971 			/* bail out */
    972 			return 0;
    973 		}
    974 		snprintf(prompt, sizeof(prompt),
    975 		    "Retype %.30s@%.128s's new password: ",
    976 		    authctxt->server_user, host);
    977 		retype = read_passphrase(prompt, 0);
    978 		if (strcmp(password, retype) != 0) {
    979 			explicit_bzero(password, strlen(password));
    980 			free(password);
    981 			logit("Mismatch; try again, EOF to quit.");
    982 			password = NULL;
    983 		}
    984 		explicit_bzero(retype, strlen(retype));
    985 		free(retype);
    986 	}
    987 	packet_put_cstring(password);
    988 	explicit_bzero(password, strlen(password));
    989 	free(password);
    990 	packet_add_padding(64);
    991 	packet_send();
    992 
    993 	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
    994 	    &input_userauth_passwd_changereq);
    995 	return 0;
    996 }
    997 
    998 static const char *
    999 key_sign_encode(const struct sshkey *key)
   1000 {
   1001 	struct ssh *ssh = active_state;
   1002 
   1003 	if (key->type == KEY_RSA) {
   1004 		switch (ssh->kex->rsa_sha2) {
   1005 		case 256:
   1006 			return "rsa-sha2-256";
   1007 		case 512:
   1008 			return "rsa-sha2-512";
   1009 		}
   1010 	}
   1011 	return key_ssh_name(key);
   1012 }
   1013 
   1014 static int
   1015 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
   1016     const u_char *data, size_t datalen, u_int compat)
   1017 {
   1018 	Key *prv;
   1019 	int ret;
   1020 
   1021 	/* the agent supports this key */
   1022 	if (id->key != NULL && id->agent_fd != -1)
   1023 		return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
   1024 		    data, datalen, key_sign_encode(id->key), compat);
   1025 
   1026 	/*
   1027 	 * we have already loaded the private key or
   1028 	 * the private key is stored in external hardware
   1029 	 */
   1030 	if (id->key != NULL &&
   1031 	    (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT)))
   1032 		return (sshkey_sign(id->key, sigp, lenp, data, datalen,
   1033 		    key_sign_encode(id->key), compat));
   1034 
   1035 	/* load the private key from the file */
   1036 	if ((prv = load_identity_file(id)) == NULL)
   1037 		return SSH_ERR_KEY_NOT_FOUND;
   1038 	ret = sshkey_sign(prv, sigp, lenp, data, datalen,
   1039 	    key_sign_encode(prv), compat);
   1040 	sshkey_free(prv);
   1041 	return (ret);
   1042 }
   1043 
   1044 static int
   1045 id_filename_matches(Identity *id, Identity *private_id)
   1046 {
   1047 	const char *suffixes[] = { ".pub", "-cert.pub", NULL };
   1048 	size_t len = strlen(id->filename), plen = strlen(private_id->filename);
   1049 	size_t i, slen;
   1050 
   1051 	if (strcmp(id->filename, private_id->filename) == 0)
   1052 		return 1;
   1053 	for (i = 0; suffixes[i]; i++) {
   1054 		slen = strlen(suffixes[i]);
   1055 		if (len > slen && plen == len - slen &&
   1056 		    strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
   1057 		    memcmp(id->filename, private_id->filename, plen) == 0)
   1058 			return 1;
   1059 	}
   1060 	return 0;
   1061 }
   1062 
   1063 static int
   1064 sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
   1065 {
   1066 	Buffer b;
   1067 	Identity *private_id;
   1068 	u_char *blob, *signature;
   1069 	size_t slen;
   1070 	u_int bloblen, skip = 0;
   1071 	int matched, ret = -1, have_sig = 1;
   1072 	char *fp;
   1073 
   1074 	if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
   1075 	    SSH_FP_DEFAULT)) == NULL)
   1076 		return 0;
   1077 	debug3("%s: %s %s", __func__, key_type(id->key), fp);
   1078 	free(fp);
   1079 
   1080 	if (key_to_blob(id->key, &blob, &bloblen) == 0) {
   1081 		/* we cannot handle this key */
   1082 		debug3("sign_and_send_pubkey: cannot handle key");
   1083 		return 0;
   1084 	}
   1085 	/* data to be signed */
   1086 	buffer_init(&b);
   1087 	if (datafellows & SSH_OLD_SESSIONID) {
   1088 		buffer_append(&b, session_id2, session_id2_len);
   1089 		skip = session_id2_len;
   1090 	} else {
   1091 		buffer_put_string(&b, session_id2, session_id2_len);
   1092 		skip = buffer_len(&b);
   1093 	}
   1094 	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
   1095 	buffer_put_cstring(&b, authctxt->server_user);
   1096 	buffer_put_cstring(&b,
   1097 	    datafellows & SSH_BUG_PKSERVICE ?
   1098 	    "ssh-userauth" :
   1099 	    authctxt->service);
   1100 	if (datafellows & SSH_BUG_PKAUTH) {
   1101 		buffer_put_char(&b, have_sig);
   1102 	} else {
   1103 		buffer_put_cstring(&b, authctxt->method->name);
   1104 		buffer_put_char(&b, have_sig);
   1105 		buffer_put_cstring(&b, key_sign_encode(id->key));
   1106 	}
   1107 	buffer_put_string(&b, blob, bloblen);
   1108 
   1109 	/*
   1110 	 * If the key is an certificate, try to find a matching private key
   1111 	 * and use it to complete the signature.
   1112 	 * If no such private key exists, fall back to trying the certificate
   1113 	 * key itself in case it has a private half already loaded.
   1114 	 */
   1115 	if (key_is_cert(id->key)) {
   1116 		matched = 0;
   1117 		TAILQ_FOREACH(private_id, &authctxt->keys, next) {
   1118 			if (sshkey_equal_public(id->key, private_id->key) &&
   1119 			    id->key->type != private_id->key->type) {
   1120 				id = private_id;
   1121 				matched = 1;
   1122 				break;
   1123 			}
   1124 		}
   1125 		/*
   1126 		 * Exact key matches are preferred, but also allow
   1127 		 * filename matches for non-PKCS#11/agent keys that
   1128 		 * didn't load public keys. This supports the case
   1129 		 * of keeping just a private key file and public
   1130 		 * certificate on disk.
   1131 		 */
   1132 		if (!matched && !id->isprivate && id->agent_fd == -1 &&
   1133 		    (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
   1134 			TAILQ_FOREACH(private_id, &authctxt->keys, next) {
   1135 				if (private_id->key == NULL &&
   1136 				    id_filename_matches(id, private_id)) {
   1137 					id = private_id;
   1138 					matched = 1;
   1139 					break;
   1140 				}
   1141 			}
   1142 		}
   1143 		if (matched) {
   1144 			debug2("%s: using private key \"%s\"%s for "
   1145 			    "certificate", __func__, id->filename,
   1146 			    id->agent_fd != -1 ? " from agent" : "");
   1147 		} else {
   1148 			debug("%s: no separate private key for certificate "
   1149 			    "\"%s\"", __func__, id->filename);
   1150 		}
   1151 	}
   1152 
   1153 	/* generate signature */
   1154 	ret = identity_sign(id, &signature, &slen,
   1155 	    buffer_ptr(&b), buffer_len(&b), datafellows);
   1156 	if (ret != 0) {
   1157 		if (ret != SSH_ERR_KEY_NOT_FOUND)
   1158 			error("%s: signing failed: %s", __func__, ssh_err(ret));
   1159 		free(blob);
   1160 		buffer_free(&b);
   1161 		return 0;
   1162 	}
   1163 #ifdef DEBUG_PK
   1164 	buffer_dump(&b);
   1165 #endif
   1166 	if (datafellows & SSH_BUG_PKSERVICE) {
   1167 		buffer_clear(&b);
   1168 		buffer_append(&b, session_id2, session_id2_len);
   1169 		skip = session_id2_len;
   1170 		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
   1171 		buffer_put_cstring(&b, authctxt->server_user);
   1172 		buffer_put_cstring(&b, authctxt->service);
   1173 		buffer_put_cstring(&b, authctxt->method->name);
   1174 		buffer_put_char(&b, have_sig);
   1175 		if (!(datafellows & SSH_BUG_PKAUTH))
   1176 			buffer_put_cstring(&b, key_ssh_name(id->key));
   1177 		buffer_put_string(&b, blob, bloblen);
   1178 	}
   1179 	free(blob);
   1180 
   1181 	/* append signature */
   1182 	buffer_put_string(&b, signature, slen);
   1183 	free(signature);
   1184 
   1185 	/* skip session id and packet type */
   1186 	if (buffer_len(&b) < skip + 1)
   1187 		fatal("userauth_pubkey: internal error");
   1188 	buffer_consume(&b, skip + 1);
   1189 
   1190 	/* put remaining data from buffer into packet */
   1191 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
   1192 	packet_put_raw(buffer_ptr(&b), buffer_len(&b));
   1193 	buffer_free(&b);
   1194 	packet_send();
   1195 
   1196 	return 1;
   1197 }
   1198 
   1199 static int
   1200 send_pubkey_test(Authctxt *authctxt, Identity *id)
   1201 {
   1202 	u_char *blob;
   1203 	u_int bloblen, have_sig = 0;
   1204 
   1205 	debug3("send_pubkey_test");
   1206 
   1207 	if (key_to_blob(id->key, &blob, &bloblen) == 0) {
   1208 		/* we cannot handle this key */
   1209 		debug3("send_pubkey_test: cannot handle key");
   1210 		return 0;
   1211 	}
   1212 	/* register callback for USERAUTH_PK_OK message */
   1213 	dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
   1214 
   1215 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
   1216 	packet_put_cstring(authctxt->server_user);
   1217 	packet_put_cstring(authctxt->service);
   1218 	packet_put_cstring(authctxt->method->name);
   1219 	packet_put_char(have_sig);
   1220 	if (!(datafellows & SSH_BUG_PKAUTH))
   1221 		packet_put_cstring(key_sign_encode(id->key));
   1222 	packet_put_string(blob, bloblen);
   1223 	free(blob);
   1224 	packet_send();
   1225 	return 1;
   1226 }
   1227 
   1228 static Key *
   1229 load_identity_file(Identity *id)
   1230 {
   1231 	Key *private = NULL;
   1232 	char prompt[300], *passphrase, *comment;
   1233 	int r, perm_ok = 0, quit = 0, i;
   1234 	struct stat st;
   1235 
   1236 	if (stat(id->filename, &st) < 0) {
   1237 		(id->userprovided ? logit : debug3)("no such identity: %s: %s",
   1238 		    id->filename, strerror(errno));
   1239 		return NULL;
   1240 	}
   1241 	snprintf(prompt, sizeof prompt,
   1242 	    "Enter passphrase for key '%.100s': ", id->filename);
   1243 	for (i = 0; i <= options.number_of_password_prompts; i++) {
   1244 		if (i == 0)
   1245 			passphrase = "";
   1246 		else {
   1247 			passphrase = read_passphrase(prompt, 0);
   1248 			if (*passphrase == '\0') {
   1249 				debug2("no passphrase given, try next key");
   1250 				free(passphrase);
   1251 				break;
   1252 			}
   1253 		}
   1254 		switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
   1255 		    passphrase, &private, &comment, &perm_ok))) {
   1256 		case 0:
   1257 			break;
   1258 		case SSH_ERR_KEY_WRONG_PASSPHRASE:
   1259 			if (options.batch_mode) {
   1260 				quit = 1;
   1261 				break;
   1262 			}
   1263 			if (i != 0)
   1264 				debug2("bad passphrase given, try again...");
   1265 			break;
   1266 		case SSH_ERR_SYSTEM_ERROR:
   1267 			if (errno == ENOENT) {
   1268 				debug2("Load key \"%s\": %s",
   1269 				    id->filename, ssh_err(r));
   1270 				quit = 1;
   1271 				break;
   1272 			}
   1273 			/* FALLTHROUGH */
   1274 		default:
   1275 			error("Load key \"%s\": %s", id->filename, ssh_err(r));
   1276 			quit = 1;
   1277 			break;
   1278 		}
   1279 		if (!quit && private != NULL && id->agent_fd == -1 &&
   1280 		    !(id->key && id->isprivate))
   1281 			maybe_add_key_to_agent(id->filename, private, comment,
   1282 			    passphrase);
   1283 		if (i > 0) {
   1284 			explicit_bzero(passphrase, strlen(passphrase));
   1285 			free(passphrase);
   1286 		}
   1287 		free(comment);
   1288 		if (private != NULL || quit)
   1289 			break;
   1290 	}
   1291 	return private;
   1292 }
   1293 
   1294 /*
   1295  * try keys in the following order:
   1296  * 	1. certificates listed in the config file
   1297  * 	2. other input certificates
   1298  *	3. agent keys that are found in the config file
   1299  *	4. other agent keys
   1300  *	5. keys that are only listed in the config file
   1301  */
   1302 static void
   1303 pubkey_prepare(Authctxt *authctxt)
   1304 {
   1305 	struct identity *id, *id2, *tmp;
   1306 	struct idlist agent, files, *preferred;
   1307 	struct sshkey *key;
   1308 	int agent_fd = -1, i, r, found;
   1309 	size_t j;
   1310 	struct ssh_identitylist *idlist;
   1311 
   1312 	TAILQ_INIT(&agent);	/* keys from the agent */
   1313 	TAILQ_INIT(&files);	/* keys from the config file */
   1314 	preferred = &authctxt->keys;
   1315 	TAILQ_INIT(preferred);	/* preferred order of keys */
   1316 
   1317 	/* list of keys stored in the filesystem and PKCS#11 */
   1318 	for (i = 0; i < options.num_identity_files; i++) {
   1319 		key = options.identity_keys[i];
   1320 		if (key && key->type == KEY_RSA1)
   1321 			continue;
   1322 		if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
   1323 			continue;
   1324 		options.identity_keys[i] = NULL;
   1325 		id = xcalloc(1, sizeof(*id));
   1326 		id->agent_fd = -1;
   1327 		id->key = key;
   1328 		id->filename = xstrdup(options.identity_files[i]);
   1329 		id->userprovided = options.identity_file_userprovided[i];
   1330 		TAILQ_INSERT_TAIL(&files, id, next);
   1331 	}
   1332 	/* list of certificates specified by user */
   1333 	for (i = 0; i < options.num_certificate_files; i++) {
   1334 		key = options.certificates[i];
   1335 		if (!key_is_cert(key) || key->cert == NULL ||
   1336 		    key->cert->type != SSH2_CERT_TYPE_USER)
   1337 			continue;
   1338 		id = xcalloc(1, sizeof(*id));
   1339 		id->agent_fd = -1;
   1340 		id->key = key;
   1341 		id->filename = xstrdup(options.certificate_files[i]);
   1342 		id->userprovided = options.certificate_file_userprovided[i];
   1343 		TAILQ_INSERT_TAIL(preferred, id, next);
   1344 	}
   1345 	/* list of keys supported by the agent */
   1346 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
   1347 		if (r != SSH_ERR_AGENT_NOT_PRESENT)
   1348 			debug("%s: ssh_get_authentication_socket: %s",
   1349 			    __func__, ssh_err(r));
   1350 	} else if ((r = ssh_fetch_identitylist(agent_fd, 2, &idlist)) != 0) {
   1351 		if (r != SSH_ERR_AGENT_NO_IDENTITIES)
   1352 			debug("%s: ssh_fetch_identitylist: %s",
   1353 			    __func__, ssh_err(r));
   1354 		close(agent_fd);
   1355 	} else {
   1356 		for (j = 0; j < idlist->nkeys; j++) {
   1357 			found = 0;
   1358 			TAILQ_FOREACH(id, &files, next) {
   1359 				/*
   1360 				 * agent keys from the config file are
   1361 				 * preferred
   1362 				 */
   1363 				if (sshkey_equal(idlist->keys[j], id->key)) {
   1364 					TAILQ_REMOVE(&files, id, next);
   1365 					TAILQ_INSERT_TAIL(preferred, id, next);
   1366 					id->agent_fd = agent_fd;
   1367 					found = 1;
   1368 					break;
   1369 				}
   1370 			}
   1371 			if (!found && !options.identities_only) {
   1372 				id = xcalloc(1, sizeof(*id));
   1373 				/* XXX "steals" key/comment from idlist */
   1374 				id->key = idlist->keys[j];
   1375 				id->filename = idlist->comments[j];
   1376 				idlist->keys[j] = NULL;
   1377 				idlist->comments[j] = NULL;
   1378 				id->agent_fd = agent_fd;
   1379 				TAILQ_INSERT_TAIL(&agent, id, next);
   1380 			}
   1381 		}
   1382 		ssh_free_identitylist(idlist);
   1383 		/* append remaining agent keys */
   1384 		for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
   1385 			TAILQ_REMOVE(&agent, id, next);
   1386 			TAILQ_INSERT_TAIL(preferred, id, next);
   1387 		}
   1388 		authctxt->agent_fd = agent_fd;
   1389 	}
   1390 	/* Prefer PKCS11 keys that are explicitly listed */
   1391 	TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
   1392 		if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
   1393 			continue;
   1394 		found = 0;
   1395 		TAILQ_FOREACH(id2, &files, next) {
   1396 			if (id2->key == NULL ||
   1397 			    (id2->key->flags & SSHKEY_FLAG_EXT) == 0)
   1398 				continue;
   1399 			if (sshkey_equal(id->key, id2->key)) {
   1400 				TAILQ_REMOVE(&files, id, next);
   1401 				TAILQ_INSERT_TAIL(preferred, id, next);
   1402 				found = 1;
   1403 				break;
   1404 			}
   1405 		}
   1406 		/* If IdentitiesOnly set and key not found then don't use it */
   1407 		if (!found && options.identities_only) {
   1408 			TAILQ_REMOVE(&files, id, next);
   1409 			explicit_bzero(id, sizeof(*id));
   1410 			free(id);
   1411 		}
   1412 	}
   1413 	/* append remaining keys from the config file */
   1414 	for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
   1415 		TAILQ_REMOVE(&files, id, next);
   1416 		TAILQ_INSERT_TAIL(preferred, id, next);
   1417 	}
   1418 	/* finally, filter by PubkeyAcceptedKeyTypes */
   1419 	TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
   1420 		if (id->key != NULL &&
   1421 		    match_pattern_list(sshkey_ssh_name(id->key),
   1422 		    options.pubkey_key_types, 0) != 1) {
   1423 			debug("Skipping %s key %s - "
   1424 			    "not in PubkeyAcceptedKeyTypes",
   1425 			    sshkey_ssh_name(id->key), id->filename);
   1426 			TAILQ_REMOVE(preferred, id, next);
   1427 			sshkey_free(id->key);
   1428 			free(id->filename);
   1429 			memset(id, 0, sizeof(*id));
   1430 			continue;
   1431 		}
   1432 		debug2("key: %s (%p)%s%s", id->filename, id->key,
   1433 		    id->userprovided ? ", explicit" : "",
   1434 		    id->agent_fd != -1 ? ", agent" : "");
   1435 	}
   1436 }
   1437 
   1438 static void
   1439 pubkey_cleanup(Authctxt *authctxt)
   1440 {
   1441 	Identity *id;
   1442 
   1443 	if (authctxt->agent_fd != -1)
   1444 		ssh_close_authentication_socket(authctxt->agent_fd);
   1445 	for (id = TAILQ_FIRST(&authctxt->keys); id;
   1446 	    id = TAILQ_FIRST(&authctxt->keys)) {
   1447 		TAILQ_REMOVE(&authctxt->keys, id, next);
   1448 		sshkey_free(id->key);
   1449 		free(id->filename);
   1450 		free(id);
   1451 	}
   1452 }
   1453 
   1454 static void
   1455 pubkey_reset(Authctxt *authctxt)
   1456 {
   1457 	Identity *id;
   1458 
   1459 	TAILQ_FOREACH(id, &authctxt->keys, next)
   1460 		id->tried = 0;
   1461 }
   1462 
   1463 static int
   1464 try_identity(Identity *id)
   1465 {
   1466 	if (!id->key)
   1467 		return (0);
   1468 	if (key_type_plain(id->key->type) == KEY_RSA &&
   1469 	    (datafellows & SSH_BUG_RSASIGMD5) != 0) {
   1470 		debug("Skipped %s key %s for RSA/MD5 server",
   1471 		    key_type(id->key), id->filename);
   1472 		return (0);
   1473 	}
   1474 	return (id->key->type != KEY_RSA1);
   1475 }
   1476 
   1477 int
   1478 userauth_pubkey(Authctxt *authctxt)
   1479 {
   1480 	Identity *id;
   1481 	int sent = 0;
   1482 
   1483 	while ((id = TAILQ_FIRST(&authctxt->keys))) {
   1484 		if (id->tried++)
   1485 			return (0);
   1486 		/* move key to the end of the queue */
   1487 		TAILQ_REMOVE(&authctxt->keys, id, next);
   1488 		TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
   1489 		/*
   1490 		 * send a test message if we have the public key. for
   1491 		 * encrypted keys we cannot do this and have to load the
   1492 		 * private key instead
   1493 		 */
   1494 		if (id->key != NULL) {
   1495 			if (try_identity(id)) {
   1496 				debug("Offering %s public key: %s",
   1497 				    key_type(id->key), id->filename);
   1498 				sent = send_pubkey_test(authctxt, id);
   1499 			}
   1500 		} else {
   1501 			debug("Trying private key: %s", id->filename);
   1502 			id->key = load_identity_file(id);
   1503 			if (id->key != NULL) {
   1504 				if (try_identity(id)) {
   1505 					id->isprivate = 1;
   1506 					sent = sign_and_send_pubkey(
   1507 					    authctxt, id);
   1508 				}
   1509 				key_free(id->key);
   1510 				id->key = NULL;
   1511 				id->isprivate = 0;
   1512 			}
   1513 		}
   1514 		if (sent)
   1515 			return (sent);
   1516 	}
   1517 	return (0);
   1518 }
   1519 
   1520 /*
   1521  * Send userauth request message specifying keyboard-interactive method.
   1522  */
   1523 int
   1524 userauth_kbdint(Authctxt *authctxt)
   1525 {
   1526 	static int attempt = 0;
   1527 
   1528 	if (attempt++ >= options.number_of_password_prompts)
   1529 		return 0;
   1530 	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
   1531 	if (attempt > 1 && !authctxt->info_req_seen) {
   1532 		debug3("userauth_kbdint: disable: no info_req_seen");
   1533 		dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
   1534 		return 0;
   1535 	}
   1536 
   1537 	debug2("userauth_kbdint");
   1538 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
   1539 	packet_put_cstring(authctxt->server_user);
   1540 	packet_put_cstring(authctxt->service);
   1541 	packet_put_cstring(authctxt->method->name);
   1542 	packet_put_cstring("");					/* lang */
   1543 	packet_put_cstring(options.kbd_interactive_devices ?
   1544 	    options.kbd_interactive_devices : "");
   1545 	packet_send();
   1546 
   1547 	dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
   1548 	return 1;
   1549 }
   1550 
   1551 /*
   1552  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
   1553  */
   1554 int
   1555 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
   1556 {
   1557 	Authctxt *authctxt = ctxt;
   1558 	char *name, *inst, *lang, *prompt, *response;
   1559 	u_int num_prompts, i;
   1560 	int echo = 0;
   1561 
   1562 	debug2("input_userauth_info_req");
   1563 
   1564 	if (authctxt == NULL)
   1565 		fatal("input_userauth_info_req: no authentication context");
   1566 
   1567 	authctxt->info_req_seen = 1;
   1568 
   1569 	name = packet_get_string(NULL);
   1570 	inst = packet_get_string(NULL);
   1571 	lang = packet_get_string(NULL);
   1572 	if (strlen(name) > 0)
   1573 		logit("%s", name);
   1574 	if (strlen(inst) > 0)
   1575 		logit("%s", inst);
   1576 	free(name);
   1577 	free(inst);
   1578 	free(lang);
   1579 
   1580 	num_prompts = packet_get_int();
   1581 	/*
   1582 	 * Begin to build info response packet based on prompts requested.
   1583 	 * We commit to providing the correct number of responses, so if
   1584 	 * further on we run into a problem that prevents this, we have to
   1585 	 * be sure and clean this up and send a correct error response.
   1586 	 */
   1587 	packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
   1588 	packet_put_int(num_prompts);
   1589 
   1590 	debug2("input_userauth_info_req: num_prompts %d", num_prompts);
   1591 	for (i = 0; i < num_prompts; i++) {
   1592 		prompt = packet_get_string(NULL);
   1593 		echo = packet_get_char();
   1594 
   1595 		response = read_passphrase(prompt, echo ? RP_ECHO : 0);
   1596 
   1597 		packet_put_cstring(response);
   1598 		explicit_bzero(response, strlen(response));
   1599 		free(response);
   1600 		free(prompt);
   1601 	}
   1602 	packet_check_eom(); /* done with parsing incoming message. */
   1603 
   1604 	packet_add_padding(64);
   1605 	packet_send();
   1606 	return 0;
   1607 }
   1608 
   1609 static int
   1610 ssh_keysign(struct sshkey *key, u_char **sigp, size_t *lenp,
   1611     const u_char *data, size_t datalen)
   1612 {
   1613 	struct sshbuf *b;
   1614 	struct stat st;
   1615 	pid_t pid;
   1616 	int i, r, to[2], from[2], status, sock = packet_get_connection_in();
   1617 	u_char rversion = 0, version = 2;
   1618 	void (*osigchld)(int);
   1619 
   1620 	*sigp = NULL;
   1621 	*lenp = 0;
   1622 
   1623 	if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
   1624 		error("%s: not installed: %s", __func__, strerror(errno));
   1625 		return -1;
   1626 	}
   1627 	if (fflush(stdout) != 0) {
   1628 		error("%s: fflush: %s", __func__, strerror(errno));
   1629 		return -1;
   1630 	}
   1631 	if (pipe(to) < 0) {
   1632 		error("%s: pipe: %s", __func__, strerror(errno));
   1633 		return -1;
   1634 	}
   1635 	if (pipe(from) < 0) {
   1636 		error("%s: pipe: %s", __func__, strerror(errno));
   1637 		return -1;
   1638 	}
   1639 	if ((pid = fork()) < 0) {
   1640 		error("%s: fork: %s", __func__, strerror(errno));
   1641 		return -1;
   1642 	}
   1643 	osigchld = signal(SIGCHLD, SIG_DFL);
   1644 	if (pid == 0) {
   1645 		/* keep the socket on exec */
   1646 		fcntl(sock, F_SETFD, 0);
   1647 		permanently_drop_suid(getuid());
   1648 		close(from[0]);
   1649 		if (dup2(from[1], STDOUT_FILENO) < 0)
   1650 			fatal("%s: dup2: %s", __func__, strerror(errno));
   1651 		close(to[1]);
   1652 		if (dup2(to[0], STDIN_FILENO) < 0)
   1653 			fatal("%s: dup2: %s", __func__, strerror(errno));
   1654 		close(from[1]);
   1655 		close(to[0]);
   1656 		/* Close everything but stdio and the socket */
   1657 		for (i = STDERR_FILENO + 1; i < sock; i++)
   1658 			close(i);
   1659 		closefrom(sock + 1);
   1660 		debug3("%s: [child] pid=%ld, exec %s",
   1661 		    __func__, (long)getpid(), _PATH_SSH_KEY_SIGN);
   1662 		execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
   1663 		fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN,
   1664 		    strerror(errno));
   1665 	}
   1666 	close(from[1]);
   1667 	close(to[0]);
   1668 
   1669 	if ((b = sshbuf_new()) == NULL)
   1670 		fatal("%s: sshbuf_new failed", __func__);
   1671 	/* send # of sock, data to be signed */
   1672 	if ((r = sshbuf_put_u32(b, sock)) != 0 ||
   1673 	    (r = sshbuf_put_string(b, data, datalen)) != 0)
   1674 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
   1675 	if (ssh_msg_send(to[1], version, b) == -1)
   1676 		fatal("%s: couldn't send request", __func__);
   1677 	sshbuf_reset(b);
   1678 	r = ssh_msg_recv(from[0], b);
   1679 	close(from[0]);
   1680 	close(to[1]);
   1681 	if (r < 0) {
   1682 		error("%s: no reply", __func__);
   1683 		goto fail;
   1684 	}
   1685 
   1686 	errno = 0;
   1687 	while (waitpid(pid, &status, 0) < 0) {
   1688 		if (errno != EINTR) {
   1689 			error("%s: waitpid %ld: %s",
   1690 			    __func__, (long)pid, strerror(errno));
   1691 			goto fail;
   1692 		}
   1693 	}
   1694 	if (!WIFEXITED(status)) {
   1695 		error("%s: exited abnormally", __func__);
   1696 		goto fail;
   1697 	}
   1698 	if (WEXITSTATUS(status) != 0) {
   1699 		error("%s: exited with status %d",
   1700 		    __func__, WEXITSTATUS(status));
   1701 		goto fail;
   1702 	}
   1703 	if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
   1704 		error("%s: buffer error: %s", __func__, ssh_err(r));
   1705 		goto fail;
   1706 	}
   1707 	if (rversion != version) {
   1708 		error("%s: bad version", __func__);
   1709 		goto fail;
   1710 	}
   1711 	if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
   1712 		error("%s: buffer error: %s", __func__, ssh_err(r));
   1713  fail:
   1714 		signal(SIGCHLD, osigchld);
   1715 		sshbuf_free(b);
   1716 		return -1;
   1717 	}
   1718 	signal(SIGCHLD, osigchld);
   1719 	sshbuf_free(b);
   1720 
   1721 	return 0;
   1722 }
   1723 
   1724 int
   1725 userauth_hostbased(Authctxt *authctxt)
   1726 {
   1727 	struct ssh *ssh = active_state;
   1728 	struct sshkey *private = NULL;
   1729 	struct sshbuf *b = NULL;
   1730 	const char *service;
   1731 	u_char *sig = NULL, *keyblob = NULL;
   1732 	char *fp = NULL, *chost = NULL, *lname = NULL;
   1733 	size_t siglen = 0, keylen = 0;
   1734 	int i, r, success = 0;
   1735 
   1736 	if (authctxt->ktypes == NULL) {
   1737 		authctxt->oktypes = xstrdup(options.hostbased_key_types);
   1738 		authctxt->ktypes = authctxt->oktypes;
   1739 	}
   1740 
   1741 	/*
   1742 	 * Work through each listed type pattern in HostbasedKeyTypes,
   1743 	 * trying each hostkey that matches the type in turn.
   1744 	 */
   1745 	for (;;) {
   1746 		if (authctxt->active_ktype == NULL)
   1747 			authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
   1748 		if (authctxt->active_ktype == NULL ||
   1749 		    *authctxt->active_ktype == '\0')
   1750 			break;
   1751 		debug3("%s: trying key type %s", __func__,
   1752 		    authctxt->active_ktype);
   1753 
   1754 		/* check for a useful key */
   1755 		private = NULL;
   1756 		for (i = 0; i < authctxt->sensitive->nkeys; i++) {
   1757 			if (authctxt->sensitive->keys[i] == NULL ||
   1758 			    authctxt->sensitive->keys[i]->type == KEY_RSA1 ||
   1759 			    authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
   1760 				continue;
   1761 			if (match_pattern_list(
   1762 			    sshkey_ssh_name(authctxt->sensitive->keys[i]),
   1763 			    authctxt->active_ktype, 0) != 1)
   1764 				continue;
   1765 			/* we take and free the key */
   1766 			private = authctxt->sensitive->keys[i];
   1767 			authctxt->sensitive->keys[i] = NULL;
   1768 			break;
   1769 		}
   1770 		/* Found one */
   1771 		if (private != NULL)
   1772 			break;
   1773 		/* No more keys of this type; advance */
   1774 		authctxt->active_ktype = NULL;
   1775 	}
   1776 	if (private == NULL) {
   1777 		free(authctxt->oktypes);
   1778 		authctxt->oktypes = authctxt->ktypes = NULL;
   1779 		authctxt->active_ktype = NULL;
   1780 		debug("No more client hostkeys for hostbased authentication.");
   1781 		goto out;
   1782 	}
   1783 
   1784 	if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
   1785 	    SSH_FP_DEFAULT)) == NULL) {
   1786 		error("%s: sshkey_fingerprint failed", __func__);
   1787 		goto out;
   1788 	}
   1789 	debug("%s: trying hostkey %s %s",
   1790 	    __func__, sshkey_ssh_name(private), fp);
   1791 
   1792 	/* figure out a name for the client host */
   1793 	if ((lname = get_local_name(packet_get_connection_in())) == NULL) {
   1794 		error("%s: cannot get local ipaddr/name", __func__);
   1795 		goto out;
   1796 	}
   1797 
   1798 	/* XXX sshbuf_put_stringf? */
   1799 	xasprintf(&chost, "%s.", lname);
   1800 	debug2("%s: chost %s", __func__, chost);
   1801 
   1802 	service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
   1803 	    authctxt->service;
   1804 
   1805 	/* construct data */
   1806 	if ((b = sshbuf_new()) == NULL) {
   1807 		error("%s: sshbuf_new failed", __func__);
   1808 		goto out;
   1809 	}
   1810 	if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
   1811 		error("%s: sshkey_to_blob: %s", __func__, ssh_err(r));
   1812 		goto out;
   1813 	}
   1814 	if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
   1815 	    (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
   1816 	    (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
   1817 	    (r = sshbuf_put_cstring(b, service)) != 0 ||
   1818 	    (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
   1819 	    (r = sshbuf_put_cstring(b, key_ssh_name(private))) != 0 ||
   1820 	    (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
   1821 	    (r = sshbuf_put_cstring(b, chost)) != 0 ||
   1822 	    (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
   1823 		error("%s: buffer error: %s", __func__, ssh_err(r));
   1824 		goto out;
   1825 	}
   1826 
   1827 #ifdef DEBUG_PK
   1828 	sshbuf_dump(b, stderr);
   1829 #endif
   1830 	if (authctxt->sensitive->external_keysign)
   1831 		r = ssh_keysign(private, &sig, &siglen,
   1832 		    sshbuf_ptr(b), sshbuf_len(b));
   1833 	else if ((r = sshkey_sign(private, &sig, &siglen,
   1834 	    sshbuf_ptr(b), sshbuf_len(b), NULL, datafellows)) != 0)
   1835 		debug("%s: sshkey_sign: %s", __func__, ssh_err(r));
   1836 	if (r != 0) {
   1837 		error("sign using hostkey %s %s failed",
   1838 		    sshkey_ssh_name(private), fp);
   1839 		goto out;
   1840 	}
   1841 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
   1842 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
   1843 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
   1844 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
   1845 	    (r = sshpkt_put_cstring(ssh, key_ssh_name(private))) != 0 ||
   1846 	    (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
   1847 	    (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
   1848 	    (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
   1849 	    (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
   1850 	    (r = sshpkt_send(ssh)) != 0) {
   1851 		error("%s: packet error: %s", __func__, ssh_err(r));
   1852 		goto out;
   1853 	}
   1854 	success = 1;
   1855 
   1856  out:
   1857 	if (sig != NULL) {
   1858 		explicit_bzero(sig, siglen);
   1859 		free(sig);
   1860 	}
   1861 	free(keyblob);
   1862 	free(lname);
   1863 	free(fp);
   1864 	free(chost);
   1865 	sshkey_free(private);
   1866 	sshbuf_free(b);
   1867 
   1868 	return success;
   1869 }
   1870 
   1871 /* find auth method */
   1872 
   1873 /*
   1874  * given auth method name, if configurable options permit this method fill
   1875  * in auth_ident field and return true, otherwise return false.
   1876  */
   1877 static int
   1878 authmethod_is_enabled(Authmethod *method)
   1879 {
   1880 	if (method == NULL)
   1881 		return 0;
   1882 	/* return false if options indicate this method is disabled */
   1883 	if  (method->enabled == NULL || *method->enabled == 0)
   1884 		return 0;
   1885 	/* return false if batch mode is enabled but method needs interactive mode */
   1886 	if  (method->batch_flag != NULL && *method->batch_flag != 0)
   1887 		return 0;
   1888 	return 1;
   1889 }
   1890 
   1891 static Authmethod *
   1892 authmethod_lookup(const char *name)
   1893 {
   1894 	Authmethod *method = NULL;
   1895 	if (name != NULL)
   1896 		for (method = authmethods; method->name != NULL; method++)
   1897 			if (strcmp(name, method->name) == 0)
   1898 				return method;
   1899 	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
   1900 	return NULL;
   1901 }
   1902 
   1903 /* XXX internal state */
   1904 static Authmethod *current = NULL;
   1905 static char *supported = NULL;
   1906 static char *preferred = NULL;
   1907 
   1908 /*
   1909  * Given the authentication method list sent by the server, return the
   1910  * next method we should try.  If the server initially sends a nil list,
   1911  * use a built-in default list.
   1912  */
   1913 static Authmethod *
   1914 authmethod_get(char *authlist)
   1915 {
   1916 	char *name = NULL;
   1917 	u_int next;
   1918 
   1919 	/* Use a suitable default if we're passed a nil list.  */
   1920 	if (authlist == NULL || strlen(authlist) == 0)
   1921 		authlist = options.preferred_authentications;
   1922 
   1923 	if (supported == NULL || strcmp(authlist, supported) != 0) {
   1924 		debug3("start over, passed a different list %s", authlist);
   1925 		free(supported);
   1926 		supported = xstrdup(authlist);
   1927 		preferred = options.preferred_authentications;
   1928 		debug3("preferred %s", preferred);
   1929 		current = NULL;
   1930 	} else if (current != NULL && authmethod_is_enabled(current))
   1931 		return current;
   1932 
   1933 	for (;;) {
   1934 		if ((name = match_list(preferred, supported, &next)) == NULL) {
   1935 			debug("No more authentication methods to try.");
   1936 			current = NULL;
   1937 			return NULL;
   1938 		}
   1939 		preferred += next;
   1940 		debug3("authmethod_lookup %s", name);
   1941 		debug3("remaining preferred: %s", preferred);
   1942 		if ((current = authmethod_lookup(name)) != NULL &&
   1943 		    authmethod_is_enabled(current)) {
   1944 			debug3("authmethod_is_enabled %s", name);
   1945 			debug("Next authentication method: %s", name);
   1946 			free(name);
   1947 			return current;
   1948 		}
   1949 		free(name);
   1950 	}
   1951 }
   1952 
   1953 static char *
   1954 authmethods_get(void)
   1955 {
   1956 	Authmethod *method = NULL;
   1957 	Buffer b;
   1958 	char *list;
   1959 
   1960 	buffer_init(&b);
   1961 	for (method = authmethods; method->name != NULL; method++) {
   1962 		if (authmethod_is_enabled(method)) {
   1963 			if (buffer_len(&b) > 0)
   1964 				buffer_append(&b, ",", 1);
   1965 			buffer_append(&b, method->name, strlen(method->name));
   1966 		}
   1967 	}
   1968 	if ((list = sshbuf_dup_string(&b)) == NULL)
   1969 		fatal("%s: sshbuf_dup_string failed", __func__);
   1970 	buffer_free(&b);
   1971 	return list;
   1972 }
   1973 
   1974