Files

298 lines
11 KiB
JavaScript

#!/usr/bin/env node
/**
* shell-tools — MCP-Server mit begrenzter Shell-/SSH-Faehigkeit fuer Jarvis.
*
* Design:
* - ssh_host bindet mit einem **eingeschraenkten SSH-Schluessel** an den Host.
* Der Schluessel erzwingt auf dem Host das Waechter-Skript
* (command="..." in authorized_keys, root-eigentuemer). Der Waechter protokolliert
* jeden Befehl nach /var/log/jarvis-ssh.log und blockt: Aenderungen am eigenen
* Zugang/Schutz, global destruktive Befehle, Aenderungen an der Trading-Instanz
* (ai-orchestrator-*, /mnt/disk1/Development-DATA/AI-Platform/openclaw/) und an
* der eigenen Policy (…/openclaw-jarvis/config/openclaw.json, config/mcp/) sowie
* destruktive Docker-Befehle.
*
* Ehrliche Grenze: Das ist Schutz vor Fehlern/Fluegelbruch, keine echte Sandbox.
* Ein Bewusst/Boedwilliger Koennte mit root-Shell konstruierte Umgehungen bauen.
* Deshalb: jede Ausfuehrung wird lokal (AUDIT_FILE) und hostseitig protokolliert.
*
* - exec_local fuehrt Befehle im Container (uid 1000, Workspace) aus. Der lokale
* Schutz greift fuer die eigene Policy-Konfiguration (openclaw.json, mcp/),
* ist aber nur eine Denylist (keine Sandbox).
*/
'use strict';
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const HOST = process.env.SSH_HOST || 'YOUR_SERVER_IP';
const USER = process.env.SSH_USER || 'root';
const KEY = process.env.SSH_KEY_FILE || '/home/node/.openclaw/ssh/id_ed25519';
const KHOSTS = process.env.SSH_KNOWN_HOSTS || '/home/node/.openclaw/ssh/known_hosts';
const AUDIT = process.env.AUDIT_FILE || '/home/node/.openclaw/workspaces/jarvis/.shell-audit.log';
const WORKSPACE = process.env.WORKSPACE || '/home/node/.openclaw/workspaces/jarvis';
const MAX_CHARS = 40000;
function audit(entry) {
try {
fs.mkdirSync(path.dirname(AUDIT), { recursive: true });
fs.appendFileSync(AUDIT, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n');
} catch (e) {
// Audit darf den Aufruf nicht unterbrechen.
}
}
// ------------------------- Denylists (lokal, ergaenzend) -------------------------
const LOCAL_DESTRUCT = [
/mkfs/i,
/wipefs/i,
/blkdiscard/i,
/dd[^\n]*of=\/dev\//i,
/shutdown/i,
/reboot/i,
/poweroff/i,
/(^|[[:space:]])(halt)([[:space:]]|$)/i,
/rm\s+-[a-zA-Z]*r[a-zA-Z]*f\s+\//i,
/systemctl\s+(stop|restart|mask|disable)/i,
];
const SELF_POLICY = [/openclaw-jarvis\/config\/openclaw\.json/i, /openclaw-jarvis\/config\/mcp\//i];
function blockedLocal(cmd) {
if (!cmd || !cmd.trim()) return 'leerer Befehl';
if (LOCAL_DESTRUCT.some((re) => re.test(cmd))) return 'global destruktiv';
if (SELF_POLICY.some((re) => re.test(cmd))) return 'eigene Policy (openclaw.json/mcp) ist tabu';
return null;
}
// ------------------------- Gemeinsame Runner -------------------------
function run(args, opts) {
return new Promise((resolve) => {
const timeoutMs = opts.timeoutMs || 30000;
const p = spawn(args[0], args.slice(1), {
env: { ...process.env, LANG: 'C', LC_ALL: 'C' },
stdio: ['ignore', 'pipe', 'pipe'],
});
let out = '';
let done = false;
const finish = (code, extra) => {
if (done) return;
done = true;
resolve({ code: code === null ? -1 : code, out: out.slice(0, MAX_CHARS), truncated: out.length > MAX_CHARS, ...extra });
};
const t = setTimeout(() => {
try {
p.kill('SIGKILL');
} catch (e) {}
finish(-2, { error: `timeout nach ${timeoutMs} ms` });
}, timeoutMs + 2000);
p.on('exit', (c, s) => {
clearTimeout(t);
finish(c === null ? (s && s.code) || -1 : c);
});
p.on('error', (e) => {
clearTimeout(t);
finish(-1, { error: String(e.message || e) });
});
p.stdout.on('data', (d) => (out += d));
p.stderr.on('data', (d) => (out += d));
});
}
async function execLocal(args) {
const cmd = String((args && args.command) || '').trim();
const timeout = Math.min(60, Math.max(3, Number((args && args.timeout_seconds) || 30))) * 1000;
const block = blockedLocal(cmd);
if (block) {
audit({ tool: 'exec_local', command: cmd, blocked: block });
return {
isError: true,
text: `exec_local VERWEIGERT (lokaler Schutz: ${block}). Aenderungen an der eigenen Konfiguration (openclaw.json, config/mcp/) und global destruktive Befehle sind nicht erlaubt.`,
};
}
const r = await run(['sh', '-c', cmd], { timeoutMs: timeout });
audit({ tool: 'exec_local', command: cmd, exit: r.code, ms: r.ms || 0, out_len: r.out.length, error: r.error || null });
const body = r.error ? `\n(FEHLER: ${r.error})` : '';
const out = (r.out || '').trim() || '(keine Ausgabe)';
return {
text: `## exec_local (Container, uid 1000, Workspace)\n\n- Befehl: \`${cmd}\`\n- Exit-Code: ${r.code}${r.truncated ? ', Ausgabe gekuerzt' : ''}\n\n\`\`\`\n${out}${body}\n\`\`\``,
isError: r.code !== 0,
};
}
async function sshHost(args) {
const cmd = String((args && args.command) || '').trim();
const timeout = Math.min(60, Math.max(3, Number((args && args.timeout_seconds) || 30))) * 1000;
if (!cmd) return { isError: true, text: 'ssh_host: Befehl fehlt.' };
const sshArgs = [
'ssh',
'-i', KEY,
'-o', 'BatchMode=yes',
'-o', 'StrictHostKeyChecking=accept-new',
'-o', `UserKnownHostsFile=${KHOSTS}`,
'-o', 'ConnectTimeout=8',
'-o', 'LogLevel=ERROR',
`${USER}@${HOST}`,
cmd,
];
const r = await run(sshArgs, { timeoutMs: timeout });
audit({ tool: 'ssh_host', host: HOST, command: cmd, exit: r.code, ms: r.ms || 0, out_len: r.out.length, error: r.error || null, blocked: (r.out || '').match(/^VERWEIGERT/) ? true : null });
const out = (r.out || '').trim() || '(keine Ausgabe)';
let note = '';
if (/^VERWEIGERT/.test(out)) note = '\n> Der Host-Waechter hat diesen Befehl abgelehnt (Log: /var/log/jarvis-ssh.log).';
else if (r.error) note = `\n(FEHLER: ${r.error})`;
return {
text: `## ssh_host (${USER}@${HOST}, bewaucht & protokolliert)\n\n- Befehl: \`${cmd}\`\n- Exit-Code: ${r.code}${r.truncated ? ', Ausgabe gekuerzt' : ''}\n\n\`\`\`\n${out}\n\`\`\`${note}`,
isError: r.code !== 0,
};
}
function shellAudit(args) {
const n = Math.min(200, Math.max(1, Number((args && args.tail_lines) || 30)));
let data = '';
try {
data = fs.readFileSync(AUDIT, 'utf8');
} catch (e) {
return { text: `## Shell-Audit\n\n_Keine Eintraege (${AUDIT} nicht vorhanden)_` };
}
const lines = data.trim().split('\n').filter(Boolean);
const tail = lines.slice(-n);
const pretty = tail.map((l) => {
try {
const j = JSON.parse(l);
return `[${j.ts}] ${j.tool} exit=${j.exit ?? '?'}${j.blocked ? ' BLOCKIERT(' + j.blocked + ')' : ''}: ${(j.command || '').slice(0, 300)}`;
} catch (e) {
return l;
}
});
return {
text: `## Shell-Audit (letzte ${tail.length} von ${lines.length})\n\n${pretty.map((l) => '- ' + l).join('\n')}`,
};
}
const TOOLS = [
{
name: 'ssh_host',
description:
'Fuehrt einen Befehl als root auf dem Unraid-Host aus. Der Host-Waechter protokolliert alles und blockt Aenderungen an der Trading-Instanz (ai-orchestrator-*, …/AI-Platform/openclaw/), an der eigenen OpenClaw-Policy (…/openclaw-jarvis/config/openclaw.json und config/mcp/), global destruktive Befehle und destruktive Docker-Befehle. Lesen ist erlaubt (ls, cat, tail, grep, docker inspect/logs/stats, smartctl …).',
inputSchema: {
type: 'object',
properties: {
command: { type: 'string', description: 'Vollstaendiger Shell-Befehl, z.B. "uptime" oder "df -h /mnt/disk1".' },
timeout_seconds: { type: 'integer', description: 'Timeout 3-60 s (Standard 30).' },
},
required: ['command'],
additionalProperties: false,
},
},
{
name: 'exec_local',
description:
'Fuehrt einen Befehl im eigenen Container aus (uid 1000, Working-Dir = Workspace). Nuetztlich fuer node/curl/Datei-Proben. Aenderungen an openclaw.json und config/mcp/ sind lokal gesperrt.',
inputSchema: {
type: 'object',
properties: {
command: { type: 'string', description: 'Shell-Befehl im Container, z.B. "df -h /home/node" oder "node -e \"...\""' },
timeout_seconds: { type: 'integer', description: 'Timeout 3-60 s (Standard 30).' },
},
required: ['command'],
additionalProperties: false,
},
},
{
name: 'shell_audit',
description: 'Zeigt die letzten Eintraege der Shell-Ausfuehrungsprotokolle (lokal; hostseitig /var/log/jarvis-ssh.log per ssh_host lesbar).',
inputSchema: {
type: 'object',
properties: {
tail_lines: { type: 'integer', description: 'Anzahl der letzten Eintraege (1-200, Standard 30).' },
},
additionalProperties: false,
},
},
];
function reply(id, result) {
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n');
}
function replyError(id, code, message) {
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }) + '\n');
}
let buf = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => {
buf += chunk;
let idx;
while ((idx = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, idx).trim();
buf = buf.slice(idx + 1);
if (!line) continue;
handle(line);
}
});
function handle(line) {
let msg;
try {
msg = JSON.parse(line);
} catch (e) {
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) + '\n');
return;
}
const { id, method, params } = msg;
if (method === 'notifications/initialized' || (id === undefined && method)) return;
if (method === 'initialize') {
reply(id, {
protocolVersion: (params && params.protocolVersion) || '2024-11-05',
capabilities: { tools: {} },
serverInfo: { name: 'shell-tools', version: '1.0.0' },
});
return;
}
if (method === 'ping') {
reply(id, {});
return;
}
if (method === 'tools/list') {
reply(id, {
tools: TOOLS.map(({ name, description, inputSchema }) => {
const destructive = name === 'ssh_host' || name === 'exec_local';
return {
name,
description,
inputSchema,
annotations: {
title: name.replace(/_/g, ' '),
readOnlyHint: !destructive,
destructiveHint: destructive,
idempotentHint: true,
openWorldHint: true,
},
};
}),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const args = (params && params.arguments) || {};
const run = async () => {
let out;
if (name === 'ssh_host') out = await sshHost(args);
else if (name === 'exec_local') out = await execLocal(args);
else if (name === 'shell_audit') out = shellAudit(args);
else return { text: `Unbekanntes Werkzeug: ${name}`, isError: true };
return { content: [{ type: 'text', text: out.text }], isError: Boolean(out.isError) };
};
run()
.then((r) => reply(id, r))
.catch((e) => reply(id, { content: [{ type: 'text', text: String(e && e.message) }], isError: true }));
return;
}
if (id !== undefined) replyError(id, -32601, `Method not found: ${method}`);
}