Debian Codegraph @

enum_tools/utils.py

raw symbols SCIP
1 """
2 Helper functions for network requests, etc
3 """
4
5 import time
6 import sys
7 import datetime
8 import re
9 import csv
10 import json
11 import ipaddress
12 from multiprocessing.dummy import Pool as ThreadPool
13 from functools import partial
14 from urllib.parse import urlparse
15 try:
16 import requests
17 import dns
18 import dns.resolver
19 from concurrent.futures import ThreadPoolExecutor
20 from requests_futures.sessions import FuturesSession
21 from concurrent.futures._base import TimeoutError
22 except ImportError:
23 print("[!] Please pip install requirements.txt.")
24 sys.exit()
25
26 LOGFILE = False
27 LOGFILE_FMT = ''
28
29
30 def init_logfile(logfile, fmt):
31 """
32 Initialize the global logfile if specified as a user-supplied argument
33 """
34 if logfile:
35 global LOGFILE
36 LOGFILE = logfile
37
38 global LOGFILE_FMT
39 LOGFILE_FMT = fmt
40
41 now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")
42 with open(logfile, 'a', encoding='utf-8') as log_writer:
43 log_writer.write(f"\n\n#### CLOUD_ENUM {now} ####\n")
44
45
46 def is_valid_domain(domain):
47 """
48 Checks if the domain has a valid format and length
49 """
50 # Check for domain total length
51 if len(domain) > 253: # According to DNS specifications
52 return False
53
54 # Check each label in the domain
55 for label in domain.split('.'):
56 # Each label should be between 1 and 63 characters long
57 if not (1 <= len(label) <= 63):
58 return False
59
60 return True
61
62
63 def get_url_batch(url_list, use_ssl=False, callback='', threads=5, redir=True):
64 """
65 Processes a list of URLs, sending the results back to the calling
66 function in real-time via the `callback` parameter
67 """
68
69 # Start a counter for a status message
70 tick = {}
71 tick['total'] = len(url_list)
72 tick['current'] = 0
73
74 # Filter out invalid URLs
75 url_list = [url for url in url_list if is_valid_domain(url)]
76
77 # Break the url list into smaller lists based on thread size
78 queue = [url_list[x:x+threads] for x in range(0, len(url_list), threads)]
79
80 # Define the protocol
81 if use_ssl:
82 proto = 'https://'
83 else:
84 proto = 'http://'
85
86 # Using the async requests-futures module, work in batches based on
87 # the 'queue' list created above. Call each URL, sending the results
88 # back to the callback function.
89 for batch in queue:
90 # I used to initialize the session object outside of this loop, BUT
91 # there were a lot of errors that looked related to pool cleanup not
92 # happening. Putting it in here fixes the issue.
93 # There is an unresolved discussion here:
94 # https://github.com/ross/requests-futures/issues/20
95 session = FuturesSession(executor=ThreadPoolExecutor(max_workers=threads+5))
96 batch_pending = {}
97 batch_results = {}
98
99 # First, grab the pending async request and store it in a dict
100 for url in batch:
101 batch_pending[url] = session.get(proto + url, allow_redirects=redir)
102
103 # Then, grab all the results from the queue.
104 # This is where we need to catch exceptions that occur with large
105 # fuzz lists and dodgy connections.
106 for url in batch_pending:
107 try:
108 # Timeout is set due to observation of some large jobs simply
109 # hanging forever with no exception raised.
110 batch_results[url] = batch_pending[url].result(timeout=30)
111 except requests.exceptions.ConnectionError as error_msg:
112 print(f" [!] Connection error on {url}:")
113 print(error_msg)
114 except TimeoutError:
115 print(f" [!] Timeout on {url}. Investigate if there are"
116 " many of these")
117
118 # Now, send all the results to the callback function for analysis
119 # We need a way to stop processing unnecessary brute-forces, so the
120 # callback may tell us to bail out.
121 for url in batch_results:
122 check = callback(batch_results[url])
123 if check == 'breakout':
124 return
125
126 # Refresh a status message
127 tick['current'] += threads
128 sys.stdout.flush()
129 sys.stdout.write(f" {tick['current']}/{tick['total']} complete...")
130 sys.stdout.write('\r')
131
132 # Clear the status message
133 sys.stdout.write(' \r')
134
135 def read_nameservers(file_path):
136 """
137 Reads nameservers from a given file.
138 Each line in the file should contain one nameserver IP address.
139 Lines starting with '#' will be ignored as comments.
140 """
141 try:
142 with open(file_path, 'r') as file:
143 nameservers = [line.strip() for line in file if line.strip() and not line.startswith('#')]
144 if not nameservers:
145 raise ValueError("Nameserver file is empty or only contains comments")
146 return nameservers
147 except FileNotFoundError:
148 print(f"Error: File '{file_path}' not found.")
149 exit(1)
150 except ValueError as e:
151 print(e)
152 exit(1)
153
154 def is_valid_ip(address):
155 try:
156 ipaddress.ip_address(address)
157 return True
158 except ValueError:
159 return False
160
161 def dns_lookup(nameserver, name):
162 """
163 This function performs the actual DNS lookup when called in a threadpool
164 by the fast_dns_lookup function.
165 """
166 nameserverfile = False
167 if not is_valid_ip(nameserver):
168 nameserverfile = nameserver
169
170 res = dns.resolver.Resolver()
171 res.timeout = 3
172 if nameserverfile:
173 nameservers = read_nameservers(nameserverfile)
174 res.nameservers = nameservers
175 else:
176 res.nameservers = [nameserver]
177
178 tries = 0
179
180 while tries < 3:
181 try:
182 res.query(name)
183 # If no exception is thrown, return the valid name
184 return name
185 except dns.resolver.NXDOMAIN:
186 return ''
187 except dns.resolver.NoNameservers as exc_text:
188 print(" [!] Error querying nameservers! This could be a problem.")
189 print(" [!] If you're using a VPN, try setting --ns to your VPN's nameserver.")
190 print(" [!] Bailing because you need to fix this")
191 print(" [!] More Info:")
192 print(exc_text)
193 return '-#BREAKOUT_DNS_ERROR#-'
194 except dns.exception.Timeout:
195 tries += 1
196
197 print(f" [!] DNS lookup for {name} timed out after 3 tries. Investigate if there are many of these.")
198 return ''
199
200
201 def fast_dns_lookup(names, nameserver, nameserverfile, callback='', threads=5):
202 """
203 Helper function to resolve DNS names. Uses multithreading.
204 """
205 total = len(names)
206 current = 0
207 valid_names = []
208
209 print(f"[*] Brute-forcing a list of {total} possible DNS names")
210
211 # Filter out invalid domains
212 names = [name for name in names if is_valid_domain(name)]
213
214 # Break the url list into smaller lists based on thread size
215 queue = [names[x:x+threads] for x in range(0, len(names), threads)]
216
217 for batch in queue:
218 pool = ThreadPool(threads)
219
220 # Because pool.map takes only a single function arg, we need to
221 # define this partial so that each iteration uses the same ns
222 if nameserverfile:
223 dns_lookup_params = partial(dns_lookup, nameserverfile)
224 else:
225 dns_lookup_params = partial(dns_lookup, nameserver)
226
227 results = pool.map(dns_lookup_params, batch)
228
229 # We should now have the batch of results back, process them.
230 for name in results:
231 if name:
232 if name == '-#BREAKOUT_DNS_ERROR#-':
233 sys.exit()
234 if callback:
235 callback(name)
236 valid_names.append(name)
237
238 current += threads
239
240 # Update the status message
241 sys.stdout.flush()
242 sys.stdout.write(f" {current}/{total} complete...")
243 sys.stdout.write('\r')
244 pool.close()
245
246 # Clear the status message
247 sys.stdout.write(' \r')
248
249 return valid_names
250
251
252 def list_bucket_contents(bucket):
253 """
254 Provides a list of full URLs to each open bucket
255 """
256 key_regex = re.compile(r'<(?:Key|Name)>(.*?)</(?:Key|Name)>')
257 reply = requests.get(bucket)
258
259 # Make a list of all the relative-path key name
260 keys = re.findall(key_regex, reply.text)
261
262 # Need to remove URL parameters before appending file names
263 # from Azure buckets
264 sub_regex = re.compile(r'(\?.*)')
265 bucket = sub_regex.sub('', bucket)
266
267 # Format them to full URLs and print to console
268 if keys:
269 print(" FILES:")
270 for key in keys:
271 url = bucket + key
272 print(f" ->{url}")
273 else:
274 print(" ...empty bucket, so sad. :(")
275
276
277 def fmt_output(data):
278 """
279 Handles the output - printing and logging based on a specified format
280 """
281 # ANSI escape sequences are set based on accessibility of target
282 # (basically, how public it is))
283 bold = '\033[1m'
284 end = '\033[0m'
285 if data['access'] == 'public':
286 ansi = bold + '\033[92m' # green
287 if data['access'] == 'protected':
288 ansi = bold + '\033[33m' # orange
289 if data['access'] == 'disabled':
290 ansi = bold + '\033[31m' # red
291
292 sys.stdout.write(' ' + ansi + data['msg'] + ': ' + data['target'] + end + '\n')
293
294 if LOGFILE:
295 with open(LOGFILE, 'a', encoding='utf-8') as log_writer:
296 if LOGFILE_FMT == 'text':
297 log_writer.write(f'{data["msg"]}: {data["target"]}\n')
298 if LOGFILE_FMT == 'csv':
299 writer = csv.DictWriter(log_writer, data.keys())
300 writer.writerow(data)
301 if LOGFILE_FMT == 'json':
302 log_writer.write(json.dumps(data) + '\n')
303
304
305 def get_brute(brute_file, mini=1, maxi=63, banned='[^a-z0-9_-]'):
306 """
307 Generates a list of brute-force words based on length and allowed chars
308 """
309 # Read the brute force file into memory
310 with open(brute_file, encoding="utf8", errors="ignore") as infile:
311 names = infile.read().splitlines()
312
313 # Clean up the names to usable for containers
314 banned_chars = re.compile(banned)
315 clean_names = []
316 for name in names:
317 name = name.lower()
318 name = banned_chars.sub('', name)
319 if maxi >= len(name) >= mini:
320 if name not in clean_names:
321 clean_names.append(name)
322
323 return clean_names
324
325
326 def start_timer():
327 """
328 Starts a timer for functions in main module
329 """
330 # Start a counter to report on elapsed time
331 start_time = time.time()
332 return start_time
333
334
335 def stop_timer(start_time):
336 """
337 Stops timer and prints a status
338 """
339 # Stop the timer
340 elapsed_time = time.time() - start_time
341 formatted_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
342
343 # Print some statistics
344 print("")
345 print(f" Elapsed time: {formatted_time}")
346 print("")