-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.py
More file actions
165 lines (122 loc) · 4.88 KB
/
monitor.py
File metadata and controls
165 lines (122 loc) · 4.88 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
#!/usr/bin/env python3
from scapy.all import sniff, IP, TCP, UDP
from collections import defaultdict, deque
from datetime import datetime, timedelta
import argparse
import logging
import json
import signal
import sys
# -----------------------------
# Argument Parsing
# -----------------------------
def parse_args():
parser = argparse.ArgumentParser(description="Lightweight Intrusion Detection Prototype")
parser.add_argument("-i", "--interface", required=True,
help="Network interface (e.g., eth0)")
parser.add_argument("--time-window", type=int, default=10,
help="Time window in seconds for analysis")
parser.add_argument("--scan-threshold", type=int, default=20,
help="Unique ports accessed within window before flagging scan")
parser.add_argument("--traffic-threshold", type=int, default=150,
help="Packets per IP within window before flagging high traffic")
parser.add_argument("--cooldown", type=int, default=30,
help="Seconds before repeating same alert for same IP")
parser.add_argument("--logfile", default="alerts.json",
help="Log file (JSON format)")
return parser.parse_args()
# -----------------------------
# Detection Engine
# -----------------------------
class IDS:
SUSPICIOUS_PORTS = {23, 4444, 1337, 3389}
def __init__(self, time_window, scan_threshold, traffic_threshold, cooldown):
self.time_window = timedelta(seconds=time_window)
self.scan_threshold = scan_threshold
self.traffic_threshold = traffic_threshold
self.cooldown = timedelta(seconds=cooldown)
self.packet_times = defaultdict(deque)
self.port_activity = defaultdict(set)
self.last_alert_time = {}
# Cleanup old packet timestamps
def _cleanup(self, ip, now):
while self.packet_times[ip] and now - self.packet_times[ip][0] > self.time_window:
self.packet_times[ip].popleft()
# Prevent alert spam
def _should_alert(self, ip, alert_type, now):
key = (ip, alert_type)
if key in self.last_alert_time:
if now - self.last_alert_time[key] < self.cooldown:
return False
self.last_alert_time[key] = now
return True
def analyze(self, packet):
if not packet.haslayer(IP):
return None
src_ip = packet[IP].src
now = datetime.now()
self.packet_times[src_ip].append(now)
self._cleanup(src_ip, now)
# High traffic detection
if len(self.packet_times[src_ip]) > self.traffic_threshold:
if self._should_alert(src_ip, "high_traffic", now):
return ("high_traffic", f"High traffic detected from {src_ip}")
# TCP logic
if packet.haslayer(TCP):
dport = packet[TCP].dport
self.port_activity[src_ip].add(dport)
if dport in self.SUSPICIOUS_PORTS:
if self._should_alert(src_ip, "suspicious_port", now):
return ("suspicious_port",
f"Suspicious TCP connection from {src_ip} to port {dport}")
if len(self.port_activity[src_ip]) > self.scan_threshold:
if self._should_alert(src_ip, "port_scan", now):
return ("port_scan",
f"Possible port scan detected from {src_ip}")
# UDP logic
if packet.haslayer(UDP):
dport = packet[UDP].dport
if dport in self.SUSPICIOUS_PORTS:
if self._should_alert(src_ip, "suspicious_port", now):
return ("suspicious_port",
f"Suspicious UDP connection from {src_ip} to port {dport}")
return None
# -----------------------------
# Logging
# -----------------------------
def log_json(logfile, alert_type, message):
entry = {
"timestamp": datetime.now().isoformat(),
"type": alert_type,
"message": message
}
print(f"[ALERT] {message}")
with open(logfile, "a") as f:
f.write(json.dumps(entry) + "\n")
# -----------------------------
# Main
# -----------------------------
def main():
args = parse_args()
ids = IDS(
time_window=args.time_window,
scan_threshold=args.scan_threshold,
traffic_threshold=args.traffic_threshold,
cooldown=args.cooldown
)
print("Lightweight IDS started")
print(f"Monitoring interface: {args.interface}")
print("Press CTRL+C to stop\n")
def packet_handler(packet):
result = ids.analyze(packet)
if result:
alert_type, message = result
log_json(args.logfile, alert_type, message)
signal.signal(signal.SIGINT, lambda s, f: sys.exit(0))
sniff(
iface=args.interface,
prn=packet_handler,
store=False
)
if __name__ == "__main__":
main()