Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63c0fc6506 | ||
|
|
682d6c8d55 |
No files matched your search
@@ -85,6 +85,17 @@ const firewall = {
|
||||
"src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(),
|
||||
comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(),
|
||||
}
|
||||
const ipv4Mangle = {
|
||||
...firewall,
|
||||
"tcp-flags": z.string().regex(/^!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)(?:,!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)){0,7}$/)
|
||||
.refine(value => new Set(value.replaceAll("!", "").split(",")).size === value.split(",").length, "Флаги TCP не должны повторяться").optional(),
|
||||
"tcp-mss": z.string().regex(/^(?:0|[1-9]\d{0,4})(?:-(?:0|[1-9]\d{0,4}))?$/).refine(value => {
|
||||
const [min, max = min] = value.split("-").map(Number)
|
||||
return min <= max && max <= 65535
|
||||
}, "Требуется значение или диапазон TCP MSS от 0 до 65535").optional(),
|
||||
"new-mss": integer(1, 65535).optional(),
|
||||
passthrough: bool.optional(),
|
||||
}
|
||||
const route = {
|
||||
"dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(),
|
||||
"target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(),
|
||||
@@ -112,7 +123,7 @@ export const rosResources: RosResourceSpec[] = [
|
||||
{ id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] },
|
||||
{ id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
|
||||
{ id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
|
||||
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
|
||||
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(family === "ip" && table === "mangle" ? ipv4Mangle : firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
|
||||
{ id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] },
|
||||
{ id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] },
|
||||
{ id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] },
|
||||
@@ -154,7 +165,7 @@ export function supportsRosPlacement(step: Pick<RosStep, "resource" | "action" |
|
||||
export const ROS_SNAPSHOT_VERSION = 3
|
||||
// OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused.
|
||||
export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource)
|
||||
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
|
||||
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd", "ip_mangle"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
|
||||
export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string }
|
||||
const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"]
|
||||
const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"])
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
|
||||
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, validateRosStep, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
|
||||
import { fingerprint } from "./security.js"
|
||||
import { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.js"
|
||||
import { readOspfTemplateFlags } from "../../services/ospf-template-flags.js"
|
||||
@@ -24,6 +24,26 @@ assert.equal(check(create, ack, [a, b], [a, b, { ...c, action: "drop" }]), false
|
||||
assert.equal(check(create, undefined, [a], [a, c]), false, "Observed object never substitutes a lost acknowledgement")
|
||||
assert.equal(check({ ...create, id: "*A" }, ack, [a], [a, c]), false)
|
||||
|
||||
const mangle = resourceById("ip_mangle")
|
||||
const mssFields = {
|
||||
chain: "forward", "out-interface": "gre-ix", "dst-address": "192.0.2.2/32", protocol: "tcp",
|
||||
"tcp-flags": "syn,ack", "tcp-mss": "1381-65535", action: "change-mss", "new-mss": 1380, passthrough: true,
|
||||
}
|
||||
const mss = { ...create, resource: mangle.id, fields: validateRosStep(mangle, "create", mssFields) }
|
||||
const liveMss = { ...mss.fields, ".id": "*C", "dst-address": "192.0.2.2", "tcp-flags": "ack,syn", passthrough: "yes", packets: "3" }
|
||||
const mangleRows = (rows: ConfigurationRow[]) => configurationRows(mangle, rows)
|
||||
assert.equal(check(mss, ack, [], mangleRows([liveMss])), true)
|
||||
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "new-mss": "1460" }])), false)
|
||||
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "dst-address": "192.0.2.2/24" }])), false)
|
||||
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "tcp-flags": "syn,!ack" }])), false)
|
||||
const mssUpdate = { ...mss, action: "update" as const, id: "*C", fields: validateRosStep(mangle, "update", { "new-mss": 1360 }, "*C") }
|
||||
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360" }])), true)
|
||||
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360", "tcp-mss": "1361-65535" }])), false)
|
||||
for (const bad of [{ "new-mss": 65536 }, { "tcp-mss": "1400-1300" }, { "tcp-mss": "1-65536" }, { "tcp-flags": "syn,!syn" }, { passthrough: "yes" }]) {
|
||||
assert.throws(() => validateRosStep(mangle, "create", { ...mssFields, ...bad }))
|
||||
}
|
||||
assert.equal(resourceById("ip_filter").fields.safeParse(mssFields).success, false)
|
||||
|
||||
const update: RosStep = { ...create, action: "update", id: "*A", fields: { action: "accept" } }
|
||||
const updated = { ...a, action: "accept" }
|
||||
assert.equal(check(update, {}, [a, b], [updated, b]), true)
|
||||
|
||||
@@ -29,6 +29,10 @@ function requested(resource: RosResourceSpec, fields: RosStep["fields"], row: Co
|
||||
if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) {
|
||||
try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false }
|
||||
}
|
||||
if (resource.id === "ip_mangle") {
|
||||
if (key === "dst-address" || key === "src-address") return String(row[key]).replace(/\/32$/, "") === value.replace(/\/32$/, "")
|
||||
if (key === "tcp-flags" && schema.safeParse(row[key]).success) return String(row[key]).split(",").sort().join(",") === value.split(",").sort().join(",")
|
||||
}
|
||||
return String(row[key]) === value
|
||||
})
|
||||
}
|
||||
|
||||
@@ -14,6 +14,26 @@ const route: IxRouterObject = {
|
||||
}
|
||||
const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }]
|
||||
|
||||
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" } }
|
||||
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" }
|
||||
const fromRow = { ...from.fields, ".id": "*B" }
|
||||
const toRow = { ...to.fields, ".id": "*C" }
|
||||
const desired = [from, to]
|
||||
const live = (rows: Array<Record<string, string>>) => device({ [path]: rows })
|
||||
assert.deepEqual(planIxNative(id, desired, desired, live([manual])).map(task => [task.fields, task.placeBefore]),
|
||||
[[from.fields, "*A"], [to.fields, "*A"]])
|
||||
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, manual])).map(task => task.fields), [to.fields])
|
||||
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, toRow, manual])), [])
|
||||
assert.deepEqual(planIxNative(id, [], desired, live([fromRow, toRow, manual])).map(task => task.rosId), ["*C", "*B"])
|
||||
assert.throws(() => planIxNative(id, desired, [], live([fromRow, manual])), /незавершённой операции/)
|
||||
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
|
||||
})
|
||||
|
||||
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" }],
|
||||
|
||||
@@ -98,6 +98,9 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
|
||||
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
|
||||
// An older applied revision had no egress list. A partial set still needs reconciliation.
|
||||
previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId))
|
||||
// Older revisions were compiled without MSS rules. Backfill only absent managed MSS rules.
|
||||
previous = previous.filter(object => !object.fields.comment?.startsWith(namespace + ":linux-mss-") ||
|
||||
devices.some(device => device.serverId === object.serverId && managedRow(device, object)))
|
||||
const desiredKeys = new Set(desired.map(deviceMarker))
|
||||
const previousByKey = new Map(previous.map(object => [deviceMarker(object), object]))
|
||||
const result: Task[] = []
|
||||
@@ -356,7 +359,7 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
|
||||
const binding: IxSite["interfaces"][number] = {
|
||||
name, kind: input.kind, prefixes: input.prefixes,
|
||||
linux: { name: input.name, clientId: previous?.linux?.clientId, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
|
||||
exit: input.exit === "local-wan" ? localExit : input.exit },
|
||||
tunnelMtu: input.tunnelMtu ?? previous?.linux?.tunnelMtu, exit: input.exit === "local-wan" ? localExit : input.exit },
|
||||
}
|
||||
if (input.kind === "wireguard") {
|
||||
const existing = previous?.provisionWireguard
|
||||
|
||||
@@ -32,6 +32,8 @@ 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"))
|
||||
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"])
|
||||
@@ -45,6 +47,35 @@ 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", () => {
|
||||
const value = fixture(), site = value.sites[0]
|
||||
site.interfaces.push(
|
||||
{ name: "linux-wg", kind: "wireguard", prefixes: [], linux: { name: "vps", enabled: true, destinations: [] },
|
||||
provisionWireguard: { localAddress: "10.254.0.1/30", peerAddress: "10.254.0.2", listenPort: 51820, peerPublicKey: "A".repeat(43) + "=" } },
|
||||
{ name: "linux-gre", kind: "gre-ipsec", prefixes: [], endpoint: "192.0.2.90", localEndpoint: "192.0.2.17",
|
||||
linux: { name: "vps", enabled: false, destinations: [] },
|
||||
provisionGre: { localAddress: "10.254.0.5/30", peerAddress: "10.254.0.6", credentialId: id } },
|
||||
{ name: "linux-wg6", kind: "wireguard", prefixes: [],
|
||||
linux: { name: "vps6", enabled: true, destinations: [], tunnelMtu: 1360 },
|
||||
provisionWireguard: { localAddress: "fd00:254::1/126", peerAddress: "fd00:254::2", listenPort: 51821, peerPublicKey: "B".repeat(43) + "=" } },
|
||||
)
|
||||
const rules = compileIxConfiguration(id, ixSegmentConfigurationSchema.parse(value)).filter(object => object.fields.action === "change-mss")
|
||||
assert.equal(rules.length, 6)
|
||||
for (const [binding, family, mss, disabled] of [
|
||||
["linux-wg", "ip", 1380, "false"], ["linux-gre", "ip", 1380, "true"], ["linux-wg6", "ipv6", 1300, "false"],
|
||||
] as const) {
|
||||
const list = ixClientRoutingTable(table, binding) + "-src"
|
||||
const shared = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
|
||||
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 } },
|
||||
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
|
||||
fields: { ...shared, chain: "postrouting", "out-interface": binding, "dst-address-list": list, comment: table + ":linux-mss-to-" + binding } },
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => {
|
||||
const value = fixture(), site = value.sites[0]
|
||||
site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99,
|
||||
|
||||
@@ -84,6 +84,11 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
|
||||
const permitted = privateTable + "-dst"
|
||||
const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])]
|
||||
const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])]
|
||||
// Use the WireGuard default as a conservative ceiling for both managed tunnel types.
|
||||
const mss = (policy.tunnelMtu ?? 1420) - (family === 4 ? 40 : 60)
|
||||
const clamp = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
|
||||
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled: String(!policy.enabled) }
|
||||
const mangle = ip + "/firewall/mangle"
|
||||
const ingress = { chain: "prerouting", "in-interface": binding.name }
|
||||
const exit = site.groups.find(group => group.id === policy.exit)
|
||||
const paths = exit ? groupPaths(exit) : []
|
||||
@@ -114,6 +119,13 @@ 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.
|
||||
add(mangle, "linux-mss-from-" + binding.name, {
|
||||
...clamp, ...ingress, "src-address-list": sources,
|
||||
})
|
||||
add(mangle, "linux-mss-to-" + binding.name, {
|
||||
...clamp, chain: "postrouting", "out-interface": binding.name, "dst-address-list": sources,
|
||||
})
|
||||
if (!exit) return
|
||||
add("/routing/table", key + "-table", { name: privateTable, fib: "true" })
|
||||
for (const [index, path] of paths.entries()) {
|
||||
@@ -122,7 +134,7 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
|
||||
})
|
||||
}
|
||||
add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
|
||||
add(ip + "/firewall/mangle", key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
|
||||
add(mangle, key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
|
||||
action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) })
|
||||
const mainPaths = paths.filter(path => path.viaMain)
|
||||
for (const [index, path] of mainPaths.entries()) {
|
||||
|
||||
@@ -48,6 +48,7 @@ const linuxPolicy = z.object({
|
||||
clientId: z.string().uuid().optional(),
|
||||
enabled: z.boolean(),
|
||||
destinations: z.array(prefix).max(64),
|
||||
tunnelMtu: z.number().int().min(1280).max(1420).optional(),
|
||||
exit: key.optional(),
|
||||
peerEndpoint: address.optional(),
|
||||
}).strict()
|
||||
@@ -152,6 +153,7 @@ export const ixLinuxClientRequest = z.object({
|
||||
peerAddress: address.optional(),
|
||||
prefixes: z.array(prefix).max(64).default([]),
|
||||
destinations: linuxPolicy.shape.destinations.default([]),
|
||||
tunnelMtu: linuxPolicy.shape.tunnelMtu,
|
||||
exit: key.optional(),
|
||||
transit: ixTransitOptions.optional(),
|
||||
rotate: z.boolean().optional(),
|
||||
|
||||
Reference in new issue
Block a user