-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
malleable_redirector.py
2142 lines (1701 loc) · 97 KB
/
malleable_redirector.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
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
#!/usr/bin/python3
#
# This script acts as a HTTP/HTTPS reverse-proxy with several restrictions imposed upon which
# requests and from whom it should process, similarly to the .htaccess file in Apache2's mod_rewrite.
#
# malleable_redirector was created to resolve the problem of effective IR/AV/EDRs/Sandboxes evasion on the
# C2 redirector's backyard.
#
# The proxy along with this plugin can both act as a CobaltStrike Teamserver C2 redirector, given Malleable C2
# profile used during the campaign and teamserver's hostname:port. The plugin will parse supplied malleable profile
# in order to understand which inbound requests may possibly come from the compatible Beacon or are not compliant with
# the profile and therefore should be misdirected. Sections such as http-stager, http-get, http-post and their corresponding
# uris, headers, prepend/append patterns, User-Agent are all used to distinguish between legitimate beacon's request
# and some Internet noise or IR/AV/EDRs out of bound inquiries.
#
# The plugin was also equipped with marvelous known bad IP ranges coming from:
# curi0usJack and the others:
# https://gist.github.com/curi0usJack/971385e8334e189d93a6cb4671238b10
#
# Using a IP addresses blacklist along with known to be bad keywords lookup on Reverse-IP DNS queries and HTTP headers,
# is considerably increasing plugin's resiliency to the unauthorized peers wanting to examine protected infrastructure.
#
# Use wisely, stay safe.
#
# Requirements:
# - brotli
# - yaml
#
# Author:
# Mariusz Banach / mgeeky, '19-'20
# <mb@binary-offensive.com>
#
import re, sys
import os
import hashlib
import socket
import pprint
import requests
import random
import os.path
import ipaddress
import yaml, json
import time
from urllib.parse import urlparse, parse_qsl, parse_qs, urlsplit
from plugins.IProxyPlugin import *
from sqlitedict import SqliteDict
from lib.ipLookupHelper import IPLookupHelper, IPGeolocationDeterminant
from datetime import datetime
BANNED_AGENTS = []
OVERRIDE_BANNED_AGENTS = []
alreadyPrintedPeers = set()
class MalleableParser:
ProtocolTransactions = ('http-stager', 'http-get', 'http-post')
TransactionBlocks = ('metadata', 'id', 'output')
UriParameters = ('uri', 'uri_x86', 'uri_x64')
CommunicationParties = ('client', 'server')
GlobalOptionsDefaults = {
'data_jitter': "0",
'dns_idle': "0.0.0.0",
'dns_max_txt': "252",
'dns_sleep': "0",
'dns_stager_prepend': "",
'dns_stager_subhost': ".stage.123456.",
'dns_ttl': "1",
'headers_remove': "",
'host_stage': "true",
'jitter': "0",
'maxdns': "255",
'pipename': "msagent_##",
'pipename_stager': "status_##",
'sample_name': "My Profile",
'sleeptime': "60000",
'smb_frame_header': "",
'ssh_banner': "Cobalt Strike 4.2",
'ssh_pipename': "postex_ssh_####",
'tcp_frame_header': "",
'tcp_port': "4444",
'useragent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.158 Safari/537.36",
}
def __init__(self, logger):
self.path = ''
self.data = ''
self.datalines = []
self.logger = logger
self.parsed = {}
self.config = self.parsed
self.variants = []
def get_config(self):
return self.config
def parse(self, path):
try:
with open(path, 'r') as f:
self.data = f.read().replace('\r\n', '\n')
self.datalines = self.data.split('\n')
self.datalines.append('\n')
except FileNotFoundError as e:
self.logger.fatal("Malleable profile specified in redirector's config file (profile) doesn't exist: ({})".format(path))
pos = 0
linenum = 0
depth = 0
dynkey = []
parsed = self.parsed
regexes = {
# Finds: set name "value";
'set-name-value' : r"\s*set\s+(\w+)\s+(?=(?:(?<!\w)'(\S.*?)'(?!\w)|\"(\S.*?)\"(?!\w))).*",
# Finds: section { as well as variant-driven: section "variant" {
'begin-section-and-variant' : r'^\s*([\w-]+)(\s+"[^"]+")?\s*\{\s*',
# Finds: [set] parameter ["value", ...];
'set-parameter-value' : r'(?:([\w-]+)\s+(?=")".*")|(?:([\w-]+)(?=;))',
# Finds: prepend "something"; and append "something";
'prepend-append-value' : r'\s*(prepend|append)\s*"([^"\\]*(?:\\.[^"\\]*)*)"',
'parameter-value' : r"(?=(?:(?<!\w)'(\S.*?)'(?!\w)|\"(\S.*?)\"(?!\w)))",
}
compregexes = {}
for k, v in regexes.items():
compregexes[k] = re.compile(v, re.I)
while linenum < len(self.datalines):
line = self.datalines[linenum]
assert len(dynkey) == depth, "Depth ({}) and dynkey differ ({})".format(depth, dynkey)
if line.strip() == '':
pos += len(line)
linenum += 1
continue
if line.lstrip().startswith('#'):
pos += len(line) + 1
linenum += 1
continue
if len(line) > 100:
self.logger.dbg('[key: {}, line: {}, pos: {}] {}...{}'.format(str(dynkey), linenum, pos, line[:50], line[-50:]))
else:
self.logger.dbg('[key: {}, line: {}, pos: {}] {}'.format(str(dynkey), linenum, pos, line[:100]))
parsed = self.parsed
for key in dynkey:
sect, variant = key
if len(variant) > 0:
parsed = parsed[sect][variant]
else:
parsed = parsed[sect]
matched = False
m = compregexes['begin-section-and-variant'].match(line)
twolines = self.datalines[linenum]
if len(self.datalines) >= linenum+1:
twolines += self.datalines[linenum+1]
n = compregexes['begin-section-and-variant'].match(twolines)
if m or n:
if m == None and n != None:
self.logger.dbg('Section opened in a new line: [{}] = ["{}"]'.format(
n.group(1),
twolines.replace('\r', "\\r").replace('\n', "\\n")
))
linenum += 1
pos += len(self.datalines[linenum])
m = n
depth += 1
section = m.group(1)
variant = ''
if section not in parsed.keys():
parsed[section] = {}
if m.group(2) is not None:
variant = m.group(2).strip().replace('"', '')
parsed[section][variant] = {}
parsed[section]['variant'] = variant
elif section in MalleableParser.ProtocolTransactions:
variant = 'default'
parsed[section][variant] = {}
parsed[section]['variant'] = variant
else:
parsed[section] = {}
if len(variant) > 0 and variant not in self.variants:
self.variants.append(variant)
self.logger.dbg('Extracted section: [{}] (variant: {})'.format(section, variant))
dynkey.append((section, variant))
matched = 'section'
pos += len(line)
linenum += 1
continue
if line.strip() == '}':
depth -= 1
matched = 'endsection'
sect, variant = dynkey.pop()
variant = ''
if sect in parsed.keys() and 'variant' in parsed[sect][variant].keys():
variant = '(variant: {})'.format(variant)
self.logger.dbg('Reached end of section {}.{}'.format(sect, variant))
pos += len(line)
linenum += 1
continue
m = compregexes['set-name-value'].match(line)
if m:
n = list(filter(lambda x: x != None, m.groups()[2:]))[0]
val = n.replace('\\\\', '\\')
param = m.group(1)
if param.lower() == 'uri' or param.lower() == 'uri_x86' or param.lower() == 'uri_x64':
parsed[param] = val.split(' ')
self.logger.dbg('Multiple URIs defined: [{}] = [{}]'.format(param, ', '.join(val.split(' '))))
else:
parsed[param] = val
self.logger.dbg('Extracted variable: [{}] = [{}]'.format(param, val))
matched = 'set'
pos += len(line)
linenum += 1
continue
# Finds: [set] parameter ["value", ...];
m = compregexes['set-parameter-value'].search(line)
if m:
paramname = list(filter(lambda x: x != None, m.groups()))[0]
restofline = line[line.find(paramname) + len(paramname):]
values = []
n = compregexes['prepend-append-value'].search(line)
if n != None and len(n.groups()) > 1:
paramname = n.groups()[0]
paramval = n.groups()[1].replace('\\\\', '\\')
values.append(paramval)
self.logger.dbg('Extracted {} value: "{}..."'.format(paramname, paramval[:20]))
else:
for n in compregexes['parameter-value'].finditer(restofline):
try:
paramval = list(filter(lambda x: x != None, n.groups()[1:]))[0]
values.append(paramval.replace('\\\\', '\\'))
except Exception as e:
self.logger.fatal(f'Could not process line as ([set] parameter ["value", ...] :\n\n\t{line}\n\nMake sure your line doesnt include apostrophes, or other characters breaking compregexes["parameter-value"] regex.')
if values == []:
values = ''
elif len(values) == 1:
values = values[0]
if paramname in parsed.keys():
if type(parsed[paramname]) == list:
parsed[paramname].append(values)
else:
parsed[paramname] = [parsed[paramname], values]
else:
if type(values) == list:
parsed[paramname] = [values, ]
else:
parsed[paramname] = values
self.logger.dbg('Extracted complex variable: [{}] = [{}]'.format(paramname, str(values)[:100]))
matched = 'complexset'
pos += len(line)
linenum += 1
continue
# Finds: prepend "value" / append "value"
if re.match(r'^\s*(?:append|prepend)\s+"', line, re.I):
self.logger.dbg(f'Found beginning of prepend/append instruction (line: {linenum}): ' + line[:30])
lineidx = 0
cancont = False
values = []
while lineidx < 100 and lineidx + linenum < len(self.datalines):
if re.match('.*";\s*$', self.datalines[lineidx + linenum]):
self.logger.dbg(f'Found end of prepend/append instruction at line: {linenum+lineidx}')
longline = ''.join(self.datalines[linenum : linenum + lineidx + 1])
m = compregexes['prepend-append-value'].match(longline, re.I|re.M)
if m:
self.logger.dbg(f'Extracted multi-line prepend/append instruction.')
paramname = m.groups()[0]
paramval = m.groups()[1].replace('\\\\', '\\')
values.append(paramval)
if values == []:
values = ''
elif len(values) == 1:
values = values[0]
if paramname in parsed.keys():
if type(parsed[paramname]) == list:
parsed[paramname].append(values)
else:
parsed[paramname] = [parsed[paramname], values]
else:
if type(values) == list:
parsed[paramname] = [values, ]
else:
parsed[paramname] = values
linenum += lineidx + 1
pos += len(longline)
matched = 'prepend-append'
cancont = True
else:
self.logger.dbg(f'Extracted prepend/append instruction IS NOT valid!')
self.logger.dbg(f'\n---------------------\n{longline}\n---------------------')
break
lineidx += 1
if cancont:
continue
a = linenum
b = linenum+1
if a > 5: a -= 5
if b > len(self.datalines): b = len(self.datalines)
elif b < len(self.datalines) + 5: b += 5
self.logger.err("Unexpected statement:\n\t{}\n\n----- Context -----\n\n{}\n".format(
line,
'\n'.join(self.datalines[a:b])
))
self.logger.err("\nParsing failed.")
return False
self.normalize()
return True
def normalize(self):
for k, v in self.config.items():
if k in MalleableParser.ProtocolTransactions:
if k == 'http-get' and 'verb' not in self.config[k].keys():
self.config[k]['verb'] = 'GET'
elif k == 'http-post' and 'verb' not in self.config[k].keys():
self.config[k]['verb'] = 'POST'
for a in MalleableParser.CommunicationParties:
if a not in self.config[k]:
self.config[k][a] = {
'header' : [],
'parameter' : [],
'variant' : 'default',
}
else:
if 'header' not in self.config[k][a].keys(): self.config[k][a]['header'] = []
if 'parameter' not in self.config[k][a].keys(): self.config[k][a]['parameter'] = []
if 'variant' not in self.config[k][a].keys(): self.config[k][a]['variant'] = 'default'
for k, v in MalleableParser.GlobalOptionsDefaults.items():
if k.lower() not in self.config.keys():
self.config[k] = v
self.logger.dbg('MalleableParser: Global variable ({}) not defined. Setting default value of: "{}"'.format(k, v))
class ProxyPlugin(IProxyPlugin):
class AlterHostHeader(Exception):
pass
RequestsHashesDatabaseFile = '.anti-replay.sqlite'
DynamicWhitelistFile = '.peers.sqlite'
DefaultRedirectorConfig = {
'profile' : '',
'teamserver_url' : [],
'drop_action': 'redirect',
'action_url': ['https://google.com', ],
'proxy_pass': {},
'log_dropped': False,
'report_only': False,
'ban_blacklisted_ip_addresses': True,
'ip_addresses_blacklist_file': 'data/banned_ips.txt',
'banned_agents_words_file': 'data/banned_words.txt',
'override_banned_agents_file': 'data/banned_words_override.txt',
'mitigate_replay_attack': False,
'whitelisted_ip_addresses' : [],
'protect_these_headers_from_tampering' : [],
'remove_these_response_headers' : [],
'verify_peer_ip_details': True,
'malleable_redirector_hidden_api_endpoint' : '',
'remove_superfluous_headers': True,
'ip_details_api_keys': {},
'ip_geolocation_requirements': {},
'throttle_down_peer_logging' : {
'log_request_delay': 60,
'requests_threshold': 3
},
'add_peers_to_whitelist_if_they_sent_valid_requests' : {
'number_of_valid_http_get_requests': 15,
'number_of_valid_http_post_requests': 5
},
'policy': {
'allow_proxy_pass' : True,
'allow_dynamic_peer_whitelisting' : True,
'drop_invalid_useragent' : True,
'drop_http_banned_header_names' : True,
'drop_http_banned_header_value' : True,
'drop_dangerous_ip_reverse_lookup' : True,
'drop_ipgeo_metadata_containing_banned_keywords' : True,
'drop_malleable_without_expected_header' : True,
'drop_malleable_without_expected_header_value' : True,
'drop_malleable_without_expected_request_section' : True,
'drop_malleable_without_request_section_in_uri' : True,
'drop_malleable_without_prepend_pattern' : True,
'drop_malleable_without_apppend_pattern' : True,
'drop_malleable_unknown_uris' : True,
'drop_malleable_with_invalid_uri_append' : True,
}
}
def __init__(self, logger, proxyOptions):
self.is_request = False
self.logger = logger
self.addToResHeaders = {}
self.proxyOptions = proxyOptions
self.malleable = None
self.ipLookupHelper = None
self.origverbose = proxyOptions['verbose']
self.ipGeolocationDeterminer = None
self.banned_ips = {}
for k, v in ProxyPlugin.DefaultRedirectorConfig.items():
if k not in self.proxyOptions.keys():
self.proxyOptions[k] = v
open(ProxyPlugin.DynamicWhitelistFile, 'w').close()
with SqliteDict(ProxyPlugin.DynamicWhitelistFile, autocommit=True) as mydict:
mydict['whitelisted_ips'] = []
mydict['peers'] = {}
@staticmethod
def get_name():
return 'malleable_redirector'
def drop_reason(self, text):
self.logger.err(text, color='magenta')
if not self.proxyOptions['report_only']:
if 'X-Drop-Reason' in self.addToResHeaders.keys():
self.addToResHeaders['X-Drop-Reason'] += '; ' + text
else:
self.addToResHeaders['X-Drop-Reason'] = text
def help(self, parser):
global BANNED_AGENTS
global OVERRIDE_BANNED_AGENTS
parametersRequiringDirectPath = (
'ip_addresses_blacklist_file',
'banned_agents_words_file',
'override_banned_agents_file',
'profile',
'output'
)
proxy2BasePath = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
if parser != None:
parser.add_argument('--redir-config',
metavar='PATH', dest='redir_config',
help='Path to the malleable-redirector\'s YAML config file. Not required if global proxy\'s config file was specified (--config) and includes options required by this plugin.'
)
else:
if not self.proxyOptions['config'] and not self.proxyOptions['redir_config']:
self.logger.fatal('Malleable-redirector config file not specified (--redir-config)!')
redirectorConfig = {}
configBasePath = ''
try:
if not self.proxyOptions['config'] and self.proxyOptions['redir_config'] != '':
with open(self.proxyOptions['redir_config']) as f:
try:
redirectorConfig = yaml.load(f, Loader=yaml.FullLoader)
except Exception as e:
self.logger.fatal(f'Could not parse redirector {f} YAML file:\n\n{e}\n\n')
self.proxyOptions.update(redirectorConfig)
for k, v in ProxyPlugin.DefaultRedirectorConfig.items():
if k not in self.proxyOptions.keys():
self.proxyOptions[k] = v
p = os.path.join(proxy2BasePath, self.proxyOptions['redir_config'])
if os.path.isfile(p) or os.path.isdir(p):
configBasePath = p
else:
configBasePath = os.path.dirname(os.path.abspath(self.proxyOptions['redir_config']))
else:
p = os.path.join(proxy2BasePath, self.proxyOptions['config'])
if os.path.isfile(p) or os.path.isdir(p):
configBasePath = p
else:
configBasePath = os.path.dirname(os.path.abspath(self.proxyOptions['config']))
self.ipLookupHelper = IPLookupHelper(self.logger, self.proxyOptions['ip_details_api_keys'])
self.ipGeolocationDeterminer = IPGeolocationDeterminant(self.logger, self.proxyOptions['ip_geolocation_requirements'])
for paramName in parametersRequiringDirectPath:
if paramName in self.proxyOptions.keys() and \
self.proxyOptions[paramName] != '' and self.proxyOptions[paramName] != None:
p = os.path.join(configBasePath, self.proxyOptions[paramName])
if not (os.path.isfile(self.proxyOptions[paramName]) or os.path.isdir(self.proxyOptions[paramName])) and (os.path.isfile(p) or os.path.isdir(p)):
self.proxyOptions[paramName] = p
except FileNotFoundError as e:
self.logger.fatal(f'Malleable-redirector config file not found: ({self.proxyOptions["config"]})!')
except Exception as e:
self.logger.fatal(f'Unhandled exception occured while parsing Malleable-redirector config file: {e}')
profileSkipped = False
if ('profile' not in self.proxyOptions.keys()) or (not self.proxyOptions['profile']):
self.logger.err('''
=================================================================================================
MALLEABLE C2 PROFILE PATH NOT SPECIFIED! LOGIC BASED ON PARSING HTTP REQUESTS WILL BE DISABLED!
=================================================================================================
''')
self.malleable = None
profileSkipped = True
else:
self.malleable = MalleableParser(self.logger)
self.logger.dbg(f'Parsing input Malleable profile: ({self.proxyOptions["profile"]})')
profilePath = self.proxyOptions['profile']
if not self.malleable.parse(profilePath):
self.logger.fatal('Could not parse specified Malleable C2 profile!')
if not profileSkipped and (not self.proxyOptions['action_url'] or len(self.proxyOptions['action_url']) == 0):
if self.proxyOptions['drop_action'] != 'reset':
self.logger.fatal('Action/Drop URL must be specified!')
elif type(self.proxyOptions['action_url']) == str:
url = self.proxyOptions['action_url']
if ',' not in url:
self.proxyOptions['action_url'] = [url.strip(), ]
else:
self.proxyOptions['action_url'] = [x.strip() for x in url.split(',')]
elif type(self.proxyOptions['action_url']) == None and profileSkipped:
self.proxyOptions['action_url'] = []
if self.proxyOptions['proxy_pass'] == None:
self.proxyOptions['proxy_pass'] = {}
elif (type(self.proxyOptions['proxy_pass']) != list) and \
(type(self.proxyOptions['proxy_pass']) != tuple):
self.logger.fatal('Proxy Pass must be a list of entries if used!')
else:
passes = {}
num = 0
for entry in self.proxyOptions['proxy_pass']:
if len(entry) < 6:
self.logger.fatal('Invalid Proxy Pass entry: ({}): too short!',format(entry))
splits = list(filter(None, entry.strip().split(' ')))
url = ''
host = ''
if len(splits) < 2:
self.logger.fatal('Invalid Proxy Pass entry: ({}): invalid syntax: <url host [options]> required!'.format(entry))
url = splits[0].strip()
host = splits[1].strip()
scheme = ''
if host.startswith('https://') or host.startswith('http://'):
parsed = urlparse(host)
if len(parsed.scheme) > 0:
scheme = parsed.scheme
host = scheme + '://' + parsed.netloc
if len(parsed.path) > 0:
host += parsed.path
if len(parsed.query) > 0:
host += '?' + parsed.query
if len(parsed.fragment) > 0:
host += '#' + parsed.fragment
elif len(parsed.netloc) > 0:
host = parsed.netloc
else:
host = parsed.path
if len(parsed.query) > 0:
host += '?' + parsed.query
if len(parsed.fragment) > 0:
host += '#' + parsed.fragment
else:
host = host.strip().replace('https://', '').replace('http://', '')
passes[num] = {}
passes[num]['url'] = url
passes[num]['redir'] = host
passes[num]['scheme'] = scheme
passes[num]['options'] = {}
if len(splits) > 2:
opts = ' '.join(splits[2:])
for opt in opts.split(','):
opt2 = opt.split('=')
k = opt2[0]
v = ''
if len(opt2) == 2:
v = opt2[1]
else:
v = '='.join(opt2[1:])
passes[num]['options'][k.strip()] = v.strip()
if len(url) == 0 or len(host) < 4:
self.logger.fatal('Invalid Proxy Pass entry: (url="{}" host="{}"): either URL or host part were missing or too short (schema is ignored).',format(url, host))
if not url.startswith('/'):
self.logger.fatal('Invalid Proxy Pass entry: (url="{}" host="{}"): URL must start with slash character (/).',format(url, host))
num += 1
if len(passes) > 0:
self.proxyOptions['proxy_pass'] = passes.copy()
lines = []
for num, e in passes.items():
what = 'host'
if '/' in e['redir']: what = 'target URL'
line = "\tRule {}. Proxy requests with URL: \"^{}$\" to {} {}".format(
num, e['url'], what, e['redir']
)
if len(e['options']) > 0:
line += " (options: "
opts = []
for k,v in e['options'].items():
if len(v) > 0:
opts.append("{}: {}".format(k, v))
else:
opts.append("{}".format(k))
line += ', '.join(opts) + ")"
lines.append(line)
self.logger.info('Collected {} proxy-pass statements: \n{}'.format(
len(passes), '\n'.join(lines)
))
#if not self.proxyOptions['teamserver_url']:
# self.logger.fatal('Teamserver URL must be specified!')
if type(self.proxyOptions['teamserver_url']) == str:
self.proxyOptions['teamserver_url'] = [self.proxyOptions['teamserver_url'], ]
try:
inports = []
for ts in self.proxyOptions['teamserver_url']:
inport, scheme, host, port = self.interpretTeamserverUrl(ts)
if inport != 0: inports.append(inport)
o = ''
if port < 1 or port > 65535: raise Exception()
if inport != 0:
if inport < 1 or inport > 65535: raise Exception()
o = 'originating from {} '.format(inport)
self.logger.dbg('Will pass inbound beacon traffic {}to {}{}:{}'.format(
o, scheme+'://' if len(scheme) else '', host, port
))
if len(inports) != len(self.proxyOptions['teamserver_url']) and len(self.proxyOptions['teamserver_url']) > 1:
self.logger.fatal('Please specify inport:host:port form of teamserver-url parameter for each listening port of proxy2')
except Exception as e:
raise
self.logger.fatal('Teamserver\'s URL does not follow <[https?://]host:port> scheme! {}'.format(str(e)))
if (not self.proxyOptions['drop_action']) or (self.proxyOptions['drop_action'] not in ['redirect', 'reset', 'proxy']):
self.logger.fatal('Drop action must be specified as either "reset", redirect" or "proxy"!')
if self.proxyOptions['drop_action'] == 'proxy':
if len(self.proxyOptions['action_url']) == 0:
self.logger.fatal('Drop URL must be specified for proxy action - pointing from which host to fetch responses!')
else:
self.logger.info('Will redirect/proxy requests to these hosts: {}'.format(', '.join(self.proxyOptions['action_url'])), color=self.logger.colors_map['cyan'])
p = os.path.join(proxy2BasePath, self.proxyOptions['banned_agents_words_file'])
if not os.path.isfile(p):
p = self.proxyOptions['banned_agents_words_file']
if not os.path.isfile(p):
self.logger.fatal('Could not locate banned_agents_words_file file!\nTried following path:\n\t' + p)
with open(p, 'r') as f:
for line in f.readlines():
if len(line.strip()) == 0: continue
if line.strip().startswith('#'): continue
BANNED_AGENTS.append(line.strip().lower())
self.logger.dbg(f'Loaded {len(BANNED_AGENTS)} banned words.')
p = os.path.join(proxy2BasePath, self.proxyOptions['override_banned_agents_file'])
if not os.path.isfile(p):
p = self.proxyOptions['override_banned_agents_file']
if not os.path.isfile(p):
self.logger.fatal('Could not locate override_banned_agents_file file!\nTried following path:\n\t' + p)
with open(p, 'r') as f:
for line in f.readlines():
if len(line.strip()) == 0: continue
if line.strip().startswith('#'): continue
OVERRIDE_BANNED_AGENTS.append(line.strip().lower())
self.logger.dbg(f'Loaded {len(OVERRIDE_BANNED_AGENTS)} whitelisted words.')
if self.proxyOptions['ban_blacklisted_ip_addresses']:
p = os.path.join(proxy2BasePath, self.proxyOptions['ip_addresses_blacklist_file'])
if not os.path.isfile(p):
p = self.proxyOptions['ip_addresses_blacklist_file']
if not os.path.isfile(p):
self.logger.fatal('Could not locate ip_addresses_blacklist_file file!\nTried following path:\n\t' + p)
with open(p, 'r') as f:
for line in f.readlines():
l = line.strip()
if l.startswith('#') or len(l) < 7: continue
if '#' in l:
ip = l[:l.find('#')].strip()
comment = l[l.find('#')+1:].strip()
self.banned_ips[ip] = comment
else:
self.banned_ips[l] = ''
self.logger.info('Loaded {} blacklisted CIDRs.'.format(len(self.banned_ips)))
if self.proxyOptions['mitigate_replay_attack']:
with SqliteDict(ProxyPlugin.RequestsHashesDatabaseFile) as mydict:
self.logger.info('Opening request hashes SQLite from file {} to prevent Replay Attacks.'.format(ProxyPlugin.RequestsHashesDatabaseFile))
if 'policy' in self.proxyOptions.keys() and self.proxyOptions['policy'] != None \
and len(self.proxyOptions['policy']) > 0:
log = 'Enabled policies:\n'
for k, v in self.proxyOptions['policy'].items():
log += '\t{}: {}\n'.format(k, str(v))
self.logger.dbg(log)
else:
self.logger.info("No policies defined in config. Defaults to all-set.")
for k, v in ProxyPlugin.DefaultRedirectorConfig['policy'].items():
self.proxyOptions['policy'][k] = v
if 'add_peers_to_whitelist_if_they_sent_valid_requests' in self.proxyOptions.keys() and self.proxyOptions['add_peers_to_whitelist_if_they_sent_valid_requests'] != None \
and len(self.proxyOptions['add_peers_to_whitelist_if_they_sent_valid_requests']) > 0:
log = 'Dynamic peers whitelisting enabled with thresholds:\n'
for k, v in self.proxyOptions['add_peers_to_whitelist_if_they_sent_valid_requests'].items():
if k not in ProxyPlugin.DefaultRedirectorConfig['add_peers_to_whitelist_if_they_sent_valid_requests'].keys():
self.logger.err("Dynamic whitelisting threshold named ({}) not supported! Skipped..".format(k))
log += '\t{}: {}\n'.format(k, str(v))
self.logger.dbg(log)
else:
self.logger.info("Dynamic peers whitelisting disabled.")
self.proxyOptions['add_peers_to_whitelist_if_they_sent_valid_requests'] = {}
def report(self, ret, ts = '', peerIP = '', path = '', userAgentValue = '', reason = ''):
prefix = 'ALLOW'
col = 'green'
if self.res != None:
return ret
if ret:
prefix = 'DROP'
col = 'magenta'
if self.proxyOptions['report_only']:
if ret:
prefix = 'WOULD-BE-DROPPED'
col = 'magenta'
#self.logger.info(' (Report-Only) =========[X] REQUEST WOULD BE BLOCKED =======', color='magenta')
ret = False
if not self.req.suppress_log_entry:
self.logger.info('[{}, {}, {}, r:{}] "{}" - UA: "{}"'.format(prefix, ts, peerIP, reason, path, userAgentValue),
color=col,
forced = True,
noprefix = True
)
return ret
@staticmethod
def get_mock_req(peerIP, command, path, headers):
class Request(object):
pass
req = Request()
req.method = command
req.client_address = [peerIP, ]
req.headers = {}
req.uri = path
if headers: req.headers = headers
return req
@staticmethod
def get_peer_ip(req):
regexes = {
'first-ip' : r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',
'forwarded-ip' : r'for=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',
}
originating_ip_headers = {
'x-forwarded-for' : regexes['first-ip'],
'forwarded' : regexes['forwarded-ip'],
'cf-connecting-ip' : regexes['first-ip'],
'true-client-ip' : regexes['first-ip'],
'x-real-ip' : regexes['first-ip'],
}
peerIP = req.client_address[0]
for k, v in req.headers.items():
if k.lower() in originating_ip_headers.keys():
res = re.findall(originating_ip_headers[k.lower()], v, re.I)
if res and len(res) > 0:
peerIP = res[0]
break
return peerIP
def interpretTeamserverUrl(self, ts):
inport = 0
host = ''
scheme = ''
port = 0
try:
_ts = ts.split(':')
inport = int(_ts[0])
ts = ':'.join(_ts[1:])
except: pass
u = urlparse(ts)
scheme, _host = u.scheme, u.netloc
if _host:
host, _port = _host.split(':')
else:
host, _port = ts.split(':')
port = int(_port)
return inport, scheme, host, port
def pickTeamserver(self, req, req_body = None, res = None, res_body = None):
if len(self.proxyOptions['teamserver_url']) == 0:
self.logger.err('No Teamserver origins specified: dropping request.')
raise Exception(self.drop_action(req, req_body, res, res_body, False))
self.logger.dbg('Peer reached the server at port: ' + str(req.server_port))
for s in self.proxyOptions['teamserver_url']:
u = urlparse(req.uri)
inport, scheme, host, port = self.interpretTeamserverUrl(s)
if inport == req.server_port:
return s
elif inport == '':
return s
#return req.uri
return random.choice(self.proxyOptions['teamserver_url'])
def redirect(self, req, _target, malleable_meta):
# Passing the request forward.
u = urlparse(req.uri)
scheme, netloc, path = u.scheme, u.netloc, (u.path + '?' + u.query if u.query else u.path)
target = _target
newhost = ''
orighost = req.headers['Host']
if target in self.proxyOptions['teamserver_url']:
inport, scheme, host, port = self.interpretTeamserverUrl(target)
if not scheme: scheme = 'https'
w = urlparse(target)
scheme2, netloc2, path2 = w.scheme, w.netloc, (w.path + '?' + w.query if w.query else w.path)
req.uri = '{}://{}:{}{}'.format(scheme, host, port, (u.path + '?' + u.query if u.query else u.path))
newhost = host
if port:
newhost += ':' + str(port)
else:
if not target.startswith('http'):
if req.is_ssl:
target = 'https://' + target
else:
target = 'http://' + target
w = urlparse(target)
scheme2, netloc2, path2 = w.scheme, w.netloc, (w.path + '?' + w.query if w.query else w.path)
if netloc2 == '': netloc2 = req.headers['Host']
req.uri = '{}://{}{}'.format(scheme2, netloc2, (u.path + '?' + u.query if u.query else u.path))
newhost = netloc2
if self.proxyOptions['remove_superfluous_headers'] and len(self.proxyOptions['profile']) > 0:
self.logger.dbg('Stripping HTTP request from superfluous headers...')
self.strip_headers(req, malleable_meta)
self.logger.dbg('Redirecting to "{}"'.format(req.uri))
req.redirected_to_c2 = True
req.headers[proxy2_metadata_headers['ignore_response_decompression_errors']] = "1"
req.headers[proxy2_metadata_headers['override_host_header']] = newhost
if 'host' in malleable_meta.keys() and len(malleable_meta['host']) > 0:
req.headers[proxy2_metadata_headers['domain_front_host_header']] = malleable_meta['host']
return None
def strip_headers(self, req, malleable_meta):
if not malleable_meta or len(malleable_meta) == 0:
self.logger.dbg("strip_headers: No malleable_meta provided!", color = 'red')
return False
section = malleable_meta['section']
variant = malleable_meta['variant']
if section == '' and variant == '':
return False
if section == '' or variant == '':
self.logger.dbg("strip_headers: No section name ({}) or variant ({}) provided!".format(section, variant), color = 'red')
return False
if section not in self.malleable.config.keys():
self.logger.dbg("strip_headers: Section name ({}) not found in malleable.config!".format(section), color = 'red')
return False
if variant not in self.malleable.config[section].keys():
self.logger.dbg("strip_headers: Variant name ({}) not found in malleable.config[{}]!".format(variant, section), color = 'red')
return False
configblock = self.malleable.config[section][variant]
reqhdrs = [x.lower() for x in req.headers.keys()]
expectedheaders = [x[0].lower() for x in configblock['client']['header']]