-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathnetdeflect.py
More file actions
1764 lines (1435 loc) · 73.2 KB
/
netdeflect.py
File metadata and controls
1764 lines (1435 loc) · 73.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Terminal color definitions
class TerminalColor:
BLACK = '\033[30m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
DARK_GRAY = '\033[90m'
PURPLE = '\033[35m'
RESET = '\033[0m'
# Version information class
class ApplicationVersion:
version = "NetDeflect v2.0"
try:
import os
import sys
import subprocess
from subprocess import DEVNULL, STDOUT
import json
import configparser
import re
from datetime import datetime
import requests
import psutil
import time
import socket
import threading
except ImportError:
# Format current timestamp
def get_timestamp():
now = datetime.now()
timestamp = now.strftime("%d-%m-%y-%H:%M:%S")
return timestamp
# Exit application
exit()
# Set recursion limit to handle large data processing
sys.setrecursionlimit(100000000)
# Format current timestamp
def get_timestamp():
now = datetime.now()
timestamp = now.strftime("%d-%m-%y-%H:%M:%S")
return timestamp
# Format current timestamp
def get_timeonly():
now = datetime.now()
timestamp = now.strftime("%H:%M:%S")
return timestamp
# Generate console output prefix
def get_output_prefix():
return f"{TerminalColor.WHITE}[{TerminalColor.RED}{ApplicationVersion.version}{TerminalColor.WHITE}][{TerminalColor.PURPLE}{get_timeonly()}{TerminalColor.WHITE}]{TerminalColor.RESET}"
# Global variables
blocked_ips = []
attack_status = "None"
try:
# Load configuration file
config = configparser.ConfigParser()
config.read('settings.ini', encoding='utf-8')
# Parse configuration settings
ip_method = config["ip_detection"]["ip_method"]
firewall_system = config["firewall"]["firewall_system"]
webhook_url = config["notification"]["webhook_url"]
detection_threshold = int(config["triggers"]["detection_threshold"])
pps_threshold = int(config["triggers"]["pps_threshold"])
trigger_mode = config["triggers"]["trigger_mode"]
mitigation_pause = int(config["triggers"]["mitigation_pause"])
mbps_threshold = int(config["triggers"]["mbps_threshold"])
packet_count = int(config["triggers"]["packet_count"])
network_interface = config["capture"]["network_interface"]
filter_arguments = config["capture"]["filter_arguments"]
trusted_ips = config["whitelist"]["trusted_ips"].split(", ")
# Advanced mitigation settings
enable_fallback_blocking = config.getboolean("advanced_mitigation", "enable_fallback_blocking")
block_other_attack_contributors = config.getboolean("advanced_mitigation", "block_other_attack_contributors", fallback=False)
enable_pattern_detection = config.getboolean("advanced_mitigation", "enable_pattern_detection", fallback=True)
block_autodetected_patterns = config.getboolean("advanced_mitigation", "block_autodetected_patterns", fallback=True)
contributor_threshold = int(config.get("advanced_mitigation", "contributor_threshold", fallback="30"))
max_pcap_files = int(config.get("advanced_mitigation", "max_pcap_files", fallback="10"))
# External firewall API integration
enable_api_integration = config.getboolean("external_firewall", "enable_api_integration", fallback=False)
if enable_api_integration:
# API endpoint and authentication
api_endpoint = config.get("external_firewall", "api_endpoint", fallback="")
auth_method = config.get("external_firewall", "auth_method", fallback="none")
auth_token = config.get("external_firewall", "auth_token", fallback="")
auth_username = config.get("external_firewall", "auth_username", fallback="")
auth_password = config.get("external_firewall", "auth_password", fallback="")
# Request configuration
additional_headers = config.get("external_firewall", "additional_headers", fallback="{}")
request_method = config.get("external_firewall", "request_method", fallback="POST")
request_body_template = config.get("external_firewall", "request_body_template", fallback="")
request_timeout = int(config.get("external_firewall", "request_timeout", fallback="10"))
# IP sending mode
sending_mode = config.get("external_firewall", "sending_mode", fallback="batch")
max_ips_per_batch = int(config.get("external_firewall", "max_ips_per_batch", fallback="10"))
# Validate API integration settings
if not api_endpoint:
print(f"{get_output_prefix()} {TerminalColor.YELLOW}Warning: External API integration enabled but endpoint URL is missing{TerminalColor.RESET}")
enable_api_integration = False
except Exception as e:
print(str(e))
# Default configuration template
config_template = """
; Please read all comments carefully before modifying values.
; This file controls application behavior, including detection thresholds, notifications, and firewall mitigation.
; Do not remove section headers (e.g., [capture], [triggers]) or field names.
# Your servers displayed IP address method.
[ip_detection]
# Options: google_dns, opendns, ipify, icanhazip, local
ip_method = opendns
########################################
# NETWORK PACKET CAPTURE CONFIGURATION
########################################
[capture]
# The name of your network interface.
# Use `ip a` or `ifconfig` to identify your active interface (e.g., eth0, wlan0, enp3s0).
network_interface=eth0
# Additional filter arguments for tcpdump (advanced).
# Leave empty for full traffic capture.
# Example for SYN/ACK packets only: tcp[tcpflags] & (tcp-syn|tcp-ack) != 0
filter_arguments=
########################################
# NOTIFICATION SETTINGS
########################################
[notification]
# Discord Webhook URL used to send alerts during an attack.
# You can generate one by editing a Discord channel → Integrations → Webhooks.
webhook_url=https://discord.com/api/webhooks/CHANGE-ME
########################################
# ATTACK DETECTION & MITIGATION SETTINGS
########################################
[triggers]
# What condition should trigger mitigation?
# Options:
# P - Packets Per Second threshold
# M - Megabytes Per Second threshold
# MP - Both PPS and MBPS must be exceeded (recommended)
# MEGABYTES IS NOT THE SAME AS MEGABITS, 1 BYTE = 8 BITS!
trigger_mode=MP
# The minimum number of packets per second to consider an attack.
# Lower this value to make detection more sensitive.
pps_threshold=15000
# The minimum network speed in megabytes per second to consider an attack.
# Set to 0 to disable MBPS threshold.
# 240 Mbit / 8 = 30 MByte/s
mbps_threshold=30
# Number of seconds to pause between automatic mitigations.
# Helps reduce repeated action during ongoing attacks.
mitigation_pause=55
# Number of packets to capture during an attack for analysis.
# Lower this if you experience memory or performance issues.
# Modify this based on your port speed and how much data you expect.
packet_count=5000
# Number of attack-type occurrences required to confirm an attack.
# If packet_count is modified, this will also need to be modified.
# Acts as a sensitivity filter — higher value = stricter classification.
detection_threshold=270
########################################
# FIREWALL / BLOCKING SYSTEM CONFIGURATION
########################################
[firewall]
# Select the blocking method for malicious IPs.
# Options:
# iptables - Traditional firewall (Linux)
# ufw - Ubuntu Firewall wrapper
# ipset - Efficient IP list blocking
# blackhole - Adds a null route to silently drop traffic (recommended)
firewall_system=blackhole
########################################
# ADVANCED MITIGATION SETTINGS
########################################
[advanced_mitigation]
# Enable fallback blocking when no specific attack signatures are detected
# Set to False to only block when a specific attack signature is identified
enable_fallback_blocking=False
# Block top traffic contributors when dealing with 'other_attacks' category
# WARNING: This may lead to false positives, use with caution
block_other_attack_contributors=False
# Enable automatic pattern detection for unclassified attacks
# This feature will identify common patterns and save them for review
enable_pattern_detection=True
# Block IPs associated with auto-detected patterns
# Set to False if you only want to log patterns without blocking
block_autodetected_patterns=False
# Minimum contribution percentage to consider an IP as malicious (1-100)
# Higher values reduce false positives but may miss some attackers
contributor_threshold=30
# Maximum number of PCAP files to keep (0 = keep all files)
# Older files will be deleted when this limit is reached
max_pcap_files=10
########################################
# IP WHITELISTING
########################################
[whitelist]
# List of IPs that should NEVER be blocked, such as your home IP or critical infrastructure.
# As it is in beta, please ensure to add your IP address to avoid being blocked.
# Use a comma and space between entries. Example: 1.1.1.1, 8.8.8.8, 139.99.201.1
trusted_ips=8.8.8.8, 8.8.4.4, 1.1.0.1, 1.1.1.1, 216.239.32.10
########################################
# EXTERNAL FIREWALL API INTEGRATION
########################################
[external_firewall]
# Enable external firewall API integration to send IPs to third-party services
enable_api_integration=False
# API endpoint URL
# Use a full URL including https:// and any required path
api_endpoint=https://api.example.com/firewall/block
# API authentication method (basic, bearer, header, none)
auth_method=bearer
# API authentication credentials
auth_token=your_api_token_here
auth_username=
auth_password=
# Additional headers (in JSON format)
# Example: {"X-Custom-Header": "value", "Content-Type": "application/json"}
additional_headers={"Content-Type": "application/json"}
# Request method (GET, POST, PUT, PATCH, DELETE)
request_method=POST
# Sending mode: single (one IP per request), batch (groups of IPs), or all (all IPs in one request) [I wouldn't recommend single as it may get you rate limited]
sending_mode=all
# Maximum IPs per batch (for batch mode)
max_ips_per_batch=100
# Request body template (JSON)
# Available placeholders:
# {{IP}} - Single IP (for single mode)
# {{IP_LIST}} - Array of IPs as strings ["1.1.1.1", "2.2.2.2"] (for batch/all modes)
# {{IP_CSV}} - Comma-separated IPs "1.1.1.1,2.2.2.2" (for batch/all modes)
# {{TIMESTAMP}} - Current timestamp
# {{SOURCE}} - "NetDeflect"
# Note: Escape quotes with backslash
request_body_template={"source": "NetDeflect", "timestamp": "{{TIMESTAMP}}", "ips": {{IP_LIST}}}
# Request timeout in seconds
request_timeout=10
"""
# Write default configuration
with open("settings.ini", "w", encoding='utf-8') as outfile:
outfile.write(config_template)
# Inform user
print(f"{get_output_prefix()} Please configure settings.ini then restart the program")
# Exit application
exit()
def get_ip(method):
if method == "google_dns":
return subprocess.getoutput('dig TXT +short o-o.myaddr.l.google.com @ns1.google.com').replace('"', '').strip()
elif method == "opendns":
return subprocess.getoutput('dig +short myip.opendns.com @resolver1.opendns.com').strip()
elif method == "ipify":
return requests.get("https://api.ipify.org", timeout=5).text.strip()
elif method == "icanhazip":
return requests.get("https://icanhazip.com", timeout=5).text.strip()
elif method == "local":
return socket.gethostbyname(socket.gethostname())
else:
raise ValueError(f"Unknown IP detection method: {method}")
system_ip = get_ip(ip_method)
# Create required directory structure
def dir():
# Define application directories
directories = [
"./application_data",
"./application_data/captures",
"./application_data/ips",
"./application_data/attack_analysis"
]
# Create each directory if it doesn't exist
for directory in directories:
try:
os.makedirs(directory, exist_ok=True)
except Exception:
pass
# Configure ipset tables for IP filtering
def configure_ipset():
# Create IP filtering tables
subprocess.call('ipset -N blocked_ips hash:net family inet', shell=True, stdout=DEVNULL, stderr=STDOUT)
subprocess.call('ipset -N trusted_ips hash:net family inet', shell=True, stdout=DEVNULL, stderr=STDOUT)
# Configure iptables rules
subprocess.call('iptables -t raw -I PREROUTING -m set --match-set blocked_ips src -j DROP', shell=True, stdout=DEVNULL, stderr=STDOUT)
subprocess.call('iptables -t raw -I PREROUTING -m set --match-set trusted_ips src -j ACCEPT', shell=True, stdout=DEVNULL, stderr=STDOUT)
def is_protected_ip(ip_address):
# Check if IP is already in blocked list
if ip_address in blocked_ips:
return True
# Protect system's own IP
if ip_address == system_ip:
return True
# Check against trusted IPs list
if ip_address in trusted_ips:
return True
# IP is not protected
return False
# Format IP address display
def format_ip_display(ip_address):
length = len(ip_address)
if 6 <= length <= 15:
spaces = " " * (15 - length)
return f"{ip_address}{spaces}"
return ip_address
def block_ip(ip_address):
try:
# Clean up IP string
ip_address = ip_address.strip()
# Format for display
formatted_ip = format_ip_display(ip_address)
# Skip protected IPs
if is_protected_ip(ip_address):
return False
# Select appropriate firewall command
cmd = ""
if firewall_system == 'ufw':
cmd = f"sudo ufw deny from {ip_address}"
elif firewall_system == 'ipset':
cmd = f"ipset -A blocked_ips {ip_address}"
elif firewall_system == "iptables":
cmd = f"iptables -A INPUT -s {ip_address} -j DROP"
elif firewall_system == "blackhole":
cmd = f"ip route add blackhole {ip_address}"
else:
print(f"{get_output_prefix()} Unrecognized firewall_system! Please select \"ufw\", \"iptables\", \"ipset\", or \"blackhole\"")
exit()
# Execute firewall command
if cmd:
subprocess.call(cmd, shell=True, stdout=DEVNULL, stderr=STDOUT)
print(f"{get_output_prefix()} Blocked malicious IP: {TerminalColor.BLUE}[{TerminalColor.RED}{formatted_ip}{TerminalColor.BLUE}]{TerminalColor.RESET}")
blocked_ips.append(ip_address)
return True
except Exception as e:
print(f"{get_output_prefix()} Error occurred: {TerminalColor.BLUE}[{TerminalColor.RED}{e}{TerminalColor.BLUE}]{TerminalColor.RESET}")
return False
update_available = False
latest_version_tag = ""
def check_for_updates():
global update_available, latest_version_tag
try:
# GitHub API URL for latest release
api_url = "https://api.github.com/repos/0vm/NetDeflect/releases/latest"
# Get current version number (extract from version string)
current_version = ApplicationVersion.version.split("v")[1].strip() if "v" in ApplicationVersion.version else "2.0"
# Request latest release info
response = requests.get(api_url, timeout=5)
if response.status_code != 200:
return
# Parse response
release_data = json.loads(response.text)
latest_version_tag = release_data.get('tag_name', '')
# Extract version number from tag (removing 'v' if present)
latest_version = latest_version_tag.replace('v', '').strip()
# Simple version comparison (this may not work for complex version schemes)
if latest_version > current_version:
# Mark update as available
update_available = True
except Exception as e:
# Silently fail - don't disrupt main application
pass
def manage_pcap_files(max_files=10):
"""
Manage the number of pcap files by keeping only the most recent ones
Args:
max_files (int): Maximum number of pcap files to keep
Returns:
int: Number of files deleted
"""
try:
# Get the pcap directory
pcap_dir = "./application_data/captures/"
# Get all pcap files in the directory
pcap_files = []
for file in os.listdir(pcap_dir):
if file.endswith(".pcap"):
file_path = os.path.join(pcap_dir, file)
# Get file modification time
mod_time = os.path.getmtime(file_path)
pcap_files.append((file_path, mod_time))
# If we have more files than the maximum, delete the oldest ones
if len(pcap_files) > max_files:
# Sort files by modification time (oldest first)
pcap_files.sort(key=lambda x: x[1])
# Calculate how many files to delete
files_to_delete = len(pcap_files) - max_files
# Delete the oldest files
deleted_count = 0
for i in range(files_to_delete):
file_path = pcap_files[i][0]
try:
os.remove(file_path)
print(f"{get_output_prefix()} {TerminalColor.BLUE}Deleted old pcap file: {file_path}{TerminalColor.RESET}")
deleted_count += 1
except Exception as e:
print(f"{get_output_prefix()} {TerminalColor.RED}Error deleting pcap file {file_path}: {str(e)}{TerminalColor.RESET}")
return deleted_count
return 0
except Exception as e:
print(f"{get_output_prefix()} {TerminalColor.RED}Error managing pcap files: {str(e)}{TerminalColor.RESET}")
return 0
def start_update_checker():
def update_check_worker():
# Initial delay to let application start properly
time.sleep(5)
# Do initial check
check_for_updates()
# Check periodically (every 12 hours)
while True:
time.sleep(43200) # 12 hours
check_for_updates()
# Start update checker in background thread
update_thread = threading.Thread(target=update_check_worker)
update_thread.daemon = True # Thread will exit when main program exits
update_thread.start()
def display_update_notification():
global update_available, latest_version_tag
if update_available:
print("\n" + "=" * 80)
print(f"{get_output_prefix()} {TerminalColor.GREEN}Update Available!{TerminalColor.RESET}")
print(f"{get_output_prefix()} Current Version: {TerminalColor.BLUE}[{TerminalColor.RED}{ApplicationVersion.version}{TerminalColor.BLUE}]{TerminalColor.RESET}")
print(f"{get_output_prefix()} Latest Version: {TerminalColor.BLUE}[{TerminalColor.GREEN}{latest_version_tag}{TerminalColor.BLUE}]{TerminalColor.RESET}")
print(f"{get_output_prefix()} {TerminalColor.BLUE}Download at: {TerminalColor.GREEN}https://github.com/0vm/NetDeflect{TerminalColor.RESET}")
print("=" * 80)
return True
return False
class AttackVectors:
spoofed_ip_attacks = {}
valid_ip_attacks = {}
other_attacks = {}
@classmethod
def load_vectors(cls):
try:
methods_file_path = "methods.json"
with open(methods_file_path, 'r') as file:
data = json.load(file)
# Get category-specific attacks
cls.spoofed_ip_attacks = data.get("spoofed_ip_attacks", {})
cls.valid_ip_attacks = data.get("valid_ip_attacks", {})
cls.other_attacks = data.get("other_attacks", {})
return True
except Exception as e:
print(f"{get_output_prefix()} Failed to load methods: {str(e)}")
print(f"{get_output_prefix()} Make sure to have methods.json in the same directory!")
return False
def send_ips_to_external_api(ip_list):
"""
Send IP addresses to an external API based on user configuration
Args:
ip_list (list): List of IP addresses to block
Returns:
bool: Success status
"""
# Skip if API integration is disabled
if not enable_api_integration:
return True
# Skip if no IPs to block
if not ip_list:
return True
try:
print(f"{get_output_prefix()} {TerminalColor.BLUE}Sending IPs to external firewall API...{TerminalColor.RESET}")
# Determine how to send the IPs based on the sending mode
if sending_mode.lower() == "single":
# Send each IP individually
success = True
for ip in ip_list:
if not send_single_ip_to_api(ip):
success = False
return success
elif sending_mode.lower() == "batch":
# Send IPs in batches
batches = [ip_list[i:i + max_ips_per_batch] for i in range(0, len(ip_list), max_ips_per_batch)]
success = True
for batch in batches:
if not send_ip_batch_to_api(batch):
success = False
return success
elif sending_mode.lower() == "all":
# Send all IPs in a single request
return send_ip_batch_to_api(ip_list)
else:
print(f"{get_output_prefix()} {TerminalColor.RED}Unknown sending mode: {sending_mode}{TerminalColor.RESET}")
return False
except Exception as e:
print(f"{get_output_prefix()} {TerminalColor.RED}Error sending IPs to external API: {str(e)}{TerminalColor.RESET}")
return False
def send_single_ip_to_api(ip):
"""
Send a single IP to the external API
Args:
ip (str): IP address to block
Returns:
bool: Success status
"""
try:
# Prepare the request
url = api_endpoint
method = request_method.upper()
# Create headers
headers = parse_json_config(additional_headers)
# Add authentication
auth = None
if auth_method.lower() == "basic":
auth = (auth_username, auth_password)
elif auth_method.lower() == "bearer":
headers["Authorization"] = f"Bearer {auth_token}"
elif auth_method.lower() == "header" and auth_token:
headers["Authorization"] = auth_token
# Prepare the request body with placeholders
if request_body_template:
body = request_body_template.replace("{{IP}}", ip)
body = body.replace("{{TIMESTAMP}}", get_timestamp())
body = body.replace("{{SOURCE}}", "NetDeflect")
# Convert string to JSON if needed
if body.strip().startswith("{") or body.strip().startswith("["):
try:
body = json.loads(body)
except json.JSONDecodeError:
pass
else:
body = {"ip": ip}
# Send the request
response = send_api_request(url, method, headers, auth, body)
if response and 200 <= response.status_code < 300:
print(f"{get_output_prefix()} {TerminalColor.GREEN}Successfully sent IP {ip} to external API{TerminalColor.RESET}")
return True
else:
status_code = response.status_code if response else "No response"
response_text = response.text if response else "No response"
print(f"{get_output_prefix()} {TerminalColor.RED}Failed to send IP {ip} to external API: {status_code} - {response_text}{TerminalColor.RESET}")
return False
except Exception as e:
print(f"{get_output_prefix()} {TerminalColor.RED}Error sending IP {ip} to external API: {str(e)}{TerminalColor.RESET}")
return False
def send_ip_batch_to_api(ip_batch):
"""
Send a batch of IPs to the external API
Args:
ip_batch (list): List of IP addresses to block
Returns:
bool: Success status
"""
try:
# Prepare the request
url = api_endpoint
method = request_method.upper()
# Create headers
headers = parse_json_config(additional_headers)
# Add authentication
auth = None
if auth_method.lower() == "basic":
auth = (auth_username, auth_password)
elif auth_method.lower() == "bearer":
headers["Authorization"] = f"Bearer {auth_token}"
elif auth_method.lower() == "header" and auth_token:
headers["Authorization"] = auth_token
# Prepare the request body with placeholders
if request_body_template:
# Format IP list as JSON array string for replacement
ip_list_json = json.dumps(ip_batch)
# Format IP list as CSV string for replacement
ip_list_csv = ",".join(ip_batch)
body = request_body_template.replace("{{IP_LIST}}", ip_list_json)
body = body.replace("{{IP_CSV}}", ip_list_csv)
body = body.replace("{{TIMESTAMP}}", get_timestamp())
body = body.replace("{{SOURCE}}", "NetDeflect")
# Convert string to JSON if needed
if body.strip().startswith("{") or body.strip().startswith("["):
try:
body = json.loads(body)
except json.JSONDecodeError:
pass
else:
body = {"ips": ip_batch}
# Send the request
response = send_api_request(url, method, headers, auth, body)
if response and 200 <= response.status_code < 300:
print(f"{get_output_prefix()} {TerminalColor.GREEN}Successfully sent {len(ip_batch)} IPs to external API{TerminalColor.RESET}")
return True
else:
status_code = response.status_code if response else "No response"
response_text = response.text if response else "No response"
print(f"{get_output_prefix()} {TerminalColor.RED}Failed to send IPs to external API: {status_code} - {response_text}{TerminalColor.RESET}")
return False
except Exception as e:
print(f"{get_output_prefix()} {TerminalColor.RED}Error sending IPs to external API: {str(e)}{TerminalColor.RESET}")
return False
def send_api_request(url, method, headers, auth, body):
"""
Send request to the API with error handling
Args:
url (str): API endpoint URL
method (str): HTTP method
headers (dict): HTTP headers
auth (tuple or None): Auth tuple for basic auth
body (dict or str): Request body
Returns:
Response or None: Response object or None if failed
"""
try:
# Get the request function based on the method
request_func = getattr(requests, method.lower(), requests.post)
# Send the request with appropriate parameters
kwargs = {
"headers": headers,
"timeout": request_timeout
}
if auth:
kwargs["auth"] = auth
if method.upper() in ["GET", "DELETE"]:
# For GET/DELETE, use params instead of JSON
if isinstance(body, dict):
kwargs["params"] = body
else:
# For POST/PUT/PATCH, use json or data based on content type
content_type = headers.get("Content-Type", "").lower()
if "json" in content_type and isinstance(body, (dict, list)):
kwargs["json"] = body
else:
kwargs["data"] = body
# Send the request
response = request_func(url, **kwargs)
return response
except Exception as e:
print(f"{get_output_prefix()} {TerminalColor.RED}API request error: {str(e)}{TerminalColor.RESET}")
return None
def parse_json_config(json_string):
"""
Parse a JSON string from config safely
Args:
json_string (str): JSON string from config
Returns:
dict: Parsed JSON object or empty dict if invalid
"""
if not json_string:
return {}
try:
return json.loads(json_string)
except json.JSONDecodeError as e:
print(f"{get_output_prefix()} {TerminalColor.RED}Error parsing JSON config: {str(e)}{TerminalColor.RESET}")
return {}
# Get network statistics
def get_network_stats():
# Collect initial network stats
bytes_initial = round(int(psutil.net_io_counters().bytes_recv) / 1024 / 1024, 3)
packets_initial = int(psutil.net_io_counters().packets_recv)
# Wait for next sample
time.sleep(1)
# Collect updated network stats
packets_current = int(psutil.net_io_counters().packets_recv)
bytes_current = round(int(psutil.net_io_counters().bytes_recv) / 1024 / 1024, 3)
# Calculate network statistics
pps = packets_current - packets_initial
mbps = round(bytes_current - bytes_initial)
cpu_usage = f"{int(round(psutil.cpu_percent()))}%"
return pps, mbps, cpu_usage
# Display current network status
def display_network_stats(pps, mbps, cpu_usage):
showed_update = display_update_notification()
print(f"{get_output_prefix()} IP Address: {TerminalColor.WHITE}[{TerminalColor.RED}{system_ip}{TerminalColor.WHITE}]{TerminalColor.RESET}")
print(f"{get_output_prefix()} CPU: {TerminalColor.WHITE}[{TerminalColor.RED}{cpu_usage}{TerminalColor.WHITE}]{TerminalColor.RESET}")
print(f"{get_output_prefix()} MB/s: {TerminalColor.WHITE}[{TerminalColor.RED}{mbps}{TerminalColor.WHITE}]{TerminalColor.RESET}")
print(f"{get_output_prefix()} Packets Per Second: {TerminalColor.WHITE}[{TerminalColor.RED}{pps}{TerminalColor.WHITE}]{TerminalColor.RESET}")
return showed_update
def extract_common_patterns(capture_file, min_pattern_length=8, min_occurrence=3, top_ips_count=10):
"""
Extract common hex patterns from packet data sent by top contributing IPs.
Args:
capture_file (str): Path to the packet capture file
min_pattern_length (int): Minimum length of hex pattern to consider (in characters)
min_occurrence (int): Minimum number of occurrences needed to consider a pattern
top_ips_count (int): Number of top contributing IPs to analyze
Returns:
tuple: (most_common_pattern, source_ips, pattern_count)
"""
try:
print(f"{get_output_prefix()} Analyzing capture for common attack patterns...")
# Get top traffic contributors
top_contributors = find_top_traffic_contributors(capture_file, top_count=top_ips_count)
if not top_contributors:
print(f"{get_output_prefix()} No significant traffic contributors found")
return None, [], 0
# Filter out protected IPs
top_ips = []
for ip, count, percent in top_contributors:
if not is_protected_ip(ip) and percent > 10: # Only consider IPs with >10% contribution
top_ips.append(ip)
if not top_ips:
print(f"{get_output_prefix()} No non-protected traffic contributors found")
return None, [], 0
print(f"{get_output_prefix()} Analyzing payloads from {len(top_ips)} source IPs")
# Extract payload data for these IPs
ip_filter = " or ".join([f"ip.src == {ip}" for ip in top_ips])
cmd = f'sudo tshark -r {capture_file} -Y "({ip_filter}) and data" -T fields -e ip.src -e data'
process = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if process.returncode != 0 or not process.stdout.strip():
print(f"{get_output_prefix()} No payload data found in capture")
return None, [], 0
# Process the output to find common patterns
ip_payload_map = {}
all_payloads = []
for line in process.stdout.strip().split('\n'):
if '\t' in line:
parts = line.strip().split('\t')
if len(parts) == 2:
ip = parts[0].strip()
payload = parts[1].strip()
# Only consider payloads of sufficient length
if len(payload) >= min_pattern_length:
if ip not in ip_payload_map:
ip_payload_map[ip] = []
# Add to IP-specific payloads
if payload not in ip_payload_map[ip]:
ip_payload_map[ip].append(payload)
# Add to all payloads for frequency counting
all_payloads.append(payload)
if not all_payloads:
print(f"{get_output_prefix()} No valid payloads found for analysis")
return None, [], 0
# Count frequency of each payload
from collections import Counter
payload_counter = Counter(all_payloads)
# Find payloads that appear in multiple IPs and have sufficient occurrences
common_patterns = {}
for payload, count in payload_counter.most_common(20):
# Count how many different IPs sent this payload
ip_count = sum(1 for ip, payloads in ip_payload_map.items() if payload in payloads)
if ip_count >= min(3, len(top_ips)) and count >= min_occurrence:
common_patterns[payload] = (count, ip_count)
if not common_patterns:
# Try to find common substrings across different payloads
substrings = extract_common_substrings(all_payloads, min_length=min_pattern_length)
if substrings:
most_common = max(substrings.items(), key=lambda x: x[1][0])
pattern = most_common[0]
count = most_common[1][0]
unique_ips = list(set([ip for ip in top_ips if any(pattern in payload for payload in ip_payload_map.get(ip, []))]))
if len(unique_ips) >= min(3, len(top_ips)) and count >= min_occurrence:
print(f"{get_output_prefix()} Found common substring pattern: {pattern} (occurs {count} times across {len(unique_ips)} IPs)")
return pattern, unique_ips, count
print(f"{get_output_prefix()} No common patterns found across multiple source IPs")
return None, [], 0
# Get the most common pattern
most_common = max(common_patterns.items(), key=lambda x: x[1][0])
pattern = most_common[0]
count = most_common[1][0]
ip_count = most_common[1][1]
# Get the specific IPs that sent this pattern
pattern_ips = [ip for ip, payloads in ip_payload_map.items() if pattern in payloads]
print(f"{get_output_prefix()} Found common pattern: {pattern} (occurs {count} times across {ip_count} IPs)")
return pattern, pattern_ips, count
except Exception as e:
print(f"{get_output_prefix()} Error analyzing for common patterns: {str(e)}")
return None, [], 0
def extract_common_substrings(payloads, min_length=8):
"""
Extract common substrings from a list of payloads.
Args:
payloads (list): List of payload strings
min_length (int): Minimum length of substring to consider
Returns:
dict: Dictionary mapping substrings to (count, ip_count)
"""
if not payloads or len(payloads) < 2:
return {}
# Get potential substrings from the first few payloads
sample_payloads = payloads[:min(20, len(payloads))]
potential_substrings = set()
for payload in sample_payloads:
length = len(payload)
for i in range(length - min_length + 1):
for j in range(i + min_length, min(i + 64, length + 1)):
substring = payload[i:j]
if len(substring) >= min_length:
potential_substrings.add(substring)
# Count occurrences of each potential substring
substring_counts = {}
for substring in potential_substrings:
count = sum(1 for payload in payloads if substring in payload)
if count >= 3:
# This is a placeholder for the IP count, which we'll compute later if needed
substring_counts[substring] = (count, 0)
return substring_counts
def save_detected_signature(ip_list, hex_pattern, category="valid_ip_attacks", label=None):
"""
Save a newly detected attack signature to new_detected_methods.json
Args:
ip_list (list): List of source IPs that exhibited this pattern
hex_pattern (str): The hex pattern that was detected
category (str): Attack category (default: valid_ip_attacks)
label (str): Custom label for the attack (default: auto-generated)
Returns:
bool: True if successful, False otherwise
"""
try:
# Auto-generate label if not provided
if not label:
# Take first 4-8 characters of the pattern for the label
prefix = hex_pattern[:min(8, len(hex_pattern))]
label = f"AutoDetect_{prefix}"
# Create entry
timestamp = get_timestamp()
new_entry = {
"timestamp": timestamp,
"source_ips": ip_list,
"pattern": hex_pattern,
"category": category,
"label": label
}
# Check if file exists and load existing data
file_path = "./application_data/new_detected_methods.json"
existing_entries = []