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