Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
311 lines (237 loc) · 9.69 KB
/
Copy pathapp.py
File metadata and controls
311 lines (237 loc) · 9.69 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
""" IPWatchdog – Suspicious IP Detection Dashboard """
import os
import sys
import json
import queue
import threading
import tempfile
import time
import logging
from pathlib import Path
from flask import (
Flask, render_template, request, jsonify,
Response, stream_with_context
)
from werkzeug.utils import secure_filename
from config import AppConfig
from core.parser import LogParser
from core.detector import IPDetector
from core.explainer import Explainer
from core.threat_intel import ThreatIntel
from core.actions import ActionEngine
# ---------------------------------------------------------------------------
# App setup
# ---------------------------------------------------------------------------
app = Flask(__name__)
app.config.from_object(AppConfig)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s – %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger("ipwatchdog")
_sse_queue: queue.Queue = queue.Queue(maxsize=500)
_analysis_cache: dict = {}
_cache_lock = threading.Lock()
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def allowed_file(filename: str) -> bool:
return "." in filename and filename.rsplit(".", 1)[-1].lower() in app.config["ALLOWED_EXTENSIONS"]
def read_ip_list(file_storage) -> set:
if not file_storage or file_storage.filename == "":
return set()
try:
content = file_storage.read().decode("utf-8", errors="ignore")
return {line.strip() for line in content.splitlines() if line.strip()}
except Exception:
logger.warning("Failed to read IP list")
return set()
def push_sse_event(event_type: str, data: dict) -> None:
try:
_sse_queue.put_nowait({"type": event_type, "data": data})
except queue.Full:
logger.warning("SSE queue full, dropping event")
# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
@app.route("/", methods=["GET"])
def index():
return render_template("dashboard.html")
@app.route("/analyze", methods=["POST"])
def analyze():
if "logfile" not in request.files:
return jsonify({"error": "No log file provided"}), 400
log_file = request.files["logfile"]
whitelist = read_ip_list(request.files.get("whitelist"))
blacklist = read_ip_list(request.files.get("blacklist"))
log_format = request.form.get("log_format", "auto")
if log_file.filename == "":
return jsonify({"error": "No file selected"}), 400
if not allowed_file(log_file.filename):
return jsonify({"error": "Invalid file type"}), 400
log_file.seek(0, 2)
size = log_file.tell()
log_file.seek(0)
if size > app.config["MAX_CONTENT_LENGTH"]:
return jsonify({"error": "File too large"}), 413
safe_name = secure_filename(log_file.filename)
tmp_path = os.path.join(tempfile.gettempdir(), f"ipwd_{os.getpid()}_{safe_name}")
try:
log_file.save(tmp_path)
push_sse_event("status", {"message": "Parsing...", "pct": 10})
parser = LogParser(log_format=log_format)
df = parser.parse(tmp_path)
if df is None or df.empty:
return jsonify({"error": "Invalid log format"}), 422
detector = IPDetector()
result_df = detector.run(df)
explainer = Explainer()
explanations = explainer.explain(result_df)
intel = ThreatIntel()
top_ips = result_df.head(10)["IP"].tolist()
threat_data = intel.bulk_lookup(top_ips)
result_records = result_df.to_dict("records")
for rec in result_records:
ip = rec["IP"]
rec["whitelisted"] = ip in whitelist
rec["blacklisted"] = ip in blacklist
rec["threat_intel"] = threat_data.get(ip, {})
rec["explanation"] = explanations.get(ip, [])
flagged_ips = [
r["IP"] for r in result_records
if r["anomaly_score"] < 0 and not r["whitelisted"]
]
action_engine = ActionEngine()
htaccess_rules = action_engine.generate_htaccess(flagged_ips)
response_payload = {
"summary": {
"total_requests": len(df),
"unique_ips": result_df["IP"].nunique(),
"suspicious_ips": int((result_df["anomaly_score"] < 0).sum()),
},
"top_ips": result_df.head(10)[["IP", "request_count", "anomaly_score"]].to_dict("records"),
"results": result_records[:200],
"htaccess_rules": htaccess_rules,
}
session_id = str(int(time.time() * 1000))
with _cache_lock:
_analysis_cache[session_id] = response_payload
response_payload["session_id"] = session_id
return jsonify(response_payload)
except Exception:
logger.exception("Error in analyze")
return jsonify({"error": "Internal server error"}), 500
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
@app.route("/export/<session_id>")
def export_csv(session_id: str):
with _cache_lock:
payload = _analysis_cache.get(session_id)
if not payload:
return jsonify({"error": "Session expired"}), 404
import csv
import io
buf = io.StringIO()
writer = csv.DictWriter(
buf,
fieldnames=["IP", "request_count", "anomaly_score", "whitelisted", "blacklisted"],
extrasaction="ignore",
)
writer.writeheader()
writer.writerows(payload.get("results", []))
buf.seek(0)
return Response(
buf.getvalue(),
mimetype="text/csv",
headers={"Content-Disposition": "attachment; filename=report.csv"},
)
@app.route("/stream")
def stream():
def event_generator():
while True:
try:
event = _sse_queue.get(timeout=30)
yield f"data: {json.dumps(event)}\n\n"
except queue.Empty:
yield "data: {\"type\":\"heartbeat\"}\n\n"
return Response(stream_with_context(event_generator()), mimetype="text/event-stream")
# ---------------------------------------------------------------------------
# FIXED: Secure path validation (CodeQL-safe FINAL)
# ---------------------------------------------------------------------------
def _validated_monitor_log_path(user_input, allowed_paths):
"""
Only allow known filenames from allowed directories.
No direct user input is used in path resolution.
"""
if not isinstance(user_input, str) or not user_input:
raise ValueError("INVALID")
for base in allowed_paths or []:
try:
root = Path(base)
# iterate only trusted files
for file in root.iterdir():
if file.is_file() and file.name == user_input:
return str(file.resolve())
except Exception:
continue
raise ValueError("NOT_FOUND")
@app.route("/monitor", methods=["POST"])
def monitor_start():
body = request.get_json(silent=True) or {}
log_path = body.get("path", "")
log_format = body.get("format", "auto")
try:
real_log_path = _validated_monitor_log_path(
log_path,
app.config.get("MONITOR_ALLOWED_PATHS", [])
)
except ValueError:
return jsonify({"error": "Invalid request"}), 400
except PermissionError:
return jsonify({"error": "Access denied"}), 403
except Exception:
logger.exception("Unexpected monitor error")
return jsonify({"error": "Internal server error"}), 500
def tail_worker():
try:
parser = LogParser(log_format=log_format)
detector = IPDetector()
with open(real_log_path, "r", encoding="utf-8", errors="ignore") as fh:
fh.seek(0, 2)
while True:
line = fh.readline()
if not line:
time.sleep(0.5)
continue
record = parser.parse_line(line)
if record:
score = detector.score_single(record)
push_sse_event("live_entry", {
**record,
"anomaly_score": score
})
except Exception:
logger.exception("tail_worker crashed")
threading.Thread(target=tail_worker, daemon=True).start()
return jsonify({"status": "monitoring started"}), 200
# ---------------------------------------------------------------------------
# Security headers
# ---------------------------------------------------------------------------
@app.after_request
def add_security_headers(response):
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Content-Security-Policy"] = "default-src 'self'; connect-src 'self';"
return response
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
app.run(
host=os.environ.get("FLASK_HOST", "127.0.0.1"),
port=int(os.environ.get("FLASK_PORT", "5000")),
debug=False
)