forked from ThoundsN/AllinOne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
executable file
·283 lines (229 loc) · 7.76 KB
/
utils.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
from invoke import run
from pathlib import Path
import glob
import sqlite3
from log import logger
import re
import config
import json
import errno
import os
import signal
import functools
import time
def exception_handler(func):
def inner_function(*args, **kwargs):
try:
func(*args, **kwargs)
except KeyboardInterrupt:
logger.exception('Keyboard interrupt caught')
exit()
except:
logger.exception(f"{func.__name__} goes wrong")
return inner_function
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
@functools.wraps(func)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wrapper
return decorator
#http://docs.pyinvoke.org/en/stable/api/runners.html#invoke.runners.Runner.run
#http://docs.pyinvoke.org/en/stable/api/runners.html#invoke.runners.Result
@timeout(33333)
def invokeCommand(command:str,*,stop_when_exception=False,return_stdout=False,pty=False):
'''
:param command:
:param stop_when_exception:
:param return_stdout:
:return: str if return_stdout
'''
if not stop_when_exception:
result = run(command,hide='both',pty=pty)
else:
try:
result = run(command,warn=True,hide='both',pty=pty)
except Exception as e:
logger.exception('FATAL', f' invokecommand error: {e} ')
pass
if return_stdout:
return result.stdout #string
def text2set(text:str)->set:
str_list = text.split("\n")
str_set = set(filter(None, str_list))
return str_set
def isEmpty(file_path:Path)->bool:
is_empty = False
if type(file_path) == str:
file_path = Path(file_path)
if not file_path.exists():
is_empty = True
if file_path.stat().st_size == 0:
is_empty = True
if file_path.stat().st_size < 1024:
with open(file_path,'r') as f:
if any(line in ['\n', '\r\n'] for line in f):
is_empty = True
if is_empty:
logger.log('INFO', f' File: {file_path} is empty')
return True
return False
# def getCurrentTime():
# current_time = datetime.today().strftime('%m-%d-%H:%M')
# return current_time
# def getDatadir():
# if not config.current_data_dir:
# config.current_data_dir = config.root_data_dir/config.domain_name/getStartTime()
# Path(config.current_data_dir).mkdir(parents=True, exist_ok=True)
# return config.current_data_dir
# return config.current_data_dir
#
# def getSubdir(subdir:str):
# subdir_absolute = getDatadir()/subdir
# Path(subdir_absolute).mkdir(parents=True, exist_ok=True)
# return subdir_absolute
def makeDir(absolute_path):
Path(absolute_path).mkdir(parents=True, exist_ok=True)
return absolute_path
def getAllJsfiles(dir) -> list:
'''
returns absolute paths
:param dir:
:return:
'''
files = glob.glob(str(dir) + '/**/*.js', recursive=True)
return files
def getFilesInDir(dir,commonality:str) -> list:
'''
returns absolute paths
:param dir:
:return:
'''
files = glob.glob(str(dir) + f'/**/*{commonality}', recursive=True)
return files
def downloadLinksInFile(file_path:str):
import config
cmd = f"{config.aria2c_command} -i {file_path} -j 15"
invokeCommand(cmd)
def location2href(filelocation:str):
import config
prefix = config.dataurl
pieces = filelocation.split('/')
del pieces[6]
del pieces[0:5]
suffix = "/".join(pieces)
href = prefix + suffix
return href
def replaceUnderscore(domain:str):
domain = domain.replace('/','_')
domain = domain.replace(':','_')
domain = domain.replace('-','_')
return domain.replace('.','_')
def querySqlite(domain:str,sqlite_path:str,query:str)-> set:
# logger.log("INFO",f"domain: {domain}")
# logger.log("INFO",replaceUnderscore(domain))
# logger.log("INFO",f"{domain in query}")
query = query.replace(domain,replaceUnderscore(domain))
logger.log("INFO",f"Querying oneforall sqlitedb {sqlite_path} with query: {query}")
con = sqlite3.connect(sqlite_path)
cursor = con.cursor()
cursor.execute(query)
sql_results = set(cursor.fetchall())
return sql_results
def writeFile(lines,file):
logger.log("INFO",f"write results to {file}")
# logger.log("INFO",f"{type(lines)} {lines}")
try:
with file.open('w') as f:
if isinstance(lines, dict):
f.write(json.dumps(lines))
elif any(isinstance(i, tuple) for i in lines):
for result_line in lines:
result_line = "".join(result_line)
f.write(result_line+'\n')
else:
for result_line in lines:
# logger.log("INFO",f" {type(result_line)}{result_line}")
f.write(result_line+'\n')
except:
logger.exception(f"write file exception : {file} ")
#stupid bug: with open(file,'w') as f:
def readFile(file:str):
try:
with open(file,'r') as f:
lines = f.read().splitlines()
return lines
except:
logger.exception(f"read file exception : {file}")
def filterNegativeFile(result_file:str):
is_vulneralbe=False
with open(result_file,'r') as r:
text = r.read()
if 'VULNERABLE' in text or 'vulnerable' in text:
is_vulneralbe = True
if is_vulneralbe:
p= Path(result_file)
newfilename = f"vul_{p.stem}{p.suffix}"
p.rename(Path(p.parent, newfilename))
notify(newfilename)
def checkOneDependency(command_path): # exit code 126,127 of invoke.run is bad
test_commands = set()
test_commands.add(f"{command_path} -h ")
test_commands.add(f"{command_path} --help ")
command_ok = False
command_possilbe_ok = False
for cmd in test_commands:
# print(cmd)
try:
result = run(cmd, hide=True,warn=True,timeout=3)
except:
print(f"{command_path} seems to be a shell pipeline program , can't determine whether it is executable ")
return
# print(result)
if result.ok:
command_ok = True
break
if result.return_code != 126 and result.return_code != 127:
command_possilbe_ok = True
if command_ok:
return
if command_possilbe_ok:
print(f"{command_path} --help/-h returns nonzero code , better check it out manually ")
else:
print(f"Very likely that {command_path} have some problems, better check it out manually ")
def lineCount(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def isUrlqueryFileUseful(fname):
count = lineCount(fname)
if count < 20 :
return False
with open(fname,'r') as f:
if '?' not in f.read():
return False
return True
def dedupeUrlsWithqeury(urls_file:str,file_out):
cmd = f"{config.urldedupe_command} -qs -s -u {urls_file} > {file_out} "
logger.log('INFO',f'Running urldedupe with command {cmd}')
invokeCommand(cmd)
return
def dedupeUrls(urls_file:str,file_out):
cmd = f"{config.urldedupe_command} -s -u {urls_file} > {file_out} "
logger.log('INFO',f'Running urldedupe with command {cmd}')
invokeCommand(cmd)
return
def notify(file_path):
file_url = location2href(file_path)
with open("/root/data/notify.txt","a") as f:
f.write(file_url)
f.write("\n")