opsairlock 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- opsairlock/__init__.py +8 -0
- opsairlock/approval.py +213 -0
- opsairlock/audit_engine.py +319 -0
- opsairlock/cli.py +705 -0
- opsairlock/config.py +262 -0
- opsairlock/daemon.py +190 -0
- opsairlock/doctor.py +197 -0
- opsairlock/handover.py +90 -0
- opsairlock/mcp_server.py +296 -0
- opsairlock/sandbox.py +165 -0
- opsairlock/ttl.py +189 -0
- opsairlock/tunnel.py +83 -0
- opsairlock/warpgate_api.py +191 -0
- opsairlock/ws_codec.py +168 -0
- opsairlock-0.1.0.dist-info/METADATA +54 -0
- opsairlock-0.1.0.dist-info/RECORD +21 -0
- opsairlock-0.1.0.dist-info/WHEEL +5 -0
- opsairlock-0.1.0.dist-info/entry_points.txt +3 -0
- opsairlock-0.1.0.dist-info/licenses/LICENSE +91 -0
- opsairlock-0.1.0.dist-info/licenses/NOTICE +13 -0
- opsairlock-0.1.0.dist-info/top_level.txt +1 -0
opsairlock/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""OpsAirlock — Zero-Trust Access Airlock, OS Sandbox & Slack-First Control Plane."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
PRODUCT_NAME = "OpsAirlock"
|
|
5
|
+
PRODUCT_URL = "https://opsairlock.com"
|
|
6
|
+
DEFAULT_ROUTER_URL = "https://router.opsairlock.com"
|
|
7
|
+
HARDENING_SERVICE_URL = "https://github.com/wu00112238/n8n-production-hardening"
|
|
8
|
+
UPSTREAM_WARPGATE_IMAGE = "ghcr.io/warp-tech/warpgate:0.30.0"
|
opsairlock/approval.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Outbound-only Human-in-the-Loop (HITL) approval & pairing client for OpsAirlock Router."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
11
|
+
|
|
12
|
+
from . import DEFAULT_ROUTER_URL, __version__
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ApprovalClient:
|
|
16
|
+
"""Submits lightweight approval tickets to OpsAirlock Approval Router and polls verdict."""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
router_url: Optional[str] = None,
|
|
21
|
+
router_token: Optional[str] = None,
|
|
22
|
+
server_label: Optional[str] = None,
|
|
23
|
+
poll_interval: float = 2.0,
|
|
24
|
+
timeout_seconds: float = 120.0,
|
|
25
|
+
) -> None:
|
|
26
|
+
self.router_url = (
|
|
27
|
+
router_url if router_url is not None else os.environ.get("OPSAIRLOCK_ROUTER_URL", "")
|
|
28
|
+
).strip().rstrip("/")
|
|
29
|
+
self.router_token = (
|
|
30
|
+
router_token if router_token is not None else os.environ.get("OPSAIRLOCK_ROUTER_TOKEN", "")
|
|
31
|
+
).strip()
|
|
32
|
+
self.server_label = (server_label or os.environ.get("OPSAIRLOCK_TARGET", "prod-server")).strip()
|
|
33
|
+
self.poll_interval = poll_interval
|
|
34
|
+
self.timeout_seconds = timeout_seconds
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def is_configured(self) -> bool:
|
|
38
|
+
return bool(self.router_url and self.router_token)
|
|
39
|
+
|
|
40
|
+
def _request(
|
|
41
|
+
self,
|
|
42
|
+
method: str,
|
|
43
|
+
path: str,
|
|
44
|
+
payload: Optional[Dict[str, Any]] = None,
|
|
45
|
+
with_auth: bool = True,
|
|
46
|
+
) -> Dict[str, Any]:
|
|
47
|
+
url = f"{self.router_url}{path}"
|
|
48
|
+
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
|
49
|
+
headers: Dict[str, str] = {"Accept": "application/json", "User-Agent": f"OpsAirlock-CLI/{__version__}"}
|
|
50
|
+
if with_auth and self.router_token:
|
|
51
|
+
headers["Authorization"] = f"Bearer {self.router_token}"
|
|
52
|
+
if data is not None:
|
|
53
|
+
headers["Content-Type"] = "application/json"
|
|
54
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
55
|
+
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
56
|
+
raw = resp.read().decode("utf-8").strip()
|
|
57
|
+
return json.loads(raw) if raw else {}
|
|
58
|
+
|
|
59
|
+
def start_pairing(
|
|
60
|
+
self,
|
|
61
|
+
channel_type: str = "telegram",
|
|
62
|
+
on_pair_url: Optional[Callable[[Dict[str, Any]], None]] = None,
|
|
63
|
+
) -> Dict[str, Any]:
|
|
64
|
+
"""Initiate zero-ID pairing via clickable URL / QR page and poll for issued token."""
|
|
65
|
+
if not self.router_url:
|
|
66
|
+
self.router_url = DEFAULT_ROUTER_URL
|
|
67
|
+
started = self._request(
|
|
68
|
+
"POST",
|
|
69
|
+
"/api/v1/pair/start",
|
|
70
|
+
{"server_label": self.server_label, "channel_type": channel_type},
|
|
71
|
+
with_auth=False,
|
|
72
|
+
)
|
|
73
|
+
if on_pair_url is not None:
|
|
74
|
+
on_pair_url(started)
|
|
75
|
+
|
|
76
|
+
pair_code = started.get("pair_code")
|
|
77
|
+
if not pair_code:
|
|
78
|
+
raise RuntimeError("Router did not return a pair_code.")
|
|
79
|
+
|
|
80
|
+
deadline = time.monotonic() + self.timeout_seconds
|
|
81
|
+
while time.monotonic() < deadline:
|
|
82
|
+
state = self._request("GET", f"/api/v1/pair/{pair_code}", with_auth=False)
|
|
83
|
+
status = str(state.get("status", "PENDING")).upper()
|
|
84
|
+
if status == "COMPLETED" and state.get("token"):
|
|
85
|
+
return state
|
|
86
|
+
if status == "EXPIRED":
|
|
87
|
+
raise RuntimeError("Pairing code expired. Please run 'opsairlock connect' again.")
|
|
88
|
+
time.sleep(self.poll_interval)
|
|
89
|
+
raise TimeoutError("Pairing timed out waiting for Slack/Telegram confirmation.")
|
|
90
|
+
|
|
91
|
+
def request_approval(
|
|
92
|
+
self,
|
|
93
|
+
actor: str,
|
|
94
|
+
channel: str,
|
|
95
|
+
command: str,
|
|
96
|
+
rule_ids: List[str],
|
|
97
|
+
severity: str,
|
|
98
|
+
) -> Dict[str, Any]:
|
|
99
|
+
"""Request human approval for a high-risk command. Fails closed if router is absent or unreachable."""
|
|
100
|
+
if not self.is_configured:
|
|
101
|
+
return {
|
|
102
|
+
"verdict": "DENIED_NO_ROUTER",
|
|
103
|
+
"approved": False,
|
|
104
|
+
"reason": "Blocked by Fail-Closed policy (no OpsAirlock Approval Router connected).",
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
created = self._request(
|
|
109
|
+
"POST",
|
|
110
|
+
"/api/v1/approvals",
|
|
111
|
+
{
|
|
112
|
+
"server_label": self.server_label,
|
|
113
|
+
"actor": actor,
|
|
114
|
+
"channel": channel,
|
|
115
|
+
"command": command,
|
|
116
|
+
"rule_ids": rule_ids,
|
|
117
|
+
"severity": severity,
|
|
118
|
+
},
|
|
119
|
+
)
|
|
120
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
121
|
+
return {
|
|
122
|
+
"verdict": "DENIED_ROUTER_ERROR",
|
|
123
|
+
"approved": False,
|
|
124
|
+
"reason": f"Approval Router unreachable (Fail-Closed): {exc}",
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
req_id = created.get("request_id")
|
|
128
|
+
if not req_id:
|
|
129
|
+
return {
|
|
130
|
+
"verdict": "DENIED_ROUTER_ERROR",
|
|
131
|
+
"approved": False,
|
|
132
|
+
"reason": "Approval Router returned no request_id (Fail-Closed).",
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
deadline = time.monotonic() + self.timeout_seconds
|
|
136
|
+
while time.monotonic() < deadline:
|
|
137
|
+
try:
|
|
138
|
+
state = self._request("GET", f"/api/v1/approvals/{req_id}")
|
|
139
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
140
|
+
return {
|
|
141
|
+
"verdict": "DENIED_ROUTER_ERROR",
|
|
142
|
+
"approved": False,
|
|
143
|
+
"request_id": req_id,
|
|
144
|
+
"reason": f"Approval Router poll error (Fail-Closed): {exc}",
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
status = str(state.get("status", "PENDING")).upper()
|
|
148
|
+
if status == "APPROVED":
|
|
149
|
+
return {
|
|
150
|
+
"verdict": "APPROVED",
|
|
151
|
+
"approved": True,
|
|
152
|
+
"request_id": req_id,
|
|
153
|
+
"decided_by": state.get("decided_by"),
|
|
154
|
+
}
|
|
155
|
+
if status in ("DENIED", "EXPIRED"):
|
|
156
|
+
return {
|
|
157
|
+
"verdict": status,
|
|
158
|
+
"approved": False,
|
|
159
|
+
"request_id": req_id,
|
|
160
|
+
"decided_by": state.get("decided_by"),
|
|
161
|
+
"reason": f"Command {status.lower()} by server owner.",
|
|
162
|
+
}
|
|
163
|
+
time.sleep(self.poll_interval)
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
"verdict": "TIMED_OUT",
|
|
167
|
+
"approved": False,
|
|
168
|
+
"request_id": req_id,
|
|
169
|
+
"reason": f"Approval request {req_id} timed out after {int(self.timeout_seconds)}s (Fail-Closed).",
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
def send_digest(self, report: Dict[str, Any]) -> Dict[str, Any]:
|
|
173
|
+
"""Push sanitized audit digest metadata (zero raw stdout/secrets) to Approval Router."""
|
|
174
|
+
if not self.is_configured:
|
|
175
|
+
return {"sent": False, "reason": "No Approval Router connected."}
|
|
176
|
+
payload = {
|
|
177
|
+
"server_label": self.server_label,
|
|
178
|
+
"overall_status": report.get("overall_status", "GREEN"),
|
|
179
|
+
"summary": report.get("summary", {}),
|
|
180
|
+
"flagged_rules": sorted({f.get("rule_id", "") for f in report.get("findings", []) if f.get("rule_id")}),
|
|
181
|
+
"replay_urls": [s.get("replay_url", "") for s in report.get("sessions", []) if s.get("replay_url")][:5],
|
|
182
|
+
}
|
|
183
|
+
return self._request("POST", "/api/v1/digest", payload)
|
|
184
|
+
|
|
185
|
+
def poll_next_command(self) -> Optional[Dict[str, Any]]:
|
|
186
|
+
"""Poll next Slack-dispatched management command from Approval Router."""
|
|
187
|
+
if not self.is_configured:
|
|
188
|
+
return None
|
|
189
|
+
res = self._request("GET", "/api/v1/commands/next")
|
|
190
|
+
return res.get("command")
|
|
191
|
+
|
|
192
|
+
def post_command_result(self, cmd_id: str, status: str, result_text: str) -> Dict[str, Any]:
|
|
193
|
+
"""Return sanitized command execution result to Approval Router."""
|
|
194
|
+
return self._request(
|
|
195
|
+
"POST",
|
|
196
|
+
f"/api/v1/commands/{cmd_id}/result",
|
|
197
|
+
{"status": status, "result_text": result_text},
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
def poll_next_proxy_request(self) -> Optional[Dict[str, Any]]:
|
|
201
|
+
"""Poll next incoming subdomain HTTP request for zero-config Web SSH tunneling."""
|
|
202
|
+
if not self.is_configured:
|
|
203
|
+
return None
|
|
204
|
+
res = self._request("GET", "/api/v1/proxy/next")
|
|
205
|
+
return res.get("request")
|
|
206
|
+
|
|
207
|
+
def post_proxy_response(self, req_id: str, status: int, headers: Dict[str, str], body_b64: str) -> Dict[str, Any]:
|
|
208
|
+
"""Return local Warpgate HTTP response back through the zero-config subdomain tunnel."""
|
|
209
|
+
return self._request(
|
|
210
|
+
"POST",
|
|
211
|
+
f"/api/v1/proxy/{req_id}/response",
|
|
212
|
+
{"status": status, "headers": headers, "body_b64": body_b64},
|
|
213
|
+
)
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Unified Black-Box Audit Engine: risk rules, replay URLs, and AI Audit Digest."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
9
|
+
|
|
10
|
+
from .ttl import iso_utc, utc_now
|
|
11
|
+
|
|
12
|
+
RISK_RULES: List[Tuple[str, str, re.Pattern[str], str]] = [
|
|
13
|
+
# CRITICAL (RED)
|
|
14
|
+
(
|
|
15
|
+
"CRITICAL",
|
|
16
|
+
"SSH_KEY_TAMPER",
|
|
17
|
+
re.compile(
|
|
18
|
+
r"(authorized_keys|/etc/ssh/sshd_config|~/.ssh/|/root/\.ssh/)",
|
|
19
|
+
re.IGNORECASE,
|
|
20
|
+
),
|
|
21
|
+
"Attempted access or modification of SSH keys or sshd configuration.",
|
|
22
|
+
),
|
|
23
|
+
(
|
|
24
|
+
"CRITICAL",
|
|
25
|
+
"PERSISTENCE_INSTALL",
|
|
26
|
+
re.compile(
|
|
27
|
+
r"(\bcrontab\b|/etc/cron|/etc/systemd/system|systemctl\s+enable|>>\s*~/\.(bashrc|profile))",
|
|
28
|
+
re.IGNORECASE,
|
|
29
|
+
),
|
|
30
|
+
"Potential persistence mechanism installed (cron, systemd, or shell profile).",
|
|
31
|
+
),
|
|
32
|
+
(
|
|
33
|
+
"CRITICAL",
|
|
34
|
+
"PRIVILEGE_ESCALATION",
|
|
35
|
+
re.compile(
|
|
36
|
+
r"(\buseradd\b|\badduser\b|/etc/sudoers|\bvisudo\b|usermod\s+.*-aG\s+.*sudo|\bpasswd\s+root\b)",
|
|
37
|
+
re.IGNORECASE,
|
|
38
|
+
),
|
|
39
|
+
"Privilege escalation or new system account creation detected.",
|
|
40
|
+
),
|
|
41
|
+
(
|
|
42
|
+
"CRITICAL",
|
|
43
|
+
"DESTRUCTIVE_OPS",
|
|
44
|
+
re.compile(
|
|
45
|
+
r"(rm\s+-rf\s+/(\s|$|\*)|\bmkfs\b|\bdd\s+if=|DROP\s+DATABASE|TRUNCATE\s+TABLE)",
|
|
46
|
+
re.IGNORECASE,
|
|
47
|
+
),
|
|
48
|
+
"Destructive filesystem or database operation detected.",
|
|
49
|
+
),
|
|
50
|
+
# WARNING (YELLOW)
|
|
51
|
+
(
|
|
52
|
+
"WARNING",
|
|
53
|
+
"SECRET_ACCESS",
|
|
54
|
+
re.compile(
|
|
55
|
+
r"(\.env\b|id_rsa|id_ed25519|\bsecrets?\b|credentials|\.pem\b|\.key\b)",
|
|
56
|
+
re.IGNORECASE,
|
|
57
|
+
),
|
|
58
|
+
"Potential read or exposure of secret material or environment files.",
|
|
59
|
+
),
|
|
60
|
+
(
|
|
61
|
+
"WARNING",
|
|
62
|
+
"FIREWALL_NETWORK",
|
|
63
|
+
re.compile(
|
|
64
|
+
r"(\bufw\b|\biptables\b|\bnft\b|\bfirewall-cmd\b)",
|
|
65
|
+
re.IGNORECASE,
|
|
66
|
+
),
|
|
67
|
+
"Firewall or network policy modification detected.",
|
|
68
|
+
),
|
|
69
|
+
(
|
|
70
|
+
"WARNING",
|
|
71
|
+
"REMOTE_SCRIPT_EXEC",
|
|
72
|
+
re.compile(
|
|
73
|
+
r"((curl|wget)\s+[^|]+\|\s*(sh|bash|zsh|python3?))",
|
|
74
|
+
re.IGNORECASE,
|
|
75
|
+
),
|
|
76
|
+
"Downloaded remote script piped directly into an interpreter.",
|
|
77
|
+
),
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
AI_REVIEW_PROMPT = (
|
|
81
|
+
"You are an independent Linux security auditor. Review the OpsAirlock session "
|
|
82
|
+
"digest below from an external contractor or AI agent. Identify: (1) any unauthorized "
|
|
83
|
+
"persistence, SSH key changes, or secret exfiltration; (2) unexpected config edits; "
|
|
84
|
+
"and (3) concrete verification commands the server owner should run next."
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def classify_command(command: str) -> List[Dict[str, str]]:
|
|
89
|
+
"""Evaluate a shell command against all deterministic security rules."""
|
|
90
|
+
matches: List[Dict[str, str]] = []
|
|
91
|
+
for severity, rule_id, pattern, reason in RISK_RULES:
|
|
92
|
+
if pattern.search(command):
|
|
93
|
+
matches.append(
|
|
94
|
+
{
|
|
95
|
+
"severity": severity,
|
|
96
|
+
"rule_id": rule_id,
|
|
97
|
+
"reason": reason,
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
return matches
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def build_replay_url(base_url: str, session_id: str) -> str:
|
|
104
|
+
clean = base_url.rstrip("/")
|
|
105
|
+
return f"{clean}/@warpgate/admin#/sessions/{session_id}"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def load_mcp_jsonl(path: Path) -> List[Dict[str, Any]]:
|
|
109
|
+
"""Load local opsairlock-mcp JSONL entries if present."""
|
|
110
|
+
if not path.exists():
|
|
111
|
+
return []
|
|
112
|
+
entries: List[Dict[str, Any]] = []
|
|
113
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
114
|
+
line = line.strip()
|
|
115
|
+
if not line:
|
|
116
|
+
continue
|
|
117
|
+
try:
|
|
118
|
+
entries.append(json.loads(line))
|
|
119
|
+
except json.JSONDecodeError:
|
|
120
|
+
continue
|
|
121
|
+
return entries
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def build_audit_report(
|
|
125
|
+
sessions: List[Dict[str, Any]],
|
|
126
|
+
commands: List[Dict[str, Any]],
|
|
127
|
+
base_url: str = "https://localhost:8080",
|
|
128
|
+
mcp_entries: Optional[List[Dict[str, Any]]] = None,
|
|
129
|
+
user_filter: Optional[str] = None,
|
|
130
|
+
generated_at: Optional[str] = None,
|
|
131
|
+
) -> Dict[str, Any]:
|
|
132
|
+
"""Converge Warpgate sessions/commands and MCP JSONL logs into Golden I/O report."""
|
|
133
|
+
normalized_sessions: List[Dict[str, Any]] = []
|
|
134
|
+
session_cmd_counts: Dict[str, int] = {}
|
|
135
|
+
findings: List[Dict[str, Any]] = []
|
|
136
|
+
|
|
137
|
+
all_commands = list(commands)
|
|
138
|
+
if mcp_entries:
|
|
139
|
+
for entry in mcp_entries:
|
|
140
|
+
sid = entry.get("session_id") or f"mcp-{entry.get('audit_id', 'local')}"
|
|
141
|
+
all_commands.append(
|
|
142
|
+
{
|
|
143
|
+
"session_id": sid,
|
|
144
|
+
"actor": entry.get("actor", "agent-mcp"),
|
|
145
|
+
"channel": "AGENT_MCP",
|
|
146
|
+
"command": entry.get("command", ""),
|
|
147
|
+
"timestamp": entry.get("timestamp", ""),
|
|
148
|
+
}
|
|
149
|
+
)
|
|
150
|
+
if not any(s.get("session_id") == sid for s in sessions):
|
|
151
|
+
sessions = list(sessions) + [
|
|
152
|
+
{
|
|
153
|
+
"session_id": sid,
|
|
154
|
+
"actor": entry.get("actor", "agent-mcp"),
|
|
155
|
+
"channel": "AGENT_MCP",
|
|
156
|
+
"remote_ip": "mcp-bridge",
|
|
157
|
+
"started_at": entry.get("timestamp", ""),
|
|
158
|
+
"ended_at": entry.get("timestamp", ""),
|
|
159
|
+
}
|
|
160
|
+
]
|
|
161
|
+
|
|
162
|
+
filtered_commands = [
|
|
163
|
+
c for c in all_commands
|
|
164
|
+
if not user_filter or c.get("actor") == user_filter
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
for cmd_obj in filtered_commands:
|
|
168
|
+
sid = str(cmd_obj.get("session_id", "unknown"))
|
|
169
|
+
actor = str(cmd_obj.get("actor", "unknown"))
|
|
170
|
+
channel = str(cmd_obj.get("channel", "HUMAN_WEB_SSH"))
|
|
171
|
+
cmd_text = str(cmd_obj.get("command", ""))
|
|
172
|
+
ts = str(cmd_obj.get("timestamp", ""))
|
|
173
|
+
|
|
174
|
+
session_cmd_counts[sid] = session_cmd_counts.get(sid, 0) + 1
|
|
175
|
+
replay_url = build_replay_url(base_url, sid)
|
|
176
|
+
|
|
177
|
+
for hit in classify_command(cmd_text):
|
|
178
|
+
findings.append(
|
|
179
|
+
{
|
|
180
|
+
"severity": hit["severity"],
|
|
181
|
+
"rule_id": hit["rule_id"],
|
|
182
|
+
"reason": hit["reason"],
|
|
183
|
+
"session_id": sid,
|
|
184
|
+
"actor": actor,
|
|
185
|
+
"channel": channel,
|
|
186
|
+
"command": cmd_text,
|
|
187
|
+
"timestamp": ts,
|
|
188
|
+
"replay_url": replay_url,
|
|
189
|
+
}
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
for sess in sessions:
|
|
193
|
+
actor = str(sess.get("actor", "unknown"))
|
|
194
|
+
if user_filter and actor != user_filter:
|
|
195
|
+
continue
|
|
196
|
+
sid = str(sess.get("session_id", "unknown"))
|
|
197
|
+
normalized_sessions.append(
|
|
198
|
+
{
|
|
199
|
+
"session_id": sid,
|
|
200
|
+
"actor": actor,
|
|
201
|
+
"channel": str(sess.get("channel", "HUMAN_WEB_SSH")),
|
|
202
|
+
"remote_ip": str(sess.get("remote_ip", "unknown")),
|
|
203
|
+
"started_at": str(sess.get("started_at", "")),
|
|
204
|
+
"ended_at": sess.get("ended_at"),
|
|
205
|
+
"command_count": session_cmd_counts.get(sid, 0),
|
|
206
|
+
"replay_url": build_replay_url(base_url, sid),
|
|
207
|
+
}
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
critical_count = sum(1 for f in findings if f["severity"] == "CRITICAL")
|
|
211
|
+
warning_count = sum(1 for f in findings if f["severity"] == "WARNING")
|
|
212
|
+
|
|
213
|
+
if critical_count > 0:
|
|
214
|
+
overall_status = "RED"
|
|
215
|
+
elif warning_count > 0:
|
|
216
|
+
overall_status = "YELLOW"
|
|
217
|
+
else:
|
|
218
|
+
overall_status = "GREEN"
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
"generated_at": generated_at or iso_utc(utc_now()),
|
|
222
|
+
"overall_status": overall_status,
|
|
223
|
+
"summary": {
|
|
224
|
+
"total_sessions": len(normalized_sessions),
|
|
225
|
+
"total_commands": len(filtered_commands),
|
|
226
|
+
"critical_count": critical_count,
|
|
227
|
+
"warning_count": warning_count,
|
|
228
|
+
},
|
|
229
|
+
"findings": findings,
|
|
230
|
+
"sessions": normalized_sessions,
|
|
231
|
+
"ai_review_prompt": AI_REVIEW_PROMPT,
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def render_terminal(report: Dict[str, Any]) -> str:
|
|
236
|
+
"""Render 3-second scannable terminal report."""
|
|
237
|
+
status = report["overall_status"]
|
|
238
|
+
badge = {"RED": "[RED - CRITICAL]", "YELLOW": "[YELLOW - WARNING]", "GREEN": "[GREEN - CLEAN]"}[status]
|
|
239
|
+
s = report["summary"]
|
|
240
|
+
lines = [
|
|
241
|
+
f"=== OpsAirlock Audit Report {badge} ===",
|
|
242
|
+
f"Generated : {report['generated_at']}",
|
|
243
|
+
f"Sessions : {s['total_sessions']} | Commands: {s['total_commands']} | "
|
|
244
|
+
f"Critical: {s['critical_count']} | Warnings: {s['warning_count']}",
|
|
245
|
+
"",
|
|
246
|
+
]
|
|
247
|
+
if report["findings"]:
|
|
248
|
+
lines.append("Risk Findings:")
|
|
249
|
+
for f in report["findings"]:
|
|
250
|
+
lines.append(
|
|
251
|
+
f" [{f['severity']}] {f['rule_id']} ({f['actor']} via {f['channel']})"
|
|
252
|
+
)
|
|
253
|
+
lines.append(f" cmd : {f['command']}")
|
|
254
|
+
lines.append(f" replay : {f['replay_url']}")
|
|
255
|
+
else:
|
|
256
|
+
lines.append("Risk Findings: None detected.")
|
|
257
|
+
|
|
258
|
+
if report["sessions"]:
|
|
259
|
+
lines.append("")
|
|
260
|
+
lines.append("Recent Sessions:")
|
|
261
|
+
for sess in report["sessions"]:
|
|
262
|
+
lines.append(
|
|
263
|
+
f" - {sess['session_id']} | {sess['actor']} ({sess['channel']}) "
|
|
264
|
+
f"| IP: {sess['remote_ip']} | cmds: {sess['command_count']}"
|
|
265
|
+
)
|
|
266
|
+
lines.append(f" replay : {sess['replay_url']}")
|
|
267
|
+
base_url = ""
|
|
268
|
+
if report["sessions"]:
|
|
269
|
+
base_url = report["sessions"][0]["replay_url"].split("/@warpgate/admin")[0]
|
|
270
|
+
if base_url:
|
|
271
|
+
lines.append("")
|
|
272
|
+
lines.append(f"Full Command Log : {base_url}/@warpgate/admin#/log")
|
|
273
|
+
lines.append(f"All Video Replays: {base_url}/@warpgate/admin#/sessions")
|
|
274
|
+
return "\n".join(lines)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def render_markdown(report: Dict[str, Any]) -> str:
|
|
278
|
+
"""Render token-efficient AI Audit Digest in Markdown."""
|
|
279
|
+
s = report["summary"]
|
|
280
|
+
lines = [
|
|
281
|
+
f"# OpsAirlock AI Audit Digest ({report['overall_status']})",
|
|
282
|
+
"",
|
|
283
|
+
f"> **AI Reviewer Prompt**: {report['ai_review_prompt']}",
|
|
284
|
+
"",
|
|
285
|
+
f"- **Generated (UTC)**: `{report['generated_at']}`",
|
|
286
|
+
f"- **Overall Risk**: `{report['overall_status']}`",
|
|
287
|
+
f"- **Totals**: {s['total_sessions']} sessions, {s['total_commands']} commands, "
|
|
288
|
+
f"{s['critical_count']} critical, {s['warning_count']} warnings",
|
|
289
|
+
"",
|
|
290
|
+
"## Flagged Commands",
|
|
291
|
+
]
|
|
292
|
+
if report["findings"]:
|
|
293
|
+
lines.append("| Severity | Rule | Actor | Channel | Command | Replay |")
|
|
294
|
+
lines.append("| :--- | :--- | :--- | :--- | :--- | :--- |")
|
|
295
|
+
for f in report["findings"]:
|
|
296
|
+
safe_cmd = f["command"].replace("|", "\\|")
|
|
297
|
+
lines.append(
|
|
298
|
+
f"| **{f['severity']}** | `{f['rule_id']}` | `{f['actor']}` | "
|
|
299
|
+
f"`{f['channel']}` | `{safe_cmd}` | [Replay]({f['replay_url']}) |"
|
|
300
|
+
)
|
|
301
|
+
else:
|
|
302
|
+
lines.append("No critical or warning commands detected.")
|
|
303
|
+
|
|
304
|
+
lines.extend(["", "## Sessions"])
|
|
305
|
+
if report["sessions"]:
|
|
306
|
+
lines.append("| Session | Actor | Channel | Source IP | Commands | Replay |")
|
|
307
|
+
lines.append("| :--- | :--- | :--- | :--- | :--- | :--- |")
|
|
308
|
+
for sess in report["sessions"]:
|
|
309
|
+
lines.append(
|
|
310
|
+
f"| `{sess['session_id']}` | `{sess['actor']}` | `{sess['channel']}` | "
|
|
311
|
+
f"`{sess['remote_ip']}` | {sess['command_count']} | [Replay]({sess['replay_url']}) |"
|
|
312
|
+
)
|
|
313
|
+
else:
|
|
314
|
+
lines.append("No sessions recorded in this window.")
|
|
315
|
+
return "\n".join(lines) + "\n"
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def render_json(report: Dict[str, Any]) -> str:
|
|
319
|
+
return json.dumps(report, indent=2) + "\n"
|