aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arc.c
blob: fd4984548233c1de8f92a37ce062d8384cd56df4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/***************************************************************************\
*                                                                           *
*  BitlBee - An IRC to IM gateway                                           *
*  Simple (but secure) ArcFour implementation for safer password storage.   *
*                                                                           *
*  Copyright 2006 Wilmer van der Gaast <wilmer@gaast.net>                   *
*                                                                           *
*  This library is free software; you can redistribute it and/or            *
*  modify it under the terms of the GNU Lesser General Public               *
*  License as published by the Free Software Foundation, version            *
*  2.1.                                                                     *
*                                                                           *
*  This library is distributed in the hope that it will be useful,          *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
*  Lesser General Public License for more details.                          *
*                                                                           *
*  You should have received a copy of the GNU Lesser General Public License *
*  along with this library; if not, write to the Free Software Foundation,  *
*  Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA           *
*                                                                           *
\***************************************************************************/

/* 
   This file implements ArcFour-encryption, which will mainly be used to
   save IM passwords safely in the new XML-format. Possibly other uses will
   come up later. It's supposed to be quite reliable (thanks to the use of a
   6-byte IV/seed), certainly compared to the old format. The only realistic
   way to crack BitlBee passwords now is to use a sniffer to get your hands
   on the user's password.
   
   If you see that something's wrong in this implementation (I asked a
   couple of people to look at it already, but who knows), please tell me.
   
   The reason I picked ArcFour is because it's pretty simple but effective,
   so it will work without adding several KBs or an extra library dependency.
   
   (ArcFour is an RC4-compatible cipher. See for details:
   http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt)
*/


#include <glib.h>
#include <gmodule.h>
#include <stdlib.h>
#include <string.h>
#include "misc.h"
#include "arc.h"

/* Add some seed to the password, to make sure we *never* use the same key.
   This defines how many bytes we use as a seed. */
#define ARC_IV_LEN 6

/* To defend against a "Fluhrer, Mantin and Shamir attack", it is recommended
   to shuffle S[] just a bit more before you start to use it. This defines how
   many bytes we'll request before we'll really use them for encryption. */
#define ARC_CYCLES 1024

struct arc_state *arc_keymaker( unsigned char *key, int kl, int cycles )
{
	struct arc_state *st;
	int i, j, tmp;
	unsigned char S2[256];
	
	st = g_malloc( sizeof( struct arc_state ) );
	st->i = st->j = 0;
	if( kl <= 0 )
		kl = strlen( (char*) key );
	
	for( i = 0; i < 256; i ++ )
	{
		st->S[i] = i;
		S2[i] = key[i%kl];
	}
	
	for( i = j = 0; i < 256; i ++ )
	{
		j = ( j + st->S[i] + S2[i] ) & 0xff;
		tmp = st->S[i];
		st->S[i] = st->S[j];
		st->S[j] = tmp;
	}
	
	memset( S2, 0, 256 );
	i = j = 0;
	
	for( i = 0; i < cycles; i ++ )
		arc_getbyte( st );
	
	return st;
}

/*
   For those who don't know, ArcFour is basically an algorithm that generates
   a stream of bytes after you give it a key. Just get a byte from it and
   xor it with your cleartext. To decrypt, just give it the same key again
   and start xorring.
   
   The function above initializes the byte generator, the next function can
   be used to get bytes from the generator (and shuffle things a bit).
*/

unsigned char arc_getbyte( struct arc_state *st )
{
	unsigned char tmp;
	
	/* Unfortunately the st-> stuff doesn't really improve readability here... */
	st->i ++;
	st->j += st->S[st->i];
	tmp = st->S[st->i];
	st->S[st->i] = st->S[st->j];
	st->S[st->j] = tmp;
	tmp = (st->S[st->i] + st->S[st->j]) & 0xff;
	
	return st->S[tmp];
}

/*
   The following two functions can be used for reliable encryption and
   decryption. Known plaintext attacks are prevented by adding some (6,
   by default) random bytes to the password before setting up the state
   structures. These 6 bytes are also saved in the results, because of
   course we'll need them in arc_decode().
   
   Because the length of the resulting string is unknown to the caller,
   it should pass a char**. Since the encode/decode functions allocate
   memory for the string, make sure the char** points at a NULL-pointer
   (or at least to something you already free()d), or you'll leak
   memory. And of course, don't forget to free() the result when you
   don't need it anymore.
   
   Both functions return the number of bytes in the result string.
   
   Note that if you use the pad_to argument, you will need zero-termi-
   nation to find back the original string length after decryption. So
   it shouldn't be used if your string contains \0s by itself!
*/

