-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
212 lines (178 loc) · 6.14 KB
/
main.py
File metadata and controls
212 lines (178 loc) · 6.14 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
from scapy.all import sniff, IP, TCP
import logging
from collections import defaultdict
import time
import json
import requests
from flask import Flask, render_template_string
import threading
import smtplib
from email.mime.text import MIMEText
# ---------------- CONFIG ----------------
FAILED_THRESHOLD = 5
PORT_SCAN_THRESHOLD = 10
TRAFFIC_THRESHOLD = 100
TIME_WINDOW = 60
BLACKLIST_IPS = ["192.168.1.100"]
ENABLE_EMAIL_ALERTS = False
EMAIL_SENDER = "your_email@gmail.com"
EMAIL_PASSWORD = "your_password"
EMAIL_RECEIVER = "receiver@gmail.com"
# ---------------- STORAGE ----------------
failed_attempts = defaultdict(list)
port_scans = defaultdict(set)
packet_count = defaultdict(int)
alerts = []
recent_alerts = set()
# ---------------- LOGGING ----------------
logging.basicConfig(filename="ids.log", level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s")
def log_json(event_type, src_ip, severity, details):
log_entry = {
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"event_type": event_type,
"severity": severity,
"source_ip": src_ip,
"details": details
}
with open("ids.json", "a") as f:
f.write(json.dumps(log_entry) + "\n")
# ---------------- GEO + THREAT INTEL ----------------
def get_geo(ip):
try:
res = requests.get(f"http://ip-api.com/json/{ip}", timeout=2).json()
return f"{res.get('country')} - {res.get('city')}"
except:
return "Unknown"
def get_threat_score(ip):
try:
res = requests.get(f"https://ipapi.co/{ip}/json/", timeout=2).json()
return res.get("org", "Unknown")
except:
return "Unknown"
# ---------------- EMAIL ALERT ----------------
def send_email_alert(message):
if not ENABLE_EMAIL_ALERTS:
return
try:
msg = MIMEText(message)
msg["Subject"] = "🚨 IDS Alert"
msg["From"] = EMAIL_SENDER
msg["To"] = EMAIL_RECEIVER
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(EMAIL_SENDER, EMAIL_PASSWORD)
server.sendmail(EMAIL_SENDER, EMAIL_RECEIVER, msg.as_string())
server.quit()
except Exception as e:
print("Email error:", e)
# ---------------- ALERT SYSTEM ----------------
def generate_alert(message, src_ip="unknown", severity="MEDIUM"):
alert_key = f"{src_ip}-{message}"
# Deduplication
if alert_key in recent_alerts:
return
recent_alerts.add(alert_key)
location = get_geo(src_ip)
threat_info = get_threat_score(src_ip)
alert_data = {
"time": time.strftime("%H:%M:%S"),
"ip": src_ip,
"location": location,
"threat": threat_info,
"severity": severity,
"message": message
}
print(f"[{severity}] {message} | {src_ip} | {location}")
logging.warning(str(alert_data))
log_json("ALERT", src_ip, severity, message)
alerts.append(alert_data)
send_email_alert(str(alert_data))
# ---------------- RULE ENGINE ----------------
def custom_rules(packet, src_ip):
if packet.haslayer(TCP):
# HTTPS flood
if packet[TCP].dport == 443 and packet_count[src_ip] > 50:
generate_alert("Possible HTTPS Flood", src_ip, "HIGH")
# High port anomaly
if packet[TCP].dport > 1024 and packet_count[src_ip] > 80:
generate_alert("Suspicious High Port Activity", src_ip, "MEDIUM")
# ---------------- PACKET ANALYSIS ----------------
def analyze_packet(packet):
if packet.haslayer(IP):
src_ip = packet[IP].src
packet_count[src_ip] += 1
# Traffic spike
if packet_count[src_ip] > TRAFFIC_THRESHOLD:
generate_alert("Traffic Spike Detected", src_ip, "HIGH")
# Blacklist
if src_ip in BLACKLIST_IPS:
generate_alert("Blacklisted IP Detected", src_ip, "CRITICAL")
if packet.haslayer(TCP):
dst_port = packet[TCP].dport
# Brute force
if dst_port == 22:
now = time.time()
failed_attempts[src_ip].append(now)
failed_attempts[src_ip] = [
t for t in failed_attempts[src_ip]
if now - t < TIME_WINDOW
]
if len(failed_attempts[src_ip]) > FAILED_THRESHOLD:
generate_alert("Brute Force Attack", src_ip, "HIGH")
# Port scan
port_scans[src_ip].add(dst_port)
if len(port_scans[src_ip]) > PORT_SCAN_THRESHOLD:
generate_alert("Port Scanning Detected", src_ip, "HIGH")
custom_rules(packet, src_ip)
logging.info(f"Traffic: {src_ip}")
log_json("TRAFFIC", src_ip, "LOW", "Normal packet")
# ---------------- DASHBOARD ----------------
app = Flask(__name__)
@app.route("/")
def dashboard():
html = """
<html>
<head>
<meta http-equiv="refresh" content="3">
<style>
body { font-family: Arial; }
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px; border: 1px solid black; }
th { background-color: black; color: white; }
</style>
</head>
<body>
<h2>🚨 SOC IDS Dashboard</h2>
<table>
<tr>
<th>Time</th>
<th>IP</th>
<th>Location</th>
<th>Threat Intel</th>
<th>Severity</th>
<th>Message</th>
</tr>
{% for alert in alerts %}
<tr>
<td>{{alert.time}}</td>
<td>{{alert.ip}}</td>
<td>{{alert.location}}</td>
<td>{{alert.threat}}</td>
<td>{{alert.severity}}</td>
<td>{{alert.message}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
"""
return render_template_string(html, alerts=alerts)
# ---------------- START IDS ----------------
def start_ids():
print("Starting SOC-Level IDS...")
sniff(prn=analyze_packet, store=False)
# ---------------- MAIN ----------------
if __name__ == "__main__":
threading.Thread(target=start_ids).start()
app.run(host="0.0.0.0", port=5000)