Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a962c1984 | ||
|
|
0a568f1640 | ||
|
|
5233a9f194 | ||
|
|
645045a5d5 |
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:pg": "node scripts/test-mcp-postgres.mjs --module-completion --restore",
|
||||
"test:mcp:pg": "node scripts/test-mcp-postgres.mjs",
|
||||
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts",
|
||||
"test:mcp:network-diagnostics": "node --experimental-test-module-mocks --import tsx --test src/modules/mcp/incident-actions.test.ts src/modules/mcp/network-diagnostic-actions.test.ts src/modules/mcp/resilience-actions.test.ts src/modules/mcp/gre-ipsec-pair-actions.test.ts src/modules/mcp/gre-ikev2-pair-actions.test.ts",
|
||||
"test:mcp:network-diagnostics:pg": "node scripts/test-mcp-postgres.mjs --network-diagnostics",
|
||||
"test:mcp:pg:sharded": "node scripts/test-mcp-postgres-sharded.mjs",
|
||||
"test:mcp:users-bindings:pg": "node scripts/test-mcp-postgres.mjs --users-bindings",
|
||||
|
||||
@@ -80,6 +80,8 @@ import { prepareWireguardPeerDeletion, registerWireguardPeerDeleteActions } from
|
||||
import { registerFirewallActions } from "./firewall-actions.js"
|
||||
import { registerBfdMoveActions } from "./bfd-move-actions.js"
|
||||
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
||||
import { registerGreIpsecPairActions } from "./gre-ipsec-pair-actions.js"
|
||||
import { registerGreIke2PairActions } from "./gre-ikev2-pair-actions.js"
|
||||
import { registerIxActions } from "./internet-exchange-actions.js"
|
||||
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
||||
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
||||
@@ -707,6 +709,8 @@ registerWireguardInterfaceDeleteActions(add)
|
||||
registerFirewallActions(add)
|
||||
registerBfdMoveActions(add)
|
||||
registerGreMutationActions(add)
|
||||
registerGreIpsecPairActions(add)
|
||||
registerGreIke2PairActions(add)
|
||||
registerIxActions(add)
|
||||
registerGreRevisionActions(add)
|
||||
registerGreNativeServices()
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { greIpsecPaths } from "../../services/gre-ipsec-transport.js"
|
||||
import { greIke2DefaultProposal, greIke2SideCommands, greIke2StableCatalogues, 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("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,267 @@
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import { z } from "zod"
|
||||
import { greMutationProof, greTarget, readGreMutationState } from "../../services/gre-mutation-state.js"
|
||||
import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "../../services/gre-ipsec-transport.js"
|
||||
import { inIxNetwork } from "../../services/internet-exchange-plan.js"
|
||||
import { ipsecPeerDeleteRows } from "../../services/ipsec-peer-delete.js"
|
||||
import { IpsecServerInitExecutionError } from "../../services/ipsec-server-init.js"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js"
|
||||
import type { add } from "./actions.js"
|
||||
import type { ChangeEvidence } from "./action-types.js"
|
||||
import { greMutationProtectionObjects } from "./gre-mutation-actions.js"
|
||||
import { routerClient } from "./resources.js"
|
||||
import { fingerprint, McpError, privateFingerprinter } from "./security.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
|
||||
const operation = "network.gre.ikev2_pair.configure"
|
||||
const endpoint = z.object({
|
||||
serverId: z.number().int().positive().safe(),
|
||||
greName: z.string().trim().min(1).max(100),
|
||||
outerAddress: z.string().refine(value => isIP(value) === 4 && value !== "0.0.0.0", "Требуется фиксированный внешний IPv4"),
|
||||
}).strict()
|
||||
const schema = z.object({ endpoints: z.array(endpoint).length(2) }).strict()
|
||||
const stepSchema = schema.extend({ side: z.union([z.literal(0), z.literal(1)]), ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/), beforeFingerprint: z.string() })
|
||||
type Pair = z.infer<typeof schema>
|
||||
type Side = 0 | 1
|
||||
type Fields = Record<string, string>
|
||||
type Catalogue = Record<string, Fields[]>
|
||||
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", "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 = stepSchema.parse(raw)
|
||||
return await Promise.all(sides.map(async side => (await readSide(input, side)).proof))
|
||||
},
|
||||
execute: async raw => {
|
||||
const input = stepSchema.parse(raw), side = input.side, state = await readSide(input, side)
|
||||
if (state.proof !== input.beforeFingerprint) throw new McpError("STATE_CONFLICT", "GRE или IPsec изменился после подготовки", 409)
|
||||
const 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 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 = stepSchema.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: 2,
|
||||
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 => {
|
||||
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: 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,78 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test, { mock } from "node:test"
|
||||
import type { add } from "./actions.js"
|
||||
import type { McpAction } from "./action-types.js"
|
||||
import type { GreMutation } from "../../services/gre-mutation-input.js"
|
||||
|
||||
const routerStates = new Map([
|
||||
[3, { ipv4: [{ address: "192.0.2.3/24" }], gre: new Array<Record<string, string>>() }],
|
||||
[6, { ipv4: [{ address: "198.51.100.6/24" }], gre: new Array<Record<string, string>>() }],
|
||||
])
|
||||
const writes: Array<{ id: number; mutation: GreMutation }> = []
|
||||
mock.module("./resources.js", { namedExports: { async routerClient(id: number) { return { server: { id } } } } })
|
||||
mock.module("./gre-mutation-actions.js", { namedExports: { async greMutationProtectionObjects(serverId: number) {
|
||||
return [{ kind: "server", id: String(serverId), serverId }]
|
||||
} } })
|
||||
mock.module("../../services/gre-mutation-state.js", { namedExports: {
|
||||
greMutationProof: (state: unknown) => state,
|
||||
async readGreMutationState(server: { id: number }) { return structuredClone(routerStates.get(server.id)) },
|
||||
} })
|
||||
const { fingerprint, redact } = await import("./security.js")
|
||||
mock.module("../../services/gre-mutation.js", { namedExports: {
|
||||
planGreMutation: () => [{}],
|
||||
async mutateGreTunnel(server: { id: number }, mutation: GreMutation, beforeFingerprint: string) {
|
||||
const state = routerStates.get(server.id)!
|
||||
assert.equal(beforeFingerprint, fingerprint(state))
|
||||
assert.equal(mutation.operation, "create")
|
||||
if (mutation.operation !== "create") throw new Error("expected create")
|
||||
writes.push({ id: server.id, mutation })
|
||||
state.gre.push({ name: mutation.fields.name, "remote-address": mutation.fields.remoteAddress })
|
||||
return { verified: true, afterFingerprint: fingerprint(state), tunnel: { ipsecSecret: mutation.fields.ipsecSecret } }
|
||||
},
|
||||
} })
|
||||
const { registerGreIpsecPairActions } = await import("./gre-ipsec-pair-actions.js")
|
||||
const { findMcpService } = await import("./service-registry.js")
|
||||
let action: Pick<McpAction, "prepare" | "target"> | undefined
|
||||
let definition: { id: string; toolName: string } | undefined
|
||||
const register: typeof add = (id, toolName, _title, _section, _permission, _effect, _scope, _schema, handlers) => {
|
||||
definition = { id, toolName }
|
||||
if (handlers.target) action = { prepare: handlers.prepare, target: handlers.target }
|
||||
}
|
||||
registerGreIpsecPairActions(register)
|
||||
|
||||
const input = { endpoints: [
|
||||
{ serverId: 3, endpoint: "192.0.2.3", name: "gre-test-home", localInnerIp: "10.253.0.1/30" },
|
||||
{ serverId: 6, endpoint: "198.51.100.6", name: "gre-test-nov", localInnerIp: "10.253.0.2/30" },
|
||||
] }
|
||||
const context = {} as Parameters<NonNullable<McpAction["prepare"]>>[1]
|
||||
|
||||
test("GRE/IPsec pair creates two disabled endpoints using one private key", async () => {
|
||||
assert.equal(definition?.toolName, "mm_gre_ipsec_pair_create_plan")
|
||||
const prepare = action!.prepare!, service = findMcpService(definition!.id)!
|
||||
const evidence = await prepare(input, context), another = await prepare(input, context)
|
||||
assert.deepEqual(await action!.target(input, context), { scope: "servers", serverIds: [3, 6] })
|
||||
assert.deepEqual(evidence.objects.map(object => object.serverId), [3, 6])
|
||||
assert.equal(writes.length, 0)
|
||||
const [first, second] = evidence.steps.map(step => { assert.equal(step.kind, "service"); return step.kind === "service" ? step.input : {} })
|
||||
const [other] = another.steps
|
||||
assert.ok(other.kind === "service" && first.ipsecSecret !== other.input.ipsecSecret)
|
||||
assert.match(String(first.ipsecSecret), /^[a-f0-9]{64}$/)
|
||||
assert.equal(first.ipsecSecret, second.ipsecSecret)
|
||||
assert.ok(!JSON.stringify(redact(evidence)).includes(String(first.ipsecSecret)))
|
||||
await assert.rejects(prepare({ ...input, ipsecSecret: "caller-supplied" }, context))
|
||||
await assert.rejects(prepare({ endpoints: input.endpoints.slice(0, 1) }, context))
|
||||
await assert.rejects(prepare({ endpoints: [input.endpoints[0], input.endpoints[0]] }, context), /два разных сервера/)
|
||||
await assert.rejects(prepare({ endpoints: [input.endpoints[0], { ...input.endpoints[1], endpoint: "203.0.113.6" }] }, context), /Внешний адрес GRE не найден/)
|
||||
assert.deepEqual(await service.current(first), evidence.before)
|
||||
for (const step of [first, second]) {
|
||||
const receipt = await service.execute(step)
|
||||
assert.ok(await service.verify!(step, receipt))
|
||||
assert.ok(!JSON.stringify(receipt).includes(String(first.ipsecSecret)))
|
||||
}
|
||||
assert.deepEqual(writes.map(({ id, mutation }) => mutation.operation === "create" ?
|
||||
[id, mutation.fields.localAddress, mutation.fields.remoteAddress, mutation.fields.enabled, mutation.fields.allowFastPath] : []), [
|
||||
[3, "192.0.2.3", "198.51.100.6", false, false],
|
||||
[6, "198.51.100.6", "192.0.2.3", false, false],
|
||||
])
|
||||
await assert.rejects(prepare(input, context), /уже есть GRE/)
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { z } from "zod"
|
||||
import { greCreateFieldsSchema, type GreMutation } from "../../services/gre-mutation-input.js"
|
||||
import { greMutationProof, readGreMutationState } from "../../services/gre-mutation-state.js"
|
||||
import { mutateGreTunnel, planGreMutation } from "../../services/gre-mutation.js"
|
||||
import { observedBoolean } from "../../services/ospf-observed-values.js"
|
||||
import type { ChangeEvidence } from "./action-types.js"
|
||||
import type { add } from "./actions.js"
|
||||
import { greMutationProtectionObjects } from "./gre-mutation-actions.js"
|
||||
import { routerClient } from "./resources.js"
|
||||
import { fingerprint, McpError } from "./security.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
|
||||
const operation = "network.gre.ipsec_pair.create"
|
||||
const endpointSchema = greCreateFieldsSchema.pick({ name: true, localInnerIp: true, comment: true }).extend({
|
||||
serverId: z.number().int().positive().safe(), endpoint: greCreateFieldsSchema.shape.remoteAddress,
|
||||
})
|
||||
const schema = z.object({
|
||||
endpoints: z.array(endpointSchema).length(2),
|
||||
mtu: greCreateFieldsSchema.shape.mtu,
|
||||
}).strict()
|
||||
const stepSchema = schema.extend({
|
||||
side: z.union([z.literal(0), z.literal(1)]),
|
||||
ipsecSecret: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
beforeFingerprint: z.string(),
|
||||
})
|
||||
type Pair = z.infer<typeof schema>
|
||||
type Side = 0 | 1
|
||||
const sides = [0, 1] as const
|
||||
|
||||
function target(input: Pair): ChangeEvidence["target"] {
|
||||
const [first, second] = input.endpoints
|
||||
if (first.serverId === second.serverId || first.endpoint === second.endpoint) {
|
||||
throw new McpError("INVALID_INPUT", "Нужны два разных сервера и два разных внешних IPv4")
|
||||
}
|
||||
return { scope: "servers", serverIds: [first.serverId, second.serverId] }
|
||||
}
|
||||
|
||||
function mutationFor(input: Pair, side: Side, ipsecSecret: string): GreMutation {
|
||||
const local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
|
||||
return { operation: "create", fields: {
|
||||
name: local.name, localAddress: local.endpoint, remoteAddress: remote.endpoint,
|
||||
localInnerIp: local.localInnerIp, comment: local.comment, mtu: input.mtu ?? "auto",
|
||||
enabled: false, allowFastPath: false, ipsecSecret,
|
||||
} }
|
||||
}
|
||||
|
||||
async function readSide(input: Pair, side: Side, ipsecSecret: string) {
|
||||
const { server } = await routerClient(input.endpoints[side].serverId)
|
||||
const mutation = mutationFor(input, side, ipsecSecret)
|
||||
const state = await readGreMutationState(server, mutation)
|
||||
return { server, mutation, state, proof: fingerprint(greMutationProof(state)) }
|
||||
}
|
||||
|
||||
export function registerGreIpsecPairActions(register: typeof add) {
|
||||
registerMcpService(operation, {
|
||||
current: async raw => {
|
||||
const input = stepSchema.parse(raw)
|
||||
const before = await Promise.all(sides.map(side => readSide(input, side, input.ipsecSecret)))
|
||||
return before.map(item => item.proof)
|
||||
},
|
||||
execute: async raw => {
|
||||
const input = stepSchema.parse(raw)
|
||||
const { server } = await routerClient(input.endpoints[input.side].serverId)
|
||||
const { tunnel: _tunnel, ...receipt } = await mutateGreTunnel(server, mutationFor(input, input.side, input.ipsecSecret), input.beforeFingerprint)
|
||||
return receipt
|
||||
},
|
||||
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, input.ipsecSecret)).proof
|
||||
},
|
||||
})
|
||||
register(operation, "mm_gre_ipsec_pair_create_plan", "План создания пары GRE/IPsec с автоматическим PSK",
|
||||
"network", "mm:network:write", "write", "servers", schema, {
|
||||
target: raw => target(schema.parse(raw)),
|
||||
prepare: async raw => {
|
||||
const input = schema.parse(raw), scope = target(input)
|
||||
const ipsecSecret = randomBytes(32).toString("hex")
|
||||
const before = await Promise.all(sides.map(side => readSide(input, side, ipsecSecret)))
|
||||
const mutationCost = sides.reduce<number>((cost, side) => {
|
||||
const item = before[side]!, local = input.endpoints[side], remote = input.endpoints[side === 0 ? 1 : 0]
|
||||
if (!item.state.ipv4.some(row => row.address.split("/")[0] === local.endpoint &&
|
||||
observedBoolean(row.disabled) !== true && observedBoolean(row.invalid) !== true)) {
|
||||
throw new McpError("STATE_CONFLICT", `Внешний адрес GRE не найден на сервере ${local.serverId}`, 409)
|
||||
}
|
||||
if (item.state.gre.some(row => [row["remote-address"], row["current-remote-address"]].includes(remote.endpoint))) {
|
||||
throw new McpError("STATE_CONFLICT", `На сервере ${local.serverId} уже есть GRE с этим удалённым адресом`, 409)
|
||||
}
|
||||
return cost + planGreMutation(item.server, item.mutation, item.state).length + 1
|
||||
}, 0)
|
||||
return {
|
||||
target: scope, objects: (await Promise.all(before.map(item => greMutationProtectionObjects(Number(item.server.id), item.state)))).flat(),
|
||||
snapshots: [], before: before.map(item => item.proof), mutationCost, requiresHuman: true,
|
||||
steps: sides.map(side => ({ kind: "service" as const, service: operation, input: {
|
||||
...input, side, ipsecSecret, beforeFingerprint: before[side]!.proof,
|
||||
} })),
|
||||
warnings: [
|
||||
"Создаются только два новых отключённых GRE. Стороны получают один автоматически сгенерированный PSK; FastPath отключён.",
|
||||
"Стороны применяются и проверяются последовательно. При отказе второй стороны первая может остаться созданной и отключённой.",
|
||||
"Установка IPsec SA и передача трафика проверяются после отдельного включения обоих интерфейсов.",
|
||||
],
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -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 },
|
||||
}
|
||||
}
|
||||
@@ -117,9 +117,20 @@ export async function readGreMutationState(server: ServerRow, input: GreMutation
|
||||
try{const value=bounded(raw);await check();return value}catch(error){throw stop(error)}
|
||||
}
|
||||
}
|
||||
// Create and compound edit prove preservation of configured routes. Learned routes
|
||||
// remain necessary for delete, rename and restore dependency checks.
|
||||
const configuredRoutesOnly = input?.operation === "create" || (input?.operation === "update" && !options.identityOnly)
|
||||
const [greRaw, ipv4Raw, ipv6Raw, dependencies, bindings, filters] = await settledGreReads([
|
||||
client.get<unknown>("/interface/gre").then(value=>readGreNativeRows(rows(value,[".id","name"],100))),client.get<unknown>("/ip/address").then(value=>rows(value,[".id","address","interface"])),client.get<unknown>("/ipv6/address").then(value=>rows(value,[".id","address","interface"])),
|
||||
settledGreReads(greDependencyPaths.map(async path => [path, rows(await client.get<unknown>(path), path === "/interface" ? [".id", "name"] : [".id"])] as const),stop),
|
||||
settledGreReads(greDependencyPaths.map(async path => {
|
||||
const configuredRoute = configuredRoutesOnly && (path === "/ip/route" || path === "/ipv6/route")
|
||||
const requestPath = configuredRoute ? path + "?static=true" : path
|
||||
const catalogue = rows(await client.get<unknown>(requestPath), path === "/interface" ? [".id", "name"] : [".id"])
|
||||
if (configuredRoute && catalogue.some(row => observedBoolean(row.dynamic) === true || observedBoolean(row.static) === false)) {
|
||||
throw greMutationProblem("RouterOS вернул маршруты вне запрошенного фильтра GRE")
|
||||
}
|
||||
return [path, catalogue] as const
|
||||
}),stop),
|
||||
pool.query('SELECT id,interface_name AS "interfaceName" FROM user_interface_bindings WHERE server_id=$1 ORDER BY id LIMIT 1001', [server.id]),
|
||||
pool.query('SELECT id,gateway_tunnel_id AS "gatewayTunnelId",gateway FROM filter_rules WHERE server_id=$1 ORDER BY id LIMIT 1001', [server.id]),
|
||||
]as const,stop)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { greMutationSchema } from "./gre-mutation-input.js"
|
||||
import { planGreMutation, verifyGreMutationOp, executeGreMutationOps } from "./gre-mutation.js"
|
||||
import { assertGreDeleteDependencies, greDependencyPaths, greMutationProof, readGrePskValue, type GreMutationState } from "./gre-mutation-state.js"
|
||||
import { assertGreDeleteDependencies, greDependencyPaths, greMutationProof, readGreMutationState, readGrePskValue, type GreMutationState } from "./gre-mutation-state.js"
|
||||
import { pool } from "../db/index.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
|
||||
import type { RosWriteOp } from "./entity-snapshots.js"
|
||||
|
||||
@@ -95,4 +97,37 @@ assert.equal(commands,1); assert.equal(state.gre[0].disabled,"true")
|
||||
const deletion = greMutationSchema.parse({operation:"delete",name:"own-gre"})
|
||||
const deleteOps = planGreMutation(server,deletion,state)
|
||||
assert.equal(deleteOps.at(-1)?.path,"/interface/gre/*C")
|
||||
|
||||
const originalClient = MikrotikClient.fromServer, originalQuery = pool.query
|
||||
const routeRequests: string[] = []
|
||||
const configured = { ".id": "*S", static: "true", dynamic: "false" }
|
||||
const learned = Array.from({ length: 25_626 }, (_, i) => ({ ".id": `*${(i + 100).toString(16)}`, dynamic: "true", bgp: "true" }))
|
||||
let ignoresFilter = false
|
||||
MikrotikClient.fromServer = (() => ({
|
||||
async get(path: string) {
|
||||
if (!/^\/(?:ip|ipv6)\/route(?:\?|$)/.test(path)) return []
|
||||
routeRequests.push(path)
|
||||
if (path.endsWith("?static=true")) return ignoresFilter ? [configured, learned[0]] : [configured]
|
||||
return [configured, ...learned]
|
||||
},
|
||||
async post() { throw new Error("Unexpected native read in route catalogue test") },
|
||||
})) as unknown as typeof MikrotikClient.fromServer
|
||||
pool.query = (async () => ({ rows: [] })) as unknown as typeof pool.query
|
||||
try {
|
||||
const configuredPaths = ["/ip/route?static=true", "/ipv6/route?static=true"]
|
||||
for (const input of [create, greMutationSchema.parse({ operation: "update", name: "test-gre", fields: { enabled: true } })]) {
|
||||
routeRequests.length = 0
|
||||
const snapshot = await readGreMutationState(server, input)
|
||||
assert.deepEqual(routeRequests.sort(), configuredPaths.sort())
|
||||
assert.deepEqual(snapshot.dependencies["/ip/route"], [configured])
|
||||
}
|
||||
ignoresFilter = true
|
||||
await assert.rejects(readGreMutationState(server, create), /вне запрошенного фильтра GRE/)
|
||||
routeRequests.length = 0
|
||||
await assert.rejects(readGreMutationState(server, deletion), /каталог зависимостей GRE/)
|
||||
assert.deepEqual(routeRequests.sort(), ["/ip/route", "/ipv6/route"].sort())
|
||||
} finally {
|
||||
MikrotikClient.fromServer = originalClient
|
||||
pool.query = originalQuery
|
||||
}
|
||||
console.log("GRE mutations: disabled staging, v4→v6 primary replacement, opaque/timer/secret preservation, native identity, parent/application dependencies, link-local exclusion, per-command proof and ignored/lost stop")
|
||||
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto"
|
||||
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
|
||||
import { greIke2TransportFields, greIpsecPaths, greIpsecPlaintextDrops } from "./gre-ipsec-transport.js"
|
||||
|
||||
export class IxConflict extends Error {
|
||||
constructor(message: string, readonly statusCode = 409) { super(message) }
|
||||
@@ -282,8 +283,9 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
||||
result.push({ serverId: site.serverId, path, fields: nameOnly ? fields : { ...fields, comment: namespace + ":" + key } })
|
||||
}
|
||||
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
|
||||
add("/ip/firewall/filter", "gre-in-" + key, { chain: "input", protocol: "gre", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!), "ipsec-policy": "in,none", action: "drop" })
|
||||
add("/ip/firewall/filter", "gre-out-" + key, { chain: "output", protocol: "gre", "src-address": host(binding.localEndpoint!), "dst-address": host(binding.endpoint!), "ipsec-policy": "out,none", action: "drop" })
|
||||
const [inbound, outbound] = greIpsecPlaintextDrops(binding.localEndpoint!, binding.endpoint!)
|
||||
add(greIpsecPaths.filter, "gre-in-" + key, inbound)
|
||||
add(greIpsecPaths.filter, "gre-out-" + key, outbound)
|
||||
}
|
||||
const dropInterface = ixDiscardInterface(id)
|
||||
for (const [index, binding] of site.interfaces.entries()) {
|
||||
@@ -296,14 +298,10 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
||||
if (gre) {
|
||||
const transport = namespace + "-" + key
|
||||
protectGre(binding, key)
|
||||
add("/ip/ipsec/profile", key, { name: transport, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" })
|
||||
add("/ip/ipsec/proposal", key, { name: transport, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" })
|
||||
add("/ip/ipsec/peer", key, { name: transport, address: host(binding.endpoint!), "local-address": binding.localEndpoint!,
|
||||
profile: transport, "exchange-mode": "ike2", passive: "true" })
|
||||
add("/ip/ipsec/identity", "gre-identity-" + key, { peer: transport, "auth-method": "pre-shared-key",
|
||||
secret: "ix-credential:" + gre.credentialId, disabled: String(!binding.linux!.enabled) })
|
||||
add("/ip/ipsec/policy", "gre-policy-" + key, { peer: transport, "src-address": host(binding.localEndpoint!),
|
||||
"dst-address": host(binding.endpoint!), protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: transport })
|
||||
const fields = greIke2TransportFields(transport, binding.localEndpoint!, binding.endpoint!, true, "ix-credential:" + gre.credentialId, !binding.linux!.enabled)
|
||||
for (const kind of ["profile", "proposal", "peer"] as const) add(greIpsecPaths[kind], key, fields[kind])
|
||||
add(greIpsecPaths.identity, "gre-identity-" + key, fields.identity)
|
||||
add(greIpsecPaths.policy, "gre-policy-" + key, fields.policy)
|
||||
add("/interface/gre", "gre-" + key, { name: binding.name, "local-address": binding.localEndpoint!,
|
||||
"remote-address": binding.endpoint!, "allow-fast-path": "false", disabled: String(!binding.linux!.enabled) })
|
||||
}
|
||||
|
||||
@@ -131,6 +131,14 @@ npm --prefix backend run mcp:stdio
|
||||
|
||||
Наличие инструмента не означает, что каждый сценарий раздела проверен на стенде. Статусы — в [манифесте](mcp-final-manifest.md).
|
||||
|
||||
### Прямой GRE/IPsec между двумя CHR
|
||||
|
||||
`mm_gre_ipsec_pair_create_plan` требует разрешение `network.gre.ipsec_pair.create` и допуск к обоим серверам. Передайте в `endpoints` два объекта с `serverId`, `name` и локальным внешним IPv4 в `endpoint`. При необходимости укажите `localInnerIp` на каждой стороне и общий `mtu`. Manager генерирует единый PSK для обеих сторон. Ключ скрыт в плане и квитанции, ручная регистрация `secretRef` не нужна.
|
||||
|
||||
Применение создаёт две отключённые стороны. Сверьте обе через `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 оставляет пробел в наблюдениях.
|
||||
|
||||
Reference in new issue
Block a user