-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
168 lines (140 loc) · 5.1 KB
/
main.py
File metadata and controls
168 lines (140 loc) · 5.1 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
import os
import json
import datetime
import httpx
import logging
import unicodedata
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Basic Configuration & Security
DISCORD_WEBHOOK_URL = os.getenv("DISCORD_WEBHOOK_URL")
# Rate limiter configuration to prevent webhook spamming
limiter = Limiter(key_func=get_remote_address)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Manage the application lifespan.
Initializes a single HTTP client for better performance and connection pooling.
"""
app.state.http_client = httpx.AsyncClient(timeout=10.0)
yield
await app.state.http_client.aclose()
app = FastAPI(title="OOB-er", lifespan=lifespan)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Restrictive CORS Middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Should be restricted in production
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
def truncate_data(data: str, max_length: int = 1000) -> str:
"""
Prevents Discord 400 errors by truncating payloads that are too large.
"""
if len(data) > max_length:
return data[:max_length] + "... [TRUNCATED]"
return data
async def send_discord_notification(details: dict, client: httpx.AsyncClient):
"""
Sends a formatted notification to the configured Discord webhook.
"""
if not DISCORD_WEBHOOK_URL:
logging.error("DISCORD_WEBHOOK_URL not configured.")
return
def sanitize(text: any, max_length: int = 1024) -> str:
"""
Sanitizes inputs for secure display in Discord.
"""
if text is None:
return "N/A"
# Convert to string and normalize Unicode (NFKC)
text = str(text)
text = unicodedata.normalize("NFKC", text)
# Remove control characters (00-1F and 7F-9F)
text = "".join(
ch for ch in text if unicodedata.category(ch)[0] != "C" or ch == "\n"
)
# Protect against Discord code block evasion
text = text.replace("`", "´")
# Clean up Discord mentions
text = text.replace("@everyone", "@-everyone").replace("@here", "@-here")
# Strict truncation (Discord field limit = 1024)
if len(text) > max_length:
text = text[: max_length - 3] + "..."
return text.strip()
embed = {
"title": "🚨 OOB Interaction Detected",
"color": 0xFF0000,
"fields": [
{
"name": "Date (UTC)",
"value": sanitize(details.get("human_readable_date")),
"inline": False,
},
{"name": "URL", "value": sanitize(details.get("url")), "inline": False},
{
"name": "Client IP",
"value": sanitize(details.get("client_ip")),
"inline": True,
},
{
"name": "Method",
"value": sanitize(details.get("method")),
"inline": True,
},
{
"name": "Query Params",
"value": f"```json\n{truncate_data(json.dumps(details.get('query_params'), indent=2))}\n```",
"inline": False,
},
{
"name": "Cookies",
"value": f"```json\n{truncate_data(json.dumps(details.get('cookies'), indent=2))}\n```",
"inline": False,
},
{
"name": "Headers",
"value": f"```json\n{truncate_data(json.dumps(details.get('headers'), indent=2))}\n```",
"inline": False,
},
],
"footer": {"text": "Security Monitoring System"},
}
try:
response = await client.post(DISCORD_WEBHOOK_URL, json={"embeds": [embed]})
response.raise_for_status()
except Exception as e:
logging.error(f"Webhook Error: {e}")
@app.get("/oob")
@limiter.limit("5/minute") # Flood protection
async def oob_endpoint(request: Request):
"""
Endpoint that triggers a Discord notification with request details.
"""
# Secure IP extraction (handles proxies)
client_ip = request.headers.get("x-forwarded-for", request.client.host)
now = datetime.datetime.now(datetime.timezone.utc)
details = {
"timestamp": now.isoformat(),
"human_readable_date": now.strftime("%Y-%m-%d %H:%M:%S"),
"url": str(request.url),
"client_ip": client_ip,
"method": request.method,
"headers": dict(request.headers),
"query_params": dict(request.query_params),
"cookies": dict(request.cookies),
}
await send_discord_notification(details, request.app.state.http_client)
return {"status": "accepted"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)