source: trunk/libtransmission/handshake.c @ 11599

Last change on this file since 11599 was 11599, checked in by charles, 11 years ago

(trunk) Join the 21st century and use only 1 space at the end sentences. This commit is nearly as important as the semi-annual ones that remove trailing spaces from the ends of lines of code... :)

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