Repository navigation
Expand file tree
/
Copy pathlabel.py
More file actions
53 lines (47 loc) · 2.2 KB
/
Copy pathlabel.py
File metadata and controls
53 lines (47 loc) · 2.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
from scapy.all import rdpcap
from scapy.layers.inet import IP, TCP, UDP
import csv
# Load your packet capture
packets = rdpcap("synthetic_traffic_1500.pcap")
# Dictionary to store labeled packets
labeled_data = []
for pkt in packets:
length = len(pkt) if pkt else 0
proto = pkt[IP].proto if IP in pkt and hasattr(pkt[IP], "proto") else 255
src_ip = pkt[IP].src if IP in pkt and hasattr(pkt[IP], "src") else "unknown"
dst_ip = pkt[IP].dst if IP in pkt and hasattr(pkt[IP], "dst") else "unknown"
label = "unknown"
if TCP in pkt:
tcp = pkt[TCP]
syn_flag = bool(tcp.flags & 0x02)
ack_flag = bool(tcp.flags & 0x10)
if tcp.dport == 80 and "SELECT" in str(pkt.payload): # Example SQL injection
label = "sql_injection"
elif syn_flag and len([p for p in packets if TCP in p and p[TCP].dport == tcp.dport]) > 10: # Port scan
label = "port_scan"
elif syn_flag and not ack_flag: # SYN flood
label = "syn_flood"
elif tcp.dport == 22 and len([p for p in packets if TCP in p and p[TCP].dport == 22]) > 50: # Brute force
label = "brute_force"
else:
label = "normal" # Default to normal for TCP
elif UDP in pkt:
udp = pkt[UDP]
same_dport_count = len([p for p in packets if UDP in p and p[UDP].dport == udp.dport])
if same_dport_count > 100: # UDP flood
src_unique = len(set(p[IP].src for p in packets if IP in p))
label = "ddos" if src_unique > 5 else "dos"
else:
label = "normal"
elif IP in pkt and src_ip.startswith("10.") and dst_ip != "192.168.1.1": # Example spoof
label = "spoof"
elif "MALWARE" in str(pkt.payload): # Example malware payload
label = "malware"
labeled_data.append({"length": length, "protocol": proto, "label": label, "packet": pkt})
# Save to CSV for easy understanding
with open("labeled_traffic.csv", "w", newline='') as f:
writer = csv.DictWriter(f, fieldnames=["length", "protocol", "label"])
writer.writeheader()
for row in labeled_data:
writer.writerow({k: row[k] for k in ["length", "protocol", "label"]})
print("Labeled data saved to labeled_traffic.csv")