source: trunk/libtransmission/handshake.c @ 6050

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

fix handshake.c crash reported by wereHamster

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