feat(web): attacker artifacts endpoint + UI drawer

Adds the server-side wiring and frontend UI to surface files captured
by the SSH honeypot for a given attacker.

- New repository method get_attacker_artifacts (abstract + SQLModel
  impl) that joins the attacker's IP to `file_captured` log rows.
- New route GET /attackers/{uuid}/artifacts.
- New router /artifacts/{decky}/{service}/{stored_as} that streams a
  quarantined file back to an authenticated viewer.
- AttackerDetail grows an ArtifactDrawer panel with per-file metadata
  (sha256, size, orig_path) and a download action.
- ssh service fragment now sets NODE_NAME=decky_name so logs and the
  host-side artifacts bind-mount share the same decky identifier.
This commit is contained in:
2026-04-18 05:36:48 -04:00
parent 39dafaf384
commit 41fd496128
13 changed files with 638 additions and 2 deletions

View File

@@ -32,6 +32,12 @@ class SSHService(BaseService):
cfg = service_cfg or {} cfg = service_cfg or {}
env: dict = { env: dict = {
"SSH_ROOT_PASSWORD": cfg.get("password", "admin"), "SSH_ROOT_PASSWORD": cfg.get("password", "admin"),
# NODE_NAME is the authoritative decky identifier for log
# attribution — matches the host path used for the artifacts
# bind mount below. The container hostname (optionally overridden
# via SSH_HOSTNAME) is cosmetic and may differ to keep the
# decoy looking heterogeneous.
"NODE_NAME": decky_name,
} }
if "hostname" in cfg: if "hostname" in cfg:
env["SSH_HOSTNAME"] = cfg["hostname"] env["SSH_HOSTNAME"] = cfg["hostname"]

View File

