-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.py
More file actions
1581 lines (1172 loc) · 39.2 KB
/
utils.py
File metadata and controls
1581 lines (1172 loc) · 39.2 KB
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import binascii
import collections
import enum
import inspect
import itertools
import os
import random
import re
import socket
import string
import subprocess
import sys
import traceback
import select
import operator
import time
import shutil
import argparse
# third-party modules are imported in their calling functions. this allows
# utils.py to be used for multiple scripts without cluttering up their
# dependencies lists.
def basedir(append='', relative=__file__):
"""
Get base directory relative to 'relative' or the location of the utils.py
file.
:param append: Text to append to base directory
:param relative: Get base directory relative to this
:return: The base directory of this script (or relative) with append on the end
"""
return os.path.realpath(os.path.dirname(relative)) + '/' + append
def file_items(files):
"""
Read a list of items from files
:param files: File names to read (any iterable)
:return: Generator producing items. Each item is strip()ed. Returns an
empty generator if None or [] is passed.
"""
if not files:
return
for fname in files:
with open(fname, 'r') as fp:
yield from (item.strip() for item in fp)
def resolve_domain(domain, tcp=True):
"""
Resolve a domain to its IP addresses
:param domain: Domain to resolve
:param tcp: Use TCP to talk to the nameserver
:return: Set of IP addresses for the domain. None if it's NoAnswer or
NXDOMAIN. Throws all other resolution exceptions.
"""
import dns.resolver
try:
ips = set([str(record) for record in dns.resolver.query(domain, 'A', tcp=tcp)])
return ips
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
return None
def is_ip(item):
"""
Check if a string looks like an IP address
:param item: String to check
:return: True if item is an IP address
"""
try:
socket.inet_aton(item)
return True
except socket.error:
return False
def is_cidr(item):
"""
Check if a string looks like an CIDR range
:param item: String to check
:return: True if item is a CIDR range
"""
import netaddr
try:
netaddr.IPNetwork(item)
return True
except netaddr.core.AddrFormatError:
return False
def cidr_ips(cidr):
"""
Get list of IP addresses for a CIDR
:param cidr: CIDR to get IP addresses for
:return: Generator producing IP addresses from the CIDR
"""
import netaddr
yield from (str(ip) for ip in netaddr.IPNetwork(cidr))
def find_cidr(cidrs, ip):
"""
Find the CIDR for an IP address in a list of CIDRs. Returns the first CIDR
if there are multiple.
:param cidrs: List of CIDRs
:param ip: IP address
:return: CIDR or None
"""
import netaddr
for cidr in cidrs:
if netaddr.IPAddress(ip) in netaddr.IPNetwork(cidr):
return cidr
return None
def resolve_to_ips(items, resolve_cidr=True, resolve_domains=True,
parse_ports=False, tcp=False):
"""
Resolve an iterable of domain names, CIDR ranges, and IP addresses to IP
addresses.
:param items: Iterable of items
:param resolve_cidr: Resolve CIDR ranges
:param resolve_domains: Resolve domains
:param parse_ports: Parse port ranges
:param tcp: Use TCP for name resolution
:return: Generator producing tuples containing: (ip, original_item,
{ports}). If the IP returned is None resolution was not possible. If the IP
returned is an Exception there was an error parsing or resolving the item.
"""
for item in items:
try:
# parse out port ranges
if parse_ports and ':' in item:
item, *portranges = item.split(':')[0:]
ports = set(parse_ranges(portranges))
else:
ports = None
if is_ip(item):
# it's an IP address
yield (item, item, ports)
elif is_cidr(item):
# it's a CIDR range
if resolve_cidr:
yield from ((ip, item, ports) for ip in cidr_ips(item))
else:
exception = RuntimeError('CIDR range resolution is disabled. Could not resolve {}'.format(item))
yield (exception, item, ports)
elif resolve_domains:
# probably a domain name. resolve it
debug('Resolving domain {}'.format(item))
resolved_ips = resolve_domain(item, tcp=tcp)
if resolved_ips:
yield from ((ip, item, ports) for ip in resolved_ips)
else:
exception = RuntimeError('Failed to resolve domain')
yield (exception, item, ports)
else:
# resolve_domains is off and it wasn't an IP or CIDR
exception = RuntimeError('Domain resolution is disabled. Could not resolve {}'.format(item))
yield (exception, item, ports)
except Exception as exception:
yield (exception, item, None)
def port_pairs(pairs):
"""
Produce (host, port) pairs for (host, ports) tuples.
:param pairs: Iterable of tuples containing (host, ports) where ports is an iterable of ports.
:return: Generator producing all possible (host, port) pairs
"""
for pair in pairs:
host, ports = pair
for port in ports:
yield host, port
def soup_up(response):
"""
Get BeautifulSoup object for requests.get() response. Handles encoding
correctly.
:param response: Response to parse
"""
if 'charset' in response.headers.get('content-type', '').lower():
http_encoding = response.encoding
else:
http_encoding = None
import bs4
html_encoding = bs4.dammit.EncodingDetector.find_declared_encoding(response.content, is_html=True)
encoding = html_encoding or http_encoding
soup = bs4.BeautifulSoup(response.content, features='lxml', from_encoding=encoding)
return soup
def rdns(ip, tcp=False):
"""
Get PTR record for an IP address
:param ip: IP to get PTR record for
:param tcp: Use TCP to talk to the nameserver
:return: PTR record or none
"""
import dns.reversename
import dns.resolver
rev = dns.reversename.from_address(ip)
try:
record = str(dns.resolver.query(rev, 'PTR', tcp=tcp)[0]).rstrip('.')
return record
except dns.resolver.NXDOMAIN:
return None
def threadify(function, items, max_threads=10, throw_exceptions=False,
arg_items=False):
"""
Threadpool helper. Automagically multi-threadifies a function with some items.
Handles generators correctly by only submitting max_threads * 2 items to
the threadpool at a time. Returns an iterator that produces (item, result)
tuples in real-time.
By default exceptions are returned in the results instead of thrown. See
throw_exceptions.
:param function: Function to execute on each item. Called like
function(item) by default. See arg_items for an
alternative.
:param items: Iterable (or generator) of items to submit to the threadpool
:param max_threads: Maximum number of threads to run at a time
:param throw_exceptions: Throw exceptions instead of returning them.
Exception.item is set to the original item.
:param arg_items: Each item is an iterable of positional arguments or a
dict of keyword arguments for the function. Function
calls become function(*item) or function(**item) if the
item is a dict.
:return: Generator producing iter((item, result)...)
"""
import concurrent.futures
thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=max_threads)
futures = set()
# There are certain generators, like range() that are iterable but not
# iterators and produce repeating, never-depleting lists of numbers for
# some reason. This fixes that problem.
items = iter(items)
# since there's no way to get the original item from a future we have to
# use this helper.
#
# this also handles exceptions. we can't use future.exception() since we'd
# have no way to associate items with their exceptions. this makes handling
# results from threadify a bit more annoying but meh... I can't really
# think of a better option.
def thread_helper(item):
try:
if arg_items:
if isinstance(item, dict):
result = function(**item)
elif is_iterable(item):
result = function(*item)
else:
raise RuntimeError('arg_items is set but item is not an iterable or dict')
else:
result = function(item)
return item, result
except Exception as exception:
return item, exception
running = True
while running or futures:
# submit to threadpool
# only submits max_threads * 2 at a time, in case items is a big generator
for item in items:
future = thread_pool.submit(thread_helper, item)
futures.add(future)
if len(futures) > max_threads * 2:
break
else:
running = False
# now we wait for some futures to complete
# in order to provide results to the caller in realtime we use FIRST_COMPLETED
done, futures = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_COMPLETED)
for future in done:
exception = future.exception()
if exception:
# we should hopefully never reach this
raise exception
item, result = future.result()
if throw_exceptions and isinstance(result, Exception):
result.item = item
raise result
else:
yield item, result
def is_iterable(item):
"""
Determine if an item is iterable.
:param item: Item to check
:return: True if 'item' is iterable
"""
try:
# sometimes python tries to optimize out native types that aren't used
null = iter(item)
return True
except TypeError:
return False
def check_iterator(iterator):
"""
Determine if an iterator is empty. For some reason Python doesn't allow you
to peak at the first element of an iterator so this is pretty hacky.
:param iterator: Iterator to check
:return: An iterator containing the original values or None if empty
"""
try:
first = next(iterator)
return itertools.chain([first], iterator)
except StopIteration:
return None
def is_int(value, base=10):
"""
Determine if a string value is an integer.
:param value: String to check
:param base: Numeric base to check with (default: 10)
:return: True if 'value' is an integer
"""
try:
# sometimes python tries to optimize out native types that aren't used
null = int(value, base=base)
return True
except ValueError:
return False
def parse_ranges(ranges, allow_unbounded=False):
"""
Parse a list of number ranges.
A number range looks like this: 1,5-7,30-32.
This turns into iter([1, 5, 6, 7, 30, 31, 32]).
A generator is returned. A range with no end will produce an infinite
amount of numbers. For example: '5-' produces all numbers from 5 to
infinity.
:param ranges: Iterable of ranges to parse
:return: Generator producing values from the parsed range
"""
for r in ranges:
for r2 in r.split(','):
if '-' in r2:
start, finish = r2.split('-')
start = int(start)
if finish:
# bounded range (start-finish)
finish = int(finish)
yield from range(start, finish + 1)
elif allow_unbounded:
# infinite/unbounded range (start-)
value = start
while True:
yield value
value += 1
else:
raise RuntimeError('unbounded range: {}'.format(r2))
else:
yield int(r2)
# print helpers
_disabled_groups = {'debug'}
_log_file = None
_status_stream = sys.stderr
def disable_groups(*groups):
"""
Disable message groups
:param groups: Groups to disable
"""
global _disabled_groups
_disabled_groups |= set(groups)
def enable_groups(*groups):
"""
Enable message groups
:param groups: Groups to enable
"""
global _disabled_groups
_disabled_groups -= set(groups)
def enable_debug():
"""
Enable debug messages from utils.debug()
"""
enable_groups('debug')
def disable_debug():
"""
Disable debug messages from utils.debug()
"""
disable_groups('debug')
def disable_status():
"""
Disable status messages from utils.info(), utils.good(), utils.bad(),
utils.subline(), utils.debug(), and utils.die()
"""
disable_groups('info', 'good', 'bad', 'subline', 'debug')
def enable_status():
"""
Enable status messages from utils.info(), utils.good(), utils.bad(),
utils.subline(), utils.debug(), and utils.die()
"""
enable_groups('info', 'good', 'bad', 'subline', 'debug')
def enable_terminal(stream=sys.stderr):
"""
Enable logging messages to terminal
:param stream: Stream to write to (default: sys.stderr)
"""
global _status_stream
_status_stream = stream
def disable_terminal():
"""
Disable logging messages to terminal
"""
global _status_stream
_status_stream = None
def set_log(fname):
"""
Write log messages to a file
"""
global _log_file
_log_file = fname
def disable_log():
"""
Disable log file
"""
global _log_file
_log_file = None
# log indent amount
_log_indent = 0
def indent(amount=4):
"""
Increase indent amount for logs
:param amount: Amount to indent
"""
global _log_indent
_log_indent +=4
def dedent(amount=4):
"""
Decrease indent amount for logs
:param amount: Amount to dedent
"""
global _log_indent
_log_indent -=4
def _indented(message):
"""
Make indented message
:param message: Message to indent
:return: Indented message
"""
global _log_indent
return ' ' * _log_indent + message
def log(message='', group='other', color=None, status=False):
"""
Log message to stderr and/or file, depending on settings
:param message: Message to log
:param group: Message group
:param color: Message color. Passed directly to termcolor, if termcolor is installed
:param status: Message is a status message. Print to stderr.
"""
global _log_file
global _status_stream
global _disabled_groups
if group in _disabled_groups:
# messagr group is disabled
return False
message = _indented(message)
if _status_stream:
# print to terminal
if color and _status_stream.isatty() and sys.platform.startswith('linux'):
try:
import termcolor
terminal_message = termcolor.colored(message, color)
except Exception as e:
debug_exception(e)
terminal_message = message
else:
terminal_message = message
if status:
print(terminal_message, file=_status_stream)
else:
print(terminal_message)
if _log_file:
# write to log file
with open(_log_file, 'a+') as fp:
fp.write(message + '\n')
return True
def debug(message):
"""
Log a debug message. Debug messages are disabled by default. Enable them
with utils.enable_debug(). Disable them again with utils.disable_debug().
:param message: Message to log
"""
return log('[D] ' + message, group='debug', status=True)
def raw_debug(message):
"""
Log a raw debug message. No prefix. See utils.debug().
:param message: Message to log
"""
return log(message, group='debug', status=True)
def info(message):
"""
Log an info message.
:param message: Message to log
"""
return log('[.] ' + message, group='info', status=True)
def good(message, color=False):
"""
Log a good message.
:param message: Message to log
"""
return log('[+] ' + message, group='good', color='green' if color else None, status=True)
def bad(message, color=False):
"""
Log a bad message.
:param message: Message to log
"""
return log('[!] ' + message, group='bad', color='yellow' if color else None)
def die(message=None, code=1):
"""
Log a bad message and exit.
:param message: Message to log
:param code: Process return code
"""
if message:
bad(message)
sys.exit(code)
def subline(message):
"""
Log an indented message.
:param message: Message to log
"""
return log(' ' * 4 + message, group='subline', status=True)
def exception_info(exception, limit=6):
"""
Get multi-line info and stacktrace for an exception
:param exception: Exception
:param limit: Stackframe limit
:return: Exception info from traceback
"""
try:
if isinstance(exception, Exception):
raise exception
else:
# not an exception
return None
except:
return traceback.format_exc(limit=limit)
# weird exception. failed to raise
return None
def debug_exception(exception, limit=6):
"""
Print info for an exception if debug is enabled.
:param exception: Exception
:param limit: Stackframe limit
"""
info = exception_info(exception, limit=limit)
if info:
raw_debug(info)
def check_args(func, args):
"""
Check argument list length before calling a function
For functions with *args there is no maximum argument length. The minimum
argument length is the number of positional and keyword arguments a
function has.
:param func: Function to check
:param args: Args to check
:return: True if function arguments are valid
"""
sig = inspect.signature(func)
min_args = 0
max_args = len(sig.parameters)
for name, info in sig.parameters.items():
if info.kind == inspect.Parameter.VAR_POSITIONAL:
# no max arg
max_args = 9999
else:
# positional, kwarg, etc
if info.default == inspect._empty:
min_args += 1
return len(args) >= min_args and len(args) <= max_args
def signature(func, trim=0):
"""
Get stringy function argument signature
:param func: Function to get signature for
:param trim: Trim N arguments from front
:return: Stringified function argument signature
"""
sig = inspect.signature(func)
params = list(sig.parameters.values())[trim:]
sig = sig.replace(parameters=params)
return str(sig)
def signature_command(func, trim=0):
"""
Get stringy function argument signature, in unix command form
'(a, b, c=None, *d)' turns into 'a b [c=None] [d...]'
:param func: Function to get signature for
:param trim: Trim N arguments from front
:return: Stringified function argument signature
"""
sig = inspect.signature(func)
params = list(sig.parameters.values())[trim:]
parsed = []
for param in params:
if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
# arg or arg=None
if param.default == param.empty:
# no default
parsed.append(param.name)
else:
# default
parsed.append('[{}={}]'.format(param.name, str(param.default)))
elif param.kind == inspect.Parameter.VAR_POSITIONAL:
# *arg
parsed.append('[{}...]'.format(param.name))
return ' '.join(parsed)
def func():
"""
Get function object of caller
:return: Function object of calling function
"""
tup = inspect.stack()[2]
return tup[0].f_globals[tup[3]]
def yaml_basic_load(yaml):
"""
Very rudimentary yaml to list-of-dict loader. It only supports a single
list of dictionaries.
:param yaml: Yaml to load
:return: A list of dicts representing the items
"""
items = []
new_item = collections.OrderedDict()
for line in yaml.splitlines():
line = line.strip()
# skip blank lines
if not line:
continue
if line.startswith('- '):
# start new item
if new_item:
items.append(new_item)
line = line[2:]
new_item = collections.OrderedDict()
# key-value pair
m = re.match('([^:]+):(.*)', line)
if m:
key = m.group(1).strip()
value = m.group(2).strip()
new_item[key] = value
else:
raise RuntimeError("yaml_basic_read: Could not parse yaml. It's probably too complex")
if new_item:
items.append(new_item)
return items
def yaml_basic_dump(items):
"""
Very rudimentary list-of-dict to yaml dumper. It only supports a single
list of dictionaries.
:param items: List of dictionaries to dump
:return: Yaml representing the items
"""
yaml = ''
for item in items:
first = True
for key, value in item.items():
# choose prefix
if first:
first = False
prefix = '- '
else:
prefix = ' '
yaml += '{}{}: {}\n'.format(prefix, key, value)
return yaml
def is_iterable(var):
"""
Determine if a variable is an Iterable.
:param var: Variable to check
:return: Boolean specifying whether 'var' is iterable
"""
try:
iterator = iter(var)
return True
except TypeError:
return False
def is_int(string, base=10):
"""
Check if a string is an integer.
:param string: String to check
:param base: Base to check with (default: 10)
:return: True if the string is an integer
"""
try:
int(string, base=base)
return True
except ValueError:
return False
def random_string(minsize=4, maxsize=8, choices=string.ascii_uppercase):
"""
Generate a random ASCII string
:param minsize: Minimum string size
:param maxsize: Maximum string size
:param choices: Character choices (default: ASCII uppercase letters)
"""
size = random.randint(minsize, maxsize)
return ''.join(random.choice(choices) for _ in range(size))
def random_number_string(length, no_zero_start=False):
"""
Produce a random fixed-length number string
:param length: Length of string
:param no_zero_start: Do not allow the string to start with 0
"""
if no_zero_start:
number = str(random.randint(1, 9))
else:
number = str(random.randint(0, 9))
number += ''.join([str(random.randint(0, 9)) for _ in range(length - 1)])
return number
def capture(command, shell=True, stdin=None, stderr=subprocess.DEVNULL, triplet=False):
"""
Run a command and capture output (blocking)
:param command: Command to run
:param shell: Run in shell?
:param stdin: Data to pass to stdin
:param stderr: Where to pipe stderr (DEVNULL, PIPE, STDOUT, etc)
:param triplet: Return a tuple triplet of (return, stdout, stderr) instead of just stdout
"""
if triplet and stderr == subprocess.DEVNULL:
stderr = subprocess.PIPE
proc = subprocess.Popen(command, shell=shell, stdout=subprocess.PIPE,
stdin=subprocess.PIPE, stderr=stderr)
if triplet:
stdout, stderr = proc.communicate(input=stdin)
return proc.returncode, stdout, stderr
else:
return proc.communicate(input=stdin)[0]
def writelines(fname, lines, append=True):
"""
Write iterable of lines to a file with linebreaks
:param fname: File to write to
:param lines: Iterable of lines
:param append: Append instead of overwriting file?
"""
mode = 'a+' if append else 'w+'
with open(fname, mode) as fp:
fp.write('\n'.join(lines) + '\n')
def parse_host(host):
"""
Parse a host
:param host: Host in [user@]host[:port] format
:return: (host, user, port)
"""
user = None
port = None
# Split port
if ':' in host:
host, port = host.split(':')
port = int(port)
# Split user
if '@' in host:
user, host = host.split('@')
return host, user, port
def print_exception(exception, limit=6):
"""
Print info for an exception
:param exception: Exception
:param limit: Stackframe limit
"""
info = exception_info(exception, limit=limit)
if info:
log(info)