source: trunk/libtransmission/handshake.c @ 3846

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

remove yet more dead code

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