source: trunk/libtransmission/handshake.c @ 13933

Last change on this file since 13933 was 13933, checked in by jordan, 10 years ago

(libT) recycle the peer id used for public torrents after N hours of use

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