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