forked from BishopFox/GitGot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gitgot.py
executable file
·374 lines (318 loc) · 11.5 KB
/
gitgot.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
#!/usr/bin/env python3
import argparse
import github
import json
import re
import sys
import ssdeep
import sre_constants
import os.path
SIMILARITY_THRESHOLD = 65
ACCESS_TOKEN = "<NO-PERMISSION-GITHUB-TOKEN-HERE>"
class bcolors:
""" Thank you Blender scripts :) """
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
CLEAR = '\x1b[2J'
class State:
def __init__(self,
bad_users=[],
bad_repos=[],
bad_files=[],
bad_signatures=[],
checks=[],
lastInitIndex=0,
index=0,
totalCount=0,
query=None,
logfile="",
):
self.bad_users = bad_users
self.bad_repos = bad_repos
self.bad_files = bad_files
self.bad_signatures = bad_signatures
self.checks = checks
self.lastInitIndex = lastInitIndex
self.index = index
self.totalCount = totalCount
self.query = query
self.logfile = logfile
def save_state(name, repositories, state):
filename = state.logfile.replace("log", "state")
if name == "ratelimited":
filename += ".ratelimited"
with open(filename, "w") as fd:
json.dump(state.__dict__, fd)
print("Saved as [{}]".format(filename))
def regex_search(checks, repo):
output = ""
for line in repo.decoded_content.splitlines():
for check in checks:
try:
line = line.decode('utf-8')
except AttributeError:
pass
try:
(line, inst) = re.subn(
check,
bcolors.BOLD + bcolors.OKBLUE + r'\1' + bcolors.ENDC,
line)
if inst > 0:
output += "\t" + line + "\n"
print("\t", line)
break
except Exception as e:
print(e)
print(bcolors.HEADER + "End of Matches" + bcolors.ENDC)
return output
def should_parse(repo, state):
if repo.repository.owner.login in state.bad_users:
print(bcolors.FAIL + "Failed check: Ignore User" + bcolors.ENDC)
return False
if repo.repository.name in state.bad_repos:
print(bcolors.FAIL + "Failed check: Ignore Repo" + bcolors.ENDC)
return False
if repo.name in state.bad_files:
print(bcolors.FAIL + "Failed check: Ignore File" + bcolors.ENDC)
return False
# Fuzzy Hash Comparison
try:
candidate_sig = ssdeep.hash(repo.decoded_content)
for sig in state.bad_signatures:
similarity = ssdeep.compare(candidate_sig, sig)
if similarity > SIMILARITY_THRESHOLD:
print(
bcolors.FAIL +
"Failed check: Ignore Fuzzy Signature on Contents "
"({}% Similarity)".format(similarity) +
bcolors.ENDC)
return False
except github.UnknownObjectException:
print(
bcolors.FAIL +
"API Error: File no longer exists on github.com" +
bcolors.ENDC)
return False
return True
def print_handler(contents):
try:
contents = contents.decode('utf-8')
except AttributeError:
pass
finally:
print(contents)
print(contents)
def input_handler(state):
return input(
bcolors.HEADER +
"(Result {}/{})".format(
state.index +
1,
state.totalCount if state.totalCount < 1000 else "1000+") +
"=== " + bcolors.ENDC +
"Ignore similar [c]ontents/" +
bcolors.OKGREEN + "[u]ser/" +
bcolors.OKBLUE + "[r]epo/" +
bcolors.WARNING + "[f]ilename" +
bcolors.HEADER +
", [p]rint contents, [s]ave state, [a]dd to log, "
"search [/(findme)], [b]ack, [q]uit, next [<Enter>]===: " +
bcolors.ENDC)
def pagination_hack(repositories, state):
count = len(repositories.__dict__["_PaginatedListBase__elements"])
if state.index >= count:
n_elements = repositories.get_page(state.index//30)
repositories.__dict__["_PaginatedListBase__elements"] += n_elements
return repositories
def regex_handler(choice, repo):
if choice[1] != "(" or choice[-1] != ")":
print(
bcolors.FAIL +
"Regex requires at least one group reference: "
"e.g., (CaSeSensitive) or ((?i)insensitive)" +
bcolors.ENDC)
return ""
else:
print(bcolors.HEADER + "Searching: " + choice[1:] + bcolors.ENDC)
return regex_search([choice[1:]], repo)
def ui_loop(repo, repositories, log_buf, state):
choice = input_handler(state)
if choice == "c":
state.bad_signatures.append(ssdeep.hash(repo.decoded_content))
elif choice == "u":
state.bad_users.append(repo.repository.owner.login)
elif choice == "r":
state.bad_repos.append(repo.repository.name)
elif choice == "f":
state.bad_files.append(repo.name)
elif choice == "p":
print_handler(repo.decoded_content)
ui_loop(repo, repositories, log_buf, state)
elif choice == "s":
save_state(state.query, repositories, state)
ui_loop(repo, repositories, log_buf, state)
elif choice == "a":
with open(state.logfile, "a") as fd:
fd.write(log_buf)
elif choice.startswith("/"):
log_buf += regex_handler(choice, repo)
ui_loop(repo, repositories, log_buf, state)
elif choice == "b":
if state.index - 1 < state.lastInitIndex:
print(
bcolors.FAIL +
"Can't go backwards past restore point "
"because of rate-limiting/API limitations" +
bcolors.ENDC)
ui_loop(repo, repositories, log_buf, state)
else:
state.index -= 2
elif choice == "q":
sys.exit(0)
def api_request_loop(state):
g = github.Github(ACCESS_TOKEN)
print("Collecting Github Search API data...")
try:
repositories = g.search_code(state.query)
state.totalCount = repositories.totalCount
# Hack to backfill PaginatedList with garbage to avoid ratelimiting on
# restore, library fetches in 30 counts
repositories.__dict__["_PaginatedListBase__elements"] = [
None] * (state.index//30) * 30
state.lastInitIndex = state.index
print(bcolors.CLEAR)
i = state.index
stepBack = False
while i < state.totalCount:
while True:
try:
state.index = i
# Manually fill Paginator to avoid ratelimiting on restore
repositories = pagination_hack(repositories, state)
repo = repositories[i]
log_buf = "https://github.com/" + \
bcolors.OKGREEN + repo.repository.owner.login + "/" + \
bcolors.OKBLUE + repo.repository.name + "/blob" + \
bcolors.ENDC + \
os.path.dirname(repo.html_url.split('blob')[1]) + \
"/" + bcolors.WARNING + repo.name + bcolors.ENDC
print(log_buf)
log_buf = "\n" + log_buf + "\n"
if should_parse(repo, state) or stepBack:
stepBack = False
log_buf += regex_search(state.checks, repo)
ui_loop(repo, repositories, log_buf, state)
if state.index < i:
i = state.index
stepBack = True
print(bcolors.CLEAR)
else:
print("Skipping...")
i += 1
break
except github.RateLimitExceededException:
try:
print(
bcolors.FAIL +
"RateLimitException: "
"Please wait about 30 seconds before you "
"try again, or exit (CTRL-C).\n " +
bcolors.ENDC)
save_state("ratelimited", repositories, state)
input("Press enter to try again...")
except KeyboardInterrupt:
sys.exit(1)
except github.RateLimitExceededException:
print(
bcolors.FAIL +
"RateLimitException: "
"Please wait about 30 seconds before you try again.\n" +
bcolors.ENDC)
save_state("ratelimited", repositories, state)
sys.exit(-1)
def regex_validator(args, state):
with open(args.checks, "r") as fd:
for line in fd.read().splitlines():
if line.startswith("#") or len(line) == 0:
continue
try:
re.subn(line, r'\1', "Expression test")
except sre_constants.error as e:
print(bcolors.FAIL + "Invalid Regular expression:\n\t" + line)
if "group" in str(e):
print(
"Ensure expression contains"
"a capture group for matches:\n\t" + str(e))
sys.exit(-1)
state.checks.append(line)
escaped_query = state.query.replace("(", "\\(").replace(")", "\\)")
state.checks.append("(?i)(" + escaped_query + ")")
return state
def main():
if sys.version_info < (3, 0):
sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n")
sys.exit(1)
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="./" + sys.argv[0] + " -q example.com\n" +
"./" + sys.argv[0] + " -q example.com -f checks/default.list "
"-o example1.log\n" +
"./" + sys.argv[0] + " -q example.com -r example.com.state")
parser.add_argument(
"-q",
"--query",
help="Github Code Query",
type=str,
required=True)
parser.add_argument(
"-f",
"--checks",
help="List of RegEx checks (checks/default.list)",
type=str,
default="checks/default.list")
parser.add_argument(
"-o",
"--output",
help="Log name (default: <query>.log)",
type=str)
parser.add_argument(
"-r",
"--recover",
help="Name of recovery file",
type=str)
args = parser.parse_args()
state = State()
state.index = 0
if ACCESS_TOKEN == "<NO-PERMISSION-GITHUB-TOKEN-HERE>":
print("Github Access token not set")
sys.exit(1)
if args.recover:
with open(args.recover, 'r') as fd:
state = State(**json.load(fd))
args.query = args.query.lstrip()
# Reusing Blacklists on new query
if state.query != args.query:
state.query = args.query
state.index = 0
if args.output:
state.logfile = args.output
else:
state.logfile = "logs/" + \
re.sub(r"[,.;@#?!&$/\\]+\ *", "_", args.query) + ".log"
# Create default directories if they don't exist
try:
os.mkdir("logs")
os.mkdir("states")
except FileExistsError:
pass
# Load/Validate RegEx Checks
state = regex_validator(args, state)
api_request_loop(state)
if __name__ == "__main__":
main()