source: trunk/libtransmission/handshake.c @ 5632

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

(1) fix choke/unchoke error. (2) if a peer keeps trying to reconnect to us, hang up during the handshake.

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