feat(mcp): добавить отдельный режим шифрования для пары туннелей
Docker images / prepare-release (push) Successful in 15s
Docker images / backend-test (push) Successful in 11m43s
Docker images / frontend-image (push) Successful in 2m34s
Docker images / updater-image (push) Successful in 54s
Docker images / netflow-agent-image (push) Successful in 40s
Docker images / backend-image (push) Successful in 2m29s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 15s
Docker images / backend-test (push) Successful in 11m43s
Docker images / frontend-image (push) Successful in 2m34s
Docker images / updater-image (push) Successful in 54s
Docker images / netflow-agent-image (push) Successful in 40s
Docker images / backend-image (push) Successful in 2m29s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
This commit is contained in:
1 parent
5233a9f194
commit
0a568f1640
7 files changed
+292
-11
No files matched your search
@@ -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()
|
||||
|
||||
@@ -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<string, string>[]]))
|
||||
|
||||
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)
|
||||
})
|
||||
@@ -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<typeof schema>
|
||||
type Side = 0 | 1
|
||||
type Fields = Record<string, string>
|
||||
type Catalogue = Record<string, Fields[]>
|
||||
const sides = [0, 1] as const
|
||||
const paths = Object.values(greIpsecPaths)
|
||||
const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = {
|
||||
[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<typeof greIke2SideCommands>) {
|
||||
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<unknown>(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<Fields>(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.",
|
||||
],
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user