-
Notifications
You must be signed in to change notification settings - Fork 0
/
Weapow.py
2126 lines (1775 loc) · 93.7 KB
/
Weapow.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
version = "v4.132-dev"
#########################################
## IMPORTAÇÃO DE BIBLIOTECAS PRINCIPAL ##
#########################################
import os
import re
import sys
import socket
import signal
import ipaddress
import time as t
import threading as th
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
###########################################################
## BANNER PRINCIPAL DO PROGRAMA, EXIBINDO A VERSÃO ATUAL ##
###########################################################
bann = f'''\033[1;33m
888 888 888 .d88b. 8888b. 88888b. .d88b. 888 888 888
888 888 888 d8P Y8b "88b 888 "88b d88""88b 888 888 888
888 888 888 88888888 .d888888 888 888 888 888 888 888 888
Y88b 888 d88P Y8b. 888 888 888 d88P Y88..88P Y88b 888 d88P
"Y8888888P" "Y8888 "Y888888 88888P" "Y88P" "Y8888888P"
\033[0;31m (\\ (\\\033[m \033[1;35m \033[m\033[1;33m888\033[m \033[7;32m{version}\033[m
\033[0;31m ( ^.^)\033[m\033[1;35m-------------------------\033[m\033[1;33m888\033[m
\033[0;31m O_(")(") \033[m \033[1;33m888\033[m\n '''
####################################################
## GRUPO DE VARIÁVEIS QUE SÃO REPETIDAS NO CODIGO ##
####################################################
press = '\033[7;31m(Pressione qualquer tecla para voltar ao menu inicial)\033[m'
Ctrl_C = 'Você pressionou Ctrl+C para interromper o programa!'
dir = 'mkdir -p ARQ'
SIGNALHOSTDISCOVERY = True
############################
## CRIA O DIRETÓRIO ./ARQ ##
############################
os.system(dir)
#########################################
## FUNÇÃO PARA INTERRUPÇÃO DO PROGRAMA ##
#########################################
def handler(signum, frame):
global pool
try:
pool.terminate()
except Exception as e:
pass
except KeyboardInterrupt:
pass
finally:
exit(0)
signal.signal(signal.SIGINT, handler)
#############################################################
## FUNÇÃO QUE BUSCA INTERFACES E CRIA UMA LISTA DE SELEÇÃO ##
#############################################################
def interfaces():
########################################
## CRIA UM MENU DE INTERFACES DE REDE ##
########################################
try:
interfaces = []
########################################################
## VERIFICA AS INTERFACES NO DIRETÓRIO A NIVEL KERNEL ##
########################################################
for interface_name in os.listdir('/sys/class/net'):
if interface_name == 'lo':
continue
interfaces.append(interface_name)
if not interfaces:
print("Nenhuma interface de rede encontrada.")
input(press)
main()
###################################################
## PARA CADA INTERFACE, E CRIADO UM ITEM NO MENU ##
###################################################
print("\nSelecione a interface de rede:")
for i, interface in enumerate((interfaces), 1):
print(f"\033[0;34m[{i}]\033[m - {interface}")
while True:
try:
escolha = int(input("Digite a opção: "))
if escolha < 0 or escolha > len(interfaces):
raise ValueError
break
if escolha == 0:
main()
except ValueError:
print("Opção inválida.")
###################################
## CASO SEJA "0" RETORNA AO MENU ##
###################################
if escolha == 0:
main()
selected_interface = interfaces[escolha - 1]
return selected_interface
except KeyboardInterrupt:
print('\n'+Ctrl_C)
quit()
#=======================================================================================
#############################################
## FUNÇÃO PARA DESCOBERTA DE HOSTS NA REDE ##
#############################################
def host_discovery():
###################################################
## DEFINE O NUMERO MÁXIMO DE THREADS SIMULTÂNEAS ##
###################################################
max_threads = 160
thread_semaphore = th.Semaphore(max_threads)
##########################################################
## EXECUTA O COMANDO PING + EXIBIR E SALVAR OS HOSTS-UP ##
##########################################################
def ping_host(ip):
with thread_semaphore:
ip = str(ip)
response = os.system(f'ping -c 2 -W 2 {ip} > /dev/null 2>&1')
if response == 0:
print(f"[+] Host ativo: {ip}")
with open('ARQ/hosts.txt', 'a') as f:
f.write(f'{ip}\n')
#########################################################
## CRIA UMA POOL PARA GERENCIAR A EXECUÇÃO DOS THREADS ##
#########################################################
def worker(subnet):
with ThreadPoolExecutor(max_workers=max_threads) as executor:
executor.map(ping_host, subnet)
##########################################
## INPUT PARA RECEBER A MÁSCARA DE REDE ##
##########################################
network = input("Digite a máscara de rede (Exemplo: 10.0.0.0/16): ")
os.system('rm -f ARQ/hosts.txt') # Limpa o arquivo anterior
all_hosts = list(ipaddress.IPv4Network(network, strict=False).hosts())
######################################################################
## DEFINE O NÚMERO DE PROCESSOS DE ACORDO COM A QUANTIDADE DE HOSTS ##
######################################################################
num_processes = multiprocessing.cpu_count()
chunk_size = len(all_hosts) // num_processes
##################################
## DISTRIBUIÇÃO ENTRE PROCESSOS ##
##################################
processes = []
for subnet in [all_hosts[i:i + chunk_size] for i in range(0, len(all_hosts), chunk_size)]:
p = multiprocessing.Process(target=worker, args=(subnet,))
processes.append(p)
p.start()
###################################
## AGUARDA OS PROCESSOS TERMINAR ##
###################################
for p in processes:
p.join()
input(press)
main()
#=======================================================================================
############################################
## PORTAS A SEREM VERIFICADAS NO PORTSCAN ##
############################################
PORTAS_PRINCIPAIS = [
1, 3, 4, 6, 7, 9, 13, 17, 19, 20, 21, 22, 23, 24, 25, 26, 30, 32, 33, 37, 42, 43, 49, 53, 70, 79, 80, 81, 82, 83, 84, 85, 88, 89, 90, 99, 100, 106, 109, 110, 111, 113, 119, 125, 135, 139, 143, 144, 146, 161, 163, 179, 199, 211,
212, 222, 254, 255, 256, 259, 264, 280, 301, 306, 311, 340, 366, 389, 406, 407, 416, 417, 425, 427, 443, 444, 445, 458, 464, 465, 481, 497, 500, 512, 513, 514, 515, 524, 541, 543, 544, 545, 548, 554, 555, 563, 587, 593, 616, 617,
625, 631, 636, 646, 648, 666, 667, 668, 683, 687, 691, 700, 705, 711, 714, 720, 722, 726, 749, 765, 777, 783, 787, 800, 801, 808, 843, 873, 880, 888, 898, 900, 901, 902, 903, 911, 912, 981, 987, 990, 992, 993, 995, 999, 1000, 1001,
1002, 1007, 1009, 1010, 1011, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055,
1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095,
1096, 1097, 1098, 1099, 1100, 1102, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1117, 1119, 1121, 1122, 1123, 1124, 1126, 1130, 1131, 1132, 1137, 1138, 1141, 1145, 1147, 1148, 1149, 1151, 1152, 1154, 1163, 1164, 1165, 1166,
1169, 1174, 1175, 1183, 1185, 1186, 1187, 1192, 1198, 1199, 1201, 1213, 1216, 1217, 1218, 1233, 1234, 1236, 1244, 1247, 1248, 1259, 1271, 1272, 1277, 1287, 1296, 1300, 1301, 1309, 1310, 1311, 1322, 1328, 1334, 1352, 1417, 1433, 1434, 1443,
1455, 1461, 1494, 1500, 1501, 1503, 1521, 1524, 1533, 1556, 1580, 1583, 1594, 1600, 1641, 1658, 1666, 1687, 1688, 1700, 1717, 1718, 1719, 1720, 1721, 1723, 1755, 1761, 1782, 1783, 1801, 1805, 1812, 1839, 1840, 1862, 1863, 1864, 1875, 1900,
1914, 1935, 1947, 1971, 1972, 1974, 1984, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2013, 2020, 2021, 2022, 2030, 2033, 2034, 2035, 2038, 2040, 2041, 2042, 2043, 2045, 2046, 2047, 2048, 2049, 2065, 2068,
2099, 2100, 2103, 2105, 2106, 2107, 2111, 2119, 2121, 2126, 2135, 2144, 2160, 2161, 2170, 2179, 2190, 2191, 2196, 2200, 2222, 2251, 2260, 2288, 2301, 2323, 2366, 2381, 2382, 2383, 2393, 2394, 2399, 2401, 2492, 2500, 2522, 2525, 2557, 2601,
2602, 2604, 2605, 2607, 2608, 2638, 2701, 2702, 2710, 2717, 2718, 2725, 2800, 2809, 2811, 2869, 2875, 2909, 2910, 2920, 2967, 2968, 2998, 3000, 3001, 3003, 3005, 3006, 3007, 3011, 3013, 3017, 3030, 3031, 3052, 3071, 3077, 3128, 3168, 3211,
3221, 3260, 3261, 3268, 3269, 3283, 3300, 3301, 3306, 3322, 3323, 3324, 3325, 3333, 3351, 3367, 3369, 3370, 3371, 3372, 3389, 3390, 3404, 3476, 3493, 3517, 3527, 3546, 3551, 3580, 3659, 3689, 3690, 3703, 3737, 3766, 3784, 3800, 3801, 3809,
3814, 3826, 3827, 3828, 3851, 3869, 3871, 3878, 3880, 3889, 3905, 3914, 3918, 3920, 3945, 3971, 3986, 3995, 3998, 4000, 4001, 4002, 4003, 4004, 4005, 4006, 4045, 4111, 4125, 4126, 4129, 4224, 4242, 4279, 4321, 4343, 4443, 4444, 4445, 4446,
4449, 4550, 4567, 4662, 4848, 4899, 4900, 4998, 5000, 5001, 5002, 5003, 5004, 5009, 5030, 5033, 5050, 5051, 5054, 5060, 5061, 5080, 5087, 5100, 5101, 5102, 5120, 5190, 5200, 5214, 5221, 5222, 5225, 5226, 5269, 5280, 5298, 5357, 5405, 5414,
5431, 5432, 5440, 5500, 5510, 5544, 5550, 5555, 5560, 5566, 5631, 5633, 5666, 5678, 5679, 5718, 5730, 5800, 5801, 5802, 5810, 5811, 5815, 5822, 5825, 5850, 5859, 5862, 5877, 5900, 5901, 5902, 5903, 5904, 5906, 5907, 5910, 5911, 5915, 5922,
5925, 5950, 5952, 5959, 5960, 5961, 5962, 5963, 5987, 5988, 5989, 5998, 5999, 6000, 6001, 6002, 6003, 6004, 6005, 6006, 6007, 6009, 6025, 6059, 6100, 6101, 6106, 6112, 6123, 6129, 6156, 6346, 6389, 6502, 6510, 6543, 6547, 6565, 6566, 6567,
6580, 6646, 6666, 6667, 6668, 6669, 6689, 6692, 6699, 6779, 6788, 6789, 6792, 6839, 6881, 6901, 6969, 7000, 7001, 7002, 7004, 7007, 7019, 7025, 7070, 7100, 7103, 7106, 7200, 7201, 7402, 7435, 7443, 7496, 7512, 7625, 7627, 7676, 7741, 7777,
7778, 7800, 7911, 7920, 7921, 7937, 7938, 7999, 8000, 8001, 8002, 8007, 8008, 8009, 8010, 8011, 8021, 8022, 8031, 8042, 8045, 8080, 8081, 8082, 8083, 8084, 8085, 8086, 8087, 8088, 8089, 8090, 8093, 8099, 8100, 8180, 8181, 8192, 8193, 8194,
8200, 8222, 8254, 8290, 8291, 8292, 8300, 8333, 8383, 8400, 8402, 8443, 8500, 8600, 8649, 8651, 8652, 8654, 8701, 8728, 8800, 8873, 8888, 8899, 8994, 9000, 9001, 9002, 9003, 9009, 9010, 9011, 9040, 9050, 9071, 9080, 9081, 9090, 9091, 9099, 9100,
9101, 9102, 9103, 9110, 9111, 9200, 9207, 9220, 9290, 9415, 9418, 9485, 9500, 9502, 9503, 9535, 9575, 9593, 9594, 9595, 9618, 9666, 9876, 9877, 9878, 9898, 9900, 9917, 9929, 9943, 9944, 9968, 9998, 9999, 10000, 10001, 10002, 10003, 10004,
10009, 10010, 10012, 10024, 10025, 10082, 10180, 10215, 10243, 10566, 10616, 10617, 10621, 10626, 10628, 10629, 10778, 11110, 11111, 11967, 12000, 12174, 12265, 12345, 13456, 13722, 13782, 13783, 14000, 14238, 14441, 14442, 15000, 15002,
15003, 15004, 15660, 15742, 16000, 16001, 16012, 16016, 16018, 16080, 16113, 16992, 16993, 17877, 17988, 18040, 18101, 18988, 19101, 19283, 19315, 19350, 19780, 19801, 19842, 20000, 20005, 20031, 20221, 20222, 20828, 21571, 22939, 23502,
24444, 24800, 25734, 25735, 26214, 27000, 27352, 27353, 27355, 27356, 27715, 28201, 30000, 30718, 30951, 31038, 31337, 32768, 32769, 32770, 32771, 32772, 32773, 32774, 32775, 32776, 32777, 32778, 32779, 32780, 32781, 32782, 32783, 32784,
32785, 33354, 33899, 34571, 34572, 34573, 35500, 38292, 40193, 40911, 41511, 42510, 44176, 44442, 44443, 44501, 45100, 48080, 49152, 49153, 49154, 49155, 49156, 49157, 49158, 49159, 49160, 49161, 49163, 49165, 49167, 49175, 49176, 49400,
49999, 50000, 50001, 50002, 50003, 50006, 50300, 50389, 50500, 50636, 50800, 51103, 51493, 52673, 52822, 52848, 52869, 54045, 54328, 55055, 55056, 55555, 55600, 56737, 56738, 57294, 57797, 58080, 60020, 60443, 61532, 61900, 62078, 63331,
64623, 64680, 65000, 65129, 65389
]
########################################################################
## FUNÇÃO QUE REALIZA A TENTATIVA DE CONEXÃO DE ACORDO COM HOST/PORTA ##
########################################################################
def scan(host, porta):
try:
l = len(str(porta))
espaco = " " * (10 - l)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(5.5)
if s.connect_ex((host, int(porta))) == 0:
with open("ARQ/portscan.txt", "a") as f:
try:
service = socket.getservbyport(porta)
print(f"{str(porta)} / TCP{espaco}{service}")
print(f"{str(porta)} / TCP{espaco}{service}", file=f)
except socket.error:
print(str(porta) + f" / TCP")
print(str(porta) + f" / TCP", file=f)
except Exception as e:
pass
##################################################################################
## ESTA FUNÇÃO FAZ UM PORTSCAN DE ACORDO COM A LISTA GERADO PELO HOST DISCOVERY ##
##################################################################################
def big_scan():
##############################################################
## FUNÇÃO PRINCIPAL QUE REALIZA O GERENCIAMENTO DO PORTSCAN ##
##############################################################
def uniq(host):
try:
with open("ARQ/portscan.txt", "a") as f:
print("\n[+] Host: " + host)
print("\n[+] Host: " + host, file=f)
print("PORTA SERVIÇO")
print("PORTA SERVIÇO", file=f)
host_ip = socket.gethostbyname(host)
except socket.gaierror:
return
global pool
pool = multiprocessing.Pool(processes=220)
try:
for porta in PORTAS_PRINCIPAIS:
pool.apply_async(scan, args=(host_ip, porta))
pool.close()
pool.join()
except Exception as e:
pool.terminate()
pool.join()
###########################################################
## INTERAÇÃO COM O USUÁRIO PARA DIRECIONAMENTO DA FUNÇÃO ##
###########################################################
os.popen('rm ARQ/portscan.txt 2>/dev/null')
sit_scan = input('Deseja utilizar um (H)ost ou a (L)ista? (H/L): ')
if sit_scan.lower() == 'h':
host = input("Digite o endereço IP ou domínio: ")
uniq(host)
elif sit_scan.lower() == 'l':
with open('ARQ/hosts.txt','r') as file:
for line in file:
uniq(line.strip())
#===============================================================================
def world_scan():
#####################################################
## DEFINE O NÚMERO DE THREADS E CRIA UM "SEMAFORO" ##
#####################################################
MAX_THREADS = 600
thread_semaphore = th.Semaphore(MAX_THREADS)
########################################################################
## FUNÇÃO QUE REALIZA A TENTATIVA DE CONEXÃO DE ACORDO COM HOST/PORTA ##
########################################################################
def scan(ip,porta):
try:
host = str(ip)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((host, porta))
if result == 0:
print(f"Port {porta} is open on {host}")
with open(f'World_Port_{porta}.txt','a') as f:
print(host, file=f)
sock.close()
except Exception as e:
print(f"Error scanning {ip}: {e}")
finally:
############################################################
## Sempre libere o semáforo, mesmo se ocorrer uma exceção ##
############################################################
thread_semaphore.release()
def worker(ips,porta):
threads = []
for ip in ips:
## Adquire o semáforo antes de criar uma nova thread ##
thread_semaphore.acquire()
t = th.Thread(target=scan, args=(ip,porta))
t.start()
threads.append(t)
# Aguardar todas as threads terminarem
for t in threads:
t.join()
ips = input('Digite a faixa de IP (Ex: xx.xx.xx.xx/xx): ')
porta = int(input('Qual porta? '))
####################################################
## CRIA A REDE DE ACORDO COM A ENTRADA DO USUÁRIO ##
####################################################
network = ipaddress.ip_network(ips, strict=False)
ips_list = list(map(str, network.hosts()))
# Dividindo a lista de IPs em partes para cada processo
num_processes = multiprocessing.cpu_count()
chunk_size = len(ips_list) // num_processes
chunks = []
for i in range(0, len(ips_list), chunk_size):
chunks.append(ips_list[i:i+chunk_size])
# Iniciando a barra de progresso fora do loop de chunks
total_ips = 0
for chunk in chunks:
total_ips += len(chunk)
# Iniciando processos para escanear em paralelo
processes = []
for chunk in chunks:
p = multiprocessing.Process(target=worker, args=(chunk,porta))
p.start()
processes.append(p)
# Aguardando todos os processos terminarem
for p in processes:
p.join()
#=======================================================================================
######################################################################
## ENVIA UMA CONEXÃO VIA NETCAT PARA RETORNAR UM POSSÍVEL CABEÇALHO ##
######################################################################
def nc_get():
os.popen('rm ARQ/HEAD/* 2>/dev/null')
os.makedirs("ARQ/HEAD", exist_ok=True)
print('No código, existe a função nc(), mais lenta e verifica todas as portas.')
def get(host, porta, servico):
try:
comando = f'echo -e "\n" | nc -vn -w 10 {host} {porta} 2>&1 | tee'
resultado = os.popen(comando).read()
caminho_arquivo = f"ARQ/HEAD/{host}"
with open(caminho_arquivo, "a") as arquivo_respostas:
arquivo_respostas.write(f"[+] Host: {host} Porta: {porta} Serviço: {servico}\t\t\n{resultado}\n")
print(f"[+] Host: {host} Porta: {porta} Serviço: {servico}\t\t\n{resultado}\n")
except Exception as e:
print(f"Erro ao executar o comando nc: {e}")
with open("ARQ/portscan.txt", "r") as arquivo:
linhas = arquivo.read().strip().split('\n')
for linha in linhas:
if '[+] Host:' in linha:
host = linha.split(':')[-1].strip()
elif 'PORTA' not in linha and '/' in linha:
porta, servico = map(str.strip, linha.split('/')[0:2])
t = th.Thread(target=get, args=(host, porta, servico))
t.start()
input(press)
main()
#=======================================================================================
###########################################################################
## VERIFICA SE EXISTE RESPOSTA "HTTP" OU "HTTPS" APOS O COMANDO "nc -vz" ##
###########################################################################
def http_finder():
###################################################
## ESTA FUNÇÃO FAZ O DOWNLOAD DO SITE ENCONTRADO ##
###################################################
def wget_pg(ip, porta):
os.system(f"rm ARQ/WEB/{ip}.html")
os.system(f'wget --no-check-certificate --mirror --convert-links --adjust-extension --page-requisites --timeout=10 http://{ip}:{porta} -P ARQ/WEB/')
os.system(f'chmod 777 -R ARQ/WEB/{ip}')
for ip in os.listdir("ARQ/HEAD"):
arquivo = os.path.join("ARQ/HEAD", ip)
if os.path.isfile(arquivo):
with open(arquivo, 'r') as arquivo:
conteudo = arquivo.readlines()
servico_web_encontrado = False
porta = None
for linha in conteudo:
match = re.search(r'Porta: (\d+)', linha)
if match:
porta = match.group(1)
if "http" in linha.lower() or "https" in linha.lower():
servico_web_encontrado = True
break
if servico_web_encontrado:
thread = th.Thread(target=wget_pg, args=(ip, porta))
thread.start()
for thread in th.enumerate():
if thread != th.current_thread():
thread.join()
input(press)
main()
#=======================================================================================
def cert_subdomain():
target_domain = input('Digite o dominio: ')
target = target_domain.replace('www.', '').split('/')[0]
try:
req = requests.get(f"https://crt.sh/?q=%.{target}&output=json")
req.raise_for_status()
except requests.RequestException:
print("[X] Information not available!")
subdomains = sorted({value['name_value'] for value in req.json()})
print(f"\n[!] TARGET: {target} [!] \n")
for subdomain in subdomains:
print(subdomain)
#=======================================================================================
def link():
# Função para realizar o crawling na URL
def crawl(url):
try:
response = requests.get(url)
response.raise_for_status() # Verifica se há erros no status
except (SSLError, requests.exceptions.RequestException) as e:
print(f"Erro ao acessar {url}: {e}")
return []
soup = BeautifulSoup(response.content, 'html.parser')
links = {urljoin(url, link['href']) for link in soup.find_all('a') if 'href' in link.attrs}
return links
# Função para extrair informações da URL
def ext_info(url):
durls = []
emails = set()
tel = set()
forms = []
subdomains = set()
try:
response = requests.get(url)
response.raise_for_status()
except (SSLError, requests.exceptions.RequestException) as e:
print(f"Erro ao acessar {url}: {e}")
return durls, emails, tel, forms, subdomains
soup = BeautifulSoup(response.content, 'html.parser')
# Extração de URLs
for link in soup.find_all('a', href=True):
href = link['href']
if href.startswith(('/', '?')):
durls.append(urljoin(url, href))
# Extração de emails e telefones
for link in soup.find_all('a', href=True):
href = link['href']
if href.startswith("mailto:"):
emails.add(href[7:])
elif href.startswith("tel:") or "phone=" in href:
tel.add(href[4:])
# Extração de formulários
forms.extend(url for _ in soup.find_all('form'))
# Extração de subdomínios
for link in soup.find_all('a', href=True):
parsed_uri = urlparse(link['href'])
domain = parsed_uri.netloc.split(':')[0]
if domain:
subdomains.add(domain)
return durls, emails, tel, forms, subdomains
# Função que processa cada URL
def process_url(url, visited_urls):
if url in visited_urls:
return
visited_urls.add(url)
divurls = crawl(url)
print(f"\n\nEfetuando WebCrawling em {url}")
for divurl in sorted(divurls):
print(f'\n{"="*92}>> {t.strftime("%d/%m/%y %H:%M:%S")}')
print(divurl)
print(f'{"="*92}>>')
durls, emails, tel, forms, subdomains = ext_info(divurl)
if durls:
print('\nURLs INTERNAS:')
for u in durls:
print(u)
if emails:
print('\nEMAILS:')
for email in emails:
print(email)
if tel:
print('\nTELEFONES:')
for phone in tel:
print(phone)
if forms:
print('\nFORMULÁRIOS:')
for form in forms:
print(form)
if subdomains:
print('\nSUBDOMÍNIOS:')
for subdomain in subdomains:
print(subdomain)
# Função principal de processamento
def links(target):
visited_urls = set()
url_to_process = ['http://' + target]
with open(f'Crawl/{target}_craw.txt', 'w') as f:
while url_to_process:
current_url = url_to_process.pop()
f.write(process_url(current_url, visited_urls))
# Preparação do ambiente de saída
os.system('rm -rf Crawl')
t.sleep(1)
os.system('mkdir Crawl')
# Escolha de host ou lista de sites
sit_scan = input('Deseja utilizar um (H)ost ou a (L)ista? (H/L): ').lower()
if sit_scan == 'h':
target = input('Digite o endereço do site (ex: site.com):\n')
links(target)
elif sit_scan == 'l':
for ip in os.listdir("ARQ/WEB"):
parse_ip = ip.split(':')[0]
result = os.system(f'ping -c 3 -W 1 {parse_ip} > /dev/null')
if result == 0:
links(parse_ip)
nsit = input(f'A busca em {parse_ip} terminou. Deseja continuar? (S/N): ').lower()
if nsit != 's':
break
#=======================================================================================
##################################################################
## FAZ UMA VERIFICAÇÃO NOS SITES BAIXADOS, BUSCANDO FORMULÁRIOS ##
##################################################################
def auto_web():
ips = os.popen(r'grep -iR -A 5 "<form" ARQ/WEB | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | sort -u').read().split()
try:
#########################################################
## FAZ UMA VARREDURA NO ARQUIVO QUE TIVER "index.html" ##
#########################################################
for ip in ips:
caminho_html = f'ARQ/WEB/{ip}/index.html'
with open(caminho_html, 'r', encoding='utf-8') as arquivo:
conteudo_html = arquivo.read()
soup = BeautifulSoup(conteudo_html, 'html.parser')
formularios = soup.find_all('form', {'action': True, 'method': True})
if ip and formularios:
print('---------------------------------------------------------')
print(f'\nAnalisando {ip}:\n')
soup = BeautifulSoup(conteudo_html, 'html.parser')
formularios = soup.find_all('form', {'action': True, 'method': True})
for formulario in formularios:
print(f'Atributo action: {formulario["action"]}')
print(f'Atributo method: {formulario["method"]}')
print(f'Conteúdo do formulário:')
print(formulario.prettify())
print('---------------------------------------------------------\n')
########################################################
## FAZ UMA VARREDURA NO ARQUIVO QUE TIVER "index.php" ##
########################################################
for ip in ips:
caminho_html = f'ARQ/WEB/{ip}/index.php'
with open(caminho_html, 'r', encoding='utf-8') as arquivo:
conteudo_html = arquivo.read()
soup = BeautifulSoup(conteudo_html, 'html.parser')
formularios = soup.find_all('form', {'action': True, 'method': True})
if ip and formularios:
print('---------------------------------------------------------')
print(f'\nAnalisando {ip}:\n')
soup = BeautifulSoup(conteudo_html, 'html.parser')
formularios = soup.find_all('form', {'action': True, 'method': True})
for formulario in formularios:
print(f'Atributo action: {formulario["action"]}')
print(f'Atributo method: {formulario["method"]}')
print(f'Conteúdo do formulário:')
print(formulario.prettify())
print('---------------------------------------------------------\n')
except FileNotFoundError:
pass
input("Pressione Enter para continuar...")
main()
#=======================================================================================
def ferramentas():
print("Esta opção irá instalar um conjunto de ferramentas uteis para RECON + PENTEST.")
sit_tool = input('Deseja continuar? (S/N) ')
#separar as ferramentas
#verificar se root ou nao
#verificar sistema operacional
#verificar se as ferramentas estao instaladas
#fazer um menu de check
#instalar cada ferramenta
try:
pass
except KeyboardInterrupt:
print('\n'+Ctrl_C)
#=======================================================================================
def backup():
print("Este processo poderá levar MUITO tempo dependendo da quantidade de arquivos.")
sit_bak = input('Deseja realmente fazer BKP do usuário desta estação? (S/N) ')
try:
if(sit_bak.lower() == "s"):
dir = input("Digite o diretório a ser feito o BKP:\n")
print('Fazendo BACKUP ...')
t.sleep(2)
os.system(f'cp -v -r {dir} /home/$USER/Backup')
else:
input(press)
main()
except KeyboardInterrupt:
print('\n'+Ctrl_C)
#=======================================================================================
def clonar():
'''
df -h
umount -t ext4 /dev/sdx && mkfs.ext4 /dev/sdx
dd if=/deb/sdx of=/dev/sdy bs=1M conv=noerror
sudo blkid
sudo nano /etc/fstab
'''
pass
#=======================================================================================
def cron():
print('''
Para configurar uma rotina C[R]ON:
\033[1;33m* * * * * /usr/bin/python3 /caminho/do/script.*\033[m
\033[0;31m- - - - - | |\033[m
\033[0;31m| | | | | +---\033[m Caminho do Executável\033[m \033[0;31m+---\033[m Extensão do arquivo a ser Executado. Ex: .sh .c .py
\033[0;31m| | | | |
\033[0;31m| | | | +----------------------\033[m Dia da Semana (0-6) [Sendo 0 = Domingo]
\033[0;31m| | | +-------------------------\033[m Mês (1-12)
\033[0;31m| | +----------------------------\033[m Dia do Mês (1-31)
\033[0;31m| +-------------------------------\033[m Hora (0-23)
\033[0;31m+----------------------------------\033[m Minutos (0-59) se quiser a cada 15min use: '/15'
Exemplo:
\033[7;33m*/15 * * * * /usr/bin/python3 /caminho/do/weapow.py\033[m [A cada 15min EXEC o arquivo weapow.py usando Python3]
\033[7;33m30 15 14 6 * /tmp/backup.sh\033[m [No dia 14JUN às 15:30 EXEC o backup.sh]
Você pode conferir a alteração com o comando: "\033[0;34m$ crontab -e\033[m"
''')
sit_cron = input("Deseja substituir as configurações do C[R]ON? (S/N)")
if(sit_cron.lower() == "s"):
try:
enter = input("Digite a entrada do C[R]ON:\n")
os.system(f'echo "{enter}" | crontab -')
print('C[R]ON configurado corretamente.')
input(press)
main()
except TypeError:
print("Faltam [Argumentos] para entrada")
input(press)
main()
else:
input(press)
main()
#=======================================================================================
def finder():
try:
find = str(input('Digite o arquivo que deseja encontrar: '))
print('Procurando com FIND:')
print('==================================================================================\n')
os.system(f' find / -name {find} 2>/dev/null | grep {find}')
print('Procurando com GREP:')
print('==================================================================================\n')
os.system(f' grep -iRl {find} / 2>/dev/null')
print('\n==================================================================================')
print('Fim da busca!\n')
input(press)
main()
except KeyboardInterrupt:
print('\n'+Ctrl_C)
#=======================================================================================
def infosys():
try:
output = ''
output += '\n'
output += 'WHOAMI =======================================================\n'
output += ' User: {}'.format(os.popen('whoami').read())
output += os.popen('hostnamectl').read()
output += ' IPAddress : {}'.format(os.popen("ip addr | awk '/inet / {if (++n == 2) print $2}'").read())
output +="\n Current Path : {}".format(os.popen('pwd').read())
output +='===============================================================\n'
output += '\n'
output += 'ID ============================================================\n'
output += os.popen('id').read()
output += '===============================================================\n'
output += '\n'
output += 'UNAME =========================================================\n'
output += os.popen('uname -a').read()
output += os.popen('cat /proc/cmdline').read()
output += '===============================================================\n'
output += '\n'
output += 'TTY +==========================================================\n'
output += os.popen('who').read()
output += os.popen('cat /proc/consoles').read()
output += '===============================================================\n'
output += '\n'
output += 'CPU ===========================================================\n'
output += os.popen('cat /proc/cpuinfo | grep "model name" | uniq').read()
output += os.popen(''' cat /proc/cpuinfo | awk '/cpu cores/ {gsub("cpu cores", "Cores"); print}' | uniq''').read()
output += os.popen(''' cat /proc/cpuinfo | awk '/siblings/ {gsub("siblings", "Threads"); print}' | uniq''').read()
output += '===============================================================\n'
output += '\n'
output += 'MEMÓRIA ========================================================\n'
output += os.popen('cat /proc/meminfo | grep MemTotal').read()
output += os.popen('cat /proc/meminfo | grep MemFree').read()
output += os.popen('cat /proc/meminfo | grep MemAvailable').read()
output += os.popen('cat /proc/meminfo | grep SwapTotal').read()
output += os.popen('cat /proc/meminfo | grep SwapFree').read()
output += '===============================================================\n'
output += '\n'
output += 'REDES =========================================================\n'
output += os.popen('ip addr').read()
output += '===============================================================\n'
output += '\n'
output += 'NETSTAT =======================================================\n'
output += os.popen('netstat -ano').read()
output += '\n'
output += os.popen('netstat -nr').read()
output += '===============================================================\n'
output += '\n'
output += 'ROTAS =========================================================\n'
output += os.popen('cat /proc/net/route').read()
output += '===============================================================\n'
output += '\n'
output += 'SISTEMAS ======================================================\n'
output += os.popen('df -h').read()
output += '===============================================================\n'
output += '\n'
output += 'PARTIÇÕES =====================================================\n'
output += os.popen('lsblk -p -f -o NAME,FSTYPE,LABEL,UUID,SIZE,TYPE,TRAN,MODE').read()
output += '===============================================================\n'
output += '\n'
output += 'USB ===========================================================\n'
output += os.popen('cat /etc/modprobe.d/blacklist.conf ').read()
output += '===============================================================\n'
output += '\n'
output += 'DISPOSITIVOS ==================================================\n'
output += os.popen('cat /proc/devices').read()
output += '===============================================================\n'
output += '\n'
output += 'LSPCI =========================================================\n'
output += os.popen('lspci').read()
output += '===============================================================\n'
output += '\n'
output += 'LSUSB =========================================================\n'
output += os.popen('lsusb').read()
output += '===============================================================\n'
output += '\n'
output += 'LSLOGINS ======================================================\n'
output += os.popen('lslogins').read()
output += '===============================================================\n'
output += '\n'
output += 'CAPTIVEF ======================================================\n'
output += os.popen('echo Travando o programa.').read()
#output += os.popen('getcap -r / 2>/dev/null').read()
output += '===============================================================\n'
output += '\n'
output += 'VARIAVEIS DE AMBIENTE =========================================\n'
output += os.popen('env').read()
output += '===============================================================\n'
output += '\n'
output += 'PROCESSOS =====================================================\n'
output += os.popen('ps axjf').read()
output += '===============================================================\n'
output += '\n'
output += 'SERVIÇOS ======================================================\n'
output += os.popen('systemctl --type=service --state=active | grep ^').read()
output += '===============================================================\n'
prog = input('Deseja exibir os programas instalados? (S/N) ')
if(prog.lower() == "s"):
output += '\n'
output += 'PROGRAMAS INSTALADOS ===========================================\n'
output += os.popen('dpkg --list | grep ^ii.').read()
output += '===============================================================\n'
output += '\n'
output += 'BASH HISTORY===================================================\n'
output += 'O histórico do BASH deve ser salvo manualmente por enquanto!\n'
output += 'Use o comando: $ history\n'
output += '===============================================================\n'
print(output)
sit_audi = input('Deseja salvar em arquivo? (S/N) ')
if(sit_audi.lower() == "s"):
os.system('rm -rf ARQ/auditoria.txt')
with open('ARQ/auditoria.txt', 'w') as file:
file.write(output)
print('Seu Arquivo foi gerado com Sucesso!')
input(press)
main()
else:
input(press)
main()
except KeyboardInterrupt:
print('\n'+Ctrl_C)
except FileNotFoundError:
os.system(dir)
with open('ARQ/auditoria.txt', 'w') as file:
file.write(output)
print('Seu Arquivo foi gerado com Sucesso!')
input(press)
main()
#=======================================================================================
def config():
os.system('clear')
ver = "v1.0-dev"
print(f'''\033[1;33m
.d8888b. .d888 d8b 88888888888 888
d88P Y88b d88P" Y8P 888 888
888 888 888 888 888
888 .d88b. 88888b. 888888 888 .d88b. 888 .d88b. .d88b. 888
888 d88""88b 888 "88b 888 888 d88P"88b 888 d88""88b d88""88b 888
888 888 888 888 888 888 888 888 888 888 888 888 888 888 888 888
Y88b d88P Y88..88P 888 888 888 888 Y88b 888 888 Y88..88P Y88..88P 888
"Y8888P" "Y88P" 888 888 888 888 "Y88888 888 "Y88P" "Y88P" 888
888
Y8b d88P \033[0;31m>Esta função precisa de Atenção!\033[m
"Y88P" \033[7;32m{ver}\033[m''')
print(''' MENU:
\033[0;34m[1]\033[m - Criar usuário em RBASH
\033[0;34m[2]\033[m - Permitir BASH padrão
\033[0;34m[3]\033[m - Restringir TODOS os comandos
\033[0;34m[4]\033[m - Config SSH
\033[0;34m[5]\033[m - xxx
\033[0;34m[6]\033[m - xxx
\033[0;34m[7]\033[m - xxx
\033[0;34m[8]\033[m - xxx
\033[0;34m[9]\033[m - xxx
\033[0;34m[10]\033[m- xxx
''')
try:
opcao=int(input('Escolha uma opção: '))
if opcao == 1:
user = input('Qual o usuário a ser configurado? ')
os.system(f" useradd -m -s /bin/rbash {user}")
senha = g.getpass("Digite a senha: ")
os.system(f"echo '{user}:{senha}' | chpasswd")
os.system(f" chown root: /home/{user}/.profile")
os.system(f" chown root: /home/{user}/.bashrc")
os.system(f" chmod 755 /home/{user}/.profile")
os.system(f" chmod 755 /home/{user}/.bashrc")
print(f"Usuário '{user}' criado com sucesso, senha definida e permissões ajustadas.")
input(press)
main()
elif opcao == 2:
user = input('Qual o usuário a ser configurado? ')
os.system(f" usermod --shell /bin/bash {user}")
elif opcao == 3:
if os.path.exists('/usr/share/block'):
print("O script já foi executado anteriormente. Evitando repetição.")
input("Pressione Enter para continuar...")
main()
else:
comandos = os.popen('apropos ""').read()
lines = comandos.splitlines()
first_names = []
for line in lines:
words = line.split()
if words:
if any(cmd in words for cmd in ["cat","ls", "cd", "exit"]):
continue
else:
first_names.append(words[0])
with open('block', 'w') as block_file:
for name in first_names:
block_file.write(name + '\n')
sita = input('Deseja confirmar o bloqueio? (S/N)')
if sita.lower() == 's':
user = input('Digite o usuário: ')
dir = f'/home/{user}/.bashrc' ###############################
var = '${comandos[@]}'
os.system(' mv block /usr/share/block')
os.system(f'''echo 'comandos=($(cat /usr/share/block))' | tee -a {dir} > /dev/null''')
os.system(f'''echo 'for comando in "{var}"; do' | tee -a {dir} > /dev/null''')
os.system(f'''echo ' alias "$comando"="echo '\''Comando bloqueado'\''"' | tee -a {dir} > /dev/null''')
os.system(f'''echo 'done' | tee -a {dir} > /dev/null''')
print("Arquivo modificado com sucesso!")
input("Pressione Enter para continuar...")
main()
else:
input("Pressione Enter para continuar...")
main()