feat: implement Bounty Vault for captured credentials and artifacts

This commit is contained in:
2026-04-09 01:52:42 -04:00
parent 0f86f883fe
commit 69626d705d
17 changed files with 370 additions and 1 deletions

View File

@@ -0,0 +1,4 @@
# file: /home/anti/Tools/DECNET/decnet/web/repository.py
# hypothesis_version: 6.151.11
[]

View File

@@ -0,0 +1,4 @@
# file: /home/anti/Tools/DECNET/decnet/web/api.py
# hypothesis_version: 6.151.11
[0.5, 400, 404, 500, 512, 1000, 1024, '*', '/api/v1/auth/login', '/api/v1/bounty', '/api/v1/deckies', '/api/v1/logs', '/api/v1/stats', '/api/v1/stream', '1.0.0', 'Authorization', 'Bearer', 'Bearer ', 'Decky not found', 'No active deployment', 'WWW-Authenticate', 'access_token', 'admin', 'bearer', 'data', 'decnet.web.api', 'histogram', 'id', 'lastEventId', 'limit', 'logs', 'message', 'must_change_password', 'offset', 'password_hash', 'role', 'stats', 'text/event-stream', 'token', 'token_type', 'total', 'type', 'unihost', 'username', 'uuid']

View File

@@ -0,0 +1,4 @@
# file: /home/anti/Tools/DECNET/decnet/web/ingester.py
# hypothesis_version: 6.151.11
['.json', 'attacker_ip', 'bounty_type', 'credential', 'decky', 'decnet.web.ingester', 'fields', 'password', 'payload', 'r', 'replace', 'service', 'username', 'utf-8']

View File

@@ -0,0 +1,4 @@
# file: /home/anti/Tools/DECNET/decnet/web/sqlite_repository.py
# hypothesis_version: 6.151.11
[' AND ', ' WHERE ', ':', '[^a-zA-Z0-9_]', 'active_deckies', 'attacker', 'attacker-ip', 'attacker_ip', 'bounty_type', 'bounty_type = ?', 'bucket_time', 'count', 'decky', 'decnet.db', 'deployed_deckies', 'event', 'event_type', 'fields', 'id > ?', 'max_id', 'msg', 'must_change_password', 'password_hash', 'payload', 'raw_line', 'role', 'service', 'time', 'timestamp', 'timestamp <= ?', 'timestamp >= ?', 'total', 'total_logs', 'unique_attackers', 'username', 'uuid']

View File

