source: branches/1.7x/libtransmission/handshake.c @ 9366

Last change on this file since 9366 was 9366, checked in by charles, 13 years ago

(1.7x) backports for 1.76: r9353 #2510 Port message never sent to outgoing peer connections

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