Skip to content

Commit 21b2396

Browse files
committed
Update
1 parent 1f55516 commit 21b2396

11 files changed

+1161
-889
lines changed

chisel

16 KB
Binary file not shown.

dnsserver.py

+3
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ def __init__(self, addr, port=53):
8181
self.debug = False
8282
self.ttl = 60 * 5
8383
self.logging = False
84+
self.not_found_handler = None
8485

8586
def addEntry(self, type, domain, value):
8687
if type not in self.entries:
@@ -135,6 +136,8 @@ def dns_response(self, data):
135136
reply.add_answer(RR(rname=qname, rtype=getattr(QTYPE, rqt), rclass=1, ttl=self.ttl, rdata=entry))
136137
if self.logging:
137138
print(f"Request: {qt} {qn} -> {entry}")
139+
elif self.not_found_handler:
140+
self.not_found_handler(request, reply)
138141

139142
if self.debug:
140143
print("DNS RESPONSE:", reply)

fileserver.py

+71-42
Original file line numberDiff line numberDiff line change
@@ -68,59 +68,61 @@ def do_OPTIONS(self):
6868
self.do_GET()
6969

7070
def do_GET(self):
71+
try:
72+
if not self.server.is_running:
73+
self.send_response(200)
74+
self.end_headers()
75+
return
7176

72-
if not self.server.is_running:
73-
self.send_response(200)
74-
self.end_headers()
75-
return
76-
77-
path = self.server.cleanPath(self.path)
78-
route = self.find_route(path)
79-
result = route(self)
77+
path = self.server.cleanPath(self.path)
78+
route = self.find_route(path)
79+
result = route(self)
8080

81-
blacklist_headers = ["transfer-encoding", "content-length", "content-encoding", "allow", "connection"]
82-
status_code = 200 if len(result) < 1 else result[0]
83-
data = b"" if len(result) < 2 else result[1]
84-
headers = { } if len(result) < 3 else result[2]
81+
blacklist_headers = ["transfer-encoding", "content-length", "content-encoding", "allow", "connection"]
82+
status_code = 200 if len(result) < 1 else result[0]
83+
data = b"" if len(result) < 2 else result[1]
84+
headers = { } if len(result) < 3 else result[2]
8585

86-
if path in self.server.dumpRequests:
87-
headers["Access-Control-Allow-Origin"] = "*"
86+
if path in self.server.dumpRequests:
87+
headers["Access-Control-Allow-Origin"] = "*"
8888

89-
headers["Content-Length"] = len(data)
89+
headers["Content-Length"] = len(data)
9090

91-
if len(headers) == 0:
92-
self.send_response(status_code)
93-
else:
94-
if path != "/dummy":
95-
self.log_request(status_code)
96-
self.send_response_only(status_code)
91+
if len(headers) == 0:
92+
self.send_response(status_code)
93+
else:
94+
if path != "/dummy":
95+
self.log_request(status_code)
96+
self.send_response_only(status_code)
9797

98-
for key, value in headers.items():
99-
if key.lower() not in blacklist_headers:
100-
self.send_header(key, value)
98+
for key, value in headers.items():
99+
if key.lower() not in blacklist_headers:
100+
self.send_header(key, value)
101101

102-
if self.command.upper() == "OPTIONS":
103-
self.send_header("Allow", "OPTIONS, GET, HEAD, POST")
102+
if self.command.upper() == "OPTIONS":
103+
self.send_header("Allow", "OPTIONS, GET, HEAD, POST")
104104

105-
self.end_headers()
105+
self.end_headers()
106106

107-
if data and self.command.upper() not in ["HEAD","OPTIONS"]:
108-
self.wfile.write(data)
107+
if data and self.command.upper() not in ["HEAD","OPTIONS"]:
108+
self.wfile.write(data)
109109

110-
if (path in self.server.dumpRequests or "/" in self.server.dumpRequests) and path != "/dummy":
111-
contentLength = self.headers.get('Content-Length')
112-
body = None
110+
if (path in self.server.dumpRequests or "/" in self.server.dumpRequests) and path != "/dummy":
111+
contentLength = self.headers.get('Content-Length')
112+
body = None
113113

114-
if contentLength and int(contentLength) > 0:
115-
body = self.rfile.read(int(contentLength))
114+
if contentLength and int(contentLength) > 0:
115+
body = self.rfile.read(int(contentLength))
116116

117-
print("===== Connection from:",self.client_address[0])
118-
print("%s %s %s" % (self.command, self.path, self.request_version))
119-
print(str(self.headers).strip())
120-
if body:
121-
print()
122-
print(body)
123-
print("==========")
117+
print("===== Connection from:",self.client_address[0])
118+
print("%s %s %s" % (self.command, self.path, self.request_version))
119+
print(str(self.headers).strip())
120+
if body:
121+
print()
122+
print(body)
123+
print("==========")
124+
except Exception as e:
125+
print("Exception on handling http", str(e))
124126

125127
def log_message(self, format, *args):
126128
if self.server.logRequests:
@@ -148,9 +150,15 @@ def cleanPath(self, path):
148150
return path.strip()
149151