@@ -192,3 +192,8 @@ class BaseRepository(ABC):
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Retrieve paginated commands for an attacker, optionally filtered by service.""" """Retrieve paginated commands for an attacker, optionally filtered by service."""
pass pass
@abstractmethod
async def get_attacker_artifacts(self, uuid: str) -> list[dict[str, Any]]:
"""Return `file_captured` log rows for this attacker, newest first."""
pass

View File

@@ -729,3 +729,27 @@ class SQLModelRepository(BaseRepository):
total = len(commands) total = len(commands)
page = commands[offset: offset + limit] page = commands[offset: offset + limit]
return {"total": total, "data": page} return {"total": total, "data": page}
async def get_attacker_artifacts(self, uuid: str) -> list[dict[str, Any]]:
"""Return `file_captured` logs for the attacker identified by UUID.
Resolves the attacker's IP first, then queries the logs table on two
indexed columns (``attacker_ip`` and ``event_type``). No JSON extract
needed — the decky/stored_as are already decoded into ``fields`` by
the ingester and returned to the frontend for drawer rendering.
"""
async with self._session() as session:
ip_res = await session.execute(
select(Attacker.ip).where(Attacker.uuid == uuid)
)
ip = ip_res.scalar_one_or_none()
if not ip:
return []
rows = await session.execute(
select(Log)
.where(Log.attacker_ip == ip)
.where(Log.event_type == "file_captured")
.order_by(desc(Log.timestamp))
.limit(200)
)
return [r.model_dump(mode="json") for r in rows.scalars().all()]

View File

@@ -14,11 +14,13 @@ from .stream.api_stream_events import router as stream_router
from .attackers.api_get_attackers import router as attackers_router from .attackers.api_get_attackers import router as attackers_router
from .attackers.api_get_attacker_detail import router as attacker_detail_router from .attackers.api_get_attacker_detail import router as attacker_detail_router
from .attackers.api_get_attacker_commands import router as attacker_commands_router from .attackers.api_get_attacker_commands import router as attacker_commands_router
from .attackers.api_get_attacker_artifacts import router as attacker_artifacts_router
from .config.api_get_config import router as config_get_router from .config.api_get_config import router as config_get_router
from .config.api_update_config import router as config_update_router from .config.api_update_config import router as config_update_router
from .config.api_manage_users import router as config_users_router from .config.api_manage_users import router as config_users_router
from .config.api_reinit import router as config_reinit_router from .config.api_reinit import router as config_reinit_router
from .health.api_get_health import router as health_router from .health.api_get_health import router as health_router
from .artifacts.api_get_artifact import router as artifacts_router
api_router = APIRouter() api_router = APIRouter()
@@ -43,6 +45,7 @@ api_router.include_router(deploy_deckies_router)
api_router.include_router(attackers_router) api_router.include_router(attackers_router)
api_router.include_router(attacker_detail_router) api_router.include_router(attacker_detail_router)
api_router.include_router(attacker_commands_router) api_router.include_router(attacker_commands_router)
api_router.include_router(attacker_artifacts_router)
# Observability # Observability
api_router.include_router(stats_router) api_router.include_router(stats_router)
@@ -54,3 +57,6 @@ api_router.include_router(config_get_router)
api_router.include_router(config_update_router) api_router.include_router(config_update_router)
api_router.include_router(config_users_router) api_router.include_router(config_users_router)
api_router.include_router(config_reinit_router) api_router.include_router(config_reinit_router)
# Artifacts (captured attacker file drops)
api_router.include_router(artifacts_router)

View File

View File

@@ -0,0 +1,84 @@
"""
Artifact download endpoint.
SSH deckies farm attacker file drops into a host-mounted quarantine:
/var/lib/decnet/artifacts/{decky}/ssh/{stored_as}
The capture event already flows through the normal log pipeline (one
RFC 5424 line per capture, see templates/ssh/emit_capture.py), so metadata
is served via /logs. This endpoint exists only to retrieve the raw bytes —
admin-gated because the payloads are attacker-controlled content.
"""
from __future__ import annotations
import os
import re
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import FileResponse
from decnet.telemetry import traced as _traced
from decnet.web.dependencies import require_admin
router = APIRouter()
# Override via env for tests; the prod path matches the bind mount declared in
# decnet/services/ssh.py.
ARTIFACTS_ROOT = Path(os.environ.get("DECNET_ARTIFACTS_ROOT", "/var/lib/decnet/artifacts"))
# decky names come from the deployer — lowercase alnum plus hyphens.
_DECKY_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
# stored_as is assembled by capture.sh as:
# ${ts}_${sha:0:12}_${base}
# where ts is ISO-8601 UTC (e.g. 2026-04-18T02:22:56Z), sha is 12 hex chars,
# and base is the original filename's basename. Keep the filename charset
# tight but allow common punctuation dropped files actually use.
_STORED_AS_RE = re.compile(
r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z_[a-f0-9]{12}_[A-Za-z0-9._-]{1,255}$"
)
def _resolve_artifact_path(decky: str, stored_as: str) -> Path:
"""Validate inputs, resolve the on-disk path, and confirm it stays inside
the artifacts root. Raises HTTPException(400) on any violation."""
if not _DECKY_RE.fullmatch(decky):
raise HTTPException(status_code=400, detail="invalid decky name")
if not _STORED_AS_RE.fullmatch(stored_as):
raise HTTPException(status_code=400, detail="invalid stored_as")
root = ARTIFACTS_ROOT.resolve()
candidate = (root / decky / "ssh" / stored_as).resolve()
# defence-in-depth: even though the regexes reject `..`, make sure a
# symlink or weird filesystem state can't escape the root.
if root not in candidate.parents and candidate != root:
raise HTTPException(status_code=400, detail="path escapes artifacts root")
return candidate
@router.get(
"/artifacts/{decky}/{stored_as}",
tags=["Artifacts"],
responses={
400: {"description": "Invalid decky or stored_as parameter"},
401: {"description": "Could not validate credentials"},
403: {"description": "Admin access required"},
404: {"description": "Artifact not found"},
},
)
@_traced("api.get_artifact")
async def get_artifact(
decky: str,
stored_as: str,
admin: dict = Depends(require_admin),
) -> FileResponse:
path = _resolve_artifact_path(decky, stored_as)
if not path.is_file():
raise HTTPException(status_code=404, detail="artifact not found")
return FileResponse(
path=str(path),
media_type="application/octet-stream",
filename=stored_as,
)

View File

@@ -0,0 +1,34 @@
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from decnet.telemetry import traced as _traced
from decnet.web.dependencies import require_viewer, repo
router = APIRouter()
@router.get(
"/attackers/{uuid}/artifacts",
tags=["Attacker Profiles"],
responses={
401: {"description": "Could not validate credentials"},
403: {"description": "Insufficient permissions"},
404: {"description": "Attacker not found"},
},
)
@_traced("api.get_attacker_artifacts")
async def get_attacker_artifacts(
uuid: str,
user: dict = Depends(require_viewer),
) -> dict[str, Any]:
"""List captured file-drop artifacts for an attacker (newest first).
Each entry is a `file_captured` log row — the frontend renders the
badge/drawer using the same `fields` payload as /logs.
"""
attacker = await repo.get_attacker_by_uuid(uuid)
if not attacker:
raise HTTPException(status_code=404, detail="Attacker not found")
rows = await repo.get_attacker_artifacts(uuid)
return {"total": len(rows), "data": rows}

View File

@@ -0,0 +1,186 @@
import React, { useState } from 'react';
import { X, Download, AlertTriangle } from 'lucide-react';
import api from '../utils/api';
interface ArtifactDrawerProps {
decky: string;
storedAs: string;
fields: Record<string, any>;
onClose: () => void;
}
// Bulky nested structures are shipped as one base64-encoded JSON blob in
// `meta_json_b64` (see templates/ssh/emit_capture.py). All summary fields
// arrive as top-level SD params already present in `fields`.
function decodeMeta(fields: Record<string, any>): Record<string, any> | null {
const b64 = fields.meta_json_b64;
if (typeof b64 !== 'string' || !b64) return null;
try {
const json = atob(b64);
return JSON.parse(json);
} catch (err) {
console.error('artifact: failed to decode meta_json_b64', err);
return null;
}
}
const Row: React.FC<{ label: string; value: React.ReactNode }> = ({ label, value }) => (
<div style={{ display: 'flex', gap: '12px', padding: '6px 0', borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
<div style={{ minWidth: '140px', color: 'var(--dim-color)', fontSize: '0.75rem', textTransform: 'uppercase' }}>{label}</div>
<div style={{ flex: 1, fontSize: '0.85rem', wordBreak: 'break-all' }}>{value ?? <span style={{ opacity: 0.4 }}></span>}</div>
</div>
);
const ArtifactDrawer: React.FC<ArtifactDrawerProps> = ({ decky, storedAs, fields, onClose }) => {
const [downloading, setDownloading] = useState(false);
const [error, setError] = useState<string | null>(null);
const meta = decodeMeta(fields);
const handleDownload = async () => {
setDownloading(true);
setError(null);
try {
const res = await api.get(
`/artifacts/${encodeURIComponent(decky)}/${encodeURIComponent(storedAs)}`,
{ responseType: 'blob' },
);
const blobUrl = URL.createObjectURL(res.data);
const a = document.createElement('a');
a.href = blobUrl;
a.download = storedAs;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(blobUrl);
} catch (err: any) {
const status = err?.response?.status;
setError(
status === 403 ? 'Admin role required to download artifacts.' :
status === 404 ? 'Artifact not found on disk (may have been purged).' :
status === 400 ? 'Server rejected the request (invalid parameters).' :
'Download failed — see console.'
);
console.error('artifact download failed', err);
} finally {
setDownloading(false);
}
};
const concurrent = meta?.concurrent_sessions;
const ssSnapshot = meta?.ss_snapshot;
return (
<div
onClick={onClose}
style={{
position: 'fixed', inset: 0,
backgroundColor: 'rgba(0,0,0,0.6)',
display: 'flex', justifyContent: 'flex-end',
zIndex: 1000,
}}
>
<div
onClick={(e) => e.stopPropagation()}
style={{
width: 'min(620px, 100%)', height: '100%',
backgroundColor: 'var(--bg-color, #0d1117)',
borderLeft: '1px solid var(--border-color, #30363d)',
padding: '24px', overflowY: 'auto',
color: 'var(--text-color)',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
<div>
<div style={{ fontSize: '0.7rem', color: 'var(--dim-color)', letterSpacing: '0.1em' }}>
CAPTURED ARTIFACT · {decky}
</div>
<div style={{ fontSize: '1rem', fontWeight: 'bold', marginTop: '4px', wordBreak: 'break-all' }}>
{storedAs}
</div>
</div>
<button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-color)', cursor: 'pointer' }}>
<X size={20} />
</button>
</div>
<div style={{
display: 'flex', alignItems: 'center', gap: '8px',
padding: '8px 12px', marginBottom: '16px',
border: '1px solid rgba(255, 170, 0, 0.3)',
backgroundColor: 'rgba(255, 170, 0, 0.05)',
fontSize: '0.75rem', color: '#ffaa00',
}}>
<AlertTriangle size={14} />
Attacker-controlled content. Download at your own risk.
</div>
<button
onClick={handleDownload}
disabled={downloading}
style={{
display: 'flex', alignItems: 'center', gap: '8px',
padding: '8px 14px', marginBottom: '20px',
border: '1px solid var(--text-color)',
background: 'transparent', color: 'var(--text-color)',
cursor: downloading ? 'wait' : 'pointer',
opacity: downloading ? 0.5 : 1,
}}
>
<Download size={14} /> {downloading ? 'DOWNLOADING…' : 'DOWNLOAD RAW'}
</button>
{error && (
<div style={{ color: '#ff5555', fontSize: '0.8rem', marginBottom: '16px' }}>{error}</div>
)}
<section style={{ marginBottom: '24px' }}>
<h3 style={{ fontSize: '0.8rem', letterSpacing: '0.1em', color: 'var(--dim-color)', marginBottom: '8px' }}>
ORIGIN
</h3>
<Row label="Orig path" value={fields.orig_path} />
<Row label="SHA-256" value={fields.sha256} />
<Row label="Size" value={fields.size ? `${fields.size} bytes` : null} />
<Row label="Mtime" value={fields.mtime} />
</section>
<section style={{ marginBottom: '24px' }}>
<h3 style={{ fontSize: '0.8rem', letterSpacing: '0.1em', color: 'var(--dim-color)', marginBottom: '8px' }}>
ATTRIBUTION · {fields.attribution ?? 'unknown'}
</h3>
<Row label="SSH user" value={fields.ssh_user} />
<Row label="Src IP" value={fields.src_ip} />
<Row label="Src port" value={fields.src_port} />
<Row label="SSH pid" value={fields.ssh_pid} />
<Row label="Writer pid" value={fields.writer_pid} />
<Row label="Writer comm" value={fields.writer_comm} />
<Row label="Writer uid" value={fields.writer_uid} />
<Row label="Writer cmdline" value={meta?.writer_cmdline} />
<Row label="Writer loginuid" value={meta?.writer_loginuid} />
</section>
{Array.isArray(concurrent) && concurrent.length > 0 && (
<section style={{ marginBottom: '24px' }}>
<h3 style={{ fontSize: '0.8rem', letterSpacing: '0.1em', color: 'var(--dim-color)', marginBottom: '8px' }}>
CONCURRENT SESSIONS ({concurrent.length})
</h3>
<pre style={{ fontSize: '0.75rem', background: 'rgba(255,255,255,0.03)', padding: '8px', overflowX: 'auto' }}>
{JSON.stringify(concurrent, null, 2)}
</pre>
</section>
)}
{Array.isArray(ssSnapshot) && ssSnapshot.length > 0 && (
<section>
<h3 style={{ fontSize: '0.8rem', letterSpacing: '0.1em', color: 'var(--dim-color)', marginBottom: '8px' }}>
SS SNAPSHOT ({ssSnapshot.length})
</h3>
<pre style={{ fontSize: '0.75rem', background: 'rgba(255,255,255,0.03)', padding: '8px', overflowX: 'auto' }}>
{JSON.stringify(ssSnapshot, null, 2)}
</pre>
</section>
)}
</div>
</div>
);
};
export default ArtifactDrawer;

View File

@@ -1,7 +1,8 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { Activity, ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Crosshair, Fingerprint, Shield, Clock, Wifi, Lock, FileKey, Radio, Timer } from 'lucide-react'; import { Activity, ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Crosshair, Fingerprint, Shield, Clock, Wifi, Lock, FileKey, Radio, Timer, Paperclip } from 'lucide-react';
import api from '../utils/api'; import api from '../utils/api';
import ArtifactDrawer from './ArtifactDrawer';
import './Dashboard.css'; import './Dashboard.css';
interface AttackerBehavior { interface AttackerBehavior {
@@ -705,7 +706,19 @@ const AttackerDetail: React.FC = () => {
behavior: true, behavior: true,
commands: true, commands: true,
fingerprints: true, fingerprints: true,
artifacts: true,
}); });
// Captured file-drop artifacts (ssh inotify farm) for this attacker.
type ArtifactLog = {
id: number;
timestamp: string;
decky: string;
service: string;
fields: string; // JSON-encoded SD params (parsed lazily below)
};
const [artifacts, setArtifacts] = useState<ArtifactLog[]>([]);
const [artifact, setArtifact] = useState<{ decky: string; storedAs: string; fields: Record<string, any> } | null>(null);
const toggle = (key: string) => setOpenSections((prev) => ({ ...prev, [key]: !prev[key] })); const toggle = (key: string) => setOpenSections((prev) => ({ ...prev, [key]: !prev[key] }));
// Commands pagination state // Commands pagination state
@@ -759,6 +772,19 @@ const AttackerDetail: React.FC = () => {
setCmdPage(1); setCmdPage(1);
}, [serviceFilter]); }, [serviceFilter]);
useEffect(() => {
if (!id) return;
const fetchArtifacts = async () => {
try {
const res = await api.get(`/attackers/${id}/artifacts`);
setArtifacts(res.data.data ?? []);
} catch {
setArtifacts([]);
}
};
fetchArtifacts();
}, [id]);
if (loading) { if (loading) {
return ( return (
<div className="dashboard"> <div className="dashboard">
@@ -1058,6 +1084,88 @@ const AttackerDetail: React.FC = () => {
); );
})()} })()}
{/* Captured Artifacts */}
<Section
title={<>CAPTURED ARTIFACTS ({artifacts.length})</>}
open={openSections.artifacts}
onToggle={() => toggle('artifacts')}
>
{artifacts.length > 0 ? (
<div className="logs-table-container">
<table className="logs-table">
<thead>
<tr>
<th>TIMESTAMP</th>
<th>DECKY</th>
<th>FILENAME</th>
<th>SIZE</th>
<th>SHA-256</th>
<th></th>
</tr>
</thead>
<tbody>
{artifacts.map((row) => {
let fields: Record<string, any> = {};
try { fields = JSON.parse(row.fields || '{}'); } catch {}
const storedAs = fields.stored_as ? String(fields.stored_as) : null;
const sha = fields.sha256 ? String(fields.sha256) : '';
return (
<tr key={row.id}>
<td className="dim" style={{ fontSize: '0.75rem', whiteSpace: 'nowrap' }}>
{new Date(row.timestamp).toLocaleString()}
</td>
<td className="violet-accent">{row.decky}</td>
<td className="matrix-text" style={{ fontFamily: 'monospace', wordBreak: 'break-all' }}>
{fields.orig_path ?? storedAs ?? '—'}
</td>
<td className="matrix-text" style={{ fontFamily: 'monospace' }}>
{fields.size ? `${fields.size} B` : '—'}
</td>
<td className="dim" style={{ fontFamily: 'monospace', fontSize: '0.7rem' }}>
{sha ? `${sha.slice(0, 12)}` : '—'}
</td>
<td>
{storedAs && (
<button
onClick={() => setArtifact({ decky: row.decky, storedAs, fields })}
title="Inspect captured artifact"
style={{
display: 'flex', alignItems: 'center', gap: '6px',
fontSize: '0.7rem',
backgroundColor: 'rgba(255, 170, 0, 0.1)',
padding: '2px 8px',
borderRadius: '4px',
border: '1px solid rgba(255, 170, 0, 0.5)',
color: '#ffaa00',
cursor: 'pointer',
}}
>
<Paperclip size={11} /> OPEN
</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
) : (
<div style={{ padding: '24px', textAlign: 'center', opacity: 0.5 }}>
NO ARTIFACTS CAPTURED FROM THIS ATTACKER
</div>
)}
</Section>
{artifact && (
<ArtifactDrawer
decky={artifact.decky}
storedAs={artifact.storedAs}
fields={artifact.fields}
onClose={() => setArtifact(null)}
/>
)}
{/* UUID footer */} {/* UUID footer */}
<div style={{ textAlign: 'right', fontSize: '0.65rem', opacity: 0.3, marginTop: '8px' }}> <div style={{ textAlign: 'right', fontSize: '0.65rem', opacity: 0.3, marginTop: '8px' }}>
UUID: {attacker.uuid} UUID: {attacker.uuid}

View File

View File

@@ -0,0 +1,127 @@
"""
Tests for GET /api/v1/artifacts/{decky}/{stored_as}.
Verifies admin-gating, 404 on missing files, 400 on malformed inputs, and
that path traversal attempts cannot escape DECNET_ARTIFACTS_ROOT.
"""
from __future__ import annotations
import httpx
import pytest
_DECKY = "test-decky-01"
_VALID_STORED_AS = "2026-04-18T02:22:56Z_abc123def456_payload.bin"
_PAYLOAD = b"attacker-drop-bytes\x00\x01\x02\xff"
@pytest.fixture
def artifacts_root(tmp_path, monkeypatch):
"""Point the artifact endpoint at a tmp dir and seed one valid file."""
root = tmp_path / "artifacts"
(root / _DECKY / "ssh").mkdir(parents=True)
(root / _DECKY / "ssh" / _VALID_STORED_AS).write_bytes(_PAYLOAD)
# Patch the module-level constant (captured at import time).
from decnet.web.router.artifacts import api_get_artifact
monkeypatch.setattr(api_get_artifact, "ARTIFACTS_ROOT", root)
return root
async def test_admin_downloads_artifact(client: httpx.AsyncClient, auth_token: str, artifacts_root):
res = await client.get(
f"/api/v1/artifacts/{_DECKY}/{_VALID_STORED_AS}",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert res.status_code == 200, res.text
assert res.content == _PAYLOAD
assert res.headers["content-type"] == "application/octet-stream"
async def test_viewer_forbidden(client: httpx.AsyncClient, viewer_token: str, artifacts_root):
res = await client.get(
f"/api/v1/artifacts/{_DECKY}/{_VALID_STORED_AS}",
headers={"Authorization": f"Bearer {viewer_token}"},
)
assert res.status_code == 403
async def test_unauthenticated_rejected(client: httpx.AsyncClient, artifacts_root):
res = await client.get(f"/api/v1/artifacts/{_DECKY}/{_VALID_STORED_AS}")
assert res.status_code == 401
async def test_missing_file_returns_404(client: httpx.AsyncClient, auth_token: str, artifacts_root):
missing = "2026-04-18T02:22:56Z_000000000000_nope.bin"
res = await client.get(
f"/api/v1/artifacts/{_DECKY}/{missing}",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert res.status_code == 404
@pytest.mark.parametrize("bad_decky", [
"UPPERCASE",
"has_underscore",
"has.dot",
"-leading-hyphen",
"",
"a/b",
])
async def test_bad_decky_rejected(client: httpx.AsyncClient, auth_token: str, artifacts_root, bad_decky):
res = await client.get(
f"/api/v1/artifacts/{bad_decky}/{_VALID_STORED_AS}",
headers={"Authorization": f"Bearer {auth_token}"},
)
# FastAPI returns 404 for routes that fail to match (e.g. `a/b` splits the
# path param); malformed-but-matching cases yield our 400.
assert res.status_code in (400, 404)
@pytest.mark.parametrize("bad_stored_as", [
"not-a-timestamp_abc123def456_payload.bin",
"2026-04-18T02:22:56Z_SHORT_payload.bin",
"2026-04-18T02:22:56Z_abc123def456_",
"random-string",
"",
])
async def test_bad_stored_as_rejected(client: httpx.AsyncClient, auth_token: str, artifacts_root, bad_stored_as):
res = await client.get(
f"/api/v1/artifacts/{_DECKY}/{bad_stored_as}",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert res.status_code in (400, 404)
async def test_path_traversal_blocked(client: httpx.AsyncClient, auth_token: str, artifacts_root, tmp_path):
"""A file placed outside the artifacts root must be unreachable even if a
caller crafts a URL-encoded `..` in the stored_as segment."""
secret = tmp_path / "secret.txt"
secret.write_bytes(b"top-secret")
# The regex for stored_as forbids slashes, `..`, etc. Any encoding trick
# that reaches the handler must still fail the regex → 400.
for payload in (
"..%2Fsecret.txt",
"..",
"../../etc/passwd",
"%2e%2e/%2e%2e/etc/passwd",
):
res = await client.get(
f"/api/v1/artifacts/{_DECKY}/{payload}",
headers={"Authorization": f"Bearer {auth_token}"},
)
# Either 400 (our validator) or 404 (FastAPI didn't match the route) is fine;
# what's NOT fine is 200 with secret bytes.
assert res.status_code != 200
assert b"top-secret" not in res.content
async def test_content_disposition_is_attachment(client: httpx.AsyncClient, auth_token: str, artifacts_root):
res = await client.get(
f"/api/v1/artifacts/{_DECKY}/{_VALID_STORED_AS}",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert res.status_code == 200
cd = res.headers.get("content-disposition", "")
assert "attachment" in cd.lower()

View File

@@ -280,6 +280,61 @@ class TestGetAttackerCommands:
assert exc_info.value.status_code == 404 assert exc_info.value.status_code == 404
# ─── GET /attackers/{uuid}/artifacts ─────────────────────────────────────────
class TestGetAttackerArtifacts:
@pytest.mark.asyncio
async def test_returns_artifacts(self):
from decnet.web.router.attackers.api_get_attacker_artifacts import get_attacker_artifacts
sample = _sample_attacker()
rows = [
{
"id": 1,
"timestamp": "2026-04-18T02:22:56+00:00",
"decky": "decky-01",
"service": "ssh",
"event_type": "file_captured",
"attacker_ip": "1.2.3.4",
"raw_line": "",
"msg": "",
"fields": json.dumps({
"stored_as": "2026-04-18T02:22:56Z_abc123def456_drop.bin",
"sha256": "deadbeef" * 8,
"size": "4096",
"orig_path": "/root/drop.bin",
}),
},
]
with patch("decnet.web.router.attackers.api_get_attacker_artifacts.repo") as mock_repo:
mock_repo.get_attacker_by_uuid = AsyncMock(return_value=sample)
mock_repo.get_attacker_artifacts = AsyncMock(return_value=rows)
result = await get_attacker_artifacts(
uuid="att-uuid-1",
user={"uuid": "test-user", "role": "viewer"},
)
assert result["total"] == 1
assert result["data"][0]["decky"] == "decky-01"
mock_repo.get_attacker_artifacts.assert_awaited_once_with("att-uuid-1")
@pytest.mark.asyncio
async def test_404_on_unknown_uuid(self):
from decnet.web.router.attackers.api_get_attacker_artifacts import get_attacker_artifacts
with patch("decnet.web.router.attackers.api_get_attacker_artifacts.repo") as mock_repo:
mock_repo.get_attacker_by_uuid = AsyncMock(return_value=None)
with pytest.raises(HTTPException) as exc_info:
await get_attacker_artifacts(
uuid="nonexistent",
user={"uuid": "test-user", "role": "viewer"},
)
assert exc_info.value.status_code == 404
# ─── Auth enforcement ──────────────────────────────────────────────────────── # ─── Auth enforcement ────────────────────────────────────────────────────────
class TestAttackersAuth: class TestAttackersAuth:

View File

@@ -271,7 +271,8 @@ def test_ssh_default_env():
env = _fragment("ssh").get("environment", {}) env = _fragment("ssh").get("environment", {})
assert env.get("SSH_ROOT_PASSWORD") == "admin" assert env.get("SSH_ROOT_PASSWORD") == "admin"
assert not any(k.startswith("COWRIE_") for k in env) assert not any(k.startswith("COWRIE_") for k in env)
assert "NODE_NAME" not in env # SSH propagates NODE_NAME for log attribution / artifact bind-mount paths.
assert env.get("NODE_NAME") == "test-decky"
def test_ssh_custom_password(): def test_ssh_custom_password():