Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a780cd52f | ||
|
|
daa494fade | ||
|
|
e7fd4e7ef5 | ||
|
|
dfdae7a532 | ||
|
|
854c99e3b2 | ||
|
|
2598de2ecc | ||
|
|
6c791cc417 | ||
|
|
0adac8a0d9 | ||
|
|
a45a811040 | ||
|
|
2f2a553fc2 | ||
|
|
6ceb29a07b |
@@ -6,6 +6,7 @@
|
||||
"n8nWebhookUrl": "http://172.16.41.197:5678/webhook/ocsentinel-ingest",
|
||||
"deviceIdentifierMode": "machineName",
|
||||
"uploadTimeoutSeconds": 30,
|
||||
"uploadQueueMaxReports": 100,
|
||||
"enableVulnerabilityCorrelation": true,
|
||||
"vulnerabilityCsvPath": "",
|
||||
"secretReference": "device-default"
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"n8nWebhookUrl": "https://n8n.example.com/webhook/ocsentinel-ingest",
|
||||
"deviceIdentifierMode": "machineName",
|
||||
"uploadTimeoutSeconds": 30,
|
||||
"uploadQueueMaxReports": 100,
|
||||
"enableVulnerabilityCorrelation": true,
|
||||
"vulnerabilityCsvPath": "",
|
||||
"secretReference": "device-default"
|
||||
|
||||
@@ -39,12 +39,39 @@ The installer creates two Windows Scheduled Tasks running as `SYSTEM`:
|
||||
`04:00` and `06:59`, derived from its Windows `MachineGuid`. This distributes
|
||||
a fleet rollout instead of sending all reports at the same time.
|
||||
- `OCSentinel Burst Check`: runs every five minutes. It performs no scan unless
|
||||
the NinjaOne device custom field `ocsentinelburst` is enabled.
|
||||
the NinjaOne device custom field `ocsentinelburst` is enabled. Once enabled,
|
||||
it scans for two hours and then disables itself automatically.
|
||||
|
||||
Create `ocsentinelburst` as a device-level `Checkbox` custom field and allow
|
||||
automation read access. Set it to `true` for a device to begin the five-minute
|
||||
burst scans; clear it to stop them. The normal daily scan continues regardless
|
||||
of the checkbox.
|
||||
automation read and write access. Set it to `true` for a device to begin the
|
||||
five-minute burst scans; clear it to stop them early. The normal daily scan
|
||||
continues regardless of the checkbox.
|
||||
|
||||
Create these accompanying device custom fields and allow automation write
|
||||
access:
|
||||
|
||||
| Field name | Type | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `ocsentinelburstuntilutc` | Date/Time | UTC time at which the active burst ends |
|
||||
| `ocsentinelburststatus` | Text | `idle`, `active until ...`, or `completed` |
|
||||
|
||||
## Upload Reliability And Client Health
|
||||
|
||||
If the upload endpoint is temporarily unavailable, the client stores up to 100
|
||||
signed report payloads locally under `C:\ProgramData\OCSentinel\upload-queue`.
|
||||
The next scheduled run sends queued payloads before its new report. The local
|
||||
health state is stored under `C:\ProgramData\OCSentinel\state`.
|
||||
|
||||
Create these additional device custom fields in NinjaOne and allow automation
|
||||
write access:
|
||||
|
||||
| Field name | Type | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `ocsentineluploadstatus` | Text | `ok`, `queued`, or `unknown` upload state |
|
||||
| `ocsentinelqueuedreports` | Integer | Reports waiting for delivery |
|
||||
| `ocsentinellastuploadutc` | Date/Time | Last successful upload time |
|
||||
| `ocsentinellasterror` | Text | Last upload error, if any |
|
||||
| `ocsentinelclientversion` | Text | Installed client version |
|
||||
|
||||
## NinjaOne Tasks
|
||||
|
||||
|
||||
8
infra/debug-dashboard/.env.example
Normal file
8
infra/debug-dashboard/.env.example
Normal file
@@ -0,0 +1,8 @@
|
||||
DB_HOST=ocsentinel-postgres
|
||||
DB_PORT=5432
|
||||
DB_NAME=ocsentinel
|
||||
DB_USER=ocsentinel_debug
|
||||
DB_PASSWORD=replace-with-server-generated-password
|
||||
DASHBOARD_USER=ocsentinel-debug
|
||||
DASHBOARD_PASSWORD=replace-with-server-generated-password
|
||||
DASHBOARD_CSRF_SECRET=replace-with-server-generated-secret
|
||||
15
infra/debug-dashboard/Dockerfile
Normal file
15
infra/debug-dashboard/Dockerfile
Normal file
@@ -0,0 +1,15 @@
|
||||
FROM python:3.13-alpine
|
||||
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY app.py .
|
||||
COPY templates ./templates
|
||||
COPY static ./static
|
||||
|
||||
RUN addgroup -S ocsentinel && adduser -S ocsentinel -G ocsentinel
|
||||
USER ocsentinel
|
||||
|
||||
EXPOSE 8080
|
||||
CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "2", "--threads", "4", "--timeout", "30", "app:app"]
|
||||
234
infra/debug-dashboard/app.py
Normal file
234
infra/debug-dashboard/app.py
Normal file
@@ -0,0 +1,234 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from functools import wraps
|
||||
|
||||
import psycopg
|
||||
from flask import Flask, Response, abort, redirect, render_template, request, url_for
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
|
||||
def db_connection():
|
||||
return psycopg.connect(
|
||||
host=os.environ["DB_HOST"],
|
||||
port=os.getenv("DB_PORT", "5432"),
|
||||
dbname=os.environ["DB_NAME"],
|
||||
user=os.environ["DB_USER"],
|
||||
password=os.environ["DB_PASSWORD"],
|
||||
connect_timeout=5,
|
||||
)
|
||||
|
||||
|
||||
def requires_auth(view):
|
||||
@wraps(view)
|
||||
def wrapped(*args, **kwargs):
|
||||
auth = __import__("flask").request.authorization
|
||||
expected_user = os.environ["DASHBOARD_USER"]
|
||||
expected_password = os.environ["DASHBOARD_PASSWORD"]
|
||||
valid = auth and hmac.compare_digest(auth.username or "", expected_user) and hmac.compare_digest(auth.password or "", expected_password)
|
||||
if not valid:
|
||||
return Response("Authentication required", 401, {"WWW-Authenticate": 'Basic realm="OCSentinel Debug"'})
|
||||
return view(*args, **kwargs)
|
||||
|
||||
return wrapped
|
||||
|
||||
|
||||
def csrf_token():
|
||||
secret = os.environ["DASHBOARD_CSRF_SECRET"].encode("utf-8")
|
||||
return hmac.new(secret, b"recipient-rules", hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def require_csrf():
|
||||
supplied = request.form.get("csrf_token", "")
|
||||
if not hmac.compare_digest(supplied, csrf_token()):
|
||||
abort(400)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
@requires_auth
|
||||
def overview():
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute("SELECT * FROM ocsentinel.organization_summary")
|
||||
summary = cursor.fetchone()
|
||||
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT machine_name, organization_name, received_at, alert_state,
|
||||
total_events, unique_ip_count, cve_total, cve_critical
|
||||
FROM (
|
||||
SELECT machine_name, received_at, alert_state, total_events,
|
||||
unique_ip_count, cve_total, cve_critical,
|
||||
payload #>> '{NinjaOne,OrganizationName}' AS organization_name
|
||||
FROM ocsentinel.current_device_status
|
||||
) AS status
|
||||
ORDER BY received_at DESC NULLS LAST
|
||||
LIMIT 100
|
||||
"""
|
||||
)
|
||||
reports = cursor.fetchall()
|
||||
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT machine_name, alert_state, total_events, unique_ip_count,
|
||||
received_at, payload
|
||||
FROM ocsentinel.current_device_status
|
||||
WHERE alert_state IN ('warning', 'critical')
|
||||
ORDER BY CASE alert_state WHEN 'critical' THEN 0 ELSE 1 END, received_at DESC
|
||||
"""
|
||||
)
|
||||
alerts = cursor.fetchall()
|
||||
|
||||
return render_template("overview.html", summary=summary, reports=reports, alerts=alerts)
|
||||
|
||||
|
||||
@app.get("/device/<machine_name>")
|
||||
@requires_auth
|
||||
def device(machine_name):
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT machine_name, first_seen_at, last_seen_at, last_client_version,
|
||||
generated_at_utc, received_at, alert_state, base_alert_state,
|
||||
total_events, unique_ip_count, cve_total, cve_critical, payload
|
||||
FROM ocsentinel.current_device_status
|
||||
WHERE machine_name = %s
|
||||
""",
|
||||
(machine_name,),
|
||||
)
|
||||
report = cursor.fetchone()
|
||||
|
||||
if report is None:
|
||||
abort(404)
|
||||
|
||||
payload = report[12]
|
||||
return render_template("device.html", report=report, payload=payload, payload_pretty=json.dumps(payload, indent=2, ensure_ascii=False))
|
||||
|
||||
|
||||
@app.get("/reports")
|
||||
@requires_auth
|
||||
def reports():
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT id, organization_name, period_start_utc, period_end_utc,
|
||||
generated_at, device_count, warning_count, critical_count,
|
||||
total_events
|
||||
FROM ocsentinel.weekly_organization_report
|
||||
ORDER BY period_end_utc DESC, organization_name
|
||||
"""
|
||||
)
|
||||
weekly_reports = cursor.fetchall()
|
||||
|
||||
return render_template("reports.html", reports=weekly_reports)
|
||||
|
||||
|
||||
@app.get("/reports/<int:report_id>")
|
||||
@requires_auth
|
||||
def weekly_report(report_id):
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT organization_name, period_start_utc, period_end_utc,
|
||||
generated_at, report_html
|
||||
FROM ocsentinel.weekly_organization_report
|
||||
WHERE id = %s
|
||||
""",
|
||||
(report_id,),
|
||||
)
|
||||
report = cursor.fetchone()
|
||||
|
||||
if report is None:
|
||||
abort(404)
|
||||
|
||||
return render_template("weekly_report.html", report=report)
|
||||
|
||||
|
||||
@app.get("/recipients")
|
||||
@requires_auth
|
||||
def recipients():
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT id, organization_id, organization_name, recipient_email, enabled
|
||||
FROM ocsentinel.organization_report_recipient
|
||||
ORDER BY organization_id = '*', organization_name, recipient_email
|
||||
"""
|
||||
)
|
||||
rules = cursor.fetchall()
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT DISTINCT payload #>> '{NinjaOne,OrganizationId}',
|
||||
payload #>> '{NinjaOne,OrganizationName}'
|
||||
FROM ocsentinel.current_device_status
|
||||
WHERE coalesce(payload #>> '{NinjaOne,OrganizationId}', '') <> ''
|
||||
ORDER BY 2
|
||||
"""
|
||||
)
|
||||
organizations = cursor.fetchall()
|
||||
|
||||
return render_template("recipients.html", rules=rules, organizations=organizations, csrf_token=csrf_token())
|
||||
|
||||
|
||||
@app.post("/recipients")
|
||||
@requires_auth
|
||||
def add_recipient():
|
||||
require_csrf()
|
||||
organization_id = request.form.get("organization_id", "").strip()
|
||||
organization_name = request.form.get("organization_name", "").strip()
|
||||
recipient_email = request.form.get("recipient_email", "").strip().lower()
|
||||
if not organization_id or not organization_name or "@" not in recipient_email:
|
||||
abort(400)
|
||||
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO ocsentinel.organization_report_recipient
|
||||
(organization_id, organization_name, recipient_email)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (organization_id, recipient_email) DO NOTHING
|
||||
""",
|
||||
(organization_id, organization_name, recipient_email),
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
return redirect(url_for("recipients"))
|
||||
|
||||
|
||||
@app.post("/recipients/<int:rule_id>/toggle")
|
||||
@requires_auth
|
||||
def toggle_recipient(rule_id):
|
||||
require_csrf()
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"UPDATE ocsentinel.organization_report_recipient SET enabled = NOT enabled WHERE id = %s",
|
||||
(rule_id,),
|
||||
)
|
||||
connection.commit()
|
||||
return redirect(url_for("recipients"))
|
||||
|
||||
|
||||
@app.post("/recipients/<int:rule_id>/delete")
|
||||
@requires_auth
|
||||
def delete_recipient(rule_id):
|
||||
require_csrf()
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute("DELETE FROM ocsentinel.organization_report_recipient WHERE id = %s", (rule_id,))
|
||||
connection.commit()
|
||||
return redirect(url_for("recipients"))
|
||||
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz():
|
||||
try:
|
||||
with db_connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute("SELECT 1")
|
||||
return {"status": "ok"}
|
||||
except Exception:
|
||||
return {"status": "unavailable"}, 503
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8080)
|
||||
22
infra/debug-dashboard/compose.yml
Normal file
22
infra/debug-dashboard/compose.yml
Normal file
@@ -0,0 +1,22 @@
|
||||
services:
|
||||
ocsentinel-debug:
|
||||
build: .
|
||||
container_name: ocsentinel-debug
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
ports:
|
||||
- "172.16.41.197:8090:8080"
|
||||
networks:
|
||||
- ocsentinel-network
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
|
||||
networks:
|
||||
ocsentinel-network:
|
||||
external: true
|
||||
name: n8n_n8n-network
|
||||
3
infra/debug-dashboard/requirements.txt
Normal file
3
infra/debug-dashboard/requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
Flask==3.1.1
|
||||
gunicorn==23.0.0
|
||||
psycopg[binary]==3.2.9
|
||||
15
infra/debug-dashboard/static/app.css
Normal file
15
infra/debug-dashboard/static/app.css
Normal file
@@ -0,0 +1,15 @@
|
||||
:root { --ink:#17201d; --muted:#66736d; --paper:#f5f3eb; --panel:#fffdf7; --line:#d8d4c6; --green:#236342; --lime:#c7ee6b; --amber:#b86613; --red:#a8342b; }
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; color:var(--ink); background:radial-gradient(circle at 86% -10%, #d6efad 0, transparent 28rem), var(--paper); font-family:Georgia, 'Times New Roman', serif; }.app-shell:before { content:''; position:fixed; z-index:-1; inset:0; opacity:.28; background-image:linear-gradient(rgba(35,99,66,.06) 1px,transparent 1px),linear-gradient(90deg,rgba(35,99,66,.06) 1px,transparent 1px); background-size:34px 34px; mask-image:linear-gradient(to bottom,black,transparent 62%); }
|
||||
.masthead { height:70px; padding:0 6vw; display:flex; align-items:center; justify-content:space-between; border-bottom:1px solid var(--line); background:rgba(255,253,247,.88); box-shadow:0 4px 22px rgba(35,56,42,.06); backdrop-filter:blur(14px); }.header-links { display:flex; gap:8px; align-items:center; }.header-links a { padding:7px 9px; border-radius:7px; color:var(--muted); font:700 12px Arial,sans-serif; text-decoration:none; transition:background .18s ease,color .18s ease; }.header-links a:hover,.header-links a.active { color:var(--green); background:#e6f1e9; }
|
||||
.brand { color:var(--ink); font:700 20px/1 Arial,sans-serif; text-decoration:none; letter-spacing:-.04em; }.brand span { display:inline-grid; place-items:center; margin-right:7px; width:28px; height:28px; background:var(--green); color:#fff; border-radius:50%; font-size:11px; letter-spacing:0; }.badge,.eyebrow { color:var(--muted); font:700 10px/1 Arial,sans-serif; text-transform:uppercase; letter-spacing:.12em; }.badge { border:1px solid var(--line); padding:6px 8px; border-radius:20px; }
|
||||
main { max-width:1280px; margin:auto; padding:58px 6vw 80px; }.hero { max-width:760px; margin-bottom:32px; }.hero h1 { font-size:clamp(34px,5vw,64px); line-height:.98; letter-spacing:-.06em; margin:10px 0; }.hero p { color:var(--muted); font-size:18px; }.hero.compact h1 { font-size:48px; }.hero-note { display:flex; align-items:center; gap:8px; margin-top:20px; color:var(--green); font:700 11px Arial,sans-serif; letter-spacing:.03em; }.hero-note span { width:8px; height:8px; border-radius:50%; background:var(--lime); box-shadow:0 0 0 4px rgba(199,238,107,.25); }
|
||||
.metrics { display:grid; grid-template-columns:repeat(5,1fr); gap:10px; margin:25px 0 46px; background:transparent; }.metrics article { min-height:130px; padding:20px; border:1px solid var(--line); border-radius:5px; background:var(--panel); box-shadow:0 5px 16px rgba(35,56,42,.035); transition:transform .18s ease,box-shadow .18s ease; }.metrics article:hover { transform:translateY(-3px); box-shadow:0 12px 24px rgba(35,56,42,.09); }.metrics span { display:block; color:var(--muted); font:700 10px Arial,sans-serif; letter-spacing:.09em; text-transform:uppercase; }.metrics strong { display:block; margin-top:16px; font:700 31px Arial,sans-serif; letter-spacing:-.05em; }.metrics .timestamp { font-size:14px; line-height:1.25; letter-spacing:-.02em; }.warning { color:var(--amber); }.critical { color:var(--red); }
|
||||
.situation { display:flex; align-items:center; justify-content:space-between; gap:22px; margin:0 0 24px; padding:20px 22px; border:1px solid #b9d8c2; background:#edf8f0; color:#195235; }.situation.warning { border-color:#f2cf99; background:#fff6e8; color:#80450d; }.situation.critical { border-color:#edb4aa; background:#fff0ed; color:#8a2a20; }.situation strong { display:block; margin-top:7px; font:700 19px/1.15 Arial,sans-serif; letter-spacing:-.025em; }.situation > span { padding:7px 9px; border:1px solid currentColor; border-radius:20px; font:700 10px Arial,sans-serif; letter-spacing:.1em; }
|
||||
.panel { margin-top:26px; padding:26px; background:var(--panel); border:1px solid var(--line); border-radius:5px; box-shadow:0 6px 18px rgba(35,56,42,.035); }.panel-heading h2 { margin:8px 0 22px; font-size:28px; letter-spacing:-.04em; }.alert-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(210px,1fr)); gap:12px; }.alert-card { padding:17px; border-left:5px solid var(--amber); border-radius:3px; background:#fff7e9; color:var(--ink); text-decoration:none; transition:transform .18s ease,box-shadow .18s ease; }.alert-card:hover { transform:translateY(-2px); box-shadow:0 9px 18px rgba(88,57,20,.12); }.alert-card.critical { border-color:var(--red); background:#fff0ed; }.alert-card span,.alert-card small { display:block; font:700 10px Arial,sans-serif; letter-spacing:.08em; text-transform:uppercase; }.alert-card strong { display:block; margin:10px 0; font:700 22px Arial,sans-serif; letter-spacing:-.04em; }
|
||||
table { width:100%; border-collapse:collapse; font-family:Arial,sans-serif; font-size:13px; } th { text-align:left; color:var(--muted); font-size:10px; letter-spacing:.1em; text-transform:uppercase; } th,td { padding:13px 8px; border-bottom:1px solid var(--line); } td a { color:var(--green); font-weight:700; text-decoration:none; }.state { display:inline-block; padding:4px 7px; border-radius:12px; background:#e2efe6; color:var(--green); font:700 10px Arial,sans-serif; text-transform:uppercase; }.state.warning { background:#fff0d7; color:var(--amber); }.state.critical { background:#ffe0db; color:var(--red); } pre { margin:0; padding:18px; overflow:auto; color:#dce7da; background:#13221b; border-radius:4px; font:12px/1.5 'Cascadia Code',Consolas,monospace; }.table-wrap { overflow:auto; }
|
||||
.report-frame { background:#fff; border:1px solid var(--line); box-shadow:0 12px 40px rgba(20,35,27,.1); }
|
||||
.panel-heading p:last-child { max-width:720px; margin:-13px 0 20px; color:var(--muted); font-size:14px; }.calm-panel { border-color:#b9d8c2; background:#f4fbf5; }
|
||||
.recipient-form { display:grid; grid-template-columns:minmax(220px,1fr) minmax(260px,1fr) auto; gap:14px; align-items:end; }.recipient-form label { display:grid; gap:6px; color:var(--muted); font:700 10px Arial,sans-serif; letter-spacing:.08em; text-transform:uppercase; }.recipient-form input,.recipient-form select { min-height:40px; padding:9px 10px; border:1px solid var(--line); border-radius:4px; background:#fff; color:var(--ink); font:14px Arial,sans-serif; }.recipient-form button,.rule-actions button { min-height:40px; padding:9px 13px; border:1px solid var(--green); border-radius:4px; background:var(--green); color:#fff; cursor:pointer; font:700 12px Arial,sans-serif; }.rule-actions { display:flex; gap:8px; }.rule-actions form { margin:0; }.rule-actions .button-secondary { border-color:#d8d4c6; background:#fffdf7; color:var(--ink); }.rule-actions .button-danger { border-color:#e3afa7; background:#fff0ed; color:#8a2a20; }
|
||||
@media (max-width:850px) { .recipient-form { grid-template-columns:1fr; }.rule-actions { min-width:220px; } }
|
||||
@media (max-width:850px) { .metrics { grid-template-columns:repeat(2,1fr); }.metrics article:last-child { grid-column:span 2; }.masthead { height:auto; min-height:70px; padding:14px 5vw; align-items:flex-start; }.header-links { justify-content:flex-end; flex-wrap:wrap; }.badge { display:none; } main { padding:38px 5vw; }.situation { align-items:flex-start; flex-direction:column; } }
|
||||
16
infra/debug-dashboard/templates/base.html
Normal file
16
infra/debug-dashboard/templates/base.html
Normal file
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{% block title %}OCSentinel Debug{% endblock %}</title>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='app.css') }}">
|
||||
</head>
|
||||
<body class="app-shell">
|
||||
<header class="masthead">
|
||||
<a href="/" class="brand"><span>OC</span> Sentinel</a>
|
||||
<div class="header-links"><a class="{{ 'active' if request.endpoint == 'overview' else '' }}" href="/">Sicherheitslage</a><a class="{{ 'active' if request.endpoint in ('reports', 'weekly_report') else '' }}" href="{{ url_for('reports') }}">Wochenberichte</a><a class="{{ 'active' if request.endpoint in ('recipients', 'add_recipient', 'toggle_recipient', 'delete_recipient') else '' }}" href="{{ url_for('recipients') }}">Empfaenger</a><div class="badge">interner Sicherheitsbereich</div></div>
|
||||
</header>
|
||||
<main>{% block content %}{% endblock %}</main>
|
||||
</body>
|
||||
</html>
|
||||
7
infra/debug-dashboard/templates/device.html
Normal file
7
infra/debug-dashboard/templates/device.html
Normal file
@@ -0,0 +1,7 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}{{ report[0] }} - OCSentinel{% endblock %}
|
||||
{% block content %}
|
||||
<section class="hero compact"><p class="eyebrow">Geraetedetails</p><h1>{{ report[0] }}</h1><p><span class="state {{ report[6] }}">{{ report[6] }}</span> | Letzte Datenmeldung: {{ report[5] }}</p></section>
|
||||
<section class="metrics compact-metrics"><article><span>Ereignisse</span><strong>{{ report[8] }}</strong></article><article><span>Quell-IPs</span><strong>{{ report[9] }}</strong></article><article><span>CVEs</span><strong>{{ report[10] }}</strong></article><article><span>Kritische CVEs</span><strong class="critical">{{ report[11] }}</strong></article></section>
|
||||
<section class="panel"><div class="panel-heading"><p class="eyebrow">Technische Details</p><h2>Signierter Sicherheitsbericht</h2><p>Unveraenderte Rohdaten zur Nachvollziehbarkeit und Fehleranalyse.</p></div><pre>{{ payload_pretty }}</pre></section>
|
||||
{% endblock %}
|
||||
43
infra/debug-dashboard/templates/overview.html
Normal file
43
infra/debug-dashboard/templates/overview.html
Normal file
@@ -0,0 +1,43 @@
|
||||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<section class="hero">
|
||||
<p class="eyebrow">OCSentinel Sicherheitszentrale</p>
|
||||
<h1>OfficeCom Sentinal Übersicht</h1>
|
||||
<p>Aktuelle Auswertung aller signierten Sicherheitsberichte aus den betreuten Organisationen.</p>
|
||||
<div class="hero-note"><span></span> Zentraler Ueberblick ueber Geraete, Ereignisse und Handlungsbedarf</div>
|
||||
</section>
|
||||
|
||||
<section class="situation {% if summary[2] %}critical{% elif summary[1] %}warning{% else %}ok{% endif %}">
|
||||
<div><p class="eyebrow">Aktuelle Lage</p><strong>{% if summary[2] %}Kritische Ereignisse erfordern Aufmerksamkeit.{% elif summary[1] %}Hinweise vorhanden - bitte auffaellige Geraete pruefen.{% else %}Keine kritischen Auffaelligkeiten gemeldet.{% endif %}</strong></div>
|
||||
<span>{% if summary[2] %}KRITISCH{% elif summary[1] %}PRUEFEN{% else %}STABIL{% endif %}</span>
|
||||
</section>
|
||||
|
||||
<section class="metrics">
|
||||
<article><span>Geraete mit Bericht</span><strong>{{ summary[0] }}</strong></article>
|
||||
<article><span>Warnungen</span><strong class="warning">{{ summary[1] }}</strong></article>
|
||||
<article><span>Kritische Geraete</span><strong class="critical">{{ summary[2] }}</strong></article>
|
||||
<article><span>Erkannte Ereignisse</span><strong>{{ summary[3] }}</strong></article>
|
||||
<article><span>Letzte Datenmeldung</span><strong class="timestamp">{{ summary[7] or 'noch keine Daten' }}</strong></article>
|
||||
</section>
|
||||
|
||||
{% if alerts %}
|
||||
<section class="panel alert-panel">
|
||||
<div class="panel-heading"><p class="eyebrow">Handlungsbedarf</p><h2>Auffaellige Geraete</h2><p>Diese Geraete haben zuletzt Warnungen oder kritische Sicherheitsereignisse gemeldet.</p></div>
|
||||
<div class="alert-grid">
|
||||
{% for alert in alerts %}
|
||||
<a class="alert-card {{ alert[1] }}" href="{{ url_for('device', machine_name=alert[0]) }}">
|
||||
<span>{{ alert[1] }}</span><strong>{{ alert[0] }}</strong><small>{{ alert[2] }} Ereignisse | {{ alert[3] }} Quell-IPs | {{ alert[4] }}</small>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
{% else %}
|
||||
<section class="panel calm-panel"><div class="panel-heading"><p class="eyebrow">Handlungsbedarf</p><h2>Keine auffaelligen Geraete</h2><p>Die zuletzt eingegangenen Berichte enthalten keine Warnungen oder kritischen Ereignisse.</p></div></section>
|
||||
{% endif %}
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><p class="eyebrow">Berichtsbestand</p><h2>Aktuelle Geraetestatus</h2><p>Jede Zeile zeigt den letzten erfolgreich uebermittelten OCSentinel-Bericht eines Geraets.</p></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>Geraet</th><th>Organisation</th><th>Status</th><th>Ereignisse</th><th>Quell-IPs</th><th>Empfangen</th></tr></thead>
|
||||
<tbody>{% for row in reports %}<tr><td><a href="{{ url_for('device', machine_name=row[0]) }}">{{ row[0] }}</a></td><td>{{ row[1] or '-' }}</td><td><span class="state {{ row[3] }}">{{ row[3] }}</span></td><td>{{ row[4] }}</td><td>{{ row[5] }}</td><td>{{ row[2] or '-' }}</td></tr>{% else %}<tr><td colspan="6">Noch keine Geraeteberichte vorhanden.</td></tr>{% endfor %}</tbody></table></div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
19
infra/debug-dashboard/templates/recipients.html
Normal file
19
infra/debug-dashboard/templates/recipients.html
Normal file
@@ -0,0 +1,19 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Berichtsempfaenger - OCSentinel{% endblock %}
|
||||
{% block content %}
|
||||
<section class="hero compact"><p class="eyebrow">Wochenberichte</p><h1>Berichtsempfaenger</h1><p>Diese Regeln bestimmen, wer den Wochenbericht einer Organisation per E-Mail erhaelt.</p></section>
|
||||
|
||||
<section class="panel"><div class="panel-heading"><p class="eyebrow">Neue Regel</p><h2>Empfaenger hinzufuegen</h2></div>
|
||||
<form class="recipient-form" method="post" action="{{ url_for('add_recipient') }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
|
||||
<label>Organisation<select name="organization_id" id="organization_id" required onchange="document.getElementById('organization_name').value=this.options[this.selectedIndex].dataset.name"><option value="*" data-name="Alle Organisationen">Alle Organisationen</option>{% for organization in organizations %}<option value="{{ organization[0] }}" data-name="{{ organization[1] }}">{{ organization[1] }}</option>{% endfor %}</select></label>
|
||||
<input type="hidden" name="organization_name" id="organization_name" value="Alle Organisationen">
|
||||
<label>E-Mail-Adresse<input type="email" name="recipient_email" placeholder="name@officecom.it" required></label>
|
||||
<button type="submit">Empfaenger speichern</button>
|
||||
</form></section>
|
||||
|
||||
<section class="panel"><div class="panel-heading"><p class="eyebrow">Aktive Regeln</p><h2>E-Mail-Verteiler</h2><p>"Alle Organisationen" wird zu jedem organisationsspezifischen Verteiler hinzugefuegt.</p></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>Organisation</th><th>E-Mail-Adresse</th><th>Status</th><th>Aktion</th></tr></thead><tbody>
|
||||
{% for rule in rules %}<tr><td>{{ rule[2] }}</td><td>{{ rule[3] }}</td><td><span class="state {{ 'ok' if rule[4] else 'warning' }}">{{ 'aktiv' if rule[4] else 'pausiert' }}</span></td><td class="rule-actions"><form method="post" action="{{ url_for('toggle_recipient', rule_id=rule[0]) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="button-secondary" type="submit">{{ 'Pausieren' if rule[4] else 'Aktivieren' }}</button></form><form method="post" action="{{ url_for('delete_recipient', rule_id=rule[0]) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="button-danger" type="submit">Loeschen</button></form></td></tr>{% else %}<tr><td colspan="4">Noch keine Empfaengerregeln angelegt.</td></tr>{% endfor %}
|
||||
</tbody></table></div></section>
|
||||
{% endblock %}
|
||||
8
infra/debug-dashboard/templates/reports.html
Normal file
8
infra/debug-dashboard/templates/reports.html
Normal file
@@ -0,0 +1,8 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Wochenberichte - OCSentinel Debug{% endblock %}
|
||||
{% block content %}
|
||||
<section class="hero compact"><p class="eyebrow">Archiv</p><h1>Wochenberichte</h1><p>Je Organisation automatisch durch n8n erzeugt.</p></section>
|
||||
<section class="panel"><div class="table-wrap"><table><thead><tr><th>Organisation</th><th>Zeitraum</th><th>Geraete</th><th>Warnung</th><th>Kritisch</th><th>Events</th><th>Erstellt</th></tr></thead><tbody>
|
||||
{% for row in reports %}<tr><td><a href="{{ url_for('weekly_report', report_id=row[0]) }}">{{ row[1] }}</a></td><td>{{ row[2] }} bis {{ row[3] }}</td><td>{{ row[5] }}</td><td>{{ row[6] }}</td><td>{{ row[7] }}</td><td>{{ row[8] }}</td><td>{{ row[4] }}</td></tr>{% else %}<tr><td colspan="7">Noch keine Wochenberichte erzeugt.</td></tr>{% endfor %}
|
||||
</tbody></table></div></section>
|
||||
{% endblock %}
|
||||
5
infra/debug-dashboard/templates/weekly_report.html
Normal file
5
infra/debug-dashboard/templates/weekly_report.html
Normal file
@@ -0,0 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}{{ report[0] }} - Wochenbericht{% endblock %}
|
||||
{% block content %}
|
||||
<section class="report-frame">{{ report[4] | safe }}</section>
|
||||
{% endblock %}
|
||||
92
infra/n8n/ocsentinel-weekly-organization-reports.json
Normal file
92
infra/n8n/ocsentinel-weekly-organization-reports.json
Normal file
@@ -0,0 +1,92 @@
|
||||
{
|
||||
"id": "OCwRpt7eK3mQ2xL9",
|
||||
"name": "OCSentinel - Weekly Organization Reports",
|
||||
"nodes": [
|
||||
{
|
||||
"parameters": { "rule": { "interval": [{ "field": "weeks", "weeksInterval": 1, "triggerAtDay": [1], "triggerAtHour": 7, "triggerAtMinute": 20 }] } },
|
||||
"id": "schedule-weekly-reports", "name": "Every Monday 07:20", "type": "n8n-nodes-base.scheduleTrigger", "typeVersion": 1.3, "position": [300, 300]
|
||||
},
|
||||
{
|
||||
"parameters": { "operation": "executeQuery", "query": "WITH latest AS (\n SELECT DISTINCT ON (d.id) d.machine_name, r.alert_state, r.payload\n FROM ocsentinel.scan_report AS r\n JOIN ocsentinel.device AS d ON d.id = r.device_id\n WHERE r.received_at >= now() - interval '8 days'\n ORDER BY d.id, r.generated_at_utc DESC, r.received_at DESC\n)\nSELECT machine_name, alert_state, payload\nFROM latest\nORDER BY payload #>> '{NinjaOne,OrganizationName}', machine_name;" },
|
||||
"id": "load-weekly-data", "name": "Load Latest Device Reports", "type": "n8n-nodes-base.postgres", "typeVersion": 2.5, "position": [560, 300],
|
||||
"credentials": { "postgres": { "id": "WkjY0kIF3kHvREys", "name": "OCSentinel PostgreSQL" } }
|
||||
},
|
||||
{
|
||||
"parameters": { "jsCode": "const esc=v=>String(v??'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/\\\"/g,'"').replace(/'/g,''');\nconst now=new Date(),end=new Date(Date.UTC(now.getUTCFullYear(),now.getUTCMonth(),now.getUTCDate()));\nend.setUTCDate(end.getUTCDate()-((end.getUTCDay()+6)%7)); const start=new Date(end-7*86400000);\nconst groups=new Map();\nfor(const item of items){const p=item.json.payload||{},n=p.NinjaOne||p.ninjaOne||{},id=String(n.OrganizationId||n.organizationId||'unknown'),name=String(n.OrganizationName||n.organizationName||`Organisation ${id}`);if(!groups.has(id))groups.set(id,{id,name,devices:[]});groups.get(id).devices.push({machine:item.json.machine_name||p.MachineName||'Unbekannt',state:String(item.json.alert_state||p.AlertState||'unknown').toLowerCase(),p});}\nconst result=[];\nfor(const group of groups.values()){let warnings=0,criticals=0,total=0,cveTotal=0,cveCritical=0;const ips=new Set(),alerts=[],clean=[];for(const d of group.devices){if(d.state==='warning')warnings++;if(d.state==='critical')criticals++;const vc=d.p.VulnerabilityCorrelation||{};cveTotal+=Number(vc.TotalCount||0);cveCritical+=Number(vc.CriticalCount||0);const events=(d.p.Events||[]).filter(e=>{const t=new Date(e.Timestamp);return !Number.isNaN(t)&&t>=start&&t<end;});total+=events.length;if(!events.length){clean.push(`<tr class=\"clean\"><td>${esc(d.machine)}</td><td>Keine</td><td>-</td><td>-</td><td>0</td><td>-</td><td>Log sauber / Keine Angriffe</td></tr>`);continue;}const rows=new Map();for(const e of events){const ip=e.SourceIp||'-',account=e.Username||'-',type=e.Target||'Sicherheitsereignis',key=[type,account,ip].join('|'),row=rows.get(key)||{ip,account,type,count:0,last:e.Timestamp};row.count++;if(new Date(e.Timestamp)>new Date(row.last))row.last=e.Timestamp;rows.set(key,row);if(ip!=='-')ips.add(ip);}for(const r of rows.values()){alerts.push(`<tr class=\"alert\"><td>${esc(d.machine)}</td><td>${esc(r.type)}</td><td>${esc(r.account)}</td><td>${esc(new Date(r.last).toLocaleString('de-DE',{timeZone:'Europe/Berlin'}))}</td><td>${r.count}</td><td>${esc(r.ip)}</td><td>${d.state==='critical'?'Problem entdeckt (kritisch)':'Problem entdeckt'}</td></tr>`);}}const summary={deviceCount:group.devices.length,warningCount:warnings,criticalCount:criticals,totalEvents:total,uniqueIps:ips.size,cveTotal,cveCritical};const html=`<div class=\"ocsentinel-report\"><style>.ocsentinel-report{font-family:Arial,sans-serif;font-size:12px;color:#1f2937;max-width:1200px}.ocsentinel-report h2{font-size:16px;color:#183b79;margin:0 0 5px;border-bottom:1px solid #183b79;padding-bottom:5px}.ocsentinel-report .meta{font-size:11px;color:#4b5563;margin-bottom:12px}.ocsentinel-report .summary{margin:10px 0;padding:8px;background:#eef5ff;border:1px solid #bfd4f2;color:#183b79}.ocsentinel-report table{width:100%;border-collapse:collapse}.ocsentinel-report th{background:#1f4a99;color:#fff;text-align:left;padding:6px;font-size:11px}.ocsentinel-report td{border:1px solid #e5e7eb;padding:6px;vertical-align:top}.ocsentinel-report tr.alert{background:#fff4ed;color:#8a3d16}.ocsentinel-report tr.clean{background:#effcf4;color:#17643a}.ocsentinel-report .footer{margin-top:10px;font-size:10px;color:#6b7280;text-align:right}</style><h2>OCSentinel - Konsolidierter Sicherheitsbericht</h2><div class=\"meta\"><strong>${esc(group.name)}</strong><br>Berichtszeitraum: ${start.toLocaleDateString('de-DE')} bis ${end.toLocaleDateString('de-DE')}<br>Erstellt am: ${now.toLocaleString('de-DE',{timeZone:'Europe/Berlin'})}</div><div class=\"summary\"><strong>${summary.deviceCount} Geräte</strong> | <strong>${summary.criticalCount} kritisch</strong> | <strong>${summary.warningCount} Warnungen</strong> | <strong>${summary.totalEvents} Ereignisse</strong> | <strong>${summary.uniqueIps} IPs</strong> | <strong>${summary.cveCritical} kritische CVEs</strong></div><table><thead><tr><th>Server</th><th>Vorfall-Typ</th><th>Betroffenes Konto</th><th>Letzter Zeitpunkt</th><th>Anzahl</th><th>Angreifer-IP</th><th>Status / Bemerkung</th></tr></thead><tbody>${alerts.join('')}${clean.join('')}</tbody></table><div class=\"footer\">Automatisch durch OCSentinel und n8n erzeugt.</div></div>`;result.push({json:{organizationId:group.id,organizationName:group.name,periodStartUtc:start.toISOString(),periodEndUtc:end.toISOString(),...summary,reportHtml:html,summaryJson:JSON.stringify(summary)}});}return result;" },
|
||||
"id": "build-weekly-reports", "name": "Build Organization HTML Reports", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [820, 300]
|
||||
},
|
||||
{
|
||||
"parameters": { "operation": "executeQuery", "query": "INSERT INTO ocsentinel.weekly_organization_report (organization_id, organization_name, period_start_utc, period_end_utc, device_count, warning_count, critical_count, total_events, unique_ips, cve_total, cve_critical, report_html, summary)\nVALUES ($1, $2, $3::timestamptz, $4::timestamptz, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb)\nON CONFLICT (organization_id, period_start_utc) DO UPDATE SET organization_name=EXCLUDED.organization_name, period_end_utc=EXCLUDED.period_end_utc, generated_at=now(), device_count=EXCLUDED.device_count, warning_count=EXCLUDED.warning_count, critical_count=EXCLUDED.critical_count, total_events=EXCLUDED.total_events, unique_ips=EXCLUDED.unique_ips, cve_total=EXCLUDED.cve_total, cve_critical=EXCLUDED.cve_critical, report_html=EXCLUDED.report_html, summary=EXCLUDED.summary\nRETURNING id;", "options": { "queryReplacement": "={{ [$json.organizationId, $json.organizationName, $json.periodStartUtc, $json.periodEndUtc, $json.deviceCount, $json.warningCount, $json.criticalCount, $json.totalEvents, $json.uniqueIps, $json.cveTotal, $json.cveCritical, $json.reportHtml, $json.summaryJson] }}" } },
|
||||
"id": "store-weekly-reports", "name": "Store Weekly Organization Reports", "type": "n8n-nodes-base.postgres", "typeVersion": 2.5, "position": [1080, 300],
|
||||
"credentials": { "postgres": { "id": "WkjY0kIF3kHvREys", "name": "OCSentinel PostgreSQL" } }
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"assignments": {
|
||||
"assignments": [
|
||||
{ "id": "email-enabled", "name": "emailEnabled", "value": true, "type": "boolean" }
|
||||
]
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
"id": "email-delivery-toggle",
|
||||
"name": "E-Mail-Versand aktiv",
|
||||
"type": "n8n-nodes-base.set",
|
||||
"typeVersion": 3.4,
|
||||
"position": [1330, 300]
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "SELECT coalesce(array_agg(recipient_email ORDER BY recipient_email), ARRAY[]::text[]) AS recipients\nFROM ocsentinel.organization_report_recipient\nWHERE enabled = TRUE AND (organization_id = '*' OR organization_id = $1);",
|
||||
"options": { "queryReplacement": "={{ [ $('Build Organization HTML Reports').item.json.organizationId ] }}" }
|
||||
},
|
||||
"id": "load-report-recipients",
|
||||
"name": "Empfaenger aus zentraler Zuordnung laden",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"typeVersion": 2.5,
|
||||
"position": [1560, 300]
|
||||
,"credentials": { "postgres": { "id": "WkjY0kIF3kHvREys", "name": "OCSentinel PostgreSQL" } }
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"jsCode": "const report = $('Build Organization HTML Reports').item.json;\nconst emailEnabled = $('E-Mail-Versand aktiv').item.json.emailEnabled === true;\nif (!emailEnabled) return [];\nconst recipients = Array.from(new Set($json.recipients || []));\nif (recipients.length === 0) throw new Error(`No weekly report recipients configured for ${report.organizationName}.`);\nreturn [{ json: { ...report, recipients } }];"
|
||||
},
|
||||
"id": "prepare-report-email",
|
||||
"name": "E-Mail vorbereiten",
|
||||
"type": "n8n-nodes-base.code",
|
||||
"typeVersion": 2,
|
||||
"position": [1800, 300]
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"fromEmail": "donotreply@officecom.biz",
|
||||
"toEmail": "={{ $json.recipients.join(', ') }}",
|
||||
"subject": "=OCSentinel Wochenbericht - {{ $json.organizationName }}",
|
||||
"html": "={{ $json.reportHtml }}",
|
||||
"options": { "appendAttribution": false }
|
||||
},
|
||||
"id": "send-weekly-report-email",
|
||||
"name": "Send Weekly Organization Report",
|
||||
"type": "n8n-nodes-base.emailSend",
|
||||
"typeVersion": 2.1,
|
||||
"position": [2040, 300],
|
||||
"credentials": { "smtp": { "id": "vafGYgYzM9SbxQbW", "name": "SMTP account" } }
|
||||
}
|
||||
],
|
||||
"connections": {
|
||||
"Every Monday 07:20": { "main": [[{ "node": "Load Latest Device Reports", "type": "main", "index": 0 }]] },
|
||||
"Load Latest Device Reports": { "main": [[{ "node": "Build Organization HTML Reports", "type": "main", "index": 0 }]] },
|
||||
"Build Organization HTML Reports": { "main": [[{ "node": "Store Weekly Organization Reports", "type": "main", "index": 0 }]] },
|
||||
"Store Weekly Organization Reports": { "main": [[{ "node": "E-Mail-Versand aktiv", "type": "main", "index": 0 }]] },
|
||||
"E-Mail-Versand aktiv": { "main": [[{ "node": "Empfaenger aus zentraler Zuordnung laden", "type": "main", "index": 0 }]] },
|
||||
"Empfaenger aus zentraler Zuordnung laden": { "main": [[{ "node": "E-Mail vorbereiten", "type": "main", "index": 0 }]] },
|
||||
"E-Mail vorbereiten": { "main": [[{ "node": "Send Weekly Organization Report", "type": "main", "index": 0 }]] }
|
||||
},
|
||||
"settings": { "executionOrder": "v1", "timezone": "Europe/Berlin" },
|
||||
"active": true,
|
||||
"pinData": {},
|
||||
"versionId": "af98f45b-192e-49c8-9a1e-e7b1fc7e00b2",
|
||||
"meta": { "templateCredsSetupCompleted": true },
|
||||
"tags": []
|
||||
}
|
||||
@@ -47,6 +47,28 @@ CREATE TABLE IF NOT EXISTS ocsentinel.ingest_nonce (
|
||||
CREATE INDEX IF NOT EXISTS ix_ocsentinel_ingest_nonce_expires
|
||||
ON ocsentinel.ingest_nonce (expires_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ocsentinel.weekly_organization_report (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
organization_id TEXT NOT NULL,
|
||||
organization_name TEXT NOT NULL,
|
||||
period_start_utc TIMESTAMPTZ NOT NULL,
|
||||
period_end_utc TIMESTAMPTZ NOT NULL,
|
||||
generated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
device_count INTEGER NOT NULL DEFAULT 0,
|
||||
warning_count INTEGER NOT NULL DEFAULT 0,
|
||||
critical_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_events INTEGER NOT NULL DEFAULT 0,
|
||||
unique_ips INTEGER NOT NULL DEFAULT 0,
|
||||
cve_total INTEGER NOT NULL DEFAULT 0,
|
||||
cve_critical INTEGER NOT NULL DEFAULT 0,
|
||||
report_html TEXT NOT NULL,
|
||||
summary JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
UNIQUE (organization_id, period_start_utc)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS ix_ocsentinel_weekly_report_organization_generated
|
||||
ON ocsentinel.weekly_organization_report (organization_id, generated_at DESC);
|
||||
|
||||
CREATE OR REPLACE VIEW ocsentinel.current_device_status AS
|
||||
SELECT DISTINCT ON (d.id)
|
||||
d.machine_name,
|
||||
|
||||
25
infra/postgres/002_organization_report_recipients.sql
Normal file
25
infra/postgres/002_organization_report_recipients.sql
Normal file
@@ -0,0 +1,25 @@
|
||||
-- Central recipient rules for OCSentinel weekly organization reports.
|
||||
-- The '*' organization ID applies to every organization.
|
||||
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ocsentinel.organization_report_recipient (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
organization_id TEXT NOT NULL,
|
||||
organization_name TEXT NOT NULL,
|
||||
recipient_email TEXT NOT NULL,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (organization_id, recipient_email)
|
||||
);
|
||||
|
||||
INSERT INTO ocsentinel.organization_report_recipient
|
||||
(organization_id, organization_name, recipient_email)
|
||||
VALUES
|
||||
('*', 'Alle Organisationen', 'lg@officecom.it'),
|
||||
('*', 'Alle Organisationen', 'rk@officecom.biz'),
|
||||
('9', 'Mildenberger Verlag', 'dd@officecom.it'),
|
||||
('16', 'Kirsch GmbH', 'dd@officecom.it')
|
||||
ON CONFLICT (organization_id, recipient_email) DO NOTHING;
|
||||
|
||||
COMMIT;
|
||||
@@ -124,6 +124,16 @@ function Publish-NinjaCustomFields {
|
||||
}
|
||||
}
|
||||
|
||||
$uploadStatus = [string]$Report.Runtime.UploadStatus
|
||||
if ([string]::IsNullOrWhiteSpace($uploadStatus)) { $uploadStatus = "unknown" }
|
||||
$queuedReports = [int]$Report.Runtime.QueuedReportCount
|
||||
$lastUploadUtc = ""
|
||||
if ($Report.Runtime.LastSuccessfulUploadUtc) {
|
||||
try { $lastUploadUtc = ([DateTimeOffset]$Report.Runtime.LastSuccessfulUploadUtc).ToUniversalTime().ToString("o") } catch { $lastUploadUtc = [string]$Report.Runtime.LastSuccessfulUploadUtc }
|
||||
}
|
||||
$lastUploadError = [string]$Report.Runtime.LastUploadError
|
||||
if ($lastUploadError.Length -gt 900) { $lastUploadError = $lastUploadError.Substring(0, 900) }
|
||||
|
||||
$fieldValues = @(
|
||||
[pscustomobject]@{ Name = "ocsentinelstatus"; Type = "Text"; Value = [string]$Report.AlertState }
|
||||
[pscustomobject]@{ Name = "ocsentinelreason"; Type = "Text"; Value = $Reason }
|
||||
@@ -135,6 +145,11 @@ function Publish-NinjaCustomFields {
|
||||
[pscustomobject]@{ Name = "ocsentinelmode"; Type = "Text"; Value = $Mode }
|
||||
[pscustomobject]@{ Name = "ocsentineltriggered"; Type = "Checkbox"; Value = $Triggered }
|
||||
[pscustomobject]@{ Name = "ocsentinellastscanutc"; Type = "DateTime"; Value = $generatedAtUtc }
|
||||
[pscustomobject]@{ Name = "ocsentineluploadstatus"; Type = "Text"; Value = $uploadStatus }
|
||||
[pscustomobject]@{ Name = "ocsentinelqueuedreports"; Type = "Integer"; Value = $queuedReports }
|
||||
[pscustomobject]@{ Name = "ocsentinellastuploadutc"; Type = "DateTime"; Value = $lastUploadUtc }
|
||||
[pscustomobject]@{ Name = "ocsentinellasterror"; Type = "Text"; Value = $lastUploadError }
|
||||
[pscustomobject]@{ Name = "ocsentinelclientversion"; Type = "Text"; Value = [string]$Report.ClientVersion }
|
||||
)
|
||||
|
||||
$updated = 0
|
||||
@@ -190,6 +205,8 @@ $events = [int]$report.TotalEvents
|
||||
$uniqueIps = [int]$report.UniqueIpCount
|
||||
$criticalCves = [int]$report.VulnerabilityCorrelation.CriticalCount
|
||||
$totalCves = [int]$report.VulnerabilityCorrelation.TotalCount
|
||||
$uploadStatus = [string]$report.Runtime.UploadStatus
|
||||
$queuedReports = [int]$report.Runtime.QueuedReportCount
|
||||
|
||||
$monitorTriggered = $false
|
||||
$monitorReason = ""
|
||||
@@ -225,6 +242,8 @@ Write-Host "Events: $events"
|
||||
Write-Host "Unique IPs: $uniqueIps"
|
||||
Write-Host "Critical/High CVEs: $criticalCves"
|
||||
Write-Host "Total CVEs: $totalCves"
|
||||
Write-Host "Upload status: $uploadStatus"
|
||||
Write-Host "Queued reports: $queuedReports"
|
||||
Write-Host "Report: $outputFullPath"
|
||||
Write-Host "Runner exit code: $runnerExitCode"
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet("daily", "burst")]
|
||||
[string]$Kind = "daily"
|
||||
[string]$Kind = "daily",
|
||||
[ValidateRange(15, 480)]
|
||||
[int]$BurstDurationMinutes = 120
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -25,9 +27,69 @@ function Get-NinjaBurstEnabled {
|
||||
return $false
|
||||
}
|
||||
|
||||
if ($Kind -eq "burst" -and -not (Get-NinjaBurstEnabled)) {
|
||||
function Get-NinjaValue {
|
||||
param([Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)][string]$Type)
|
||||
|
||||
try {
|
||||
if (Get-Command -Name "Get-NinjaProperty" -ErrorAction SilentlyContinue) {
|
||||
return Get-NinjaProperty -Name $Name -Type $Type
|
||||
}
|
||||
if (Get-Command -Name "Ninja-Property-Get" -ErrorAction SilentlyContinue) {
|
||||
return Ninja-Property-Get -Name $Name
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Could not read Ninja field '$Name': $($_.Exception.Message)"
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Set-NinjaValue {
|
||||
param([Parameter(Mandatory)][string]$Name, [AllowEmptyString()][string]$Value, [Parameter(Mandatory)][string]$Type)
|
||||
|
||||
try {
|
||||
if (Get-Command -Name "Set-NinjaProperty" -ErrorAction SilentlyContinue) {
|
||||
Set-NinjaProperty -Name $Name -Value $Value -Type $Type -Force | Out-Null
|
||||
return $true
|
||||
}
|
||||
if (Get-Command -Name "Ninja-Property-Set" -ErrorAction SilentlyContinue) {
|
||||
Ninja-Property-Set -Name $Name -Value $Value | Out-Null
|
||||
return $true
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Could not update Ninja field '$Name': $($_.Exception.Message)"
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
if ($Kind -eq "burst") {
|
||||
if (-not (Get-NinjaBurstEnabled)) {
|
||||
Set-NinjaValue -Name "ocsentinelburststatus" -Value "idle" -Type "Text" | Out-Null
|
||||
Write-Host "OfficeCom Sentinel burst check: disabled."
|
||||
exit 0
|
||||
}
|
||||
|
||||
$now = [DateTimeOffset]::UtcNow
|
||||
$untilValue = Get-NinjaValue -Name "ocsentinelburstuntilutc" -Type "DateTime"
|
||||
$until = $null
|
||||
if (-not [string]::IsNullOrWhiteSpace([string]$untilValue)) {
|
||||
try { $until = [DateTimeOffset]$untilValue } catch { Write-Warning "Burst end time is invalid and will be restarted." }
|
||||
}
|
||||
|
||||
if ($null -eq $until) {
|
||||
$until = $now.AddMinutes($BurstDurationMinutes)
|
||||
Set-NinjaValue -Name "ocsentinelburstuntilutc" -Value $until.ToString("o") -Type "DateTime" | Out-Null
|
||||
Write-Host "OfficeCom Sentinel burst window started until $($until.ToString('u'))."
|
||||
}
|
||||
elseif ($until -le $now) {
|
||||
Set-NinjaValue -Name "ocsentinelburst" -Value "false" -Type "Checkbox" | Out-Null
|
||||
Set-NinjaValue -Name "ocsentinelburststatus" -Value "completed" -Type "Text" | Out-Null
|
||||
Write-Host "OfficeCom Sentinel burst window completed and was disabled."
|
||||
exit 0
|
||||
}
|
||||
|
||||
Set-NinjaValue -Name "ocsentinelburststatus" -Value "active until $($until.ToUniversalTime().ToString('o'))" -Type "Text" | Out-Null
|
||||
}
|
||||
|
||||
$createdNew = $false
|
||||
@@ -39,7 +101,11 @@ try {
|
||||
}
|
||||
|
||||
Write-Host "OfficeCom Sentinel scheduled $Kind scan started."
|
||||
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $monitorScript -Mode status -UploadMode required -SecretPath $secretPath -SuppressTriggerExit
|
||||
$monitorArgs = @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $monitorScript, "-Mode", "status", "-UploadMode", "required", "-SecretPath", $secretPath, "-SuppressTriggerExit")
|
||||
if ($Kind -eq "burst") {
|
||||
$monitorArgs += @("-LookbackDays", "1", "-TopCount", "25")
|
||||
}
|
||||
& powershell.exe @monitorArgs
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
finally {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"channel": "stable",
|
||||
"version": "1.3.2",
|
||||
"publishedAtUtc": "2026-07-26T00:23:31.3024295Z",
|
||||
"artifactUrl": "https://gitea.officecom.cloud/officecom/oc-sentinel/releases/download/v1.3.2/OCSentinelClient-win-x64.zip",
|
||||
"sha256": "dbfedf0890176873cef8bc91b9f7a6d6c3c8382ffadc972324b9900bad1153cc",
|
||||
"version": "1.3.3",
|
||||
"publishedAtUtc": "2026-07-26T18:25:32.8762198Z",
|
||||
"artifactUrl": "https://gitea.officecom.cloud/officecom/oc-sentinel/releases/download/v1.3.3/OCSentinelClient-win-x64.zip",
|
||||
"sha256": "9bb2b2dc25c59bc6faf53ded6095667ac73640038cfd426a74f3bf6aca81bd86",
|
||||
"minUpdaterVersion": "1.0.0"
|
||||
}
|
||||
|
||||
@@ -124,6 +124,16 @@ function Publish-NinjaCustomFields {
|
||||
}
|
||||
}
|
||||
|
||||
$uploadStatus = [string]$Report.Runtime.UploadStatus
|
||||
if ([string]::IsNullOrWhiteSpace($uploadStatus)) { $uploadStatus = "unknown" }
|
||||
$queuedReports = [int]$Report.Runtime.QueuedReportCount
|
||||
$lastUploadUtc = ""
|
||||
if ($Report.Runtime.LastSuccessfulUploadUtc) {
|
||||
try { $lastUploadUtc = ([DateTimeOffset]$Report.Runtime.LastSuccessfulUploadUtc).ToUniversalTime().ToString("o") } catch { $lastUploadUtc = [string]$Report.Runtime.LastSuccessfulUploadUtc }
|
||||
}
|
||||
$lastUploadError = [string]$Report.Runtime.LastUploadError
|
||||
if ($lastUploadError.Length -gt 900) { $lastUploadError = $lastUploadError.Substring(0, 900) }
|
||||
|
||||
$fieldValues = @(
|
||||
[pscustomobject]@{ Name = "ocsentinelstatus"; Type = "Text"; Value = [string]$Report.AlertState }
|
||||
[pscustomobject]@{ Name = "ocsentinelreason"; Type = "Text"; Value = $Reason }
|
||||
@@ -135,6 +145,11 @@ function Publish-NinjaCustomFields {
|
||||
[pscustomobject]@{ Name = "ocsentinelmode"; Type = "Text"; Value = $Mode }
|
||||
[pscustomobject]@{ Name = "ocsentineltriggered"; Type = "Checkbox"; Value = $Triggered }
|
||||
[pscustomobject]@{ Name = "ocsentinellastscanutc"; Type = "DateTime"; Value = $generatedAtUtc }
|
||||
[pscustomobject]@{ Name = "ocsentineluploadstatus"; Type = "Text"; Value = $uploadStatus }
|
||||
[pscustomobject]@{ Name = "ocsentinelqueuedreports"; Type = "Integer"; Value = $queuedReports }
|
||||
[pscustomobject]@{ Name = "ocsentinellastuploadutc"; Type = "DateTime"; Value = $lastUploadUtc }
|
||||
[pscustomobject]@{ Name = "ocsentinellasterror"; Type = "Text"; Value = $lastUploadError }
|
||||
[pscustomobject]@{ Name = "ocsentinelclientversion"; Type = "Text"; Value = [string]$Report.ClientVersion }
|
||||
)
|
||||
|
||||
$updated = 0
|
||||
@@ -190,6 +205,8 @@ $events = [int]$report.TotalEvents
|
||||
$uniqueIps = [int]$report.UniqueIpCount
|
||||
$criticalCves = [int]$report.VulnerabilityCorrelation.CriticalCount
|
||||
$totalCves = [int]$report.VulnerabilityCorrelation.TotalCount
|
||||
$uploadStatus = [string]$report.Runtime.UploadStatus
|
||||
$queuedReports = [int]$report.Runtime.QueuedReportCount
|
||||
|
||||
$monitorTriggered = $false
|
||||
$monitorReason = ""
|
||||
@@ -225,6 +242,8 @@ Write-Host "Events: $events"
|
||||
Write-Host "Unique IPs: $uniqueIps"
|
||||
Write-Host "Critical/High CVEs: $criticalCves"
|
||||
Write-Host "Total CVEs: $totalCves"
|
||||
Write-Host "Upload status: $uploadStatus"
|
||||
Write-Host "Queued reports: $queuedReports"
|
||||
Write-Host "Report: $outputFullPath"
|
||||
Write-Host "Runner exit code: $runnerExitCode"
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet("daily", "burst")]
|
||||
[string]$Kind = "daily"
|
||||
[string]$Kind = "daily",
|
||||
[ValidateRange(15, 480)]
|
||||
[int]$BurstDurationMinutes = 120
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -25,9 +27,69 @@ function Get-NinjaBurstEnabled {
|
||||
return $false
|
||||
}
|
||||
|
||||
if ($Kind -eq "burst" -and -not (Get-NinjaBurstEnabled)) {
|
||||
function Get-NinjaValue {
|
||||
param([Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)][string]$Type)
|
||||
|
||||
try {
|
||||
if (Get-Command -Name "Get-NinjaProperty" -ErrorAction SilentlyContinue) {
|
||||
return Get-NinjaProperty -Name $Name -Type $Type
|
||||
}
|
||||
if (Get-Command -Name "Ninja-Property-Get" -ErrorAction SilentlyContinue) {
|
||||
return Ninja-Property-Get -Name $Name
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Could not read Ninja field '$Name': $($_.Exception.Message)"
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Set-NinjaValue {
|
||||
param([Parameter(Mandatory)][string]$Name, [AllowEmptyString()][string]$Value, [Parameter(Mandatory)][string]$Type)
|
||||
|
||||
try {
|
||||
if (Get-Command -Name "Set-NinjaProperty" -ErrorAction SilentlyContinue) {
|
||||
Set-NinjaProperty -Name $Name -Value $Value -Type $Type -Force | Out-Null
|
||||
return $true
|
||||
}
|
||||
if (Get-Command -Name "Ninja-Property-Set" -ErrorAction SilentlyContinue) {
|
||||
Ninja-Property-Set -Name $Name -Value $Value | Out-Null
|
||||
return $true
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Could not update Ninja field '$Name': $($_.Exception.Message)"
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
if ($Kind -eq "burst") {
|
||||
if (-not (Get-NinjaBurstEnabled)) {
|
||||
Set-NinjaValue -Name "ocsentinelburststatus" -Value "idle" -Type "Text" | Out-Null
|
||||
Write-Host "OfficeCom Sentinel burst check: disabled."
|
||||
exit 0
|
||||
}
|
||||
|
||||
$now = [DateTimeOffset]::UtcNow
|
||||
$untilValue = Get-NinjaValue -Name "ocsentinelburstuntilutc" -Type "DateTime"
|
||||
$until = $null
|
||||
if (-not [string]::IsNullOrWhiteSpace([string]$untilValue)) {
|
||||
try { $until = [DateTimeOffset]$untilValue } catch { Write-Warning "Burst end time is invalid and will be restarted." }
|
||||
}
|
||||
|
||||
if ($null -eq $until) {
|
||||
$until = $now.AddMinutes($BurstDurationMinutes)
|
||||
Set-NinjaValue -Name "ocsentinelburstuntilutc" -Value $until.ToString("o") -Type "DateTime" | Out-Null
|
||||
Write-Host "OfficeCom Sentinel burst window started until $($until.ToString('u'))."
|
||||
}
|
||||
elseif ($until -le $now) {
|
||||
Set-NinjaValue -Name "ocsentinelburst" -Value "false" -Type "Checkbox" | Out-Null
|
||||
Set-NinjaValue -Name "ocsentinelburststatus" -Value "completed" -Type "Text" | Out-Null
|
||||
Write-Host "OfficeCom Sentinel burst window completed and was disabled."
|
||||
exit 0
|
||||
}
|
||||
|
||||
Set-NinjaValue -Name "ocsentinelburststatus" -Value "active until $($until.ToUniversalTime().ToString('o'))" -Type "Text" | Out-Null
|
||||
}
|
||||
|
||||
$createdNew = $false
|
||||
@@ -39,7 +101,11 @@ try {
|
||||
}
|
||||
|
||||
Write-Host "OfficeCom Sentinel scheduled $Kind scan started."
|
||||
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $monitorScript -Mode status -UploadMode required -SecretPath $secretPath -SuppressTriggerExit
|
||||
$monitorArgs = @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $monitorScript, "-Mode", "status", "-UploadMode", "required", "-SecretPath", $secretPath, "-SuppressTriggerExit")
|
||||
if ($Kind -eq "burst") {
|
||||
$monitorArgs += @("-LookbackDays", "1", "-TopCount", "25")
|
||||
}
|
||||
& powershell.exe @monitorArgs
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
finally {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using OCSentinelCli.Configuration;
|
||||
using OCSentinelCli.Models;
|
||||
using System.Text.Json;
|
||||
using OCSentinelCli.Security;
|
||||
using OCSentinelCli.Transport;
|
||||
@@ -56,30 +57,52 @@ internal static class UploadCommand
|
||||
|
||||
string reportFullPath = Path.GetFullPath(reportPath);
|
||||
string json = File.ReadAllText(reportFullPath);
|
||||
string secret = ProtectedSecretStore.LoadSecret(resolvedSecretPath);
|
||||
var client = new N8nUploadClient();
|
||||
var queue = new UploadQueue(config.UploadQueueMaxReports);
|
||||
UploadHealth health = queue.LoadHealth();
|
||||
DateTimeOffset attemptTime = DateTimeOffset.UtcNow;
|
||||
ScanResult? parsedReport = JsonSerializer.Deserialize<ScanResult>(json, JsonOptions.Default);
|
||||
|
||||
if (parsedReport is not null)
|
||||
{
|
||||
parsedReport = parsedReport with
|
||||
{
|
||||
Runtime = parsedReport.Runtime with
|
||||
{
|
||||
UploadAttempted = true
|
||||
UploadAttempted = true,
|
||||
UploadStatus = "attempting",
|
||||
QueuedReportCount = health.QueuedReportCount,
|
||||
LastSuccessfulUploadUtc = health.LastSuccessfulUploadUtc
|
||||
}
|
||||
};
|
||||
|
||||
json = JsonSerializer.Serialize(parsedReport, JsonOptions.Default);
|
||||
File.WriteAllText(reportFullPath, json);
|
||||
}
|
||||
|
||||
string secret = ProtectedSecretStore.LoadSecret(resolvedSecretPath);
|
||||
var client = new N8nUploadClient();
|
||||
var result = client.UploadJson(config.N8nWebhookUrl, Environment.MachineName, BuildMetadata.Version, json, secret, config.UploadTimeoutSeconds);
|
||||
UploadResult? deferredFailure = queue.Drain(
|
||||
client,
|
||||
config.N8nWebhookUrl,
|
||||
Environment.MachineName,
|
||||
BuildMetadata.Version,
|
||||
secret,
|
||||
config.UploadTimeoutSeconds);
|
||||
|
||||
if (!result.Success)
|
||||
if (deferredFailure is null)
|
||||
{
|
||||
Console.Error.WriteLine($"Upload failed ({result.StatusCode}): {result.Message}");
|
||||
return 1;
|
||||
}
|
||||
var result = client.UploadJson(config.N8nWebhookUrl, Environment.MachineName, BuildMetadata.Version, json, secret, config.UploadTimeoutSeconds);
|
||||
if (result.Success)
|
||||
{
|
||||
UploadHealth successHealth = new()
|
||||
{
|
||||
LastUploadAttemptUtc = attemptTime,
|
||||
LastSuccessfulUploadUtc = DateTimeOffset.UtcNow,
|
||||
LastUploadStatus = "ok",
|
||||
LastUploadError = string.Empty,
|
||||
QueuedReportCount = queue.GetQueueDepth()
|
||||
};
|
||||
queue.SaveHealth(successHealth);
|
||||
WriteReportRuntime(reportFullPath, parsedReport, successHealth, true);
|
||||
|
||||
Console.WriteLine($"Upload succeeded ({result.StatusCode})");
|
||||
Console.WriteLine($"Nonce: {result.Nonce}");
|
||||
@@ -87,6 +110,50 @@ internal static class UploadCommand
|
||||
return 0;
|
||||
}
|
||||
|
||||
deferredFailure = result;
|
||||
}
|
||||
|
||||
UploadResult failure = deferredFailure ?? throw new InvalidOperationException("Upload failed without a result.");
|
||||
int queuedCount = queue.Enqueue(json);
|
||||
UploadHealth queuedHealth = new()
|
||||
{
|
||||
LastUploadAttemptUtc = attemptTime,
|
||||
LastSuccessfulUploadUtc = health.LastSuccessfulUploadUtc,
|
||||
LastUploadStatus = "queued",
|
||||
LastUploadError = failure.Message,
|
||||
QueuedReportCount = queuedCount
|
||||
};
|
||||
queue.SaveHealth(queuedHealth);
|
||||
WriteReportRuntime(reportFullPath, parsedReport, queuedHealth, true);
|
||||
|
||||
Console.WriteLine($"Upload deferred ({failure.StatusCode}): {failure.Message}");
|
||||
Console.WriteLine($"Queued reports: {queuedCount}");
|
||||
Console.WriteLine("The report will be retried automatically on the next scheduled run.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void WriteReportRuntime(string reportPath, ScanResult? report, UploadHealth health, bool attempted)
|
||||
{
|
||||
if (report is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ScanResult updated = report with
|
||||
{
|
||||
Runtime = report.Runtime with
|
||||
{
|
||||
UploadAttempted = attempted,
|
||||
UploadSucceeded = string.Equals(health.LastUploadStatus, "ok", StringComparison.Ordinal),
|
||||
UploadStatus = health.LastUploadStatus,
|
||||
QueuedReportCount = health.QueuedReportCount,
|
||||
LastSuccessfulUploadUtc = health.LastSuccessfulUploadUtc,
|
||||
LastUploadError = health.LastUploadError
|
||||
}
|
||||
};
|
||||
File.WriteAllText(reportPath, JsonSerializer.Serialize(updated, JsonOptions.Default));
|
||||
}
|
||||
|
||||
private static string ReadValue(string[] args, ref int index, string argName)
|
||||
{
|
||||
if (index + 1 >= args.Length)
|
||||
|
||||
@@ -18,6 +18,8 @@ internal sealed record ClientConfiguration
|
||||
|
||||
public int UploadTimeoutSeconds { get; init; } = 30;
|
||||
|
||||
public int UploadQueueMaxReports { get; init; } = 100;
|
||||
|
||||
public bool EnableVulnerabilityCorrelation { get; init; } = true;
|
||||
|
||||
public string VulnerabilityCsvPath { get; init; } = string.Empty;
|
||||
|
||||
@@ -136,6 +136,16 @@ internal sealed record ScanRuntimeMetadata
|
||||
public DateTimeOffset FinishedAtUtc { get; init; }
|
||||
|
||||
public bool UploadAttempted { get; init; }
|
||||
|
||||
public bool UploadSucceeded { get; init; }
|
||||
|
||||
public string UploadStatus { get; init; } = "not-attempted";
|
||||
|
||||
public int QueuedReportCount { get; init; }
|
||||
|
||||
public DateTimeOffset? LastSuccessfulUploadUtc { get; init; }
|
||||
|
||||
public string LastUploadError { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed record VulnerabilityFinding
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
<RootNamespace>OCSentinelCli</RootNamespace>
|
||||
<Product>OfficeCom Sentinel</Product>
|
||||
<Company>OfficeCom</Company>
|
||||
<Version>1.3.2</Version>
|
||||
<AssemblyVersion>1.3.2.0</AssemblyVersion>
|
||||
<FileVersion>1.3.2.0</FileVersion>
|
||||
<InformationalVersion>1.3.2</InformationalVersion>
|
||||
<Version>1.3.4</Version>
|
||||
<AssemblyVersion>1.3.4.0</AssemblyVersion>
|
||||
<FileVersion>1.3.4.0</FileVersion>
|
||||
<InformationalVersion>1.3.4</InformationalVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -38,6 +38,8 @@ internal sealed class N8nUploadClient
|
||||
request.Headers.Add("X-ATN-Payload-SHA256", payloadHash);
|
||||
request.Headers.Add("X-ATN-Signature", signature);
|
||||
|
||||
try
|
||||
{
|
||||
using HttpResponseMessage response = httpClient.Send(request);
|
||||
string responseText = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
|
||||
@@ -50,6 +52,18 @@ internal sealed class N8nUploadClient
|
||||
PayloadSha256 = payloadHash
|
||||
};
|
||||
}
|
||||
catch (Exception exception) when (exception is HttpRequestException or TaskCanceledException)
|
||||
{
|
||||
return new UploadResult
|
||||
{
|
||||
Success = false,
|
||||
StatusCode = 0,
|
||||
Message = exception.Message,
|
||||
Nonce = nonce,
|
||||
PayloadSha256 = payloadHash
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private static string ComputeSha256(string value)
|
||||
{
|
||||
|
||||
106
src/OCSentinelCli/Transport/UploadQueue.cs
Normal file
106
src/OCSentinelCli/Transport/UploadQueue.cs
Normal file
@@ -0,0 +1,106 @@
|
||||
using System.Text.Json;
|
||||
using OCSentinelCli.Models;
|
||||
|
||||
namespace OCSentinelCli.Transport;
|
||||
|
||||
internal sealed record UploadHealth
|
||||
{
|
||||
public DateTimeOffset? LastUploadAttemptUtc { get; init; }
|
||||
|
||||
public DateTimeOffset? LastSuccessfulUploadUtc { get; init; }
|
||||
|
||||
public string LastUploadStatus { get; init; } = "not-attempted";
|
||||
|
||||
public string LastUploadError { get; init; } = string.Empty;
|
||||
|
||||
public int QueuedReportCount { get; init; }
|
||||
}
|
||||
|
||||
internal sealed class UploadQueue
|
||||
{
|
||||
private readonly string queueDirectory;
|
||||
private readonly string healthPath;
|
||||
private readonly int maxReports;
|
||||
|
||||
public UploadQueue(int maxReports)
|
||||
{
|
||||
string root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "OCSentinel");
|
||||
queueDirectory = Path.Combine(root, "upload-queue");
|
||||
healthPath = Path.Combine(root, "state", "upload-health.json");
|
||||
this.maxReports = Math.Clamp(maxReports, 10, 500);
|
||||
}
|
||||
|
||||
public UploadHealth LoadHealth()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(healthPath))
|
||||
{
|
||||
return new UploadHealth { QueuedReportCount = GetQueueDepth() };
|
||||
}
|
||||
|
||||
UploadHealth? health = JsonSerializer.Deserialize<UploadHealth>(File.ReadAllText(healthPath), JsonOptions.Default);
|
||||
return (health ?? new UploadHealth()) with { QueuedReportCount = GetQueueDepth() };
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return new UploadHealth { QueuedReportCount = GetQueueDepth() };
|
||||
}
|
||||
}
|
||||
|
||||
public void SaveHealth(UploadHealth health)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(healthPath)!);
|
||||
WriteAtomically(healthPath, JsonSerializer.Serialize(health, JsonOptions.Default));
|
||||
}
|
||||
|
||||
public UploadResult? Drain(N8nUploadClient client, string webhookUrl, string machineName, string clientVersion, string secret, int timeoutSeconds)
|
||||
{
|
||||
foreach (string path in GetQueuedPaths())
|
||||
{
|
||||
string payload = File.ReadAllText(path);
|
||||
UploadResult result = client.UploadJson(webhookUrl, machineName, clientVersion, payload, secret, timeoutSeconds);
|
||||
if (!result.Success)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
File.Delete(path);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public int Enqueue(string payloadJson)
|
||||
{
|
||||
Directory.CreateDirectory(queueDirectory);
|
||||
string fileName = $"{DateTimeOffset.UtcNow:yyyyMMddHHmmssfff}-{Guid.NewGuid():N}.json";
|
||||
WriteAtomically(Path.Combine(queueDirectory, fileName), payloadJson);
|
||||
|
||||
foreach (string stalePath in GetQueuedPaths().Take(Math.Max(0, GetQueueDepth() - maxReports)))
|
||||
{
|
||||
File.Delete(stalePath);
|
||||
}
|
||||
|
||||
return GetQueueDepth();
|
||||
}
|
||||
|
||||
public int GetQueueDepth()
|
||||
{
|
||||
return Directory.Exists(queueDirectory) ? Directory.EnumerateFiles(queueDirectory, "*.json").Count() : 0;
|
||||
}
|
||||
|
||||
private IEnumerable<string> GetQueuedPaths()
|
||||
{
|
||||
return Directory.Exists(queueDirectory)
|
||||
? Directory.EnumerateFiles(queueDirectory, "*.json").OrderBy(static path => path, StringComparer.Ordinal)
|
||||
: Enumerable.Empty<string>();
|
||||
}
|
||||
|
||||
private static void WriteAtomically(string path, string content)
|
||||
{
|
||||
string temporaryPath = path + ".tmp";
|
||||
File.WriteAllText(temporaryPath, content);
|
||||
File.Move(temporaryPath, path, true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user