150152
def addFile(self, name, data, mimeType=None):
153+
154+
if hasattr(data, "read"):
155+
fd = data
156+
data = data.read()
157+
fd.close()
158+
151159
if isinstance(data, str):
152160
data = data.encode("UTF-8")
153-
161+
154162
headers = {
155163
"Access-Control-Allow-Origin": "*",
156164
}
@@ -160,6 +168,27 @@ def addFile(self, name, data, mimeType=None):
160168
# return 200 - OK and data
161169
self.addRoute(name, lambda req: (200, data, headers))
162170

171+
def add_file_path(self, path, name=None):
172+
def readfile():
173+
with open(path, "rb") as f:
174+
return f.read()
175+
176+
if name is None:
177+
name = os.path.basename(path)
178+
self.addRoute(name, lambda req: (200, readfile()))
179+
180+
def load_directory(self, path, recursive=True, exclude_ext=[]):
181+
if not os.path.isdir(path):
182+
print("Not a directory:", path)
183+
return
184+
185+
for dp, dn, filenames in os.walk(path):
186+
for f in filenames:
187+
file_path = os.path.join(dp, f)
188+
if not exclude_ext or os.path.splitext(file_path)[1] not in exclude_ext:
189+
relative_path = file_path[len(path):]
190+
self.add_file_path(file_path, relative_path)
191+
163192
def dumpRequest(self, name):
164193
self.dumpRequests.append(self.cleanPath(name))
165194

git-dumper.py

+30-21
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ def get_indexed_files(response):
4444
if (url.path and
4545
url.path != '.' and
4646
url.path != '..' and
47+
url.path != './' and
48+
url.path != '../' and
4749
not url.path.startswith('/') and
4850
not url.scheme and
4951
not url.netloc):
@@ -171,15 +173,15 @@ def process_tasks(initial_tasks, worker, jobs, args=(), tasks_done=None):
171173
class DownloadWorker(Worker):
172174
''' Download a list of files '''
173175

174-
def init(self, url, directory, retry, timeout, module=None):
176+
def init(self, url, directory, retry, timeout, follow_redirects=False, module=None):
175177
self.session = requests.Session()
176178
self.session.verify = False
177179
self.session.mount(url, requests.adapters.HTTPAdapter(max_retries=retry))
178180
self.module = module
179181

180-
def do_task(self, filepath, url, directory, retry, timeout, module=None):
182+
def do_task(self, filepath, url, directory, retry, timeout, follow_redirects=False, module=None):
181183
with closing(self.session.get('%s/%s' % (url, filepath),
182-
allow_redirects=False,
184+
allow_redirects=follow_redirects,
183185
stream=True,
184186
timeout=timeout,
185187
headers={"User-Agent": USER_AGENT})) as response:
@@ -202,9 +204,9 @@ def do_task(self, filepath, url, directory, retry, timeout, module=None):
202204
class RecursiveDownloadWorker(DownloadWorker):
203205
''' Download a directory recursively '''
204206

205-
def do_task(self, filepath, url, directory, retry, timeout):
207+
def do_task(self, filepath, url, directory, retry, timeout, follow_redirects=False):
206208
with closing(self.session.get('%s/%s' % (url, filepath),
207-
allow_redirects=False,
209+
allow_redirects=follow_redirects,
208210
stream=True,
209211
timeout=timeout,
210212
headers={"User-Agent": USER_AGENT})) as response:
@@ -237,9 +239,9 @@ def do_task(self, filepath, url, directory, retry, timeout):
237239
class FindRefsWorker(DownloadWorker):
238240
''' Find refs/ '''
239241

240-
def do_task(self, filepath, url, directory, retry, timeout, module):
242+
def do_task(self, filepath, url, directory, retry, timeout, follow_redirects=False, module=None):
241243
response = self.session.get('%s/%s' % (url, filepath),
242-
allow_redirects=False,
244+
allow_redirects=follow_redirects,
243245
timeout=timeout,
244246
headers={"User-Agent": USER_AGENT})
245247
printf('[-] Fetching %s/%s [%d]\n', url, filepath, response.status_code)
@@ -271,11 +273,11 @@ def do_task(self, filepath, url, directory, retry, timeout, module):
271273
class FindObjectsWorker(DownloadWorker):
272274
''' Find objects '''
273275

274-
def do_task(self, obj, url, directory, retry, timeout, module):
276+
def do_task(self, obj, url, directory, retry, timeout, follow_redirects, module):
275277
# module = ".git" if not url.endswith("/modules") else ""
276278
filepath = '%s/objects/%s/%s' % (self.module, obj[:2], obj[2:])
277279
response = self.session.get('%s/%s' % (url, filepath),
278-
allow_redirects=False,
280+
allow_redirects=follow_redirects,
279281
timeout=timeout,
280282
headers={"User-Agent": USER_AGENT})
281283
printf('[-] Fetching %s/%s [%d]\n', url, filepath, response.status_code)
@@ -295,7 +297,7 @@ def do_task(self, obj, url, directory, retry, timeout, module):
295297
return get_referenced_sha1(obj_file)
296298

297299