@@ -135,6 +135,13 @@ class LogsResponse(BaseModel):
data: list[dict[str, Any]]
class BountyResponse(BaseModel):
total: int
limit: int
offset: int
data: list[dict[str, Any]]
@app.post("/api/v1/auth/login", response_model=Token)
async def login(request: LoginRequest) -> dict[str, Any]:
_user: Optional[dict[str, Any]] = await repo.get_user_by_username(request.username)
@@ -190,6 +197,25 @@ async def get_logs(
}
@app.get("/api/v1/bounty", response_model=BountyResponse)
async def get_bounties(
limit: int = Query(50, ge=1, le=1000),
offset: int = Query(0, ge=0),
bounty_type: Optional[str] = None,
search: Optional[str] = None,
current_user: str = Depends(get_current_user)
) -> dict[str, Any]:
"""Retrieve collected bounties (harvested credentials, payloads, etc.)."""
_data = await repo.get_bounties(limit=limit, offset=offset, bounty_type=bounty_type, search=search)
_total = await repo.get_total_bounties(bounty_type=bounty_type, search=search)
return {
"total": _total,
"limit": limit,
"offset": offset,
"data": _data
}
@app.get("/api/v1/logs/histogram")
async def get_logs_histogram(
search: Optional[str] = None,

View File

@@ -54,6 +54,7 @@ async def log_ingestion_worker(repo: BaseRepository) -> None:
try:
_log_data: dict[str, Any] = json.loads(_line.strip())
await repo.add_log(_log_data)
await _extract_bounty(repo, _log_data)
except json.JSONDecodeError:
logger.error(f"Failed to decode JSON log line: {_line}")
continue
@@ -66,3 +67,28 @@ async def log_ingestion_worker(repo: BaseRepository) -> None:
await asyncio.sleep(5)
await asyncio.sleep(1)
async def _extract_bounty(repo: BaseRepository, log_data: dict[str, Any]) -> None:
"""Detect and extract valuable artifacts (bounties) from log entries."""
_fields = log_data.get("fields")
if not isinstance(_fields, dict):
return
# 1. Credentials (User/Pass)
_user = _fields.get("username")
_pass = _fields.get("password")
if _user and _pass:
await repo.add_bounty({
"decky": log_data.get("decky"),
"service": log_data.get("service"),
"attacker_ip": log_data.get("attacker_ip"),
"bounty_type": "credential",
"payload": {
"username": _user,
"password": _pass
}
})
# 2. Add more extractors here later (e.g. file hashes, crypto keys)

View File

@@ -59,3 +59,24 @@ class BaseRepository(ABC):
async def update_user_password(self, uuid: str, password_hash: str, must_change_password: bool = False) -> None:
"""Update a user's password and change the must_change_password flag."""
pass
@abstractmethod
async def add_bounty(self, bounty_data: dict[str, Any]) -> None:
"""Add a new harvested artifact (bounty) to the database."""
pass
@abstractmethod
async def get_bounties(
self,
limit: int = 50,
offset: int = 0,
bounty_type: Optional[str] = None,
search: Optional[str] = None
) -> list[dict[str, Any]]:
"""Retrieve paginated bounty entries."""
pass
@abstractmethod
async def get_total_bounties(self, bounty_type: Optional[str] = None, search: Optional[str] = None) -> int:
"""Retrieve the total count of bounties, optionally filtered."""
pass

View File

@@ -37,6 +37,17 @@ class SQLiteRepository(BaseRepository):
must_change_password BOOLEAN DEFAULT 0
)
""")
_conn.execute("""
CREATE TABLE IF NOT EXISTS bounty (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
decky TEXT,
service TEXT,
attacker_ip TEXT,
bounty_type TEXT,
payload TEXT
)
""")
_conn.commit()
async def add_log(self, log_data: dict[str, Any]) -> None:
@@ -296,3 +307,75 @@ class SQLiteRepository(BaseRepository):
(password_hash, must_change_password, uuid)
)
await _db.commit()
async def add_bounty(self, bounty_data: dict[str, Any]) -> None:
import json
async with aiosqlite.connect(self.db_path) as _db:
await _db.execute(
"INSERT INTO bounty (decky, service, attacker_ip, bounty_type, payload) VALUES (?, ?, ?, ?, ?)",
(
bounty_data.get("decky"),
bounty_data.get("service"),
bounty_data.get("attacker_ip"),
bounty_data.get("bounty_type"),
json.dumps(bounty_data.get("payload", {}))
)
)
await _db.commit()
def _build_bounty_where(
self,
bounty_type: Optional[str] = None,
search: Optional[str] = None
) -> tuple[str, list[Any]]:
_where_clauses = []
_params = []
if bounty_type:
_where_clauses.append("bounty_type = ?")
_params.append(bounty_type)
if search:
_where_clauses.append("(decky LIKE ? OR service LIKE ? OR attacker_ip LIKE ? OR payload LIKE ?)")
_like_val = f"%{search}%"
_params.extend([_like_val, _like_val, _like_val, _like_val])
if _where_clauses:
return " WHERE " + " AND ".join(_where_clauses), _params
return "", []
async def get_bounties(
self,
limit: int = 50,
offset: int = 0,
bounty_type: Optional[str] = None,
search: Optional[str] = None
) -> list[dict[str, Any]]:
import json
_where, _params = self._build_bounty_where(bounty_type, search)
_query = f"SELECT * FROM bounty{_where} ORDER BY timestamp DESC LIMIT ? OFFSET ?" # nosec B608
_params.extend([limit, offset])
async with aiosqlite.connect(self.db_path) as _db:
_db.row_factory = aiosqlite.Row
async with _db.execute(_query, _params) as _cursor:
_rows: list[aiosqlite.Row] = await _cursor.fetchall()
_results = []
for _row in _rows:
_d = dict(_row)
try:
_d["payload"] = json.loads(_d["payload"])
except Exception:
pass
_results.append(_d)
return _results
async def get_total_bounties(self, bounty_type: Optional[str] = None, search: Optional[str] = None) -> int:
_where, _params = self._build_bounty_where(bounty_type, search)
_query = f"SELECT COUNT(*) as total FROM bounty{_where}" # nosec B608
async with aiosqlite.connect(self.db_path) as _db:
_db.row_factory = aiosqlite.Row
async with _db.execute(_query, _params) as _cursor:
_row: Optional[aiosqlite.Row] = await _cursor.fetchone()
return _row["total"] if _row else 0

View File

@@ -7,6 +7,7 @@ import DeckyFleet from './components/DeckyFleet';
import LiveLogs from './components/LiveLogs';
import Attackers from './components/Attackers';
import Config from './components/Config';
import Bounty from './components/Bounty';
function App() {
const [token, setToken] = useState<string | null>(localStorage.getItem('token'));
@@ -43,6 +44,7 @@ function App() {
<Route path="/" element={<Dashboard searchQuery={searchQuery} />} />
<Route path="/fleet" element={<DeckyFleet />} />
<Route path="/live-logs" element={<LiveLogs />} />
<Route path="/bounty" element={<Bounty />} />
<Route path="/attackers" element={<Attackers />} />
<Route path="/config" element={<Config />} />
<Route path="*" element={<Navigate to="/" replace />} />

View File

@@ -0,0 +1,166 @@
import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Archive, Search, ChevronLeft, ChevronRight, Filter } from 'lucide-react';
import api from '../utils/api';
import './Dashboard.css';
interface BountyEntry {
id: number;
timestamp: string;
decky: string;
service: string;
attacker_ip: string;
bounty_type: string;
payload: any;
}
const Bounty: React.FC = () => {
const [searchParams, setSearchParams] = useSearchParams();
const query = searchParams.get('q') || '';
const typeFilter = searchParams.get('type') || '';
const page = parseInt(searchParams.get('page') || '1');
const [bounties, setBounties] = useState<BountyEntry[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [searchInput, setSearchInput] = useState(query);
const limit = 50;
const fetchBounties = async () => {
setLoading(true);
try {
const offset = (page - 1) * limit;
let url = `/bounty?limit=${limit}&offset=${offset}`;
if (query) url += `&search=${encodeURIComponent(query)}`;
if (typeFilter) url += `&bounty_type=${typeFilter}`;
const res = await api.get(url);
setBounties(res.data.data);
setTotal(res.data.total);
} catch (err) {
console.error('Failed to fetch bounties', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchBounties();
}, [query, typeFilter, page]);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
setSearchParams({ q: searchInput, type: typeFilter, page: '1' });
};
const setPage = (p: number) => {
setSearchParams({ q: query, type: typeFilter, page: p.toString() });
};
const setType = (t: string) => {
setSearchParams({ q: query, type: t, page: '1' });
};
const totalPages = Math.ceil(total / limit);
return (
<div className="dashboard-container">
<div className="dashboard-header">
<div className="header-title">
<Archive size={24} className="violet-accent" />
<h1>BOUNTY VAULT</h1>
</div>
<div className="header-actions">
<div className="filter-group">
<Filter size={16} className="dim-color" />
<select value={typeFilter} onChange={(e) => setType(e.target.value)}>
<option value="">ALL TYPES</option>
<option value="credential">CREDENTIALS</option>
<option value="payload">PAYLOADS</option>
</select>
</div>
<form onSubmit={handleSearch} className="query-container">
<Search size={18} className="search-icon" />
<input
type="text"
placeholder="Search bounty..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
/>
</form>
</div>
</div>
<div className="card log-card">
<div className="card-header">
<div className="status-indicator">
<span className="matrix-text">{total} ARTIFACTS CAPTURED</span>
</div>
<div className="pagination-controls">
<button disabled={page <= 1} onClick={() => setPage(page - 1)} className="icon-btn">
<ChevronLeft size={16} />
</button>
<span className="dim-color">PAGE {page} OF {totalPages || 1}</span>
<button disabled={page >= totalPages} onClick={() => setPage(page + 1)} className="icon-btn">
<ChevronRight size={16} />
</button>
</div>
</div>
<div className="log-table-container">
<table className="log-table">
<thead>
<tr>
<th>TIMESTAMP</th>
<th>DECKY</th>
<th>SERVICE</th>
<th>ATTACKER</th>
<th>TYPE</th>
<th>DATA</th>
</tr>
</thead>
<tbody>
{bounties.map((b) => (
<tr key={b.id}>
<td className="dim-color" style={{ whiteSpace: 'nowrap' }}>{b.timestamp}</td>
<td className="violet-accent">{b.decky}</td>
<td>{b.service}</td>
<td className="matrix-text">{b.attacker_ip}</td>
<td>
<span className={`severity-badge ${b.bounty_type === 'credential' ? 'high' : 'info'}`}>
{b.bounty_type.toUpperCase()}
</span>
</td>
<td>
<div className="payload-preview">
{b.bounty_type === 'credential' ? (
<>
<span className="dim-color">user:</span> {b.payload.username}
<span className="dim-color" style={{marginLeft: '10px'}}>pass:</span> {b.payload.password}
</>
) : (
JSON.stringify(b.payload)
)}
</div>
</td>
</tr>
))}
{!loading && bounties.length === 0 && (
<tr>
<td colSpan={6} style={{ textAlign: 'center', padding: '40px' }} className="dim-color">
THE VAULT IS EMPTY
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
);
};
export default Bounty;

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import { NavLink } from 'react-router-dom';
import { Menu, X, Search, Activity, LayoutDashboard, Terminal, Settings, LogOut, Server } from 'lucide-react';
import { Menu, X, Search, Activity, LayoutDashboard, Terminal, Settings, LogOut, Server, Archive } from 'lucide-react';
import api from '../utils/api';
import './Layout.css';
@@ -50,6 +50,7 @@ const Layout: React.FC<LayoutProps> = ({ children, onLogout, onSearch }) => {
<NavItem to="/" icon={<LayoutDashboard size={20} />} label="Dashboard" open={sidebarOpen} />
<NavItem to="/fleet" icon={<Server size={20} />} label="Decoy Fleet" open={sidebarOpen} />
<NavItem to="/live-logs" icon={<Terminal size={20} />} label="Live Logs" open={sidebarOpen} />
<NavItem to="/bounty" icon={<Archive size={20} />} label="Bounty" open={sidebarOpen} />
<NavItem to="/attackers" icon={<Activity size={20} />} label="Attackers" open={sidebarOpen} />
<NavItem to="/config" icon={<Settings size={20} />} label="Config" open={sidebarOpen} />
</nav>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

28
tests/test_bounty.py Normal file
View File

@@ -0,0 +1,28 @@
import pytest
from fastapi.testclient import TestClient
from decnet.web.api import app
from decnet.env import DECNET_ADMIN_USER, DECNET_ADMIN_PASSWORD
@pytest.fixture
def auth_token():
with TestClient(app) as client:
resp = client.post("/api/v1/auth/login", json={"username": DECNET_ADMIN_USER, "password": DECNET_ADMIN_PASSWORD})
return resp.json()["access_token"]
def test_add_and_get_bounty(auth_token):
with TestClient(app) as client:
# We can't directly call add_bounty from API yet (it's internal to ingester)
# But we can test the repository if we want, or mock a log line that triggers it.
# For now, let's test the endpoint returns 200 even if empty.
resp = client.get("/api/v1/bounty", headers={"Authorization": f"Bearer {auth_token}"})
assert resp.status_code == 200
data = resp.json()
assert "total" in data
assert "data" in data
assert isinstance(data["data"], list)
def test_bounty_pagination(auth_token):
with TestClient(app) as client:
resp = client.get("/api/v1/bounty?limit=1&offset=0", headers={"Authorization": f"Bearer {auth_token}"})
assert resp.status_code == 200
assert resp.json()["limit"] == 1