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