source: trunk/libtransmission/handshake.c @ 12136

Last change on this file since 12136 was 12136, checked in by jordan, 11 years ago

(trunk libT) #4106 "Assert in buildHandshakeMessage, r12131" -- probable fix

  • Property svn:keywords set to Date Rev Author Id
File size: 37.5 KB
Line 
1/*
2 * This file Copyright (C) Mnemosyne LLC
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 12136 2011-03-11 19:28:44Z jordan $
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 <event2/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 "session.h"
30#include "torrent.h"
31#include "tr-dht.h"
32#include "utils.h"
33
34/* enable LibTransmission extension protocol */
35#define ENABLE_LTEP * /
36/* fast extensions */
37#define ENABLE_FAST * /
38/* DHT */
39#define ENABLE_DHT * /
40
41/***
42****
43***/
44
45#define HANDSHAKE_NAME "\023BitTorrent protocol"
46
47enum
48{
49    /* BitTorrent Handshake Constants */
50    HANDSHAKE_NAME_LEN             = 20,
51    HANDSHAKE_FLAGS_LEN            = 8,
52    HANDSHAKE_SIZE                 = 68,
53    INCOMING_HANDSHAKE_LEN         = 48,
54
55    /* Encryption Constants */
56    PadA_MAXLEN                    = 512,
57    PadB_MAXLEN                    = 512,
58    PadC_MAXLEN                    = 512,
59    PadD_MAXLEN                    = 512,
60    VC_LENGTH                      = 8,
61    KEY_LEN                        = 96,
62    CRYPTO_PROVIDE_PLAINTEXT       = 1,
63    CRYPTO_PROVIDE_CRYPTO          = 2,
64
65    /* how long to wait before giving up on a handshake */
66    HANDSHAKE_TIMEOUT_SEC          = 30
67};
68
69
70#ifdef ENABLE_LTEP
71 #define HANDSHAKE_HAS_LTEP( bits ) ( ( ( bits )[5] & 0x10 ) ? 1 : 0 )
72 #define HANDSHAKE_SET_LTEP( bits ) ( ( bits )[5] |= 0x10 )
73#else
74 #define HANDSHAKE_HAS_LTEP( bits ) ( 0 )
75 #define HANDSHAKE_SET_LTEP( bits ) ( (void)0 )
76#endif
77
78#ifdef ENABLE_FAST
79 #define HANDSHAKE_HAS_FASTEXT( bits ) ( ( ( bits )[7] & 0x04 ) ? 1 : 0 )
80 #define HANDSHAKE_SET_FASTEXT( bits ) ( ( bits )[7] |= 0x04 )
81#else
82 #define HANDSHAKE_HAS_FASTEXT( bits ) ( 0 )
83 #define HANDSHAKE_SET_FASTEXT( bits ) ( (void)0 )
84#endif
85
86#ifdef ENABLE_DHT
87 #define HANDSHAKE_HAS_DHT( bits ) ( ( ( bits )[7] & 0x01 ) ? 1 : 0 )
88 #define HANDSHAKE_SET_DHT( bits ) ( ( bits )[7] |= 0x01 )
89#else
90 #define HANDSHAKE_HAS_DHT( bits ) ( 0 )
91 #define HANDSHAKE_SET_DHT( bits ) ( (void)0 )
92#endif
93
94/* http://www.azureuswiki.com/index.php/Extension_negotiation_protocol
95   these macros are to be used if both extended messaging and the
96   azureus protocol is supported, they indicate which protocol is preferred */
97#define HANDSHAKE_GET_EXTPREF( reserved )      ( ( reserved )[5] & 0x03 )
98#define HANDSHAKE_SET_EXTPREF( reserved, val ) ( ( reserved )[5] |= 0x03 &\
99                                                                    ( val ) )
100
101typedef uint8_t handshake_state_t;
102
103struct tr_handshake
104{
105    tr_bool               haveReadAnythingFromPeer;
106    tr_bool               havePeerID;
107    tr_bool               haveSentBitTorrentHandshake;
108    tr_peerIo *           io;
109    tr_crypto *           crypto;
110    tr_session *          session;
111    uint8_t               mySecret[KEY_LEN];
112    handshake_state_t     state;
113    tr_encryption_mode    encryptionMode;
114    uint16_t              pad_c_len;
115    uint16_t              pad_d_len;
116    uint16_t              ia_len;
117    uint32_t              crypto_select;
118    uint32_t              crypto_provide;
119    uint8_t               myReq1[SHA_DIGEST_LENGTH];
120    handshakeDoneCB       doneCB;
121    void *                doneUserData;
122    struct event        * timeout_timer;
123};
124
125/**
126***
127**/
128
129enum
130{
131    /* incoming */
132    AWAITING_HANDSHAKE,
133    AWAITING_PEER_ID,
134    AWAITING_YA,
135    AWAITING_PAD_A,
136    AWAITING_CRYPTO_PROVIDE,
137    AWAITING_PAD_C,
138    AWAITING_IA,
139    AWAITING_PAYLOAD_STREAM,
140
141    /* outgoing */
142    AWAITING_YB,
143    AWAITING_VC,
144    AWAITING_CRYPTO_SELECT,
145    AWAITING_PAD_D,
146};
147
148/**
149***
150**/
151
152#define dbgmsg( handshake, ... ) \
153    do { \
154        if( tr_deepLoggingIsActive( ) ) \
155            tr_deepLog( __FILE__, __LINE__, tr_peerIoGetAddrStr( handshake->io ), __VA_ARGS__ ); \
156    } while( 0 )
157
158static const char*
159getStateName( const handshake_state_t state )
160{
161    const char * str = "f00!";
162
163    switch( state )
164    {
165        case AWAITING_HANDSHAKE:
166            str = "awaiting handshake"; break;
167
168        case AWAITING_PEER_ID:
169            str = "awaiting peer id"; break;
170
171        case AWAITING_YA:
172            str = "awaiting ya"; break;
173
174        case AWAITING_PAD_A:
175            str = "awaiting pad a"; break;
176
177        case AWAITING_CRYPTO_PROVIDE:
178            str = "awaiting crypto_provide"; break;
179
180        case AWAITING_PAD_C:
181            str = "awaiting pad c"; break;
182
183        case AWAITING_IA:
184            str = "awaiting ia"; break;
185
186        case AWAITING_YB:
187            str = "awaiting yb"; break;
188
189        case AWAITING_VC:
190            str = "awaiting vc"; break;
191
192        case AWAITING_CRYPTO_SELECT:
193            str = "awaiting crypto select"; break;
194
195        case AWAITING_PAD_D:
196            str = "awaiting pad d"; break;
197    }
198    return str;
199}
200
201static void
202setState( tr_handshake * handshake, handshake_state_t state )
203{
204    dbgmsg( handshake, "setting to state [%s]", getStateName( state ) );
205    handshake->state = state;
206}
207
208static void
209setReadState( tr_handshake * handshake, handshake_state_t state )
210{
211    setState( handshake, state );
212}
213
214static void
215buildHandshakeMessage( tr_handshake * handshake, uint8_t * buf )
216{
217    uint8_t          * walk = buf;
218    const uint8_t    * torrentHash = tr_cryptoGetTorrentHash( handshake->crypto );
219    const tr_torrent * tor = tr_torrentFindFromHash( handshake->session, torrentHash );
220    const uint8_t    * peer_id = tor && *tor->peer_id ? tor->peer_id : tr_getPeerId( handshake->session );
221
222    memcpy( walk, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN );
223    walk += HANDSHAKE_NAME_LEN;
224    memset( walk, 0, HANDSHAKE_FLAGS_LEN );
225    HANDSHAKE_SET_LTEP( walk );
226    HANDSHAKE_SET_FASTEXT( walk );
227
228    /* Note that this doesn't depend on whether the torrent is private.
229     * We don't accept DHT peers for a private torrent,
230     * but we participate in the DHT regardless. */
231    if( tr_dhtEnabled( handshake->session ) )
232        HANDSHAKE_SET_DHT( walk );
233
234    walk += HANDSHAKE_FLAGS_LEN;
235    memcpy( walk, torrentHash, SHA_DIGEST_LENGTH );
236    walk += SHA_DIGEST_LENGTH;
237    memcpy( walk, peer_id, PEER_ID_LEN );
238    walk += PEER_ID_LEN;
239
240    assert( strlen( ( const char* )peer_id ) == PEER_ID_LEN );
241    assert( walk - buf == HANDSHAKE_SIZE );
242}
243
244static int tr_handshakeDone( tr_handshake * handshake,
245                             tr_bool        isConnected );
246
247enum
248{
249    HANDSHAKE_OK,
250    HANDSHAKE_ENCRYPTION_WRONG,
251    HANDSHAKE_BAD_TORRENT,
252    HANDSHAKE_PEER_IS_SELF,
253};
254
255static int
256parseHandshake( tr_handshake *    handshake,
257                struct evbuffer * inbuf )
258{
259    uint8_t name[HANDSHAKE_NAME_LEN];
260    uint8_t reserved[HANDSHAKE_FLAGS_LEN];
261    uint8_t hash[SHA_DIGEST_LENGTH];
262    const tr_torrent * tor;
263    const uint8_t * tor_peer_id;
264    uint8_t peer_id[PEER_ID_LEN];
265
266    dbgmsg( handshake, "payload: need %d, got %zu",
267            HANDSHAKE_SIZE, evbuffer_get_length( inbuf ) );
268
269    if( evbuffer_get_length( inbuf ) < HANDSHAKE_SIZE )
270        return READ_LATER;
271
272    /* confirm the protocol */
273    tr_peerIoReadBytes( handshake->io, inbuf, name, HANDSHAKE_NAME_LEN );
274    if( memcmp( name, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN ) )
275        return HANDSHAKE_ENCRYPTION_WRONG;
276
277    /* read the reserved bytes */
278    tr_peerIoReadBytes( handshake->io, inbuf, reserved, HANDSHAKE_FLAGS_LEN );
279
280    /* torrent hash */
281    tr_peerIoReadBytes( handshake->io, inbuf, hash, sizeof( hash ) );
282    assert( tr_peerIoHasTorrentHash( handshake->io ) );
283    if( !tr_torrentExists( handshake->session, hash )
284      || memcmp( hash, tr_peerIoGetTorrentHash( handshake->io ),
285                 SHA_DIGEST_LENGTH ) )
286    {
287        dbgmsg( handshake, "peer returned the wrong hash. wtf?" );
288        return HANDSHAKE_BAD_TORRENT;
289    }
290
291    /* peer_id */
292    tr_peerIoReadBytes( handshake->io, inbuf, peer_id, sizeof( peer_id ) );
293    tr_peerIoSetPeersId( handshake->io, peer_id );
294
295    /* peer id */
296    handshake->havePeerID = TRUE;
297    dbgmsg( handshake, "peer-id is [%*.*s]", PEER_ID_LEN, PEER_ID_LEN, peer_id );
298
299    tor = tr_torrentFindFromHash( handshake->session, hash );
300    tor_peer_id = tor ? tor->peer_id : tr_getPeerId( handshake->session );
301    if( !memcmp( peer_id, tor_peer_id, PEER_ID_LEN ) )
302    {
303        dbgmsg( handshake, "streuth!  we've connected to ourselves." );
304        return HANDSHAKE_PEER_IS_SELF;
305    }
306
307    /**
308    *** Extensions
309    **/
310
311    tr_peerIoEnableLTEP( handshake->io, HANDSHAKE_HAS_LTEP( reserved ) );
312
313    tr_peerIoEnableFEXT( handshake->io, HANDSHAKE_HAS_FASTEXT( reserved ) );
314
315    tr_peerIoEnableDHT( handshake->io, HANDSHAKE_HAS_DHT( reserved ) );
316
317    return HANDSHAKE_OK;
318}
319
320/***
321****
322****  OUTGOING CONNECTIONS
323****
324***/
325
326/* 1 A->B: Diffie Hellman Ya, PadA */
327static void
328sendYa( tr_handshake * handshake )
329{
330    int               len;
331    const uint8_t *   public_key;
332    char              outbuf[ KEY_LEN + PadA_MAXLEN ], *walk=outbuf;
333
334    /* add our public key (Ya) */
335    public_key = tr_cryptoGetMyPublicKey( handshake->crypto, &len );
336    assert( len == KEY_LEN );
337    assert( public_key );
338    memcpy( walk, public_key, len );
339    walk += len;
340
341    /* add some bullshit padding */
342    len = tr_cryptoRandInt( PadA_MAXLEN );
343    tr_cryptoRandBuf( walk, len );
344    walk += len;
345
346    /* send it */
347    setReadState( handshake, AWAITING_YB );
348    tr_peerIoWriteBytes( handshake->io, outbuf, walk - outbuf, FALSE );
349}
350
351static uint32_t
352getCryptoProvide( const tr_handshake * handshake )
353{
354    uint32_t provide = 0;
355
356    switch( handshake->encryptionMode )
357    {
358        case TR_ENCRYPTION_REQUIRED:
359        case TR_ENCRYPTION_PREFERRED:
360            provide |= CRYPTO_PROVIDE_CRYPTO;
361            break;
362
363        case TR_CLEAR_PREFERRED:
364            provide |= CRYPTO_PROVIDE_CRYPTO | CRYPTO_PROVIDE_PLAINTEXT;
365            break;
366    }
367
368    return provide;
369}
370
371static uint32_t
372getCryptoSelect( const tr_handshake * handshake,
373                 uint32_t             crypto_provide )
374{
375    uint32_t choices[2];
376    int      i, nChoices = 0;
377
378    switch( handshake->encryptionMode )
379    {
380        case TR_ENCRYPTION_REQUIRED:
381            choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
382            break;
383
384        case TR_ENCRYPTION_PREFERRED:
385            choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
386            choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
387            break;
388
389        case TR_CLEAR_PREFERRED:
390            choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
391            choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
392            break;
393    }
394
395    for( i = 0; i < nChoices; ++i )
396        if( crypto_provide & choices[i] )
397            return choices[i];
398
399    return 0;
400}
401
402static int
403readYb( tr_handshake * handshake, struct evbuffer * inbuf )
404{
405    int               isEncrypted;
406    const uint8_t *   secret;
407    uint8_t           yb[KEY_LEN];
408    struct evbuffer * outbuf;
409    size_t            needlen = HANDSHAKE_NAME_LEN;
410
411    if( evbuffer_get_length( inbuf ) < needlen )
412        return READ_LATER;
413
414    isEncrypted = memcmp( evbuffer_pullup( inbuf, HANDSHAKE_NAME_LEN ), HANDSHAKE_NAME, HANDSHAKE_NAME_LEN );
415    if( isEncrypted )
416    {
417        needlen = KEY_LEN;
418        if( evbuffer_get_length( inbuf ) < needlen )
419            return READ_LATER;
420    }
421
422    dbgmsg( handshake, "got a %s handshake",
423           ( isEncrypted ? "encrypted" : "plaintext" ) );
424
425    tr_peerIoSetEncryption( handshake->io, isEncrypted ? PEER_ENCRYPTION_RC4
426                                                       : PEER_ENCRYPTION_NONE );
427    if( !isEncrypted )
428    {
429        setState( handshake, AWAITING_HANDSHAKE );
430        return READ_NOW;
431    }
432
433    handshake->haveReadAnythingFromPeer = TRUE;
434
435    /* compute the secret */
436    evbuffer_remove( inbuf, yb, KEY_LEN );
437    secret = tr_cryptoComputeSecret( handshake->crypto, yb );
438    memcpy( handshake->mySecret, secret, KEY_LEN );
439
440    /* now send these: HASH('req1', S), HASH('req2', SKEY) xor HASH('req3', S),
441     * ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)), ENCRYPT(IA) */
442    outbuf = evbuffer_new( );
443
444    /* HASH('req1', S) */
445    {
446        uint8_t req1[SHA_DIGEST_LENGTH];
447        tr_sha1( req1, "req1", 4, secret, KEY_LEN, NULL );
448        evbuffer_add( outbuf, req1, SHA_DIGEST_LENGTH );
449    }
450
451    /* HASH('req2', SKEY) xor HASH('req3', S) */
452    {
453        int     i;
454        uint8_t req2[SHA_DIGEST_LENGTH];
455        uint8_t req3[SHA_DIGEST_LENGTH];
456        uint8_t buf[SHA_DIGEST_LENGTH];
457        tr_sha1( req2, "req2", 4,
458                 tr_cryptoGetTorrentHash( handshake->crypto ),
459                 SHA_DIGEST_LENGTH, NULL );
460        tr_sha1( req3, "req3", 4, secret, KEY_LEN, NULL );
461        for( i = 0; i < SHA_DIGEST_LENGTH; ++i )
462            buf[i] = req2[i] ^ req3[i];
463        evbuffer_add( outbuf, buf, SHA_DIGEST_LENGTH );
464    }
465
466    /* ENCRYPT(VC, crypto_provide, len(PadC), PadC
467     * PadC is reserved for future extensions to the handshake...
468     * standard practice at this time is for it to be zero-length */
469    {
470        uint8_t vc[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
471
472        tr_peerIoWriteBuf( handshake->io, outbuf, FALSE );
473        tr_cryptoEncryptInit( handshake->crypto );
474        tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_RC4 );
475
476        evbuffer_add        ( outbuf, vc, VC_LENGTH );
477        evbuffer_add_uint32 ( outbuf, getCryptoProvide( handshake ) );
478        evbuffer_add_uint16 ( outbuf, 0 );
479    }
480
481    /* ENCRYPT len(IA)), ENCRYPT(IA) */
482    {
483        uint8_t msg[HANDSHAKE_SIZE];
484        buildHandshakeMessage( handshake, msg );
485
486        evbuffer_add_uint16 ( outbuf, sizeof( msg ) );
487        evbuffer_add        ( outbuf, msg, sizeof( msg ) );
488
489        handshake->haveSentBitTorrentHandshake = 1;
490    }
491
492    /* send it */
493    tr_cryptoDecryptInit( handshake->crypto );
494    setReadState( handshake, AWAITING_VC );
495    tr_peerIoWriteBuf( handshake->io, outbuf, FALSE );
496
497    /* cleanup */
498    evbuffer_free( outbuf );
499    return READ_LATER;
500}
501
502static int
503readVC( tr_handshake *    handshake,
504        struct evbuffer * inbuf )
505{
506    const uint8_t key[VC_LENGTH] = { 0, 0, 0, 0, 0, 0, 0, 0 };
507    const int     key_len = VC_LENGTH;
508    uint8_t       tmp[VC_LENGTH];
509
510    /* note: this works w/o having to `unwind' the buffer if
511     * we read too much, but it is pretty brute-force.
512     * it would be nice to make this cleaner. */
513    for( ; ; )
514    {
515        if( evbuffer_get_length( inbuf ) < VC_LENGTH )
516        {
517            dbgmsg( handshake, "not enough bytes... returning read_more" );
518            return READ_LATER;
519        }
520
521        memcpy( tmp, evbuffer_pullup( inbuf, key_len ), key_len );
522        tr_cryptoDecryptInit( handshake->crypto );
523        tr_cryptoDecrypt( handshake->crypto, key_len, tmp, tmp );
524        if( !memcmp( tmp, key, key_len ) )
525            break;
526
527        evbuffer_drain( inbuf, 1 );
528    }
529
530    dbgmsg( handshake, "got it!" );
531    evbuffer_drain( inbuf, key_len );
532    setState( handshake, AWAITING_CRYPTO_SELECT );
533    return READ_NOW;
534}
535
536static int
537readCryptoSelect( tr_handshake *    handshake,
538                  struct evbuffer * inbuf )
539{
540    uint32_t     crypto_select;
541    uint16_t     pad_d_len;
542    const size_t needlen = sizeof( uint32_t ) + sizeof( uint16_t );
543
544    if( evbuffer_get_length( inbuf ) < needlen )
545        return READ_LATER;
546
547    tr_peerIoReadUint32( handshake->io, inbuf, &crypto_select );
548    handshake->crypto_select = crypto_select;
549    dbgmsg( handshake, "crypto select is %d", (int)crypto_select );
550    if( !( crypto_select & getCryptoProvide( handshake ) ) )
551    {
552        dbgmsg( handshake,
553                "peer selected an encryption option we didn't provide" );
554        return tr_handshakeDone( handshake, FALSE );
555    }
556
557    tr_peerIoReadUint16( handshake->io, inbuf, &pad_d_len );
558    dbgmsg( handshake, "pad_d_len is %d", (int)pad_d_len );
559
560    if( pad_d_len > 512 )
561    {
562        dbgmsg( handshake, "encryption handshake: pad_d_len is too long" );
563        return tr_handshakeDone( handshake, FALSE );
564    }
565
566    handshake->pad_d_len = pad_d_len;
567
568    setState( handshake, AWAITING_PAD_D );
569    return READ_NOW;
570}
571
572static int
573readPadD( tr_handshake *    handshake,
574          struct evbuffer * inbuf )
575{
576    const size_t needlen = handshake->pad_d_len;
577    uint8_t *    tmp;
578
579    dbgmsg( handshake, "pad d: need %zu, got %zu",
580            needlen, evbuffer_get_length( inbuf ) );
581    if( evbuffer_get_length( inbuf ) < needlen )
582        return READ_LATER;
583
584    tmp = tr_new( uint8_t, needlen );
585    tr_peerIoReadBytes( handshake->io, inbuf, tmp, needlen );
586    tr_free( tmp );
587
588    tr_peerIoSetEncryption( handshake->io, handshake->crypto_select );
589
590    setState( handshake, AWAITING_HANDSHAKE );
591    return READ_NOW;
592}
593
594/***
595****
596****  INCOMING CONNECTIONS
597****
598***/
599
600static int
601readHandshake( tr_handshake *    handshake,
602               struct evbuffer * inbuf )
603{
604    uint8_t   pstrlen;
605    uint8_t * pstr;
606    uint8_t   reserved[HANDSHAKE_FLAGS_LEN];
607    uint8_t   hash[SHA_DIGEST_LENGTH];
608
609    dbgmsg( handshake, "payload: need %d, got %zu",
610            INCOMING_HANDSHAKE_LEN, evbuffer_get_length( inbuf ) );
611
612    if( evbuffer_get_length( inbuf ) < INCOMING_HANDSHAKE_LEN )
613        return READ_LATER;
614
615    handshake->haveReadAnythingFromPeer = TRUE;
616
617    pstrlen = evbuffer_pullup( inbuf, 1 )[0]; /* peek, don't read. We may be
618                                                 handing inbuf to AWAITING_YA */
619
620    if( pstrlen == 19 ) /* unencrypted */
621    {
622        tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_NONE );
623
624        if( handshake->encryptionMode == TR_ENCRYPTION_REQUIRED )
625        {
626            dbgmsg( handshake,
627                    "peer is unencrypted, and we're disallowing that" );
628            return tr_handshakeDone( handshake, FALSE );
629        }
630    }
631    else /* encrypted or corrupt */
632    {
633        tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_RC4 );
634
635        if( tr_peerIoIsIncoming( handshake->io ) )
636        {
637            dbgmsg( handshake,
638                    "I think peer is sending us an encrypted handshake..." );
639            setState( handshake, AWAITING_YA );
640            return READ_NOW;
641        }
642        tr_cryptoDecrypt( handshake->crypto, 1, &pstrlen, &pstrlen );
643
644        if( pstrlen != 19 )
645        {
646            dbgmsg( handshake,
647                    "I think peer has sent us a corrupt handshake..." );
648            return tr_handshakeDone( handshake, FALSE );
649        }
650    }
651
652    evbuffer_drain( inbuf, 1 );
653
654    /* pstr (BitTorrent) */
655    pstr = tr_new( uint8_t, pstrlen + 1 );
656    tr_peerIoReadBytes( handshake->io, inbuf, pstr, pstrlen );
657    pstr[pstrlen] = '\0';
658    if( strcmp( (char*)pstr, "BitTorrent protocol" ) )
659    {
660        tr_free( pstr );
661        return tr_handshakeDone( handshake, FALSE );
662    }
663    tr_free( pstr );
664
665    /* reserved bytes */
666    tr_peerIoReadBytes( handshake->io, inbuf, reserved, sizeof( reserved ) );
667
668    /**
669    *** Extensions
670    **/
671
672    tr_peerIoEnableLTEP( handshake->io, HANDSHAKE_HAS_LTEP( reserved ) );
673
674    tr_peerIoEnableFEXT( handshake->io, HANDSHAKE_HAS_FASTEXT( reserved ) );
675
676    tr_peerIoEnableDHT( handshake->io, HANDSHAKE_HAS_DHT( reserved ) );
677
678    /* torrent hash */
679    tr_peerIoReadBytes( handshake->io, inbuf, hash, sizeof( hash ) );
680    if( tr_peerIoIsIncoming( handshake->io ) )
681    {
682        if( !tr_torrentExists( handshake->session, hash ) )
683        {
684            dbgmsg( handshake, "peer is trying to connect to us for a torrent we don't have." );
685            return tr_handshakeDone( handshake, FALSE );
686        }
687        else
688        {
689            assert( !tr_peerIoHasTorrentHash( handshake->io ) );
690            tr_peerIoSetTorrentHash( handshake->io, hash );
691        }
692    }
693    else /* outgoing */
694    {
695        assert( tr_peerIoHasTorrentHash( handshake->io ) );
696        if( memcmp( hash, tr_peerIoGetTorrentHash( handshake->io ),
697                    SHA_DIGEST_LENGTH ) )
698        {
699            dbgmsg( handshake, "peer returned the wrong hash. wtf?" );
700            return tr_handshakeDone( handshake, FALSE );
701        }
702    }
703
704    /**
705    ***  If it's an incoming message, we need to send a response handshake
706    **/
707
708    if( !handshake->haveSentBitTorrentHandshake )
709    {
710        uint8_t msg[HANDSHAKE_SIZE];
711        buildHandshakeMessage( handshake, msg );
712        tr_peerIoWriteBytes( handshake->io, msg, sizeof( msg ), FALSE );
713        handshake->haveSentBitTorrentHandshake = 1;
714    }
715
716    setReadState( handshake, AWAITING_PEER_ID );
717    return READ_NOW;
718}
719
720static int
721readPeerId( tr_handshake    * handshake,
722            struct evbuffer * inbuf )
723{
724    tr_bool peerIsGood;
725    char client[128];
726    tr_torrent * tor;
727    const uint8_t * tor_peer_id;
728    uint8_t peer_id[PEER_ID_LEN];
729
730    if( evbuffer_get_length( inbuf ) < PEER_ID_LEN )
731        return READ_LATER;
732
733    /* peer id */
734    tr_peerIoReadBytes( handshake->io, inbuf, peer_id, PEER_ID_LEN );
735    tr_peerIoSetPeersId( handshake->io, peer_id );
736    handshake->havePeerID = TRUE;
737    tr_clientForId( client, sizeof( client ), peer_id );
738    dbgmsg( handshake, "peer-id is [%s] ... isIncoming is %d", client,
739            tr_peerIoIsIncoming( handshake->io ) );
740
741    /* if we've somehow connected to ourselves, don't keep the connection */
742    tor = tr_torrentFindFromHash( handshake->session, tr_peerIoGetTorrentHash( handshake->io ) );
743    tor_peer_id = tor ? tor->peer_id : tr_getPeerId( handshake->session );
744    peerIsGood = memcmp( peer_id, tor_peer_id, PEER_ID_LEN ) != 0;
745    dbgmsg( handshake, "isPeerGood == %d", (int)peerIsGood );
746    return tr_handshakeDone( handshake, peerIsGood );
747}
748
749static int
750readYa( tr_handshake *    handshake,
751        struct evbuffer * inbuf )
752{
753    uint8_t        ya[KEY_LEN];
754    uint8_t *      walk, outbuf[KEY_LEN + PadB_MAXLEN];
755    const uint8_t *myKey, *secret;
756    int            len;
757
758    dbgmsg( handshake, "in readYa... need %d, have %zu",
759            KEY_LEN, evbuffer_get_length( inbuf ) );
760    if( evbuffer_get_length( inbuf ) < KEY_LEN )
761        return READ_LATER;
762
763    /* read the incoming peer's public key */
764    evbuffer_remove( inbuf, ya, KEY_LEN );
765    secret = tr_cryptoComputeSecret( handshake->crypto, ya );
766    memcpy( handshake->mySecret, secret, KEY_LEN );
767    tr_sha1( handshake->myReq1, "req1", 4, secret, KEY_LEN, NULL );
768
769    dbgmsg( handshake, "sending B->A: Diffie Hellman Yb, PadB" );
770    /* send our public key to the peer */
771    walk = outbuf;
772    myKey = tr_cryptoGetMyPublicKey( handshake->crypto, &len );
773    memcpy( walk, myKey, len );
774    walk += len;
775    len = tr_cryptoRandInt( PadB_MAXLEN );
776    tr_cryptoRandBuf( walk, len );
777    walk += len;
778
779    setReadState( handshake, AWAITING_PAD_A );
780    tr_peerIoWriteBytes( handshake->io, outbuf, walk - outbuf, FALSE );
781    return READ_NOW;
782}
783
784static int
785readPadA( tr_handshake * handshake, struct evbuffer * inbuf )
786{
787    /* resynchronizing on HASH('req1',S) */
788    struct evbuffer_ptr ptr = evbuffer_search( inbuf, (const char*)handshake->myReq1, SHA_DIGEST_LENGTH, NULL );
789
790    if( ptr.pos != -1 ) /* match */
791    {
792        evbuffer_drain( inbuf, ptr.pos );
793        dbgmsg( handshake, "found it... looking setting to awaiting_crypto_provide" );
794        setState( handshake, AWAITING_CRYPTO_PROVIDE );
795        return READ_NOW;
796    }
797    else
798    {
799        const size_t len = evbuffer_get_length( inbuf );
800        if( len > SHA_DIGEST_LENGTH )
801            evbuffer_drain( inbuf, len - SHA_DIGEST_LENGTH );
802        return READ_LATER;
803    }
804}
805
806static int
807readCryptoProvide( tr_handshake *    handshake,
808                   struct evbuffer * inbuf )
809{
810    /* HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide,
811      len(PadC)) */
812
813    int          i;
814    uint8_t      vc_in[VC_LENGTH];
815    uint8_t      req2[SHA_DIGEST_LENGTH];
816    uint8_t      req3[SHA_DIGEST_LENGTH];
817    uint8_t      obfuscatedTorrentHash[SHA_DIGEST_LENGTH];
818    uint16_t     padc_len = 0;
819    uint32_t     crypto_provide = 0;
820    const size_t needlen = SHA_DIGEST_LENGTH /* HASH('req1',s) */
821                           + SHA_DIGEST_LENGTH /* HASH('req2', SKEY) xor
822                                                 HASH('req3', S) */
823                           + VC_LENGTH
824                           + sizeof( crypto_provide )
825                           + sizeof( padc_len );
826    tr_torrent * tor = NULL;
827
828    if( evbuffer_get_length( inbuf ) < needlen )
829        return READ_LATER;
830
831    /* TODO: confirm they sent HASH('req1',S) here? */
832    evbuffer_drain( inbuf, SHA_DIGEST_LENGTH );
833
834    /* This next piece is HASH('req2', SKEY) xor HASH('req3', S) ...
835     * we can get the first half of that (the obufscatedTorrentHash)
836     * by building the latter and xor'ing it with what the peer sent us */
837    dbgmsg( handshake, "reading obfuscated torrent hash..." );
838    evbuffer_remove( inbuf, req2, SHA_DIGEST_LENGTH );
839    tr_sha1( req3, "req3", 4, handshake->mySecret, KEY_LEN, NULL );
840    for( i = 0; i < SHA_DIGEST_LENGTH; ++i )
841        obfuscatedTorrentHash[i] = req2[i] ^ req3[i];
842    if(( tor = tr_torrentFindFromObfuscatedHash( handshake->session, obfuscatedTorrentHash )))
843    {
844        const tr_bool clientIsSeed = tr_torrentIsSeed( tor );
845        const tr_bool peerIsSeed = tr_peerMgrPeerIsSeed( tor, tr_peerIoGetAddress( handshake->io, NULL ) );
846        dbgmsg( handshake, "got INCOMING connection's encrypted handshake for torrent [%s]",
847                tr_torrentName( tor ) );
848        tr_peerIoSetTorrentHash( handshake->io, tor->info.hash );
849
850        if( clientIsSeed && peerIsSeed )
851        {
852            dbgmsg( handshake, "another seed tried to reconnect to us!" );
853            return tr_handshakeDone( handshake, FALSE );
854        }
855    }
856    else
857    {
858        dbgmsg( handshake, "can't find that torrent..." );
859        return tr_handshakeDone( handshake, FALSE );
860    }
861
862    /* next part: ENCRYPT(VC, crypto_provide, len(PadC), */
863
864    tr_cryptoDecryptInit( handshake->crypto );
865
866    tr_peerIoReadBytes( handshake->io, inbuf, vc_in, VC_LENGTH );
867
868    tr_peerIoReadUint32( handshake->io, inbuf, &crypto_provide );
869    handshake->crypto_provide = crypto_provide;
870    dbgmsg( handshake, "crypto_provide is %d", (int)crypto_provide );
871
872    tr_peerIoReadUint16( handshake->io, inbuf, &padc_len );
873    dbgmsg( handshake, "padc is %d", (int)padc_len );
874    handshake->pad_c_len = padc_len;
875    setState( handshake, AWAITING_PAD_C );
876    return READ_NOW;
877}
878
879static int
880readPadC( tr_handshake *    handshake,
881          struct evbuffer * inbuf )
882{
883    uint16_t     ia_len;
884    const size_t needlen = handshake->pad_c_len + sizeof( uint16_t );
885
886    if( evbuffer_get_length( inbuf ) < needlen )
887        return READ_LATER;
888
889    evbuffer_drain( inbuf, handshake->pad_c_len );
890
891    tr_peerIoReadUint16( handshake->io, inbuf, &ia_len );
892    dbgmsg( handshake, "ia_len is %d", (int)ia_len );
893    handshake->ia_len = ia_len;
894    setState( handshake, AWAITING_IA );
895    return READ_NOW;
896}
897
898static int
899readIA( tr_handshake *    handshake,
900        struct evbuffer * inbuf )
901{
902    const size_t      needlen = handshake->ia_len;
903    struct evbuffer * outbuf;
904    uint32_t          crypto_select;
905
906    dbgmsg( handshake, "reading IA... have %zu, need %zu",
907            evbuffer_get_length( inbuf ), needlen );
908    if( evbuffer_get_length( inbuf ) < needlen )
909        return READ_LATER;
910
911    /**
912    ***  B->A: ENCRYPT(VC, crypto_select, len(padD), padD), ENCRYPT2(Payload Stream)
913    **/
914
915    tr_cryptoEncryptInit( handshake->crypto );
916    outbuf = evbuffer_new( );
917
918    dbgmsg( handshake, "sending vc" );
919    /* send VC */
920    {
921        uint8_t vc[VC_LENGTH];
922        memset( vc, 0, VC_LENGTH );
923        evbuffer_add( outbuf, vc, VC_LENGTH );
924    }
925
926    /* send crypto_select */
927    crypto_select = getCryptoSelect( handshake, handshake->crypto_provide );
928    if( crypto_select )
929    {
930        dbgmsg( handshake, "selecting crypto mode '%d'", (int)crypto_select );
931        evbuffer_add_uint32( outbuf, crypto_select );
932    }
933    else
934    {
935        dbgmsg( handshake, "peer didn't offer an encryption mode we like." );
936        evbuffer_free( outbuf );
937        return tr_handshakeDone( handshake, FALSE );
938    }
939
940    dbgmsg( handshake, "sending pad d" );
941    /* ENCRYPT(VC, crypto_provide, len(PadD), PadD
942     * PadD is reserved for future extensions to the handshake...
943     * standard practice at this time is for it to be zero-length */
944    {
945        const uint16_t len = 0;
946        evbuffer_add_uint16( outbuf, len );
947    }
948
949    /* maybe de-encrypt our connection */
950    if( crypto_select == CRYPTO_PROVIDE_PLAINTEXT )
951    {
952        tr_peerIoWriteBuf( handshake->io, outbuf, FALSE );
953        tr_peerIoSetEncryption( handshake->io, PEER_ENCRYPTION_NONE );
954    }
955
956    dbgmsg( handshake, "sending handshake" );
957    /* send our handshake */
958    {
959        uint8_t msg[HANDSHAKE_SIZE];
960        buildHandshakeMessage( handshake, msg );
961
962        evbuffer_add( outbuf, msg, sizeof( msg ) );
963        handshake->haveSentBitTorrentHandshake = 1;
964    }
965
966    /* send it out */
967    tr_peerIoWriteBuf( handshake->io, outbuf, FALSE );
968    evbuffer_free( outbuf );
969
970    /* now await the handshake */
971    setState( handshake, AWAITING_PAYLOAD_STREAM );
972    return READ_NOW;
973}
974
975static int
976readPayloadStream( tr_handshake    * handshake,
977                   struct evbuffer * inbuf )
978{
979    int i;
980    const size_t      needlen = HANDSHAKE_SIZE;
981
982    dbgmsg( handshake, "reading payload stream... have %zu, need %zu",
983            evbuffer_get_length( inbuf ), needlen );
984    if( evbuffer_get_length( inbuf ) < needlen )
985        return READ_LATER;
986
987    /* parse the handshake ... */
988    i = parseHandshake( handshake, inbuf );
989    dbgmsg( handshake, "parseHandshake returned %d", i );
990    if( i != HANDSHAKE_OK )
991        return tr_handshakeDone( handshake, FALSE );
992
993    /* we've completed the BT handshake... pass the work on to peer-msgs */
994    return tr_handshakeDone( handshake, TRUE );
995}
996
997/***
998****
999****
1000****
1001***/
1002
1003static ReadState
1004canRead( struct tr_peerIo * io, void * arg, size_t * piece )
1005{
1006    tr_handshake    * handshake = arg;
1007    struct evbuffer * inbuf = tr_peerIoGetReadBuffer( io );
1008    ReadState         ret;
1009    tr_bool           readyForMore = TRUE;
1010
1011    assert( tr_isPeerIo( io ) );
1012
1013    /* no piece data in handshake */
1014    *piece = 0;
1015
1016    dbgmsg( handshake, "handling canRead; state is [%s]",
1017           getStateName( handshake->state ) );
1018
1019    while( readyForMore )
1020    {
1021        switch( handshake->state )
1022        {
1023            case AWAITING_HANDSHAKE:
1024                ret = readHandshake    ( handshake, inbuf ); break;
1025
1026            case AWAITING_PEER_ID:
1027                ret = readPeerId       ( handshake, inbuf ); break;
1028
1029            case AWAITING_YA:
1030                ret = readYa           ( handshake, inbuf ); break;
1031
1032            case AWAITING_PAD_A:
1033                ret = readPadA         ( handshake, inbuf ); break;
1034
1035            case AWAITING_CRYPTO_PROVIDE:
1036                ret = readCryptoProvide( handshake, inbuf ); break;
1037
1038            case AWAITING_PAD_C:
1039                ret = readPadC         ( handshake, inbuf ); break;
1040
1041            case AWAITING_IA:
1042                ret = readIA           ( handshake, inbuf ); break;
1043
1044            case AWAITING_PAYLOAD_STREAM:
1045                ret = readPayloadStream( handshake, inbuf ); break;
1046
1047            case AWAITING_YB:
1048                ret = readYb           ( handshake, inbuf ); break;
1049
1050            case AWAITING_VC:
1051                ret = readVC           ( handshake, inbuf ); break;
1052
1053            case AWAITING_CRYPTO_SELECT:
1054                ret = readCryptoSelect ( handshake, inbuf ); break;
1055
1056            case AWAITING_PAD_D:
1057                ret = readPadD         ( handshake, inbuf ); break;
1058
1059            default:
1060                assert( 0 );
1061        }
1062
1063        if( ret != READ_NOW )
1064            readyForMore = FALSE;
1065        else if( handshake->state == AWAITING_PAD_C )
1066            readyForMore = evbuffer_get_length( inbuf ) >= handshake->pad_c_len;
1067        else if( handshake->state == AWAITING_PAD_D )
1068            readyForMore = evbuffer_get_length( inbuf ) >= handshake->pad_d_len;
1069        else if( handshake->state == AWAITING_IA )
1070            readyForMore = evbuffer_get_length( inbuf ) >= handshake->ia_len;
1071    }
1072
1073    return ret;
1074}
1075
1076static tr_bool
1077fireDoneFunc( tr_handshake * handshake, tr_bool isConnected )
1078{
1079    const uint8_t * peer_id = isConnected && handshake->havePeerID
1080                            ? tr_peerIoGetPeersId( handshake->io )
1081                            : NULL;
1082    const tr_bool success = ( *handshake->doneCB )( handshake,
1083                                                    handshake->io,
1084                                                    handshake->haveReadAnythingFromPeer,
1085                                                    isConnected,
1086                                                    peer_id,
1087                                                    handshake->doneUserData );
1088
1089    return success;
1090}
1091
1092static void
1093tr_handshakeFree( tr_handshake * handshake )
1094{
1095    if( handshake->io )
1096        tr_peerIoUnref( handshake->io ); /* balanced by the ref in tr_handshakeNew */
1097
1098    event_free( handshake->timeout_timer );
1099    tr_free( handshake );
1100}
1101
1102static int
1103tr_handshakeDone( tr_handshake * handshake,
1104                  tr_bool        isOK )
1105{
1106    tr_bool success;
1107
1108    dbgmsg( handshake, "handshakeDone: %s", isOK ? "connected" : "aborting" );
1109    tr_peerIoSetIOFuncs( handshake->io, NULL, NULL, NULL, NULL );
1110
1111    success = fireDoneFunc( handshake, isOK );
1112
1113    tr_handshakeFree( handshake );
1114
1115    return success ? READ_LATER : READ_ERR;
1116}
1117
1118void
1119tr_handshakeAbort( tr_handshake * handshake )
1120{
1121    if( handshake != NULL )
1122        tr_handshakeDone( handshake, FALSE );
1123}
1124
1125static void
1126gotError( tr_peerIo  * io,
1127          short        what,
1128          void       * vhandshake )
1129{
1130    int errcode = errno;
1131    tr_handshake * handshake = vhandshake;
1132
1133    if( io->utp_socket && !io->isIncoming && handshake->state == AWAITING_YB ) {
1134        /* This peer probably doesn't speak uTP. */
1135        tr_torrent *tor =
1136            tr_peerIoHasTorrentHash( io ) ?
1137            tr_torrentFindFromHash( handshake->session,
1138                                    tr_peerIoGetTorrentHash( io ) ) :
1139            NULL;
1140        /* Don't mark a peer as non-uTP unless it's really a connect failure. */
1141        if( tor && ( errcode == ETIMEDOUT || errcode == ECONNREFUSED ) ) {
1142            tr_torrentLock( tor );
1143            tr_peerMgrSetUtpFailed( tor,
1144                                    tr_peerIoGetAddress( io, NULL ),
1145                                    TRUE );
1146            tr_torrentUnlock( tor );
1147        }
1148
1149        if( !tr_peerIoReconnect( handshake->io ) ) {
1150            uint8_t msg[HANDSHAKE_SIZE];
1151            buildHandshakeMessage( handshake, msg );
1152            handshake->haveSentBitTorrentHandshake = 1;
1153            setReadState( handshake, AWAITING_HANDSHAKE );
1154            tr_peerIoWriteBytes( handshake->io, msg, sizeof( msg ), FALSE );
1155        }
1156    }
1157
1158    /* if the error happened while we were sending a public key, we might
1159     * have encountered a peer that doesn't do encryption... reconnect and
1160     * try a plaintext handshake */
1161    if( ( ( handshake->state == AWAITING_YB )
1162        || ( handshake->state == AWAITING_VC ) )
1163      && ( handshake->encryptionMode != TR_ENCRYPTION_REQUIRED )
1164      && ( !tr_peerIoReconnect( handshake->io ) ) )
1165    {
1166        uint8_t msg[HANDSHAKE_SIZE];
1167
1168        dbgmsg( handshake, "handshake failed, trying plaintext..." );
1169        buildHandshakeMessage( handshake, msg );
1170        handshake->haveSentBitTorrentHandshake = 1;
1171        setReadState( handshake, AWAITING_HANDSHAKE );
1172        tr_peerIoWriteBytes( handshake->io, msg, sizeof( msg ), FALSE );
1173    }
1174    else
1175    {
1176        dbgmsg( handshake, "libevent got an error what==%d, errno=%d (%s)",
1177               (int)what, errno, tr_strerror( errno ) );
1178        tr_handshakeDone( handshake, FALSE );
1179    }
1180}
1181
1182/**
1183***
1184**/
1185
1186static void
1187handshakeTimeout( int foo UNUSED, short bar UNUSED, void * handshake )
1188{
1189    tr_handshakeAbort( handshake );
1190}
1191
1192tr_handshake*
1193tr_handshakeNew( tr_peerIo           * io,
1194                 tr_encryption_mode    encryptionMode,
1195                 handshakeDoneCB       doneCB,
1196                 void                * doneUserData )
1197{
1198    tr_handshake * handshake;
1199    tr_session * session = tr_peerIoGetSession( io );
1200
1201    handshake = tr_new0( tr_handshake, 1 );
1202    handshake->io = io;
1203    handshake->crypto = tr_peerIoGetCrypto( io );
1204    handshake->encryptionMode = encryptionMode;
1205    handshake->doneCB = doneCB;
1206    handshake->doneUserData = doneUserData;
1207    handshake->session = session;
1208    handshake->timeout_timer = evtimer_new( session->event_base, handshakeTimeout, handshake );
1209    tr_timerAdd( handshake->timeout_timer, HANDSHAKE_TIMEOUT_SEC, 0 );
1210
1211    tr_peerIoRef( io ); /* balanced by the unref in tr_handshakeFree */
1212    tr_peerIoSetIOFuncs( handshake->io, canRead, NULL, gotError, handshake );
1213    tr_peerIoSetEncryption( io, PEER_ENCRYPTION_NONE );
1214
1215    if( tr_peerIoIsIncoming( handshake->io ) )
1216        setReadState( handshake, AWAITING_HANDSHAKE );
1217    else if( encryptionMode != TR_CLEAR_PREFERRED )
1218        sendYa( handshake );
1219    else
1220    {
1221        uint8_t msg[HANDSHAKE_SIZE];
1222        buildHandshakeMessage( handshake, msg );
1223
1224        handshake->haveSentBitTorrentHandshake = 1;
1225        setReadState( handshake, AWAITING_HANDSHAKE );
1226        tr_peerIoWriteBytes( handshake->io, msg, sizeof( msg ), FALSE );
1227    }
1228
1229    return handshake;
1230}
1231
1232struct tr_peerIo*
1233tr_handshakeGetIO( tr_handshake * handshake )
1234{
1235    assert( handshake );
1236    assert( handshake->io );
1237
1238    return handshake->io;
1239}
1240
1241struct tr_peerIo*
1242tr_handshakeStealIO( tr_handshake * handshake )
1243{
1244    struct tr_peerIo * io;
1245
1246    assert( handshake );
1247    assert( handshake->io );
1248
1249    io = handshake->io;
1250    handshake->io = NULL;
1251    return io;
1252}
1253
1254const tr_address *
1255tr_handshakeGetAddr( const struct tr_handshake * handshake,
1256                     tr_port                   * port )
1257{
1258    assert( handshake );
1259    assert( handshake->io );
1260
1261    return tr_peerIoGetAddress( handshake->io, port );
1262}
1263
Note: See TracBrowser for help on using the repository browser.