Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea13365f37 | ||
|
|
8a962c1984 | ||
|
|
0a568f1640 |
No files matched your search
@@ -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": "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:module-completion:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
||||||
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
"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:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics",
|
||||||
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
||||||
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ import { registerFirewallActions } from "./firewall-actions.js"
|
|||||||
import { registerBfdMoveActions } from "./bfd-move-actions.js"
|
import { registerBfdMoveActions } from "./bfd-move-actions.js"
|
||||||
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
||||||
import { registerGreIpsecPairActions } from "./gre-ipsec-pair-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 { registerIxActions } from "./internet-exchange-actions.js"
|
||||||
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
||||||
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
||||||
@@ -709,6 +710,7 @@ registerFirewallActions(add)
|
|||||||
registerBfdMoveActions(add)
|
registerBfdMoveActions(add)
|
||||||
registerGreMutationActions(add)
|
registerGreMutationActions(add)
|
||||||
registerGreIpsecPairActions(add)
|
registerGreIpsecPairActions(add)
|
||||||
|
registerGreIke2PairActions(add)
|
||||||
registerIxActions(add)
|
registerIxActions(add)
|
||||||
registerGreRevisionActions(add)
|
registerGreRevisionActions(add)
|
||||||
registerGreNativeServices()
|
registerGreNativeServices()
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import assert from "node:assert/strict"
|
||||||
|
import test from "node:test"
|
||||||
|
import { greIpsecPaths } from "../../services/gre-ipsec-transport.js"
|
||||||
|
import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, greIke2StepInput, greIke2StepSchema, planGreIke2Side, validateGreIke2Defaults, verifyGreIke2Create, verifyGreIke2Update } 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, 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)
|
||||||
|
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(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"])
|
||||||
|
})
|
||||||
|
|
||||||
|
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(() => 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(() => 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(() => planGreIke2Side(pair, 0, catalogs, commands), /Уже настроен IKEv2 peer/)
|
||||||
|
catalogs[greIpsecPaths.peer].pop()
|
||||||
|
catalogs[greIpsecPaths.filter].push({ ".id": "*E", comment: commands[0].fields.comment! })
|
||||||
|
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", () => {
|
||||||
|
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,281 @@
|
|||||||
|
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 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 Side = 0 | 1
|
||||||
|
type Fields = Record<string, string>
|
||||||
|
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 paths = Object.values(greIpsecPaths)
|
||||||
|
const runtimeFields: Readonly<Record<string, ReadonlySet<string>>> = {
|
||||||
|
[greIpsecPaths.filter]: new Set(["bytes", "packets"]),
|
||||||
|
[greIpsecPaths.policy]: new Set(["active", "invalid", "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", "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, proposal: "default", 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
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 => 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) {
|
||||||
|
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"
|
||||||
|
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) &&
|
||||||
|
(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 = greIke2StepSchema.parse(raw)
|
||||||
|
return await Promise.all(sides.map(async side => (await readSide(input, side)).proof))
|
||||||
|
},
|
||||||
|
execute: async raw => {
|
||||||
|
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)
|
||||||
|
const desired = greIke2SideCommands(input, side, input.ipsecSecret)
|
||||||
|
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
|
||||||
|
for (const command of commands) {
|
||||||
|
let dispatched = false
|
||||||
|
try {
|
||||||
|
const first = command.path === greIpsecPaths.filter ? before[command.path][0]?.[".id"] : undefined
|
||||||
|
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())
|
||||||
|
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
|
||||||
|
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)
|
||||||
|
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 = greIke2StepSchema.parse(raw)
|
||||||
|
const receipt = result as { verified?: boolean; afterFingerprint?: string } | null
|
||||||
|
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: 3,
|
||||||
|
target: raw => target(schema.parse(raw)),
|
||||||
|
prepare: async raw => {
|
||||||
|
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 => ({ 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()
|
||||||
|
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, peer, identity, транспортная policy GRE с proposal default и два правила против GRE без IPsec. Первая сторона — responder, вторая — инициатор.`,
|
||||||
|
"GRE остаются отключёнными. Proposal default используется после проверки совместимости и не изменяется. Для IKE/ESP требуются разрешения действующего firewall.",
|
||||||
|
"Ранее созданные объекты пары переиспользуются только при совпадении параметров. У старой политики пары разрешена смена proposal на default. IPsec SA проверяется после отдельного включения GRE.",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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 },
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto"
|
|||||||
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||||
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
|
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
|
||||||
|
import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "./gre-ipsec-transport.js"
|
||||||
|
|
||||||
export class IxConflict extends Error {
|
export class IxConflict extends Error {
|
||||||
constructor(message: string, readonly statusCode = 409) { super(message) }
|
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 } })
|
result.push({ serverId: site.serverId, path, fields: nameOnly ? fields : { ...fields, comment: namespace + ":" + key } })
|
||||||
}
|
}
|
||||||
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
|
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" })
|
const [inbound, outbound] = greIpsecPlaintextDrops(binding.localEndpoint!, binding.endpoint!)
|
||||||
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" })
|
add(greIpsecPaths.filter, "gre-in-" + key, inbound)
|
||||||
|
add(greIpsecPaths.filter, "gre-out-" + key, outbound)
|
||||||
}
|
}
|
||||||
const dropInterface = ixDiscardInterface(id)
|
const dropInterface = ixDiscardInterface(id)
|
||||||
for (const [index, binding] of site.interfaces.entries()) {
|
for (const [index, binding] of site.interfaces.entries()) {
|
||||||
@@ -296,14 +298,10 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
|||||||
if (gre) {
|
if (gre) {
|
||||||
const transport = namespace + "-" + key
|
const transport = namespace + "-" + key
|
||||||
protectGre(binding, key)
|
protectGre(binding, key)
|
||||||
add("/ip/ipsec/profile", key, { name: transport, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" })
|
const fields = greIke2TransportFields(transport, binding.localEndpoint!, binding.endpoint!, true, "ix-credential:" + gre.credentialId, !binding.linux!.enabled)
|
||||||
add("/ip/ipsec/proposal", key, { name: transport, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" })
|
for (const kind of ["profile", "proposal", "peer"] as const) add(greIpsecPaths[kind], key, fields[kind])
|
||||||
add("/ip/ipsec/peer", key, { name: transport, address: host(binding.endpoint!), "local-address": binding.localEndpoint!,
|
add(greIpsecPaths.identity, "gre-identity-" + key, fields.identity)
|
||||||
profile: transport, "exchange-mode": "ike2", passive: "true" })
|
add(greIpsecPaths.policy, "gre-policy-" + key, fields.policy)
|
||||||
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 })
|
|
||||||
add("/interface/gre", "gre-" + key, { name: binding.name, "local-address": binding.localEndpoint!,
|
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) })
|
"remote-address": binding.endpoint!, "allow-fast-path": "false", disabled: String(!binding.linux!.enabled) })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -137,6 +137,8 @@ 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 между этими адресами. Политики используют существующие proposal `default` после проверки их совместимости. Повторный план сверяет и переиспользует совпадающие объекты пары, а у проверенной политики предыдущей версии переключает только proposal. После проверки плана включите GRE отдельно и проверьте SA и связность. Если ранее для GRE был задан встроенный PSK, очистите его через `mm_gre_tunnel_update_plan` с `clearIpsecSecret: true` при отключённом интерфейсе.
|
||||||
|
|
||||||
### Разбор отказа и проверка резерва
|
### Разбор отказа и проверка резерва
|
||||||
|
|
||||||
1. Зафиксируйте источник, назначение, ожидаемый выход и максимальный допустимый перерыв. Проверьте доступ через `mm_capabilities_get` и давность наблюдений через `mm_telemetry_health_get`. Обрыв экспорта NetFlow оставляет пробел в наблюдениях.
|
1. Зафиксируйте источник, назначение, ожидаемый выход и максимальный допустимый перерыв. Проверьте доступ через `mm_capabilities_get` и давность наблюдений через `mm_telemetry_health_get`. Обрыв экспорта NetFlow оставляет пробел в наблюдениях.
|
||||||
|
|||||||
Reference in new issue
Block a user