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