| 1 | from sha import sha |
|---|
| 2 | from random import randint |
|---|
| 3 | from struct import unpack |
|---|
| 4 | |
|---|
| 5 | |
|---|
| 6 | rand = open("/dev/random","r").read |
|---|
| 7 | |
|---|
| 8 | class RC4: |
|---|
| 9 | def __call__(self, i): |
|---|
| 10 | return rand(i) |
|---|
| 11 | |
|---|
| 12 | rc4 = RC4() |
|---|
| 13 | |
|---|
| 14 | |
|---|
| 15 | MAX_PEERS = 100 |
|---|
| 16 | |
|---|
| 17 | |
|---|
| 18 | infohash = sha("dummy_info").digest() |
|---|
| 19 | pseudo = '' |
|---|
| 20 | num_peers = 1000 |
|---|
| 21 | tracker_peer_list = rand(6) * num_peers |
|---|
| 22 | obfuscated_tracker_peer_list = '' |
|---|
| 23 | |
|---|
| 24 | def xor(plaintext,pseudo): |
|---|
| 25 | isint = False |
|---|
| 26 | if type(plaintext) == int: |
|---|
| 27 | plaintext = "".join([chr(int(x,16)) for x in "%.4x" % plaintext]) |
|---|
| 28 | isint = True |
|---|
| 29 | |
|---|
| 30 | n = len(pseudo) |
|---|
| 31 | |
|---|
| 32 | ciphertext = "".join( |
|---|
| 33 | [chr(ord(pseudo[i%n])^ord(plaintext[i])) for i in xrange(len(plaintext))] ) |
|---|
| 34 | |
|---|
| 35 | if isint: |
|---|
| 36 | ciphertext = unpack("!I", ciphertext)[0] |
|---|
| 37 | return ciphertext |
|---|
| 38 | |
|---|
| 39 | def init(): |
|---|
| 40 | global iv, x, n, n_xor_y, obfuscated_tracker_peer_list |
|---|
| 41 | iv = rand(20) |
|---|
| 42 | rc4.key = sha(infohash + iv).digest()[0:8] |
|---|
| 43 | rc4(768) |
|---|
| 44 | x = rc4(4) |
|---|
| 45 | y = rc4(4) |
|---|
| 46 | n = min(num_peers, randint(MAX_PEERS * 2, MAX_PEERS * 4)) |
|---|
| 47 | n_xor_y = xor(n,y) |
|---|
| 48 | pseudo = rc4(n*6) |
|---|
| 49 | obfuscated_tracker_peer_list = xor(tracker_peer_list,pseudo) |
|---|
| 50 | |
|---|
| 51 | def getpeers( numwant ): |
|---|
| 52 | global iv, x, n, n_xor_y, obfuscated_tracker_peer_list |
|---|
| 53 | response = {} |
|---|
| 54 | response['iv'] = iv |
|---|
| 55 | numwant = min(numwant, MAX_PEERS) |
|---|
| 56 | if numwant >= num_peers: |
|---|
| 57 | response['peers'] = obfuscated_tracker_peer_list |
|---|
| 58 | return response |
|---|
| 59 | |
|---|
| 60 | i = randint(0,num_peers-numwant) |
|---|
| 61 | response['i'] = xor(i,x) |
|---|
| 62 | response['n'] = n_xor_y |
|---|
| 63 | |
|---|
| 64 | |
|---|
| 65 | response['peers'] = obfuscated_tracker_peer_list[i*6:(i+numwant)*6] |
|---|
| 66 | return response |
|---|
| 67 | |
|---|
| 68 | init() |
|---|
| 69 | response = getpeers(20) |
|---|
| 70 | print "response=", response |
|---|
| 71 | print "len(response['peers'])=", len(response['peers']) |
|---|