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