Generic gssapi support
[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 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 (GSS_ERROR(gss_indicate_mechs(&min, &gss_supported))) {
705                         gss_supported = NULL;
706                         return 0;
707                 }
708
709         /* Check to see if the mechanism is usable before we offer it */
710         while (mech < gss_supported->count && !ok) {
711                 /* My DER encoding requires length<128 */
712                 if (gss_supported->elements[mech].length < 128 &&
713                     ssh_gssapi_check_mechanism(&gssctxt, 
714                     &gss_supported->elements[mech], gss_host, 
715                     options.gss_client_identity)) {
716                         ok = 1; /* Mechanism works */
717                 } else {
718                         mech++;
719                 }
720         }
721
722         if (!ok)
723                 return 0;
724
725         authctxt->methoddata=(void *)gssctxt;
726
727         packet_start(SSH2_MSG_USERAUTH_REQUEST);
728         packet_put_cstring(authctxt->server_user);
729         packet_put_cstring(authctxt->service);
730         packet_put_cstring(authctxt->method->name);
731
732         packet_put_int(1);
733
734         packet_put_int((gss_supported->elements[mech].length) + 2);
735         packet_put_char(SSH_GSS_OIDTYPE);
736         packet_put_char(gss_supported->elements[mech].length);
737         packet_put_raw(gss_supported->elements[mech].elements,
738             gss_supported->elements[mech].length);
739
740         packet_send();
741
742         dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
743         dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
744         dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
745         dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
746
747         mech++; /* Move along to next candidate */
748
749         return 1;
750 }
751
752 static OM_uint32
753 process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
754 {
755         Authctxt *authctxt = ctxt;
756         Gssctxt *gssctxt = authctxt->methoddata;
757         gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
758         gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
759         gss_buffer_desc gssbuf;
760         OM_uint32 status, ms, flags;
761         Buffer b;
762
763         status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
764             recv_tok, &send_tok, &flags);
765
766         if (send_tok.length > 0) {
767                 if (GSS_ERROR(status))
768                         packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
769                 else
770                         packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
771
772                 packet_put_string(send_tok.value, send_tok.length);
773                 packet_send();
774                 gss_release_buffer(&ms, &send_tok);
775         }
776
777         if (status == GSS_S_COMPLETE) {
778                 /* send either complete or MIC, depending on mechanism */
779                 if (!(flags & GSS_C_INTEG_FLAG)) {
780                         packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
781                         packet_send();
782                 } else {
783                         ssh_gssapi_buildmic(&b, authctxt->server_user,
784                             authctxt->service, "gssapi-with-mic");
785
786                         gssbuf.value = buffer_ptr(&b);
787                         gssbuf.length = buffer_len(&b);
788
789                         status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
790
791                         if (!GSS_ERROR(status)) {
792                                 packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
793                                 packet_put_string(mic.value, mic.length);
794
795                                 packet_send();
796                         }
797
798                         buffer_free(&b);
799                         gss_release_buffer(&ms, &mic);
800                 }
801         }
802
803         return status;
804 }
805
806 /* ARGSUSED */
807 void
808 input_gssapi_response(int type, u_int32_t plen, void *ctxt)
809 {
810         Authctxt *authctxt = ctxt;
811         Gssctxt *gssctxt;
812         u_int oidlen;
813         u_char *oidv;
814
815         if (authctxt == NULL)
816                 fatal("input_gssapi_response: no authentication context");
817         gssctxt = authctxt->methoddata;
818
819         /* Setup our OID */
820         oidv = packet_get_string(&oidlen);
821
822         if (oidlen <= 2 ||
823             oidv[0] != SSH_GSS_OIDTYPE ||
824             oidv[1] != oidlen - 2) {
825                 xfree(oidv);
826                 debug("Badly encoded mechanism OID received");
827                 userauth(authctxt, NULL);
828                 return;
829         }
830
831         if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
832                 fatal("Server returned different OID than expected");
833
834         packet_check_eom();
835
836         xfree(oidv);
837
838         if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
839                 /* Start again with next method on list */
840                 debug("Trying to start again");
841                 userauth(authctxt, NULL);
842                 return;
843         }
844 }
845
846 /* ARGSUSED */
847 void
848 input_gssapi_token(int type, u_int32_t plen, void *ctxt)
849 {
850         Authctxt *authctxt = ctxt;
851         gss_buffer_desc recv_tok;
852         OM_uint32 status;
853         u_int slen;
854
855         if (authctxt == NULL)
856                 fatal("input_gssapi_response: no authentication context");
857
858         recv_tok.value = packet_get_string(&slen);
859         recv_tok.length = slen; /* safe typecast */
860
861         packet_check_eom();
862
863         status = process_gssapi_token(ctxt, &recv_tok);
864
865         xfree(recv_tok.value);
866
867         if (GSS_ERROR(status)) {
868                 /* Start again with the next method in the list */
869                 userauth(authctxt, NULL);
870                 return;
871         }
872 }
873
874 /* ARGSUSED */
875 void
876 input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
877 {
878         Authctxt *authctxt = ctxt;
879         Gssctxt *gssctxt;
880         gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
881         gss_buffer_desc recv_tok;
882         OM_uint32 status, ms;
883         u_int len;
884
885         if (authctxt == NULL)
886                 fatal("input_gssapi_response: no authentication context");
887         gssctxt = authctxt->methoddata;
888
889         recv_tok.value = packet_get_string(&len);
890         recv_tok.length = len;
891
892         packet_check_eom();
893
894         /* Stick it into GSSAPI and see what it says */
895         status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
896             &recv_tok, &send_tok, NULL);
897
898         xfree(recv_tok.value);
899         gss_release_buffer(&ms, &send_tok);
900
901         /* Server will be returning a failed packet after this one */
902 }
903
904 /* ARGSUSED */
905 void
906 input_gssapi_error(int type, u_int32_t plen, void *ctxt)
907 {
908         OM_uint32 maj, min;
909         char *msg;
910         char *lang;
911
912         maj=packet_get_int();
913         min=packet_get_int();
914         msg=packet_get_string(NULL);
915         lang=packet_get_string(NULL);
916
917         packet_check_eom();
918
919         debug("Server GSSAPI Error:\n%s", msg);
920         xfree(msg);
921         xfree(lang);
922 }
923
924 int
925 userauth_gsskeyex(Authctxt *authctxt)
926 {
927         Buffer b;
928         gss_buffer_desc gssbuf;
929         gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
930         OM_uint32 ms;
931
932         static int attempt = 0;
933         if (attempt++ >= 1)
934                 return (0);
935
936         if (gss_kex_context == NULL) {
937                 debug("No valid Key exchange context"); 
938                 return (0);
939         }
940
941         ssh_gssapi_buildmic(&b, authctxt->server_user, authctxt->service,
942             "gssapi-keyex");
943
944         gssbuf.value = buffer_ptr(&b);
945         gssbuf.length = buffer_len(&b);
946
947         if (GSS_ERROR(ssh_gssapi_sign(gss_kex_context, &gssbuf, &mic))) {
948                 buffer_free(&b);
949                 return (0);
950         }
951
952         packet_start(SSH2_MSG_USERAUTH_REQUEST);
953         packet_put_cstring(authctxt->server_user);
954         packet_put_cstring(authctxt->service);
955         packet_put_cstring(authctxt->method->name);
956         packet_put_string(mic.value, mic.length);
957         packet_send();
958
959         buffer_free(&b);
960         gss_release_buffer(&ms, &mic);
961
962         return (1);
963 }
964
965 #endif /* GSSAPI */
966
967 int
968 userauth_none(Authctxt *authctxt)
969 {
970         /* initial userauth request */
971         packet_start(SSH2_MSG_USERAUTH_REQUEST);
972         packet_put_cstring(authctxt->server_user);
973         packet_put_cstring(authctxt->service);
974         packet_put_cstring(authctxt->method->name);
975         packet_send();
976         return 1;
977 }
978
979 int
980 userauth_passwd(Authctxt *authctxt)
981 {
982         static int attempt = 0;
983         char prompt[150];
984         char *password;
985         const char *host = options.host_key_alias ?  options.host_key_alias :
986             authctxt->host;
987
988         if (attempt++ >= options.number_of_password_prompts)
989                 return 0;
990
991         if (attempt != 1)
992                 error("Permission denied, please try again.");
993
994         snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
995             authctxt->server_user, host);
996         password = read_passphrase(prompt, 0);
997         packet_start(SSH2_MSG_USERAUTH_REQUEST);
998         packet_put_cstring(authctxt->server_user);
999         packet_put_cstring(authctxt->service);
1000         packet_put_cstring(authctxt->method->name);
1001         packet_put_char(0);
1002         packet_put_cstring(password);
1003         memset(password, 0, strlen(password));
1004         xfree(password);
1005         packet_add_padding(64);
1006         packet_send();
1007
1008         dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1009             &input_userauth_passwd_changereq);
1010
1011         return 1;
1012 }
1013
1014 /*
1015  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
1016  */
1017 /* ARGSUSED */
1018 void
1019 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
1020 {
1021         Authctxt *authctxt = ctxt;
1022         char *info, *lang, *password = NULL, *retype = NULL;
1023         char prompt[150];
1024         const char *host = options.host_key_alias ? options.host_key_alias :
1025             authctxt->host;
1026
1027         debug2("input_userauth_passwd_changereq");
1028
1029         if (authctxt == NULL)
1030                 fatal("input_userauth_passwd_changereq: "
1031                     "no authentication context");
1032
1033         info = packet_get_string(NULL);
1034         lang = packet_get_string(NULL);
1035         if (strlen(info) > 0)
1036                 logit("%s", info);
1037         xfree(info);
1038         xfree(lang);
1039         packet_start(SSH2_MSG_USERAUTH_REQUEST);
1040         packet_put_cstring(authctxt->server_user);
1041         packet_put_cstring(authctxt->service);
1042         packet_put_cstring(authctxt->method->name);
1043         packet_put_char(1);                     /* additional info */
1044         snprintf(prompt, sizeof(prompt),
1045             "Enter %.30s@%.128s's old password: ",
1046             authctxt->server_user, host);
1047         password = read_passphrase(prompt, 0);
1048         packet_put_cstring(password);
1049         memset(password, 0, strlen(password));
1050         xfree(password);
1051         password = NULL;
1052         while (password == NULL) {
1053                 snprintf(prompt, sizeof(prompt),
1054                     "Enter %.30s@%.128s's new password: ",
1055                     authctxt->server_user, host);
1056                 password = read_passphrase(prompt, RP_ALLOW_EOF);
1057                 if (password == NULL) {
1058                         /* bail out */
1059                         return;
1060                 }
1061                 snprintf(prompt, sizeof(prompt),
1062                     "Retype %.30s@%.128s's new password: ",
1063                     authctxt->server_user, host);
1064                 retype = read_passphrase(prompt, 0);
1065                 if (strcmp(password, retype) != 0) {
1066                         memset(password, 0, strlen(password));
1067                         xfree(password);
1068                         logit("Mismatch; try again, EOF to quit.");
1069                         password = NULL;
1070                 }
1071                 memset(retype, 0, strlen(retype));
1072                 xfree(retype);
1073         }
1074         packet_put_cstring(password);
1075         memset(password, 0, strlen(password));
1076         xfree(password);
1077         packet_add_padding(64);
1078         packet_send();
1079
1080         dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1081             &input_userauth_passwd_changereq);
1082 }
1083
1084 #ifdef JPAKE
1085 static char *
1086 pw_encrypt(const char *password, const char *crypt_scheme, const char *salt)
1087 {
1088         /* OpenBSD crypt(3) handles all of these */
1089         if (strcmp(crypt_scheme, "crypt") == 0 ||
1090             strcmp(crypt_scheme, "bcrypt") == 0 ||
1091             strcmp(crypt_scheme, "md5crypt") == 0 ||
1092             strcmp(crypt_scheme, "crypt-extended") == 0)
1093                 return xstrdup(crypt(password, salt));
1094         error("%s: unsupported password encryption scheme \"%.100s\"",
1095             __func__, crypt_scheme);
1096         return NULL;
1097 }
1098
1099 static BIGNUM *
1100 jpake_password_to_secret(Authctxt *authctxt, const char *crypt_scheme,
1101     const char *salt)
1102 {
1103         char prompt[256], *password, *crypted;
1104         u_char *secret;
1105         u_int secret_len;
1106         BIGNUM *ret;
1107
1108         snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password (JPAKE): ",
1109             authctxt->server_user, authctxt->host);
1110         password = read_passphrase(prompt, 0);
1111
1112         if ((crypted = pw_encrypt(password, crypt_scheme, salt)) == NULL) {
1113                 logit("Disabling %s authentication", authctxt->method->name);
1114                 authctxt->method->enabled = NULL;
1115                 /* Continue with an empty password to fail gracefully */
1116                 crypted = xstrdup("");
1117         }
1118
1119 #ifdef JPAKE_DEBUG
1120         debug3("%s: salt = %s", __func__, salt);
1121         debug3("%s: scheme = %s", __func__, crypt_scheme);
1122         debug3("%s: crypted = %s", __func__, crypted);
1123 #endif
1124
1125         if (hash_buffer(crypted, strlen(crypted), EVP_sha256(),
1126             &secret, &secret_len) != 0)
1127                 fatal("%s: hash_buffer", __func__);
1128
1129         bzero(password, strlen(password));
1130         bzero(crypted, strlen(crypted));
1131         xfree(password);
1132         xfree(crypted);
1133
1134         if ((ret = BN_bin2bn(secret, secret_len, NULL)) == NULL)
1135                 fatal("%s: BN_bin2bn (secret)", __func__);
1136         bzero(secret, secret_len);
1137         xfree(secret);
1138
1139         return ret;
1140 }
1141
1142 /* ARGSUSED */
1143 void
1144 input_userauth_jpake_server_step1(int type, u_int32_t seq, void *ctxt)
1145 {
1146         Authctxt *authctxt = ctxt;
1147         struct jpake_ctx *pctx = authctxt->methoddata;
1148         u_char *x3_proof, *x4_proof, *x2_s_proof;
1149         u_int x3_proof_len, x4_proof_len, x2_s_proof_len;
1150         char *crypt_scheme, *salt;
1151
1152         /* Disable this message */
1153         dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP1, NULL);
1154
1155         if ((pctx->g_x3 = BN_new()) == NULL ||
1156             (pctx->g_x4 = BN_new()) == NULL)
1157                 fatal("%s: BN_new", __func__);
1158
1159         /* Fetch step 1 values */
1160         crypt_scheme = packet_get_string(NULL);
1161         salt = packet_get_string(NULL);
1162         pctx->server_id = packet_get_string(&pctx->server_id_len);
1163         packet_get_bignum2(pctx->g_x3);
1164         packet_get_bignum2(pctx->g_x4);
1165         x3_proof = packet_get_string(&x3_proof_len);
1166         x4_proof = packet_get_string(&x4_proof_len);
1167         packet_check_eom();
1168
1169         JPAKE_DEBUG_CTX((pctx, "step 1 received in %s", __func__));
1170
1171         /* Obtain password and derive secret */
1172         pctx->s = jpake_password_to_secret(authctxt, crypt_scheme, salt);
1173         bzero(crypt_scheme, strlen(crypt_scheme));
1174         bzero(salt, strlen(salt));
1175         xfree(crypt_scheme);
1176         xfree(salt);
1177         JPAKE_DEBUG_BN((pctx->s, "%s: s = ", __func__));
1178
1179         /* Calculate step 2 values */
1180         jpake_step2(pctx->grp, pctx->s, pctx->g_x1,
1181             pctx->g_x3, pctx->g_x4, pctx->x2,
1182             pctx->server_id, pctx->server_id_len,
1183             pctx->client_id, pctx->client_id_len,
1184             x3_proof, x3_proof_len,
1185             x4_proof, x4_proof_len,
1186             &pctx->a,
1187             &x2_s_proof, &x2_s_proof_len);
1188
1189         bzero(x3_proof, x3_proof_len);
1190         bzero(x4_proof, x4_proof_len);
1191         xfree(x3_proof);
1192         xfree(x4_proof);
1193
1194         JPAKE_DEBUG_CTX((pctx, "step 2 sending in %s", __func__));
1195
1196         /* Send values for step 2 */
1197         packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_STEP2);
1198         packet_put_bignum2(pctx->a);
1199         packet_put_string(x2_s_proof, x2_s_proof_len);
1200         packet_send();
1201
1202         bzero(x2_s_proof, x2_s_proof_len);
1203         xfree(x2_s_proof);
1204
1205         /* Expect step 2 packet from peer */
1206         dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP2,
1207             input_userauth_jpake_server_step2);
1208 }
1209
1210 /* ARGSUSED */
1211 void
1212 input_userauth_jpake_server_step2(int type, u_int32_t seq, void *ctxt)
1213 {
1214         Authctxt *authctxt = ctxt;
1215         struct jpake_ctx *pctx = authctxt->methoddata;
1216         u_char *x4_s_proof;
1217         u_int x4_s_proof_len;
1218
1219         /* Disable this message */
1220         dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP2, NULL);
1221
1222         if ((pctx->b = BN_new()) == NULL)
1223                 fatal("%s: BN_new", __func__);
1224
1225         /* Fetch step 2 values */
1226         packet_get_bignum2(pctx->b);
1227         x4_s_proof = packet_get_string(&x4_s_proof_len);
1228         packet_check_eom();
1229
1230         JPAKE_DEBUG_CTX((pctx, "step 2 received in %s", __func__));
1231
1232         /* Derive shared key and calculate confirmation hash */
1233         jpake_key_confirm(pctx->grp, pctx->s, pctx->b,
1234             pctx->x2, pctx->g_x1, pctx->g_x2, pctx->g_x3, pctx->g_x4,
1235             pctx->client_id, pctx->client_id_len,
1236             pctx->server_id, pctx->server_id_len,
1237             session_id2, session_id2_len,
1238             x4_s_proof, x4_s_proof_len,
1239             &pctx->k,
1240             &pctx->h_k_cid_sessid, &pctx->h_k_cid_sessid_len);
1241
1242         bzero(x4_s_proof, x4_s_proof_len);
1243         xfree(x4_s_proof);
1244
1245         JPAKE_DEBUG_CTX((pctx, "confirm sending in %s", __func__));
1246
1247         /* Send key confirmation proof */
1248         packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_CONFIRM);
1249         packet_put_string(pctx->h_k_cid_sessid, pctx->h_k_cid_sessid_len);
1250         packet_send();
1251
1252         /* Expect confirmation from peer */
1253         dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_CONFIRM,
1254             input_userauth_jpake_server_confirm);
1255 }
1256
1257 /* ARGSUSED */
1258 void
1259 input_userauth_jpake_server_confirm(int type, u_int32_t seq, void *ctxt)
1260 {
1261         Authctxt *authctxt = ctxt;
1262         struct jpake_ctx *pctx = authctxt->methoddata;
1263
1264         /* Disable this message */
1265         dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_CONFIRM, NULL);
1266
1267         pctx->h_k_sid_sessid = packet_get_string(&pctx->h_k_sid_sessid_len);
1268         packet_check_eom();
1269
1270         JPAKE_DEBUG_CTX((pctx, "confirm received in %s", __func__));
1271
1272         /* Verify expected confirmation hash */
1273         if (jpake_check_confirm(pctx->k,
1274             pctx->server_id, pctx->server_id_len,
1275             session_id2, session_id2_len,
1276             pctx->h_k_sid_sessid, pctx->h_k_sid_sessid_len) == 1)
1277                 debug("%s: %s success", __func__, authctxt->method->name);
1278         else {
1279                 debug("%s: confirmation mismatch", __func__);
1280                 /* XXX stash this so if auth succeeds then we can warn/kill */
1281         }
1282
1283         userauth_jpake_cleanup(authctxt);
1284 }
1285 #endif /* JPAKE */
1286
1287 static int
1288 identity_sign(Identity *id, u_char **sigp, u_int *lenp,
1289     u_char *data, u_int datalen)
1290 {
1291         Key *prv;
1292         int ret;
1293
1294         /* the agent supports this key */
1295         if (id->ac)
1296                 return (ssh_agent_sign(id->ac, id->key, sigp, lenp,
1297                     data, datalen));
1298         /*
1299          * we have already loaded the private key or
1300          * the private key is stored in external hardware
1301          */
1302         if (id->isprivate || (id->key->flags & KEY_FLAG_EXT))
1303                 return (key_sign(id->key, sigp, lenp, data, datalen));
1304         /* load the private key from the file */
1305         if ((prv = load_identity_file(id->filename)) == NULL)
1306                 return (-1);
1307         ret = key_sign(prv, sigp, lenp, data, datalen);
1308         key_free(prv);
1309         return (ret);
1310 }
1311
1312 static int
1313 sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1314 {
1315         Buffer b;
1316         u_char *blob, *signature;
1317         u_int bloblen, slen;
1318         u_int skip = 0;
1319         int ret = -1;
1320         int have_sig = 1;
1321         char *fp;
1322
1323         fp = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
1324         debug3("sign_and_send_pubkey: %s %s", key_type(id->key), fp);
1325         xfree(fp);
1326
1327         if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1328                 /* we cannot handle this key */
1329                 debug3("sign_and_send_pubkey: cannot handle key");
1330                 return 0;
1331         }
1332         /* data to be signed */
1333         buffer_init(&b);
1334         if (datafellows & SSH_OLD_SESSIONID) {
1335                 buffer_append(&b, session_id2, session_id2_len);
1336                 skip = session_id2_len;
1337         } else {
1338                 buffer_put_string(&b, session_id2, session_id2_len);
1339                 skip = buffer_len(&b);
1340         }
1341         buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1342         buffer_put_cstring(&b, authctxt->server_user);
1343         buffer_put_cstring(&b,
1344             datafellows & SSH_BUG_PKSERVICE ?
1345             "ssh-userauth" :
1346             authctxt->service);
1347         if (datafellows & SSH_BUG_PKAUTH) {
1348                 buffer_put_char(&b, have_sig);
1349         } else {
1350                 buffer_put_cstring(&b, authctxt->method->name);
1351                 buffer_put_char(&b, have_sig);
1352                 buffer_put_cstring(&b, key_ssh_name(id->key));
1353         }
1354         buffer_put_string(&b, blob, bloblen);
1355
1356         /* generate signature */
1357         ret = identity_sign(id, &signature, &slen,
1358             buffer_ptr(&b), buffer_len(&b));
1359         if (ret == -1) {
1360                 xfree(blob);
1361                 buffer_free(&b);
1362                 return 0;
1363         }
1364 #ifdef DEBUG_PK
1365         buffer_dump(&b);
1366 #endif
1367         if (datafellows & SSH_BUG_PKSERVICE) {
1368                 buffer_clear(&b);
1369                 buffer_append(&b, session_id2, session_id2_len);
1370                 skip = session_id2_len;
1371                 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1372                 buffer_put_cstring(&b, authctxt->server_user);
1373                 buffer_put_cstring(&b, authctxt->service);
1374                 buffer_put_cstring(&b, authctxt->method->name);
1375                 buffer_put_char(&b, have_sig);
1376                 if (!(datafellows & SSH_BUG_PKAUTH))
1377                         buffer_put_cstring(&b, key_ssh_name(id->key));
1378                 buffer_put_string(&b, blob, bloblen);
1379         }
1380         xfree(blob);
1381
1382         /* append signature */
1383         buffer_put_string(&b, signature, slen);
1384         xfree(signature);
1385
1386         /* skip session id and packet type */
1387         if (buffer_len(&b) < skip + 1)
1388                 fatal("userauth_pubkey: internal error");
1389         buffer_consume(&b, skip + 1);
1390
1391         /* put remaining data from buffer into packet */
1392         packet_start(SSH2_MSG_USERAUTH_REQUEST);
1393         packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1394         buffer_free(&b);
1395         packet_send();
1396
1397         return 1;
1398 }
1399
1400 static int
1401 send_pubkey_test(Authctxt *authctxt, Identity *id)
1402 {
1403         u_char *blob;
1404         u_int bloblen, have_sig = 0;
1405
1406         debug3("send_pubkey_test");
1407
1408         if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1409                 /* we cannot handle this key */
1410                 debug3("send_pubkey_test: cannot handle key");
1411                 return 0;
1412         }
1413         /* register callback for USERAUTH_PK_OK message */
1414         dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1415
1416         packet_start(SSH2_MSG_USERAUTH_REQUEST);
1417         packet_put_cstring(authctxt->server_user);
1418         packet_put_cstring(authctxt->service);
1419         packet_put_cstring(authctxt->method->name);
1420         packet_put_char(have_sig);
1421         if (!(datafellows & SSH_BUG_PKAUTH))
1422                 packet_put_cstring(key_ssh_name(id->key));
1423         packet_put_string(blob, bloblen);
1424         xfree(blob);
1425         packet_send();
1426         return 1;
1427 }
1428
1429 static Key *
1430 load_identity_file(char *filename)
1431 {
1432         Key *private;
1433         char prompt[300], *passphrase;
1434         int perm_ok = 0, quit, i;
1435         struct stat st;
1436
1437         if (stat(filename, &st) < 0) {
1438                 debug3("no such identity: %s", filename);
1439                 return NULL;
1440         }
1441         private = key_load_private_type(KEY_UNSPEC, filename, "", NULL, &perm_ok);
1442         if (!perm_ok)
1443                 return NULL;
1444         if (private == NULL) {
1445                 if (options.batch_mode)
1446                         return NULL;
1447                 snprintf(prompt, sizeof prompt,
1448                     "Enter passphrase for key '%.100s': ", filename);
1449                 for (i = 0; i < options.number_of_password_prompts; i++) {
1450                         passphrase = read_passphrase(prompt, 0);
1451                         if (strcmp(passphrase, "") != 0) {
1452                                 private = key_load_private_type(KEY_UNSPEC,
1453                                     filename, passphrase, NULL, NULL);
1454                                 quit = 0;
1455                         } else {
1456                                 debug2("no passphrase given, try next key");
1457                                 quit = 1;
1458                         }
1459                         memset(passphrase, 0, strlen(passphrase));
1460                         xfree(passphrase);
1461                         if (private != NULL || quit)
1462                                 break;
1463                         debug2("bad passphrase given, try again...");
1464                 }
1465         }
1466         return private;
1467 }
1468
1469 /*
1470  * try keys in the following order:
1471  *      1. agent keys that are found in the config file
1472  *      2. other agent keys
1473  *      3. keys that are only listed in the config file
1474  */
1475 static void
1476 pubkey_prepare(Authctxt *authctxt)
1477 {
1478         Identity *id;
1479         Idlist agent, files, *preferred;
1480         Key *key;
1481         AuthenticationConnection *ac;
1482         char *comment;
1483         int i, found;
1484
1485         TAILQ_INIT(&agent);     /* keys from the agent */
1486         TAILQ_INIT(&files);     /* keys from the config file */
1487         preferred = &authctxt->keys;
1488         TAILQ_INIT(preferred);  /* preferred order of keys */
1489
1490         /* list of keys stored in the filesystem */
1491         for (i = 0; i < options.num_identity_files; i++) {
1492                 key = options.identity_keys[i];
1493                 if (key && key->type == KEY_RSA1)
1494                         continue;
1495                 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1496                         continue;
1497                 options.identity_keys[i] = NULL;
1498                 id = xcalloc(1, sizeof(*id));
1499                 id->key = key;
1500                 id->filename = xstrdup(options.identity_files[i]);
1501                 TAILQ_INSERT_TAIL(&files, id, next);
1502         }
1503         /* list of keys supported by the agent */
1504         if ((ac = ssh_get_authentication_connection())) {
1505                 for (key = ssh_get_first_identity(ac, &comment, 2);
1506                     key != NULL;
1507                     key = ssh_get_next_identity(ac, &comment, 2)) {
1508                         found = 0;
1509                         TAILQ_FOREACH(id, &files, next) {
1510                                 /* agent keys from the config file are preferred */
1511                                 if (key_equal(key, id->key)) {
1512                                         key_free(key);
1513                                         xfree(comment);
1514                                         TAILQ_REMOVE(&files, id, next);
1515                                         TAILQ_INSERT_TAIL(preferred, id, next);
1516                                         id->ac = ac;
1517                                         found = 1;
1518                                         break;
1519                                 }
1520                         }
1521                         if (!found && !options.identities_only) {
1522                                 id = xcalloc(1, sizeof(*id));
1523                                 id->key = key;
1524                                 id->filename = comment;
1525                                 id->ac = ac;
1526                                 TAILQ_INSERT_TAIL(&agent, id, next);
1527                         }
1528                 }
1529                 /* append remaining agent keys */
1530                 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1531                         TAILQ_REMOVE(&agent, id, next);
1532                         TAILQ_INSERT_TAIL(preferred, id, next);
1533                 }
1534                 authctxt->agent = ac;
1535         }
1536         /* append remaining keys from the config file */
1537         for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1538                 TAILQ_REMOVE(&files, id, next);
1539                 TAILQ_INSERT_TAIL(preferred, id, next);
1540         }
1541         TAILQ_FOREACH(id, preferred, next) {
1542                 debug2("key: %s (%p)", id->filename, id->key);
1543         }
1544 }
1545
1546 static void
1547 pubkey_cleanup(Authctxt *authctxt)
1548 {
1549         Identity *id;
1550
1551         if (authctxt->agent != NULL)
1552                 ssh_close_authentication_connection(authctxt->agent);
1553         for (id = TAILQ_FIRST(&authctxt->keys); id;
1554             id = TAILQ_FIRST(&authctxt->keys)) {
1555                 TAILQ_REMOVE(&authctxt->keys, id, next);
1556                 if (id->key)
1557                         key_free(id->key);
1558                 if (id->filename)
1559                         xfree(id->filename);
1560                 xfree(id);
1561         }
1562 }
1563
1564 int
1565 userauth_pubkey(Authctxt *authctxt)
1566 {
1567         Identity *id;
1568         int sent = 0;
1569
1570         while ((id = TAILQ_FIRST(&authctxt->keys))) {
1571                 if (id->tried++)
1572                         return (0);
1573                 /* move key to the end of the queue */
1574                 TAILQ_REMOVE(&authctxt->keys, id, next);
1575                 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1576                 /*
1577                  * send a test message if we have the public key. for
1578                  * encrypted keys we cannot do this and have to load the
1579                  * private key instead
1580                  */
1581                 if (id->key && id->key->type != KEY_RSA1) {
1582                         debug("Offering %s public key: %s", key_type(id->key),
1583                             id->filename);
1584                         sent = send_pubkey_test(authctxt, id);
1585                 } else if (id->key == NULL) {
1586                         debug("Trying private key: %s", id->filename);
1587                         id->key = load_identity_file(id->filename);
1588                         if (id->key != NULL) {
1589                                 id->isprivate = 1;
1590                                 sent = sign_and_send_pubkey(authctxt, id);
1591                                 key_free(id->key);
1592                                 id->key = NULL;
1593                         }
1594                 }
1595                 if (sent)
1596                         return (sent);
1597         }
1598         return (0);
1599 }
1600
1601 /*
1602  * Send userauth request message specifying keyboard-interactive method.
1603  */
1604 int
1605 userauth_kbdint(Authctxt *authctxt)
1606 {
1607         static int attempt = 0;
1608
1609         if (attempt++ >= options.number_of_password_prompts)
1610                 return 0;
1611         /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1612         if (attempt > 1 && !authctxt->info_req_seen) {
1613                 debug3("userauth_kbdint: disable: no info_req_seen");
1614                 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1615                 return 0;
1616         }
1617
1618         debug2("userauth_kbdint");
1619         packet_start(SSH2_MSG_USERAUTH_REQUEST);
1620         packet_put_cstring(authctxt->server_user);
1621         packet_put_cstring(authctxt->service);
1622         packet_put_cstring(authctxt->method->name);
1623         packet_put_cstring("");                                 /* lang */
1624         packet_put_cstring(options.kbd_interactive_devices ?
1625             options.kbd_interactive_devices : "");
1626         packet_send();
1627
1628         dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1629         return 1;
1630 }
1631
1632 /*
1633  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1634  */
1635 void
1636 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1637 {
1638         Authctxt *authctxt = ctxt;
1639         char *name, *inst, *lang, *prompt, *response;
1640         u_int num_prompts, i;
1641         int echo = 0;
1642
1643         debug2("input_userauth_info_req");
1644
1645         if (authctxt == NULL)
1646                 fatal("input_userauth_info_req: no authentication context");
1647
1648         authctxt->info_req_seen = 1;
1649
1650         name = packet_get_string(NULL);
1651         inst = packet_get_string(NULL);
1652         lang = packet_get_string(NULL);
1653         if (strlen(name) > 0)
1654                 logit("%s", name);
1655         if (strlen(inst) > 0)
1656                 logit("%s", inst);
1657         xfree(name);
1658         xfree(inst);
1659         xfree(lang);
1660
1661         num_prompts = packet_get_int();
1662         /*
1663          * Begin to build info response packet based on prompts requested.
1664          * We commit to providing the correct number of responses, so if
1665          * further on we run into a problem that prevents this, we have to
1666          * be sure and clean this up and send a correct error response.
1667          */
1668         packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1669         packet_put_int(num_prompts);
1670
1671         debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1672         for (i = 0; i < num_prompts; i++) {
1673                 prompt = packet_get_string(NULL);
1674                 echo = packet_get_char();
1675
1676                 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1677
1678                 packet_put_cstring(response);
1679                 memset(response, 0, strlen(response));
1680                 xfree(response);
1681                 xfree(prompt);
1682         }
1683         packet_check_eom(); /* done with parsing incoming message. */
1684
1685         packet_add_padding(64);
1686         packet_send();
1687 }
1688
1689 static int
1690 ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
1691     u_char *data, u_int datalen)
1692 {
1693         Buffer b;
1694         struct stat st;
1695         pid_t pid;
1696         int to[2], from[2], status, version = 2;
1697
1698         debug2("ssh_keysign called");
1699
1700         if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1701                 error("ssh_keysign: not installed: %s", strerror(errno));
1702                 return -1;
1703         }
1704         if (fflush(stdout) != 0)
1705                 error("ssh_keysign: fflush: %s", strerror(errno));
1706         if (pipe(to) < 0) {
1707                 error("ssh_keysign: pipe: %s", strerror(errno));
1708                 return -1;
1709         }
1710         if (pipe(from) < 0) {
1711                 error("ssh_keysign: pipe: %s", strerror(errno));
1712                 return -1;
1713         }
1714         if ((pid = fork()) < 0) {
1715                 error("ssh_keysign: fork: %s", strerror(errno));
1716                 return -1;
1717         }
1718         if (pid == 0) {
1719                 /* keep the socket on exec */
1720                 fcntl(packet_get_connection_in(), F_SETFD, 0);
1721                 permanently_drop_suid(getuid());
1722                 close(from[0]);
1723                 if (dup2(from[1], STDOUT_FILENO) < 0)
1724                         fatal("ssh_keysign: dup2: %s", strerror(errno));
1725                 close(to[1]);
1726                 if (dup2(to[0], STDIN_FILENO) < 0)
1727                         fatal("ssh_keysign: dup2: %s", strerror(errno));
1728                 close(from[1]);
1729                 close(to[0]);
1730                 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
1731                 fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
1732                     strerror(errno));
1733         }
1734         close(from[1]);
1735         close(to[0]);
1736
1737         buffer_init(&b);
1738         buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
1739         buffer_put_string(&b, data, datalen);
1740         if (ssh_msg_send(to[1], version, &b) == -1)
1741                 fatal("ssh_keysign: couldn't send request");
1742
1743         if (ssh_msg_recv(from[0], &b) < 0) {
1744                 error("ssh_keysign: no reply");
1745                 buffer_free(&b);
1746                 return -1;
1747         }
1748         close(from[0]);
1749         close(to[1]);
1750
1751         while (waitpid(pid, &status, 0) < 0)
1752                 if (errno != EINTR)
1753                         break;
1754
1755         if (buffer_get_char(&b) != version) {
1756                 error("ssh_keysign: bad version");
1757                 buffer_free(&b);
1758                 return -1;
1759         }
1760         *sigp = buffer_get_string(&b, lenp);
1761         buffer_free(&b);
1762
1763         return 0;
1764 }
1765
1766 int
1767 userauth_hostbased(Authctxt *authctxt)
1768 {
1769         Key *private = NULL;
1770         Sensitive *sensitive = authctxt->sensitive;
1771         Buffer b;
1772         u_char *signature, *blob;
1773         char *chost, *pkalg, *p;
1774         const char *service;
1775         u_int blen, slen;
1776         int ok, i, found = 0;
1777
1778         /* check for a useful key */
1779         for (i = 0; i < sensitive->nkeys; i++) {
1780                 private = sensitive->keys[i];
1781                 if (private && private->type != KEY_RSA1) {
1782                         found = 1;
1783                         /* we take and free the key */
1784                         sensitive->keys[i] = NULL;
1785                         break;
1786                 }
1787         }
1788         if (!found) {
1789                 debug("No more client hostkeys for hostbased authentication.");
1790                 return 0;
1791         }
1792         if (key_to_blob(private, &blob, &blen) == 0) {
1793                 key_free(private);
1794                 return 0;
1795         }
1796         /* figure out a name for the client host */
1797         p = get_local_name(packet_get_connection_in());
1798         if (p == NULL) {
1799                 error("userauth_hostbased: cannot get local ipaddr/name");
1800                 key_free(private);
1801                 xfree(blob);
1802                 return 0;
1803         }
1804         xasprintf(&chost, "%s.", p);
1805         debug2("userauth_hostbased: chost %s", chost);
1806         xfree(p);
1807
1808         service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1809             authctxt->service;
1810         pkalg = xstrdup(key_ssh_name(private));
1811         buffer_init(&b);
1812         /* construct data */
1813         buffer_put_string(&b, session_id2, session_id2_len);
1814         buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1815         buffer_put_cstring(&b, authctxt->server_user);
1816         buffer_put_cstring(&b, service);
1817         buffer_put_cstring(&b, authctxt->method->name);
1818         buffer_put_cstring(&b, pkalg);
1819         buffer_put_string(&b, blob, blen);
1820         buffer_put_cstring(&b, chost);
1821         buffer_put_cstring(&b, authctxt->local_user);
1822 #ifdef DEBUG_PK
1823         buffer_dump(&b);
1824 #endif
1825         if (sensitive->external_keysign)
1826                 ok = ssh_keysign(private, &signature, &slen,
1827                     buffer_ptr(&b), buffer_len(&b));
1828         else
1829                 ok = key_sign(private, &signature, &slen,
1830                     buffer_ptr(&b), buffer_len(&b));
1831         key_free(private);
1832         buffer_free(&b);
1833         if (ok != 0) {
1834                 error("key_sign failed");
1835                 xfree(chost);
1836                 xfree(pkalg);
1837                 xfree(blob);
1838                 return 0;
1839         }
1840         packet_start(SSH2_MSG_USERAUTH_REQUEST);
1841         packet_put_cstring(authctxt->server_user);
1842         packet_put_cstring(authctxt->service);
1843         packet_put_cstring(authctxt->method->name);
1844         packet_put_cstring(pkalg);
1845         packet_put_string(blob, blen);
1846         packet_put_cstring(chost);
1847         packet_put_cstring(authctxt->local_user);
1848         packet_put_string(signature, slen);
1849         memset(signature, 's', slen);
1850         xfree(signature);
1851         xfree(chost);
1852         xfree(pkalg);
1853         xfree(blob);
1854
1855         packet_send();
1856         return 1;
1857 }
1858
1859 #ifdef JPAKE
1860 int
1861 userauth_jpake(Authctxt *authctxt)
1862 {
1863         struct jpake_ctx *pctx;
1864         u_char *x1_proof, *x2_proof;
1865         u_int x1_proof_len, x2_proof_len;
1866         static int attempt = 0; /* XXX share with userauth_password's? */
1867
1868         if (attempt++ >= options.number_of_password_prompts)
1869                 return 0;
1870         if (attempt != 1)
1871                 error("Permission denied, please try again.");
1872
1873         if (authctxt->methoddata != NULL)
1874                 fatal("%s: authctxt->methoddata already set (%p)",
1875                     __func__, authctxt->methoddata);
1876
1877         authctxt->methoddata = pctx = jpake_new();
1878
1879         /*
1880          * Send request immediately, to get the protocol going while
1881          * we do the initial computations.
1882          */
1883         packet_start(SSH2_MSG_USERAUTH_REQUEST);
1884         packet_put_cstring(authctxt->server_user);
1885         packet_put_cstring(authctxt->service);
1886         packet_put_cstring(authctxt->method->name);
1887         packet_send();
1888         packet_write_wait();
1889
1890         jpake_step1(pctx->grp,
1891             &pctx->client_id, &pctx->client_id_len,
1892             &pctx->x1, &pctx->x2, &pctx->g_x1, &pctx->g_x2,
1893             &x1_proof, &x1_proof_len,
1894             &x2_proof, &x2_proof_len);
1895
1896         JPAKE_DEBUG_CTX((pctx, "step 1 sending in %s", __func__));
1897
1898         packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_STEP1);
1899         packet_put_string(pctx->client_id, pctx->client_id_len);
1900         packet_put_bignum2(pctx->g_x1);
1901         packet_put_bignum2(pctx->g_x2);
1902         packet_put_string(x1_proof, x1_proof_len);
1903         packet_put_string(x2_proof, x2_proof_len);
1904         packet_send();
1905
1906         bzero(x1_proof, x1_proof_len);
1907         bzero(x2_proof, x2_proof_len);
1908         xfree(x1_proof);
1909         xfree(x2_proof);
1910
1911         /* Expect step 1 packet from peer */
1912         dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP1,
1913             input_userauth_jpake_server_step1);
1914         dispatch_set(SSH2_MSG_USERAUTH_SUCCESS,
1915             &input_userauth_success_unexpected);
1916
1917         return 1;
1918 }
1919
1920 void
1921 userauth_jpake_cleanup(Authctxt *authctxt)
1922 {
1923         debug3("%s: clean up", __func__);
1924         if (authctxt->methoddata != NULL) {
1925                 jpake_free(authctxt->methoddata);
1926                 authctxt->methoddata = NULL;
1927         }
1928         dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
1929 }
1930 #endif /* JPAKE */
1931
1932 /* find auth method */
1933
1934 /*
1935  * given auth method name, if configurable options permit this method fill
1936  * in auth_ident field and return true, otherwise return false.
1937  */
1938 static int
1939 authmethod_is_enabled(Authmethod *method)
1940 {
1941         if (method == NULL)
1942                 return 0;
1943         /* return false if options indicate this method is disabled */
1944         if  (method->enabled == NULL || *method->enabled == 0)
1945                 return 0;
1946         /* return false if batch mode is enabled but method needs interactive mode */
1947         if  (method->batch_flag != NULL && *method->batch_flag != 0)
1948                 return 0;
1949         return 1;
1950 }
1951
1952 static Authmethod *
1953 authmethod_lookup(const char *name)
1954 {
1955         Authmethod *method = NULL;
1956         if (name != NULL)
1957                 for (method = authmethods; method->name != NULL; method++)
1958                         if (strcmp(name, method->name) == 0)
1959                                 return method;
1960         debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1961         return NULL;
1962 }
1963
1964 /* XXX internal state */
1965 static Authmethod *current = NULL;
1966 static char *supported = NULL;
1967 static char *preferred = NULL;
1968
1969 /*
1970  * Given the authentication method list sent by the server, return the
1971  * next method we should try.  If the server initially sends a nil list,
1972  * use a built-in default list.
1973  */
1974 static Authmethod *
1975 authmethod_get(char *authlist)
1976 {
1977         char *name = NULL;
1978         u_int next;
1979
1980         /* Use a suitable default if we're passed a nil list.  */
1981         if (authlist == NULL || strlen(authlist) == 0)
1982                 authlist = options.preferred_authentications;
1983
1984         if (supported == NULL || strcmp(authlist, supported) != 0) {
1985                 debug3("start over, passed a different list %s", authlist);
1986                 if (supported != NULL)
1987                         xfree(supported);
1988                 supported = xstrdup(authlist);
1989                 preferred = options.preferred_authentications;
1990                 debug3("preferred %s", preferred);
1991                 current = NULL;
1992         } else if (current != NULL && authmethod_is_enabled(current))
1993                 return current;
1994
1995         for (;;) {
1996                 if ((name = match_list(preferred, supported, &next)) == NULL) {
1997                         debug("No more authentication methods to try.");
1998                         current = NULL;
1999                         return NULL;
2000                 }
2001                 preferred += next;
2002                 debug3("authmethod_lookup %s", name);
2003                 debug3("remaining preferred: %s", preferred);
2004                 if ((current = authmethod_lookup(name)) != NULL &&
2005                     authmethod_is_enabled(current)) {
2006                         debug3("authmethod_is_enabled %s", name);
2007                         debug("Next authentication method: %s", name);
2008                         xfree(name);
2009                         return current;
2010                 }
2011         }
2012         if (name != NULL)
2013                 xfree(name);
2014 }
2015
2016 static char *
2017 authmethods_get(void)
2018 {
2019         Authmethod *method = NULL;
2020         Buffer b;
2021         char *list;
2022
2023         buffer_init(&b);
2024         for (method = authmethods; method->name != NULL; method++) {
2025                 if (authmethod_is_enabled(method)) {
2026                         if (buffer_len(&b) > 0)
2027                                 buffer_append(&b, ",", 1);
2028                         buffer_append(&b, method->name, strlen(method->name));
2029                 }
2030         }
2031         buffer_append(&b, "\0", 1);
2032         list = xstrdup(buffer_ptr(&b));
2033         buffer_free(&b);
2034         return list;
2035 }
2036