int arc_encode( char *clear, int clear_len, unsigned char **crypt, char *password, int pad_to )
{
	struct arc_state *st;
	unsigned char *key;
	char *padded = NULL;
	int key_len, i, padded_len;
	
	key_len = strlen( password ) + ARC_IV_LEN;
	if( clear_len <= 0 )
		clear_len = strlen( clear );
	
	/* Pad the string to the closest multiple of pad_to. This makes it
	   impossible to see the exact length of the password. */
	if( pad_to > 0 && ( clear_len % pad_to ) > 0 )
	{
		padded_len = clear_len + pad_to - ( clear_len % pad_to );
		padded = g_malloc( padded_len );
		memcpy( padded, clear, clear_len );
		
		/* First a \0 and then random data, so we don't have to do
		   anything special when decrypting. */
		padded[clear_len] = 0;
		random_bytes( (unsigned char*) padded + clear_len + 1, padded_len - clear_len - 1 );
		
		clear = padded;
		clear_len = padded_len;
	}
	
	/* Prepare buffers and the key + IV */
	*crypt = g_malloc( clear_len + ARC_IV_LEN );
	key = g_malloc( key_len );
	strcpy( (char*) key, password );
	
	/* Add the salt. Save it for later (when decrypting) and, of course,
	   add it to the encryption key. */
	random_bytes( crypt[0], ARC_IV_LEN );
	memcpy( key + key_len - ARC_IV_LEN, crypt[0], ARC_IV_LEN );
	
	/* Generate the initial S[] from the IVed key. */
	st = arc_keymaker( key, key_len, ARC_CYCLES );
	g_free( key );
	
	for( i = 0; i < clear_len; i ++ )
		crypt[0][i+ARC_IV_LEN] = clear[i] ^ arc_getbyte( st );
	
	g_free( st );
	g_free( padded );
	
	return clear_len + ARC_IV_LEN;
}

