source: branches/1.3x/libtransmission/handshake.c @ 7282

Last change on this file since 7282 was 7282, checked in by charles, 14 years ago

(1.3x libT) backport #1557: handshake peer-id doesn't match the peer-id sent in the tracker announce

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