source: trunk/libtransmission/handshake.c @ 3397

Last change on this file since 3397 was 3397, checked in by charles, 15 years ago

try to get more connected peers to agree to encrypted connections

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