-
Notifications
You must be signed in to change notification settings - Fork 3
/
pplay.py
executable file
·3395 lines (2603 loc) · 118 KB
/
pplay.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/env python3
import argparse
import atexit
import binascii
import datetime
import difflib
import fileinput
import hashlib
import json
import os
import re
import socket
import struct
import sys
import tempfile
import threading
import time
from select import select
class Features:
have_scapy = False
have_paramiko = False
have_colorama = False
have_ssl = False
have_tls13 = False
have_requests = False
have_socks = False
have_crypto = False
have_sctp = False
host_platform = None
verbose = False
debuk = False
option_dump_received_correct = False
option_dump_received_different = True
option_auto_send = 5
option_socks = None
option_interactive = False
fuzz_prng = None
fuzz_level = 230
scatter_prng = None
pplay_version = "2.0.9"
# EMBEDDED DATA BEGIN
# EMBEDDED DATA END
title = 'pplay - application payload player - %s' % (pplay_version,)
pplay_copyright = "written by Ales Stibal <[email protected]>"
g_script_module = None
g_delete_files = []
g_hostname = socket.gethostname()
try:
from scapy.all import rdpcap
from scapy.all import IP
from scapy.all import IPv6
from scapy.all import TCP
from scapy.all import UDP
from scapy.all import SCTP
from scapy.all import Padding
Features.have_scapy = True
except ImportError as e:
print('== No scapy, pcap files not supported.', file=sys.stderr)
# try to import colorama, indicate with have_ variable
try:
import colorama
from colorama import Fore, Back, Style
Features.have_colorama = True
except ImportError as e:
print('== No colorama library, enjoy.', file=sys.stderr)
# try to import ssl, indicate with have_ variable
try:
import ssl
Features.have_ssl = True
except ImportError as e:
print('== No SSL python support!', file=sys.stderr)
# try to import paramiko, indicate with have_ variable
try:
import paramiko
Features.have_paramiko = True
except ImportError as e:
print('== No paramiko library, use ssh with pipes!', file=sys.stderr)
# try to import paramiko, indicate with have_ variable
try:
import requests
Features.have_requests = True
except ImportError as e:
print('== No requests library support, files on http(s) won\'t be accessible!', file=sys.stderr)
# try to import paramiko, indicate with have_ variable
try:
import socks
Features.have_socks = True
except ImportError as e:
print('== No pysocks library support, can\'t use SOCKS proxy!', file=sys.stderr)
try:
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import AuthorityInformationAccessOID
from cryptography.x509.oid import NameOID
Features.have_crypto = True
except ImportError as e:
print('== no cryptography library support, can\'t use CA to sign dynamic certificates based on SNI!',
file=sys.stderr)
try:
import sctp
Features.have_sctp = True
except ImportError as e:
print('== no sctp support', file=sys.stderr)
try:
import platform
host_platform = platform.system()
except ImportError as e:
print('== cannot detect your OS', file=sys.stderr)
def help_sctp():
print()
print_white_bright("To install support for SCTP in linux:")
# pysctp3 from pip is **broken**
# print(" apt install libsctp-dev libsctp1 lksctp-tools")
# print(" pip3 install pysctp3")
# print()
print()
print_red(' =!= pip version 0.7 is broken =!=')
print()
print(" git clone https://github.com/P1sec/pysctp/")
print(" cd pysctp/")
print(" python setup.py install")
def str_time():
t = None
failed = False
try:
t = datetime.now()
except AttributeError:
failed = True
if not t and failed:
try:
t = datetime.datetime.now()
except AttributeError:
t = "<?>"
return socket.gethostname() + "@" + str(t)
def print_green_bright(what):
if Features.have_colorama:
print(Fore.GREEN + Style.BRIGHT + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_green(what):
if Features.have_colorama:
print(Fore.GREEN + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_yellow_bright(what):
if Features.have_colorama:
print(Fore.YELLOW + Style.BRIGHT + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_yellow(what):
if Features.have_colorama:
print(Fore.YELLOW + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_red_bright(what):
if Features.have_colorama:
print(Fore.RED + Style.BRIGHT + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_red(what):
if Features.have_colorama:
print(Fore.RED + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_white_bright(what):
if Features.have_colorama:
print(Fore.WHITE + Style.BRIGHT + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_white(what):
if Features.have_colorama:
print(Fore.WHITE + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_blue(what):
if Features.have_colorama:
print(Fore.BLUE + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def print_blue_bright(what):
if Features.have_colorama:
print(Fore.BLUE + Style.BRIGHT + what + Style.RESET_ALL, file=sys.stderr)
else:
print(what, file=sys.stderr)
def debuk(what):
if Features.debuk:
print_white(what)
def verbose(what):
if Features.verbose:
print_white(what)
__vis_filter = b"""................................ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[.]^_`abcdefghijklmnopqrstuvwxyz{|}~................................................................................................................................."""
def hexdump(xbuf, length=16):
"""Return a hexdump output string of the given buffer."""
n = 0
res = []
buf = bytearray(xbuf)
while buf:
line, buf = buf[:length], buf[length:]
hexa = ' '.join(['%02x' % x for x in line])
line = line.translate(__vis_filter).decode()
res.append(' %04d: %-*s %s' % (n, length * 3, hexa, line))
n += length
return '\n'.join(res)
def colorize(s, keywords):
t = s
for k in keywords:
t = re.sub(k, Fore.CYAN + Style.BRIGHT + k + Fore.RESET + Style.RESET_ALL, t)
return t
# download file from HTTP and store it in /tmp/, add it to g_delete_files
# so they are deleted at end of the program
def http_download_temp(url):
r = requests.get(url, stream=True)
if not r:
print_red_bright("cannot download: " + url)
sys.exit(1)
local_filename = tempfile.mkstemp(prefix="pplay_dwn_")[1]
g_delete_files.append(local_filename)
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
r.close()
print_green("downloaded file into " + local_filename)
return local_filename
class SxyCA:
SETTINGS = {
"ca": {},
"srv": {},
"clt": {},
"prt": {},
"path": "/tmp/",
"ttl": 60
}
class Options:
indent = 0
debug = False
@staticmethod
def pref_choice(*args):
for a in args:
if a:
return a
return None
@staticmethod
def init_directories(etc_dir):
SxyCA.SETTINGS["path"] = etc_dir
for X in [
SxyCA.SETTINGS["path"],
os.path.join(SxyCA.SETTINGS["path"], "certs/"),
os.path.join(SxyCA.SETTINGS["path"], "certs/", "default/")]:
if not os.path.isdir(X):
try:
os.mkdir(X)
except FileNotFoundError:
print(SxyCA.Options.indent * " " + "fatal: path {} doesn't exit".format(X))
return
except PermissionError:
print(SxyCA.Options.indent * " " + "fatal: Permission denied: {}".format(X))
return
SxyCA.SETTINGS["path"] = os.path.join(SxyCA.SETTINGS["path"], "certs/", "default/")
@staticmethod
def init_settings(cn, c, ou=None, o=None, l=None, s=None, def_subj_ca=None, def_subj_srv=None, def_subj_clt=None):
SxyCA.NameOIDMap = {
"cn": NameOID.COMMON_NAME,
"ou": NameOID.ORGANIZATIONAL_UNIT_NAME,
"o": NameOID.ORGANIZATION_NAME,
"l": NameOID.LOCALITY_NAME,
"s": NameOID.STATE_OR_PROVINCE_NAME,
"c": NameOID.COUNTRY_NAME
}
# we want to extend, but not overwrite already existing settings
SxyCA.load_settings()
r = SxyCA.SETTINGS
for k in ["ca", "srv", "clt", "prt"]:
if k not in r:
r[k] = {}
for k in ["ca", "srv", "clt", "prt"]:
if "ou" not in r[k]:
r[k]["ou"] = SxyCA.pref_choice(ou)
if "o" not in r[k]:
r[k]["o"] = SxyCA.pref_choice("Smithproxy Software")
if "s" not in r[k]:
r[k]["s"] = SxyCA.pref_choice(s)
if "l" not in r[k]:
r[k]["l"] = SxyCA.pref_choice(l)
if "c" not in r[k]:
r[k]["c"] = SxyCA.pref_choice("CZ", c)
if "cn" not in r["ca"]:
r["ca"]["cn"] = SxyCA.pref_choice(def_subj_ca, "Smithproxy Root CA")
if "cn" not in r["srv"]:
r["srv"]["cn"] = SxyCA.pref_choice(def_subj_srv, "Smithproxy Server Certificate")
if "cn" not in r["clt"]:
r["clt"]["cn"] = SxyCA.pref_choice(def_subj_clt, "Smithproxy Client Certificate")
if "cn" not in r["prt"]:
r["prt"]["cn"] = "Smithproxy Portal Certificate"
if "settings" not in r["ca"]:
r["ca"]["settings"] = {
"grant_ca": "false"
}
debuk("config to be written: %s" % (r,))
try:
with open(os.path.join(SxyCA.SETTINGS["path"], "sslca.json"), "w") as f:
json.dump(r, f, indent=4)
except Exception as e:
print(SxyCA.Options.indent * " " + "write_default_settings: exception caught: " + str(e))
@staticmethod
def load_settings():
try:
with open(os.path.join(SxyCA.SETTINGS["path"], "sslca.json"), "r") as f:
r = json.load(f)
if SxyCA.Options.debug: print(SxyCA.Options.indent * " " + "load_settings: loaded settings: {}",
str(r))
SxyCA.SETTINGS = r
except Exception as e:
print(SxyCA.Options.indent * " " + "load_default_settings: exception caught: " + str(e))
@staticmethod
def generate_rsa_key(size):
return rsa.generate_private_key(public_exponent=65537, key_size=size, backend=default_backend())
@staticmethod
def load_key(fnm, pwd=None):
with open(fnm, "rb") as key_file:
return serialization.load_pem_private_key(key_file.read(), password=pwd, backend=default_backend())
@staticmethod
def generate_ec_key(curve):
return ec.generate_private_key(curve=curve, backend=default_backend())
@staticmethod
def save_key(key, keyfile, passphrase=None):
# inner function
def choose_enc(pwd):
if not pwd:
return serialization.NoEncryption()
return serialization.BestAvailableEncryption(pwd)
try:
with open(os.path.join(SxyCA.SETTINGS['path'], keyfile), "wb") as f:
f.write(key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=choose_enc(passphrase),
))
except Exception as e:
print(SxyCA.Options.indent * " " + "save_key: exception caught: " + str(e))
@staticmethod
def construct_sn(profile, sn_override=None):
snlist = []
override = sn_override
if not sn_override:
override = {}
for subj_entry in ["cn", "ou", "o", "l", "s", "c"]:
if subj_entry in override and subj_entry in SxyCA.NameOIDMap:
snlist.append(x509.NameAttribute(SxyCA.NameOIDMap[subj_entry], override[subj_entry]))
elif subj_entry in SxyCA.SETTINGS[profile] \
and SxyCA.SETTINGS[profile][subj_entry] \
and subj_entry in SxyCA.NameOIDMap:
snlist.append(x509.NameAttribute(SxyCA.NameOIDMap[subj_entry], SxyCA.SETTINGS[profile][subj_entry]))
return snlist
@staticmethod
def generate_csr(key, profile, sans_dns=None, sans_ip=None, isca=False, custom_subj=None):
cn = SxyCA.SETTINGS[profile]["cn"].replace(" ", "-")
sn = x509.Name(SxyCA.construct_sn(profile, custom_subj))
sans_list = [x509.DNSName(cn)]
if sans_dns:
for s in sans_dns:
if s == cn:
continue
sans_list.append(x509.DNSName(s))
if sans_ip:
try:
import ipaddress
for i in sans_ip:
ii = ipaddress.ip_address(i)
sans_list.append(x509.IPAddress(ii))
except ImportError:
# cannot use ipaddress module
pass
sans = x509.SubjectAlternativeName(sans_list)
builder = x509.CertificateSigningRequestBuilder()
builder = builder.subject_name(sn)
if sans:
builder = builder.add_extension(sans, critical=False)
builder = builder.add_extension(
x509.BasicConstraints(ca=isca, path_length=None), critical=True)
if isca:
builder = builder.add_extension(x509.KeyUsage(crl_sign=True, key_cert_sign=True,
digital_signature=False, content_commitment=False,
key_encipherment=False, data_encipherment=False,
key_agreement=False, encipher_only=False,
decipher_only=False),
critical=True)
else:
builder = builder.add_extension(x509.KeyUsage(crl_sign=False, key_cert_sign=False,
digital_signature=True, content_commitment=False,
key_encipherment=True, data_encipherment=False,
key_agreement=False, encipher_only=False,
decipher_only=False),
critical=True)
ex = [x509.oid.ExtendedKeyUsageOID.SERVER_AUTH, x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH]
builder = builder.add_extension(x509.ExtendedKeyUsage(ex), critical=False)
csr = builder.sign(key, hashes.SHA256(), default_backend())
return csr
@staticmethod
def sign_csr(key, csr, caprofile, arg_valid=0, isca=False, cacert=None, aia_issuers=None, ocsp_responders=None):
valid = 30
if arg_valid > 0:
valid = arg_valid
else:
try:
valid = SxyCA.SETTINGS["ttl"]
except KeyError:
pass
one_day = datetime.timedelta(1, 0, 0)
builder = x509.CertificateBuilder()
builder = builder.subject_name(csr.subject)
if not cacert:
builder = builder.issuer_name(x509.Name(construct_sn(caprofile)))
else:
builder = builder.issuer_name(cacert.subject)
builder = builder.not_valid_before(datetime.datetime.today() - one_day)
builder = builder.not_valid_after(datetime.datetime.today() + (one_day * valid))
# builder = builder.serial_number(x509.random_serial_number()) # too new to some systems
builder = builder.serial_number(int.from_bytes(os.urandom(10), byteorder="big"))
builder = builder.public_key(csr.public_key())
builder = builder.add_extension(x509.SubjectKeyIdentifier.from_public_key(csr.public_key()), critical=False)
# more info about issuer
has_ski = False
try:
if cacert:
ski = cacert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
builder = builder.add_extension(
x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski.value),
critical=False)
has_ski = True
except AttributeError:
# workaround for older versions of python cryptography, not having from_issuer_subject_key_identifier
# -> which throws AttributeError
has_ski = False
except x509.extensions.ExtensionNotFound:
has_ski = False
if not has_ski:
builder = builder.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),
critical=False)
all_aias = []
if aia_issuers:
for loc in aia_issuers:
aia_uri = x509.AccessDescription(AuthorityInformationAccessOID.CA_ISSUERS,
x509.UniformResourceIdentifier(loc))
all_aias.append(aia_uri)
if ocsp_responders:
for resp in ocsp_responders:
aia_uri = x509.AccessDescription(AuthorityInformationAccessOID.OCSP,
x509.UniformResourceIdentifier(resp))
all_aias.append(aia_uri)
if all_aias:
alist = x509.AuthorityInformationAccess(all_aias)
builder = builder.add_extension(alist, critical=False)
if SxyCA.Options.debug: print(SxyCA.Options.indent * " " + "sign CSR: == extensions ==")
for e in csr.extensions:
if isinstance(e.value, x509.BasicConstraints):
if SxyCA.Options.debug: print(SxyCA.Options.indent * " " + "sign CSR: %s" % (e.oid,))
if e.value.ca:
if SxyCA.Options.debug: print((SxyCA.Options.indent + 2) * " " + " CA=TRUE requested")
if isca and not SxyCA.SETTINGS["ca"]["settings"]["grant_ca"]:
if SxyCA.Options.debug:
print((SxyCA.Options.indent + 2) * " " + " CA not allowed but overridden")
elif not SxyCA.SETTINGS["ca"]["settings"]["grant_ca"]:
if SxyCA.Options.debug:
print((SxyCA.Options.indent + 2) * " " + " CA not allowed by rule")
continue
else:
if SxyCA.Options.debug: print(
(SxyCA.Options.indent + 2) * " " + " CA allowed by rule")
builder = builder.add_extension(e.value, e.critical)
certificate = builder.sign(private_key=key, algorithm=hashes.SHA256(), backend=default_backend())
return certificate
@staticmethod
def save_certificate(cert, certfile):
try:
with open(os.path.join(SxyCA.SETTINGS['path'], certfile), "wb") as f:
f.write(cert.public_bytes(
encoding=serialization.Encoding.PEM))
except Exception as e:
print(SxyCA.Options.indent * " " + "save_certificate: exception caught: " + str(e))
@staticmethod
def load_certificate(fnm):
with open(fnm, 'r', encoding='utf-8') as f:
ff = f.read()
return x509.load_pem_x509_certificate(ff.encode('ascii'), backend=default_backend())
# BytesGenerator is convenient, deterministic bytes generator, which expands data
# based on its previous state
# given the same @magic and same sequence of rand_* requests, it will produce always
# the same data.
class BytesGenerator:
def __init__(self, magic, use_hash):
self.magic = magic
self.hash = use_hash
use_hash.update(self.magic.encode('ascii'))
self.state = use_hash.digest()
rep = 0
for i in self.state:
rep += int(i)
# self._strengthen(rep)
self.pool = b''
# update with one bock
self._get_bytes(1)
def _roll(self):
self.hash.update(self.state)
self.state = self.hash.digest()
def _strengthen(self, times):
rep = 0
while rep < times:
rep += 1
self._roll()
def _get_bytes(self, min_sz):
while len(self.pool) < min_sz:
self._roll()
self.pool += self.state
def rand_bytes(self, sz):
self._get_bytes(sz)
ret = self.pool[0:sz]
self.pool = self.pool[sz:]
return ret
def rand_int(self):
return struct.unpack('>l', self.rand_bytes(4))[0]
def rand_uint(self):
return struct.unpack('>L', self.rand_bytes(4))[0]
def rand_choice(self, lst):
return lst[self.rand_uint() % len(lst)]
@staticmethod
def _fillchart(beg, end, base=None):
x = ord(beg)
chart = [chr(x), ]
while x <= ord(end):
chart.append(chr(x))
x += 1
if base:
return base + chart
return chart
def rand_str(self, sz, low_cap=True, high_cap=True, nums=True, space=False, include_list=None, exclude_list=None):
ch = []
if low_cap:
ch = BytesGenerator._fillchart('a', 'z')
if high_cap:
ch = BytesGenerator._fillchart('A', 'Z', ch)
if nums:
ch = BytesGenerator._fillchart('0', '9', ch)
if space:
ch.append(' ')
if include_list:
ch += include_list
if exclude_list:
for ex in exclude_list:
try:
ch.remove(ex)
except ValueError as e:
pass
ret = ''
for i in range(0, sz):
ret += ch[self.rand_uint() % len(ch)]
return ret
def rand_range(self, a, b):
r = range(a, b)
return r[self.rand_uint() % len(r)]
def taint_str(self, orig, ceil=127, **kwargs):
mask = self.rand_bytes(len(orig))
ret = ''
for i in range(0, len(orig)):
if mask[i] > ceil:
ret += self.rand_str(1, **kwargs)
else:
ret += orig[i]
return ret
def taint_bytes(self, orig, ceil=127, **kwargs):
mask = self.rand_bytes(len(orig))
ret = bytearray()
for i in range(0, len(orig)):
if mask[i] > ceil:
ret += self.rand_bytes(1)
else:
a = orig[i]
ret.append(a)
return ret
class Repeater:
def __init__(self, fnm, server_ip, custom_sport=None):
self.fnm = fnm
self.select_timeout = 2
self.packets = []
self.origins = {}
# write this data :)
self.to_send = b''
# list of indexes in packets
self.origins['client'] = []
self.origins['server'] = []
self.sock = None
self.sock_upgraded = None
self.server_port = 0
self.custom_ip = server_ip
self.custom_sport = custom_sport # custom source port (only with for client connections)
self.whoami = ""
# index of our origin
self.packet_index = 0
# index of in all packets regardless of origin
self.total_packet_index = 0
# packet read counter (don't use it directly - for read_packet smart reads)
self.read_packet_counter = 0
self.use_ssl = False
self.sslv = 0
self.ssl_context = None
self.ssl_cipher = None
self.ssl_sni = None
self.ssl_alpn = None
self.ssl_ecdh_curve = None
self.ssl_cert = None
self.ssl_key = None
self.ssl_ca_cert = None
self.ssl_ca_key = None
self.tstamp_last_read = 0
self.tstamp_last_write = 0
self._last_countdown_print = 0
self.scripter = None
self.scripter_args = None
self.exitoneot = False
self.exitondiff = False
self.nostdin = False
self.nohexdump = False
self.omexit = False
self.is_udp = False
self.is_sctp = False
self.fuzz = False
self.scatter = False
# our peer (ip,port)
self.target = (0, 0)
# countdown timer for sending
self.send_countdown = 0
# ctrl-c counter (needed to break udp loop)
self.ctrc_count = 0
if host_platform and host_platform.startswith("Windows"):
self.nostdin = True
self.die_after = 0
self.deathhand = None
def reset(self):
self.to_send = ''
self.packet_index = 0
self.total_packet_index = 0
self.read_packet_counter = 0
# write @txt to temp file and return its full path
def deploy_tmp_file(self, text):
h, fnm = tempfile.mkstemp()
o = os.fdopen(h, "w")
o.write(text)
o.close()
g_delete_files.append(fnm)
return fnm
def load_scripter_defaults(self):
global g_delete_files
if self.scripter:
self.server_port = self.scripter.server_port
self.packets = self.scripter.packets
self.origins = self.scripter.origins
has_cert = False
has_ca = False
if self.scripter.ssl_cert and self.scripter.ssl_key:
has_cert = True
if self.scripter.ssl_ca_cert and self.scripter.ssl_ca_key:
has_ca = True
try:
if has_cert:
if self.scripter.ssl_cert and not self.ssl_cert:
self.ssl_cert = self.deploy_tmp_file(self.scripter.ssl_cert)
if self.scripter.ssl_key and not self.ssl_key:
self.ssl_key = self.deploy_tmp_file(self.scripter.ssl_key)
if has_ca:
if self.scripter.ssl_ca_cert and not self.ssl_ca_cert:
self.ssl_ca_cert = self.deploy_tmp_file(self.scripter.ssl_ca_cert)
print("deployed temp ca cert:" + self.ssl_ca_cert)
if self.scripter.ssl_ca_key and not self.ssl_ca_key:
self.ssl_ca_key = self.deploy_tmp_file(self.scripter.ssl_ca_key)
print("deployed temp ca key:" + self.ssl_ca_key)
except IOError as e:
print("error deploying temporary files: " + str(e))
def list_pcap(self, verbose=False, do_print=True):
flows = {}
ident = {}
frame = -1
first_ip_flow = None
if verbose:
print_yellow("# >>> Flow list:")
packets = rdpcap(self.fnm)
for packet in packets:
frame += 1
if packet.haslayer(IP):
l3_layer = IP
elif packet.haslayer(IPv6):
l3_layer = IPv6
else:
continue
try:
sip = packet[l3_layer].src
dip = packet[l3_layer].dst
except IndexError as e:
# not even IP packet
continue
sport = ""
dport = ""
# TCP
if packet[l3_layer].haslayer(TCP):
sport = str(packet[l3_layer][TCP].sport)
dport = str(packet[l3_layer][TCP].dport)
proto = "TCP"
elif packet[l3_layer].haslayer(UDP):
sport = str(packet[l3_layer][UDP].sport)
dport = str(packet[l3_layer][UDP].dport)
proto = "UDP"
elif packet[l3_layer].haslayer(SCTP):
sport = str(packet[l3_layer][SCTP].sport)
dport = str(packet[l3_layer][SCTP].dport)
print_white_bright("----")
packet[l3_layer][SCTP].show()
proto = "SCTP"
else:
proto = "Unknown"
# Unknown
if proto == "Unknown":
continue
# set a hint of the initial connection
if not first_ip_flow:
first_ip_flow = sip + ":" + sport
key = proto + " / " + sip + ":" + sport + " -> " + dip + ":" + dport
ident1 = sip + ":" + sport
ident2 = dip + ":" + dport
if key not in flows:
if verbose:
if do_print:
print_yellow("%s (starting at frame %d)" % (key, frame))
flows[key] = (ident1, ident2)
if ident1 not in ident.keys():
ident[ident1] = []
if ident2 not in ident.keys():
ident[ident2] = []
ident[ident1].append(key)
ident[ident2].append(key)
if do_print:
print_yellow("\n# >>> Usable connection IDs:\n")
if verbose:
print_white(" Yellow - probably services")
print_white(" Green - clients\n")
print_white("# More than 2 simplex flows:\n"
"# * source port reuse, or it's a service")
print_white("# * can't be used to uniquely dissect data from file.")
print_white("--")
candidate = None
for unique_ident in ident.keys():
port = unique_ident.split(":")[-1]
no_simplex_flows = len(ident[unique_ident])
if no_simplex_flows == 2:
if int(port) < 1024:
print_yellow(" " + unique_ident + " # %d simplex flows" % (no_simplex_flows,))
else:
# IANA suggests ephemeral port range starting at 49152, but many linuxes start already with 32768