source: trunk/libtransmission/handshake.c @ 3508

Last change on this file since 3508 was 3508, checked in by charles, 15 years ago

rewind this morning's changes.

  • Property svn:keywords set to Date Rev Author Id
File size: 31.2 KB
Line 
1/*
2 * This file Copyright (C) 2007 Charles Kerr <charles@rebelbase.com>
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: handshake.c 3508 2007-10-23 20:42:00Z charles $
11 */
12
13#include <assert.h>
14#include <errno.h>
15#include <inttypes.h>
16#include <limits.h> /* UCHAR_MAX */
17#include <string.h>
18#include <stdio.h>
19#include <libgen.h> /* basename */
20
21#include <sys/types.h> /* event.h needs this */
22#include <event.h>
23
24#include "clients.h"
25#include "transmission.h"
26#include "bencode.h"
27#include "crypto.h"
28#include "handshake.h"
29#include "peer-io.h"
30#include "trevent.h"
31#include "utils.h"
32
33/* enable LibTransmission extension protocol */
34#define ENABLE_LTEP */
35
36/* enable fast peers extension protocol */
37/* #define ENABLE_FASTPEER */
38
39/***
40****
41***/
42
43#define HANDSHAKE_NAME "\023BitTorrent protocol"
44
45enum
46{
47    /* BitTorrent Handshake Constants */
48    HANDSHAKE_NAME_LEN             = 20,
49    HANDSHAKE_FLAGS_LEN            = 8,
50    HANDSHAKE_SIZE                 = 68,
51    PEER_ID_LEN                    = 20,
52
53    /* Encryption Constants */
54    PadA_MAXLEN                    = 512,
55    PadB_MAXLEN                    = 512,
56    PadC_MAXLEN                    = 512,
57    PadD_MAXLEN                    = 512,
58    VC_LENGTH                      = 8,
59    KEY_LEN                        = 96,
60    CRYPTO_PROVIDE_PLAINTEXT       = 1,
61    CRYPTO_PROVIDE_CRYPTO          = 2
62};
63
64
65#ifdef ENABLE_LTEP
66#define HANDSHAKE_HAS_LTEP( bits ) ( ( (bits)[5] & 0x10 ) ? 1 : 0 )
67#define HANDSHAKE_SET_LTEP( bits ) ( (bits)[5] |= 0x10 )
68#else
69#define HANDSHAKE_HAS_LTEP( bits ) ( 0 )
70#define HANDSHAKE_SET_LTEP( bits ) ( (void)0 )
71#endif
72
73#ifdef ENABLE_FASTPEER
74#define HANDSHAKE_HAS_FASTEXT( bits ) ( ( (bits)[7] & 0x04 ) ? 1 : 0 )
75#define HANDSHAKE_SET_FASTEXT( bits ) ( (bits)[7] |= 0x04 )
76#else
77#define HANDSHAKE_HAS_FASTEXT( bits ) ( 0 )
78#define HANDSHAKE_SET_FASTEXT( bits ) ( (void)0 )
79#endif
80
81/* http://www.azureuswiki.com/index.php/Extension_negotiation_protocol
82   these macros are to be used if both extended messaging and the
83   azureus protocol is supported, they indicate which protocol is preferred */
84#define HANDSHAKE_GET_EXTPREF( reserved )      ( (reserved)[5] & 0x03 )
85#define HANDSHAKE_SET_EXTPREF( reserved, val ) ( (reserved)[5] |= 0x03 & (val) )
86
87extern const char* getPeerId( void ) ;
88
89struct tr_handshake
90{
91    unsigned int havePeerID                   : 1;
92    unsigned int haveSentBitTorrentHandshake  : 1;
93    unsigned int allowUnencryptedPeers        : 1;
94    tr_peerIo * io;
95    tr_crypto * crypto;
96    struct tr_handle * handle;
97    uint8_t myPublicKey[KEY_LEN];
98    uint8_t mySecret[KEY_LEN];
99    uint8_t state;
100    uint16_t pad_c_len;
101    uint16_t pad_d_len;
102    uint16_t  ia_len;
103    uint32_t crypto_select;
104    uint32_t crypto_provide;
105    uint8_t myReq1[SHA_DIGEST_LENGTH];
106    uint8_t peer_id[PEER_ID_LEN];
107    handshakeDoneCB doneCB;
108    void * doneUserData;
109};
110
111/**
112***
113**/
114
115enum
116{
117    /* incoming */
118    AWAITING_HANDSHAKE,
119    AWAITING_YA,
120    AWAITING_PAD_A,
121    AWAITING_CRYPTO_PROVIDE,
122    AWAITING_PAD_C,
123    AWAITING_IA,
124
125    /* outgoing */
126    AWAITING_YB,
127    AWAITING_VC,
128    AWAITING_CRYPTO_SELECT,
129    AWAITING_PAD_D,
130};
131
132/**
133***
134**/
135
136static void
137myDebug( const char * file, int line, const tr_handshake * handshake, const char * fmt, ... )
138{
139    FILE * fp = tr_getLog( );
140    if( fp != NULL )
141    {
142        va_list args;
143        char timestr[64];
144        struct evbuffer * buf = evbuffer_new( );
145        char * myfile = tr_strdup( file );
146
147        evbuffer_add_printf( buf, "[%s] %s: ",
148                             tr_getLogTimeStr( timestr, sizeof(timestr) ),
149                             tr_peerIoGetAddrStr( handshake->io ) );
150        va_start( args, fmt );
151        evbuffer_add_vprintf( buf, fmt, args );
152        va_end( args );
153        evbuffer_add_printf( buf, " (%s:%d)\n", basename(myfile), line );
154        fwrite( EVBUFFER_DATA(buf), 1, EVBUFFER_LENGTH(buf), fp );
155
156        tr_free( myfile );
157        evbuffer_free( buf );
158    }
159}
160
161#define dbgmsg(handshake, fmt...) myDebug(__FILE__, __LINE__, handshake, ##fmt )
162
163static const char* getStateName( short state )
164{
165    const char * str = "f00!";
166    switch( state ) {
167        case AWAITING_HANDSHAKE:      str = "awaiting handshake"; break;
168        case AWAITING_YA:             str = "awaiting ya"; break;
169        case AWAITING_PAD_A:          str = "awaiting pad a"; break;
170        case AWAITING_CRYPTO_PROVIDE: str = "awaiting crypto_provide"; break;
171        case AWAITING_PAD_C:          str = "awaiting pad c"; break;
172        case AWAITING_IA:             str = "awaiting ia"; break;
173        case AWAITING_YB:             str = "awaiting yb"; break;
174        case AWAITING_VC:             str = "awaiting vc"; break;
175        case AWAITING_CRYPTO_SELECT:  str = "awaiting crypto select"; break;
176        case AWAITING_PAD_D:          str = "awaiting pad d"; break;
177    }
178    return str;
179}
180
181static void
182setState( tr_handshake * handshake, short state )
183{
184    dbgmsg( handshake, "setting to state [%s]", getStateName(state) );
185    handshake->state = state;
186}
187
188static void
189setReadState( tr_handshake * handshake, int state )
190{
191    setState( handshake, state );
192}
193
194static uint8_t *
195buildHandshakeMessage( tr_handshake * handshake,
196                       int          * setme_len )
197{
198    uint8_t * buf = tr_new0( uint8_t, HANDSHAKE_SIZE );
199    uint8_t * walk = buf;
200    const uint8_t * torrentHash = tr_cryptoGetTorrentHash( handshake->crypto );
201
202    memcpy( walk, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN );
203    walk += HANDSHAKE_NAME_LEN;
204    memset( walk, 0, HANDSHAKE_FLAGS_LEN );
205    HANDSHAKE_SET_LTEP( walk );
206    HANDSHAKE_SET_FASTEXT( walk );
207
208    walk += HANDSHAKE_FLAGS_LEN;
209    memcpy( walk, torrentHash, SHA_DIGEST_LENGTH );
210    walk += SHA_DIGEST_LENGTH;
211    memcpy( walk, getPeerId(), TR_ID_LEN );
212    walk += TR_ID_LEN;
213
214    assert( walk-buf == HANDSHAKE_SIZE );
215    *setme_len = walk - buf;
216    return buf;
217}
218
219static void
220tr_handshakeDone( tr_handshake * handshake, int isConnected );
221
222enum
223{
224    HANDSHAKE_OK,
225    HANDSHAKE_ENCRYPTION_WRONG,
226    HANDSHAKE_BAD_TORRENT,
227    HANDSHAKE_PEER_IS_SELF,
228};
229
230static int
231parseHandshake( tr_handshake     * handshake,
232                struct evbuffer  * inbuf )
233{
234    uint8_t name[HANDSHAKE_NAME_LEN];
235    uint8_t reserved[HANDSHAKE_FLAGS_LEN];
236    uint8_t hash[SHA_DIGEST_LENGTH];
237
238    dbgmsg( handshake, "payload: need %d, got %d", (int)HANDSHAKE_SIZE, (int)EVBUFFER_LENGTH(inbuf) );
239
240    if( EVBUFFER_LENGTH(inbuf) < HANDSHAKE_SIZE )
241        return READ_MORE;
242
243    /* confirm the protocol */
244    tr_peerIoReadBytes( handshake->io, inbuf, name, HANDSHAKE_NAME_LEN );
245    if( memcmp( name, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN ) )
246        return HANDSHAKE_ENCRYPTION_WRONG;
247
248    /* read the reserved bytes */
249    tr_peerIoReadBytes( handshake->io, inbuf, reserved, HANDSHAKE_FLAGS_LEN );
250
251    /* torrent hash */
252    tr_peerIoReadBytes( handshake->io, inbuf, hash, sizeof(hash) );
253    assert( tr_torrentExists( handshake->handle, hash ) );
254    assert( tr_peerIoHasTorrentHash( handshake->io ) );
255    if( memcmp( hash, tr_peerIoGetTorrentHash(handshake->io), SHA_DIGEST_LENGTH ) ) {
256        dbgmsg( handshake, "peer returned the wrong hash. wtf?" );
257        return HANDSHAKE_BAD_TORRENT;
258    }
259
260    /* peer_id */
261    tr_peerIoReadBytes( handshake->io, inbuf, handshake->peer_id, sizeof(handshake->peer_id) );
262    tr_peerIoSetPeersId( handshake->io, handshake->peer_id );
263
264    /* peer id */
265    handshake->havePeerID = TRUE;
266    dbgmsg( handshake, "peer-id is [%*.*s]", PEER_ID_LEN, PEER_ID_LEN, handshake->peer_id );
267    if( !memcmp( handshake->peer_id, getPeerId(), PEER_ID_LEN ) ) {
268        dbgmsg( handshake, "streuth!  we've connected to ourselves." );
269        return HANDSHAKE_PEER_IS_SELF;
270    }
271
272    /**
273    *** Extensions
274    **/
275
276    if( HANDSHAKE_HAS_LTEP( reserved ) )
277    {
278        tr_peerIoEnableLTEP( handshake->io, 1 );
279        dbgmsg(handshake,"using ltep" );
280    }
281
282    if( HANDSHAKE_HAS_FASTEXT( reserved ) )
283    {
284        tr_peerIoEnableFEXT( handshake->io, 1 );
285        dbgmsg(handshake,"using fext" );
286    }
287       
288    return HANDSHAKE_OK;
289}
290
291/***
292****
293****  OUTGOING CONNECTIONS
294****
295***/
296
297/* 1 A->B: Diffie Hellman Ya, PadA */
298static void
299sendYa( tr_handshake * handshake )
300{
301    int i;
302    int len;
303    const uint8_t * public_key;
304    struct evbuffer * outbuf = evbuffer_new( );
305    uint8_t pad_a[PadA_MAXLEN];
306
307    /* add our public key (Ya) */
308    public_key = tr_cryptoGetMyPublicKey( handshake->crypto, &len );
309    assert( len == KEY_LEN );
310    assert( public_key != NULL );
311    evbuffer_add( outbuf, public_key, len );
312
313    /* add some bullshit padding */
314    len = tr_rand( PadA_MAXLEN );
315    for( i=0; i<len; ++i )
316        pad_a[i] = tr_rand( UCHAR_MAX );
317    evbuffer_add( outbuf, pad_a, len );
318
319    /* send it */
320    setReadState( handshake, AWAITING_YB );
321    tr_peerIoWriteBuf( handshake->io, outbuf );
322
323    /* cleanup */
324    evbuffer_free( outbuf );
325}
326
327static uint32_t
328getCryptoProvide( const tr_handshake * handshake UNUSED )
329{
330    uint32_t i = 0;
331
332    i |= CRYPTO_PROVIDE_CRYPTO; /* always allow crypto */
333
334#if 0
335    /* by the time we send a crypto_provide, we _know_
336     * the peer supports encryption. */
337    if( handshake->allowUnencryptedPeers )
338        i |= CRYPTO_PROVIDE_PLAINTEXT;
339#endif
340
341   return i;
342}
343
344static int
345readYb( tr_handshake * handshake, struct evbuffer * inbuf )
346{
347    int isEncrypted;
348    const uint8_t * secret;
349    uint8_t yb[KEY_LEN];
350    struct evbuffer * outbuf;
351    size_t needlen = HANDSHAKE_NAME_LEN;
352
353    if( EVBUFFER_LENGTH(inbuf) < needlen )
354        return READ_MORE;
355
356    isEncrypted = memcmp( EVBUFFER_DATA(inbuf), HANDSHAKE_NAME, HANDSHAKE_NAME_LEN );
357    if( isEncrypted ) {
358        needlen = KEY_LEN;
359        if( EVBUFFER_LENGTH(inbuf) < needlen )
360            return READ_MORE;
361    }
362
363    dbgmsg( handshake, "got a %s handshake", (isEncrypted ? "encrypted" : "plaintext") );
364
365    tr_peerIoSetEncryption( handshake->io, isEncrypted ? PEER_ENCRYPTION_RC4
366                                                       : PEER_ENCRYPTION_NONE );
367    if( !isEncrypted ) {
368        setState( handshake, AWAITING_HANDSHAKE );
369        return READ_AGAIN;
370    }
371
372    /* compute the secret */
373    evbuffer_remove( inbuf, yb, KEY_LEN );
374    secret = tr_cryptoComputeSecret( handshake->crypto, yb );
375    memcpy( handshake->mySecret, secret, KEY_LEN );
376
377    /* now send these: HASH('req1', S), HASH('req2', SKEY) xor HASH('req3', S),
378     * ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)), ENCRYPT(IA) */
379    outbuf = evbuffer_new( );
380
381    /* HASH('req1', S) */
382    {
383        uint8_t req1[SHA_DIGEST_LENGTH];
384        tr_sha1( req1, "req1", 4, secret, KEY_LEN, NULL );
385        evbuffer_add( outbuf, req1, SHA_DIGEST_LENGTH );
386    }
387
388    /* HASH('req2', SKEY) xor HASH('req3', S) */
389    {
390        int i;
391        uint8_t req2[SHA_DIGEST_LENGTH];
392        uint8_t req3[SHA_DIGEST_LENGTH];
393        uint8_t buf[SHA_DIGEST_LENGTH];
394        tr_sha1( req2, "req2", 4, tr_cryptoGetTorrentHash(handshake->crypto), SHA_DIGEST_LENGTH, NULL );
395        tr_sha1( req3, "req3", 4, secret, KEY_LEN, NULL );
396        for( i=0; i<SHA_DIGEST_LENGTH; ++i )
397            buf[i] = req2[i] ^ req3[i];
398        evbuffer_add( outbuf, buf, SHA_DIGEST_LENGTH );
399    }
400     
401    /* ENCRYPT(VC, crypto_provide, len(PadC), PadC
402     * PadC is reserved for future extensions to the handshake...
403     * standard practice at this time is for it to be zero-length */
404    {
405        uint8_t vc[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
406
407        tr_cryptoEncryptInit( handshake->crypto );
408        tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_RC4 );
409     
410        tr_peerIoWriteBytes( handshake->io, outbuf, vc, VC_LENGTH ); 
411        tr_peerIoWriteUint32( handshake->io, outbuf, getCryptoProvide( handshake ) );
412        tr_peerIoWriteUint16( handshake->io, outbuf, 0 );
413    }
414
415    /* ENCRYPT len(IA)), ENCRYPT(IA) */
416    {
417        int msglen;
418        uint8_t * msg = buildHandshakeMessage( handshake, &msglen );
419
420        tr_peerIoWriteUint16( handshake->io, outbuf, msglen );
421        tr_peerIoWriteBytes( handshake->io, outbuf, msg, msglen );
422
423        handshake->haveSentBitTorrentHandshake = 1;
424        tr_free( msg );
425    }
426
427    /* send it */
428    tr_cryptoDecryptInit( handshake->crypto );
429    setReadState( handshake, AWAITING_VC );
430    tr_peerIoWriteBuf( handshake->io, outbuf );
431
432    /* cleanup */
433    evbuffer_free( outbuf );
434    return READ_DONE;
435}
436
437static int
438readVC( tr_handshake * handshake, struct evbuffer * inbuf )
439{
440    const uint8_t key[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
441    const int key_len = VC_LENGTH;
442    uint8_t tmp[VC_LENGTH];
443
444    /* note: this works w/o having to `unwind' the buffer if
445     * we read too much, but it is pretty brute-force.
446     * it would be nice to make this cleaner. */
447    for( ;; )
448    {
449        if( EVBUFFER_LENGTH(inbuf) < VC_LENGTH ) {
450            dbgmsg( handshake, "not enough bytes... returning read_more" );
451            return READ_MORE;
452        }
453
454        memcpy( tmp, EVBUFFER_DATA(inbuf), key_len );
455        tr_cryptoDecryptInit( handshake->crypto );
456        tr_cryptoDecrypt( handshake->crypto, key_len, tmp, tmp );
457        if( !memcmp( tmp, key, key_len ) )
458            break;
459
460        evbuffer_drain( inbuf, 1 );
461    }
462
463    dbgmsg( handshake, "got it!" );
464    evbuffer_drain( inbuf, key_len );
465    setState( handshake, AWAITING_CRYPTO_SELECT );
466    return READ_AGAIN;
467}
468
469static int
470readCryptoSelect( tr_handshake * handshake, struct evbuffer * inbuf )
471{
472    uint32_t crypto_select;
473    uint16_t pad_d_len;
474    const size_t needlen = sizeof(uint32_t) + sizeof(uint16_t);
475
476    if( EVBUFFER_LENGTH(inbuf) < needlen )
477        return READ_MORE;
478
479    tr_peerIoReadUint32( handshake->io, inbuf, &crypto_select );
480    handshake->crypto_select = crypto_select;
481    dbgmsg( handshake, "crypto select is %d", (int)crypto_select );
482    if( ! ( crypto_select & getCryptoProvide( handshake ) ) )
483    {
484        dbgmsg( handshake, "peer selected an encryption option we didn't provide" );
485        tr_handshakeDone( handshake, FALSE );
486        return READ_DONE;
487    }
488
489    tr_peerIoReadUint16( handshake->io, inbuf, &pad_d_len );
490    dbgmsg( handshake, "pad_d_len is %d", (int)pad_d_len );
491    assert( pad_d_len <= 512 );
492    handshake->pad_d_len = pad_d_len;
493
494    setState( handshake, AWAITING_PAD_D );
495    return READ_AGAIN;
496}
497
498static int
499readPadD( tr_handshake * handshake, struct evbuffer * inbuf )
500{
501    const size_t needlen = handshake->pad_d_len;
502    uint8_t * tmp;
503
504    dbgmsg( handshake, "pad d: need %d, got %d", (int)needlen, (int)EVBUFFER_LENGTH(inbuf) );
505    if( EVBUFFER_LENGTH(inbuf) < needlen )
506        return READ_MORE;
507
508    tmp = tr_new( uint8_t, needlen );
509    tr_peerIoReadBytes( handshake->io, inbuf, tmp, needlen );
510    tr_free( tmp );
511
512    tr_peerIoSetEncryption( handshake->io,
513                            handshake->crypto_select );
514
515    setState( handshake, AWAITING_HANDSHAKE );
516    return READ_AGAIN;
517}
518
519/***
520****
521****  INCOMING CONNECTIONS
522****
523***/
524
525static int
526readHandshake( tr_handshake * handshake, struct evbuffer * inbuf )
527{
528    uint8_t pstrlen;
529    uint8_t * pstr;
530    uint8_t reserved[HANDSHAKE_FLAGS_LEN];
531    uint8_t hash[SHA_DIGEST_LENGTH];
532    char * client;
533
534/* FIXME: use  readHandshake here */
535
536    dbgmsg( handshake, "payload: need %d, got %d", (int)HANDSHAKE_SIZE, (int)EVBUFFER_LENGTH(inbuf) );
537
538    if( EVBUFFER_LENGTH(inbuf) < HANDSHAKE_SIZE )
539        return READ_MORE;
540
541    pstrlen = EVBUFFER_DATA(inbuf)[0]; /* peek, don't read.  We may be
542                                          handing inbuf to AWAITING_YA */
543
544    if( pstrlen == 19 ) /* unencrypted */
545    {
546        tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_NONE );
547
548        if( !handshake->allowUnencryptedPeers )
549        {
550            dbgmsg( handshake, "peer is unencrypted, and we're disallowing that" );
551            tr_handshakeDone( handshake, FALSE );
552            return READ_DONE;
553        }
554    }
555    else /* encrypted or corrupt */
556    {
557        tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_RC4 );
558
559        if( tr_peerIoIsIncoming( handshake->io ) )
560        {
561            dbgmsg( handshake, "I think peer is sending us an encrypted handshake..." );
562            setState( handshake, AWAITING_YA );
563            return READ_AGAIN;
564        }
565        tr_cryptoDecrypt( handshake->crypto, 1, &pstrlen, &pstrlen );
566
567        if( pstrlen != 19 )
568        {
569            dbgmsg( handshake, "I think peer has sent us a corrupt handshake..." );
570            tr_handshakeDone( handshake, FALSE );
571            return READ_DONE;
572        }
573    }
574
575    evbuffer_drain( inbuf, 1 );
576
577    /* pstr (BitTorrent) */
578    pstr = tr_new( uint8_t, pstrlen+1 );
579    tr_peerIoReadBytes( handshake->io, inbuf, pstr, pstrlen );
580    pstr[pstrlen] = '\0';
581    if( strcmp( (char*)pstr, "BitTorrent protocol" ) ) {
582        tr_free( pstr );
583        tr_handshakeDone( handshake, FALSE );
584        return READ_DONE;
585    }
586    tr_free( pstr );
587
588    /* reserved bytes */
589    tr_peerIoReadBytes( handshake->io, inbuf, reserved, sizeof(reserved) );
590
591    /* torrent hash */
592    tr_peerIoReadBytes( handshake->io, inbuf, hash, sizeof(hash) );
593    if( tr_peerIoIsIncoming( handshake->io ) )
594    {
595        if( !tr_torrentExists( handshake->handle, hash ) )
596        {
597            dbgmsg( handshake, "peer is trying to connect to us for a torrent we don't have." );
598            tr_handshakeDone( handshake, FALSE );
599            return READ_DONE;
600        }
601        else
602        {
603            assert( !tr_peerIoHasTorrentHash( handshake->io ) );
604            tr_peerIoSetTorrentHash( handshake->io, hash );
605        }
606    }
607    else /* outgoing */
608    {
609        assert( tr_peerIoHasTorrentHash( handshake->io ) );
610        if( memcmp( hash, tr_peerIoGetTorrentHash(handshake->io), SHA_DIGEST_LENGTH ) )
611        {
612            dbgmsg( handshake, "peer returned the wrong hash. wtf?" );
613            tr_handshakeDone( handshake, FALSE );
614            return READ_DONE;
615        }
616    }
617
618    /* peer id */
619    tr_peerIoReadBytes( handshake->io, inbuf, handshake->peer_id, sizeof(handshake->peer_id) );
620    tr_peerIoSetPeersId( handshake->io, handshake->peer_id );
621    handshake->havePeerID = TRUE;
622    client = tr_clientForId( handshake->peer_id );
623    dbgmsg( handshake, "peer-id is [%s]", client );
624    tr_free( client );
625    if( !memcmp( handshake->peer_id, getPeerId(), PEER_ID_LEN ) ) {
626        dbgmsg( handshake, "streuth!  we've connected to ourselves." );
627        tr_handshakeDone( handshake, FALSE );
628        return READ_DONE;
629    }
630
631    /**
632    *** Extension negotiation
633    **/
634
635    if( HANDSHAKE_HAS_LTEP( reserved ) )
636    {
637        tr_peerIoEnableLTEP( handshake->io, 1 );
638        dbgmsg( handshake,"using ltep" );
639    }
640    if( HANDSHAKE_HAS_FASTEXT( reserved ) )
641    {
642        tr_peerIoEnableFEXT( handshake->io, 1 );
643        dbgmsg( handshake,"using fext" );
644    }
645   
646    /**
647    ***  If this is an incoming message, then we need to send a response handshake
648    **/
649
650    if( !handshake->haveSentBitTorrentHandshake )
651    {
652        int msgSize;
653        uint8_t * msg = buildHandshakeMessage( handshake, &msgSize );
654        tr_peerIoWrite( handshake->io, msg, msgSize );
655        tr_free( msg );
656        handshake->haveSentBitTorrentHandshake = 1;
657    }
658
659    /* we've completed the BT handshake... pass the work on to peer-msgs */
660    tr_handshakeDone( handshake, TRUE );
661    return READ_DONE;
662}
663
664static int
665readYa( tr_handshake * handshake, struct evbuffer  * inbuf )
666{
667    uint8_t ya[KEY_LEN];
668    uint8_t *walk, outbuf[KEY_LEN + PadB_MAXLEN];
669    const uint8_t *myKey, *secret;
670    int len;
671
672dbgmsg( handshake, "in readYa... need %d, have %d", (int)KEY_LEN, (int)EVBUFFER_LENGTH( inbuf ) );
673    if( EVBUFFER_LENGTH( inbuf ) < KEY_LEN )
674        return READ_MORE;
675
676    /* read the incoming peer's public key */
677    evbuffer_remove( inbuf, ya, KEY_LEN );
678    secret = tr_cryptoComputeSecret( handshake->crypto, ya );
679    memcpy( handshake->mySecret, secret, KEY_LEN );
680    tr_sha1( handshake->myReq1, "req1", 4, secret, KEY_LEN, NULL );
681
682dbgmsg( handshake, "sending B->A: Diffie Hellman Yb, PadB" );
683    /* send our public key to the peer */
684    walk = outbuf;
685    myKey = tr_cryptoGetMyPublicKey( handshake->crypto, &len );
686    memcpy( walk, myKey, len );
687    walk += len;
688    len = tr_rand( PadB_MAXLEN );
689    while( len-- )
690        *walk++ = tr_rand( UCHAR_MAX );
691
692    setReadState( handshake, AWAITING_PAD_A );
693    tr_peerIoWrite( handshake->io, outbuf, walk-outbuf );
694    return READ_AGAIN;
695}
696
697static int
698readPadA( tr_handshake * handshake, struct evbuffer * inbuf )
699{
700    uint8_t * pch;
701
702dbgmsg( handshake, "looking to get past pad a... & resync on hash('req',S) ... have %d bytes", (int)EVBUFFER_LENGTH(inbuf) );
703    /**
704    *** Resynchronizing on HASH('req1',S)
705    **/
706
707    pch = memchr( EVBUFFER_DATA(inbuf),
708                  handshake->myReq1[0],
709                  EVBUFFER_LENGTH(inbuf) );
710    if( pch == NULL ) {
711        dbgmsg( handshake, "no luck so far.. draining %d bytes", (int)EVBUFFER_LENGTH(inbuf) );
712        evbuffer_drain( inbuf, EVBUFFER_LENGTH(inbuf) );
713        return READ_MORE;
714    }
715    dbgmsg( handshake, "looking for hash('req',S) ... draining %d bytes", (int)(pch-EVBUFFER_DATA(inbuf)) );
716    evbuffer_drain( inbuf, pch-EVBUFFER_DATA(inbuf) );
717    if( EVBUFFER_LENGTH(inbuf) < SHA_DIGEST_LENGTH )
718        return READ_MORE;
719    if( memcmp( EVBUFFER_DATA(inbuf), handshake->myReq1, SHA_DIGEST_LENGTH ) ) {
720        dbgmsg( handshake, "draining one more byte" );
721        evbuffer_drain( inbuf, 1 );
722        return READ_AGAIN;
723    }
724
725dbgmsg( handshake, "found it... looking setting to awaiting_crypto_provide" );
726    setState( handshake, AWAITING_CRYPTO_PROVIDE );
727    return READ_AGAIN;
728}
729
730static int
731readCryptoProvide( tr_handshake * handshake, struct evbuffer * inbuf )
732{
733    /* HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide, len(PadC)) */
734
735    int i;
736    uint8_t vc_in[VC_LENGTH];
737    uint8_t req2[SHA_DIGEST_LENGTH];
738    uint8_t req3[SHA_DIGEST_LENGTH];
739    uint8_t obfuscatedTorrentHash[SHA_DIGEST_LENGTH];
740    uint16_t padc_len = 0;
741    uint32_t crypto_provide = 0;
742    const size_t needlen = SHA_DIGEST_LENGTH /* HASH('req1',s) */
743                         + SHA_DIGEST_LENGTH /* HASH('req2', SKEY) xor HASH('req3', S) */
744                         + VC_LENGTH
745                         + sizeof(crypto_provide)
746                         + sizeof(padc_len);
747    tr_torrent * tor = NULL;
748
749    if( EVBUFFER_LENGTH(inbuf) < needlen )
750        return READ_MORE;
751
752    /* TODO: confirm they sent HASH('req1',S) here? */
753    evbuffer_drain( inbuf, SHA_DIGEST_LENGTH );
754
755    /* This next piece is HASH('req2', SKEY) xor HASH('req3', S) ...
756     * we can get the first half of that (the obufscatedTorrentHash)
757     * by building the latter and xor'ing it with what the peer sent us */
758    dbgmsg( handshake, "reading obfuscated torrent hash..." );
759    evbuffer_remove( inbuf, req2, SHA_DIGEST_LENGTH );
760    tr_sha1( req3, "req3", 4, handshake->mySecret, KEY_LEN, NULL );
761    for( i=0; i<SHA_DIGEST_LENGTH; ++i )
762        obfuscatedTorrentHash[i] = req2[i] ^ req3[i];
763    tor = tr_torrentFindFromObfuscatedHash( handshake->handle, obfuscatedTorrentHash );
764    if( tor != NULL ) {
765        dbgmsg( handshake, "found the torrent; it's [%s]", tor->info.name );
766        tr_peerIoSetTorrentHash( handshake->io, tor->info.hash );
767    } else {
768        dbgmsg( handshake, "can't find that torrent..." );
769        tr_handshakeDone( handshake, FALSE );
770        return READ_DONE;
771    }
772
773    /* next part: ENCRYPT(VC, crypto_provide, len(PadC), */
774
775    tr_cryptoDecryptInit( handshake->crypto );
776
777    tr_peerIoReadBytes( handshake->io, inbuf, vc_in, VC_LENGTH );
778
779    tr_peerIoReadUint32( handshake->io, inbuf, &crypto_provide );
780    handshake->crypto_provide = crypto_provide;
781    dbgmsg( handshake, "crypto_provide is %d", (int)crypto_provide );
782
783    tr_peerIoReadUint16( handshake->io, inbuf, &padc_len );
784    dbgmsg( handshake, "padc is %d", (int)padc_len );
785    handshake->pad_c_len = padc_len;
786    setState( handshake, AWAITING_PAD_C );
787    return READ_AGAIN;
788}
789
790static int
791readPadC( tr_handshake * handshake, struct evbuffer * inbuf )
792{
793    uint16_t ia_len;
794    const size_t needlen = handshake->pad_c_len + sizeof(uint16_t);
795
796    if( EVBUFFER_LENGTH(inbuf) < needlen )
797        return READ_MORE;
798
799    evbuffer_drain( inbuf, handshake->pad_c_len );
800
801    tr_peerIoReadUint16( handshake->io, inbuf, &ia_len );
802    dbgmsg( handshake, "ia_len is %d", (int)ia_len );
803    handshake->ia_len = ia_len;
804    setState( handshake, AWAITING_IA );
805    return READ_AGAIN;
806}
807
808static int
809readIA( tr_handshake * handshake, struct evbuffer * inbuf )
810{
811    int i;
812    const size_t needlen = handshake->ia_len;
813    struct evbuffer * outbuf = evbuffer_new( );
814    uint32_t crypto_select;
815
816dbgmsg( handshake, "reading IA... have %d, need %d", (int)EVBUFFER_LENGTH(inbuf), (int)needlen );
817    if( EVBUFFER_LENGTH(inbuf) < needlen )
818        return READ_MORE;
819
820dbgmsg( handshake, "reading IA..." );
821    /* parse the handshake ... */
822    i = parseHandshake( handshake, inbuf );
823dbgmsg( handshake, "parseHandshake returned %d", i );
824    if( i != HANDSHAKE_OK ) {
825        evbuffer_free( outbuf );
826        tr_handshakeDone( handshake, FALSE );
827        return READ_DONE;
828    }
829
830    /**
831    ***  B->A: ENCRYPT(VC, crypto_select, len(padD), padD), ENCRYPT2(Payload Stream)
832    **/
833
834    tr_cryptoEncryptInit( handshake->crypto );
835
836dbgmsg( handshake, "sending vc" );
837    /* send VC */
838    {
839        uint8_t vc[VC_LENGTH];
840        memset( vc, 0, VC_LENGTH );
841        tr_peerIoWriteBytes( handshake->io, outbuf, vc, VC_LENGTH );
842    }
843
844dbgmsg( handshake, "sending crypto_select" );
845    /* send crypto_select */
846    {
847dbgmsg( handshake, "handshake->crypto_provide is %d", (int)handshake->crypto_provide );
848        if( handshake->crypto_provide & CRYPTO_PROVIDE_CRYPTO )
849            crypto_select = CRYPTO_PROVIDE_CRYPTO;
850        else if( handshake->allowUnencryptedPeers )
851            crypto_select = CRYPTO_PROVIDE_PLAINTEXT;
852        else {
853dbgmsg( handshake, "gronk..." );
854            evbuffer_free( outbuf );
855            tr_handshakeDone( handshake, FALSE );
856            return READ_DONE;
857        }
858
859dbgmsg( handshake, "we select crypto_select as %d...", (int)crypto_select );
860        tr_peerIoWriteUint32( handshake->io, outbuf, crypto_select );
861    }
862
863dbgmsg( handshake, "sending pad d" );
864    /* ENCRYPT(VC, crypto_provide, len(PadC), PadC
865     * PadD is reserved for future extensions to the handshake...
866     * standard practice at this time is for it to be zero-length */
867    {
868        const int len = 0;
869        tr_peerIoWriteUint16( handshake->io, outbuf, len );
870    }
871
872    /* maybe de-encrypt our connection */
873    if( crypto_select == CRYPTO_PROVIDE_PLAINTEXT )
874        tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_NONE );
875
876dbgmsg( handshake, "sending handshake" );
877    /* send our handshake */
878    {
879        int msgSize;
880        uint8_t * msg = buildHandshakeMessage( handshake, &msgSize );
881        tr_peerIoWriteBytes( handshake->io, outbuf, msg, msgSize );
882        handshake->haveSentBitTorrentHandshake = 1;
883        tr_free( msg );
884    }
885
886    /* send it out */
887    tr_peerIoWriteBuf( handshake->io, outbuf );
888    evbuffer_free( outbuf );
889
890    /* we've completed the BT handshake... pass the work on to peer-msgs */
891    tr_handshakeDone( handshake, TRUE );
892    return READ_DONE;
893}
894
895/***
896****
897****
898****
899***/
900
901static ReadState
902canRead( struct bufferevent * evin, void * arg )
903{
904    tr_handshake * handshake = (tr_handshake *) arg;
905    struct evbuffer * inbuf = EVBUFFER_INPUT ( evin );
906    ReadState ret;
907    dbgmsg( handshake, "handling canRead; state is [%s]", getStateName(handshake->state) );
908
909    switch( handshake->state )
910    {
911        case AWAITING_HANDSHAKE:       ret = readHandshake    ( handshake, inbuf ); break;
912        case AWAITING_YA:              ret = readYa           ( handshake, inbuf ); break;
913        case AWAITING_PAD_A:           ret = readPadA         ( handshake, inbuf ); break;
914        case AWAITING_CRYPTO_PROVIDE:  ret = readCryptoProvide( handshake, inbuf ); break;
915        case AWAITING_PAD_C:           ret = readPadC         ( handshake, inbuf ); break;
916        case AWAITING_IA:              ret = readIA           ( handshake, inbuf ); break;
917
918        case AWAITING_YB:              ret = readYb           ( handshake, inbuf ); break;
919        case AWAITING_VC:              ret = readVC           ( handshake, inbuf ); break;
920        case AWAITING_CRYPTO_SELECT:   ret = readCryptoSelect ( handshake, inbuf ); break;
921        case AWAITING_PAD_D:           ret = readPadD         ( handshake, inbuf ); break;
922
923        default: assert( 0 );
924    }
925
926    return ret;
927}
928
929static void
930fireDoneFunc( tr_handshake * handshake, int isConnected )
931{
932    const uint8_t * peer_id = isConnected && handshake->havePeerID
933        ? handshake->peer_id
934        : NULL;
935    (*handshake->doneCB)( handshake,
936                          handshake->io,
937                          isConnected,
938                          peer_id,
939                          handshake->doneUserData );
940}
941
942void
943tr_handshakeDone( tr_handshake * handshake, int isOK )
944{
945    dbgmsg( handshake, "handshakeDone: %s", isOK ? "connected" : "aborting" );
946    tr_peerIoSetIOFuncs( handshake->io, NULL, NULL, NULL, NULL );
947
948    fireDoneFunc( handshake, isOK );
949
950    tr_free( handshake );
951}
952
953void
954tr_handshakeAbort( tr_handshake * handshake )
955{
956    tr_handshakeDone( handshake, FALSE );
957}
958
959static void
960gotError( struct bufferevent * evbuf UNUSED, short what, void * arg )
961{
962    tr_handshake * handshake = (tr_handshake *) arg;
963
964    /* if the error happened while we were sending a public key, we might
965     * have encountered a peer that doesn't do encryption... reconnect and
966     * try a plaintext handshake */
967    if(    ( ( handshake->state == AWAITING_YB ) || ( handshake->state == AWAITING_VC ) )
968        && ( handshake->allowUnencryptedPeers )
969        && ( !tr_peerIoReconnect( handshake->io ) ) )
970    {
971        dbgmsg( handshake, "handshake failed, trying plaintext..." );
972        int msgSize; 
973        uint8_t * msg = buildHandshakeMessage( handshake, &msgSize );
974        handshake->haveSentBitTorrentHandshake = 1;
975        setReadState( handshake, AWAITING_HANDSHAKE );
976        tr_peerIoWrite( handshake->io, msg, msgSize );
977        tr_free( msg );
978    }
979    else
980    {
981        dbgmsg( handshake, "libevent got an error what==%d, errno=%d (%s)",
982                (int)what, errno, strerror(errno) );
983        tr_handshakeDone( handshake, FALSE );
984    }
985}
986
987/**
988***
989**/
990
991tr_handshake*
992tr_handshakeNew( tr_peerIo           * io,
993                 tr_encryption_mode    encryption_mode,
994                 handshakeDoneCB       doneCB,
995                 void                * doneUserData )
996{
997    tr_handshake * handshake;
998
999    handshake = tr_new0( tr_handshake, 1 );
1000    handshake->io = io;
1001    handshake->crypto = tr_peerIoGetCrypto( io );
1002    handshake->allowUnencryptedPeers = encryption_mode!=TR_ENCRYPTION_REQUIRED;
1003    handshake->doneCB = doneCB;
1004    handshake->doneUserData = doneUserData;
1005    handshake->handle = tr_peerIoGetHandle( io );
1006   
1007    tr_peerIoSetIOMode( handshake->io, EV_READ|EV_WRITE, 0 );
1008    tr_peerIoSetIOFuncs( handshake->io, canRead, NULL, gotError, handshake );
1009
1010    if( tr_peerIoIsIncoming( handshake->io ) )
1011        setReadState( handshake, AWAITING_HANDSHAKE );
1012    else
1013        sendYa( handshake );
1014
1015    return handshake;
1016}
1017
1018const struct in_addr *
1019tr_handshakeGetAddr( const struct tr_handshake * handshake, uint16_t * port )
1020{
1021    assert( handshake != NULL );
1022    assert( handshake->io != NULL );
1023
1024    return tr_peerIoGetAddress( handshake->io, port );
1025}
Note: See TracBrowser for help on using the repository browser.