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