Files
MikrotikManager/backend/src/services/wireguard-config.test.ts
T

164 lines
10 KiB
TypeScript

import assert from "node:assert/strict"
import {
detectWgConfigFormat,
generateMikrotikRsc,
generateNativeConf,
parseMikrotikRsc,
parseNativeConf,
parseWgConfig,
generatePeerClientConf,
WG_CONFIG_LIMITS,
splitWgEndpoint,
formatWgEndpoint,
} from "./wireguard-config.js"
import { parseWireguardImport } from "./wireguard-import.js"
const sampleConf = `[Interface]
PrivateKey = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=
Address = 10.210.0.1/30
ListenPort = 13231
MTU = 1420
[Peer]
PublicKey = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=
AllowedIPs = 10.210.0.2/32, 192.168.20.0/24
Endpoint = 10.0.1.1:13231
PersistentKeepalive = 25
`
const parsedConf = parseNativeConf(sampleConf)
assert.equal(parsedConf.format, "conf")
assert.equal(parsedConf.interface.listenPort, 13231)
assert.equal(parsedConf.interface.address, "10.210.0.1/30")
assert.equal(parsedConf.peers.length, 1)
assert.equal(parsedConf.peers[0]?.endpointAddress, "10.0.1.1")
assert.equal(parsedConf.peers[0]?.endpointPort, 13231)
assert.deepEqual(parsedConf.peers[0]?.allowedAddresses, ["10.210.0.2/32", "192.168.20.0/24"])
const roundConf = generateNativeConf({
name: "wg0",
listenPort: parsedConf.interface.listenPort ?? 13231,
mtu: parsedConf.interface.mtu ?? 1420,
privateKey: parsedConf.interface.privateKey,
address: parsedConf.interface.address,
peers: parsedConf.peers.map((p) => ({
publicKey: p.publicKey,
allowedIps: p.allowedAddresses,
endpoint: p.endpointAddress
? `${p.endpointAddress}:${p.endpointPort ?? 13231}`
: undefined,
persistentKeepalive: p.persistentKeepalive,
})),
}, { includePrivateKey: true })
const reparsed = parseNativeConf(roundConf)
assert.equal(reparsed.interface.privateKey, parsedConf.interface.privateKey)
assert.equal(reparsed.peers[0]?.publicKey, parsedConf.peers[0]?.publicKey)
const sampleRsc = `# WireGuard
/interface wireguard add \\
name=wg-msk-spb \\
listen-port=13231 \\
mtu=1420 \\
comment="MSK → SPB"
/ip address add \\
address=10.210.0.1/30 \\
interface=wg-msk-spb
/interface wireguard peers add \\
interface=wg-msk-spb \\
public-key="SPBPublicKeyBase64AAAAAAAAAAAAAAAAAAAAAA=" \\
allowed-address=10.210.0.2/32,192.168.20.0/24 \\
endpoint-address=10.0.1.1 \\
endpoint-port=13231 \\
persistent-keepalive=25
`
assert.equal(detectWgConfigFormat(sampleRsc), "rsc")
assert.equal(detectWgConfigFormat(sampleConf), "conf")
const parsedRsc = parseMikrotikRsc(sampleRsc)
assert.equal(parsedRsc.interface.name, "wg-msk-spb")
assert.equal(parsedRsc.interface.address, "10.210.0.1/30")
assert.equal(parsedRsc.peers.length, 1)
assert.equal(parsedRsc.peers[0]?.endpointPort, 13231)
const generatedRsc = generateMikrotikRsc({
name: parsedRsc.interface.name,
listenPort: parsedRsc.interface.listenPort ?? 13231,
mtu: parsedRsc.interface.mtu ?? 1420,
comment: parsedRsc.interface.comment,
address: parsedRsc.interface.address,
peers: parsedRsc.peers.map((p) => ({
publicKey: p.publicKey,
allowedIps: p.allowedAddresses,
endpoint: p.endpointAddress
? `${p.endpointAddress}:${p.endpointPort ?? 13231}`
: undefined,
persistentKeepalive: p.persistentKeepalive,
})),
})
const rscAgain = parseWgConfig(generatedRsc, "rsc")
assert.equal(rscAgain.interface.name, "wg-msk-spb")
assert.equal(rscAgain.peers[0]?.publicKey, parsedRsc.peers[0]?.publicKey)
console.log("wireguard-config tests ok")
const privateKey = Buffer.alloc(32, 81).toString("base64"), peerKey = Buffer.alloc(32, 82).toString("base64"), otherKey = Buffer.alloc(32, 83).toString("base64"), peerPrivate = Buffer.alloc(32, 84).toString("base64")
const literal = 'Юникод 😀 "quotes" \\ $[ /system reboot ]; ${variable} [x] #tag'
const full = { name: 'wg "edge" \\ $() [1]; тест', enabled: false, mtu: 1380, listenPort: 24567, privateKey, address: "2001:db8::1/64", comment: literal,
peers: [{ publicKey: peerKey, allowedIps: ["192.0.2.2/32", "2001:db8::2/128"], endpoint: "[2001:db8::10]:33445", persistentKeepalive: 0, disabled: true, privateKey: peerPrivate, name: literal, comment: literal, clientAddress: "192.0.2.2", clientDns: "1.1.1.1", clientEndpoint: literal },
{ publicKey: otherKey, allowedIps: ["198.51.100.2/32"], disabled: false, privateKey: "none", endpointAddress: "vpn.example.test", endpointPort: 12345 }] }
const fullRsc = generateMikrotikRsc(full, { includePrivateKey: true }), decoded = parseWireguardImport(fullRsc, "rsc")
assert.equal(decoded.interface.name, full.name); assert.equal(decoded.interface.comment, literal); assert.equal(decoded.interface.privateKey, privateKey); assert.equal(decoded.interface.disabled, true)
assert.equal(decoded.peers.length, 2); assert.equal(decoded.peers[0].name, literal); assert.equal(decoded.peers[0].comment, literal); assert.equal(decoded.peers[0].clientEndpoint, literal)
assert.equal(decoded.peers[0].privateKey, peerPrivate); assert.equal(decoded.peers[0].disabled, true); assert.equal(decoded.peers[1].disabled, false); assert.equal(decoded.peers[1].privateKey, "none")
assert.equal(decoded.peers[0].endpointAddress, "2001:db8::10"); assert.equal(decoded.peers[0].endpointPort, 33445); assert.equal(decoded.peers[0].persistentKeepalive, 0)
assert.deepEqual(splitWgEndpoint(formatWgEndpoint("2001:db8::10", 33445)), { address: "2001:db8::10", port: 33445 })
assert.equal(fullRsc.includes("\\$["), true); assert.equal(fullRsc.includes('comment="'), true)
for (const comment of ['\\$name', '\\"quoted"', '$()', '$[]', 'slash\\end', '#;[]{}()', '😀\\$"; [ :put x ]']) assert.equal(parseMikrotikRsc(generateMikrotikRsc({ name: "literal", mtu: 1420, comment, peers: [] })).interface.comment, comment)
for (const flags of [undefined, { includePrivateKey: false }]) {
const redacted = generateMikrotikRsc(full, flags)
assert.equal(redacted.includes(privateKey), false); assert.equal(redacted.includes(peerPrivate), false); assert.equal(parseMikrotikRsc(redacted).interface.privateKey, undefined)
assert.equal(parseMikrotikRsc(redacted).peers[1].privateKey, "none")
const confWithoutKey = generateNativeConf({ ...full, enabled: true, peers: [{ ...full.peers[0], disabled: false }] }, flags)
assert.equal(confWithoutKey.includes(privateKey), false); assert.equal(confWithoutKey.includes(peerPrivate), false)
assert.equal(generatePeerClientConf({ peerPrivateKey: privateKey, serverPublicKey: peerKey }, flags).includes(privateKey), false)
}
const interop = generateNativeConf({ name: "wg0", mtu: 1420, privateKey, address: "192.0.2.1/24", peers: [{ publicKey: peerKey, allowedIps: ["0.0.0.0/0"], endpoint: "[2001:db8::10]:33445", persistentKeepalive: 0 }] }, { includePrivateKey: true })
assert.equal(parseWireguardImport(interop, "conf").interface.privateKey, privateKey); assert.equal(parseWireguardImport(interop, "conf").peers[0].persistentKeepalive, 0)
assert.equal(generatePeerClientConf({ peerPrivateKey: privateKey, serverPublicKey: peerKey }, { includePrivateKey: true }).includes(privateKey), true)
assert.throws(() => generateMikrotikRsc({ ...full, comment: privateKey }), /Приватный ключ/)
assert.throws(() => generateNativeConf({ ...full, enabled: true, peers: [{ ...full.peers[0], disabled: false, comment: peerPrivate }] }), /Приватный ключ/)
assert.throws(() => generatePeerClientConf({ peerPrivateKey: privateKey, serverPublicKey: privateKey }), /Приватный ключ/)
assert.throws(() => generateNativeConf(full, { includePrivateKey: true }), /Отключённые/)
assert.throws(() => generateNativeConf({ ...full, enabled: true }, { includePrivateKey: true }), /Отключённые/)
for (const unsafe of ["[2001:db8::10]", "2001:db8::10:33445", "host:0", "host:65536", "host;ignored:22", "host\nPostUp=x:22", "[fe80::1%eth0]:22"]) assert.throws(() => splitWgEndpoint(unsafe))
for (const source of [
'/interface wireguard add name="$[ /system reboot ]"',
'/interface wireguard add name=[/system identity get name]',
'/interface wireguard add name="wg"; /system reboot',
'/interface wireguard add name="wg" /system reboot',
'/interface wireguard add name="wg" name="duplicate"',
'/interface wireguard add name="wg" on-up="NEVER_SCRIPT"',
'/interface wireguard add name="unterminated',
'/interface wireguard add name="wg"\n/system reboot',
'/interface wireguard add name="wg"\n/interface wireguard add name="other"',
'/interface wireguard add name="wg"\\',
'/interface wireguard add name="\\nNEVER_SCRIPT"',
'/interface wireguard add name="wg" comment="\\ff"',
]) assert.throws(() => parseMikrotikRsc(source), (error: Error) => !error.message.includes("NEVER_SCRIPT"))
assert.equal(parseMikrotikRsc('/interface wireguard add name="\\D0\\9C\\D0\\9A"').interface.name, "МК")
const multiline = 'line one\n/system reboot\r\n[Peer]\rPrivateKey = literal\t$[x] "quoted"'
const multilineSource = generateMikrotikRsc({ ...full, comment: multiline, peers: [{ ...full.peers[0], comment: multiline }] }, { includePrivateKey: true })
assert.equal(multilineSource.split("\n").filter(line => line.startsWith("/system")).length, 0)
const multilineParsed = parseWireguardImport(multilineSource, "rsc")
assert.equal(multilineParsed.interface.comment, multiline); assert.equal(multilineParsed.peers[0].comment, multiline)
const multilineConf = generateNativeConf({ ...full, enabled: true, comment: multiline, peers: [{ ...full.peers[0], disabled: false, comment: multiline }] }, { includePrivateKey: true })
assert.equal((multilineConf.match(/^\[Peer\]$/gm) ?? []).length, 1)
assert.ok(multilineConf.includes("# /system reboot")); assert.ok(multilineConf.includes("# PrivateKey = literal"))
assert.equal(parseNativeConf(multilineConf).peers.length, 1)
for (const bad of [{ ...full, name: "bad\nname" }, { ...full, comment: "bad\0comment" }, { ...full, peers: [{ ...full.peers[0], name: "bad\npeer" }] }]) assert.throws(() => generateMikrotikRsc(bad))
for (const source of ["#".repeat(WG_CONFIG_LIMITS.bytes + 1), "\n".repeat(WG_CONFIG_LIMITS.lines), '#'.repeat(WG_CONFIG_LIMITS.lineBytes + 1), '/interface wireguard add name="' + "я".repeat(WG_CONFIG_LIMITS.tokenBytes / 2 + 1) + '"']) assert.throws(() => parseWgConfig(source, "rsc"))
console.log("WireGuard codecs: explicit secret flags, literal RSC escaping, all peer fields and disabled state, bracket IPv6, zero keepalive, unknown/script rejection and UTF-8 work bounds passed")