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