int arc_decode( unsigned char *crypt, int crypt_len, char **clear, char *password )
{
	struct arc_state *st;
	unsigned char *key;
	int key_len, clear_len, i;
	
	key_len = strlen( password ) + ARC_IV_LEN;
	clear_len = crypt_len - ARC_IV_LEN;
	
	if( clear_len < 0 )
	{
		*clear = g_strdup( "" );
		return 0;
	}
	
	/* Prepare buffers and the key + IV */
	*clear = g_malloc( clear_len + 1 );
	key = g_malloc( key_len );
	strcpy( (char*) key, password );
	for( i = 0; i < ARC_IV_LEN; i ++ )
		key[key_len-ARC_IV_LEN+i] = crypt[i];
	
	/* Generate the initial S[] from the IVed key. */
	st = arc_keymaker( key, key_len, ARC_CYCLES );
	g_free( key );
	
	for( i = 0; i < clear_len; i ++ )
		clear[0][i] = crypt[i+ARC_IV_LEN] ^ arc_getbyte( st );
	clear[0][i] = 0; /* Nice to have for plaintexts. */
	
	g_free( st );
	
	return clear_len;
}
> = ssl_read( jd->ssl, buf, sizeof( buf ) ); else st = read( jd->fd, buf, sizeof( buf ) ); if( st > 0 ) { /* Parse. */ if( xt_feed( jd->xt, buf, st ) < 0 ) { imcb_error( ic, "XML stream error" ); imc_logout( ic, TRUE ); return FALSE; } /* Execute all handlers. */ if( !xt_handle( jd->xt, NULL, 1 ) ) { /* Don't do anything, the handlers should have aborted the connection already. */ return FALSE; } if( jd->flags & JFLAG_STREAM_RESTART ) { jd->flags &= ~JFLAG_STREAM_RESTART; jabber_start_stream( ic ); } /* Garbage collection. */ xt_cleanup( jd->xt, NULL, 1 ); /* This is a bit hackish, unfortunately. Although xmltree has nifty event handler stuff, it only calls handlers when nodes are complete. Since the server should only send an opening <stream:stream> tag, we have to check this by hand. :-( */ if( !( jd->flags & JFLAG_STREAM_STARTED ) && jd->xt && jd->xt->root ) { if( g_strcasecmp( jd->xt->root->name, "stream:stream" ) == 0 ) { jd->flags |= JFLAG_STREAM_STARTED; /* If there's no version attribute, assume this is an old server that can't do SASL authentication. */ if( !sasl_supported( ic ) ) { /* If there's no version= tag, we suppose this server does NOT implement: XMPP 1.0, SASL and TLS. */ if( set_getbool( &ic->acc->set, "tls" ) ) { imcb_error( ic, "TLS is turned on for this " "account, but is not supported by this server" ); imc_logout( ic, FALSE ); return FALSE; } else { return jabber_init_iq_auth( ic ); } } } else { imcb_error( ic, "XML stream error" ); imc_logout( ic, TRUE ); return FALSE; } } } else if( st == 0 || ( st < 0 && !ssl_sockerr_again( jd->ssl ) ) ) { closesocket( jd->fd ); jd->fd = -1; imcb_error( ic, "Error while reading from server" ); imc_logout( ic, TRUE ); return FALSE; } if( ssl_pending( jd->ssl ) ) /* OpenSSL empties the TCP buffers completely but may keep some data in its internap buffers. select() won't see that, but ssl_pending() does. */ return jabber_read_callback( data, fd, cond ); else return TRUE; } gboolean jabber_connected_plain( gpointer data, gint source, b_input_condition cond ) { struct im_connection *ic = data; if( g_slist_find( jabber_connections, ic ) == NULL ) return FALSE; if( source == -1 ) { imcb_error( ic, "Could not connect to server" ); imc_logout( ic, TRUE ); return FALSE; } imcb_log( ic, "Connected to server, logging in" ); return jabber_start_stream( ic ); } gboolean jabber_connected_ssl( gpointer data, void *source, b_input_condition cond ) { struct im_connection *ic = data; struct jabber_data *jd; if( g_slist_find( jabber_connections, ic ) == NULL ) return FALSE; jd = ic->proto_data; if( source == NULL ) { /* The SSL connection will be cleaned up by the SSL lib already, set it to NULL here to prevent a double cleanup: */ jd->ssl = NULL; imcb_error( ic, "Could not connect to server" ); imc_logout( ic, TRUE ); return FALSE; } imcb_log( ic, "Connected to server, logging in" ); return jabber_start_stream( ic ); } static xt_status jabber_end_of_stream( struct xt_node *node, gpointer data ) { imc_logout( data, TRUE ); return XT_ABORT; } static xt_status jabber_pkt_features( struct xt_node *node, gpointer data ) { struct im_connection *ic = data; struct jabber_data *jd = ic->proto_data; struct xt_node *c, *reply; int trytls; trytls = g_strcasecmp( set_getstr( &ic->acc->set, "tls" ), "try" ) == 0; c = xt_find_node( node->children, "starttls" ); if( c && !jd->ssl ) { /* If the server advertises the STARTTLS feature and if we're not in a secure connection already: */ c = xt_find_node( c->children, "required" ); if( c && ( !trytls && !set_getbool( &ic->acc->set, "tls" ) ) ) { imcb_error( ic, "Server requires TLS connections, but TLS is turned off for this account" ); imc_logout( ic, FALSE ); return XT_ABORT; } /* Only run this if the tls setting is set to true or try: */ if( ( trytls || set_getbool( &ic->acc->set, "tls" ) ) ) { reply = xt_new_node( "starttls", NULL, NULL ); xt_add_attr( reply, "xmlns", XMLNS_TLS ); if( !jabber_write_packet( ic, reply ) ) { xt_free_node( reply ); return XT_ABORT; } xt_free_node( reply ); return XT_HANDLED; } } else if( !c && !jd->ssl ) { /* If the server does not advertise the STARTTLS feature and we're not in a secure connection already: (Servers have a habit of not advertising <starttls/> anymore when already using SSL/TLS. */ if( !trytls && set_getbool( &ic->acc->set, "tls" ) ) { imcb_error( ic, "TLS is turned on for this account, but is not supported by this server" ); imc_logout( ic, FALSE ); return XT_ABORT; } } /* This one used to be in jabber_handlers[], but it has to be done from here to make sure the TLS session will be initialized properly before we attempt SASL authentication. */ if( ( c = xt_find_node( node->children, "mechanisms" ) ) ) { if( sasl_pkt_mechanisms( c, data ) == XT_ABORT ) return XT_ABORT; } /* If the server *SEEMS* to support SASL authentication but doesn't support it after all, we should try to do authentication the other way. jabber.com doesn't seem to do SASL while it pretends to be XMPP 1.0 compliant! */ else if( !( jd->flags & JFLAG_AUTHENTICATED ) && sasl_supported( ic ) ) { if( !jabber_init_iq_auth( ic ) ) return XT_ABORT; } if( ( c = xt_find_node( node->children, "bind" ) ) ) jd->flags |= JFLAG_WANT_BIND; if( ( c = xt_find_node( node->children, "session" ) ) ) jd->flags |= JFLAG_WANT_SESSION; if( jd->flags & JFLAG_AUTHENTICATED ) return jabber_pkt_bind_sess( ic, NULL, NULL ); return XT_HANDLED; } static xt_status jabber_pkt_proceed_tls( struct xt_node *node, gpointer data ) { struct im_connection *ic = data; struct jabber_data *jd = ic->proto_data; char *xmlns; xmlns = xt_find_attr( node, "xmlns" ); /* Just ignore it when it doesn't seem to be TLS-related (is that at all possible??). */ if( !xmlns || strcmp( xmlns, XMLNS_TLS ) != 0 ) return XT_HANDLED; /* We don't want event handlers to touch our TLS session while it's still initializing! */ b_event_remove( jd->r_inpa ); if( jd->tx_len > 0 ) { /* Actually the write queue should be empty here, but just to be sure... */ b_event_remove( jd->w_inpa ); g_free( jd->txq ); jd->txq = NULL; jd->tx_len = 0; } jd->w_inpa = jd->r_inpa = 0; imcb_log( ic, "Converting stream to TLS" ); jd->flags |= JFLAG_STARTTLS_DONE; jd->ssl = ssl_starttls( jd->fd, jabber_connected_ssl, ic ); return XT_HANDLED; } static xt_status jabber_pkt_stream_error( struct xt_node *node, gpointer data ) { struct im_connection *ic = data; int allow_reconnect = TRUE; struct jabber_error *err; err = jabber_error_parse( node, XMLNS_STREAM_ERROR ); /* Tssk... */ if( err->code == NULL ) { imcb_error( ic, "Unknown stream error reported by server" ); imc_logout( ic, allow_reconnect ); jabber_error_free( err ); return XT_ABORT; } /* We know that this is a fatal error. If it's a "conflict" error, we should turn off auto-reconnect to make sure we won't get some nasty infinite loop! */ if( strcmp( err->code, "conflict" ) == 0 ) { imcb_error( ic, "Account and resource used from a different location" ); allow_reconnect = FALSE; } else { imcb_error( ic, "Stream error: %s%s%s", err->code, err->text ? ": " : "", err->text ? err->text : "" ); } jabber_error_free( err ); imc_logout( ic, allow_reconnect ); return XT_ABORT; } static xt_status jabber_xmlconsole( struct xt_node *node, gpointer data ) { struct im_connection *ic = data; struct jabber_data *jd = ic->proto_data; if( jd->flags & JFLAG_XMLCONSOLE ) { char *msg, *pkt; pkt = xt_to_string( node ); msg = g_strdup_printf( "RX: %s", pkt ); imcb_buddy_msg( ic, JABBER_XMLCONSOLE_HANDLE, msg, 0, 0 ); g_free( msg ); g_free( pkt ); } return XT_NEXT; } static const struct xt_handler_entry jabber_handlers[] = { { NULL, "stream:stream", jabber_xmlconsole }, { "stream:stream", "<root>", jabber_end_of_stream }, { "message", "stream:stream", jabber_pkt_message }, { "presence", "stream:stream", jabber_pkt_presence }, { "iq", "stream:stream", jabber_pkt_iq }, { "stream:features", "stream:stream", jabber_pkt_features }, { "stream:error", "stream:stream", jabber_pkt_stream_error }, { "proceed", "stream:stream", jabber_pkt_proceed_tls }, { "challenge", "stream:stream", sasl_pkt_challenge }, { "success", "stream:stream", sasl_pkt_result }, { "failure", "stream:stream", sasl_pkt_result }, { NULL, NULL, NULL } }; gboolean jabber_start_stream( struct im_connection *ic ) { struct jabber_data *jd = ic->proto_data; int st; char *greet; /* We'll start our stream now, so prepare everything to receive one from the server too. */ xt_free( jd->xt ); /* In case we're RE-starting. */ jd->xt = xt_new( jabber_handlers, ic ); if( jd->r_inpa <= 0 ) jd->r_inpa = b_input_add( jd->fd, GAIM_INPUT_READ, jabber_read_callback, ic ); greet = g_strdup_printf( "%s<stream:stream to=\"%s\" xmlns=\"jabber:client\" " "xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">", ( jd->flags & JFLAG_STARTTLS_DONE ) ? "" : "<?xml version='1.0' ?>", jd->server ); st = jabber_write( ic, greet, strlen( greet ) ); g_free( greet ); return st; } void jabber_end_stream( struct im_connection *ic ) { struct jabber_data *jd = ic->proto_data; /* Let's only do this if the queue is currently empty, otherwise it'd take too long anyway. */ if( jd->tx_len == 0 ) { char eos[] = "</stream:stream>"; struct xt_node *node; int st = 1; if( ic->flags & OPT_LOGGED_IN ) { node = jabber_make_packet( "presence", "unavailable", NULL, NULL ); st = jabber_write_packet( ic, node ); xt_free_node( node ); } if( st ) jabber_write( ic, eos, strlen( eos ) ); } }