Compare commits

..
3 Commits
Author SHA1 Message Date
Denozordec 1337325697 fix(ix): исправить цепочку ограничения размера сегмента
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m57s
Docker images / frontend-image (push) Successful in 2m58s
Docker images / updater-image (push) Successful in 1m26s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 3m33s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-12-04 23:31:36 +07:00
Denozordec f9b742b730 fix(ix): учесть включённые правила блокировки открытых туннелей
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 11m35s
Docker images / backend-image (push) Successful in 4m31s
Docker images / frontend-image (push) Successful in 4m57s
Docker images / updater-image (push) Successful in 2m9s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-12-04 22:53:04 +07:00
Denozordec b395c06ffb fix(ix): исправить проверку и продолжение настройки туннелей
Docker images / prepare-release (push) Successful in 13s
Docker images / backend-test (push) Successful in 11m9s
Docker images / frontend-image (push) Successful in 5m7s
Docker images / updater-image (push) Successful in 3m58s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-image (push) Successful in 6m53s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-12-04 22:16:10 +07:00
4 changed files with 182 additions and 47 deletions

No files matched your search

@@ -1,8 +1,8 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import type { IxRouterObject } from "@mmapp/contracts/internet-exchange"
import { ixSegmentConfigurationSchema, type IxRouterObject } from "@mmapp/contracts/internet-exchange"
import { planIxNative } from "./internet-exchange-execution.js"
import { ixNamespace } from "./internet-exchange-plan.js"
import { compileIxConfiguration, ixNamespace } from "./internet-exchange-plan.js"
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
const name = ixNamespace(id)
@@ -17,7 +17,7 @@ const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serve
test("managed MSS rules are backfilled and removed without adopting a hand-written rule", () => {
const path = "/ip/firewall/mangle"
const from = { serverId: 17, path, fields: { comment: name + ":linux-mss-from-il-wg", action: "change-mss",
chain: "prerouting", "in-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
chain: "forward", "in-interface": name, "new-mss": "1380", "tcp-mss": "1381-65535" } }
const to = { serverId: 17, path, fields: { comment: name + ":linux-mss-to-il-wg", action: "change-mss",
chain: "postrouting", "out-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const manual = { ...to.fields, comment: "manual MSS", ".id": "*A" }
@@ -34,6 +34,22 @@ test("managed MSS rules are backfilled and removed without adopting a hand-writt
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
})
test("IX migrates an exact disabled legacy ingress MSS rule", () => {
const path = "/ip/firewall/mangle"
const fields = { comment: name + ":linux-mss-from-il-vps", chain: "forward", "in-interface": name,
action: "change-mss", "new-mss": "1380", disabled: "true" }
const previous = { serverId: 17, path, fields }
const next = { ...previous, fields: { ...fields, disabled: "false" } }
const legacy = { ...fields, ".id": "*C", chain: "prerouting", "in-interface": "il-vps" }
const [update] = planIxNative(id, [next], [previous], device({ [path]: [legacy] }))
assert.equal(update.rosId, "*C")
assert.deepEqual(update.fields, { chain: "forward", "in-interface": name, disabled: "false" })
const [resumed] = planIxNative(id, [previous], [], device({ [path]: [legacy] }), true)
assert.deepEqual(resumed.fields, { chain: "forward", "in-interface": name })
assert.throws(() => planIxNative(id, [next], [previous], device({ [path]: [{ ...legacy, "new-mss": "1400" }] })), /изменён вне операции/)
})
test("a new VRF is inserted before main and no foreign route is altered", () => {
const changes = planIxNative(id, [vrf, route], [], device({
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
@@ -96,6 +112,67 @@ test("RouterOS REST host matches allow only the equivalent explicit host length"
}
})
test("another Linux VPS can be planned while a managed GRE/IPsec peer has no SA", () => {
const binding = (client: string, endpoint: string, localAddress: string, peerAddress: string) => ({
name: "il-gre-" + client, kind: "gre-ipsec", endpoint, localEndpoint: "192.0.2.17",
provisionGre: { localAddress, peerAddress, credentialId: id }, linux: { name: client, enabled: true, destinations: [] },
})
const existing = binding("old", "192.0.2.20", "10.254.0.1/30", "10.254.0.2")
const next = binding("new", "192.0.2.21", "10.254.0.5/30", "10.254.0.6")
const compile = (...interfaces: ReturnType<typeof binding>[]) => compileIxConfiguration(id, ixSegmentConfigurationSchema.parse({
name: "compute", sites: [{ serverId: 17, autonomousSystem: 64512, routerId: "192.0.2.17", interfaces }],
}))
const previous = compile(existing)
const desired = compile(existing, next)
const policyPath = "/ip/ipsec/policy", peerPath = "/ip/ipsec/peer"
const rows: Record<string, Array<Record<string, string>>> = {}
for (const [index, { path, fields }] of previous.entries()) {
const catalogue = rows[path] ??= []
catalogue.push({ ...fields, ".id": "*" + (index + 1).toString(16) })
}
const [policy] = rows[policyPath]
Object.assign(policy, { "src-address": "::/0", "dst-address": "::/0", invalid: "true" })
delete policy.template
delete policy["ipsec-protocols"]
const tasks = planIxNative(id, desired, previous, device(rows))
const policyTasks = tasks.filter(task => task.path === policyPath)
assert.equal(policyTasks.length, 1)
const [create] = policyTasks
assert.equal(create.rosId, undefined)
assert.equal(create.fields?.peer, name + "-" + next.name)
assert.equal(create.fields?.["src-address"], undefined)
assert.equal(create.fields?.["dst-address"], undefined)
policy.level = "use"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
policy.level = "require"
policy.template = "true"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
delete policy.template
rows[peerPath][0].address = "192.0.2.99/32"
assert.throws(() => planIxNative(id, desired, previous, device(rows)), /изменён вне операции/)
})
test("an omitted enabled-by-default flag on a GRE plaintext drop does not block IX", () => {
const path = "/ip/firewall/filter"
const object = (chain: string, policy: string) => ({ serverId: 17, path, fields: {
comment: name + ":gre-" + chain + "-il-vps", chain, action: "drop", protocol: "gre", "ipsec-policy": policy, disabled: "false",
} })
const inbound = object("input", "in,none"), outbound = object("output", "out,none")
const rows = [inbound, outbound].map(({ fields }, index) => {
const { disabled: _disabled, ...observed } = fields
return { ...observed, ".id": "*" + (index + 1), invalid: "false" }
})
assert.deepEqual(planIxNative(id, [inbound], [inbound], device({ [path]: [rows[0]] })), [])
assert.deepEqual(planIxNative(id, [inbound, outbound], [inbound], device({ [path]: rows }), true), [])
const disabled = { ...rows[0], disabled: "true" }
assert.throws(() => planIxNative(id, [inbound], [inbound], device({ [path]: [disabled] }), true), /изменён вне операции.*gre-input-il-vps.*disabled/)
const otherRule = { ...inbound, fields: { ...inbound.fields, protocol: "tcp" } }
const observedOtherRule = { ...rows[0], protocol: "tcp" }
assert.throws(() => planIxNative(id, [otherRule], [otherRule], device({ [path]: [observedOtherRule] })), /изменён вне операции.*disabled/)
})
test("RouterOS REST encodes an enabled blackhole route as a present empty flag", () => {
const fields = { comment: name + ":default-discard-4", "routing-table": name, "dst-address": "0.0.0.0/0", blackhole: "yes" }
const discard = { ...route, fields }
@@ -8,7 +8,8 @@ import { audit } from "../modules/mcp/store.js"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixManagedGreFields, ixNamespace } from "./internet-exchange-plan.js"
import { greIpsecPaths } from "./gre-ipsec-transport.js"
import { archiveIxSegment, assertIxBondClientAssignments, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, assertIxSegmentWithoutBonds, ixBondClientId, ixKnownVpsClient, ixReservedLinuxPoolBlocks, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { MikrotikClient } from "./mikrotik.js"
import { ixGreClientTemplate, ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
@@ -59,6 +60,8 @@ const ipsecPolicyColumns = [".id", "action", "level", "tunnel", "protocol", "src
function normalize(field: string, value: string | undefined) {
if (["blackhole", "fib"].includes(field) && value === "") return "yes"
if (field === "ipsec-protocols") return value ?? "esp"
if (field === "template") return isTrue(value) ? "yes" : "no"
if (["disabled", "advertise", "blackhole", "multihop", "fib", "passive", "tunnel", "allow-fast-path", "passthrough"].includes(field)) {
return value === undefined ? null : isTrue(value) ? "yes" : "no"
}
@@ -75,8 +78,17 @@ function normalize(field: string, value: string | undefined) {
return value
}
function fieldMatches(row: NativeRow, fields: Record<string, string>, field: string) {
// RouterOS can omit disabled=no on GRE plaintext drops created without an explicit flag.
if (field === "disabled" && row.disabled === undefined && fields.disabled === "false" &&
fields.action === "drop" && fields.protocol === "gre" &&
((fields.chain === "input" && fields["ipsec-policy"] === "in,none") ||
(fields.chain === "output" && fields["ipsec-policy"] === "out,none"))) return true
return normalize(field, row[field]) === normalize(field, fields[field])
}
function matches(row: NativeRow, fields: Record<string, string>) {
return Object.entries(fields).every(([field, value]) => normalize(field, row[field]) === normalize(field, value))
return Object.keys(fields).every(field => fieldMatches(row, fields, field))
}
function rowsFor(device: NativeDevice, path: string) { return device.rows[path] ?? [] }
@@ -94,6 +106,11 @@ function verifyNativeId(row: NativeRow) {
export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[], resume = false): Task[] {
const namespace = ixNamespace(id)
const egressObject = (comment = "") => comment.startsWith(namespace + ":egress-")
const legacyMssIngress = (row: NativeRow, fields: Record<string, string>) => {
const prefix = namespace + ":linux-mss-from-"
return fields.disabled === "true" && fields.action === "change-mss" && fields.comment?.startsWith(prefix) &&
matches(row, { ...fields, chain: "prerouting", "in-interface": fields.comment.slice(prefix.length) })
}
const withEgressList = new Set(devices.filter(device => Object.values(device.rows).some(rows =>
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
// An older applied revision had no egress list. A partial set still needs reconciliation.
@@ -115,7 +132,9 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
const tunnel = ["/interface/wireguard", "/interface/gre"].includes(object.path)
const managedTunnel = tunnel && [":wg-il-", ":gre-il-", ":transit-it-"].some(sign => object.fields.comment?.includes(sign))
const alreadyStopped = managedTunnel && resume && row && matches(row, { ...object.fields, disabled: "true" })
if (!row || !alreadyStopped && !matches(row, object.fields)) throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
if (!row || !alreadyStopped && !matches(row, object.fields) && !legacyMssIngress(row, object.fields)) {
throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
}
const task = { serverId: object.serverId, path: object.path, rosId: verifyNativeId(row), before: row }
if (managedTunnel && !isTrue(row.disabled)) shutdown.push({ ...task, fields: { disabled: "true" } })
const steps = tunnel ? interfaceCleanup : result
@@ -129,21 +148,24 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
throw new IxConflict("Служебный next hop BGP уже занят в таблице main")
}
if (resume && row && !isTrue(row.invalid) && matches(row, object.fields)) { verifyNativeId(row); continue }
if (row && !previousByKey.has(deviceMarker(object))) {
const before = previousByKey.get(deviceMarker(object)) ??
(resume && row && legacyMssIngress(row, object.fields) ? object : undefined)
if (row && !before) {
throw new IxConflict(object.fields.comment ? "Найден объект незавершённой операции IX. Сначала выполните сверку" :
"Имя объекта IX уже занято. Сначала выполните сверку")
}
if (row) {
const before = previousByKey.get(deviceMarker(object))!
if (!matches(row, before.fields)) throw new IxConflict("Объект IX изменён вне операции")
if (row && before) {
const differences = Object.keys(before.fields).filter(field => !fieldMatches(row, before.fields, field))
if (differences.length && !legacyMssIngress(row, before.fields)) throw new IxConflict("Объект IX изменён вне операции · узел " + object.serverId + " · " + path +
" · " + (object.fields.comment ?? object.fields.name) + " · " + differences.join(", "))
if (Object.keys(before.fields).some(field => !(field in object.fields))) {
throw new IxConflict("Поле RouterOS нельзя неявно сбросить. Замените объект с новым идентификатором")
}
const fields = Object.fromEntries(Object.entries(object.fields).filter(([field, value]) => normalize(field, row[field]) !== normalize(field, value)))
const fields = Object.fromEntries(Object.entries(object.fields).filter(([field]) => !fieldMatches(row, object.fields, field)))
if (Object.keys(fields).length) result.push({ serverId: object.serverId, path, rosId: verifyNativeId(row), fields, before: row })
continue
}
if (previousByKey.has(deviceMarker(object))) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
if (before) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
const foreign = rowsFor(device, path).some(entry => !entry.comment?.startsWith(namespace + ":") &&
(object.fields.name && entry.name === object.fields.name || object.fields.chain && entry.chain === object.fields.chain && path === "/routing/filter/rule" ||
object.fields["routing-table"] && entry["routing-table"] === namespace && !isTrue(entry.dynamic)))
@@ -448,7 +470,7 @@ export async function configureIxTransit(segment: IxSegment, input: IxTransitReq
return configuration
}
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false): Promise<NativeDevice> {
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false, verifyExternalGre = false): Promise<NativeDevice> {
const client = MikrotikClient.fromServer(server)
const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]],
["/ip/vrf", columns], ["/ip/route", columns], ["/ipv6/route", columns]])
@@ -461,7 +483,7 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[], removing
...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])])
}
if (fieldsByPath.has("/interface/list")) fieldsByPath.get("/interface/list")!.push("include", "exclude")
if (objects.some(object => object.fields["ipsec-policy"])) {
if (verifyExternalGre) {
fieldsByPath.set("/interface/gre", [...new Set([...greColumns, ...(fieldsByPath.get("/interface/gre") ?? [])])])
fieldsByPath.set("/ip/ipsec/policy", [...new Set([...ipsecPolicyColumns, ...(fieldsByPath.get("/ip/ipsec/policy") ?? [])])])
}
@@ -474,14 +496,10 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[], removing
return { serverId: server.id, source: fingerprint(server), rows }
}
function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: NativeRow[], policies: NativeRow[]) {
function verifyGreInterface(binding: IxSite["interfaces"][number], interfaces: NativeRow[]) {
const gre = interfaces.find(row => row.name === binding.name)
const policy = policies.some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint || !policy) {
throw new IxConflict("Для " + binding.name + " не подтверждены адреса и обязательная политика GRE/IPsec")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint) {
throw new IxConflict("Для " + binding.name + " не подтверждены внешние адреса GRE")
}
if (!["false", "no"].includes(gre["allow-fast-path"])) {
throw new IxConflict("Отключите FastPath на интерфейсе GRE/IPsec " + binding.name)
@@ -489,6 +507,14 @@ function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: Nat
return gre
}
function verifyGrePolicy(binding: IxSite["interfaces"][number], policies: NativeRow[]) {
const policy = policies.some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!policy) throw new IxConflict("Для " + binding.name + " не подтверждена обязательная политика GRE/IPsec")
}
/** Inspect operator-owned transports without running the provisioning or VRF planner. */
export async function verifyIxExistingTransport(segmentId: string, serverId: number, name: string, path: IxExistingTransport) {
const client = await requiredIxNode(serverId)
@@ -517,7 +543,9 @@ export async function verifyIxExistingTransport(segmentId: string, serverId: num
if (path.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns)])
const gre = verifyGreBinding({ name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }, interfaces, policies)
const binding = { name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }
const gre = verifyGreInterface(binding, interfaces)
verifyGrePolicy(binding, policies)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс отключён: " + name)
if (!sameIP(local.network, path.address) && !inIxNetwork(local.address, path.address)) {
const routes = await readRows(client, isIP(path.address) === 4 ? "/ip/route" : "/ipv6/route", ["dst-address", "gateway", "immediate-gw", "disabled"])
@@ -582,8 +610,9 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
gateway.trim().split("@")[0].split("%").at(-1) === binding.name))) {
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
}
if (binding.kind === "gre-ipsec") {
verifyGreBinding(binding, rowsFor(device, "/interface/gre"), rowsFor(device, "/ip/ipsec/policy"))
if (binding.kind === "gre-ipsec" && !binding.provisionGre) {
verifyGreInterface(binding, rowsFor(device, "/interface/gre"))
verifyGrePolicy(binding, rowsFor(device, "/ip/ipsec/policy"))
}
}
}
@@ -648,7 +677,8 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
if (site?.autoRouterId && (await observedIxRouterIds(MikrotikClient.fromServer(server), id)).has(site.routerId)) {
throw new IxConflict("Router ID " + site.routerId + " уже используется на CHR")
}
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
const verifyExternalGre = site?.interfaces.some(binding => binding.kind === "gre-ipsec" && !binding.provisionGre)
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration, verifyExternalGre))
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
}
if (configuration) validateBindings(configuration, id, before, resume ? objects.concat(previous) : previous)
@@ -673,10 +703,19 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
async function assertIxResume(id: string, revision: number, native: IxNativeChange) {
const { rows: [attempt] } = await pool.query<{ sources: unknown }>(`
SELECT payload->'sources' AS sources FROM mcp_audit
WHERE action='ix.web.apply_started' AND payload->>'segmentId'=$1 AND payload->>'revision'=$2
ORDER BY id DESC LIMIT 1
`, [id, String(revision)])
WITH last_attempt AS (
SELECT payload FROM mcp_audit
WHERE action='ix.web.apply_started' AND payload->>'segmentId'=$1::uuid::text
ORDER BY id DESC LIMIT 1
)
SELECT last_attempt.payload->'sources' AS sources
FROM last_attempt
JOIN ix_segments s ON s.id=$1
JOIN ix_segment_revisions draft ON draft.segment_id=s.id AND draft.revision=s.revision
JOIN ix_segment_revisions started ON started.segment_id=s.id AND started.revision::text=last_attempt.payload->>'revision'
WHERE draft.revision=$2 AND started.revision>COALESCE(s.applied_revision,0)
AND started.revision<=draft.revision AND started.configuration=draft.configuration
`, [id, revision])
const sources = native.before.map(device => [device.serverId, device.source])
if (!attempt || fingerprint(attempt.sources) !== fingerprint(sources)) {
throw new IxConflict("Нет подтверждённой попытки применения этой ревизии к этим устройствам")
@@ -889,11 +928,24 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
}
const client = MikrotikClient.fromServer(server)
if (binding.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([
readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns),
])
if (isTrue(verifyGreBinding(binding, interfaces, policies).disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
const interfaces = await readRows(client, "/interface/gre", [...greColumns, "disabled"])
const gre = verifyGreInterface(binding, interfaces)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
if (binding.provisionGre) {
const { peer, policy } = ixManagedGreFields(ixNamespace(segment.id), binding)
const [peers, policies] = await Promise.all([
readRows(client, greIpsecPaths.peer, [".id", "dynamic", ...Object.keys(peer)]),
readRows(client, greIpsecPaths.policy, [".id", "dynamic", ...Object.keys(policy)]),
])
const device = { serverId, source: "", rows: { [greIpsecPaths.peer]: peers, [greIpsecPaths.policy]: policies } }
for (const [path, fields] of [[greIpsecPaths.peer, peer], [greIpsecPaths.policy, policy]] as const) {
const row = managedRow(device, { serverId, path, fields })
if (!row || !matches(row, fields)) throw new IxConflict("Пир или политика GRE/IPsec изменены на узле · " + name)
verifyNativeId(row)
}
} else {
verifyGrePolicy(binding, await readRows(client, greIpsecPaths.policy, ipsecPolicyColumns))
}
if (includeCredential && !binding.provisionGre) throw new IxConflict("IX не выдавал этот IKEv2 PSK", 404)
const credential = includeCredential && binding.provisionGre
? (await privateFingerprinterExisting("ix-gre-client-credential-v1"))(segment.id + ":" + serverId + ":ix-credential:" + binding.provisionGre.credentialId)
@@ -974,7 +1026,7 @@ async function applyNativeTasks(native: IxNativeChange, authorize: () => Promise
if (!returnedId || !routerId.test(returnedId)) throw new IxConflict("RouterOS не подтвердил ID объекта IX")
const row = (await readRows(client, task.path, [".id", ...Object.keys(task.fields)])).find(entry => entry[".id"] === returnedId)
if (!row || !matches(row, task.fields)) {
const fields = row ? Object.keys(task.fields).filter(field => normalize(field, row[field]) !== normalize(field, task.fields![field])) : []
const fields = row ? Object.keys(task.fields).filter(field => !fieldMatches(row, task.fields!, field)) : []
throw new IxConflict("Перечитанный объект IX не совпал с планом · " + task.path + (fields.length ? " · " + fields.join(", ") : ""))
}
const vrfName = task.path === "/ip/vrf" ? task.fields.name : undefined
@@ -32,8 +32,7 @@ test("managed clients get their own return path and fail closed if both exit pro
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
const objects = compileIxConfiguration(id, value)
const clamp = objects.findIndex(object => object.fields.comment === table + ":linux-mss-from-linux-wg")
assert.ok(clamp >= 0 && clamp < objects.findIndex(object => object.fields.comment === table + ":linux-linux-wg-route"))
assert.equal(objects.find(object => object.fields.comment === table + ":linux-linux-wg-route")?.fields.chain, "prerouting")
const clientTable = ixClientRoutingTable(table, "linux-wg")
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
@@ -47,7 +46,7 @@ test("managed clients get their own return path and fail closed if both exit pro
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
})
test("managed Linux tunnels clamp TCP SYN in both directions before routing marks can end prerouting", () => {
test("managed Linux tunnels clamp TCP SYN in forward from IX and postrouting to the tunnel", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push(
{ name: "linux-wg", kind: "wireguard", prefixes: [], linux: { name: "vps", enabled: true, destinations: [] },
@@ -69,7 +68,7 @@ test("managed Linux tunnels clamp TCP SYN in both directions before routing mark
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled }
assert.deepEqual(rules.filter(object => object.fields.comment.endsWith("-" + binding)), [
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "prerouting", "in-interface": binding, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
fields: { ...shared, chain: "forward", "in-interface": table, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "postrouting", "out-interface": binding, "dst-address-list": list, comment: table + ":linux-mss-to-" + binding } },
])
+15 -8
View File
@@ -28,6 +28,15 @@ const forbiddenPublic = {
}
export function ixNamespace(id: string) { return "ix-" + id.replace(/-/g, "").slice(0, 18) }
export function ixManagedGreFields(namespace: string, binding: IxSite["interfaces"][number]) {
const name = namespace + "-" + binding.name
const fields = greIke2TransportFields(name, binding.localEndpoint!, binding.endpoint!, true,
"ix-credential:" + binding.provisionGre!.credentialId, !binding.linux!.enabled)
// RouterOS derives transport-mode selectors from the active SA.
const { "src-address": _source, "dst-address": _destination, ...policy } = fields.policy
return { ...fields, peer: { ...fields.peer, disabled: "false" },
policy: { ...policy, disabled: "false", template: "false", "ipsec-protocols": "esp", comment: namespace + ":gre-policy-" + binding.name } }
}
// RouterOS accepts unambiguous prefixes for interface names before the VRF interface appears.
export function ixDiscardInterface(id: string) { return "ix-drop-" + ixNamespace(id).slice(3) }
export function ixEgressList(id: string) { return "ix-out-" + ixNamespace(id).slice(3) }
@@ -120,9 +129,9 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
action: "accept", disabled: String(!policy.enabled) })
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
// The real VRF member is visible before routing and after routing, respectively.
// RouterOS allows MSS changes in forward, where ingress is the virtual VRF interface.
add(mangle, "linux-mss-from-" + binding.name, {
...clamp, ...ingress, "src-address-list": sources,
...clamp, chain: "forward", "in-interface": namespace, "src-address-list": sources,
})
add(mangle, "linux-mss-to-" + binding.name, {
...clamp, chain: "postrouting", "out-interface": binding.name, "dst-address-list": sources,
@@ -284,8 +293,8 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
}
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
const [inbound, outbound] = greIpsecPlaintextDrops(binding.localEndpoint!, binding.endpoint!)
add(greIpsecPaths.filter, "gre-in-" + key, inbound)
add(greIpsecPaths.filter, "gre-out-" + key, outbound)
add(greIpsecPaths.filter, "gre-in-" + key, { ...inbound, disabled: "false" })
add(greIpsecPaths.filter, "gre-out-" + key, { ...outbound, disabled: "false" })
}
const dropInterface = ixDiscardInterface(id)
for (const [index, binding] of site.interfaces.entries()) {
@@ -294,11 +303,9 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
if (binding.provisionTransit) compileIxTransit(namespace, site, binding, object => result.push(object))
if (wireguard) add("/interface/wireguard", "wg-" + key, { name: binding.name, "listen-port": String(wireguard.listenPort),
...(binding.linux && { disabled: String(!binding.linux.enabled) }) })
const gre = binding.provisionGre
if (gre) {
const transport = namespace + "-" + key
if (binding.provisionGre) {
protectGre(binding, key)
const fields = greIke2TransportFields(transport, binding.localEndpoint!, binding.endpoint!, true, "ix-credential:" + gre.credentialId, !binding.linux!.enabled)
const fields = ixManagedGreFields(namespace, binding)
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)