Compare commits

..
2 Commits
Author SHA1 Message Date
Denozordec ea13365f37 fix(mcp): принимать перечень команд при выполнении плана туннеля
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m46s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 38s
Docker images / backend-image (push) Successful in 2m25s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 20:00:42 +07:00
Denozordec 8a962c1984 fix(mcp): продолжать настройку туннелей со штатным набором алгоритмов
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m34s
Docker images / frontend-image (push) Successful in 2m23s
Docker images / updater-image (push) Successful in 46s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / backend-image (push) Successful in 2m8s
Docker images / publish-release (push) Successful in 15s
Docker images / notify-webhook (push) Successful in 2s
2026-11-30 19:28:43 +07:00
3 changed files with 172 additions and 42 deletions

No files matched your search

@@ -1,7 +1,7 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import test from "node:test" import test from "node:test"
import { greIpsecPaths } from "../../services/gre-ipsec-transport.js" import { greIpsecPaths } from "../../services/gre-ipsec-transport.js"
import { greIke2SideCommands, greIke2StableCatalogues, validateNewPairSide, verifyGreIke2Create } from "./gre-ikev2-pair-actions.js" import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, greIke2StepInput, greIke2StepSchema, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } from "./gre-ikev2-pair-actions.js"
import { redact } from "./security.js" import { redact } from "./security.js"
const pair = { endpoints: [ 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", () => { 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)) const [left, right] = ([0, 1] as const).map(side => greIke2SideCommands(pair, side, secret))
assert.equal(left.length, 7) assert.equal(left.length, 6)
assert.equal(right.length, 7) assert.equal(right.length, 6)
for (const path of [greIpsecPaths.profile, greIpsecPaths.proposal]) { assert.equal(left.some(command => command.path === greIpsecPaths.proposal), false)
assert.deepEqual(left.find(command => command.path === path), right.find(command => command.path === path)) 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(left.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "true")
assert.equal(right.find(command => command.path === greIpsecPaths.peer)?.fields.passive, "false") 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(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], 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"]) ["192.0.2.3/32", "198.51.100.6/32", "gre", "require", "false"])
assert.equal(rightPolicy["src-address"], leftPolicy["dst-address"]) assert.equal(rightPolicy["src-address"], leftPolicy["dst-address"])
assert.equal(leftPolicy.proposal, "default")
assert.equal(rightPolicy["dst-address"], leftPolicy["src-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"]) assert.deepEqual(left.slice(0, 2).map(command => command.fields["ipsec-policy"]), ["in,none", "out,none"])
}) })
@@ -36,15 +36,55 @@ test("rejects existing objects and opposing IPv4 selectors without touching othe
const commands = greIke2SideCommands(pair, 0, secret), catalogs = empty() 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.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" }) 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" }) 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.policy].pop()
catalogs[greIpsecPaths.peer].push({ ".id": "*D", address: "198.51.100.6/32", "exchange-mode": "ike2" }) 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.peer].pop()
catalogs[greIpsecPaths.filter].push({ ".id": "*E", comment: commands[0].fields.comment! }) 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("the runner can parse the prepared plan after its JSON round trip", () => {
const planned = greIke2StepInput(pair, 0, secret, "source-proof", [
{ path: greIpsecPaths.peer, fields: {} },
{ path: greIpsecPaths.policy, id: "*4", fields: { proposal: "default" } },
])
assert.deepEqual(greIke2StepSchema.parse(JSON.parse(JSON.stringify(planned))), planned)
assert.deepEqual(planned.writes, [
{ path: greIpsecPaths.peer, action: "create" },
{ path: greIpsecPaths.policy, id: "*4", action: "update" },
])
assert.throws(() => greIke2StepSchema.parse({ ...planned, writes: [{ path: greIpsecPaths.proposal, id: "*4", action: "update" }] }))
}) })
test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => { test("requires the new plaintext drop to precede existing rules and preserve every prior object", () => {
+121 -31
View File
@@ -22,16 +22,30 @@ const endpoint = z.object({
outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"), outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"),
}).strict() }).strict()
const schema = z.object({ endpoints: z.array(endpoint).length(2) }).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() }) const writePath = z.enum([greIpsecPaths.filter, greIpsecPaths.profile, greIpsecPaths.peer, greIpsecPaths.identity, greIpsecPaths.policy])
export const greIke2StepSchema = schema.extend({
side: z.union([z.literal(0), z.literal(1)]),
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
beforeFingerprint: z.string(),
writes: z.array(z.discriminatedUnion("action", [
z.object({ path: writePath, action: z.literal("create") }).strict(),
z.object({ path: z.literal(greIpsecPaths.policy), action: z.literal("update"), id: z.string().regex(/^\*[a-z0-9]+$/i) }).strict(),
])).max(6),
})
type Pair = z.infer<typeof schema> type Pair = z.infer<typeof schema>
type Side = 0 | 1 type Side = 0 | 1
type Fields = Record<string, string> type Fields = Record<string, string>
type Catalogue = Record<string, Fields[]> type Catalogue = Record<string, Fields[]>
type RouterWrite = { path: string; fields: Fields; id?: string }
export function greIke2StepInput(input: Pair, side: Side, ipsecSecret: string, beforeFingerprint: string, commands: RouterWrite[]) {
const writes = commands.map(({ path, id }) => id ? { path, id, action: "update" } : { path, action: "create" })
return greIke2StepSchema.parse({ endpoints: input.endpoints, side, ipsecSecret, beforeFingerprint, writes })
}
const sides = [0, 1] as const const sides = [0, 1] as const
const paths = Object.values(greIpsecPaths) const paths = Object.values(greIpsecPaths)
const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = { const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = {
[greIpsecPaths.filter]: new Set(["bytes", "packets"]), [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"] { function target(input: Pair): ChangeEvidence["target"] {
@@ -50,9 +64,9 @@ export function greIke2SideCommands(input: Pair, side: Side, secret: string) {
return [ return [
{ path: greIpsecPaths.filter, fields: { ...inbound, comment: `${name}:plain-in` } }, { path: greIpsecPaths.filter, fields: { ...inbound, comment: `${name}:plain-in` } },
{ path: greIpsecPaths.filter, fields: { ...outbound, comment: `${name}:plain-out` } }, { 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.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 }> ] satisfies Array<{ path: string; fields: Fields }>
} }
@@ -66,21 +80,59 @@ function includesIp(selector: string | undefined, address: string) {
return inIxNetwork(`${host}/${length ?? "32"}`, address) return inIxNetwork(`${host}/${length ?? "32"}`, address)
} }
export function validateNewPairSide(input: Pair, side: Side, catalogs: Catalogue, commands: ReturnType<typeof greIke2SideCommands>) { function ownedRows(catalogs: Catalogue, command: RouterWrite) {
const name = nameFor(input), local = input.endpoints[side].outerAddress, remote = input.endpoints[side === 0 ? 1 : 0].outerAddress return catalogs[command.path].filter(row => command.fields.comment ? row.comment === command.fields.comment : row.name === command.fields.name)
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)
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"])))) { [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) 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) && [undefined, "", "all", "0", "255", "gre", "47"].includes(row.protocol) &&
((includesIp(row["src-address"], local) && includesIp(row["dst-address"], remote)) || ((includesIp(row["src-address"], local) && includesIp(row["dst-address"], remote)) ||
(includesIp(row["src-address"], remote) && includesIp(row["dst-address"], local))))) { (includesIp(row["src-address"], remote) && includesIp(row["dst-address"], local))))) {
throw new McpError("DEPENDENCY_CONFLICT", "Существующая IPsec policy перекрывает GRE между выбранными адресами", 409) 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) { export function greIke2StableCatalogues(catalogs: Catalogue) {
@@ -95,10 +147,38 @@ function matches(expected: Fields, observed: Fields) {
if (["disabled", "tunnel", "passive"].includes(key)) return (observedBoolean(actual) ?? (actual === undefined ? false : null)) === observedBoolean(value) 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 (["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 === "protocol" && value === "gre") return actual === "gre" || actual === "47"
if (key === "proposal" && value === "default") return actual === undefined || actual === "default"
return actual === value 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) { 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) const created = after[command.path].find(row => row[".id"] === nativeId)
return !!created && !before[command.path].some(row => row[".id"] === nativeId) && matches(command.fields, created) && return !!created && !before[command.path].some(row => row[".id"] === nativeId) && matches(command.fields, created) &&
@@ -126,28 +206,34 @@ async function readSide(input: Pair, side: Side) {
export function registerGreIke2PairActions(register: typeof add) { export function registerGreIke2PairActions(register: typeof add) {
registerMcpService(operation, { registerMcpService(operation, {
current: async raw => { current: async raw => {
const input = stepSchema.parse(raw) const input = greIke2StepSchema.parse(raw)
return await Promise.all(sides.map(async side => (await readSide(input, side)).proof)) return await Promise.all(sides.map(async side => (await readSide(input, side)).proof))
}, },
execute: async raw => { execute: async raw => {
const input = stepSchema.parse(raw), side = input.side, state = await readSide(input, side) const input = greIke2StepSchema.parse(raw), side = input.side, state = await readSide(input, side)
if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409) if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409)
const commands = greIke2SideCommands(input, side, input.ipsecSecret) const desired = greIke2SideCommands(input, side, input.ipsecSecret)
validateNewPairSide(input, side, state.catalogs, commands) const commands = planGreIke2Side(input, side, state.catalogs, desired)
const reviewed = greIke2StepInput(input, side, input.ipsecSecret, state.proof, commands).writes
if (fingerprint(reviewed) !== fingerprint(input.writes)) throw new McpError("STATE_CONFLICT", "Подготовленные команды IKEv2 отличаются от плана", 409)
let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0 let before = greIke2StableCatalogues(state.catalogs), confirmed = 0, verified = 0
for (const command of commands) { for (const command of commands) {
let dispatched = false let dispatched = false
try { try {
const first = command.path === greIpsecPaths.filter ? before[command.path][0]?.[".id"] : undefined 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() await assertVerifiedConfigurationAccess()
if (fingerprint((await routerClient(Number(state.server.id))).server) !== fingerprint(state.server)) throw new McpError("STATE_CONFLICT", "Источник RouterOS изменился перед записью", 409) 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) if (fingerprint(greIke2StableCatalogues(await state.readCatalogues())) !== fingerprint(before)) throw new McpError("STATE_CONFLICT", "IPsec изменился перед записью", 409)
dispatched = true 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++ confirmed++
const after = greIke2StableCatalogues(await state.readCatalogues()) 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) throw new McpError("VERIFICATION_FAILED", "Ответ RouterOS не подтверждает точное добавление объекта", 502)
} }
before = after before = after
@@ -159,31 +245,35 @@ export function registerGreIke2PairActions(register: typeof add) {
} }
} }
const after = await readSide(input, side) const after = await readSide(input, side)
if (fingerprint(greIke2StableCatalogues(after.catalogs)) !== fingerprint(before)) throw new IpsecServerInitExecutionError("VERIFICATION_FAILED", "Состояние IPsec изменилось после последней команды", confirmed, verified, commands.length) const afterFingerprint = completedPairProof(input, side, after.catalogs, desired)
return { verified: true, commandCount: commands.length, afterFingerprint: after.proof, greEnabled: false, forwardingVerified: false } return { verified: true, commandCount: commands.length, afterFingerprint, greEnabled: false, forwardingVerified: false }
}, },
verify: async (raw, result) => { verify: async (raw, result) => {
const input = stepSchema.parse(raw) const input = greIke2StepSchema.parse(raw)
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null 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, { register(operation, "mm_gre_ikev2_pair_configure_plan", "План настройки отдельного IKEv2 для двух существующих GRE", "network", "mm:network:write", "write", "servers", schema, {
version: 3,
target: raw => target(schema.parse(raw)), target: raw => target(schema.parse(raw)),
prepare: async 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 before = await Promise.all(sides.map(side => readSide(input, side)))
const steps = sides.map(side => { const catalogs = before.map(state => state.catalogs)
const commands = greIke2SideCommands(input, side, ipsecSecret) validateGreIke2Defaults(greIke2DefaultProposal(catalogs[0]), greIke2DefaultProposal(catalogs[1]))
validateNewPairSide(input, side, before[side].catalogs, commands) const ipsecSecret = pairSecret(input, catalogs)
return { kind: "service" as const, service: operation, input: { ...input, side, ipsecSecret, beforeFingerprint: before[side].proof } } const changes = sides.map(side => planGreIke2Side(input, side, catalogs[side], greIke2SideCommands(input, side, ipsecSecret)))
}) const steps = sides.map(side => ({ kind: "service" as const, service: operation,
input: greIke2StepInput(input, side, ipsecSecret, before[side].proof, changes[side]),
}))
const objects = (await Promise.all(before.map(state => greMutationProtectionObjects(Number(state.server.id), state.gre)))).flat() 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: [ warnings: [
`На каждом CHR создаются выделенные объекты ${nameFor(input)}: profile, proposal, peer, identity, статическая policy GRE в транспортном режиме и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`, `На каждом CHR настраиваются выделенные объекты ${nameFor(input)}: profile, peer, identity, транспортная policy GRE с proposal default и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`,
"Существующие GRE остаются отключёнными. PSK автоматически создаётся для пары. Глобальные IPsec-профили не меняются. Для IKE/ESP требуются разрешения действующего firewall.", "GRE остаются отключёнными. Proposal default используется после проверки совместимости и не изменяется. Для IKE/ESP требуются разрешения действующего firewall.",
"Планы проверяются и применяются последовательно. При сбое требуется сверить уже добавленные объекты до повтора. IPsec SA и прохождение трафика проверяются после отдельного включения GRE.", "Ранее созданные объекты пары переиспользуются только при совпадении параметров. У старой политики пары разрешена смена 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 и связность. При ошибке сверяйте обе стороны перед следующей операцией. Первая сторона может остаться созданной и отключённой. Применение создаёт две отключённые стороны. Сверьте обе через `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` при отключённом интерфейсе.
### Разбор отказа и проверка резерва ### Разбор отказа и проверка резерва