2 * This file Copyright (C) 2007-2010 Mnemosyne LLC
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.
10 * $Id: handshake.c 10912 2010-06-30 16:40:19Z charles $
16 #include <limits.h> /* UCHAR_MAX */
22 #include "transmission.h"
26 #include "handshake.h"
34 /* enable LibTransmission extension protocol */
35 #define ENABLE_LTEP * /
37 #define ENABLE_FAST * /
39 #define ENABLE_DHT * /
45 #define HANDSHAKE_NAME "\023BitTorrent protocol"
49 /* BitTorrent Handshake Constants */
50 HANDSHAKE_NAME_LEN
= 20,
51 HANDSHAKE_FLAGS_LEN
= 8,
54 INCOMING_HANDSHAKE_LEN
= 48,
56 /* Encryption Constants */
63 CRYPTO_PROVIDE_PLAINTEXT
= 1,
64 CRYPTO_PROVIDE_CRYPTO
= 2,
66 /* how long to wait before giving up on a handshake */
67 HANDSHAKE_TIMEOUT_SEC
= 30
72 #define HANDSHAKE_HAS_LTEP( bits ) ( ( ( bits )[5] & 0x10 ) ? 1 : 0 )
73 #define HANDSHAKE_SET_LTEP( bits ) ( ( bits )[5] |= 0x10 )
75 #define HANDSHAKE_HAS_LTEP( bits ) ( 0 )
76 #define HANDSHAKE_SET_LTEP( bits ) ( (void)0 )
80 #define HANDSHAKE_HAS_FASTEXT( bits ) ( ( ( bits )[7] & 0x04 ) ? 1 : 0 )
81 #define HANDSHAKE_SET_FASTEXT( bits ) ( ( bits )[7] |= 0x04 )
83 #define HANDSHAKE_HAS_FASTEXT( bits ) ( 0 )
84 #define HANDSHAKE_SET_FASTEXT( bits ) ( (void)0 )
88 #define HANDSHAKE_HAS_DHT( bits ) ( ( ( bits )[7] & 0x01 ) ? 1 : 0 )
89 #define HANDSHAKE_SET_DHT( bits ) ( ( bits )[7] |= 0x01 )
91 #define HANDSHAKE_HAS_DHT( bits ) ( 0 )
92 #define HANDSHAKE_SET_DHT( bits ) ( (void)0 )
95 /* http://www.azureuswiki.com/index.php/Extension_negotiation_protocol
96 these macros are to be used if both extended messaging and the
97 azureus protocol is supported, they indicate which protocol is preferred */
98 #define HANDSHAKE_GET_EXTPREF( reserved ) ( ( reserved )[5] & 0x03 )
99 #define HANDSHAKE_SET_EXTPREF( reserved, val ) ( ( reserved )[5] |= 0x03 &\
102 typedef uint8_t handshake_state_t
;
106 tr_bool haveReadAnythingFromPeer
;
108 tr_bool haveSentBitTorrentHandshake
;
111 tr_session
* session
;
112 uint8_t mySecret
[KEY_LEN
];
113 handshake_state_t state
;
114 tr_encryption_mode encryptionMode
;
118 uint32_t crypto_select
;
119 uint32_t crypto_provide
;
120 uint8_t myReq1
[SHA_DIGEST_LENGTH
];
121 handshakeDoneCB doneCB
;
123 struct event timeout_timer
;
137 AWAITING_CRYPTO_PROVIDE
,
140 AWAITING_PAYLOAD_STREAM
,
145 AWAITING_CRYPTO_SELECT
,
153 #define dbgmsg( handshake, ... ) \
155 if( tr_deepLoggingIsActive( ) ) \
156 tr_deepLog( __FILE__, __LINE__, tr_peerIoGetAddrStr( handshake->io ), __VA_ARGS__ ); \
160 getStateName( const handshake_state_t state
)
162 const char * str
= "f00!";
166 case AWAITING_HANDSHAKE
:
167 str
= "awaiting handshake"; break;
169 case AWAITING_PEER_ID
:
170 str
= "awaiting peer id"; break;
173 str
= "awaiting ya"; break;
176 str
= "awaiting pad a"; break;
178 case AWAITING_CRYPTO_PROVIDE
:
179 str
= "awaiting crypto_provide"; break;
182 str
= "awaiting pad c"; break;
185 str
= "awaiting ia"; break;
188 str
= "awaiting yb"; break;
191 str
= "awaiting vc"; break;
193 case AWAITING_CRYPTO_SELECT
:
194 str
= "awaiting crypto select"; break;
197 str
= "awaiting pad d"; break;
203 setState( tr_handshake
* handshake
, handshake_state_t state
)
205 dbgmsg( handshake
, "setting to state [%s]", getStateName( state
) );
206 handshake
->state
= state
;
210 setReadState( tr_handshake
* handshake
, handshake_state_t state
)
212 setState( handshake
, state
);
216 buildHandshakeMessage( tr_handshake
* handshake
, uint8_t * buf
)
218 uint8_t * walk
= buf
;
219 const uint8_t * torrentHash
= tr_cryptoGetTorrentHash( handshake
->crypto
);
220 const tr_torrent
* tor
= tr_torrentFindFromHash( handshake
->session
, torrentHash
);
221 const uint8_t * peer_id
= tor
&& tor
->peer_id
? tor
->peer_id
: tr_getPeerId( );
223 memcpy( walk
, HANDSHAKE_NAME
, HANDSHAKE_NAME_LEN
);
224 walk
+= HANDSHAKE_NAME_LEN
;
225 memset( walk
, 0, HANDSHAKE_FLAGS_LEN
);
226 HANDSHAKE_SET_LTEP( walk
);
227 HANDSHAKE_SET_FASTEXT( walk
);
229 /* Note that this doesn't depend on whether the torrent is private.
230 * We don't accept DHT peers for a private torrent,
231 * but we participate in the DHT regardless. */
232 if( tr_dhtEnabled( handshake
->session
) )
233 HANDSHAKE_SET_DHT( walk
);
235 walk
+= HANDSHAKE_FLAGS_LEN
;
236 memcpy( walk
, torrentHash
, SHA_DIGEST_LENGTH
);
237 walk
+= SHA_DIGEST_LENGTH
;
238 memcpy( walk
, peer_id
, PEER_ID_LEN
);
241 assert( strlen( ( const char* )peer_id
) == PEER_ID_LEN
);
242 assert( walk
- buf
== HANDSHAKE_SIZE
);
245 static int tr_handshakeDone( tr_handshake
* handshake
,
246 tr_bool isConnected
);
251 HANDSHAKE_ENCRYPTION_WRONG
,
252 HANDSHAKE_BAD_TORRENT
,
253 HANDSHAKE_PEER_IS_SELF
,
257 parseHandshake( tr_handshake
* handshake
,
258 struct evbuffer
* inbuf
)
260 uint8_t name
[HANDSHAKE_NAME_LEN
];
261 uint8_t reserved
[HANDSHAKE_FLAGS_LEN
];
262 uint8_t hash
[SHA_DIGEST_LENGTH
];
263 const tr_torrent
* tor
;
264 const uint8_t * tor_peer_id
;
265 uint8_t peer_id
[PEER_ID_LEN
];
267 dbgmsg( handshake
, "payload: need %d, got %zu",
268 (int)HANDSHAKE_SIZE
, EVBUFFER_LENGTH( inbuf
) );
270 if( EVBUFFER_LENGTH( inbuf
) < HANDSHAKE_SIZE
)
273 /* confirm the protocol */
274 tr_peerIoReadBytes( handshake
->io
, inbuf
, name
, HANDSHAKE_NAME_LEN
);
275 if( memcmp( name
, HANDSHAKE_NAME
, HANDSHAKE_NAME_LEN
) )
276 return HANDSHAKE_ENCRYPTION_WRONG
;
278 /* read the reserved bytes */
279 tr_peerIoReadBytes( handshake
->io
, inbuf
, reserved
, HANDSHAKE_FLAGS_LEN
);
282 tr_peerIoReadBytes( handshake
->io
, inbuf
, hash
, sizeof( hash
) );
283 assert( tr_peerIoHasTorrentHash( handshake
->io
) );
284 if( !tr_torrentExists( handshake
->session
, hash
)
285 || memcmp( hash
, tr_peerIoGetTorrentHash( handshake
->io
),
286 SHA_DIGEST_LENGTH
) )
288 dbgmsg( handshake
, "peer returned the wrong hash. wtf?" );
289 return HANDSHAKE_BAD_TORRENT
;
293 tr_peerIoReadBytes( handshake
->io
, inbuf
, peer_id
, sizeof( peer_id
) );
294 tr_peerIoSetPeersId( handshake
->io
, peer_id
);
297 handshake
->havePeerID
= TRUE
;
298 dbgmsg( handshake
, "peer-id is [%*.*s]", PEER_ID_LEN
, PEER_ID_LEN
, peer_id
);
300 tor
= tr_torrentFindFromHash( handshake
->session
, hash
);
301 tor_peer_id
= tor
&& tor
->peer_id
? tor
->peer_id
: tr_getPeerId( );
302 if( !memcmp( peer_id
, tor_peer_id
, PEER_ID_LEN
) )
304 dbgmsg( handshake
, "streuth! we've connected to ourselves." );
305 return HANDSHAKE_PEER_IS_SELF
;
312 tr_peerIoEnableLTEP( handshake
->io
, HANDSHAKE_HAS_LTEP( reserved
) );
314 tr_peerIoEnableFEXT( handshake
->io
, HANDSHAKE_HAS_FASTEXT( reserved
) );
316 tr_peerIoEnableDHT( handshake
->io
, HANDSHAKE_HAS_DHT( reserved
) );
323 **** OUTGOING CONNECTIONS
327 /* 1 A->B: Diffie Hellman Ya, PadA */
329 sendYa( tr_handshake
* handshake
)
332 const uint8_t * public_key
;
333 char outbuf
[ KEY_LEN
+ PadA_MAXLEN
], *walk
=outbuf
;
335 /* add our public key (Ya) */
336 public_key
= tr_cryptoGetMyPublicKey( handshake
->crypto
, &len
);
337 assert( len
== KEY_LEN
);
338 assert( public_key
);
339 memcpy( walk
, public_key
, len
);
342 /* add some bullshit padding */
343 len
= tr_cryptoRandInt( PadA_MAXLEN
);
344 tr_cryptoRandBuf( walk
, len
);
348 setReadState( handshake
, AWAITING_YB
);
349 tr_peerIoWrite( handshake
->io
, outbuf
, walk
- outbuf
, FALSE
);
353 getCryptoProvide( const tr_handshake
* handshake
)
355 uint32_t provide
= 0;
357 switch( handshake
->encryptionMode
)
359 case TR_ENCRYPTION_REQUIRED
:
360 case TR_ENCRYPTION_PREFERRED
:
361 provide
|= CRYPTO_PROVIDE_CRYPTO
;
364 case TR_CLEAR_PREFERRED
:
365 provide
|= CRYPTO_PROVIDE_CRYPTO
| CRYPTO_PROVIDE_PLAINTEXT
;
373 getCryptoSelect( const tr_handshake
* handshake
,
374 uint32_t crypto_provide
)
379 switch( handshake
->encryptionMode
)
381 case TR_ENCRYPTION_REQUIRED
:
382 choices
[nChoices
++] = CRYPTO_PROVIDE_CRYPTO
;
385 case TR_ENCRYPTION_PREFERRED
:
386 choices
[nChoices
++] = CRYPTO_PROVIDE_CRYPTO
;
387 choices
[nChoices
++] = CRYPTO_PROVIDE_PLAINTEXT
;
390 case TR_CLEAR_PREFERRED
:
391 choices
[nChoices
++] = CRYPTO_PROVIDE_PLAINTEXT
;
392 choices
[nChoices
++] = CRYPTO_PROVIDE_CRYPTO
;
396 for( i
= 0; i
< nChoices
; ++i
)
397 if( crypto_provide
& choices
[i
] )
404 readYb( tr_handshake
* handshake
,
405 struct evbuffer
* inbuf
)
408 const uint8_t * secret
;
410 struct evbuffer
* outbuf
;
411 size_t needlen
= HANDSHAKE_NAME_LEN
;
413 if( EVBUFFER_LENGTH( inbuf
) < needlen
)
416 isEncrypted
= memcmp( EVBUFFER_DATA( inbuf
), HANDSHAKE_NAME
, HANDSHAKE_NAME_LEN
);
420 if( EVBUFFER_LENGTH( inbuf
) < needlen
)
424 dbgmsg( handshake
, "got a %s handshake",
425 ( isEncrypted
? "encrypted" : "plaintext" ) );
427 tr_peerIoSetEncryption( handshake
->io
, isEncrypted
? PEER_ENCRYPTION_RC4
428 : PEER_ENCRYPTION_NONE
);
431 setState( handshake
, AWAITING_HANDSHAKE
);
435 handshake
->haveReadAnythingFromPeer
= TRUE
;
437 /* compute the secret */
438 evbuffer_remove( inbuf
, yb
, KEY_LEN
);
439 secret
= tr_cryptoComputeSecret( handshake
->crypto
, yb
);
440 memcpy( handshake
->mySecret
, secret
, KEY_LEN
);
442 /* now send these: HASH('req1', S), HASH('req2', SKEY) xor HASH('req3', S),
443 * ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)), ENCRYPT(IA) */
444 outbuf
= evbuffer_new( );
446 /* HASH('req1', S) */
448 uint8_t req1
[SHA_DIGEST_LENGTH
];
449 tr_sha1( req1
, "req1", 4, secret
, KEY_LEN
, NULL
);
450 evbuffer_add( outbuf
, req1
, SHA_DIGEST_LENGTH
);
453 /* HASH('req2', SKEY) xor HASH('req3', S) */
456 uint8_t req2
[SHA_DIGEST_LENGTH
];
457 uint8_t req3
[SHA_DIGEST_LENGTH
];
458 uint8_t buf
[SHA_DIGEST_LENGTH
];
459 tr_sha1( req2
, "req2", 4,
460 tr_cryptoGetTorrentHash( handshake
->crypto
),
461 SHA_DIGEST_LENGTH
, NULL
);
462 tr_sha1( req3
, "req3", 4, secret
, KEY_LEN
, NULL
);
463 for( i
= 0; i
< SHA_DIGEST_LENGTH
; ++i
)
464 buf
[i
] = req2
[i
] ^ req3
[i
];
465 evbuffer_add( outbuf
, buf
, SHA_DIGEST_LENGTH
);
468 /* ENCRYPT(VC, crypto_provide, len(PadC), PadC
469 * PadC is reserved for future extensions to the handshake...
470 * standard practice at this time is for it to be zero-length */
472 uint8_t vc
[VC_LENGTH
] = { 0, 0, 0, 0, 0, 0, 0, 0 };
474 tr_peerIoWriteBuf( handshake
->io
, outbuf
, FALSE
);
475 tr_cryptoEncryptInit( handshake
->crypto
);
476 tr_peerIoSetEncryption( handshake
->io
, PEER_ENCRYPTION_RC4
);
478 tr_peerIoWriteBytes( handshake
->io
, outbuf
, vc
, VC_LENGTH
);
479 tr_peerIoWriteUint32( handshake
->io
, outbuf
,
480 getCryptoProvide( handshake
) );
481 tr_peerIoWriteUint16( handshake
->io
, outbuf
, 0 );
484 /* ENCRYPT len(IA)), ENCRYPT(IA) */
486 uint8_t msg
[HANDSHAKE_SIZE
];
487 buildHandshakeMessage( handshake
, msg
);
489 tr_peerIoWriteUint16( handshake
->io
, outbuf
, sizeof( msg
) );
490 tr_peerIoWriteBytes( handshake
->io
, outbuf
, msg
, sizeof( msg
) );
492 handshake
->haveSentBitTorrentHandshake
= 1;
496 tr_cryptoDecryptInit( handshake
->crypto
);
497 setReadState( handshake
, AWAITING_VC
);
498 tr_peerIoWriteBuf( handshake
->io
, outbuf
, FALSE
);
501 evbuffer_free( outbuf
);
506 readVC( tr_handshake
* handshake
,
507 struct evbuffer
* inbuf
)
509 const uint8_t key
[VC_LENGTH
] = { 0, 0, 0, 0, 0, 0, 0, 0 };
510 const int key_len
= VC_LENGTH
;
511 uint8_t tmp
[VC_LENGTH
];
513 /* note: this works w/o having to `unwind' the buffer if
514 * we read too much, but it is pretty brute-force.
515 * it would be nice to make this cleaner. */
518 if( EVBUFFER_LENGTH( inbuf
) < VC_LENGTH
)
520 dbgmsg( handshake
, "not enough bytes... returning read_more" );
524 memcpy( tmp
, EVBUFFER_DATA( inbuf
), key_len
);
525 tr_cryptoDecryptInit( handshake
->crypto
);
526 tr_cryptoDecrypt( handshake
->crypto
, key_len
, tmp
, tmp
);
527 if( !memcmp( tmp
, key
, key_len
) )
530 evbuffer_drain( inbuf
, 1 );
533 dbgmsg( handshake
, "got it!" );
534 evbuffer_drain( inbuf
, key_len
);
535 setState( handshake
, AWAITING_CRYPTO_SELECT
);
540 readCryptoSelect( tr_handshake
* handshake
,
541 struct evbuffer
* inbuf
)
543 uint32_t crypto_select
;
545 const size_t needlen
= sizeof( uint32_t ) + sizeof( uint16_t );
547 if( EVBUFFER_LENGTH( inbuf
) < needlen
)
550 tr_peerIoReadUint32( handshake
->io
, inbuf
, &crypto_select
);
551 handshake
->crypto_select
= crypto_select
;
552 dbgmsg( handshake
, "crypto select is %d", (int)crypto_select
);
553 if( !( crypto_select
& getCryptoProvide( handshake
) ) )
556 "peer selected an encryption option we didn't provide" );
557 return tr_handshakeDone( handshake
, FALSE
);
560 tr_peerIoReadUint16( handshake
->io
, inbuf
, &pad_d_len
);
561 dbgmsg( handshake
, "pad_d_len is %d", (int)pad_d_len
);
563 if( pad_d_len
> 512 )
565 dbgmsg( handshake
, "encryption handshake: pad_d_len is too long" );
566 return tr_handshakeDone( handshake
, FALSE
);
569 handshake
->pad_d_len
= pad_d_len
;
571 setState( handshake
, AWAITING_PAD_D
);
576 readPadD( tr_handshake
* handshake
,
577 struct evbuffer
* inbuf
)
579 const size_t needlen
= handshake
->pad_d_len
;
582 dbgmsg( handshake
, "pad d: need %zu, got %zu",
583 needlen
, EVBUFFER_LENGTH( inbuf
) );
584 if( EVBUFFER_LENGTH( inbuf
) < needlen
)
587 tmp
= tr_new( uint8_t, needlen
);
588 tr_peerIoReadBytes( handshake
->io
, inbuf
, tmp
, needlen
);
591 tr_peerIoSetEncryption( handshake
->io
, handshake
->crypto_select
);
593 setState( handshake
, AWAITING_HANDSHAKE
);
599 **** INCOMING CONNECTIONS
604 readHandshake( tr_handshake
* handshake
,
605 struct evbuffer
* inbuf
)
609 uint8_t reserved
[HANDSHAKE_FLAGS_LEN
];
610 uint8_t hash
[SHA_DIGEST_LENGTH
];
612 dbgmsg( handshake
, "payload: need %d, got %zu",
613 (int)INCOMING_HANDSHAKE_LEN
, EVBUFFER_LENGTH( inbuf
) );
615 if( EVBUFFER_LENGTH( inbuf
) < INCOMING_HANDSHAKE_LEN
)
618 handshake
->haveReadAnythingFromPeer
= TRUE
;
620 pstrlen
= EVBUFFER_DATA( inbuf
)[0]; /* peek, don't read. We may be
621 handing inbuf to AWAITING_YA */
623 if( pstrlen
== 19 ) /* unencrypted */
625 tr_peerIoSetEncryption( handshake
->io
, PEER_ENCRYPTION_NONE
);
627 if( handshake
->encryptionMode
== TR_ENCRYPTION_REQUIRED
)
630 "peer is unencrypted, and we're disallowing that" );
631 return tr_handshakeDone( handshake
, FALSE
);
634 else /* encrypted or corrupt */
636 tr_peerIoSetEncryption( handshake
->io
, PEER_ENCRYPTION_RC4
);
638 if( tr_peerIoIsIncoming( handshake
->io
) )
641 "I think peer is sending us an encrypted handshake..." );
642 setState( handshake
, AWAITING_YA
);
645 tr_cryptoDecrypt( handshake
->crypto
, 1, &pstrlen
, &pstrlen
);
650 "I think peer has sent us a corrupt handshake..." );
651 return tr_handshakeDone( handshake
, FALSE
);
655 evbuffer_drain( inbuf
, 1 );
657 /* pstr (BitTorrent) */
658 pstr
= tr_new( uint8_t, pstrlen
+ 1 );
659 tr_peerIoReadBytes( handshake
->io
, inbuf
, pstr
, pstrlen
);
660 pstr
[pstrlen
] = '\0';
661 if( strcmp( (char*)pstr
, "BitTorrent protocol" ) )
664 return tr_handshakeDone( handshake
, FALSE
);
669 tr_peerIoReadBytes( handshake
->io
, inbuf
, reserved
, sizeof( reserved
) );
675 tr_peerIoEnableLTEP( handshake
->io
, HANDSHAKE_HAS_LTEP( reserved
) );
677 tr_peerIoEnableFEXT( handshake
->io
, HANDSHAKE_HAS_FASTEXT( reserved
) );
679 tr_peerIoEnableDHT( handshake
->io
, HANDSHAKE_HAS_DHT( reserved
) );
682 tr_peerIoReadBytes( handshake
->io
, inbuf
, hash
, sizeof( hash
) );
683 if( tr_peerIoIsIncoming( handshake
->io
) )
685 if( !tr_torrentExists( handshake
->session
, hash
) )
687 dbgmsg( handshake
, "peer is trying to connect to us for a torrent we don't have." );
688 return tr_handshakeDone( handshake
, FALSE
);
692 assert( !tr_peerIoHasTorrentHash( handshake
->io
) );
693 tr_peerIoSetTorrentHash( handshake
->io
, hash
);
698 assert( tr_peerIoHasTorrentHash( handshake
->io
) );
699 if( memcmp( hash
, tr_peerIoGetTorrentHash( handshake
->io
),
700 SHA_DIGEST_LENGTH
) )
702 dbgmsg( handshake
, "peer returned the wrong hash. wtf?" );
703 return tr_handshakeDone( handshake
, FALSE
);
708 *** If it's an incoming message, we need to send a response handshake
711 if( !handshake
->haveSentBitTorrentHandshake
)
713 uint8_t msg
[HANDSHAKE_SIZE
];
714 buildHandshakeMessage( handshake
, msg
);
715 tr_peerIoWrite( handshake
->io
, msg
, sizeof( msg
), FALSE
);
716 handshake
->haveSentBitTorrentHandshake
= 1;
719 setReadState( handshake
, AWAITING_PEER_ID
);
724 readPeerId( tr_handshake
* handshake
,
725 struct evbuffer
* inbuf
)
730 const uint8_t * tor_peer_id
;
731 uint8_t peer_id
[PEER_ID_LEN
];
733 if( EVBUFFER_LENGTH( inbuf
) < PEER_ID_LEN
)
737 tr_peerIoReadBytes( handshake
->io
, inbuf
, peer_id
, PEER_ID_LEN
);
738 tr_peerIoSetPeersId( handshake
->io
, peer_id
);
739 handshake
->havePeerID
= TRUE
;
740 tr_clientForId( client
, sizeof( client
), peer_id
);
741 dbgmsg( handshake
, "peer-id is [%s] ... isIncoming is %d", client
,
742 tr_peerIoIsIncoming( handshake
->io
) );
744 /* if we've somehow connected to ourselves, don't keep the connection */
745 tor
= tr_torrentFindFromHash( handshake
->session
, tr_peerIoGetTorrentHash( handshake
->io
) );
746 tor_peer_id
= tor
&& tor
->peer_id
? tor
->peer_id
: tr_getPeerId( );
747 peerIsGood
= memcmp( peer_id
, tor_peer_id
, PEER_ID_LEN
) != 0;
748 dbgmsg( handshake
, "isPeerGood == %d", (int)peerIsGood
);
749 return tr_handshakeDone( handshake
, peerIsGood
);
753 readYa( tr_handshake
* handshake
,
754 struct evbuffer
* inbuf
)
757 uint8_t * walk
, outbuf
[KEY_LEN
+ PadB_MAXLEN
];
758 const uint8_t *myKey
, *secret
;
761 dbgmsg( handshake
, "in readYa... need %d, have %zu",
762 (int)KEY_LEN
, EVBUFFER_LENGTH( inbuf
) );
763 if( EVBUFFER_LENGTH( inbuf
) < KEY_LEN
)
766 /* read the incoming peer's public key */
767 evbuffer_remove( inbuf
, ya
, KEY_LEN
);
768 secret
= tr_cryptoComputeSecret( handshake
->crypto
, ya
);
769 memcpy( handshake
->mySecret
, secret
, KEY_LEN
);
770 tr_sha1( handshake
->myReq1
, "req1", 4, secret
, KEY_LEN
, NULL
);
772 dbgmsg( handshake
, "sending B->A: Diffie Hellman Yb, PadB" );
773 /* send our public key to the peer */
775 myKey
= tr_cryptoGetMyPublicKey( handshake
->crypto
, &len
);
776 memcpy( walk
, myKey
, len
);
778 len
= tr_cryptoRandInt( PadB_MAXLEN
);
779 tr_cryptoRandBuf( walk
, len
);
782 setReadState( handshake
, AWAITING_PAD_A
);
783 tr_peerIoWrite( handshake
->io
, outbuf
, walk
- outbuf
, FALSE
);
788 readPadA( tr_handshake
* handshake
,
789 struct evbuffer
* inbuf
)
793 dbgmsg( handshake
, "looking to get past pad a... & resync on hash('req',S) ... have %zu bytes",
794 EVBUFFER_LENGTH( inbuf
) );
796 *** Resynchronizing on HASH('req1',S)
799 pch
= memchr( EVBUFFER_DATA( inbuf
),
800 handshake
->myReq1
[0],
801 EVBUFFER_LENGTH( inbuf
) );
804 dbgmsg( handshake
, "no luck so far.. draining %zu bytes",
805 EVBUFFER_LENGTH( inbuf
) );
806 evbuffer_drain( inbuf
, EVBUFFER_LENGTH( inbuf
) );
809 dbgmsg( handshake
, "looking for hash('req',S) ... draining %d bytes",
810 (int)( pch
- EVBUFFER_DATA( inbuf
) ) );
811 evbuffer_drain( inbuf
, pch
- EVBUFFER_DATA( inbuf
) );
812 if( EVBUFFER_LENGTH( inbuf
) < SHA_DIGEST_LENGTH
)
814 if( memcmp( EVBUFFER_DATA( inbuf
), handshake
->myReq1
,
815 SHA_DIGEST_LENGTH
) )
817 dbgmsg( handshake
, "draining one more byte" );
818 evbuffer_drain( inbuf
, 1 );
823 "found it... looking setting to awaiting_crypto_provide" );
824 setState( handshake
, AWAITING_CRYPTO_PROVIDE
);
829 readCryptoProvide( tr_handshake
* handshake
,
830 struct evbuffer
* inbuf
)
832 /* HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide,
836 uint8_t vc_in
[VC_LENGTH
];
837 uint8_t req2
[SHA_DIGEST_LENGTH
];
838 uint8_t req3
[SHA_DIGEST_LENGTH
];
839 uint8_t obfuscatedTorrentHash
[SHA_DIGEST_LENGTH
];
840 uint16_t padc_len
= 0;
841 uint32_t crypto_provide
= 0;
842 const size_t needlen
= SHA_DIGEST_LENGTH
/* HASH('req1',s) */
843 + SHA_DIGEST_LENGTH
/* HASH('req2', SKEY) xor
846 + sizeof( crypto_provide
)
847 + sizeof( padc_len
);
848 tr_torrent
* tor
= NULL
;
850 if( EVBUFFER_LENGTH( inbuf
) < needlen
)
853 /* TODO: confirm they sent HASH('req1',S) here? */
854 evbuffer_drain( inbuf
, SHA_DIGEST_LENGTH
);
856 /* This next piece is HASH('req2', SKEY) xor HASH('req3', S) ...
857 * we can get the first half of that (the obufscatedTorrentHash)
858 * by building the latter and xor'ing it with what the peer sent us */
859 dbgmsg( handshake
, "reading obfuscated torrent hash..." );
860 evbuffer_remove( inbuf
, req2
, SHA_DIGEST_LENGTH
);
861 tr_sha1( req3
, "req3", 4, handshake
->mySecret
, KEY_LEN
, NULL
);
862 for( i
= 0; i
< SHA_DIGEST_LENGTH
; ++i
)
863 obfuscatedTorrentHash
[i
] = req2
[i
] ^ req3
[i
];
864 if(( tor
= tr_torrentFindFromObfuscatedHash( handshake
->session
, obfuscatedTorrentHash
)))
866 const tr_bool clientIsSeed
= tr_torrentIsSeed( tor
);
867 const tr_bool peerIsSeed
= tr_peerMgrPeerIsSeed( tor
, tr_peerIoGetAddress( handshake
->io
, NULL
) );
868 dbgmsg( handshake
, "got INCOMING connection's encrypted handshake for torrent [%s]",
869 tr_torrentName( tor
) );
870 tr_peerIoSetTorrentHash( handshake
->io
, tor
->info
.hash
);
872 if( clientIsSeed
&& peerIsSeed
)
874 dbgmsg( handshake
, "another seed tried to reconnect to us!" );
875 return tr_handshakeDone( handshake
, FALSE
);
880 dbgmsg( handshake
, "can't find that torrent..." );
881 return tr_handshakeDone( handshake
, FALSE
);
884 /* next part: ENCRYPT(VC, crypto_provide, len(PadC), */
886 tr_cryptoDecryptInit( handshake
->crypto
);
888 tr_peerIoReadBytes( handshake
->io
, inbuf
, vc_in
, VC_LENGTH
);
890 tr_peerIoReadUint32( handshake
->io
, inbuf
, &crypto_provide
);
891 handshake
->crypto_provide
= crypto_provide
;
892 dbgmsg( handshake
, "crypto_provide is %d", (int)crypto_provide
);
894 tr_peerIoReadUint16( handshake
->io
, inbuf
, &padc_len
);
895 dbgmsg( handshake
, "padc is %d", (int)padc_len
);
896 handshake
->pad_c_len
= padc_len
;
897 setState( handshake
, AWAITING_PAD_C
);
902 readPadC( tr_handshake
* handshake
,
903 struct evbuffer
* inbuf
)
906 const size_t needlen
= handshake
->pad_c_len
+ sizeof( uint16_t );
908 if( EVBUFFER_LENGTH( inbuf
) < needlen
)
911 evbuffer_drain( inbuf
, handshake
->pad_c_len
);
913 tr_peerIoReadUint16( handshake
->io
, inbuf
, &ia_len
);
914 dbgmsg( handshake
, "ia_len is %d", (int)ia_len
);
915 handshake
->ia_len
= ia_len
;
916 setState( handshake
, AWAITING_IA
);
921 readIA( tr_handshake
* handshake
,
922 struct evbuffer
* inbuf
)
924 const size_t needlen
= handshake
->ia_len
;
925 struct evbuffer
* outbuf
;
926 uint32_t crypto_select
;
928 dbgmsg( handshake
, "reading IA... have %zu, need %zu",
929 EVBUFFER_LENGTH( inbuf
), needlen
);
930 if( EVBUFFER_LENGTH( inbuf
) < needlen
)
934 *** B->A: ENCRYPT(VC, crypto_select, len(padD), padD), ENCRYPT2(Payload Stream)
937 tr_cryptoEncryptInit( handshake
->crypto
);
938 outbuf
= evbuffer_new( );
940 dbgmsg( handshake
, "sending vc" );
943 uint8_t vc
[VC_LENGTH
];
944 memset( vc
, 0, VC_LENGTH
);
945 tr_peerIoWriteBytes( handshake
->io
, outbuf
, vc
, VC_LENGTH
);
948 /* send crypto_select */
949 crypto_select
= getCryptoSelect( handshake
, handshake
->crypto_provide
);
952 dbgmsg( handshake
, "selecting crypto mode '%d'", (int)crypto_select
);
953 tr_peerIoWriteUint32( handshake
->io
, outbuf
, crypto_select
);
957 dbgmsg( handshake
, "peer didn't offer an encryption mode we like." );
958 evbuffer_free( outbuf
);
959 return tr_handshakeDone( handshake
, FALSE
);
962 dbgmsg( handshake
, "sending pad d" );
963 /* ENCRYPT(VC, crypto_provide, len(PadD), PadD
964 * PadD is reserved for future extensions to the handshake...
965 * standard practice at this time is for it to be zero-length */
967 const uint16_t len
= 0;
968 tr_peerIoWriteUint16( handshake
->io
, outbuf
, len
);
971 /* maybe de-encrypt our connection */
972 if( crypto_select
== CRYPTO_PROVIDE_PLAINTEXT
)
974 tr_peerIoWriteBuf( handshake
->io
, outbuf
, FALSE
);
975 tr_peerIoSetEncryption( handshake
->io
, PEER_ENCRYPTION_NONE
);
978 dbgmsg( handshake
, "sending handshake" );
979 /* send our handshake */
981 uint8_t msg
[HANDSHAKE_SIZE
];
982 buildHandshakeMessage( handshake
, msg
);
984 tr_peerIoWriteBytes( handshake
->io
, outbuf
, msg
, sizeof( msg
) );
985 handshake
->haveSentBitTorrentHandshake
= 1;
989 tr_peerIoWriteBuf( handshake
->io
, outbuf
, FALSE
);
990 evbuffer_free( outbuf
);
992 /* now await the handshake */
993 setState( handshake
, AWAITING_PAYLOAD_STREAM
);
998 readPayloadStream( tr_handshake
* handshake
,
999 struct evbuffer
* inbuf
)
1002 const size_t needlen
= HANDSHAKE_SIZE
;
1004 dbgmsg( handshake
, "reading payload stream... have %zu, need %zu",
1005 EVBUFFER_LENGTH( inbuf
), needlen
);
1006 if( EVBUFFER_LENGTH( inbuf
) < needlen
)
1009 /* parse the handshake ... */
1010 i
= parseHandshake( handshake
, inbuf
);
1011 dbgmsg( handshake
, "parseHandshake returned %d", i
);
1012 if( i
!= HANDSHAKE_OK
)
1013 return tr_handshakeDone( handshake
, FALSE
);
1015 /* we've completed the BT handshake... pass the work on to peer-msgs */
1016 return tr_handshakeDone( handshake
, TRUE
);
1026 canRead( struct tr_peerIo
* io
, void * arg
, size_t * piece
)
1028 tr_handshake
* handshake
= arg
;
1029 struct evbuffer
* inbuf
= tr_peerIoGetReadBuffer( io
);
1031 tr_bool readyForMore
= TRUE
;
1033 assert( tr_isPeerIo( io
) );
1035 /* no piece data in handshake */
1038 dbgmsg( handshake
, "handling canRead; state is [%s]",
1039 getStateName( handshake
->state
) );
1041 while( readyForMore
)
1043 switch( handshake
->state
)
1045 case AWAITING_HANDSHAKE
:
1046 ret
= readHandshake ( handshake
, inbuf
); break;
1048 case AWAITING_PEER_ID
:
1049 ret
= readPeerId ( handshake
, inbuf
); break;
1052 ret
= readYa ( handshake
, inbuf
); break;
1054 case AWAITING_PAD_A
:
1055 ret
= readPadA ( handshake
, inbuf
); break;
1057 case AWAITING_CRYPTO_PROVIDE
:
1058 ret
= readCryptoProvide( handshake
, inbuf
); break;
1060 case AWAITING_PAD_C
:
1061 ret
= readPadC ( handshake
, inbuf
); break;
1064 ret
= readIA ( handshake
, inbuf
); break;
1066 case AWAITING_PAYLOAD_STREAM
:
1067 ret
= readPayloadStream( handshake
, inbuf
); break;
1070 ret
= readYb ( handshake
, inbuf
); break;
1073 ret
= readVC ( handshake
, inbuf
); break;
1075 case AWAITING_CRYPTO_SELECT
:
1076 ret
= readCryptoSelect ( handshake
, inbuf
); break;
1078 case AWAITING_PAD_D
:
1079 ret
= readPadD ( handshake
, inbuf
); break;
1085 if( ret
!= READ_NOW
)
1086 readyForMore
= FALSE
;
1087 else if( handshake
->state
== AWAITING_PAD_C
)
1088 readyForMore
= EVBUFFER_LENGTH( inbuf
) >= handshake
->pad_c_len
;
1089 else if( handshake
->state
== AWAITING_PAD_D
)
1090 readyForMore
= EVBUFFER_LENGTH( inbuf
) >= handshake
->pad_d_len
;
1091 else if( handshake
->state
== AWAITING_IA
)
1092 readyForMore
= EVBUFFER_LENGTH( inbuf
) >= handshake
->ia_len
;
1099 fireDoneFunc( tr_handshake
* handshake
, tr_bool isConnected
)
1101 const uint8_t * peer_id
= isConnected
&& handshake
->havePeerID
1102 ? tr_peerIoGetPeersId( handshake
->io
)
1104 const tr_bool success
= ( *handshake
->doneCB
)( handshake
,
1106 handshake
->haveReadAnythingFromPeer
,
1109 handshake
->doneUserData
);
1115 tr_handshakeFree( tr_handshake
* handshake
)
1118 tr_peerIoUnref( handshake
->io
); /* balanced by the ref in tr_handshakeNew */
1120 evtimer_del( &handshake
->timeout_timer
);
1122 tr_free( handshake
);
1126 tr_handshakeDone( tr_handshake
* handshake
,
1131 dbgmsg( handshake
, "handshakeDone: %s", isOK
? "connected" : "aborting" );
1132 tr_peerIoSetIOFuncs( handshake
->io
, NULL
, NULL
, NULL
, NULL
);
1134 success
= fireDoneFunc( handshake
, isOK
);
1136 tr_handshakeFree( handshake
);
1138 return success
? READ_LATER
: READ_ERR
;
1142 tr_handshakeAbort( tr_handshake
* handshake
)
1144 if( handshake
!= NULL
)
1145 tr_handshakeDone( handshake
, FALSE
);
1149 gotError( tr_peerIo
* io UNUSED
,
1153 tr_handshake
* handshake
= vhandshake
;
1155 /* if the error happened while we were sending a public key, we might
1156 * have encountered a peer that doesn't do encryption... reconnect and
1157 * try a plaintext handshake */
1158 if( ( ( handshake
->state
== AWAITING_YB
)
1159 || ( handshake
->state
== AWAITING_VC
) )
1160 && ( handshake
->encryptionMode
!= TR_ENCRYPTION_REQUIRED
)
1161 && ( !tr_peerIoReconnect( handshake
->io
) ) )
1163 uint8_t msg
[HANDSHAKE_SIZE
];
1165 dbgmsg( handshake
, "handshake failed, trying plaintext..." );
1166 buildHandshakeMessage( handshake
, msg
);
1167 handshake
->haveSentBitTorrentHandshake
= 1;
1168 setReadState( handshake
, AWAITING_HANDSHAKE
);
1169 tr_peerIoWrite( handshake
->io
, msg
, sizeof( msg
), FALSE
);
1173 dbgmsg( handshake
, "libevent got an error what==%d, errno=%d (%s)",
1174 (int)what
, errno
, tr_strerror( errno
) );
1175 tr_handshakeDone( handshake
, FALSE
);
1184 handshakeTimeout( int foo UNUSED
, short bar UNUSED
, void * handshake
)
1186 tr_handshakeAbort( handshake
);
1190 tr_handshakeNew( tr_peerIo
* io
,
1191 tr_encryption_mode encryptionMode
,
1192 handshakeDoneCB doneCB
,
1193 void * doneUserData
)
1195 tr_handshake
* handshake
;
1197 handshake
= tr_new0( tr_handshake
, 1 );
1199 handshake
->crypto
= tr_peerIoGetCrypto( io
);
1200 handshake
->encryptionMode
= encryptionMode
;
1201 handshake
->doneCB
= doneCB
;
1202 handshake
->doneUserData
= doneUserData
;
1203 handshake
->session
= tr_peerIoGetSession( io
);
1205 evtimer_set( &handshake
->timeout_timer
, handshakeTimeout
, handshake
);
1206 tr_timerAdd( &handshake
->timeout_timer
, HANDSHAKE_TIMEOUT_SEC
, 0 );
1208 tr_peerIoRef( io
); /* balanced by the unref in tr_handshakeFree */
1209 tr_peerIoSetIOFuncs( handshake
->io
, canRead
, NULL
, gotError
, handshake
);
1210 tr_peerIoSetEncryption( io
, PEER_ENCRYPTION_NONE
);
1212 if( tr_peerIoIsIncoming( handshake
->io
) )
1213 setReadState( handshake
, AWAITING_HANDSHAKE
);
1214 else if( encryptionMode
!= TR_CLEAR_PREFERRED
)
1215 sendYa( handshake
);
1218 uint8_t msg
[HANDSHAKE_SIZE
];
1219 buildHandshakeMessage( handshake
, msg
);
1221 handshake
->haveSentBitTorrentHandshake
= 1;
1222 setReadState( handshake
, AWAITING_HANDSHAKE
);
1223 tr_peerIoWrite( handshake
->io
, msg
, sizeof( msg
), FALSE
);
1230 tr_handshakeGetIO( tr_handshake
* handshake
)
1232 assert( handshake
);
1233 assert( handshake
->io
);
1235 return handshake
->io
;
1239 tr_handshakeStealIO( tr_handshake
* handshake
)
1241 struct tr_peerIo
* io
;
1243 assert( handshake
);
1244 assert( handshake
->io
);
1247 handshake
->io
= NULL
;
1252 tr_handshakeGetAddr( const struct tr_handshake
* handshake
,
1255 assert( handshake
);
1256 assert( handshake
->io
);
1258 return tr_peerIoGetAddress( handshake
->io
, port
);