From 0a568f1640ddf5d20580b76af46fc0bc017d98d9 Mon Sep 17 00:00:00 2001 From: Denozordec Date: Mon, 30 Nov 2026 17:50:41 +0700 Subject: [PATCH] =?UTF-8?q?feat(mcp):=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D1=82=D1=8C=20=D0=BE=D1=82=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20=D1=80=D0=B5=D0=B6=D0=B8=D0=BC=20=D1=88=D0=B8?= =?UTF-8?q?=D1=84=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=BF=D0=B0=D1=80=D1=8B=20=D1=82=D1=83=D0=BD=D0=BD?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/package.json | 2 +- backend/src/modules/mcp/actions.ts | 2 + .../mcp/gre-ikev2-pair-actions.test.ts | 63 ++++++ .../src/modules/mcp/gre-ikev2-pair-actions.ts | 191 ++++++++++++++++++ backend/src/services/gre-ipsec-transport.ts | 25 +++ .../src/services/internet-exchange-plan.ts | 18 +- docs/mcp.md | 2 + 7 files changed, 292 insertions(+), 11 deletions(-) create mode 100644 backend/src/modules/mcp/gre-ikev2-pair-actions.test.ts create mode 100644 backend/src/modules/mcp/gre-ikev2-pair-actions.ts create mode 100644 backend/src/services/gre-ipsec-transport.ts diff --git a/backend/package.json b/backend/package.json index e7a7b47d..98e792de 100644 --- a/backend/package.json +++ b/backend/package.json @@ -7,7 +7,7 @@ "test:mcp:module-completion": "tsx src/services/ipsec-server-init-model.test.ts && tsx src/modules/mcp/ipsec-server-init-actions.test.ts && tsx src/services/wireguard-revision-restore.test.ts && tsx src/modules/mcp/vrf-ticket-runtime.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-pool-dependencies.test.ts && tsx src/services/vrf-production-transition.test.ts && tsx src/services/vrf-production-action-binding.test.ts && tsx src/services/ipsec-revision-restore-model.test.ts && tsx src/modules/mcp/ipsec-revision-actions.test.ts && tsx src/modules/mcp/service-native-progress.test.ts && tsx src/services/ipsec-revision-restore.test.ts && tsx src/services/ipsec-revision-secret.test.ts", "test:mcp:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore", "test:mcp:pg": "node scripts/test-mcp-postgres.mjs", - "test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts src/modules/mcp/gre-ipsec-pair-actions.test.ts", + "test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts src/modules/mcp/gre-ipsec-pair-actions.test.ts src/modules/mcp/gre-ikev2-pair-actions.test.ts", "test:mcp:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics", "test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs", "test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings", diff --git a/backend/src/modules/mcp/actions.ts b/backend/src/modules/mcp/actions.ts index 0eda8939..f1429e04 100644 --- a/backend/src/modules/mcp/actions.ts +++ b/backend/src/modules/mcp/actions.ts @@ -81,6 +81,7 @@ import { registerFirewallActions } from "./firewall-actions.js" import { registerBfdMoveActions } from "./bfd-move-actions.js" import { registerGreMutationActions } from "./gre-mutation-actions.js" import { registerGreIpsecPairActions } from "./gre-ipsec-pair-actions.js" +import { registerGreIke2PairActions } from "./gre-ikev2-pair-actions.js" import { registerIxActions } from "./internet-exchange-actions.js" import { registerGreRevisionActions } from "./gre-revision-actions.js" import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js" @@ -709,6 +710,7 @@ registerFirewallActions(add) registerBfdMoveActions(add) registerGreMutationActions(add) registerGreIpsecPairActions(add) +registerGreIke2PairActions(add) registerIxActions(add) registerGreRevisionActions(add) registerGreNativeServices() diff --git a/backend/src/modules/mcp/gre-ikev2-pair-actions.test.ts b/backend/src/modules/mcp/gre-ikev2-pair-actions.test.ts new file mode 100644 index 00000000..ea8404dc --- /dev/null +++ b/backend/src/modules/mcp/gre-ikev2-pair-actions.test.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { greIpsecPaths } from "../../services/gre-ipsec-transport.js" +import { greIke2SideCommands, greIke2StableCatalogues, validateNewPairSide, verifyGreIke2Create } from "./gre-ikev2-pair-actions.js" +import { redact } from "./security.js" + +const pair = { endpoints: [ + { serverId: 3, greName: "gre-jh-test-home", outerAddress: "192.0.2.3" }, + { serverId: 6, greName: "gre-jh-test-nov", outerAddress: "198.51.100.6" }, +] } +const secret = "ab".repeat(32) +const empty = () => Object.fromEntries(Object.values(greIpsecPaths).map(path => [path, [] as Record[]])) + +test("emits the IX transport suite with a fixed GRE selector and independent identities", () => { + const [left, right] = ([0, 1] as const).map(side => greIke2SideCommands(pair, side, secret)) + assert.equal(left.length, 7) + assert.equal(right.length, 7) + for (const path of [greIpsecPaths.profile, greIpsecPaths.proposal]) { + assert.deepEqual(left.find(command => command.path === path), right.find(command => command.path === path)) + } + assert.equal(left.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "true") + assert.equal(right.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "false") + assert.equal(left.find(command => command.path === greIpsecPaths.identity)?.fields.secret, secret) + assert.equal(right.find(command => command.path === greIpsecPaths.identity)?.fields.secret, secret) + assert.equal(JSON.stringify(redact({ ipsecSecret: secret, commands: left })).includes(secret), false) + const leftPolicy = left.find(command => command.path === greIpsecPaths.policy)!.fields + const rightPolicy = right.find(command => command.path === greIpsecPaths.policy)!.fields + assert.deepEqual([leftPolicy["src-address"], leftPolicy["dst-address"], leftPolicy.protocol, leftPolicy.level, leftPolicy.tunnel], + ["192.0.2.3/32", "198.51.100.6/32", "gre", "require", "false"]) + assert.equal(rightPolicy["src-address"], leftPolicy["dst-address"]) + assert.equal(rightPolicy["dst-address"], leftPolicy["src-address"]) + assert.deepEqual(left.slice(0, 2).map(command => command.fields["ipsec-policy"]), ["in,none", "out,none"]) +}) + +test("rejects existing objects and opposing IPv4 selectors without touching other peers", () => { + const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty() + catalogs[greIpsecPaths.policy].push({ ".id": "*A", template: "true", protocol: "all", "src-address": "0.0.0.0/0", "dst-address": "0.0.0.0/0" }) + catalogs[greIpsecPaths.peer].push({ ".id": "*B", address: "0.0.0.0/0", "exchange-mode": "ike2" }) + assert.doesNotThrow(() => validateNewPairSide(pair, 0, catalogs, commands)) + catalogs[greIpsecPaths.policy].push({ ".id": "*C", "src-address": "192.0.2.0/24", "dst-address": "198.51.100.0/24", protocol: "all" }) + assert.throws(() => validateNewPairSide(pair, 0, catalogs, commands), /перекрывает GRE/) + catalogs[greIpsecPaths.policy].pop() + catalogs[greIpsecPaths.peer].push({ ".id": "*D", address: "198.51.100.6/32", "exchange-mode": "ike2" }) + assert.throws(() => validateNewPairSide(pair, 0, catalogs, commands), /Уже настроен IKEv2 peer/) + catalogs[greIpsecPaths.peer].pop() + catalogs[greIpsecPaths.filter].push({ ".id": "*E", comment: commands[0].fields.comment! }) + assert.throws(() => validateNewPairSide(pair, 0, catalogs, commands), /уже присутствуют/) +}) + +test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => { + const [command] = greIke2SideCommands(pair, 0, secret), before = empty() + before[greIpsecPaths.filter] = [{ ".id": "*A", chain: "input", action: "accept", packets: "19" }] + const after = structuredClone(before) + after[greIpsecPaths.filter][0].packets = "20" + after[greIpsecPaths.filter].unshift({ ...command.fields, ".id": "*B", packets: "0" }) + const verified = () => verifyGreIke2Create(greIke2StableCatalogues(before), greIke2StableCatalogues(after), command, "*B", "*A") + assert.equal(verified(), true) + after[greIpsecPaths.filter].reverse() + assert.equal(verified(), false) + after[greIpsecPaths.filter].reverse() + after[greIpsecPaths.filter][1].action = "drop" + assert.equal(verified(), false) +}) diff --git a/backend/src/modules/mcp/gre-ikev2-pair-actions.ts b/backend/src/modules/mcp/gre-ikev2-pair-actions.ts new file mode 100644 index 00000000..2156c151 --- /dev/null +++ b/backend/src/modules/mcp/gre-ikev2-pair-actions.ts @@ -0,0 +1,191 @@ +import { randomBytes } from "node:crypto" +import { isIP } from "node:net" +import { z } from "zod" +import { greMutationProof, greTarget, readGreMutationState } from "../../services/gre-mutation-state.js" +import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "../../services/gre-ipsec-transport.js" +import { inIxNetwork } from "../../services/internet-exchange-plan.js" +import { ipsecPeerDeleteRows } from "../../services/ipsec-peer-delete.js" +import { IpsecServerInitExecutionError } from "../../services/ipsec-server-init.js" +import { observedBoolean } from "../../services/ospf-observed-values.js" +import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import type { add } from "./actions.js" +import type { ChangeEvidence } from "./action-types.js" +import { greMutationProtectionObjects } from "./gre-mutation-actions.js" +import { routerClient } from "./resources.js" +import { fingerprint, McpError, privateFingerprinter } from "./security.js" +import { registerMcpService } from "./service-registry.js" + +const operation = "network.gre.ikev2_pair.configure" +const endpoint = z.object({ + serverId: z.number().int().positive().safe(), + greName: z.string().trim().min(1).max(100), + outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"), +}).strict() +const schema = z.object({ endpoints: z.array(endpoint).length(2) }).strict() +const stepSchema = schema.extend({ side: z.union([z.literal(0), z.literal(1)]), ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/), beforeFingerprint: z.string() }) +type Pair = z.infer +type Side = 0 | 1 +type Fields = Record +type Catalogue = Record +const sides = [0, 1] as const +const paths = Object.values(greIpsecPaths) +const runtimeFields: Readonly>> = { + [greIpsecPaths.filter]: new Set(["bytes", "packets"]), + [greIpsecPaths.policy]: new Set(["active", "ph2-count", "ph2-state"]), +} + +function target(input: Pair): ChangeEvidence["target"] { + const [first, second] = input.endpoints + if (first.serverId === second.serverId || first.outerAddress === second.outerAddress) { + throw new McpError("INVALID_INPUT", "Требуются два разных CHR и два разных внешних адреса") + } + return { scope: "servers", serverIds: [first.serverId, second.serverId] } +} + +const nameFor = (input: Pair) => "mm-gre-ike2-" + fingerprint([...input.endpoints].sort((a, b) => a.serverId - b.serverId)).slice(0, 14) +export function greIke2SideCommands(input: Pair, side: Side, secret: string) { + const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress + const [inbound, outbound] = greIpsecPlaintextDrops(local, remote) + const fields = greIke2TransportFields(name, local, remote, side === 0, secret, false) + return [ + { path: greIpsecPaths.filter, fields: { ...inbound, comment: `${name}:plain-in` } }, + { path: greIpsecPaths.filter, fields: { ...outbound, comment: `${name}:plain-out` } }, + ...(["profile", "proposal", "peer"] as const).map(kind => ({ path: greIpsecPaths[kind], fields: fields[kind] })), + { path: greIpsecPaths.identity, fields: { ...fields.identity, comment: `${name}:identity` } }, + { path: greIpsecPaths.policy, fields: { ...fields.policy, comment: `${name}:policy` } }, + ] satisfies Array<{ path: string; fields: Fields }> +} + +function includesIp(selector: string | undefined, address: string) { + if (!selector) return true + const [host, length] = selector.split("/") + if (isIP(host) === 6) return false + if (isIP(host) !== 4 || (length !== undefined && (!/^\d+$/.test(length) || Number(length) > 32))) { + throw new McpError("STATE_UNAVAILABLE", "Не подтверждён адресный селектор IPsec", 502) + } + return inIxNetwork(`${host}/${length ?? "32"}`, address) +} + +export function validateNewPairSide(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType) { + const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress + if (commands.some(command => catalogs[command.path].some(row => row.name === name || ("comment" in command.fields && row.comment === command.fields.comment)))) { + throw new McpError("STATE_CONFLICT", "Объекты этой пары IKEv2 уже присутствуют. Требуется сверка обеих сторон", 409) + } + if (catalogs[greIpsecPaths.peer].some(row => row["exchange-mode"] === "ike2" && observedBoolean(row.disabled) !== true && + [remote, `${remote}/32`].includes(row.address) && (!row["local-address"] || ["0.0.0.0", local].includes(row["local-address"])))) { + throw new McpError("DEPENDENCY_CONFLICT", "Уже настроен IKEv2 peer для этих внешних адресов", 409) + } + if (catalogs[greIpsecPaths.policy].some(row => observedBoolean(row.template) !== true && observedBoolean(row.disabled) !== true && + [undefined, "", "all", "0", "255", "gre", "47"].includes(row.protocol) && + ((includesIp(row["src-address"], local) && includesIp(row["dst-address"], remote)) || + (includesIp(row["src-address"], remote) && includesIp(row["dst-address"], local))))) { + throw new McpError("DEPENDENCY_CONFLICT", "Существующая IPsec policy перекрывает GRE между выбранными адресами", 409) + } +} + +export function greIke2StableCatalogues(catalogs: Catalogue) { + return Object.fromEntries(paths.map(path => [path, catalogs[path] + .filter(row => observedBoolean(row.dynamic) !== true) + .map(row => Object.fromEntries(Object.entries(row).filter(([key]) => !runtimeFields[path]?.has(key))))])) +} + +function matches(expected: Fields, observed: Fields) { + return Object.entries(expected).every(([key, value]) => { + const actual = observed[key] + if (["disabled", "tunnel", "passive"].includes(key)) return (observedBoolean(actual) ?? (actual === undefined ? false : null)) === observedBoolean(value) + if (["address", "src-address", "dst-address"].includes(key)) return actual?.replace(/\/32$/, "") === value.replace(/\/32$/, "") + if (key === "protocol" && value === "gre") return actual === "gre" || actual === "47" + return actual === value + }) +} + +export function verifyGreIke2Create(before: Catalogue, after: Catalogue, command: { path: string; fields: Fields }, nativeId: string | undefined, first: string | undefined) { + const created = after[command.path].find(row => row[".id"] === nativeId) + return !!created && !before[command.path].some(row => row[".id"] === nativeId) && matches(command.fields, created) && + (first === undefined || after[command.path][0] === created) && + fingerprint({ ...after, [command.path]: after[command.path].filter(row => row !== created) }) === fingerprint(before) +} + +async function readSide(input: Pair, side: Side) { + const local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0] + const { server, client } = await routerClient(local.serverId) + const mutation = { operation: "update" as const, name: local.greName, fields: { ipsecSecret: "" } } + const readCatalogues = async () => Object.fromEntries(await Promise.all(paths.map(async path => + [path, ipsecPeerDeleteRows(await client.get(path, 10000, undefined, 1048576))] as const))) + const [gre, catalogs] = await Promise.all([readGreMutationState(server, mutation), readCatalogues()]) + const row = greTarget(mutation, gre) + if (!row || observedBoolean(row.dynamic) === true || observedBoolean(row.disabled) !== true || observedBoolean(row["allow-fast-path"]) !== false || + row["local-address"] !== local.outerAddress || row["remote-address"] !== remote.outerAddress || row["ipsec-secret"] !== "") { + throw new McpError("STATE_CONFLICT", `На сервере ${local.serverId} требуется статический отключённый GRE с указанными адресами, без FastPath и встроенного PSK`, 409) + } + const seal = await privateFingerprinter("mcp-gre-ikev2-pair-v1") + const proof = seal(fingerprint({ gre: greMutationProof(gre), catalogs: greIke2StableCatalogues(catalogs) })) + return { server, client, gre, catalogs, readCatalogues, proof } +} + +export function registerGreIke2PairActions(register: typeof add) { + registerMcpService(operation, { + current: async raw => { + const input = stepSchema.parse(raw) + return await Promise.all(sides.map(async side => (await readSide(input, side)).proof)) + }, + execute: async raw => { + const input = stepSchema.parse(raw), side = input.side, state = await readSide(input, side) + if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409) + const commands = greIke2SideCommands(input, side, input.ipsecSecret) + validateNewPairSide(input, side, state.catalogs, commands) + let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0 + for (const command of commands) { + let dispatched = false + try { + const first = command.path === greIpsecPaths.filter ? before[command.path][0]?.[".id"] : undefined + const ack = await state.client.put(command.path, { ...command.fields, ...(first ? { "place-before": first } : {}) }, 10000, async () => { + await assertVerifiedConfigurationAccess() + if (fingerprint((await routerClient(Number(state.server.id))).server) !== fingerprint(state.server)) throw new McpError("STATE_CONFLICT", "Источник RouterOS изменился перед записью", 409) + if (fingerprint(greIke2StableCatalogues(await state.readCatalogues())) !== fingerprint(before)) throw new McpError("STATE_CONFLICT", "IPsec изменился перед записью", 409) + dispatched = true + }) + confirmed++ + const after = greIke2StableCatalogues(await state.readCatalogues()) + if (!verifyGreIke2Create(before, after, command, ack?.[".id"], first)) { + throw new McpError("VERIFICATION_FAILED", "Ответ RouterOS не подтверждает точное добавление объекта", 502) + } + before = after + verified++ + } catch (error) { + if (!dispatched && !confirmed && error instanceof McpError) throw error + throw new IpsecServerInitExecutionError(error instanceof McpError && error.code === "VERIFICATION_FAILED" || !dispatched ? "VERIFICATION_FAILED" : "MUTATION_OUTCOME_UNKNOWN", + `Настройка IKEv2 остановлена на ${command.path}. GRE оставлен отключённым, требуется сверка перед повтором.`, confirmed, verified, commands.length) + } + } + const after = await readSide(input, side) + if (fingerprint(greIke2StableCatalogues(after.catalogs)) !== fingerprint(before)) throw new IpsecServerInitExecutionError("VERIFICATION_FAILED", "Состояние IPsec изменилось после последней команды", confirmed, verified, commands.length) + return { verified: true, commandCount: commands.length, afterFingerprint: after.proof, greEnabled: false, forwardingVerified: false } + }, + verify: async (raw, result) => { + const input = stepSchema.parse(raw) + const receipt = result as { verified?: boolean; afterFingerprint?: string } | null + return receipt?.verified === true && receipt.afterFingerprint === (await readSide(input, input.side)).proof + }, + }) + register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, { + target: raw => target(schema.parse(raw)), + prepare: async raw => { + const input = schema.parse(raw), scope = target(input), ipsecSecret = randomBytes(32).toString("hex") + const before = await Promise.all(sides.map(side => readSide(input, side))) + const steps = sides.map(side => { + const commands = greIke2SideCommands(input, side, ipsecSecret) + validateNewPairSide(input, side, before[side].catalogs, commands) + return { kind: "service" as const, service: operation, input: { ...input, side, ipsecSecret, beforeFingerprint: before[side].proof } } + }) + const objects = (await Promise.all(before.map(state => greMutationProtectionObjects(Number(state.server.id), state.gre)))).flat() + return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: 14, requiresHuman: true, + warnings: [ + `На каждом CHR создаются выделенные объекты ${nameFor(input)}: profile, proposal, peer, identity, статическая policy GRE в транспортном режиме и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`, + "Существующие GRE остаются отключёнными. PSK автоматически создаётся для пары. Глобальные IPsec-профили не меняются. Для IKE/ESP требуются разрешения действующего firewall.", + "Планы проверяются и применяются последовательно. При сбое требуется сверить уже добавленные объекты до повтора. IPsec SA и прохождение трафика проверяются после отдельного включения GRE.", + ], + } + }, + }) +} diff --git a/backend/src/services/gre-ipsec-transport.ts b/backend/src/services/gre-ipsec-transport.ts new file mode 100644 index 00000000..10d3d929 --- /dev/null +++ b/backend/src/services/gre-ipsec-transport.ts @@ -0,0 +1,25 @@ +export const greIpsecPaths = { + filter: "/ip/firewall/filter", + profile: "/ip/ipsec/profile", + proposal: "/ip/ipsec/proposal", + peer: "/ip/ipsec/peer", + identity: "/ip/ipsec/identity", + policy: "/ip/ipsec/policy", +} as const + +export function greIpsecPlaintextDrops(local: string, remote: string) { + return [ + { chain: "input", protocol: "gre", "src-address": `${remote}/32`, "dst-address": `${local}/32`, "ipsec-policy": "in,none", action: "drop" }, + { chain: "output", protocol: "gre", "src-address": `${local}/32`, "dst-address": `${remote}/32`, "ipsec-policy": "out,none", action: "drop" }, + ] +} + +export function greIke2TransportFields(name: string, local: string, remote: string, passive: boolean, secret: string, disabled: boolean) { + return { + profile: { name, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" }, + proposal: { name, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" }, + peer: { name, address: `${remote}/32`, "local-address": local, profile: name, "exchange-mode": "ike2", passive: String(passive) }, + identity: { peer: name, "auth-method": "pre-shared-key", secret, disabled: String(disabled) }, + policy: { peer: name, "src-address": `${local}/32`, "dst-address": `${remote}/32`, protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: name }, + } +} diff --git a/backend/src/services/internet-exchange-plan.ts b/backend/src/services/internet-exchange-plan.ts index 0f61aa44..44f67aba 100644 --- a/backend/src/services/internet-exchange-plan.ts +++ b/backend/src/services/internet-exchange-plan.ts @@ -3,6 +3,7 @@ import { createHash } from "node:crypto" import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange" import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js" import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js" +import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "./gre-ipsec-transport.js" export class IxConflict extends Error { constructor(message: string, readonly statusCode = 409) { super(message) } @@ -282,8 +283,9 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio result.push({ serverId: site.serverId, path, fields: nameOnly ? fields : { ...fields, comment: namespace + ":" + key } }) } const protectGre = (binding: IxSite["interfaces"][number], key: string) => { - add("/ip/firewall/filter", "gre-in-" + key, { chain: "input", protocol: "gre", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!), "ipsec-policy": "in,none", action: "drop" }) - add("/ip/firewall/filter", "gre-out-" + key, { chain: "output", protocol: "gre", "src-address": host(binding.localEndpoint!), "dst-address": host(binding.endpoint!), "ipsec-policy": "out,none", action: "drop" }) + const [inbound, outbound] = greIpsecPlaintextDrops(binding.localEndpoint!, binding.endpoint!) + add(greIpsecPaths.filter, "gre-in-" + key, inbound) + add(greIpsecPaths.filter, "gre-out-" + key, outbound) } const dropInterface = ixDiscardInterface(id) for (const [index, binding] of site.interfaces.entries()) { @@ -296,14 +298,10 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio if (gre) { const transport = namespace + "-" + key protectGre(binding, key) - add("/ip/ipsec/profile", key, { name: transport, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" }) - add("/ip/ipsec/proposal", key, { name: transport, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" }) - add("/ip/ipsec/peer", key, { name: transport, address: host(binding.endpoint!), "local-address": binding.localEndpoint!, - profile: transport, "exchange-mode": "ike2", passive: "true" }) - add("/ip/ipsec/identity", "gre-identity-" + key, { peer: transport, "auth-method": "pre-shared-key", - secret: "ix-credential:" + gre.credentialId, disabled: String(!binding.linux!.enabled) }) - add("/ip/ipsec/policy", "gre-policy-" + key, { peer: transport, "src-address": host(binding.localEndpoint!), - "dst-address": host(binding.endpoint!), protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: transport }) + const fields = greIke2TransportFields(transport, binding.localEndpoint!, binding.endpoint!, true, "ix-credential:" + gre.credentialId, !binding.linux!.enabled) + for (const kind of ["profile", "proposal", "peer"] as const) add(greIpsecPaths[kind], key, fields[kind]) + add(greIpsecPaths.identity, "gre-identity-" + key, fields.identity) + add(greIpsecPaths.policy, "gre-policy-" + key, fields.policy) add("/interface/gre", "gre-" + key, { name: binding.name, "local-address": binding.localEndpoint!, "remote-address": binding.endpoint!, "allow-fast-path": "false", disabled: String(!binding.linux!.enabled) }) } diff --git a/docs/mcp.md b/docs/mcp.md index c6cea230..01a79a06 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -137,6 +137,8 @@ npm --prefix backend run mcp:stdio Применение создаёт две отключённые стороны. Сверьте обе через `mm_gre_state_get`, затем включите их через `mm_gre_tunnel_update_plan` и проверьте IPsec и связность. При ошибке сверяйте обе стороны перед следующей операцией. Первая сторона может остаться созданной и отключённой. +Для выделенных профилей, как в управляемом GRE/IPsec на IX, используйте `mm_gre_ikev2_pair_configure_plan` с допуском `network.gre.ikev2_pair.configure`. Ему нужны два существующих отключённых GRE с выключенным FastPath и пустым `ipsec-secret`. Передайте в `endpoints` по одному объекту с `serverId`, `greName` и локальным `outerAddress`. Первая сторона отвечает на IKEv2, вторая инициирует соединение. Manager создаёт отдельные профили, общий PSK для пары и статические политики транспортного режима только для GRE между этими адресами. После проверки плана включите GRE отдельно и проверьте SA и связность. Если ранее для GRE был задан встроенный PSK, очистите его через `mm_gre_tunnel_update_plan` с `clearIpsecSecret: true` при отключённом интерфейсе. + ### Разбор отказа и проверка резерва 1. Зафиксируйте источник, назначение, ожидаемый выход и максимальный допустимый перерыв. Проверьте доступ через `mm_capabilities_get` и давность наблюдений через `mm_telemetry_health_get`. Обрыв экспорта NetFlow оставляет пробел в наблюдениях.