Files
MUA-Mikes-Unraid-Agent/src/auth.ts
T
Mikei386andClaude Opus 5.5 b8d89ffd9c release: MUA 2026.11.20.r036
Read-only shell
- Accept a full command line (`command`) and parse it without /bin/sh:
  quotes, escapes, ~, pipes between allowed programs, ; && ||, globs in
  absolute paths; 2>&1 and 2>/dev/null are tolerated. Pipeline stages run
  with strictly single-quoted, pre-validated literals only.
- Per-program option policies that understand combined short flags,
  --opt=value and GNU abbreviations. Closes bypasses: ip abbreviations
  (ip a a / ip r d / ip link s), dmesg -c/-Tc/--console-level=, ss -tK/-D,
  date operands, sort -o, uniq output file, file -C.
- Block credential files (shadow, SSH private keys, mua.conf, admin token,
  /proc/*/environ, docker config.v2.json); redact password hashes, private
  PEM keys and WireGuard keys in output. MUA API key and admin token are
  never emitted by any tool.
- More diagnostic programs (echo, printf, sort, uniq, cut, tr, findmnt,
  sensors, zpool/zfs read verbs, mdcmd status, ...). grep without matches
  is reported as no_match instead of an error.

Process handling
- Spawn every child in its own process group; timeouts kill the whole
  tree. The MCP hard timeout kills exactly the processes of that call.
- Async jobs: command in its own file (exit no longer loses the exit
  code), new unraid_system_job_cancel, finished jobs pruned after 7 days.

Other
- Cache toolbox discovery briefly; validate and bound session IDs; /health
  shows version/port only with a valid token; constant-time admin token
  check; auto-granted tools are logged and shown in the WebGUI.
- Remove the legacy PHP server (mcp/), drop old packages from dist/, pin
  @types/bun.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:51:14 +01:00

330 lines
11 KiB
TypeScript

/**
* MUA — Mikes Unraid Agent
* auth.ts — API-Key-Auth + Tool-Filter (Config-Management)
*
* Config-Datei: /boot/config/plugins/mua/mua.conf (chmod 600)
* Format (INI):
* MUA_API_KEY=<64 hex chars>
* MUA_ENABLED_TOOLS=all | none | <comma-separated tool names>
*
* Auth-Flow:
* Client sendet: Authorization: Bearer ***
* Server prüft: timing-safe comparison (timing-attack-sicher)
* Fehlschlag: 401 Unauthorized
*
* /health bleibt ohne Auth (Monitoring).
* /mcp (POST + DELETE) erfordert gültiges Token.
*
* Tool-Filter:
* MUA_ENABLED_TOOLS=all → alle Tools aktiv
* MUA_ENABLED_TOOLS=a,b,c → nur diese Tools (tools/list + tools/call)
*/
import { readFileSync, writeFileSync, mkdirSync, chmodSync } from "node:fs";
import { randomBytes, timingSafeEqual } from "node:crypto";
import { forgetSecret, registerSecret } from "./redact";
const CONFIG_DIR = process.env["MUA_CONFIG_DIR"] ?? "/boot/config/plugins/mua";
const CONFIG_FILE = `${CONFIG_DIR}/mua.conf`;
// ── Config-Struktur ─────────────────────────────────────────────────────
export interface MUAConfig {
apiKey: string;
enabledTools: string[];
allToolsEnabled: boolean;
toolboxEnabled: boolean;
/**
* Tools, die beim Laden aus Kompatibilitätsgründen automatisch ergänzt
* wurden (nicht in der Datei, aber durch eine bereits erteilte, gleich
* starke Freigabe gedeckt). Wird geloggt und in der WebGUI angezeigt.
*/
autoGranted?: string[];
}
// Sichere Grundeinstellung für Neuinstallationen. Schreibzugriffe, aktive
// Netzwerkscans und die Root-Shell müssen ausdrücklich in der GUI aktiviert
// werden.
export const SAFE_DEFAULT_TOOLS = [
"unraid_docker_list",
"unraid_docker_inspect",
"unraid_docker_logs",
"unraid_docker_analyze_logs",
"unraid_docker_processes",
"unraid_docker_stats",
"unraid_docker_info",
"unraid_docker_update_status",
"unraid_network_inventory",
"unraid_network_list",
"unraid_network_inspect",
"unraid_network_host_state",
"unraid_system_connection_test",
"unraid_system_shell_readonly",
"unraid_system_health",
"unraid_storage_status",
"unraid_disk_health",
"unraid_notifications_list",
"unraid_shares_list",
"unraid_share_inspect",
"unraid_files_inventory",
];
// ── Config laden ────────────────────────────────────────────────────────
let cachedConfig: MUAConfig | null = null;
export function parseConfig(content: string): MUAConfig {
const cfg: MUAConfig = {
apiKey: "",
enabledTools: [...SAFE_DEFAULT_TOOLS],
allToolsEnabled: false,
toolboxEnabled: false,
};
const grant = (name: string) => {
if (!cfg.enabledTools.includes(name)) {
cfg.enabledTools.push(name);
(cfg.autoGranted ??= []).push(name);
}
};
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (trimmed.startsWith("#") || trimmed === "") continue;
const eq = trimmed.indexOf("=");
if (eq < 0) continue;
const key = trimmed.slice(0, eq).trim();
const value = trimmed.slice(eq + 1).trim();
if (key === "MUA_API_KEY") {
cfg.apiKey = value;
} else if (key === "MUA_ENABLED_TOOLS") {
if (value === "all") {
cfg.enabledTools = [];
cfg.allToolsEnabled = true;
} else if (value === "none" || value === "") {
cfg.enabledTools = [];
cfg.allToolsEnabled = false;
} else {
cfg.enabledTools = value
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0);
cfg.allToolsEnabled = false;
}
} else if (key === "MUA_TOOLBOX_ENABLED") {
cfg.toolboxEnabled = ["1", "true", "yes", "on"].includes(value.toLowerCase());
}
}
// r019 replaces repeated single-container update calls with an idempotent
// batch variant. If an administrator already enabled the older update
// capability, expose the safer equivalent automatically; this does not
// grant a new class of operation.
if (!cfg.allToolsEnabled && cfg.enabledTools.includes("unraid_docker_update")) {
grant("unraid_docker_update_verified_batch");
}
// r020 adds a bounded metadata-only filesystem inventory. It is strictly
// less powerful than the already-enabled read-only shell and avoids many
// repeated ls/find calls, so existing read-only installations may receive
// it without granting a new write capability.
if (!cfg.allToolsEnabled && cfg.enabledTools.includes("unraid_system_shell_readonly")) {
grant("unraid_files_inventory");
}
// Async jobs are the bounded long-running equivalent of the already
// unrestricted root shell. Existing administrators who explicitly enabled
// that critical capability receive no new authority class here.
if (!cfg.allToolsEnabled && cfg.enabledTools.includes("unraid_system_shell")) {
for (const name of [
"unraid_system_job_start",
"unraid_system_job_status",
"unraid_system_job_cancel",
"unraid_system_job_cleanup",
]) {
grant(name);
}
}
return cfg;
}
function loadConfig(): MUAConfig {
if (cachedConfig) return cachedConfig;
const cfg = loadConfigUncached();
registerSecret(cfg.apiKey);
if (cfg.autoGranted?.length) {
console.log(`[MUA] Kompatibilität: automatisch freigegeben (durch bestehende Freigaben gedeckt): ${cfg.autoGranted.join(", ")}`);
}
return cfg;
}
function loadConfigUncached(): MUAConfig {
// 1. Env-Override (für Testing / Docker)
const envToken = process.env["MUA_API_KEY"];
if (envToken && envToken.length > 0) {
const envTools = process.env["MUA_ENABLED_TOOLS"] ?? "";
cachedConfig = parseConfig(
`MUA_API_KEY=${envToken}\n` +
`MUA_ENABLED_TOOLS=${envTools || "none"}\n` +
`MUA_TOOLBOX_ENABLED=${process.env["MUA_TOOLBOX_ENABLED"] ?? "false"}\n`,
);
return cachedConfig;
}
// 2. Aus Config-Datei laden
try {
const content = readFileSync(CONFIG_FILE, "utf-8");
const cfg = parseConfig(content);
if (cfg.apiKey.length > 0) {
cachedConfig = cfg;
return cachedConfig;
}
} catch {
// Datei nicht vorhanden — generiere neue Config
}
// 3. Neue Config generieren
const newToken = randomBytes(32).toString("hex"); // 64 hex chars
cachedConfig = {
apiKey: newToken,
enabledTools: [...SAFE_DEFAULT_TOOLS],
allToolsEnabled: false,
toolboxEnabled: false,
};
try {
mkdirSync(CONFIG_DIR, { recursive: true });
writeConfigFile(cachedConfig);
console.log(`[MUA] Neue Config generiert: ${CONFIG_FILE}`);
} catch (e) {
console.error(`[MUA] WARNUNG: Config konnte nicht gespeichert werden: ${String(e)}`);
console.error("[MUA] Aus Sicherheitsgründen wird der flüchtige API-Key nicht protokolliert.");
}
return cachedConfig;
}
// ── Config schreiben ────────────────────────────────────────────────────
function writeConfigFile(cfg: MUAConfig): void {
const toolsValue = cfg.allToolsEnabled
? "all"
: cfg.enabledTools.length === 0
? "none"
: cfg.enabledTools.join(",");
const content = [
"# MUA Configuration",
"# API-Key für MCP-HTTP-Endpunkt (Port 3002)",
"# Format: Authorization: Bearer ***",
`MUA_API_KEY=${cfg.apiKey}`,
"# Aktive Tools (all = alle, none = keine, oder kommagetrennte Tool-Namen)",
`MUA_ENABLED_TOOLS=${toolsValue}`,
"# Optionalen, per Docker-Label erkannten Werkzeugcontainer bekanntgeben",
`MUA_TOOLBOX_ENABLED=${cfg.toolboxEnabled ? "true" : "false"}`,
"",
].join("\n");
writeFileSync(CONFIG_FILE, content, { mode: 0o600 });
chmodSync(CONFIG_FILE, 0o600);
}
export function saveConfig(cfg: MUAConfig): void {
cachedConfig = cfg;
registerSecret(cfg.apiKey);
writeConfigFile(cfg);
// Nach dem Speichern stehen alle Tools explizit in der Datei.
cfg.autoGranted = undefined;
}
/** Automatisch ergänzte Tools der aktuell geladenen Konfiguration. */
export function getAutoGrantedTools(): string[] {
return [...(loadConfig().autoGranted ?? [])];
}
// ── API-Key ─────────────────────────────────────────────────────────────
export function getApiKey(): string {
return loadConfig().apiKey;
}
export function setApiKey(newKey: string): void {
const cfg = loadConfig();
forgetSecret(cfg.apiKey);
cfg.apiKey = newKey;
saveConfig(cfg);
}
export function generateApiKey(): string {
const newKey = randomBytes(32).toString("hex");
setApiKey(newKey);
return newKey;
}
// ── Tool-Filter ─────────────────────────────────────────────────────────
/**
* Liefert die Liste aktiver Tool-Namen.
* Leer-Array = alle Tools aktiv.
*/
export function getEnabledTools(): string[] {
return loadConfig().enabledTools;
}
export function getAllToolsEnabled(): boolean {
return loadConfig().allToolsEnabled;
}
/**
* Setzt die aktiven Tools.
* Ein leeres Array bedeutet ausdrücklich: keine Tools aktiv.
*/
export function setEnabledTools(names: string[], allToolsEnabled = false): void {
const cfg = loadConfig();
cfg.enabledTools = [...new Set(names)];
cfg.allToolsEnabled = allToolsEnabled;
saveConfig(cfg);
}
export function getToolboxEnabled(): boolean {
return loadConfig().toolboxEnabled;
}
export function setToolboxEnabled(enabled: boolean): void {
const cfg = loadConfig();
cfg.toolboxEnabled = enabled;
saveConfig(cfg);
}
/**
* Prüft, ob ein Tool aktiv ist.
* true = aktiv, false = deaktiviert.
*/
export function isToolEnabled(toolName: string): boolean {
const enabled = getEnabledTools();
if (getAllToolsEnabled()) return true;
return enabled.includes(toolName);
}
// ── Timing-safe Token-Check ─────────────────────────────────────────────
export function checkAuth(req: Request): boolean {
const token = getApiKey();
const authHeader = req.headers.get("authorization") ?? "";
// Format: "Bearer <token>"
if (!authHeader.startsWith("Bearer ")) {
return false;
}
const provided = authHeader.slice(7).trim();
// Timing-safe comparison (verhindert Timing-Attacks)
if (provided.length !== token.length) {
return false;
}
return safeEqual(provided, token);
}
/** Zeitkonstanter Vergleich gleich langer Strings. */
export function safeEqual(provided: string, expected: string): boolean {
if (expected.length === 0) return false;
const a = Buffer.from(provided);
const b = Buffer.from(expected);
return a.length === b.length && timingSafeEqual(a, b);
}
export function getMaskedApiKey(): string {
const key = getApiKey();
return key.length >= 8 ? `••••••••${key.slice(-8)}` : "gesetzt";
}