256 lines
13 KiB
Python
256 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Crée le dashboard "Securite - Alertes Web et CrowdSec" dans OpenSearch Dashboards (Wazuh).
|
|
|
|
Usage:
|
|
python3 create-dashboard.py
|
|
|
|
Le script se connecte depuis l'intérieur du container wazuh_dashboard via:
|
|
docker exec wazuh_dashboard python3 /tmp/create-dashboard.py
|
|
|
|
Ou directement si OpenSearch Dashboards est accessible sur localhost:5601.
|
|
"""
|
|
|
|
import json
|
|
import urllib.request
|
|
import urllib.error
|
|
import ssl
|
|
import base64
|
|
import subprocess
|
|
import sys
|
|
import os
|
|
|
|
# ── Configuration ─────────────────────────────────────────────────────────────
|
|
DASHBOARD_HOST = "https://localhost:5601"
|
|
DASHBOARD_USER = "kibanaserver"
|
|
DASHBOARD_PASS = os.environ.get("DASHBOARD_PASSWORD", "E9Jpr6586kQ3wYrCS2!")
|
|
INDEX_PATTERN = "wazuh-alerts-*"
|
|
|
|
# ── Queries de filtre ─────────────────────────────────────────────────────────
|
|
Q_WEB = "rule.groups: web OR rule.groups: attack OR rule.groups: modsecurity OR rule.groups: api_brute_force"
|
|
Q_CS = "rule.groups: crowdsec OR rule.groups: crowdsec_ban"
|
|
Q_ALL = Q_WEB + " OR " + Q_CS
|
|
|
|
# ── Client HTTP ───────────────────────────────────────────────────────────────
|
|
ctx = ssl.create_default_context()
|
|
ctx.check_hostname = False
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
|
|
_auth = base64.b64encode(f"{DASHBOARD_USER}:{DASHBOARD_PASS}".encode()).decode()
|
|
_headers = {
|
|
"Content-Type": "application/json",
|
|
"osd-xsrf": "true",
|
|
"Authorization": f"Basic {_auth}",
|
|
}
|
|
|
|
def api(method, path, body=None):
|
|
data = json.dumps(body).encode() if body else None
|
|
req = urllib.request.Request(DASHBOARD_HOST + path, data=data, headers=_headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, context=ctx, timeout=15) as r:
|
|
return json.loads(r.read())
|
|
except urllib.error.HTTPError as e:
|
|
return {"error": e.code, "msg": e.read().decode()[:300]}
|
|
|
|
def search_src(query):
|
|
return json.dumps({
|
|
"index": INDEX_PATTERN,
|
|
"filter": [],
|
|
"query": {"language": "kuery", "query": query},
|
|
})
|
|
|
|
# ── Définition des visualisations ─────────────────────────────────────────────
|
|
VISUALIZATIONS = [
|
|
{
|
|
"id": "sec-web-count",
|
|
"title": "[Securite] Alertes Web - Total",
|
|
"type": "metric",
|
|
"query": Q_WEB,
|
|
"visState": {
|
|
"type": "metric",
|
|
"params": {
|
|
"metric": {
|
|
"percentageMode": False,
|
|
"useRanges": False,
|
|
"colorSchema": "Green to Red",
|
|
"metricColorMode": "Labels",
|
|
"colorsRange": [{"from": 0, "to": 10}, {"from": 10, "to": 100}, {"from": 100, "to": 9999}],
|
|
"labels": {"show": True},
|
|
"invertColors": False,
|
|
"style": {"bgFill": "#000", "bgColor": False, "labelColor": False, "subText": "alertes web", "fontSize": 60},
|
|
}
|
|
},
|
|
"aggs": [{"id": "1", "enabled": True, "type": "count", "schema": "metric", "params": {}}],
|
|
},
|
|
},
|
|
{
|
|
"id": "sec-cs-count",
|
|
"title": "[Securite] CrowdSec - Total Bans",
|
|
"type": "metric",
|
|
"query": Q_CS,
|
|
"visState": {
|
|
"type": "metric",
|
|
"params": {
|
|
"metric": {
|
|
"percentageMode": False,
|
|
"useRanges": False,
|
|
"colorSchema": "Green to Red",
|
|
"metricColorMode": "Labels",
|
|
"colorsRange": [{"from": 0, "to": 5}, {"from": 5, "to": 50}, {"from": 50, "to": 9999}],
|
|
"labels": {"show": True},
|
|
"invertColors": False,
|
|
"style": {"bgFill": "#000", "bgColor": False, "labelColor": False, "subText": "bans crowdsec", "fontSize": 60},
|
|
}
|
|
},
|
|
"aggs": [{"id": "1", "enabled": True, "type": "count", "schema": "metric", "params": {}}],
|
|
},
|
|
},
|
|
{
|
|
"id": "sec-web-timeline",
|
|
"title": "[Securite] Alertes Web - Timeline",
|
|
"type": "histogram",
|
|
"query": Q_WEB,
|
|
"visState": {
|
|
"type": "histogram",
|
|
"params": {
|
|
"type": "histogram",
|
|
"grid": {"categoryLines": False},
|
|
"categoryAxes": [{"id": "CategoryAxis-1", "type": "category", "position": "bottom", "show": True, "style": {}, "scale": {"type": "linear"}, "labels": {"show": True, "truncate": 100}, "title": {}}],
|
|
"valueAxes": [{"id": "ValueAxis-1", "name": "LeftAxis-1", "type": "value", "position": "left", "show": True, "style": {}, "scale": {"type": "linear", "mode": "normal"}, "labels": {"show": True, "rotate": 0, "filter": False, "truncate": 100}, "title": {"text": "Alertes"}}],
|
|
"seriesParams": [{"show": True, "type": "histogram", "mode": "stacked", "data": {"label": "Alertes", "id": "1"}, "valueAxis": "ValueAxis-1", "drawLinesBetweenPoints": True, "showCircles": True}],
|
|
"addTooltip": True, "addLegend": True, "legendPosition": "right", "times": [], "addTimeMarker": False,
|
|
},
|
|
"aggs": [
|
|
{"id": "1", "enabled": True, "type": "count", "schema": "metric", "params": {}},
|
|
{"id": "2", "enabled": True, "type": "date_histogram", "schema": "segment", "params": {"field": "@timestamp", "interval": "auto", "customInterval": "2h", "min_doc_count": 1, "extended_bounds": {}}},
|
|
],
|
|
},
|
|
},
|
|
{
|
|
"id": "sec-top-ips",
|
|
"title": "[Securite] Top IPs Attaquantes",
|
|
"type": "horizontal_bar",
|
|
"query": Q_ALL,
|
|
"visState": {
|
|
"type": "horizontal_bar",
|
|
"params": {
|
|
"type": "horizontal_bar",
|
|
"grid": {"categoryLines": False},
|
|
"categoryAxes": [{"id": "CategoryAxis-1", "type": "category", "position": "left", "show": True, "style": {}, "scale": {"type": "linear"}, "labels": {"show": True, "rotate": 0, "filter": True, "truncate": 200}, "title": {}}],
|
|
"valueAxes": [{"id": "ValueAxis-1", "name": "LeftAxis-1", "type": "value", "position": "bottom", "show": True, "style": {}, "scale": {"type": "linear", "mode": "normal"}, "labels": {"show": True, "rotate": 75, "filter": False, "truncate": 100}, "title": {"text": "Alertes"}}],
|
|
"seriesParams": [{"show": True, "type": "horizontal_bar", "mode": "stacked", "data": {"label": "Alertes", "id": "1"}, "valueAxis": "ValueAxis-1", "drawLinesBetweenPoints": True, "showCircles": True}],
|
|
"addTooltip": True, "addLegend": True, "legendPosition": "right", "times": [], "addTimeMarker": False,
|
|
},
|
|
"aggs": [
|
|
{"id": "1", "enabled": True, "type": "count", "schema": "metric", "params": {}},
|
|
{"id": "2", "enabled": True, "type": "terms", "schema": "segment", "params": {"field": "data.srcip", "size": 15, "order": "desc", "orderBy": "1", "otherBucket": False, "missingBucket": False}},
|
|
],
|
|
},
|
|
},
|
|
{
|
|
"id": "sec-top-rules",
|
|
"title": "[Securite] Top Regles Declenchees",
|
|
"type": "pie",
|
|
"query": Q_WEB,
|
|
"visState": {
|
|
"type": "pie",
|
|
"params": {"type": "pie", "addTooltip": True, "addLegend": True, "legendPosition": "right", "isDonut": True, "labels": {"show": False, "values": True, "last_level": True, "truncate": 100}},
|
|
"aggs": [
|
|
{"id": "1", "enabled": True, "type": "count", "schema": "metric", "params": {}},
|
|
{"id": "2", "enabled": True, "type": "terms", "schema": "segment", "params": {"field": "rule.description", "size": 10, "order": "desc", "orderBy": "1", "otherBucket": True, "otherBucketLabel": "Autres", "missingBucket": False}},
|
|
],
|
|
},
|
|
},
|
|
{
|
|
"id": "sec-cs-bans-table",
|
|
"title": "[Securite] CrowdSec - IPs Bannies",
|
|
"type": "table",
|
|
"query": Q_CS,
|
|
"visState": {
|
|
"type": "table",
|
|
"params": {"perPage": 20, "showPartialRows": False, "showMetricsAtAllLevels": False, "sort": {"columnIndex": None, "direction": None}, "showTotal": False, "totalFunc": "sum"},
|
|
"aggs": [
|
|
{"id": "1", "enabled": True, "type": "count", "schema": "metric", "params": {}},
|
|
{"id": "2", "enabled": True, "type": "terms", "schema": "bucket", "params": {"field": "data.srcip", "size": 30, "order": "desc", "orderBy": "1", "otherBucket": False, "missingBucket": False}},
|
|
{"id": "3", "enabled": True, "type": "terms", "schema": "bucket", "params": {"field": "rule.description", "size": 5, "order": "desc", "orderBy": "1", "otherBucket": False, "missingBucket": False}},
|
|
],
|
|
},
|
|
"uiStateJSON": json.dumps({"vis": {"params": {"sort": {"columnIndex": 0, "direction": "desc"}}}}),
|
|
},
|
|
{
|
|
"id": "sec-severity",
|
|
"title": "[Securite] Distribution Severite",
|
|
"type": "pie",
|
|
"query": Q_WEB,
|
|
"visState": {
|
|
"type": "pie",
|
|
"params": {"type": "pie", "addTooltip": True, "addLegend": True, "legendPosition": "right", "isDonut": False, "labels": {"show": True, "values": True, "last_level": True, "truncate": 100}},
|
|
"aggs": [
|
|
{"id": "1", "enabled": True, "type": "count", "schema": "metric", "params": {}},
|
|
{"id": "2", "enabled": True, "type": "terms", "schema": "segment", "params": {"field": "rule.level", "size": 15, "order": "desc", "orderBy": "1", "otherBucket": False}},
|
|
],
|
|
},
|
|
},
|
|
]
|
|
|
|
# ── Layout dashboard (grid 48 colonnes) ───────────────────────────────────────
|
|
PANELS = [
|
|
{"panelIndex": "1", "gridData": {"x": 0, "y": 0, "w": 24, "h": 6, "i": "1"}, "version": "2.19.5", "type": "visualization", "id": "sec-web-count", "embeddableConfig": {}},
|
|
{"panelIndex": "2", "gridData": {"x": 24, "y": 0, "w": 24, "h": 6, "i": "2"}, "version": "2.19.5", "type": "visualization", "id": "sec-cs-count", "embeddableConfig": {}},
|
|
{"panelIndex": "3", "gridData": {"x": 0, "y": 6, "w": 48, "h": 12, "i": "3"}, "version": "2.19.5", "type": "visualization", "id": "sec-web-timeline", "embeddableConfig": {}},
|
|
{"panelIndex": "4", "gridData": {"x": 0, "y": 18, "w": 28, "h": 14, "i": "4"}, "version": "2.19.5", "type": "visualization", "id": "sec-top-ips", "embeddableConfig": {}},
|
|
{"panelIndex": "5", "gridData": {"x": 28, "y": 18, "w": 20, "h": 14, "i": "5"}, "version": "2.19.5", "type": "visualization", "id": "sec-top-rules", "embeddableConfig": {}},
|
|
{"panelIndex": "6", "gridData": {"x": 0, "y": 32, "w": 48, "h": 12, "i": "6"}, "version": "2.19.5", "type": "visualization", "id": "sec-cs-bans-table", "embeddableConfig": {}},
|
|
{"panelIndex": "7", "gridData": {"x": 0, "y": 44, "w": 24, "h": 10, "i": "7"}, "version": "2.19.5", "type": "visualization", "id": "sec-severity", "embeddableConfig": {}},
|
|
]
|
|
|
|
# ── Main ──────────────────────────────────────────────────────────────────────
|
|
def main():
|
|
print("=== Création du dashboard Securite - Alertes Web et CrowdSec ===\n")
|
|
|
|
# Visualisations
|
|
for viz in VISUALIZATIONS:
|
|
vis_state = dict(viz["visState"])
|
|
vis_state["title"] = viz["title"]
|
|
body = {
|
|
"attributes": {
|
|
"title": viz["title"],
|
|
"visState": json.dumps(vis_state),
|
|
"uiStateJSON": viz.get("uiStateJSON", "{}"),
|
|
"description": "",
|
|
"kibanaSavedObjectMeta": {"searchSourceJSON": search_src(viz["query"])},
|
|
}
|
|
}
|
|
r = api("POST", f"/api/saved_objects/visualization/{viz['id']}?overwrite=true", body)
|
|
if "id" in r:
|
|
print(f" ✅ {viz['title']}")
|
|
else:
|
|
print(f" ❌ {viz['title']}: {r}")
|
|
sys.exit(1)
|
|
|
|
# Dashboard
|
|
dashboard_body = {
|
|
"attributes": {
|
|
"title": "Securite - Alertes Web et CrowdSec",
|
|
"description": "Alertes OWASP ModSecurity brute-force API et bans CrowdSec",
|
|
"panelsJSON": json.dumps(PANELS),
|
|
"optionsJSON": json.dumps({"useMargins": True, "hidePanelTitles": False}),
|
|
"timeRestore": False,
|
|
"kibanaSavedObjectMeta": {
|
|
"searchSourceJSON": json.dumps({"query": {"language": "kuery", "query": ""}, "filter": []})
|
|
},
|
|
}
|
|
}
|
|
r = api("POST", "/api/saved_objects/dashboard/sec-web-crowdsec-dashboard?overwrite=true", dashboard_body)
|
|
if "id" in r:
|
|
print(f"\n ✅ Dashboard: {r['id']}")
|
|
print(f"\n URL: https://<monitoring-ip>/#/app/dashboards#/view/{r['id']}")
|
|
else:
|
|
print(f"\n ❌ Dashboard: {r}")
|
|
sys.exit(1)
|
|
|
|
print("\n=== Terminé ===")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|