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