source: protocols/jabber/sasl.c @ bb2d198

Last change on this file since bb2d198 was 644b808, checked in by Wilmer van der Gaast <wilmer@…>, at 2011-12-26T10:50:34Z

A few more minor cleanups before merging this into mainline.

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