import { createHash } from "node:crypto" import { isIP } from "node:net" import type { IxConfiguration, IxSite } from "@mmapp/contracts/internet-exchange" import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js" import { IxConflict } from "./internet-exchange-plan.js" type Binding = IxSite["interfaces"][number] export function ixLinuxBindingKind(binding: Binding) { if (binding.kind === "wireguard" && binding.provisionWireguard?.hubEndpoint) return "wireguard" if (binding.kind === "gre-ipsec" && binding.localEndpoint && binding.endpoint) return "gre-ipsec" return null } export function ixLegacyWireguardRoutes(configuration: IxConfiguration, binding: Binding) { return configuration.sites.flatMap(site => site.interfaces .filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes)) } export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Pick) { return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12) } export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>", transportOnly = false) { const config = binding.provisionWireguard if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) { throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX") } const serverAddress = config.localAddress.split("/")[0] const family = isIP(serverAddress) const address = (value: string) => value + (family === 4 ? "/32" : "/128") const endpoint = isIP(config.hubEndpoint) === 6 ? "[" + config.hubEndpoint + "]" : config.hubEndpoint return [ "[Interface]", "Address = " + address(config.peerAddress), "PrivateKey = " + privateKey, binding.linux && !transportOnly ? "Table = auto" : "Table = off", ...(!transportOnly && binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [ "PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main", "PreDown = ip -" + family + " rule del pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main", ] : []), "", "[Peer]", "PublicKey = " + hubPublicKey, "Endpoint = " + endpoint + ":" + config.listenPort, "AllowedIPs = " + [...new Set([address(serverAddress), ...routes.map(canonicalBgpPolicyPrefix)])].join(", "), "PersistentKeepalive = 25", "", ].join("\n") } export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string, transportOnly = false) { const hub = binding.localEndpoint const client = binding.endpoint if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) { throw new IxConflict("Для Linux GRE/IPsec нужны два разных внешних IPv4-адреса") } const id = ixLinuxInterfaceName("ixg", serverId, binding) const hostMask = bgp && isIP(bgp.address) === 6 ? "/128" : "/32" const tunnel = binding.provisionGre const family = tunnel ? isIP(tunnel.peerAddress) : 4 const protocol = "ip -" + family const table = 30000 + parseInt(id.slice(-4), 16) const management = 12000 + 2 * parseInt(id.slice(-3), 16) const managementRules = [ ["ip -4", "to " + hub + "/32 lookup main"], ["ip -4", "from " + client + "/32 lookup main"], ...(family === 6 && binding.linux?.exit ? [["ip -6", "ipproto tcp sport 22 lookup main"]] : []), ] const greParameters = id + " mode gre local " + client + " remote " + hub const common = [ "swanctl --load-all", "swanctl --initiate --child " + id + " --timeout 20", "ip tunnel add " + greParameters, ] const addressCommand = tunnel && "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id const transportSetup = transportOnly && tunnel && [ 'conf="$(dirname -- "$0")/' + id + '.conf"', 'unit=/etc/systemd/system/ix-gre-' + id + '.service', 'profile=/etc/swanctl/conf.d/' + id + '.conf', 'if [ ! -r "$conf" ]; then echo "Положите ' + id + '.conf рядом со скриптом."; exit 1; fi', 'candidate=$(mktemp)', 'trap \'rm -f "$candidate"\' EXIT', 'cat >"$candidate" <<\'IX_GRE_UNIT\'', "[Unit]", "Description=IX Client GRE/IPsec " + id, "Wants=network-online.target", "After=network-online.target strongswan.service", "Requires=strongswan.service", "[Service]", "Type=oneshot", "RemainAfterExit=yes", "ExecStartPre=/usr/sbin/swanctl --load-all", "ExecStart=/bin/sh -ec '/usr/sbin/ip tunnel add " + greParameters + '; trap "/usr/sbin/ip link del dev ' + id + '" EXIT; /usr/sbin/' + addressCommand + "; /usr/sbin/ip link set " + id + " up; trap - EXIT'", "ExecStop=/usr/sbin/ip link del dev " + id, "[Install]", "WantedBy=multi-user.target", "IX_GRE_UNIT", 'if [ -e "$unit" ] && ! cmp -s "$candidate" "$unit"; then echo "Служба уже принадлежит другой конфигурации."; exit 1; fi', 'if [ -e "$profile" ] && ! cmp -s "$conf" "$profile"; then echo "Профиль strongSwan отличается от существующего."; exit 1; fi', 'if [ ! -e "$unit" ] && ip link show dev ' + id + ' >/dev/null 2>&1; then echo "Интерфейс уже существует."; exit 1; fi', 'install -d -m 0700 /etc/swanctl/conf.d', 'if [ ! -e "$profile" ]; then install -m 0600 "$conf" "$profile"; fi', 'install -m 0644 "$candidate" "$unit"', "systemctl daemon-reload", "systemctl enable --now ix-gre-" + id + ".service", ].join("\n") return { filename: id + ".conf", template: [ ...(tunnel ? [] : ["# Сверьте предложения и идентификаторы IKE с профилем узла IX."]), "connections {", " " + id + " {", " version = 2", " local_addrs = " + client, " remote_addrs = " + hub, " proposals = aes256-sha256-modp2048", " mobike = no", " local {", " auth = psk", " id = " + client, " }", " remote {", " auth = psk", " id = " + hub, " }", " children {", " " + id + " {", " local_ts = " + client + "/32[47]", " remote_ts = " + hub + "/32[47]", " mode = transport", " esp_proposals = aes256-sha256-modp2048", " start_action = trap", " }", " }", " }", "}", "secrets {", " ike-" + id + " {", " id-1 = " + client, " id-2 = " + hub, ' secret = "' + (credential ?? "") + '"', " }", "}", "", ].join("\n"), setup: transportSetup || (tunnel ? [ 'conf="$(dirname -- "$0")/' + id + '.conf"', 'if [ ! -r "$conf" ]; then echo "Положите файл ' + id + '.conf рядом со скриптом" >&2; exit 1; fi', 'if ip link show dev ' + id + ' >/dev/null 2>&1; then echo "GRE уже поднят" >&2; exit 1; fi', 'install -d -m 0700 /etc/swanctl/conf.d', 'install -m 0600 "$conf" /etc/swanctl/conf.d/' + id + '.conf', "cleanup() {", " " + protocol + " rule del pref " + (management + 1) + " lookup " + table + " 2>/dev/null || :", " ip link del dev " + id + " 2>/dev/null || :", ...managementRules.map(([ip, selector]) => " " + ip + " rule del pref " + management + " " + selector + " 2>/dev/null || :"), " swanctl --terminate --ike " + id + " --timeout 5 >/dev/null 2>&1 || :", "}", "trap cleanup 0", ...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector), ...common, addressCommand!, "ip link set " + id + " up", ...[...new Set([ tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"), ...(binding.linux?.destinations ?? []).map(canonicalBgpPolicyPrefix), ...(bgp && isIP(bgp.localAddress) === family ? [bgp.localAddress + hostMask] : []), ...(binding.linux?.exit ? ["default"] : []), ])].map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress + " table " + table), protocol + " rule add pref " + (management + 1) + " lookup " + table, "trap - 0", ] : [ ...common, bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.", "ip link set " + id + " up", ...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []), ]).join("\n"), } }