fix(mcp): продолжать настройку туннелей со штатным набором алгоритмов

This commit is contained in:
Denozordec committed 2026-11-30 19:28:43 +07:00
1 parent 0a568f1640
commit ca4ad07727
3 files changed
+139 -36

No files matched your search

@@ -1,7 +1,7 @@
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 { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js"
import { redact } from "./security.js"
const pair = { endpoints: [
@@ -13,11 +13,10 @@ const empty = () => Object.fromEntries(Object.values(greIpsecPaths).map(path =>
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.length, 6)
assert.equal(right.length, 6)
assert.equal(left.some(command => command.path === greIpsecPaths.proposal), false)
assert.deepEqual(left.find(command => command.path === greIpsecPaths.profile), right.find(command => command.path === greIpsecPaths.profile))
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)
@@ -28,6 +27,7 @@ test("emits the IX transport suite with a fixed GRE selector and independent ide
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(leftPolicy.proposal, "default")
assert.equal(rightPolicy["dst-address"], leftPolicy["src-address"])
assert.deepEqual(left.slice(0, 2).map(command => command.fields["ipsec-policy"]), ["in,none", "out,none"])
})
@@ -36,15 +36,42 @@ test("rejects existing objects and opposing IPv4 selectors without touching othe
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))
assert.doesNotThrow(() => planGreIke2Side(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/)
assert.throws(() => planGreIke2Side(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/)
assert.throws(() => planGreIke2Side(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), /уже присутствуют/)
assert.throws(() => planGreIke2Side(pair, 0, catalogs, commands), /изменённый объект/)
})
test("checks the existing defaults for a common encrypted suite and equal PFS", () => {
const catalogs = empty()
const first = { ".id": "*A", name: "default", "pfs-group": "modp1024", "enc-algorithms": "3des,aes-128-cbc,aes-256-cbc", "auth-algorithms": "sha1,sha256" }
catalogs[greIpsecPaths.proposal].push(first)
assert.equal(greIke2DefaultProposal(catalogs), first)
const second = { ...first, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256" }
assert.doesNotThrow(() => validateGreIke2Defaults(first, second))
assert.throws(() => validateGreIke2Defaults(first, { ...second, "pfs-group": "modp2048" }), /несовместимы/)
assert.throws(() => validateGreIke2Defaults(first, { ...second, "enc-algorithms": "null" }), /несовместимы/)
})
test("resumes a partial side and changes only the verified old test policy's proposal", () => {
const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty()
const name = commands.find(command => command.path === greIpsecPaths.profile)!.fields.name!
for (const [index, command] of commands.entries()) catalogs[command.path].push({ ...command.fields, ".id": `*${index + 1}` })
const [policy] = catalogs[greIpsecPaths.policy]
policy.proposal = name
const [patch] = planGreIke2Side(pair, 0, catalogs, commands)
assert.deepEqual(patch, { path: greIpsecPaths.policy, id: policy[".id"], fields: { proposal: "default" } })
const after = structuredClone(catalogs)
delete after[greIpsecPaths.policy][0].proposal
assert.equal(verifyGreIke2Update(catalogs, after, patch), true)
assert.deepEqual(planGreIke2Side(pair, 0, after, commands), [])
after[greIpsecPaths.policy][0].level = "use"
assert.equal(verifyGreIke2Update(catalogs, after, patch), false)
})
test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => {
+101 -25
View File
@@ -27,11 +27,12 @@ type Pair = z.infer<typeof schema>
type Side = 0 | 1
type Fields = Record<string, string>
type Catalogue = Record<string, Fields[]>
type RouterWrite = { path: string; fields: Fields; id?: string }
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"]),
[greIpsecPaths.policy]: new Set(["active", "invalid", "ph2-count", "ph2-state"]),
}
function target(input: Pair): ChangeEvidence["target"] {
@@ -50,9 +51,9 @@ export function greIke2SideCommands(input: Pair, side: Side, secret: string) {
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] })),
...(["profile", "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` } },
{ path: greIpsecPaths.policy, fields: { ...fields.policy, proposal: "default", comment: `${name}:policy` } },
] satisfies Array<{ path: string; fields: Fields }>
}
@@ -66,21 +67,59 @@ function includesIp(selector: string | undefined, address: string) {
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)
function ownedRows(catalogs: Catalogue, command: RouterWrite) {
return catalogs[command.path].filter(row => command.fields.comment ? row.comment === command.fields.comment : row.name === command.fields.name)
}
export function greIke2DefaultProposal(catalogs: Catalogue) {
const rows = catalogs[greIpsecPaths.proposal].filter(row => row.name === "default")
const row = rows[0]
if (rows.length !== 1 || observedBoolean(row.disabled) === true || !row["pfs-group"] || !row["enc-algorithms"] || row["auth-algorithms"] === undefined) {
throw new McpError("STATE_UNAVAILABLE", "Не подтверждены действующие параметры IPsec proposal default", 502)
}
if (catalogs[greIpsecPaths.peer].some(row => row["exchange-mode"] === "ike2" && observedBoolean(row.disabled) !== true &&
return row
}
export function validateGreIke2Defaults(first: Fields, second: Fields) {
const list = (row: Fields, field: string) => row[field].split(",").map(value => value.trim())
const shared = (field: string) => list(first, field).filter(value => list(second, field).includes(value))
const encryption = shared("enc-algorithms").filter(value => !!value && value !== "null")
const compatible = first["pfs-group"] === second["pfs-group"] && encryption.some(value => value.endsWith("-gcm") || value === "chacha20-poly1305" || shared("auth-algorithms").some(auth => !!auth && auth !== "null"))
if (!compatible || (list(first, "enc-algorithms").includes("null") && list(second, "enc-algorithms").includes("null"))) {
throw new McpError("DEPENDENCY_CONFLICT", "IPsec proposal default на двух CHR несовместимы или допускают GRE без шифрования", 409)
}
}
export function planGreIke2Side(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>): RouterWrite[] {
const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress
if (catalogs[greIpsecPaths.peer].some(row => row.name !== name && 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 &&
if (catalogs[greIpsecPaths.policy].some(row => row.comment !== `${name}:policy` && 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)
}
return commands.flatMap<RouterWrite>(command => {
const found = ownedRows(catalogs, command), row = found[0]
if (!row) return [command]
if (found.length === 1 && observedBoolean(row.dynamic) !== true && observedBoolean(row.builtin) !== true && observedBoolean(row.disabled) !== true) {
if (matches(command.fields, row)) {
if (command.path === greIpsecPaths.filter && catalogs[command.path].slice(0, catalogs[command.path].indexOf(row)).some(previous =>
observedBoolean(previous.dynamic) !== true && observedBoolean(previous.disabled) !== true && previous.chain === row.chain && previous.action !== "drop" &&
[undefined, "", "all", "0", "255", "gre", "47"].includes(previous.protocol) && !previous["ipsec-policy"]?.endsWith(",ipsec"))) {
throw new McpError("DEPENDENCY_CONFLICT", "Правило против незашифрованного GRE находится после правила, которое может пропустить его", 409)
}
return []
}
if (command.path === greIpsecPaths.policy && matches({ ...command.fields, proposal: name }, row)) {
return [{ path: command.path, id: row[".id"], fields: { proposal: "default" } }]
}
}
throw new McpError("STATE_CONFLICT", `Пара IKEv2 имеет неоднозначный или изменённый объект в ${command.path}`, 409)
})
}
export function greIke2StableCatalogues(catalogs: Catalogue) {
@@ -95,10 +134,38 @@ function matches(expected: Fields, observed: Fields) {
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"
if (key === "proposal" && value === "default") return actual === undefined || actual === "default"
return actual === value
})
}
export function verifyGreIke2Update(before: Catalogue, after: Catalogue, command: RouterWrite) {
const source = before[command.path].find(row => row[".id"] === command.id)
const observed = after[command.path].find(row => row[".id"] === command.id)
if (!source || !observed || !matches(command.fields, observed)) return false
const projected = { ...source }
for (const key of Object.keys(command.fields)) {
if (observed[key] === undefined) delete projected[key]
else projected[key] = observed[key]
}
return fingerprint({ ...before, [command.path]: before[command.path].map(row => row === source ? projected : row) }) === fingerprint(after)
}
function pairSecret(input: Pair, sides: Catalogue[]) {
const name = nameFor(input)
const identities = sides.flatMap(catalogs => catalogs[greIpsecPaths.identity].filter(row => row.comment === `${name}:identity`))
const values = new Set(identities.map(row => row.secret))
if (values.size === 0) return randomBytes(32).toString("hex")
const [value] = values
if (values.size !== 1 || typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) throw new McpError("STATE_CONFLICT", "Не подтверждён общий PSK частично настроенной пары", 409)
return value
}
function completedPairProof(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>) {
if (planGreIke2Side(input, side, catalogs, commands).length !== 0) throw new McpError("VERIFICATION_FAILED", "IKEv2 остался настроен не полностью", 502)
return fingerprint({ proposal: greIke2DefaultProposal(catalogs), objects: commands.map(command => ({ path: command.path, id: ownedRows(catalogs, command)[0][".id"] })) })
}
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) &&
@@ -132,22 +199,26 @@ export function registerGreIke2PairActions(register: typeof add) {
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)
const desired = greIke2SideCommands(input, side, input.ipsecSecret)
const commands = planGreIke2Side(input, side, state.catalogs, desired)
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 () => {
const fence = 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
})
}
const ack = command.id
? await state.client.patch<Fields>(`${command.path}/${encodeURIComponent(command.id)}`, command.fields, 10000, fence)
: await state.client.put<Fields>(command.path, { ...command.fields, ...(first ? { "place-before": first } : {}) }, 10000, fence)
confirmed++
const after = greIke2StableCatalogues(await state.readCatalogues())
if (!verifyGreIke2Create(before, after, command, ack?.[".id"], first)) {
const exact = command.id ? verifyGreIke2Update(before, after, command) : verifyGreIke2Create(before, after, command, ack?.[".id"], first)
if (!exact) {
throw new McpError("VERIFICATION_FAILED", "Ответ RouterOS не подтверждает точное добавление объекта", 502)
}
before = after
@@ -159,31 +230,36 @@ export function registerGreIke2PairActions(register: typeof add) {
}
}
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 }
const afterFingerprint = completedPairProof(input, side, after.catalogs, desired)
return { verified: true, commandCount: commands.length, afterFingerprint, 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
return receipt?.verified === true && receipt.afterFingerprint === completedPairProof(input, input.side,
(await readSide(input, input.side)).catalogs, greIke2SideCommands(input, input.side, input.ipsecSecret))
},
})
register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, {
version: 2,
target: raw => target(schema.parse(raw)),
prepare: async raw => {
const input = schema.parse(raw), scope = target(input), ipsecSecret = randomBytes(32).toString("hex")
const input = schema.parse(raw), scope = target(input)
const before = await Promise.all(sides.map(side => readSide(input, side)))
const catalogs = before.map(state => state.catalogs)
validateGreIke2Defaults(greIke2DefaultProposal(catalogs[0]), greIke2DefaultProposal(catalogs[1]))
const ipsecSecret = pairSecret(input, catalogs)
const changes = sides.map(side => planGreIke2Side(input, side, catalogs[side], greIke2SideCommands(input, side, ipsecSecret)))
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 writes = changes[side].map(command => ({ path: command.path, id: command.id, action: command.id ? "update" : "create" }))
return { kind: "service" as const, service: operation, input: { ...input, side, ipsecSecret, beforeFingerprint: before[side].proof, writes } }
})
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,
return { target: scope, objects, snapshots: [], before: before.map(state => state.proof), steps, mutationCost: Math.max(1, changes.flat().length), requiresHuman: true,
warnings: [
`На каждом CHR создаются выделенные объекты ${nameFor(input)}: profile, proposal, peer, identity, статическая policy GRE в транспортном режиме и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`,
"Существующие GRE остаются отключёнными. PSK автоматически создаётся для пары. Глобальные IPsec-профили не меняются. Для IKE/ESP требуются разрешения действующего firewall.",
"Планы проверяются и применяются последовательно. При сбое требуется сверить уже добавленные объекты до повтора. IPsec SA и прохождение трафика проверяются после отдельного включения GRE.",
`На каждом CHR настраиваются выделенные объекты ${nameFor(input)}: profile, peer, identity, транспортная policy GRE с proposal default и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`,
"GRE остаются отключёнными. Proposal default используется после проверки совместимости и не изменяется. Для IKE/ESP требуются разрешения действующего firewall.",
"Ранее созданные объекты пары переиспользуются только при совпадении параметров. У старой политики пары разрешена смена proposal на default. IPsec SA проверяется после отдельного включения GRE.",
],
}
},
+1 -1
View File
@@ -137,7 +137,7 @@ 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` при отключённом интерфейсе.
Для выделенных профилей, как в управляемом 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 между этими адресами. Политики используют существующие proposal `default` после проверки их совместимости. Повторный план сверяет и переиспользует совпадающие объекты пары, а у проверенной политики предыдущей версии переключает только proposal. После проверки плана включите GRE отдельно и проверьте SA и связность. Если ранее для GRE был задан встроенный PSK, очистите его через `mm_gre_tunnel_update_plan` с `clearIpsecSecret: true` при отключённом интерфейсе.
### Разбор отказа и проверка резерва