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