298-
def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
300+
def fetch_git(url, directory, jobs, retry, timeout, follow_redirects, module=".git"):
299301
''' Dump a git repository into the output directory '''
300302

301303
assert os.path.isdir(directory), '%s is not a directory' % directory
@@ -320,7 +322,7 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
320322

321323
# check for /.git/HEAD
322324
printf('[-] Testing %s/%s/HEAD ', url, module)
323-
response = requests.get('%s/%s/HEAD' % (url, module), verify=False, allow_redirects=False, headers={"User-Agent": USER_AGENT})
325+
response = requests.get('%s/%s/HEAD' % (url, module), verify=False, allow_redirects=follow_redirects, headers={"User-Agent": USER_AGENT})
324326
printf('[%d]\n', response.status_code)
325327

326328
if response.status_code != 200:
@@ -332,15 +334,15 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
332334

333335
# check for directory listing
334336
printf('[-] Testing %s/%s/ ', url, module)
335-
response = requests.get('%s/%s/' % (url, module), verify=False, allow_redirects=False, headers={"User-Agent": USER_AGENT})
337+
response = requests.get('%s/%s/' % (url, module), verify=False, allow_redirects=follow_redirects, headers={"User-Agent": USER_AGENT})
336338
printf('[%d]\n', response.status_code)
337339

338340
if response.status_code == 200 and is_html(response) and 'HEAD' in get_indexed_files(response):
339341
printf('[-] Fetching .git recursively\n')
340342
process_tasks(['.git/', '.gitignore'],
341343
RecursiveDownloadWorker,
342344
jobs,
343-
args=(url, directory, retry, timeout))
345+
args=(url, directory, retry, timeout, follow_redirects))
344346

345347
printf('[-] Running git checkout .\n')
346348
os.chdir(directory)
@@ -378,7 +380,7 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
378380
process_tasks(tasks,
379381
DownloadWorker,
380382
jobs,
381-
args=(url, directory, retry, timeout, module))
383+
args=(url, directory, retry, timeout, follow_redirects, module))
382384

383385
if module == ".git":
384386
modules_path = os.path.join(directory, '.gitmodules')
@@ -392,7 +394,7 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
392394
printf("[-] Fetching module: %s\n", module_name)
393395
# os.makedirs(os.path.abspath(module_dir))
394396
module_url = url + "/.git/modules"
395-
fetch_git(module_url, module_dir, jobs, retry, timeout, module=module_name)
397+
fetch_git(module_url, module_dir, jobs, retry, timeout, follow_redirects, module=module_name)
396398
printf("[+] Done iterating module\n")
397399

398400
# find refs
@@ -420,7 +422,7 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
420422
process_tasks(tasks,
421423
FindRefsWorker,
422424
jobs,
423-
args=(url, directory, retry, timeout, module))
425+
args=(url, directory, retry, timeout, follow_redirects, module))
424426

425427
# find packs
426428
printf('[-] Finding packs\n')
@@ -439,7 +441,7 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
439441
process_tasks(tasks,
440442
DownloadWorker,
441443
jobs,
442-
args=(url, directory, retry, timeout))
444+
args=(url, directory, retry, timeout, follow_redirects))
443445

444446
# find objects
445447
printf('[-] Finding objects\n')
@@ -477,8 +479,12 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
477479
if os.path.exists(index_path):
478480
index = dulwich.index.Index(index_path)
479481

480-
for entry in index.iterblobs():
481-
objs.add(entry[1].decode())
482+
# index.iteritems()
483+
for entry in index.iteritems():
484+
if isinstance(entry[1], dulwich.index.IndexEntry):
485+
objs.add(entry[1].sha.decode())
486+
elif hasattr(entry[1], "decode"):
487+
objs.add(entry[1].decode())
482488

483489
# use packs to find more objects to fetch, and objects that are packed
484490
pack_file_dir = os.path.join(directory, module, 'objects', 'pack')
@@ -500,7 +506,7 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
500506
process_tasks(objs,
501507
FindObjectsWorker,
502508
jobs,
503-
args=(url, directory, retry, timeout, module),
509+
args=(url, directory, retry, timeout, follow_redirects, module),
504510
tasks_done=packed_objs)
505511

506512
# git checkout
@@ -529,6 +535,9 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
529535
help='number of request attempts before giving up')
530536
parser.add_argument('-t', '--timeout', type=int, default=3,
531537
help='maximum time in seconds before giving up')
538+
parser.add_argument('-L', '--follow-redirects', default=False,
539+
dest='follow_redirects', action="store_true",
540+
help='follow redirects')
532541
args = parser.parse_args()
533542

534543
# jobs
@@ -576,7 +585,7 @@ def fetch_git(url, directory, jobs, retry, timeout, module=".git"):
576585

577586
# fetch everything
578587
path = os.path.realpath(args.directory)
579-
code = fetch_git(args.url, args.directory, args.jobs, args.retry, args.timeout)
588+
code = fetch_git(args.url, args.directory, args.jobs, args.retry, args.timeout, args.follow_redirects)
580589
if not os.listdir(path):
581590
os.rmdir(path)
582591

0 commit comments

Comments
 (0)