Skip to content

Commit f8022c8

Browse files
committed
error handling for async scanning
1 parent b96ea0f commit f8022c8

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

secheaders/secheaders.py

+20-19
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ def main():
4040
target_list = list(set(target_list)) # Remove possible duplicates
4141

4242
if args.url:
43-
4443
try:
4544
res = scan_target(args.url, args)
4645
except SecurityHeadersException as e:
@@ -55,20 +54,18 @@ def main():
5554

5655

5756
def async_scan_done(scan):
58-
try:
59-
res, args = scan.result()
57+
res, args = scan.result()
58+
if 'error' in res:
59+
print(f"Scanning target {res['target']}...")
60+
print(f"Error: {res['error']}\n")
61+
else:
6062
print(cmd_utils.output_text(res['target'], res['headers'], res['https'], args.no_color, args.verbose))
61-
except SecurityHeadersException as e:
62-
print(e, file=sys.stderr)
6363

6464

6565
def scan_target(url, args):
66-
try:
67-
header_check = SecurityHeaders(url, args.max_redirects, args.insecure)
68-
header_check.fetch_headers()
69-
headers = header_check.check_headers()
70-
except SecurityHeadersException as e:
71-
raise e
66+
header_check = SecurityHeaders(url, args.max_redirects, args.insecure)
67+
header_check.fetch_headers()
68+
headers = header_check.check_headers()
7269

7370
if not headers:
7471
raise FailedToFetchHeaders("Failed to fetch headers")
@@ -78,8 +75,11 @@ def scan_target(url, args):
7875

7976

8077
def scan_target_wrapper(url, args):
81-
# A bit of a dirty hack to pass args to the done callback
82-
return scan_target(url, args), args
78+
try:
79+
# Return the args also for the callback function
80+
return scan_target(url, args), args
81+
except SecurityHeadersException as e:
82+
return {'target': url, 'error': str(e)}, args
8383

8484

8585
async def scan_multiple_targets(args):
@@ -89,22 +89,23 @@ async def scan_multiple_targets(args):
8989
loop = asyncio.get_event_loop()
9090
tasks = []
9191
for target in targets:
92-
if args.json:
93-
task = loop.run_in_executor(None, scan_target, target, args)
94-
else:
95-
task = loop.run_in_executor(None, scan_target_wrapper, target, args)
92+
task = loop.run_in_executor(None, scan_target_wrapper, target, args)
93+
if not args.json:
94+
# Output result of each scan immediately
9695
task.add_done_callback(async_scan_done)
9796
tasks.append(task)
9897

9998
res = []
10099
for task in tasks:
101100
await task
102101

102+
# When json output, aggregate the results and output the json dump at the end
103103
if args.json:
104104
for t in tasks:
105-
res.append(t.result())
105+
val, _args = t.result()
106+
res.append(val)
106107

107-
print(str(res))
108+
print(json.dumps(res, indent=2))
108109

109110
if __name__ == "__main__":
110111
main()

0 commit comments

Comments
 (0)