source: protocols/jabber/sasl.c @ 83f179d6

Last change on this file since 83f179d6 was 91dd19c, checked in by dequis <dx@…>, at 2015-07-30T03:20:30Z

Only try DIGEST-MD5 if there's no SSL/TLS or if PLAIN isn't supported

Which in practice means "don't bother with DIGEST-MD5 most of the time".

It's weak, pointless over TLS, and often breaks with some servers
(hi openfire)

  • Property mode set to 100644
File size: 16.2 KB
Line 
1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Jabber module - SASL authentication                                      *
5*                                                                           *
6*  Copyright 2006-2012 Wilmer van der Gaast <wilmer@gaast.net>              *
7*                                                                           *
8*  This program is free software; you can redistribute it and/or modify     *
9*  it under the terms of the GNU General Public License as published by     *
10*  the Free Software Foundation; either version 2 of the License, or        *
11*  (at your option) any later version.                                      *
12*                                                                           *
13*  This program is distributed in the hope that it will be useful,          *
14*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
15*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
16*  GNU General Public License for more details.                             *
17*                                                                           *
18*  You should have received a copy of the GNU General Public License along  *
19*  with this program; if not, write to the Free Software Foundation, Inc.,  *
20*  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              *
21*                                                                           *
22\***************************************************************************/
23
24#include <ctype.h>
25
26#include "jabber.h"
27#include "base64.h"
28#include "oauth2.h"
29#include "oauth.h"
30
31const struct oauth2_service oauth2_service_google =
32{
33        "https://accounts.google.com/o/oauth2/auth",
34        "https://accounts.google.com/o/oauth2/token",
35        "urn:ietf:wg:oauth:2.0:oob",
36        "https://www.googleapis.com/auth/googletalk",
37        "783993391592.apps.googleusercontent.com",
38        "6C-Zgf7Tr7gEQTPlBhMUgo7R",
39};
40const struct oauth2_service oauth2_service_facebook =
41{
42        "https://www.facebook.com/dialog/oauth",
43        "https://graph.facebook.com/oauth/access_token",
44        "https://www.bitlbee.org/main.php/Facebook/oauth2.html",
45        "offline_access,xmpp_login",
46        "126828914005625",
47        "4b100f0f244d620bf3f15f8b217d4c32",
48};
49
50xt_status sasl_pkt_mechanisms(struct xt_node *node, gpointer data)
51{
52        struct im_connection *ic = data;
53        struct jabber_data *jd = ic->proto_data;
54        struct xt_node *c, *reply;
55        char *s;
56        int sup_plain = 0, sup_digest = 0, sup_gtalk = 0, sup_fb = 0, sup_anonymous = 0;
57        int want_oauth = FALSE, want_hipchat = FALSE, want_anonymous = FALSE;
58        GString *mechs;
59
60        if (!sasl_supported(ic)) {
61                /* Should abort this now, since we should already be doing
62                   IQ authentication. Strange things happen when you try
63                   to do both... */
64                imcb_log(ic,
65                         "XMPP 1.0 non-compliant server seems to support SASL, please report this as a BitlBee bug!");
66                return XT_HANDLED;
67        }
68
69        s = xt_find_attr(node, "xmlns");
70        if (!s || strcmp(s, XMLNS_SASL) != 0) {
71                imcb_log(ic, "Stream error while authenticating");
72                imc_logout(ic, FALSE);
73                return XT_ABORT;
74        }
75
76        want_anonymous = set_getbool(&ic->acc->set, "anonymous");
77        want_oauth = set_getbool(&ic->acc->set, "oauth");
78        want_hipchat = (jd->flags & JFLAG_HIPCHAT);
79
80        mechs = g_string_new("");
81        c = node->children;
82        while ((c = xt_find_node(c, "mechanism"))) {
83                if (c->text && g_strcasecmp(c->text, "PLAIN") == 0) {
84                        sup_plain = 1;
85                } else if (c->text && g_strcasecmp(c->text, "DIGEST-MD5") == 0) {
86                        sup_digest = 1;
87                } else if (c->text && g_strcasecmp(c->text, "ANONYMOUS") == 0) {
88                        sup_anonymous = 1;
89                } else if (c->text && g_strcasecmp(c->text, "X-OAUTH2") == 0) {
90                        sup_gtalk = 1;
91                } else if (c->text && g_strcasecmp(c->text, "X-FACEBOOK-PLATFORM") == 0) {
92                        sup_fb = 1;
93                }
94
95                if (c->text) {
96                        g_string_append_printf(mechs, " %s", c->text);
97                }
98
99                c = c->next;
100        }
101
102        if (!want_oauth && !sup_plain && !sup_digest) {
103                if (!sup_gtalk && !sup_fb) {
104                        imcb_error(ic, "This server requires OAuth "
105                                   "(supported schemes:%s)", mechs->str);
106                } else {
107                        imcb_error(ic, "BitlBee does not support any of the offered SASL "
108                                   "authentication schemes:%s", mechs->str);
109                }
110                imc_logout(ic, FALSE);
111                g_string_free(mechs, TRUE);
112                return XT_ABORT;
113        }
114        g_string_free(mechs, TRUE);
115
116        reply = xt_new_node("auth", NULL, NULL);
117        if (!want_hipchat) {
118                xt_add_attr(reply, "xmlns", XMLNS_SASL);
119        } else {
120                xt_add_attr(reply, "xmlns", XMLNS_HIPCHAT);
121        }
122
123        if (sup_gtalk && want_oauth) {
124                int len;
125
126                /* X-OAUTH2 is, not *the* standard OAuth2 SASL/XMPP implementation.
127                   It's currently used by GTalk and vaguely documented on
128                   http://code.google.com/apis/cloudprint/docs/rawxmpp.html . */
129                xt_add_attr(reply, "mechanism", "X-OAUTH2");
130
131                len = strlen(jd->username) + strlen(jd->oauth2_access_token) + 2;
132                s = g_malloc(len + 1);
133                s[0] = 0;
134                strcpy(s + 1, jd->username);
135                strcpy(s + 2 + strlen(jd->username), jd->oauth2_access_token);
136                reply->text = base64_encode((unsigned char *) s, len);
137                reply->text_len = strlen(reply->text);
138                g_free(s);
139        } else if (sup_fb && want_oauth) {
140                xt_add_attr(reply, "mechanism", "X-FACEBOOK-PLATFORM");
141                jd->flags |= JFLAG_SASL_FB;
142        } else if (want_oauth) {
143                imcb_error(ic, "OAuth requested, but not supported by server");
144                imc_logout(ic, FALSE);
145                xt_free_node(reply);
146                return XT_ABORT;
147        } else if (want_anonymous && sup_anonymous) {
148                xt_add_attr(reply, "mechanism", "ANONYMOUS");
149
150                /* Well, that was easy. */
151        } else if (want_anonymous) {
152                imcb_error(ic, "Anonymous login requested, but not supported by server");
153                imc_logout(ic, FALSE);
154                xt_free_node(reply);
155                return XT_ABORT;
156        } else if (sup_digest && !(jd->ssl && sup_plain)) {
157                /* Only try DIGEST-MD5 if there's no SSL/TLS or if PLAIN isn't supported.
158                 * Which in practice means "don't bother with DIGEST-MD5 most of the time".
159                 * It's weak, pointless over TLS, and often breaks with some servers (hi openfire) */
160
161                xt_add_attr(reply, "mechanism", "DIGEST-MD5");
162
163                /* The rest will be done later, when we receive a <challenge/>. */
164        } else if (sup_plain) {
165                int len;
166                GString *gs;
167                char *username;
168
169                if (!want_hipchat) {
170                        xt_add_attr(reply, "mechanism", "PLAIN");
171                        username = jd->username;
172                } else {
173                        username = jd->me;
174                }
175
176                /* set an arbitrary initial size to avoid reallocations */
177                gs = g_string_sized_new(128);
178
179                /* With SASL PLAIN in XMPP, the text should be b64(\0user\0pass) */
180                g_string_append_c(gs, '\0');
181                g_string_append(gs, username);
182                g_string_append_c(gs, '\0');
183                g_string_append(gs, ic->acc->pass);
184                if (want_hipchat) {
185                        /* Hipchat's variation adds \0resource at the end */
186                        g_string_append_c(gs, '\0');
187                        g_string_append(gs, set_getstr(&ic->acc->set, "resource"));
188                }
189
190                len = gs->len;
191                s = g_string_free(gs, FALSE);
192
193                reply->text = base64_encode((unsigned char *) s, len);
194                reply->text_len = strlen(reply->text);
195                g_free(s);
196        }
197
198        if (reply && !jabber_write_packet(ic, reply)) {
199                xt_free_node(reply);
200                return XT_ABORT;
201        }
202        xt_free_node(reply);
203
204        /* To prevent classic authentication from happening. */
205        jd->flags |= JFLAG_STREAM_STARTED;
206
207        return XT_HANDLED;
208}
209
210/* Non-static function, but not mentioned in jabber.h because it's for internal
211   use, just that the unittest should be able to reach it... */
212char *sasl_get_part(char *data, char *field)
213{
214        int i, len;
215
216        len = strlen(field);
217
218        while (g_ascii_isspace(*data) || *data == ',') {
219                data++;
220        }
221
222        if (g_strncasecmp(data, field, len) == 0 && data[len] == '=') {
223                i = strlen(field) + 1;
224        } else {
225                for (i = 0; data[i]; i++) {
226                        /* If we have a ", skip until it's closed again. */
227                        if (data[i] == '"') {
228                                i++;
229                                while (data[i] != '"' || data[i - 1] == '\\') {
230                                        i++;
231                                }
232                        }
233
234                        /* If we got a comma, we got a new field. Check it,
235                           find the next key after it. */
236                        if (data[i] == ',') {
237                                while (g_ascii_isspace(data[i]) || data[i] == ',') {
238                                        i++;
239                                }
240
241                                if (g_strncasecmp(data + i, field, len) == 0 &&
242                                    data[i + len] == '=') {
243                                        i += len + 1;
244                                        break;
245                                }
246                        }
247                }
248        }
249
250        if (data[i] == '"') {
251                int j;
252                char *ret;
253
254                i++;
255                len = 0;
256                while (data[i + len] != '"' || data[i + len - 1] == '\\') {
257                        len++;
258                }
259
260                ret = g_strndup(data + i, len);
261                for (i = j = 0; ret[i]; i++) {
262                        if (ret[i] == '\\') {
263                                ret[j++] = ret[++i];
264                        } else {
265                                ret[j++] = ret[i];
266                        }
267                }
268                ret[j] = 0;
269
270                return ret;
271        } else if (data[i]) {
272                len = 0;
273                while (data[i + len] && data[i + len] != ',') {
274                        len++;
275                }
276
277                return g_strndup(data + i, len);
278        } else {
279                return NULL;
280        }
281}
282
283xt_status sasl_pkt_challenge(struct xt_node *node, gpointer data)
284{
285        struct im_connection *ic = data;
286        struct jabber_data *jd = ic->proto_data;
287        struct xt_node *reply_pkt = NULL;
288        char *nonce = NULL, *realm = NULL, *cnonce = NULL;
289        unsigned char cnonce_bin[30];
290        char *digest_uri = NULL;
291        char *dec = NULL;
292        char *s = NULL, *reply = NULL;
293        xt_status ret = XT_ABORT;
294
295        if (node->text_len == 0) {
296                goto error;
297        }
298
299        dec = frombase64(node->text);
300
301        if (jd->flags & JFLAG_SASL_FB) {
302                /* New-style Facebook OAauth2 support. Instead of sending a refresh
303                   token, they just send an access token that should never expire. */
304                GSList *p_in = NULL, *p_out = NULL;
305                char time[33];
306
307                oauth_params_parse(&p_in, dec);
308                oauth_params_add(&p_out, "nonce", oauth_params_get(&p_in, "nonce"));
309                oauth_params_add(&p_out, "method", oauth_params_get(&p_in, "method"));
310                oauth_params_free(&p_in);
311
312                g_snprintf(time, sizeof(time), "%lld", (long long) (gettime() * 1000));
313                oauth_params_add(&p_out, "call_id", time);
314                oauth_params_add(&p_out, "api_key", oauth2_service_facebook.consumer_key);
315                oauth_params_add(&p_out, "v", "1.0");
316                oauth_params_add(&p_out, "format", "XML");
317                oauth_params_add(&p_out, "access_token", jd->oauth2_access_token);
318
319                reply = oauth_params_string(p_out);
320                oauth_params_free(&p_out);
321        } else if (!(s = sasl_get_part(dec, "rspauth"))) {
322                /* See RFC 2831 for for information. */
323                md5_state_t A1, A2, H;
324                md5_byte_t A1r[16], A2r[16], Hr[16];
325                char A1h[33], A2h[33], Hh[33];
326                int i;
327
328                nonce = sasl_get_part(dec, "nonce");
329                realm = sasl_get_part(dec, "realm");
330
331                if (!nonce) {
332                        goto error;
333                }
334
335                /* Jabber.Org considers the realm part optional and doesn't
336                   specify one. Oh well, actually they're right, but still,
337                   don't know if this is right... */
338                if (!realm) {
339                        realm = g_strdup(jd->server);
340                }
341
342                random_bytes(cnonce_bin, sizeof(cnonce_bin));
343                cnonce = base64_encode(cnonce_bin, sizeof(cnonce_bin));
344                digest_uri = g_strdup_printf("%s/%s", "xmpp", jd->server);
345
346                /* Generate the MD5 hash of username:realm:password,
347                   I decided to call it H. */
348                md5_init(&H);
349                s = g_strdup_printf("%s:%s:%s", jd->username, realm, ic->acc->pass);
350                md5_append(&H, (unsigned char *) s, strlen(s));
351                g_free(s);
352                md5_finish(&H, Hr);
353
354                /* Now generate the hex. MD5 hash of H:nonce:cnonce, called A1. */
355                md5_init(&A1);
356                s = g_strdup_printf(":%s:%s", nonce, cnonce);
357                md5_append(&A1, Hr, 16);
358                md5_append(&A1, (unsigned char *) s, strlen(s));
359                g_free(s);
360                md5_finish(&A1, A1r);
361                for (i = 0; i < 16; i++) {
362                        sprintf(A1h + i * 2, "%02x", A1r[i]);
363                }
364
365                /* A2... */
366                md5_init(&A2);
367                s = g_strdup_printf("%s:%s", "AUTHENTICATE", digest_uri);
368                md5_append(&A2, (unsigned char *) s, strlen(s));
369                g_free(s);
370                md5_finish(&A2, A2r);
371                for (i = 0; i < 16; i++) {
372                        sprintf(A2h + i * 2, "%02x", A2r[i]);
373                }
374
375                /* Final result: A1:nonce:00000001:cnonce:auth:A2. Let's reuse H for it. */
376                md5_init(&H);
377                s = g_strdup_printf("%s:%s:%s:%s:%s:%s", A1h, nonce, "00000001", cnonce, "auth", A2h);
378                md5_append(&H, (unsigned char *) s, strlen(s));
379                g_free(s);
380                md5_finish(&H, Hr);
381                for (i = 0; i < 16; i++) {
382                        sprintf(Hh + i * 2, "%02x", Hr[i]);
383                }
384
385                /* Now build the SASL response string: */
386                reply = g_strdup_printf("username=\"%s\",realm=\"%s\",nonce=\"%s\",cnonce=\"%s\","
387                                        "nc=%08x,qop=auth,digest-uri=\"%s\",response=%s,charset=%s",
388                                        jd->username, realm, nonce, cnonce, 1, digest_uri, Hh, "utf-8");
389        } else {
390                /* We found rspauth, but don't really care... */
391                g_free(s);
392        }
393
394        s = reply ? tobase64(reply) : NULL;
395        reply_pkt = xt_new_node("response", s, NULL);
396        xt_add_attr(reply_pkt, "xmlns", XMLNS_SASL);
397
398        if (!jabber_write_packet(ic, reply_pkt)) {
399                goto silent_error;
400        }
401
402        ret = XT_HANDLED;
403        goto silent_error;
404
405error:
406        imcb_error(ic, "Incorrect SASL challenge received");
407        imc_logout(ic, FALSE);
408
409silent_error:
410        g_free(digest_uri);
411        g_free(cnonce);
412        g_free(nonce);
413        g_free(reply);
414        g_free(realm);
415        g_free(dec);
416        g_free(s);
417        xt_free_node(reply_pkt);
418
419        return ret;
420}
421
422xt_status sasl_pkt_result(struct xt_node *node, gpointer data)
423{
424        struct im_connection *ic = data;
425        struct jabber_data *jd = ic->proto_data;
426        char *s;
427
428        s = xt_find_attr(node, "xmlns");
429        if (!s || strcmp(s, XMLNS_SASL) != 0) {
430                imcb_log(ic, "Stream error while authenticating");
431                imc_logout(ic, FALSE);
432                return XT_ABORT;
433        }
434
435        if (strcmp(node->name, "success") == 0) {
436                imcb_log(ic, "Authentication finished");
437                jd->flags |= JFLAG_AUTHENTICATED | JFLAG_STREAM_RESTART;
438
439                if (jd->flags & JFLAG_HIPCHAT) {
440                        return hipchat_handle_success(ic, node);
441                }
442        } else if (strcmp(node->name, "failure") == 0) {
443                imcb_error(ic, "Authentication failure");
444                imc_logout(ic, FALSE);
445                return XT_ABORT;
446        }
447
448        return XT_HANDLED;
449}
450
451/* This one is needed to judge if we'll do authentication using IQ or SASL.
452   It's done by checking if the <stream:stream> from the server has a
453   version attribute. I don't know if this is the right way though... */
454gboolean sasl_supported(struct im_connection *ic)
455{
456        struct jabber_data *jd = ic->proto_data;
457
458        return (jd->xt && jd->xt->root && xt_find_attr(jd->xt->root, "version")) != 0;
459}
460
461void sasl_oauth2_init(struct im_connection *ic)
462{
463        struct jabber_data *jd = ic->proto_data;
464        char *msg, *url;
465
466        imcb_log(ic, "Starting OAuth authentication");
467
468        /* Temporary contact, just used to receive the OAuth response. */
469        imcb_add_buddy(ic, JABBER_OAUTH_HANDLE, NULL);
470        url = oauth2_url(jd->oauth2_service);
471        msg = g_strdup_printf("Open this URL in your browser to authenticate: %s", url);
472        imcb_buddy_msg(ic, JABBER_OAUTH_HANDLE, msg, 0, 0);
473        imcb_buddy_msg(ic, JABBER_OAUTH_HANDLE, "Respond to this message with the returned "
474                       "authorization token.", 0, 0);
475
476        g_free(msg);
477        g_free(url);
478}
479
480static gboolean sasl_oauth2_remove_contact(gpointer data, gint fd, b_input_condition cond)
481{
482        struct im_connection *ic = data;
483
484        if (g_slist_find(jabber_connections, ic)) {
485                imcb_remove_buddy(ic, JABBER_OAUTH_HANDLE, NULL);
486        }
487        return FALSE;
488}
489
490static void sasl_oauth2_got_token(gpointer data, const char *access_token, const char *refresh_token,
491                                  const char *error);
492
493int sasl_oauth2_get_refresh_token(struct im_connection *ic, const char *msg)
494{
495        struct jabber_data *jd = ic->proto_data;
496        char *code;
497        int ret;
498
499        imcb_log(ic, "Requesting OAuth access token");
500
501        /* Don't do it here because the caller may get confused if the contact
502           we're currently sending a message to is deleted. */
503        b_timeout_add(1, sasl_oauth2_remove_contact, ic);
504
505        code = g_strdup(msg);
506        g_strstrip(code);
507        ret = oauth2_access_token(jd->oauth2_service, OAUTH2_AUTH_CODE,
508                                  code, sasl_oauth2_got_token, ic);
509
510        g_free(code);
511        return ret;
512}
513
514int sasl_oauth2_refresh(struct im_connection *ic, const char *refresh_token)
515{
516        struct jabber_data *jd = ic->proto_data;
517
518        return oauth2_access_token(jd->oauth2_service, OAUTH2_AUTH_REFRESH,
519                                   refresh_token, sasl_oauth2_got_token, ic);
520}
521
522static void sasl_oauth2_got_token(gpointer data, const char *access_token, const char *refresh_token, const char *error)
523{
524        struct im_connection *ic = data;
525        struct jabber_data *jd;
526        GSList *auth = NULL;
527
528        if (g_slist_find(jabber_connections, ic) == NULL) {
529                return;
530        }
531
532        jd = ic->proto_data;
533
534        if (access_token == NULL) {
535                imcb_error(ic, "OAuth failure (%s)", error);
536                imc_logout(ic, TRUE);
537                return;
538        }
539
540        oauth_params_parse(&auth, ic->acc->pass);
541        if (refresh_token) {
542                oauth_params_set(&auth, "refresh_token", refresh_token);
543        }
544        if (access_token) {
545                oauth_params_set(&auth, "access_token", access_token);
546        }
547
548        g_free(ic->acc->pass);
549        ic->acc->pass = oauth_params_string(auth);
550        oauth_params_free(&auth);
551
552        g_free(jd->oauth2_access_token);
553        jd->oauth2_access_token = g_strdup(access_token);
554
555        jabber_connect(ic);
556}
Note: See TracBrowser for help on using the repository browser.