source: trunk/libtransmission/handshake.c @ 6517

Last change on this file since 6517 was 6517, checked in by muks, 13 years ago

Replace random number generation code

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