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

331 lines
24 KiB
TypeScript

import { isIP } from "node:net"
/**
* WireGuard config codecs: native .conf ↔ MikroTik .rsc
*/
export type WgParsedPeer = {
publicKey: string
allowedAddresses: string[]
endpointAddress?: string
endpointPort?: number
persistentKeepalive?: number
comment?: string
name?: string
privateKey?: "auto" | "none" | string
clientAddress?: string
clientDns?: string
clientEndpoint?: string
disabled?: boolean
}
export type WgParsedInterface = {
name: string
listenPort?: number
mtu?: number
privateKey?: string
comment?: string
address?: string
disabled?: boolean
}
export type WgParsedConfig = {
format: "rsc" | "conf"
interface: WgParsedInterface
peers: WgParsedPeer[]
}
export type WgExportIface = {
name: string
listenPort?: number
mtu: number
comment?: string
enabled?: boolean
privateKey?: string
publicKey?: string
address?: string
serverName?: string
peers: Array<{
publicKey: string
allowedIps: string[]
endpoint?: string
endpointAddress?: string
endpointPort?: number
disabled?: boolean
privateKey?: string
persistentKeepalive?: number
persistent?: boolean
comment?: string
name?: string
clientAddress?: string
clientDns?: string
clientEndpoint?: string
}>
}
/** Limits bound decoded input and parser work, including content held in secret references. */
export const WG_CONFIG_LIMITS = Object.freeze({ bytes: 262144, lines: 4096, lineBytes: 16384, tokenBytes: 4096, peers: 100, addressesPerPeer: 100, fieldsPerCommand: 24 })
const invalid = (message = "Неподдерживаемая или неоднозначная конфигурация WireGuard") => new Error(message)
function text(value: string, multilineComment = false) {
if (typeof value !== "string" || Buffer.byteLength(value) > WG_CONFIG_LIMITS.tokenBytes || (multilineComment ? /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/ : /[\u0000-\u001f\u007f]/).test(value) || Buffer.from(value).toString("utf8") !== value) throw invalid()
return value
}
function inputLines(content: string) {
if (typeof content !== "string" || Buffer.byteLength(content) > WG_CONFIG_LIMITS.bytes || /\0/.test(content) || Buffer.from(content).toString("utf8") !== content) throw invalid("Превышен предел или некорректный текст конфигурации WireGuard")
const lines = content.replace(/\r\n|\r/g, "\n").split("\n")
if (lines.length > WG_CONFIG_LIMITS.lines || lines.some(line => Buffer.byteLength(line) > WG_CONFIG_LIMITS.lineBytes)) throw invalid("Превышен предел строк конфигурации WireGuard")
return lines
}
function integer(value: string, field: string) {
if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value))) throw invalid("Некорректный " + field)
return Number(value)
}
function boolean(value: string) {
if (value === "yes" || value === "true") return true
if (value === "no" || value === "false") return false
throw invalid("Некорректный disabled или флаг адреса WireGuard")
}
function list(value: string, field: string) {
const values = value.split(",").map(item => item.trim())
if (!values.length || values.length > WG_CONFIG_LIMITS.addressesPerPeer || values.some(item => !item)) throw invalid("Некорректный " + field)
return values
}
export function splitWgEndpoint(value: string): { address: string; port: number } {
text(value)
const match = value.match(/^(?:\[([^\]]+)\]|([^:\s\[\]]+)):(\d+)$/)
if (!match) throw invalid("Некорректный Endpoint: нужен host:port или [IPv6]:port")
const address = match[1] ?? match[2], port = integer(match[3], "Endpoint")
if (!address || (match[1] !== undefined && isIP(address) !== 6) || port < 1 || port > 65535 || !endpointHost(address)) throw invalid("Некорректный Endpoint")
return { address, port }
}
export function formatWgEndpoint(address: string, port: number) {
text(address)
if (!endpointHost(address) || !Number.isSafeInteger(port) || port < 1 || port > 65535) throw invalid("Некорректный Endpoint")
return `${isIP(address) === 6 ? `[${address}]` : address}:${port}`
}
function endpointHost(address: string) { return address.length <= 253 && !address.includes("%") && (isIP(address) !== 0 || /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.?$/i.test(address)) }
function peerEndpoint(peer: WgExportIface["peers"][number]) {
if (peer.endpointAddress !== undefined || peer.endpointPort !== undefined) {
if (peer.endpointAddress === undefined || peer.endpointPort === undefined) throw invalid("Неполный Endpoint")
const endpoint = formatWgEndpoint(peer.endpointAddress, peer.endpointPort)
if (peer.endpoint && formatWgEndpoint(splitWgEndpoint(peer.endpoint).address, splitWgEndpoint(peer.endpoint).port) !== endpoint) throw invalid("Противоречивый Endpoint")
return endpoint
}
if (!peer.endpoint) return undefined
const endpoint = splitWgEndpoint(peer.endpoint)
return formatWgEndpoint(endpoint.address, endpoint.port)
}
export function detectWgConfigFormat(content: string): "rsc" | "conf" {
const lines = inputLines(content).map(line => line.trim()).filter(line => line && !/^[#;]/.test(line))
return lines[0]?.startsWith("[") ? "conf" : "rsc"
}
export function parseNativeConf(content: string): WgParsedConfig {
const iface: WgParsedInterface = { name: "wg0" }, peers: WgParsedPeer[] = []
let section: "interface" | "peer" | undefined, current: WgParsedPeer | undefined, found = false, seen = new Set<string>()
for (const raw of inputLines(content)) {
const line = raw.trim()
if (!line || /^[#;]/.test(line)) continue
if (line.startsWith("[")) {
if (/^\[Interface\]$/i.test(line)) {
if (found || peers.length) throw invalid("Конфигурация должна содержать одну секцию [Interface] перед [Peer]")
found = true; section = "interface"
} else if (/^\[Peer\]$/i.test(line)) {
if (!found) throw invalid("Сначала нужна секция [Interface]")
if (peers.length >= WG_CONFIG_LIMITS.peers) throw invalid("Превышен предел peers WireGuard")
section = "peer"; current = { publicKey: "", allowedAddresses: [] }; peers.push(current)
} else throw invalid("Неподдерживаемая секция WireGuard")
seen = new Set(); continue
}
const match = line.match(/^([A-Za-z][A-Za-z0-9]*)\s*=\s*(.*)$/)
if (!match || !section) throw invalid()
const key = match[1].toLowerCase(), value = text(match[2])
if (seen.has(key)) throw invalid("Повторяющееся поле конфигурации WireGuard")
seen.add(key)
if (key === "presharedkey") throw invalid("Импорт PresharedKey пока не поддерживается")
if (section === "interface") {
if (key === "privatekey") iface.privateKey = value
else if (key === "address") { if (value.includes(",")) throw invalid("Импорт нескольких адресов Address пока не поддерживается"); iface.address = value }
else if (key === "listenport") iface.listenPort = integer(value, "ListenPort")
else if (key === "mtu") iface.mtu = integer(value, "MTU")
else if (key === "name") iface.name = value
else throw invalid("Неподдерживаемое поле [Interface] WireGuard")
} else {
if (key === "publickey") current!.publicKey = value
else if (key === "allowedips") current!.allowedAddresses = list(value, "AllowedIPs")
else if (key === "endpoint") { const endpoint = splitWgEndpoint(value); current!.endpointAddress = endpoint.address; current!.endpointPort = endpoint.port }
else if (key === "persistentkeepalive") current!.persistentKeepalive = integer(value, "PersistentKeepalive")
else throw invalid("Неподдерживаемое поле [Peer] WireGuard")
}
}
if (!found) throw invalid("Нужна секция [Interface]")
if (peers.some(peer => !peer.publicKey)) throw invalid("У каждого пира должен быть PublicKey")
return { format: "conf", interface: iface, peers }
}
function logicalRscLines(content: string) {
const result: string[] = []; let pending = ""
for (const raw of inputLines(content)) {
const line = raw.trim()
if (!line || line.startsWith("#")) { if (pending) throw invalid(); continue }
let quoted = false
for (let index = 0; index < line.length; index++) {
if (line[index] === String.fromCharCode(92) && quoted) { index++; continue }
if (line[index] === '"') quoted = !quoted
}
if (quoted) throw invalid("Незакрытая строка конфигурации WireGuard")
const continued = line.endsWith(String.fromCharCode(92))
pending += (continued ? line.slice(0, -1).trimEnd() : line) + (continued ? " " : "")
if (Buffer.byteLength(pending) > WG_CONFIG_LIMITS.lineBytes) throw invalid("Превышен предел команды WireGuard")
if (!continued) { result.push(pending); pending = "" }
}
if (pending) throw invalid("Незавершённая команда WireGuard")
return result
}
/** Constant strings only: no variables, concatenation, command substitution or executable suffix. */
function rscFields(raw: string) {
const fields: Record<string, string> = Object.create(null)
let cursor = 0
while (cursor < raw.length) {
while (/\s/.test(raw[cursor] ?? "") && cursor < raw.length) cursor++
if (cursor === raw.length || raw[cursor] === "#") break
const match = raw.slice(cursor).match(/^([A-Za-z][A-Za-z0-9-]*)=/)
if (!match) throw invalid()
const key = match[1].toLowerCase(); cursor += match[0].length
if (Object.hasOwn(fields, key) || Object.keys(fields).length >= WG_CONFIG_LIMITS.fieldsPerCommand) throw invalid("Повторяющиеся поля или превышен предел полей WireGuard")
let value = ""
if (raw[cursor] === '"') {
cursor++; const bytes: Buffer[] = []; let closed = false
while (cursor < raw.length) {
const character = raw[cursor++]
if (character === '"') { closed = true; break }
if (character === "$") throw invalid("Переменные и выражения RouterOS не поддерживаются")
if (character !== String.fromCharCode(92)) { const point = raw.codePointAt(cursor - 1)!; const literal = String.fromCodePoint(point); cursor += literal.length - 1; bytes.push(Buffer.from(literal)); continue }
const escaped = raw[cursor++]
if ([String.fromCharCode(92), '"', "$"].includes(escaped)) bytes.push(Buffer.from(escaped))
else if (["n", "r", "t"].includes(escaped)) bytes.push(Buffer.from(escaped === "n" ? "\n" : escaped === "r" ? "\r" : "\t"))
else if (escaped === "_") bytes.push(Buffer.from(" "))
else if (/^[0-9A-F]$/.test(escaped ?? "") && /^[0-9A-F]$/.test(raw[cursor] ?? "")) bytes.push(Buffer.from([parseInt(escaped + raw[cursor++], 16)]))
else throw invalid("Неподдерживаемая escape-последовательность RouterOS")
}
if (!closed || cursor < raw.length && !/\s/.test(raw[cursor])) throw invalid()
const buffer = Buffer.concat(bytes); value = buffer.toString("utf8")
if (!Buffer.from(value).equals(buffer)) throw invalid()
} else {
const start = cursor
while (cursor < raw.length && !/\s/.test(raw[cursor])) cursor++
value = raw.slice(start, cursor)
if (!value || value.includes(String.fromCharCode(92)) || /[$;{}()\[\]"'#]/.test(value)) throw invalid("Исполняемые выражения RouterOS не поддерживаются")
}
fields[key] = text(value, key === "comment")
}
return fields
}
function allowed(fields: Record<string, string>, keys: string[]) {
if (Object.hasOwn(fields, "preshared-key")) throw invalid("Импорт PresharedKey пока не поддерживается")
if (Object.keys(fields).some(key => !keys.includes(key))) throw invalid("Неподдерживаемое поле RouterOS WireGuard")
}
export function parseMikrotikRsc(content: string): WgParsedConfig {
const iface: WgParsedInterface = { name: "wg0" }, peers: WgParsedPeer[] = []
let found = false, addressSeen = false
for (const line of logicalRscLines(content)) {
const command = line.match(/^(\/interface(?:\s+|\/)wireguard(?:\s+|\/)peers\s+add|\/interface(?:\s+|\/)wireguard\s+add|\/(?:ip|ipv6)(?:\s+|\/)address\s+add)(?:\s+(.*))?$/i)
if (!command) throw invalid("Неподдерживаемая команда RouterOS WireGuard")
const path = command[1].replace(/\//g, " ").replace(/\s+/g, " ").trim().toLowerCase(), fields = rscFields(command[2] ?? "")
if (path === "interface wireguard add") {
if (found) throw invalid("Конфигурация должна содержать один интерфейс WireGuard")
allowed(fields, ["name", "listen-port", "mtu", "private-key", "comment", "disabled"])
if (fields.name !== undefined) iface.name = fields.name
if (fields["listen-port"] !== undefined) iface.listenPort = integer(fields["listen-port"], "ListenPort")
if (fields.mtu !== undefined) iface.mtu = integer(fields.mtu, "MTU")
if (fields["private-key"] !== undefined) iface.privateKey = fields["private-key"]
if (fields.comment !== undefined) iface.comment = fields.comment
if (fields.disabled !== undefined) iface.disabled = boolean(fields.disabled)
found = true
} else {
if (!found) throw invalid("Не удалось распознать интерфейс RouterOS WireGuard перед зависимыми объектами")
if (fields.interface !== undefined && fields.interface !== iface.name) throw invalid("Объект относится к другому интерфейсу")
if (path === "interface wireguard peers add") {
allowed(fields, ["interface", "public-key", "allowed-address", "endpoint-address", "endpoint-port", "persistent-keepalive", "comment", "name", "private-key", "client-address", "client-dns", "client-endpoint", "disabled"])
if (peers.length >= WG_CONFIG_LIMITS.peers) throw invalid("Превышен предел peers WireGuard")
peers.push({ publicKey: fields["public-key"] ?? "", allowedAddresses: fields["allowed-address"] === undefined ? [] : list(fields["allowed-address"], "allowed-address"),
...(fields["endpoint-address"] === undefined ? {} : { endpointAddress: fields["endpoint-address"] }), ...(fields["endpoint-port"] === undefined ? {} : { endpointPort: integer(fields["endpoint-port"], "Endpoint") }),
...(fields["persistent-keepalive"] === undefined ? {} : { persistentKeepalive: integer(fields["persistent-keepalive"], "PersistentKeepalive") }),
...(fields.comment === undefined ? {} : { comment: fields.comment }), ...(fields.name === undefined ? {} : { name: fields.name }), ...(fields["private-key"] === undefined ? {} : { privateKey: fields["private-key"] }),
...(fields["client-address"] === undefined ? {} : { clientAddress: fields["client-address"] }), ...(fields["client-dns"] === undefined ? {} : { clientDns: fields["client-dns"] }), ...(fields["client-endpoint"] === undefined ? {} : { clientEndpoint: fields["client-endpoint"] }), ...(fields.disabled === undefined ? {} : { disabled: boolean(fields.disabled) }) })
} else {
allowed(fields, ["interface", "address", "advertise", "disabled", "no-dad", "eui-64", "from-pool"])
if (addressSeen) throw invalid("Импорт нескольких адресов пока не поддерживается")
if (!fields.address) throw invalid("Не указан Address")
if (fields["from-pool"] || ["advertise", "disabled", "no-dad", "eui-64"].some(key => fields[key] !== undefined && boolean(fields[key]))) throw invalid("Импорт специальных параметров адреса не поддерживается")
if ((path.startsWith("ipv6 ") ? 6 : 4) !== isIP(fields.address.split("/")[0])) throw invalid("Не совпадает семейство Address")
iface.address = fields.address; addressSeen = true
}
}
}
if (!found) throw invalid("Не удалось распознать RouterOS WireGuard .rsc")
return { format: "rsc", interface: iface, peers }
}
export function parseWgConfig(content: string, format: "auto" | "rsc" | "conf" = "auto"): WgParsedConfig {
if (!["auto", "rsc", "conf"].includes(format)) throw invalid()
return (format === "auto" ? detectWgConfigFormat(content) : format) === "conf" ? parseNativeConf(content) : parseMikrotikRsc(content)
}
function checkedExport(iface: WgExportIface) {
text(iface.name); if (!iface.name.trim() || iface.peers.length > WG_CONFIG_LIMITS.peers) throw invalid()
if (iface.comment !== undefined) text(iface.comment, true)
for (const value of [iface.serverName, iface.privateKey, iface.publicKey, iface.address]) if (value !== undefined) text(value)
for (const value of [iface.mtu, iface.listenPort]) if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 65535)) throw invalid()
for (const peer of iface.peers) {
if (peer.comment !== undefined) text(peer.comment, true)
for (const value of [peer.publicKey, peer.name, peer.privateKey, peer.clientAddress, peer.clientDns, peer.clientEndpoint]) if (value !== undefined) text(value)
if (peer.allowedIps.length > WG_CONFIG_LIMITS.addressesPerPeer) throw invalid()
peer.allowedIps.forEach(value => text(value)); peerEndpoint(peer)
if (peer.persistentKeepalive !== undefined && (!Number.isSafeInteger(peer.persistentKeepalive) || peer.persistentKeepalive < 0 || peer.persistentKeepalive > 65535)) throw invalid()
}
}
function output(value: string) { inputLines(value); return value }
function secretOutput(value: string, keys: Array<string | undefined>, includePrivateKey?: boolean) {
if (includePrivateKey !== true && keys.some(key => key && key !== "auto" && key !== "none" && value.includes(key))) throw invalid("Приватный ключ найден в публичных полях экспорта WireGuard")
return output(value)
}
function confAtom(value: string) { text(value); if (!value || /[\s#;]/.test(value)) throw invalid("Значение нельзя представить в WireGuard .conf"); return value }
function keepalive(peer: WgExportIface["peers"][number]) { return peer.persistentKeepalive ?? (peer.persistent ? 25 : undefined) }
export function generateNativeConf(iface: WgExportIface, opts?: { includePrivateKey?: boolean }): string {
checkedExport(iface)
if (iface.enabled === false || iface.peers.some(peer => peer.disabled === true)) throw invalid("Отключённые объекты нельзя воспроизвести в WireGuard .conf")
const lines = ["[Interface]", opts?.includePrivateKey === true && iface.privateKey ? `PrivateKey = ${confAtom(iface.privateKey)}` : "# PrivateKey = <заполните приватный ключ с роутера>"]
if (iface.comment) lines.push(...iface.comment.split(/\r\n|\r|\n/).map(line => `# ${line}`))
if (iface.address) lines.push(`Address = ${confAtom(iface.address)}`)
if (iface.listenPort !== undefined) lines.push(`ListenPort = ${iface.listenPort}`)
lines.push(`MTU = ${iface.mtu}`, "")
for (const peer of iface.peers) {
lines.push("[Peer]", `PublicKey = ${confAtom(peer.publicKey)}`, `AllowedIPs = ${peer.allowedIps.map(confAtom).join(", ")}`)
const endpoint = peerEndpoint(peer); if (endpoint) lines.push(`Endpoint = ${endpoint}`)
if (keepalive(peer) !== undefined) lines.push(`PersistentKeepalive = ${keepalive(peer)}`)
if (peer.comment) lines.push(...peer.comment.split(/\r\n|\r|\n/).map(line => `# ${line}`))
lines.push("")
}
return secretOutput(lines.join("\n").trimEnd() + "\n", [iface.privateKey, ...iface.peers.map(peer => peer.privateKey)], opts?.includePrivateKey)
}
export function generatePeerClientConf(args: { peerPrivateKey?: string; peerAddress?: string; peerDns?: string; serverPublicKey: string; allowedIps?: string[]; endpoint?: string; persistentKeepalive?: number }, opts?: { includePrivateKey?: boolean }): string {
const lines = ["[Interface]", opts?.includePrivateKey === true && args.peerPrivateKey ? `PrivateKey = ${confAtom(args.peerPrivateKey)}` : "# PrivateKey = <ключ клиента>"]
if (args.peerAddress?.trim()) lines.push(`Address = ${confAtom(args.peerAddress.trim())}`); else lines.push("# Address = <укажите адрес клиента>")
if (args.peerDns) lines.push(`DNS = ${args.peerDns.split(",").map(value => confAtom(value.trim())).join(", ")}`)
lines.push("", "[Peer]", `PublicKey = ${confAtom(args.serverPublicKey)}`)
if (args.allowedIps?.length) { if (args.allowedIps.length > WG_CONFIG_LIMITS.addressesPerPeer) throw invalid(); lines.push(`AllowedIPs = ${args.allowedIps.map(confAtom).join(", ")}`) } else lines.push("# AllowedIPs = <укажите сети через туннель>")
if (args.endpoint) { const endpoint = splitWgEndpoint(args.endpoint); lines.push(`Endpoint = ${formatWgEndpoint(endpoint.address, endpoint.port)}`) } else lines.push("# Endpoint = <укажите адрес сервера и порт>")
if (args.persistentKeepalive !== undefined) { if (!Number.isSafeInteger(args.persistentKeepalive) || args.persistentKeepalive < 0 || args.persistentKeepalive > 65535) throw invalid(); lines.push(`PersistentKeepalive = ${args.persistentKeepalive}`) }
return secretOutput(lines.join("\n") + "\n", [args.peerPrivateKey], opts?.includePrivateKey)
}
/** RouterOS double-quoted constant encoding; escape interpolation as well as quotes and backslashes. */
export function quoteWgRsc(value: string, multilineComment = false) { const slash = String.fromCharCode(92); return '"' + text(value, multilineComment).split(slash).join(slash + slash).replace(/"/g, slash + '"').replace(/[$]/g, slash + "$" ).replace(/\r/g, slash + "r").replace(/\n/g, slash + "n").replace(/\t/g, slash + "t") + '"' }
export function generateMikrotikRsc(iface: WgExportIface, opts?: { includePrivateKey?: boolean }): string {
checkedExport(iface)
const command = (path: string, values: Record<string, string | number | boolean | undefined>) => path + " " + Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => `${key}=${typeof value === "string" ? quoteWgRsc(value, key === "comment") : typeof value === "boolean" ? value ? "yes" : "no" : value}`).join(" ")
const lines = ["# WireGuard - MikrotikManager", command("/interface wireguard add", { name: iface.name, "listen-port": iface.listenPort ?? 13231, mtu: iface.mtu, comment: iface.comment, disabled: iface.enabled === undefined ? undefined : !iface.enabled, "private-key": opts?.includePrivateKey === true ? iface.privateKey : undefined })]
if (iface.address) lines.push(command(`${iface.address.includes(":") ? "/ipv6" : "/ip"} address add`, { address: iface.address, interface: iface.name, ...(iface.address.includes(":") ? { advertise: false } : {}) }))
for (const peer of iface.peers) {
const endpoint = peerEndpoint(peer), parts = endpoint ? splitWgEndpoint(endpoint) : undefined
lines.push(command("/interface wireguard peers add", { interface: iface.name, "public-key": peer.publicKey, "allowed-address": peer.allowedIps.join(","), "endpoint-address": parts?.address, "endpoint-port": parts?.port, "persistent-keepalive": keepalive(peer), comment: peer.comment, name: peer.name, disabled: peer.disabled, "private-key": peer.privateKey === "auto" || peer.privateKey === "none" || opts?.includePrivateKey === true ? peer.privateKey : undefined, "client-address": peer.clientAddress, "client-dns": peer.clientDns, "client-endpoint": peer.clientEndpoint }))
}
return secretOutput(lines.join("\n") + "\n", [iface.privateKey, ...iface.peers.map(peer => peer.privateKey)], opts?.includePrivateKey)
}