-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_manager.py
More file actions
executable file
·85 lines (65 loc) · 2.68 KB
/
Copy pathlog_manager.py
File metadata and controls
executable file
·85 lines (65 loc) · 2.68 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
import os
import datetime
from scapy.all import wrpcap, DNS
LOGS_DIR = "logs"
current_task_id = None
log_file_path = None
def start_new_log_session():
"""
Starts a new logging session by creating a unique task directory and a single pcap file.
"""
global current_task_id, log_file_path
os.makedirs(LOGS_DIR, exist_ok=True)
current_task_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
task_dir = os.path.join(LOGS_DIR, current_task_id)
os.makedirs(task_dir, exist_ok=True)
log_file_path = os.path.join(task_dir, "task.log")
pcap_file_path = os.path.join(task_dir, "capture.pcap")
# Create an empty pcap file to append to later
wrpcap(pcap_file_path, [])
print(f"[*] New log session started. Task ID: {current_task_id}")
return current_task_id
def log_triggered_rule(rule, query_packet):
"""
Writes a log entry for a triggered rule.
"""
if not log_file_path:
return
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
qname = query_packet[DNS].qd.qname.decode().rstrip('.')
rule_name = rule.get('name', rule.get('rule_id'))
log_message = f"{timestamp} - Rule '{rule_name}' triggered by query for '{qname}'.\n"
with open(log_file_path, 'a') as f:
f.write(log_message)
def save_pcap_files(rule, query_packet, response_packet):
"""
Appends the query and response packets to the single pcap file for the current session.
"""
if not current_task_id:
return
task_dir = os.path.join(LOGS_DIR, current_task_id)
pcap_filepath = os.path.join(task_dir, "capture.pcap")
# Append both packets to the existing pcap file
wrpcap(pcap_filepath, [query_packet, response_packet], append=True)
print(f"[*] Appended query and response to {pcap_filepath}")
def get_log_sessions():
"""
Lists all available log session directories.
"""
if not os.path.exists(LOGS_DIR):
return []
return [d for d in os.listdir(LOGS_DIR) if os.path.isdir(os.path.join(LOGS_DIR, d))]
def get_log_details(task_id):
"""
Gets the log entries and pcap files for a specific task_id.
"""
task_dir = os.path.join(LOGS_DIR, task_id)
if not os.path.isdir(task_dir):
return None
log_content = ""
log_file = os.path.join(task_dir, "task.log")
if os.path.exists(log_file):
with open(log_file, 'r') as f:
log_content = f.read()
pcap_files = [f for f in os.listdir(task_dir) if f.endswith(".pcap")]
return {"log_content": log_content, "pcap_files": pcap_files}