-
Notifications
You must be signed in to change notification settings - Fork 0
/
ruzzle-mitm-bot.py
383 lines (310 loc) · 12.9 KB
/
ruzzle-mitm-bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import re
import json
import os
from functools import wraps
from threading import Event
from libmproxy.protocol.http import decoded
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
MY_USER_ID = '4650359378'
scoring = {
'A': 1,
'B': 4,
'C': 4,
'D': 2,
'E': 1,
'F': 4,
'G': 3,
'H': 4,
'I': 1,
'J': 10,
'K': 5,
'L': 1,
'M': 3,
'N': 1,
'O': 1,
'P': 4,
'Q': 10,
'R': 1,
'S': 1,
'T': 1,
'U': 2,
'V': 4,
'W': 4,
'X': 8,
'Y': 4,
'Z': 10
}
AES_SECRET = "398C7E2774E7A196AF30DFED78762328427E1F1EAD4C1F5D0D86CE44948E1CB0"
def get_word_indexes(board, word):
indexes = [board.index(char) for char in word]
return indexes
def score_word(board, bonus, word):
moves = get_word_indexes(board, word)
score = 0
double = False
triple = False
for move in moves:
if bonus[move] == 'D':
score += scoring.get(board[move]) * 2
elif bonus[move] == 'T':
score += scoring.get(board[move]) * 3
else:
score += scoring.get(board[move])
if bonus[move] == 'V':
double = True
elif bonus[move] == 'W':
triple = True
if double:
score *= 2
elif triple:
score *= 3
return score
def get_moves(board, word):
v7 = ""
v1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
'D', 'E', 'F']
indexes = get_word_indexes(board, word)
v8 = indexes
v7 += v1[len(v8) - 1]
v0 = v8
v4 = len(v0)
v3 = 0
while True:
if v3 >= v4:
break
v7 += v1[v0[v3]]
v3 += 1
return v7
def get_movestring(board, wordlist):
return (len(wordlist), "".
join([get_moves(board, word) for word in wordlist]))
def uniq(lst):
last = object()
for item in lst:
if item == last:
continue
yield item
last = item
def sort_and_deduplicate(l):
return list(uniq(sorted(l, reverse=True)))
def decode_moves(encoded_moves):
results = []
if not encoded_moves:
return results
for char in encoded_moves:
v2 = 0
while v2 < len(encoded_moves):
char = encoded_moves[v2]
hexchar = ('0' + char).decode('hex')
v3 = ord(hexchar) + 1
v0 = v2 + v3
v6 = []
v5 = 0
while v2 < v0:
v6.append(ord(('0' + encoded_moves[v2 + 1]).decode('hex')))
v5 += 1
v2 += 1
v2 += 1
results.append(v6)
return sort_and_deduplicate(results)
def letterize(board, decoded_moves):
results = []
for word in decoded_moves:
wordletters = "".join([board[l] for l in word])
results.append(wordletters)
return results
def decrypt(iv, cryptotext):
backend = default_backend()
key = AES_SECRET.decode("hex")
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
decryptor = cipher.decryptor()
plaintext = decryptor.update(cryptotext)
plaintext = plaintext + decryptor.finalize()
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
unpadded = unpadder.update(plaintext)
unpadded += unpadder.finalize()
unpadded = unpadded.decode('utf-8')
return unpadded
def encrypt(iv, plaintext):
plaintext = plaintext.encode('utf-8')
backend = default_backend()
key = AES_SECRET.decode("hex")
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
decryptor = cipher.encryptor()
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(plaintext)
padded_data += padder.finalize()
cryptotext = decryptor.update(padded_data)
cryptotext = cryptotext + decryptor.finalize()
return cryptotext
def get_filenames(context, flow, type):
filename = flow.request.host + '_' + flow.request.path
filename = filename.strip().replace(' ', '_')
filename = re.sub(r'(?u)[^-\w.]', '_', filename)
filename = filename + "." + type
if not context.seen.get(filename):
context.seen[filename] = 1
else:
context.seen[filename] = context.seen[filename] + 1
filename = filename + "." + str(context.seen[filename])
cryptofile = context.dirname + '/' + filename + ".crypto.bin"
plainfile = context.dirname + '/' + filename + ".plain.bin"
return (cryptofile, plainfile)
def decrypt_flow(flow, **kwargs):
target = kwargs.get('target')
iv = flow.request.headers.get('payload-session')[0].decode('hex')
cryptotext = getattr(flow, target).content
decrypted = decrypt(iv, cryptotext)
return decrypted
def decrypt_request(flow):
return decrypt_flow(flow, target='request')
def decrypt_response(flow):
return decrypt_flow(flow, target='response')
def cheat_game(context, flow):
if 'davincigames' not in flow.request.host:
return
desired_request = 'playRound'
try:
game_state = json.loads(context.plugins.get_option_value('ruzzle', 'game_state'))
except ValueError:
game_state = {}
try:
decrypted = decrypt_request(flow)
request_json = json.loads(decrypted)
if desired_request in flow.request.get_path_components():
if game_state.get(unicode(request_json[u'round']['gameId'])):
print "cheating at known game... " + unicode(request_json[u'round']['gameId'])
this_game = game_state.get(unicode(request_json[u'round']['gameId']))
target_player = str(this_game['target_player'])
# find all the words possible
all_words = request_json.get(
u'round')['board']['words']
# now we need to play a winning game
wordcount, all_word_movestring = get_movestring(
request_json.get(u'round')['board']['board'], all_words)
# play all the words
request_json[u'round'][
'player' + target_player + 'Moves'] = all_word_movestring
request_json[u'round']['wordsInRound'] = wordcount
# now change the swipe distance to something believable
request_json[u'round'][
'player' + target_player + 'SwipeDistance'] = int(len(all_word_movestring) / 0.09733124018838304)
request_json[u'round']['swipeDistance'] = int(
len(all_word_movestring) / 0.09733124018838304)
# now make a string of move times...
# should probably randomize these so the bot isn't as
# fingerprintable :)
lastmovetime = 106600
firstmovetime = 8866
increment = (lastmovetime - firstmovetime) / wordcount
count = 1
moveTimes = str(firstmovetime)
prevmovetime = firstmovetime
while count < wordcount:
moveTimes += "," + str(prevmovetime + increment)
prevmovetime = prevmovetime + increment
count += 1
request_json[u'round'][
'player' + target_player + 'MoveTimes'] = moveTimes
# now update our score
request_json[u'round']['player' + target_player + 'Score'] = sum([score_word(request_json.get(
u'round')['board']['board'], request_json.get(u'round')['board']['bonus'], word) for word in all_words])
# no errors!
request_json[u'round']['moveErrors'] = 0
request_json[u'round'][
'Player' + target_player + 'MoveErrors'] = 0
# re-encrypt and put back on the wire
iv = flow.request.headers.get('payload-session')[0].decode('hex')
flow.request.content = encrypt(
iv, json.dumps(request_json))
except Exception, e:
print "Error cheating"
print repr(e)
def extract_game(context, flow):
try:
try:
game_state = json.loads(context.plugins.get_option_value('ruzzle', 'game_state'))
except ValueError:
game_state = {}
with decoded(flow.request):
if 'davincigames' not in flow.request.host:
return
if 'readGame' in flow.request.get_path_components():
# we can extract the user ID for a game from this request
# object
request_json = json.loads(decrypt_request(flow))
try:
game = game_state.get(unicode(request_json[u'game']['id'])) or {}
if request_json.get(u'game').get('player1User'):
# the first readGame request doesn't have all the game state
# but the response will
if int(request_json[u'game'].get('player1User').get('userId')) == int(MY_USER_ID):
game['target_player'] = 1
else:
game['target_player'] = 2
game['description'] = "Player 1: %s vs 2: %s" % (request_json[u'game'].get('player1User').get('userId'), request_json[u'game'].get('player2User').get('userId'))
game_state[unicode(request_json[u'game']['id'])] = game
except Exception, e:
print("EXCEPTION")
print(repr(e))
if flow.response:
with decoded(flow.response):
# response available on this flow...
response_json = json.loads(decrypt_response(flow))
if response_json.get('game'):
# there's a game element present
server_game = response_json['game']
game = game_state.get(unicode(server_game['id'])) or {}
game['round'] = server_game.get('round')
game_state[unicode(server_game['id'])] = game
if response_json.get('player1User'):
# readGame response
if 'readGame' in flow.request.get_path_components():
if int(response_json.get('player1User').get('userId')) == int(MY_USER_ID):
game['target_player'] = 1
else:
game['target_player'] = 2
game['description'] = "Player 1: %s vs 2: %s" % (response_json.get('player1User').get('userId'), response_json.get('player2User').get('userId'))
game_state[unicode(response_json['id'])] = game
context.plugins.set_option_value('ruzzle', 'game_state', json.dumps(game_state))
except Exception, e:
print "Error extracting game: %s" % repr(e)
def start(context, argv):
context.plugins.register_view('Decrypt',
title='Ruzzle Decrypt View Plugin',
transformer=decrypt_flow)
context.plugins.register_action('ruzzle',
title='Ruzzle Cheats',
actions=[
{
'title': 'Extract Game Info',
'id': 'extract_game',
'possible_hooks': [
'request',
'response', ],
'state': {
'every_flow': True,
},
},
{
'title': 'Cheat at Game',
'id': 'cheat_game',
'possible_hooks': [
'request',
],
'state': {
'every_flow': False,
},
},
],
options=[{
'title': 'Game State',
'id': 'game_state',
'state': {
'value': 'No Games Detected',
},
'type': 'display_only',
}],
)