#!/usr/bin/env node /** Read-only MCP server for the local OPNsense API. */ 'use strict'; const fs = require('fs'); const https = require('https'); const BASE = new URL(process.env.OPNSENSE_URL || 'https://YOUR_FIREWALL_IP'); const CREDENTIALS_FILE = process.env.OPNSENSE_CREDENTIALS_FILE || '/home/node/.openclaw/mcp/.opnsense-credentials'; const CERT_SHA256 = normalizeFingerprint(process.env.OPNSENSE_CERT_SHA256 || ''); const TIMEOUT_MS = 15000; const MAX_ROWS = 500; let cachedAuth = null; function normalizeFingerprint(value) { return String(value).replace(/[^a-fA-F0-9]/g, '').toUpperCase(); } function readAuth() { if (cachedAuth) return cachedAuth; let st; try { st = fs.statSync(CREDENTIALS_FILE); } catch { throw new Error(`Credential-Datei nicht lesbar: ${CREDENTIALS_FILE}`); } if ((st.mode & 0o077) !== 0) throw new Error(`Credential-Datei ist nicht restriktiv (Modus ${st.mode & 0o777}).`); if (st.uid !== 1000) throw new Error(`Credential-Datei gehoert uid ${st.uid}, erwartet 1000.`); const lines = fs.readFileSync(CREDENTIALS_FILE, 'utf8').split(/\r?\n/).map((x) => x.trim()).filter(Boolean); if (lines.length !== 2) throw new Error('Credential-Datei muss genau API-Key und API-Secret enthalten.'); cachedAuth = { key: lines[0], secret: lines[1] }; return cachedAuth; } function api(path) { return new Promise((resolve, reject) => { const auth = readAuth(); let settled = false; const finish = (fn, value) => { if (settled) return; settled = true; fn(value); }; const req = https.request({ protocol: BASE.protocol, hostname: BASE.hostname, port: BASE.port || 443, path, method: 'GET', rejectUnauthorized: false, agent: false, headers: { Authorization: 'Basic ' + Buffer.from(`${auth.key}:${auth.secret}`).toString('base64'), Accept: 'application/json', }, }, (res) => { let body = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { body += chunk; if (body.length > 8 * 1024 * 1024) req.destroy(new Error('OPNsense-Antwort ist zu gross.')); }); res.on('end', () => { if (res.statusCode < 200 || res.statusCode >= 300) { finish(reject, new Error(`OPNsense API antwortete mit HTTP ${res.statusCode}.`)); return; } try { finish(resolve, JSON.parse(body)); } catch { finish(reject, new Error('OPNsense API lieferte kein gueltiges JSON.')); } }); }); req.setTimeout(TIMEOUT_MS, () => req.destroy(new Error('OPNsense API Timeout.'))); req.on('socket', (socket) => { socket.once('secureConnect', () => { const actual = normalizeFingerprint((socket.getPeerCertificate() || {}).fingerprint256 || ''); if (!CERT_SHA256) req.destroy(new Error('Kein OPNsense-Zertifikat-Fingerprint konfiguriert.')); else if (actual !== CERT_SHA256) req.destroy(new Error('OPNsense-Zertifikat stimmt nicht mit dem konfigurierten Fingerprint ueberein.')); }); }); req.on('error', (error) => finish(reject, error)); req.end(); }); } function escapeCell(value) { return String(value ?? '-').replace(/\r?\n/g, ', ').replace(/\|/g, '\\|'); } function yesNo(value) { return value === true || value === 1 || value === '1' ? 'ja' : 'nein'; } async function status() { const [system, services, interfaces, gateways] = await Promise.all([ api('/api/core/system/status'), api('/api/core/service/search'), api('/api/interfaces/overview/interfacesInfo'), api('/api/routes/gateway/status'), ]); const serviceRows = services.rows || []; const interfaceRows = interfaces.rows || []; const gatewayRows = gateways.items || []; const message = system.metadata && system.metadata.system ? system.metadata.system.message : 'unbekannt'; return [ '## OPNsense Status', '', `- API: ${BASE.origin}`, `- System: ${message}`, `- Dienste: ${serviceRows.filter((x) => Number(x.running) === 1).length}/${serviceRows.length} laufen`, `- Interfaces: ${interfaceRows.filter((x) => x.status === 'up').length}/${interfaceRows.length} up`, `- Gateways: ${gatewayRows.filter((x) => x.status_translated === 'Online').length}/${gatewayRows.length} online`, '- Zugriff: read-only MCP; Zertifikat SHA-256-gepinnt', ].join('\n'); } async function services(args) { let rows = (await api('/api/core/service/search')).rows || []; if (args && args.running_only) rows = rows.filter((x) => Number(x.running) === 1); rows.sort((a, b) => String(a.name).localeCompare(String(b.name))); const lines = ['## OPNsense Dienste', '', `Dienste: ${rows.length}`, '', '| Dienst | Beschreibung | Laeuft | Gesperrt |', '|---|---|---:|---:|']; for (const row of rows) lines.push(`| ${escapeCell(row.name)} | ${escapeCell(row.description)} | ${yesNo(row.running)} | ${yesNo(row.locked)} |`); return lines.join('\n'); } async function interfaces(args) { let rows = (await api('/api/interfaces/overview/interfacesInfo')).rows || []; if (args && args.assigned_only) rows = rows.filter((x) => x.identifier); rows.sort((a, b) => String(a.description).localeCompare(String(b.description))); const lines = ['## OPNsense Interfaces', '', `Interfaces: ${rows.length}`, '', '| Name | Geraet | Status | IPv4 | IPv6 | MTU | Medium |', '|---|---|---|---|---|---:|---|']; for (const row of rows) { const ipv4 = (row.ipv4 || []).map((x) => x.ipaddr).join(', ') || '-'; const ipv6 = (row.ipv6 || []).map((x) => x.ipaddr).join(', ') || '-'; lines.push(`| ${escapeCell(row.description || row.identifier || 'Unassigned')} | ${escapeCell(row.device)} | ${escapeCell(row.status)} | ${escapeCell(ipv4)} | ${escapeCell(ipv6)} | ${escapeCell(row.mtu)} | ${escapeCell(row.media)} |`); } return lines.join('\n'); } async function gateways() { const data = await api('/api/routes/gateway/status'); const rows = data.items || []; const lines = ['## OPNsense Gateways', '', `Status: ${data.status || '-'}, Gateways: ${rows.length}`, '', '| Name | Adresse | Status | Verlust | Latenz |', '|---|---|---|---:|---:|']; for (const row of rows) lines.push(`| ${escapeCell(row.name)} | ${escapeCell(row.address)} | ${escapeCell(row.status_translated)} | ${escapeCell(row.loss)} | ${escapeCell(row.delay)} |`); return lines.join('\n'); } async function firewallRules(args) { const params = new URLSearchParams({ current: '1', rowCount: String(MAX_ROWS) }); const search = String((args && args.search) || '').trim(); if (search) params.set('searchPhrase', search); const data = await api('/api/firewall/filter/searchRule?' + params.toString()); const rows = data.rows || []; const lines = [ '## OPNsense Automation-Firewallregeln', '', `Regeln: ${data.total ?? rows.length}${search ? `, Filter: ${search}` : ''}`, '', '> Diese API zeigt nur Regeln aus Firewall > Automation, nicht zwingend alle klassischen GUI-Regeln.', '', '| Beschreibung | Interface | Richtung | Aktion | Protokoll | Quelle | Ziel | Aktiv |', '|---|---|---|---|---|---|---|---:|', ]; for (const row of rows) { lines.push(`| ${escapeCell(row.description)} | ${escapeCell(row.interface)} | ${escapeCell(row.direction)} | ${escapeCell(row.action)} | ${escapeCell(row.protocol)} | ${escapeCell(row.source_net || row.source)} | ${escapeCell(row.destination_net || row.destination)} | ${yesNo(row.enabled)} |`); } if (!rows.length) lines.push('| (keine Automation-Regeln) | | | | | | | |'); return lines.join('\n'); } async function aliases(args) { const params = new URLSearchParams({ current: '1', rowCount: String(MAX_ROWS) }); const search = String((args && args.search) || '').trim(); if (search) params.set('searchPhrase', search); const includeContent = Boolean(args && args.include_content); const data = await api('/api/firewall/alias/searchItem?' + params.toString()); const rows = data.rows || []; const lines = ['## OPNsense Aliase', '', `Aliase: ${data.total ?? rows.length}${search ? `, Filter: ${search}` : ''}`, '', includeContent ? '| Name | Typ | Aktiv | Inhalt |' : '| Name | Typ | Aktiv | Eintraege | Geaendert |', includeContent ? '|---|---|---:|---|' : '|---|---|---:|---:|---|']; for (const row of rows) { if (includeContent) lines.push(`| ${escapeCell(row.name)} | ${escapeCell(row['%type'] || row.type)} | ${yesNo(row.enabled)} | ${escapeCell(row.content || '-')} |`); else lines.push(`| ${escapeCell(row.name)} | ${escapeCell(row['%type'] || row.type)} | ${yesNo(row.enabled)} | ${escapeCell(row.current_items || '-')} | ${escapeCell(row.last_updated || '-')} |`); } return lines.join('\n'); } const TOOLS = [ { name: 'opnsense_status', description: 'Kompakter Zustand von OPNsense, Diensten, Interfaces und Gateways. Lesend.', inputSchema: { type: 'object', properties: {}, additionalProperties: false } }, { name: 'opnsense_services', description: 'Listet OPNsense-Dienste mit Lauf- und Sperrstatus. Lesend.', inputSchema: { type: 'object', properties: { running_only: { type: 'boolean', description: 'Nur laufende Dienste anzeigen.' } }, additionalProperties: false } }, { name: 'opnsense_interfaces', description: 'Listet Interfaces mit Status, IP-Adressen, MTU und Medium. Lesend.', inputSchema: { type: 'object', properties: { assigned_only: { type: 'boolean', description: 'Nur zugewiesene Interfaces anzeigen.' } }, additionalProperties: false } }, { name: 'opnsense_gateways', description: 'Listet Gateways mit Online-Status, Verlust und Latenz. Lesend.', inputSchema: { type: 'object', properties: {}, additionalProperties: false } }, { name: 'opnsense_firewall_rules', description: 'Listet Regeln der OPNsense Firewall-Automation. Zeigt nicht zwingend klassische GUI-Regeln. Lesend.', inputSchema: { type: 'object', properties: { search: { type: 'string', description: 'Optionaler Suchtext.' } }, additionalProperties: false } }, { name: 'opnsense_aliases', description: 'Listet Firewall-Aliase. Inhalte nur explizit mit include_content=true; Credential-Felder werden nie ausgegeben. Lesend.', inputSchema: { type: 'object', properties: { search: { type: 'string', description: 'Optionaler Suchtext.' }, include_content: { type: 'boolean', description: 'Alias-Inhalte anzeigen (Standard false).' } }, 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 buffer = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', (chunk) => { buffer += chunk; let index; while ((index = buffer.indexOf('\n')) >= 0) { const line = buffer.slice(0, index).trim(); buffer = buffer.slice(index + 1); if (line) handle(line); } }); function handle(line) { let message; try { message = JSON.parse(line); } catch { replyError(null, -32700, 'Parse error'); return; } const { id, method, params } = message; if (method === 'notifications/initialized' || (id === undefined && method)) return; if (method === 'initialize') { reply(id, { protocolVersion: (params && params.protocolVersion) || '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'opnsense', version: '1.0.0' } }); return; } if (method === 'ping') { reply(id, {}); return; } if (method === 'tools/list') { reply(id, { tools: TOOLS.map((tool) => ({ ...tool, annotations: { title: tool.name.replace(/_/g, ' '), readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true } })) }); return; } if (method === 'tools/call') { const name = params && params.name; const args = (params && params.arguments) || {}; const dispatch = { opnsense_status: () => status(), opnsense_services: () => services(args), opnsense_interfaces: () => interfaces(args), opnsense_gateways: () => gateways(), opnsense_firewall_rules: () => firewallRules(args), opnsense_aliases: () => aliases(args), }; const fn = dispatch[name]; if (!fn) { reply(id, { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true }); return; } fn().then((text) => reply(id, { content: [{ type: 'text', text }], isError: false })) .catch((error) => reply(id, { content: [{ type: 'text', text: `Interner Fehler: ${error.message || error}` }], isError: true })); return; } replyError(id, -32601, 'Method not found'); }