import type { MikrotikClient } from "./mikrotik.js" import { normalizeIpsecRemoteId, IPSEC_POLICY_GROUP, isIpsecManagedComment, ipsecManagedComment, isManagedIpsecModeConfig, selectIke2Peers, selectSharedIke2Identity, type Ike2IdentityLike, type PeerLike, } from "./ipsec-config.js" export function toRosBody(obj: Record): Record { const out: Record = {} for (const [k, v] of Object.entries(obj)) { if (v == null) continue const s = String(v) if (s === "") continue out[k] = s } return out } type RosRow = Record async function listByPath(client: MikrotikClient, path: string): Promise { const raw = await client.get(path) if (!Array.isArray(raw) || raw.some(row => !row || typeof row !== "object" || Array.isArray(row) || typeof row[".id"] !== "string" || !row[".id"])) throw new Error(`Некорректный ответ IPsec: ${path}`) return raw as RosRow[] } /** PUT (создать) или PATCH по имени — мастер инициализации идемпотентен. */ export async function putOrPatchByName( client: MikrotikClient, path: string, name: string, body: Record, ): Promise<"created" | "patched"> { const rows = await listByPath(client, path) const existing = rows.find((r) => String(r.name ?? "").trim() === name) if (existing?.[".id"]) { await client.patch(`${path}/${encodeURIComponent(existing[".id"])}`, body) return "patched" } await client.put(path, body) return "created" } async function findRosId(client: MikrotikClient, path: string, name: string): Promise { const rows = await listByPath(client, path) return rows.find((r) => String(r.name ?? "").trim() === name)?.[".id"] ?? null } // ── инициализация IKEv2-сервера ───────────────────────────────────────────── export async function ensureIpsecProfile(client: MikrotikClient, name: string, _comment: string): Promise { await putOrPatchByName(client, "/ip/ipsec/profile", name, toRosBody({ name, "hash-algorithm": "sha256", "enc-algorithm": "aes-256,aes-192,aes-128", "dh-group": "modp2048", "nat-traversal": "yes", })) } export async function ensureIpsecProposal(client: MikrotikClient, name: string, comment: string): Promise { await putOrPatchByName(client, "/ip/ipsec/proposal", name, toRosBody({ name, "auth-algorithms": "sha256", "enc-algorithms": "aes-256-cbc,aes-192-cbc,aes-128-cbc", "pfs-group": "modp2048", comment, })) } export async function ensureIpsecPool(client: MikrotikClient, name: string, ranges: string, comment: string): Promise { await putOrPatchByName(client, "/ip/pool", name, toRosBody({ name, ranges, comment })) } /** Общий mode-config: адрес клиентам из пула. */ export async function ensureSharedModeConfig( client: MikrotikClient, name: string, poolName: string, dns: string | undefined, _comment: string, ): Promise { await putOrPatchByName(client, "/ip/ipsec/mode-config", name, toRosBody({ name, "address-pool": poolName, responder: "yes", "static-dns": dns, })) } export async function ensurePolicyTemplate( client: MikrotikClient, dstCidr: string, proposalName: string, comment: string, ): Promise { const rows = await listByPath(client, "/ip/ipsec/policy") const managed = rows.find((r) => (r.comment ?? "").trim() === comment && (r.template === "true" || r.template === "yes")) if (managed?.[".id"]) { await client.patch(`/ip/ipsec/policy/${encodeURIComponent(managed[".id"])}`, toRosBody({ "src-address": "0.0.0.0/0", "dst-address": dstCidr, proposal: proposalName, group: IPSEC_POLICY_GROUP, comment, })) return } await client.put("/ip/ipsec/policy", toRosBody({ "src-address": "0.0.0.0/0", "dst-address": dstCidr, proposal: proposalName, group: IPSEC_POLICY_GROUP, template: "yes", comment, })) } export class IpsecPolicyGroupConflict extends Error {} /** Reserved group reuse requires a managed template and no foreign consumers. */ export async function ipsecPolicyGroupExists(client: MikrotikClient): Promise { const groups = await listByPath(client, "/ip/ipsec/policy/group") if (!groups.some(g => g.name === IPSEC_POLICY_GROUP)) return false const [policies, identities] = await Promise.all([listByPath(client, "/ip/ipsec/policy"), listByPath(client, "/ip/ipsec/identity")]) if (!policies.some(p => p.group === IPSEC_POLICY_GROUP && isIpsecManagedComment(p.comment))) throw new IpsecPolicyGroupConflict("Зарезервированное имя группы политик занято объектом без подтверждённого управления") if (policies.some(p => p.group === IPSEC_POLICY_GROUP && !isIpsecManagedComment(p.comment) && p.dynamic !== "true" && p.dynamic !== "yes") || identities.some(i => i["policy-template-group"] === IPSEC_POLICY_GROUP && !isIpsecManagedComment(i.comment))) throw new IpsecPolicyGroupConflict("Группа политик используется чужой конфигурацией") return true } export async function ensureIpsecPeer( client: MikrotikClient, name: string, _serverCertName: string, profileName: string, comment: string, ): Promise { await putOrPatchByName(client, "/ip/ipsec/peer", name, toRosBody({ name, address: "0.0.0.0/0", "exchange-mode": "ike2", passive: "yes", profile: profileName, comment, })) } export class IpsecNatInterfaceConflict extends Error {} export function selectIpsecNatInterface(routes: RosRow[], interfaces: RosRow[]): string { const candidates = new Set() for (const route of routes) { if (route["dst-address"] !== "0.0.0.0/0" || !["true", "yes"].includes(route.active ?? "") || (route["routing-table"] && route["routing-table"] !== "main")) continue const hops = (route["immediate-gw"] ?? route.gateway ?? "").split(",") for (const hop of hops) { const name = hop.includes("%") ? hop.slice(hop.lastIndexOf("%") + 1).trim() : hop.trim() if (interfaces.some(i => i.name === name && !["true", "yes"].includes(i.disabled ?? ""))) candidates.add(name) } } if (candidates.size !== 1) throw new IpsecNatInterfaceConflict("Не удалось однозначно определить исходящий интерфейс по активному маршруту main. Отключите NAT в мастере и настройте правило вручную") return [...candidates][0]! } export async function resolveIpsecNatInterface(client: MikrotikClient): Promise { const [routes, interfaces] = await Promise.all([listByPath(client, "/ip/route"), listByPath(client, "/interface")]) return selectIpsecNatInterface(routes, interfaces) } /** Managed srcnat masquerade only through the verified default-route egress. */ export async function ensureNatRule(client: MikrotikClient, poolCidr: string, comment: string, outInterface: string): Promise { const rows = await listByPath(client, "/ip/firewall/nat") const existing = rows.find( (r) => (r.comment ?? "").trim() === comment && r.chain === "srcnat", ) const body = toRosBody({ chain: "srcnat", action: "masquerade", "src-address": poolCidr, "out-interface": outInterface, "ipsec-policy": "out,none", comment, }) if (existing?.[".id"]) { await client.patch(`/ip/firewall/nat/${encodeURIComponent(existing[".id"])}`, body) } else await client.put("/ip/firewall/nat", body) } // ── клиенты ───────────────────────────────────────────────────────────────── export async function putUserModeConfig( client: MikrotikClient, name: string, staticIp: string, _comment: string, ): Promise { await putOrPatchByName(client, "/ip/ipsec/mode-config", name, toRosBody({ name, address: staticIp, responder: "yes", "address-prefix-length": "32", })) } export async function deleteUserModeConfig(client: MikrotikClient, name: string): Promise { const row = (await listByPath(client, "/ip/ipsec/mode-config")).find(row => row.name === name) if (!row?.[".id"] || !isManagedIpsecModeConfig(row)) return if ((await listByPath(client, "/ip/ipsec/identity")).some(i => i["mode-config"] === name)) return await client.delete(`/ip/ipsec/mode-config/${encodeURIComponent(row[".id"])}`) } export interface IdentityFields { peerName: string modeConfig: string comment: string authMethod: "certificate" | "pre-shared-key" /** cert: серверный сертификат (router представляет его клиенту). */ certificate?: string /** cert: строгий мэтч конкретного клиента по его сертификату. */ remoteCertificate?: string /** psk. */ secret?: string remoteId?: string /** Legacy hint: RouterOS identities do not accept place-before; specificity uses match-by/remote-certificate. */ placeBefore?: string policyTemplateGroup?: string } export function identityRosBody(f: IdentityFields): Record { return toRosBody({ peer: f.peerName, "auth-method": f.authMethod === "certificate" ? "digital-signature" : "pre-shared-key", certificate: f.certificate, "remote-certificate": f.remoteCertificate, "match-by": f.authMethod === "certificate" && f.remoteCertificate ? "certificate" : undefined, secret: f.secret, "remote-id": f.remoteId === undefined ? undefined : normalizeIpsecRemoteId(f.remoteId), "mode-config": f.modeConfig, "generate-policy": "port-strict", "policy-template-group": f.policyTemplateGroup, comment: f.comment, }) } export async function putIdentity(client: MikrotikClient, fields: IdentityFields): Promise { if (!fields.policyTemplateGroup) { const shared = selectSharedIke2Identity(await listByPath(client, "/ip/ipsec/identity"), [fields.peerName]) fields = { ...fields, policyTemplateGroup: shared?.["policy-template-group"] } } await client.put("/ip/ipsec/identity", identityRosBody(fields)) } /** * Общая listener-identity на IKEv2 peer для всех клиентов (reuse существующей, иначе создать). * Без `remote-certificate`/`match-by` — RouterOS принимает любой клиентский серт, подписанный доверенным CA. */ export async function ensureSharedIke2Identity( client: MikrotikClient, args: { peerName: string; serverCertName: string; modeConfigName?: string; comment: string; policyTemplateGroup?: string }, ): Promise { const identities = await listByPath(client, "/ip/ipsec/identity") const peers = await listByPath(client, "/ip/ipsec/peer") const peerNames = selectIke2Peers(peers as PeerLike[]).map((p) => (p.name ?? "").trim()).filter(Boolean) const existing = selectSharedIke2Identity( identities as Ike2IdentityLike[], peerNames.length > 0 ? peerNames : [args.peerName], ) if (existing?.[".id"]) { if (args.policyTemplateGroup && existing["policy-template-group"] !== args.policyTemplateGroup) { if (!isIpsecManagedComment(existing.comment)) throw new Error("Нельзя изменить группу политик чужой listener identity") await client.patch(`/ip/ipsec/identity/${encodeURIComponent(existing[".id"])}`, { "policy-template-group": args.policyTemplateGroup }) } return String(existing[".id"]) } await putIdentity(client, { peerName: args.peerName, modeConfig: args.modeConfigName ?? "", comment: args.comment, authMethod: "certificate", certificate: args.serverCertName, policyTemplateGroup: args.policyTemplateGroup, }) return undefined } export async function patchIdentity(client: MikrotikClient, rosId: string, body: Record): Promise { await client.patch(`/ip/ipsec/identity/${encodeURIComponent(rosId)}`, body) } export async function deleteIdentity(client: MikrotikClient, rosId: string): Promise { await client.delete(`/ip/ipsec/identity/${encodeURIComponent(rosId)}`) } export async function patchPeer(client: MikrotikClient, rosId: string, body: Record): Promise { await client.patch(`/ip/ipsec/peer/${encodeURIComponent(rosId)}`, body) } export async function deletePeer(client: MikrotikClient, rosId: string): Promise { await client.delete(`/ip/ipsec/peer/${encodeURIComponent(rosId)}`) } /** Снять с identity персональный mode-config (вернуть выдачу из пула) безопасно: пустой patch не шлём. */ export async function clearIdentityModeConfig(client: MikrotikClient, rosId: string, sharedModeConfig: string): Promise { await patchIdentity(client, rosId, toRosBody({ "mode-config": sharedModeConfig })) } export { listByPath, findRosId, ipsecManagedComment }