fix(ipsec): совместимость инициализации и клиентов IPsec с RouterOS 7.24
Проверено пробами на стенде RouterOS 7.24.5: /certificate не принимает comment, sign и export-certificate адресуются только по .id и не принимают name и days-valid, подпись меняет authority и digest-algorithm, peer с address 0.0.0.0/0 возвращается без address, id файлов имеют вид **<base62>. Сертификаты продукта опознаются по имени и цепочке подписи, версии операций повышены (init 5, user_create 3, экспорт 2). Стабы приёмки отказывают как RouterOS 7.24. Генеральная репетиция на CHR: init 13 и PSK-клиент 2 команды сошлись с проекцией продукта, туннель, ping 10/10, рост SA, сверка 66/66. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
a237813ff5
commit
e7eb108c32
22 files changed
+125
-77
No files matched your search
@@ -41,7 +41,7 @@ try {
|
||||
const [id, tool, , section, permission, effect, scope, schema, handlers] = calls[0]
|
||||
assert.equal(id, operation); assert.equal(tool, "mm_ipsec_existing_certificate_export_plan")
|
||||
assert.equal(section, "network"); assert.equal(permission, "mm:network:write"); assert.equal(effect, "write"); assert.equal(scope, "servers")
|
||||
assert.equal(handlers.prepare, adapter.prepare); assert.equal(handlers.version, 1)
|
||||
assert.equal(handlers.prepare, adapter.prepare); assert.equal(handlers.version, 2)
|
||||
assert.equal(schema.safeParse({ serverId: 1, selector: { kind: "certificate", name: "client" }, privateKeyExport: true, passphrase: { kind: "generate" } }).success, true)
|
||||
assert.equal(schema.safeParse({ serverId: 1, selector: { kind: "certificate", name: "client" }, privateKeyExport: true, passphrase: "NEVER_RAW" }).success, false)
|
||||
assert.equal(findMcpService(operation), productionService)
|
||||
|
||||
@@ -8,7 +8,7 @@ import { registerMcpService } from "./service-registry.js"
|
||||
* registration runs on import. JSON/tool requests cannot install an adapter. */
|
||||
export function installIpsecExistingCertificateExportAdapter(register: typeof add, service: typeof registerMcpService, adapter: ReturnType<typeof createIpsecExistingCertificateExportAdapter>) {
|
||||
service(IPSEC_EXISTING_CERTIFICATE_EXPORT_OPERATION, adapter.service)
|
||||
register(IPSEC_EXISTING_CERTIFICATE_EXPORT_OPERATION, "mm_ipsec_existing_certificate_export_plan", "Экспорт существующего сертификата IPsec с явным приватным/CA-допуском и выдачей файла только владельцу", "network", "mm:network:write", "write", "servers", ipsecExistingCertificateExportActionSchema, { version: 1, prepare: adapter.prepare })
|
||||
register(IPSEC_EXISTING_CERTIFICATE_EXPORT_OPERATION, "mm_ipsec_existing_certificate_export_plan", "Экспорт существующего сертификата IPsec с явным приватным/CA-допуском и выдачей файла только владельцу", "network", "mm:network:write", "write", "servers", ipsecExistingCertificateExportActionSchema, { version: 2, prepare: adapter.prepare })
|
||||
}
|
||||
|
||||
export function registerIpsecExistingCertificateExportActions(register: typeof add): boolean {
|
||||
|
||||
@@ -52,15 +52,20 @@ export async function acceptIpsecServerInit(actor: AuthUser) {
|
||||
let raw = ""; for await (const chunk of req) raw += chunk
|
||||
const fields = raw ? JSON.parse(raw) as Row : {}
|
||||
commands.push({ method: req.method!, path, fields })
|
||||
// RouterOS 7.24 (stand probe 2026-11-21): no `comment` on /certificate; sign and export by `.id` only, no `name`/`days-valid`.
|
||||
const refusal = req.method === "PUT" && path === "/certificate" && "comment" in fields ? "unknown parameter comment"
|
||||
: path === "/certificate/sign" && ("days-valid" in fields || "name" in fields) ? ("days-valid" in fields ? "unknown parameter days-valid" : "missing =.id=")
|
||||
: path === "/certificate/export-certificate" && "name" in fields ? "unknown parameter name" : undefined
|
||||
if (refusal) { res.statusCode = 400; res.end(JSON.stringify({ error: 400, message: "Bad Request", detail: refusal })); return }
|
||||
let result: Row = {}
|
||||
if (mode !== "ignored") {
|
||||
if (path === "/certificate/sign") {
|
||||
const row = catalogs["/certificate"].find(row => row.name === fields.name); assert(row)
|
||||
Object.assign(row, { ...(fields.ca ? { ca: fields.ca } : {}), fingerprint: "synthetic-fingerprint", "invalid-before": "2026-01-01", "invalid-after": "2030-01-01", "private-key": "true", "serial-number": "synthetic" })
|
||||
const row = catalogs["/certificate"].find(row => row[".id"] === fields[".id"]); assert(row)
|
||||
Object.assign(row, { ...(fields.ca ? { ca: fields.ca } : { authority: "true" }), "digest-algorithm": "sha256", fingerprint: "synthetic-fingerprint", "invalid-before": "2026-01-01", "invalid-after": "2030-01-01", "private-key": "true", "serial-number": "synthetic" })
|
||||
} else {
|
||||
const catalog = Object.hasOwn(catalogs, path) ? path : Object.keys(catalogs).sort((a, b) => b.length - a.length).find(value => path.startsWith(value + "/")); assert(catalog)
|
||||
if (req.method === "PUT") { result = { ".id": `*new${++serial}`, ...fields, "native-default": "NEVER_NATIVE_DEFAULT" }; catalogs[catalog].push(result) }
|
||||
else if (req.method === "PATCH") { const row = catalogs[catalog].find(row => row[".id"] === path.slice(catalog.length + 1)); assert(row); Object.assign(row, fields) }
|
||||
if (req.method === "PUT") { result = { ".id": `*new${++serial}`, ...fields, "native-default": "NEVER_NATIVE_DEFAULT" }; if (catalog === "/ip/ipsec/peer" && result.address === "0.0.0.0/0") delete result.address; catalogs[catalog].push(result) }
|
||||
else if (req.method === "PATCH") { const row = catalogs[catalog].find(row => row[".id"] === path.slice(catalog.length + 1)); assert(row); Object.assign(row, fields); if (catalog === "/ip/ipsec/peer" && row.address === "0.0.0.0/0") delete row.address }
|
||||
else throw Error("unexpected mutation")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,5 +105,5 @@ export function createIpsecServerInitAdapter(overrides: Partial<typeof productio
|
||||
export function registerIpsecServerInitActions(register: typeof add) {
|
||||
const adapter = createIpsecServerInitAdapter()
|
||||
registerMcpService(operation, adapter.service)
|
||||
register(operation, "mm_ipsec_server_init_plan", "Инициализировать сервер IKEv2 с полным preflight и проверкой каждой native-команды", "network", "mm:network:write", "write", "servers", ipsecServerInitActionSchema, { version: 4, prepare: adapter.prepare })
|
||||
register(operation, "mm_ipsec_server_init_plan", "Инициализировать сервер IKEv2 с полным preflight и проверкой каждой native-команды", "network", "mm:network:write", "write", "servers", ipsecServerInitActionSchema, { version: 5, prepare: adapter.prepare })
|
||||
}
|
||||
@@ -44,12 +44,17 @@ export async function acceptIpsecUserCreate(actor: AuthUser) {
|
||||
const fields = raw ? JSON.parse(raw) as Row : {}
|
||||
if (path === "/file/get" || path === "/file/print") { res.end(JSON.stringify({ ret: fakeP12 })); return }
|
||||
commands.push({ method: req.method!, path, fields })
|
||||
// RouterOS 7.24 (stand probe 2026-11-21): no `comment` on /certificate; sign and export by `.id` only, no `name`/`days-valid`.
|
||||
const refusal = req.method === "PUT" && path === "/certificate" && "comment" in fields ? "unknown parameter comment"
|
||||
: path === "/certificate/sign" && ("days-valid" in fields || "name" in fields) ? ("days-valid" in fields ? "unknown parameter days-valid" : "missing =.id=")
|
||||
: path === "/certificate/export-certificate" && "name" in fields ? "unknown parameter name" : undefined
|
||||
if (refusal) { res.statusCode = 400; res.end(JSON.stringify({ error: 400, message: "Bad Request", detail: refusal })); return }
|
||||
let result: Row = {}
|
||||
if (mode !== "ignored") {
|
||||
if (path === "/certificate/sign") {
|
||||
const row = catalogs["/certificate"].find(row => row.name === fields.name); assert(row)
|
||||
Object.assign(row, { ca: fields.ca, fingerprint: "synthetic-fingerprint", "invalid-before": "2026-01-01", "invalid-after": "2030-01-01", "private-key": "true", "serial-number": "synthetic" })
|
||||
} else if (path === "/certificate/export-certificate") catalogs["/file"].push({ ".id": `*new${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" })
|
||||
const row = catalogs["/certificate"].find(row => row[".id"] === fields[".id"]); assert(row)
|
||||
Object.assign(row, { ca: fields.ca, "digest-algorithm": "sha256", fingerprint: "synthetic-fingerprint", "invalid-before": "2026-01-01", "invalid-after": "2030-01-01", "private-key": "true", "serial-number": "synthetic" })
|
||||
} else if (path === "/certificate/export-certificate") assert(catalogs["/certificate"].some(row => row[".id"] === fields[".id"])), catalogs["/file"].push({ ".id": `*new${++serial}`, name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeP12)), type: "file" })
|
||||
else {
|
||||
const catalog = Object.keys(catalogs).find(value => path === value || path.startsWith(value + "/")); assert(catalog)
|
||||
if (req.method === "PUT") { result = { ".id": `*new${++serial}`, ...fields, "native-default": "NEVER_NATIVE_DEFAULT" }; catalogs[catalog].push(result) }
|
||||
|
||||
@@ -148,5 +148,5 @@ export function createIpsecUserCreateAdapter(overrides: Partial<typeof productio
|
||||
export function registerIpsecUserCreateActions(register: typeof add) {
|
||||
const adapter = createIpsecUserCreateAdapter()
|
||||
registerMcpService(operation, adapter.service)
|
||||
register(operation, "mm_ipsec_user_create_plan", "Создать клиента IPsec с проверкой всех native-команд, явным приватным экспортом и managed-only историей", "network", "mm:network:write", "write", "servers", ipsecUserCreateActionSchema, { version: 2, prepare: adapter.prepare })
|
||||
register(operation, "mm_ipsec_user_create_plan", "Создать клиента IPsec с проверкой всех native-команд, явным приватным экспортом и managed-only историей", "network", "mm:network:write", "write", "servers", ipsecUserCreateActionSchema, { version: 3, prepare: adapter.prepare })
|
||||
}
|
||||
@@ -10,8 +10,10 @@ assert.equal(findMcpOperation(fullFlowSettings.operation.id)?.version, 3)
|
||||
assert.equal(fullFlowSettings.schema.safeParse({ settings: { collectorIp: "10.255.254.1", enabled: false, mapServiceMinSharePct: 0 } }).success, true)
|
||||
assert.equal(fullFlowSettings.schema.safeParse({ topN: 10 }).success, false)
|
||||
assert.equal(findAction("mm_netflow_host_keys_generate_plan").operation.id, "traffic.flow.settings.generate-keys")
|
||||
assert.equal(findAction("mm_ipsec_user_create_plan").operation.version, 2)
|
||||
assert.equal(findAction("mm_ipsec_server_init_plan").operation.version, 4)
|
||||
assert.equal(findAction("mm_ipsec_user_create_plan").operation.version, 3)
|
||||
assert.equal(findAction("mm_ipsec_server_init_plan").operation.version, 5)
|
||||
// RouterOS 7.24 certificate bodies (no comment, sign/export by .id): earlier prepared plans need a new approval.
|
||||
assert.equal(findAction("mm_ipsec_existing_certificate_export_plan").operation.version, 2)
|
||||
assert.equal(findAction("mm_ipsec_server_remove_plan").operation.version, 2)
|
||||
assert.equal(findAction("mm_ipsec_revision_restore_plan").operation.version, 1)
|
||||
assert.equal(findAction("mm_wireguard_revision_restore_plan").operation.id, "config.wireguard.revisions.restore")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { MikrotikClient } from "./mikrotik.js"
|
||||
import { IPSEC_CA_CERT, IPSEC_SERVER_CERT, clientCertName, ipsecManagedComment, ipsecServerCertificateNames } from "./ipsec-config.js"
|
||||
import { IPSEC_CA_CERT, IPSEC_CA_COMMON_NAME, IPSEC_SERVER_CERT, clientCertName, ipsecServerCertificateNames } from "./ipsec-config.js"
|
||||
|
||||
type RosCertRow = Record<string, string | undefined>
|
||||
|
||||
@@ -33,15 +33,14 @@ export async function ensureCaCertificate(client: MikrotikClient, daysValid: num
|
||||
if (!existing) {
|
||||
await client.addCertificate({
|
||||
name: IPSEC_CA_CERT,
|
||||
"common-name": "MikrotikManager IPsec CA",
|
||||
"common-name": IPSEC_CA_COMMON_NAME,
|
||||
"key-size": "4096",
|
||||
"key-usage": "key-cert-sign,crl-sign",
|
||||
"days-valid": String(daysValid),
|
||||
comment: ipsecManagedComment("CA"),
|
||||
})
|
||||
}
|
||||
if (!(await isCertificateSigned(client, IPSEC_CA_CERT))) {
|
||||
await client.signCertificate({ name: IPSEC_CA_CERT, daysValid })
|
||||
await client.signCertificate({ name: IPSEC_CA_CERT })
|
||||
await waitCertificateSigned(client, IPSEC_CA_CERT)
|
||||
}
|
||||
const ca = await findCertificate(client, IPSEC_CA_CERT)
|
||||
@@ -66,11 +65,10 @@ export async function ensureServerCertificate(
|
||||
"key-size": "2048",
|
||||
"key-usage": "digital-signature,key-encipherment,tls-server",
|
||||
"days-valid": String(args.daysValid),
|
||||
comment: ipsecManagedComment("server"),
|
||||
})
|
||||
}
|
||||
if (!(await isCertificateSigned(client, IPSEC_SERVER_CERT))) {
|
||||
await client.signCertificate({ name: IPSEC_SERVER_CERT, ca: args.caCertName, daysValid: args.daysValid })
|
||||
await client.signCertificate({ name: IPSEC_SERVER_CERT, ca: args.caCertName })
|
||||
await waitCertificateSigned(client, IPSEC_SERVER_CERT)
|
||||
}
|
||||
return IPSEC_SERVER_CERT
|
||||
@@ -99,9 +97,8 @@ export async function issueClientCertificate(
|
||||
"key-size": "2048",
|
||||
"key-usage": "digital-signature,key-encipherment,tls-client",
|
||||
"days-valid": String(args.daysValid),
|
||||
comment: ipsecManagedComment(`client ${args.userName.trim()}`),
|
||||
})
|
||||
await client.signCertificate({ name: certName, ca: args.caCertName, daysValid: args.daysValid })
|
||||
await client.signCertificate({ name: certName, ca: args.caCertName })
|
||||
await waitCertificateSigned(client, certName)
|
||||
return { certName, commonName: args.userName.trim(), existed: false }
|
||||
}
|
||||
|
||||
@@ -126,6 +126,30 @@ export function clientCertName(userName: string): string {
|
||||
return `ipsec-user-${ipsecSlug(userName) || "client"}`
|
||||
}
|
||||
|
||||
export const IPSEC_CA_COMMON_NAME = "MikrotikManager IPsec CA"
|
||||
/** RouterOS native id: `*<hex>` for configuration rows; RouterOS 7.24 `/file` rows use case-sensitive `**<base62>` ids
|
||||
* whose length follows the file path (stand probe 2026-11-21). */
|
||||
export function isRouterOsNativeId(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length <= 256 && /^\*\*?[a-z0-9]+$/i.test(value)
|
||||
}
|
||||
/** Duplicate key: hex ids compare case-insensitively without leading zeros; `**` file ids compare exactly. */
|
||||
export function routerOsIdKey(value: string): string {
|
||||
return value.startsWith("**") ? value : value.toLowerCase().replace(/^\*0+(?=[a-z0-9])/, "*")
|
||||
}
|
||||
/** RouterOS 7.24 omits a peer `address` equal to the any-address from REST rows (stand probe 2026-11-21). */
|
||||
export const IPSEC_ANY_PEER_ADDRESS = "0.0.0.0/0"
|
||||
/** RouterOS 7.24 `/certificate` has no `comment` (PUT refuses it), so product certificates are recognised by their
|
||||
* fixed name and signing chain. A legacy managed comment is still accepted on read. */
|
||||
export function isIpsecManagedCertificate(row: { name?: string; comment?: string; ca?: string; "common-name"?: string }): boolean {
|
||||
if (row.comment?.trim()) return isIpsecManagedComment(row.comment) // a router version with comments: the comment decides
|
||||
const name = row.name ?? ""
|
||||
return (name === IPSEC_CA_CERT && row["common-name"] === IPSEC_CA_COMMON_NAME) ||
|
||||
((name === IPSEC_SERVER_CERT || name.startsWith("ipsec-user-")) && row.ca === IPSEC_CA_CERT)
|
||||
}
|
||||
/** RouterOS 7.24 addresses `/certificate/sign` and `/certificate/export-certificate` by `.id` only and refuses
|
||||
* `name` and `days-valid` there; the validity period belongs to the certificate template. */
|
||||
export const ipsecSignedCertificateFields = ["authority", "digest-algorithm", "ca", "ca-crl-host", "serial-number", "fingerprint", "invalid-before", "invalid-after", "expires-after", "akid", "skid", "issuer", "private-key", "issued", "status", "trusted"]
|
||||
|
||||
export function userModeConfigName(userName: string): string {
|
||||
return `mc-ipsec-${ipsecSlug(userName) || "client"}`
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { z } from "zod"
|
||||
import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
|
||||
import { McpError } from "../modules/mcp/security.js"
|
||||
import { ipsecPeerDeletePaths, type IpsecPeerDeleteState } from "./ipsec-peer-delete.js"
|
||||
import { IPSEC_COMMON_NAME, IPSEC_SERVER_CERT, parseIpsecUserComment, resolveIke2ServerCert, selectIke2Peers } from "./ipsec-config.js"
|
||||
import { IPSEC_COMMON_NAME, IPSEC_SERVER_CERT, isRouterOsNativeId, parseIpsecUserComment, routerOsIdKey, resolveIke2ServerCert, selectIke2Peers } from "./ipsec-config.js"
|
||||
import { certificateRole } from "./certificate-parse.js"
|
||||
import { resolveIpsecClientTarget, type IpsecServerState } from "./ipsec-live.js"
|
||||
import { MAX_OWNED_FILE_BYTES } from "./mikrotik.js"
|
||||
@@ -27,8 +27,8 @@ export type IpsecExistingCertificateExportState = IpsecPeerDeleteState
|
||||
type Row = Record<string, string>
|
||||
export const ipsecExistingCertificateExportSecretPurpose = (serverId: number, target: IpsecExistingCertificateExportRequest["selector"]) => `ipsec-existing-export-passphrase:${serverId}:${target.kind}:${encodeURIComponent(target.kind === "client" ? target.clientId : target.name)}`
|
||||
const fail = (message: string, code = "STATE_CONFLICT", status = code === "INVALID_INPUT" ? 400 : code === "STATE_UNAVAILABLE" || code === "VERIFICATION_FAILED" ? 502 : 409) => new McpError(code, message, status)
|
||||
const idKey = (value: string) => value.toLowerCase().replace(/^\*0+(?=[a-z0-9])/, "*")
|
||||
const nativeId = (value: unknown): value is string => typeof value === "string" && /^\*[a-z0-9]+$/i.test(value) && value.length <= 100
|
||||
const idKey = routerOsIdKey
|
||||
const nativeId = isRouterOsNativeId
|
||||
export function validateIpsecExistingCertificateExportState(state: IpsecExistingCertificateExportState) {
|
||||
if (!state?.source || !Array.isArray(state.protections) || !state.catalogs || Buffer.byteLength(JSON.stringify(state)) > 1048576) throw fail("Неполное состояние экспорта IPsec", "STATE_UNAVAILABLE")
|
||||
for (const path of [...ipsecPeerDeletePaths, "/file"]) {
|
||||
|
||||
@@ -38,7 +38,7 @@ function fixture() {
|
||||
publish: async (_a, bundle, _proof, authorize) => { await authorize(); return bundle },
|
||||
generatePassphrase: () => "GENERATED_PRIVATE_PASSPHRASE", clock: () => 100000,
|
||||
client: () => ({
|
||||
post: async (_path: string, fields: Record<string, string>, _timeout: unknown, _signal: unknown, dispatch: () => Promise<unknown>) => { await dispatch(); commands.push(fields.name); state.catalogs["/file"].push({ ".id": "*new", name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(bytes)) }); if (mode === "lostAck") throw Error(secret); return {} },
|
||||
post: async (_path: string, fields: Record<string, string>, _timeout: unknown, _signal: unknown, dispatch: () => Promise<unknown>) => { await dispatch(); assert.equal("name" in fields, false, "RouterOS 7.24 refuses name on export-certificate"); commands.push(state.catalogs["/certificate"].find(row => row[".id"] === fields[".id"])?.name); state.catalogs["/file"].push({ ".id": "*new", name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(bytes)) }); if (mode === "lostAck") throw Error(secret); return {} },
|
||||
downloadOwnedFile: async (_file: unknown, control: { authorize: () => Promise<unknown> }) => { await control.authorize(); return Buffer.from(bytes) },
|
||||
delete: async (path: string, _timeout: unknown, dispatch: () => Promise<unknown>) => { await dispatch(); commands.push(path); state.catalogs["/file"] = [] },
|
||||
}) as never,
|
||||
|
||||
@@ -23,7 +23,7 @@ export class IpsecExistingCertificateExportRestJournalError extends Error {
|
||||
}
|
||||
function fail(): never { throw new IpsecExistingCertificateExportRestJournalError() }
|
||||
const digest = z.string().regex(/^[a-f0-9]{64}$/), uuid = z.string().uuid()
|
||||
const nativeId = z.string().regex(/^\*[a-z0-9]+$/i).max(100)
|
||||
const nativeId = z.string().regex(/^\*\*?[a-z0-9]+$/i).max(256) // RouterOS 7.24 file ids are `**<base62>`
|
||||
const actorSchema = z.object({ id: z.string().min(1).max(200), email: z.string(), name: z.string(), apps: z.array(z.string()).max(1000),
|
||||
permissions: z.array(z.string()).max(1000), isAdmin: z.boolean().optional(), expiresAt: z.number().int().positive().safe(), issuedAt: z.number().int().nonnegative().safe() }).strict()
|
||||
const selectionSchema = z.object({ serverId: z.number().int().positive().safe(),
|
||||
|
||||
@@ -71,7 +71,7 @@ try {
|
||||
post: async (path: string, fields: Row, _timeout: unknown, _signal: unknown, beforeDispatch: () => Promise<unknown>) => {
|
||||
if (mode === "missingPostFence") return {}
|
||||
if (mode === "parallelPostFence") { delayNextRead = true; await Promise.all([beforeDispatch().then(() => { commands.push({ method: "POST", path }) }), beforeDispatch()]); return {} }
|
||||
await beforeDispatch(); if (mode === "duplicatePostFence") await beforeDispatch(); commands.push({ method: "POST", path }); assert.equal(path, "/certificate/export-certificate"); assert.equal(fields.type, "pkcs12"); assert.equal(fields.name, "client-cert"); assert.equal(fields["file-name"], clientPlan.exportPrefix)
|
||||
await beforeDispatch(); if (mode === "duplicatePostFence") await beforeDispatch(); commands.push({ method: "POST", path }); assert.equal(path, "/certificate/export-certificate"); assert.equal(fields.type, "pkcs12"); assert.equal("name" in fields, false, "RouterOS 7.24 refuses name on export-certificate"); assert.equal(fields[".id"], "*c"); assert.equal(fields["file-name"], clientPlan.exportPrefix)
|
||||
if (mode !== "ignored") state.catalogs["/file"].push({ ".id": "*new", name: `${fields["file-name"]}.p12`, size: String(Buffer.byteLength(fakeBytes)), type: "file", opaque: "NEVER_NEW_FILE" })
|
||||
if (mode === "collateral") state.catalogs["/certificate"][0].opaque = "NEVER_CHANGED_CA"
|
||||
if (mode === "revoked") revoked = true
|
||||
|
||||
@@ -122,7 +122,7 @@ export function createIpsecExistingCertificateExportExecutor<A extends IpsecExis
|
||||
const client = deps.client(server)
|
||||
const fence = async () => { const current = await read(); if (current.proof !== state.proof) throw new McpError("STATE_CONFLICT", "Состояние экспорта изменилось после durable intent", 409); await source() }
|
||||
let dispatched = false, exportFences = 0, cleanupFences = 0, duplicateFence = false
|
||||
try { await bounded(() => client.post("/certificate/export-certificate", { name: plan.certificateName, type: "pkcs12", "file-name": plan.exportPrefix, "export-passphrase": passphrase }, remaining(60000), signal, async () => { if (++exportFences !== 1) { duplicateFence = true; throw new McpError("VERIFICATION_FAILED", "Повтор export dispatch fence запрещён", 502) }; await fence(); if (duplicateFence || exportFences !== 1) throw new McpError("VERIFICATION_FAILED", "Export fence отозван параллельным callback", 502); dispatched = true; nativeAttempted = true })); if (!dispatched || exportFences !== 1) throw stopped("VERIFICATION_FAILED"); confirmedWrites++ }
|
||||
try { await bounded(() => client.post("/certificate/export-certificate", { ".id": plan.certificateId, type: "pkcs12", "file-name": plan.exportPrefix, "export-passphrase": passphrase }, remaining(60000), signal, async () => { if (++exportFences !== 1) { duplicateFence = true; throw new McpError("VERIFICATION_FAILED", "Повтор export dispatch fence запрещён", 502) }; await fence(); if (duplicateFence || exportFences !== 1) throw new McpError("VERIFICATION_FAILED", "Export fence отозван параллельным callback", 502); dispatched = true; nativeAttempted = true })); if (!dispatched || exportFences !== 1) throw stopped("VERIFICATION_FAILED"); confirmedWrites++ }
|
||||
catch (error) { if (duplicateFence || error instanceof IpsecExistingCertificateExportExecutionError) throw stopped("VERIFICATION_FAILED"); if (!dispatched && error instanceof McpError) throw error; throw stopped("MUTATION_OUTCOME_UNKNOWN") }
|
||||
let file: { id: string; name: string; size: number }
|
||||
let afterExport: IpsecExistingCertificateExportState
|
||||
|
||||
@@ -4,7 +4,7 @@ import { fingerprint, McpError, privateFingerprinter } from "../modules/mcp/secu
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { sameWireguardEndpoint, wireguardEndpointSource } from "./wireguard-source.js"
|
||||
import { observedBoolean } from "./ospf-observed-values.js"
|
||||
import { identityDisplayName } from "./ipsec-config.js"
|
||||
import { identityDisplayName, isRouterOsNativeId } from "./ipsec-config.js"
|
||||
import { captureIpsecSnapshot } from "./ipsec-live.js"
|
||||
import { captureAndAppendRevision } from "./config-revisions.js"
|
||||
import { maskNetworkSecrets, networkSecretValues } from "./network-observed-read.js"
|
||||
@@ -25,7 +25,7 @@ async function source(server: ServerRow, authorize: () => Promise<unknown>) {
|
||||
if (!fresh || !sameWireguardEndpoint(fresh, server)) throw fail("STATE_CONFLICT", "Источник IPsec изменился")
|
||||
}
|
||||
export function ipsecPeerDeleteRows(value: unknown): Row[] {
|
||||
if (!Array.isArray(value) || value.length > 2000 || value.some(row => !row || typeof row !== "object" || Array.isArray(row) || typeof row[".id"] !== "string" || !/^\*[a-z0-9]+$/i.test(row[".id"]) || Object.values(row).some(v => typeof v !== "string"))) throw fail("STATE_UNAVAILABLE", "Неполный native-каталог IPsec")
|
||||
if (!Array.isArray(value) || value.length > 2000 || value.some(row => !row || typeof row !== "object" || Array.isArray(row) || typeof row[".id"] !== "string" || !isRouterOsNativeId(row[".id"]) || Object.values(row).some(v => typeof v !== "string"))) throw fail("STATE_UNAVAILABLE", "Неполный native-каталог IPsec")
|
||||
if (new Set(value.map(row => row[".id"])).size !== value.length) throw fail("STATE_UNAVAILABLE", "Повторяющийся native ID IPsec")
|
||||
return value as Row[]
|
||||
}
|
||||
|
||||
@@ -13,6 +13,13 @@ const state = empty(), frozen = structuredClone(state), plan = planIpsecServerIn
|
||||
assert.deepEqual(state, frozen)
|
||||
assert.equal(plan.commands.length, 14)
|
||||
assert.equal(plan.commands.filter(row => row.action === "sign").length, 2)
|
||||
// RouterOS 7.24 refuses `comment` on /certificate and `name`/`days-valid` on sign (stand probe 2026-11-21).
|
||||
assert(plan.commands.filter(row => row.path === "/certificate" && row.action === "create").every(row => !("comment" in row.fields)))
|
||||
assert(plan.commands.filter(row => row.action === "sign").every(row => Object.keys(row.fields).every(key => key === "ca")))
|
||||
for (const foreign of [{ "common-name": "Other CA" }, { "common-name": "MikrotikManager IPsec CA", comment: "foreign" }].map(extra => ({ ".id": "*f", name: IPSEC_CA_CERT, fingerprint: "f", "invalid-after": "2030-01-01", ...extra }))) {
|
||||
const bad = empty(); bad.catalogs["/certificate"].push(foreign)
|
||||
assert.throws(() => planIpsecServerInit(bad, server, request), foreign.comment ? undefined : { code: "PROTECTED_OBJECT" })
|
||||
}
|
||||
assert(!plan.commands.some(row => /export|^\/file/.test(row.path)))
|
||||
assert.equal(plan.commands.at(-1)!.fields["out-interface"], "ether1")
|
||||
assert.equal(plan.commands.find(row => row.fields.name === IPSEC_SERVER_CERT && row.action === "create")!.fields["days-valid"], "900")
|
||||
@@ -41,20 +48,23 @@ const owned = new Set<string>()
|
||||
for (const command of plan.commands) {
|
||||
const input = projected, prior = structuredClone(projected)
|
||||
if (command.action === "create") {
|
||||
const id = `*n${++serial}`, row = { ".id": id, ...command.fields, "opaque-default": "NEVER_DEFAULT" }
|
||||
const id = `*n${++serial}`, row: Record<string, string> = { ".id": id, ...command.fields, "opaque-default": "NEVER_DEFAULT" }
|
||||
if (command.path === "/ip/ipsec/peer" && row.address === "0.0.0.0/0") delete row.address // RouterOS 7.24 omits the any-address
|
||||
assert.throws(() => projectIpsecServerInit(projected, command, { observedRow: row }))
|
||||
assert.throws(() => projectIpsecServerInit(projected, command, { assignedId: id, observedRow: { ...row, [Object.keys(command.fields)[0]]: "changed" } }))
|
||||
projected = projectIpsecServerInit(projected, command, { assignedId: id, observedRow: row })
|
||||
if (command.path === "/certificate") owned.add(id)
|
||||
} else if (command.action === "sign") {
|
||||
const row = projected.catalogs["/certificate"].find(row => row.name === command.name)!
|
||||
const signed = { ...row, ...(command.fields.ca ? { ca: command.fields.ca } : {}), fingerprint: "synthetic", "invalid-after": "2030-01-01" }
|
||||
const signed = { ...row, ...(command.fields.ca ? { ca: command.fields.ca } : {}), fingerprint: "synthetic", "invalid-after": "2030-01-01", "digest-algorithm": "sha256", ...(command.fields.ca ? {} : { authority: "true" }) }
|
||||
assert.throws(() => projectIpsecServerInit(projected, command, { observedRow: signed, ownedCertificateIds: new Set() }))
|
||||
assert.throws(() => projectIpsecServerInit(projected, command, { observedRow: { ...signed, "opaque-default": "changed" }, ownedCertificateIds: owned }))
|
||||
projected = projectIpsecServerInit(projected, command, { observedRow: signed, ownedCertificateIds: owned })
|
||||
} else projected = projectIpsecServerInit(projected, command, { ownedCertificateIds: owned })
|
||||
assert.deepEqual(input, prior)
|
||||
}
|
||||
// Commentless product certificates (as RouterOS 7.24 stores them) are recognised by name and chain on a rerun.
|
||||
assert(projected.catalogs["/certificate"].every(row => !("comment" in row)))
|
||||
const rerun = planIpsecServerInit(projected, server, request)
|
||||
assert(!rerun.commands.some(row => row.action === "sign"))
|
||||
assert(!rerun.commands.some(row => row.action === "create"))
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { ServerRow } from "../modules/servers/repository/servers-repository
|
||||
import { McpError } from "../modules/mcp/security.js"
|
||||
import { ipsecPeerDeletePaths, type IpsecPeerDeleteState } from "./ipsec-peer-delete.js"
|
||||
import { observedBoolean } from "./ospf-observed-values.js"
|
||||
import { IPSEC_CA_CERT, IPSEC_COMMON_NAME, IPSEC_SERVER_CERT, IPSEC_POLICY_GROUP, ipsecManagedComment, ipsecServerCertificateNames, isIpsecManagedComment, poolRangesFromCidr, selectIke2Peers, selectSharedIke2Identity } from "./ipsec-config.js"
|
||||
import { IPSEC_ANY_PEER_ADDRESS, IPSEC_CA_CERT, IPSEC_CA_COMMON_NAME, IPSEC_COMMON_NAME, IPSEC_SERVER_CERT, IPSEC_POLICY_GROUP, ipsecManagedComment, ipsecServerCertificateNames, ipsecSignedCertificateFields, isIpsecManagedCertificate, isIpsecManagedComment, poolRangesFromCidr, selectIke2Peers, selectSharedIke2Identity } from "./ipsec-config.js"
|
||||
import { identityRosBody, selectIpsecNatInterface } from "./ipsec-ros.js"
|
||||
import { assertPoolMutationDependencies } from "./ipsec-pool-dependencies.js"
|
||||
|
||||
@@ -63,9 +63,9 @@ export function planIpsecServerInit(state: IpsecServerInitState, server: ServerR
|
||||
system(row)
|
||||
const legacy = row.name === IPSEC_COMMON_NAME && ["/ip/ipsec/profile", "/ip/ipsec/mode-config"].includes(path) && managedPeer
|
||||
const group = path === "/ip/ipsec/policy/group" && row.name === IPSEC_POLICY_GROUP && c["/ip/ipsec/policy"].some(p => references(p.group, path, row) && isIpsecManagedComment(p.comment))
|
||||
if (!isIpsecManagedComment(row.comment) && !legacy && !group) throw fail("Имя IPsec занято чужим объектом", "PROTECTED_OBJECT")
|
||||
if (!isIpsecManagedComment(row.comment) && !legacy && !group && !(path === "/certificate" && isIpsecManagedCertificate(row))) throw fail("Имя IPsec занято чужим объектом", "PROTECTED_OBJECT")
|
||||
for (const consumer of consumers(path, row)) {
|
||||
if (consumer.path === "/certificate" && consumer.row[".id"] === row[".id"]) continue
|
||||
if (consumer.path === "/certificate" && (consumer.row[".id"] === row[".id"] || isIpsecManagedCertificate(consumer.row))) continue
|
||||
if (consumer.path === "/ip/ipsec/policy" && observedBoolean(consumer.row.dynamic) === true) continue
|
||||
const legacyMc = consumer.path === "/ip/ipsec/mode-config" && consumer.row.name === IPSEC_COMMON_NAME && managedPeer
|
||||
if (!isIpsecManagedComment(consumer.row.comment) && !legacyMc) throw fail("Объект IPsec используется чужой конфигурацией", "DEPENDENCY_CONFLICT")
|
||||
@@ -78,12 +78,12 @@ export function planIpsecServerInit(state: IpsecServerInitState, server: ServerR
|
||||
const certificate = (name: string, fields: Row, ca?: string) => {
|
||||
const row = named("/certificate", name)
|
||||
if (row) { owned("/certificate", row); if (!row["invalid-after"]?.trim() || !row.fingerprint?.trim()) throw fail("Существующий неподписанный сертификат требует отдельного проверенного плана; подпись разрешена только новому ACK-owned сертификату"); if (ca && row.ca !== ca) throw fail("Серверный сертификат подписан другим CA"); return row }
|
||||
commands.push({ action: "create", path: "/certificate", fields: { name, ...fields } }, { action: "sign", path: "/certificate/sign", name, fields: { name, ...(ca ? { ca } : {}), "days-valid": fields["days-valid"] } })
|
||||
commands.push({ action: "create", path: "/certificate", fields: { name, ...fields } }, { action: "sign", path: "/certificate/sign", name, fields: { ...(ca ? { ca } : {}) } })
|
||||
return undefined
|
||||
}
|
||||
const ca = certificate(IPSEC_CA_CERT, { "common-name": "MikrotikManager IPsec CA", "key-size": "4096", "key-usage": "key-cert-sign,crl-sign", "days-valid": String(body.caDaysValid), comment: ipsecManagedComment("CA") })
|
||||
const ca = certificate(IPSEC_CA_CERT, { "common-name": IPSEC_CA_COMMON_NAME, "key-size": "4096", "key-usage": "key-cert-sign,crl-sign", "days-valid": String(body.caDaysValid) })
|
||||
if (!ca || observedBoolean(ca.trusted) !== true) commands.push({ action: "update", path: "/certificate", ...(ca ? { id: ca[".id"] } : { name: IPSEC_CA_CERT }), fields: { trusted: "yes" } })
|
||||
certificate(IPSEC_SERVER_CERT, { "common-name": namesForCertificate.endpoint, "subject-alt-name": namesForCertificate.san, "key-size": "2048", "key-usage": "digital-signature,key-encipherment,tls-server", "days-valid": String(body.serverDaysValid), comment: ipsecManagedComment("server") }, IPSEC_CA_CERT)
|
||||
certificate(IPSEC_SERVER_CERT, { "common-name": namesForCertificate.endpoint, "subject-alt-name": namesForCertificate.san, "key-size": "2048", "key-usage": "digital-signature,key-encipherment,tls-server", "days-valid": String(body.serverDaysValid) }, IPSEC_CA_CERT)
|
||||
const comment = ipsecManagedComment("IKEv2 road-warrior")
|
||||
upsert("/ip/ipsec/profile", { name: IPSEC_COMMON_NAME, "hash-algorithm": "sha256", "enc-algorithm": "aes-256,aes-192,aes-128", "dh-group": "modp2048", "nat-traversal": "yes" })
|
||||
upsert("/ip/ipsec/proposal", { name: IPSEC_COMMON_NAME, "auth-algorithms": "sha256", "enc-algorithms": "aes-256-cbc,aes-192-cbc,aes-128-cbc", "pfs-group": "modp2048", comment })
|
||||
@@ -94,7 +94,7 @@ export function planIpsecServerInit(state: IpsecServerInitState, server: ServerR
|
||||
const templates = c["/ip/ipsec/policy"].filter(row => row.comment?.trim() === comment && observedBoolean(row.template) === true)
|
||||
if (templates.length > 1) throw fail("Неоднозначный шаблон IPsec")
|
||||
upsert("/ip/ipsec/policy", { "src-address": "0.0.0.0/0", "dst-address": body.poolCidr, proposal: IPSEC_COMMON_NAME, group: IPSEC_POLICY_GROUP, comment, ...(!templates.length ? { template: "yes" } : {}) }, templates[0])
|
||||
upsert("/ip/ipsec/peer", { name: IPSEC_COMMON_NAME, address: "0.0.0.0/0", "exchange-mode": "ike2", passive: "yes", profile: IPSEC_COMMON_NAME, comment })
|
||||
upsert("/ip/ipsec/peer", { name: IPSEC_COMMON_NAME, address: IPSEC_ANY_PEER_ADDRESS, "exchange-mode": "ike2", passive: "yes", profile: IPSEC_COMMON_NAME, comment })
|
||||
const names = [...new Set([...selectIke2Peers(c["/ip/ipsec/peer"]).map(row => row.name!), IPSEC_COMMON_NAME])]
|
||||
const listener = selectSharedIke2Identity(c["/ip/ipsec/identity"], names) as Row | undefined
|
||||
if (listener) { owned("/ip/ipsec/identity", listener); if (listener["policy-template-group"] !== IPSEC_POLICY_GROUP) commands.push({ action: "update", path: "/ip/ipsec/identity", id: listener[".id"], fields: { "policy-template-group": IPSEC_POLICY_GROUP } }) }
|
||||
@@ -130,7 +130,7 @@ export function projectIpsecServerInit(state: IpsecServerInitState, command: Ips
|
||||
} else if (command.action === "sign") {
|
||||
const row = rows.find(item => item.name === command.name), observed = options.observedRow
|
||||
if (!row || !options.ownedCertificateIds?.has(row[".id"]) || !observed || observed[".id"] !== row[".id"] || !observed["invalid-after"]?.trim() || !observed.fingerprint?.trim()) throw fail("Не подтверждена подпись нового сертификата", "VERIFICATION_FAILED")
|
||||
const generated = new Set(["ca", "ca-crl-host", "serial-number", "fingerprint", "invalid-before", "invalid-after", "expires-after", "akid", "skid", "issuer", "private-key", "issued", "status", "trusted"])
|
||||
const generated = new Set(ipsecSignedCertificateFields)
|
||||
for (const key of new Set([...Object.keys(row), ...Object.keys(observed)])) if (!generated.has(key) && observed[key] !== row[key]) throw fail("При подписи изменены исходные поля сертификата", "VERIFICATION_FAILED")
|
||||
if (command.fields.ca && observed.ca !== command.fields.ca) throw fail("CA подписи не подтверждён", "VERIFICATION_FAILED")
|
||||
rows[rows.indexOf(row)] = structuredClone(observed)
|
||||
@@ -138,7 +138,7 @@ export function projectIpsecServerInit(state: IpsecServerInitState, command: Ips
|
||||
const row = options.observedRow, id = options.assignedId
|
||||
if (!row || !exactId(id) || row[".id"] !== id || rows.some(item => idKey(item[".id"]) === idKey(id)) || Object.values(row).some(value => typeof value !== "string")) throw fail("Не подтверждён ACK нового объекта", "VERIFICATION_FAILED")
|
||||
for (const flag of ["dynamic", "builtin", "default"]) if (row[flag] !== undefined && observedBoolean(row[flag]) !== false) throw fail("Создан системный объект", "VERIFICATION_FAILED")
|
||||
for (const [key, value] of Object.entries(command.fields)) if (row[key] !== value && !(["disabled", "responder", "template", "nat-traversal", "passive", "trusted"].includes(key) && observedBoolean(row[key]) !== null && observedBoolean(row[key]) === observedBoolean(value))) throw fail("Поля нового объекта не подтверждены", "VERIFICATION_FAILED")
|
||||
for (const [key, value] of Object.entries(command.fields)) if (row[key] !== value && !(command.path === "/ip/ipsec/peer" && key === "address" && row[key] === undefined && value === IPSEC_ANY_PEER_ADDRESS) && !(["disabled", "responder", "template", "nat-traversal", "passive", "trusted"].includes(key) && observedBoolean(row[key]) !== null && observedBoolean(row[key]) === observedBoolean(value))) throw fail("Поля нового объекта не подтверждены", "VERIFICATION_FAILED")
|
||||
rows.push(structuredClone(row))
|
||||
}
|
||||
return next
|
||||
|
||||
@@ -12,6 +12,7 @@ import { captureAndAppendRevision } from "./config-revisions.js"
|
||||
import { captureIpsecSnapshot, mapClients, mapServerSummary, type IpsecServerState } from "./ipsec-live.js"
|
||||
import { ipsecServerInitRequest, planIpsecServerInit, projectIpsecServerInit, validateIpsecServerInitState, type IpsecServerInitState } from "./ipsec-server-init-model.js"
|
||||
import { ipsecExternalPoolDependencyPaths, ipsecPoolDependencies } from "./ipsec-pool-dependencies.js"
|
||||
import { IPSEC_ANY_PEER_ADDRESS } from "./ipsec-config.js"
|
||||
|
||||
// Interface counters and link timestamps change with every packet; sealing them made two reads of a live
|
||||
// router disagree, so prepare, fence and per-command read-back refused. Configuration and `running` stay sealed.
|
||||
@@ -20,6 +21,8 @@ const interfaceTelemetry = ["rx-byte", "tx-byte", "rx-packet", "tx-packet", "rx-
|
||||
export function ipsecServerInitValue(state: IpsecServerInitState) {
|
||||
const value = ipsecPeerDeleteValue(state)
|
||||
for (const row of value.catalogs["/interface"] ?? []) for (const key of interfaceTelemetry) delete row[key]
|
||||
// RouterOS 7.24 does not return a peer address equal to the any-address; an update that sends it is not a change.
|
||||
for (const row of value.catalogs["/ip/ipsec/peer"] ?? []) if (row.address === IPSEC_ANY_PEER_ADDRESS) delete row.address
|
||||
for (const rows of Object.values(value.catalogs)) for (const row of rows) for (const key of ["disabled", "responder", "template", "nat-traversal", "passive", "trusted"]) {
|
||||
if (row[key] === undefined) continue
|
||||
const boolean = observedBoolean(row[key])
|
||||
@@ -66,7 +69,12 @@ export async function initIpsecServerGuarded(server: ServerRow, raw: unknown, ex
|
||||
const id = command.id ?? state.catalogs[command.path].find(row => row.name === command.name && ownedCertificateIds.has(row[".id"]))?.[".id"]
|
||||
if (!id) throw new McpError("STATE_CONFLICT", "Не подтверждён объект изменения IPsec", 409)
|
||||
response = await client.patch(`${command.path}/${encodeURIComponent(id)}`, command.fields, 15000, fence)
|
||||
} else response = await client.post(command.path, command.fields, 120000, undefined, fence)
|
||||
} else {
|
||||
// RouterOS signs by native id only; the certificate is the one this run created and ACKed.
|
||||
const id = state.catalogs["/certificate"].find(row => row.name === command.name && ownedCertificateIds.has(row[".id"]))?.[".id"]
|
||||
if (!id) throw new McpError("STATE_CONFLICT", "Не подтверждён сертификат подписи IPsec", 409)
|
||||
response = await client.post(command.path, { ".id": id, ...command.fields }, 120000, undefined, fence)
|
||||
}
|
||||
confirmedWrites++
|
||||
} catch (error) {
|
||||
if (!dispatched && !completedCommands && error instanceof McpError) throw error
|
||||
|
||||
@@ -19,6 +19,9 @@ const base = (): IpsecUserCreateState => ({ source: "source", proof: "proof", pr
|
||||
const request = { serverId: 1, name: "Alice", authMethod: "pre-shared-key", psk: "NEVER_TEST_SECRET" }
|
||||
const state = base(), original = structuredClone(state), psk = plan(state, server, request, "mm-ipsec-fixture")
|
||||
assert.equal(psk.commands.length, 1)
|
||||
// RouterOS 7.24 /file ids are case-sensitive `**<base62>` (stand probe 2026-11-21): accepted, never folded into duplicates.
|
||||
const files = base(); files.catalogs["/file"].push({ ".id": "**Qb24a2KNOW6Ay8FA4", name: "a.rsc", size: "1" }, { ".id": "**qB24a2KNOW6Ay8FA4", name: "b.rsc", size: "1" })
|
||||
assert.equal(plan(files, server, request, "mm-ipsec-fixture").commands.length, 1)
|
||||
assert.deepEqual(psk.commands[0].fields, { peer: "ike", "auth-method": "pre-shared-key", secret: "NEVER_TEST_SECRET", "remote-id": "key-id:Alice", "mode-config": "ipsec-vpn", "generate-policy": "port-strict", "policy-template-group": "group", comment: "MikrotikManager:ipsec user=Alice" })
|
||||
for (const id of ["*p", "*r", "*l", "*g", "*y", "*q", "*m", "*o"]) assert(psk.companions.some(row => row.id === id))
|
||||
const staticPlan = plan(state, server, { ...request, staticIp: "192.0.2.7", remoteId: "fqdn:alice.example.test", peerName: "ike" }, "mm-ipsec-fixture")
|
||||
@@ -55,9 +58,13 @@ assert.throws(() => plan(chain, server, { serverId: 1, name: "Alice" }, "mm-ipse
|
||||
const cert = plan(state, server, { serverId: 1, name: "Alice", daysValid: 365, passphrase: "export-secret" }, "mm-ipsec-fixture")
|
||||
assert.deepEqual(cert.commands.map(row => row.action), ["create", "sign", "export", "cleanup"])
|
||||
assert.equal(cert.commands[0].fields["days-valid"], "365")
|
||||
// RouterOS 7.24 refuses `comment` on /certificate, `name`/`days-valid` on sign and `name` on export (stand probe 2026-11-21).
|
||||
assert.equal("comment" in cert.commands[0].fields, false)
|
||||
assert.deepEqual(cert.commands[1].fields, { ca: "ca" })
|
||||
assert.equal(cert.commands[2].certificate, cert.commands[0].fields.name); assert.equal("name" in cert.commands[2].fields, false)
|
||||
const certCommand = cert.commands[0], createdRow = { ".id": "*new", ...certCommand.fields, "private-key": "true", opaque: "new" }
|
||||
const withCert = project(state, certCommand, { assignedId: "*new", observedRow: createdRow })
|
||||
const signed = { ...createdRow, ca: "ca", fingerprint: "1234", "invalid-after": "2030-01-01", "invalid-before": "2026-01-01", "serial-number": "123" }
|
||||
const signed = { ...createdRow, ca: "ca", fingerprint: "1234", "invalid-after": "2030-01-01", "invalid-before": "2026-01-01", "serial-number": "123", "digest-algorithm": "sha256" }
|
||||
assert.throws(() => project(withCert, cert.commands[1], { observedRow: signed }), /подпись/)
|
||||
const signedState = project(withCert, cert.commands[1], { observedRow: signed, ownedCertificateIds: new Set(["*new"]) })
|
||||
assert.deepEqual(signedState.catalogs["/certificate"].slice(0, 2), state.catalogs["/certificate"])
|
||||
|
||||
@@ -4,21 +4,21 @@ import type { ServerRow } from "../modules/servers/repository/servers-repository
|
||||
import { McpError } from "../modules/mcp/security.js"
|
||||
import { ipsecPeerDeletePaths, type IpsecPeerDeleteState } from "./ipsec-peer-delete.js"
|
||||
import { mapClients, type IpsecServerState } from "./ipsec-live.js"
|
||||
import { IPSEC_COMMON_NAME, clientCertName, ipsecManagedComment, ipsecUserComment, isIpsecManagedComment, isManagedIpsecModeConfig, isIke2RemoteAccessIdentity, normalizeIpsecRemoteId, resolveIke2CaName, resolveIke2ServerCert, selectIke2Peers, selectSharedIke2Identity, userModeConfigName } from "./ipsec-config.js"
|
||||
import { IPSEC_COMMON_NAME, ipsecSignedCertificateFields, isRouterOsNativeId, routerOsIdKey, clientCertName, ipsecManagedComment, ipsecUserComment, isIpsecManagedComment, isManagedIpsecModeConfig, isIke2RemoteAccessIdentity, normalizeIpsecRemoteId, resolveIke2CaName, resolveIke2ServerCert, selectIke2Peers, selectSharedIke2Identity, userModeConfigName } from "./ipsec-config.js"
|
||||
import { identityRosBody } from "./ipsec-ros.js"
|
||||
import { observedBoolean } from "./ospf-observed-values.js"
|
||||
|
||||
type Row = Record<string, string>
|
||||
export type IpsecUserCreateState = IpsecPeerDeleteState
|
||||
export const ipsecUserCreateRequest = ipsecUserCreateRequestSchema.strict()
|
||||
export interface IpsecUserCreateCommand { action: "create" | "update" | "sign" | "export" | "cleanup"; path: string; fields: Row; id?: string; name?: string }
|
||||
export interface IpsecUserCreateCommand { action: "create" | "update" | "sign" | "export" | "cleanup"; path: string; fields: Row; id?: string; name?: string; certificate?: string }
|
||||
const fail = (message: string, code = "STATE_CONFLICT") => new McpError(code, message, code === "INVALID_INPUT" ? 400 : code === "STATE_UNAVAILABLE" ? 502 : 409)
|
||||
const exactId = (value: unknown): value is string => typeof value === "string" && /^\*[a-z0-9]+$/i.test(value) && value.length <= 100
|
||||
const exactId = isRouterOsNativeId
|
||||
export function validateIpsecUserCreateState(state: IpsecUserCreateState) {
|
||||
if (!state?.source || !state.catalogs || !Array.isArray(state.protections)) throw fail("Неполное состояние IPsec", "STATE_UNAVAILABLE")
|
||||
for (const path of [...ipsecPeerDeletePaths, "/file"]) {
|
||||
const rows = state.catalogs[path]
|
||||
if (!Array.isArray(rows) || rows.length > 2000 || rows.some(row => !row || !exactId(row[".id"]) || Object.values(row).some(value => typeof value !== "string")) || new Set(rows.map(row => row[".id"].toLowerCase())).size !== rows.length) throw fail("Неполный native-каталог IPsec", "STATE_UNAVAILABLE")
|
||||
if (!Array.isArray(rows) || rows.length > 2000 || rows.some(row => !row || !exactId(row[".id"]) || Object.values(row).some(value => typeof value !== "string")) || new Set(rows.map(row => routerOsIdKey(row[".id"]))).size !== rows.length) throw fail("Неполный native-каталог IPsec", "STATE_UNAVAILABLE")
|
||||
const names = rows.map(row => row.name?.trim()).filter(Boolean)
|
||||
if (path !== "/ip/ipsec/active-peers" && new Set(names).size !== names.length) throw fail("Неоднозначное имя IPsec")
|
||||
}
|
||||
@@ -62,13 +62,13 @@ export function planIpsecUserCreate(state: IpsecUserCreateState, server: ServerR
|
||||
}
|
||||
if (certName) {
|
||||
seed("/certificate", serverCert); seed("/certificate", c["/certificate"].find(row => row.name === caName))
|
||||
commands.push({ action: "create", path: "/certificate", fields: { name: certName, "common-name": body.name.trim(), "key-size": "2048", "key-usage": "digital-signature,key-encipherment,tls-client", "days-valid": String(body.daysValid ?? 1825), comment: ipsecManagedComment(`client ${body.name.trim()}`) } })
|
||||
commands.push({ action: "sign", path: "/certificate/sign", name: certName, fields: { name: certName, ca: caName!, "days-valid": String(body.daysValid ?? 1825) } })
|
||||
commands.push({ action: "create", path: "/certificate", fields: { name: certName, "common-name": body.name.trim(), "key-size": "2048", "key-usage": "digital-signature,key-encipherment,tls-client", "days-valid": String(body.daysValid ?? 1825) } })
|
||||
commands.push({ action: "sign", path: "/certificate/sign", name: certName, fields: { ca: caName! } })
|
||||
}
|
||||
if (body.authMethod !== "certificate" || body.staticIp || !sharedIdentity) commands.push({ action: "create", path: "/ip/ipsec/identity", fields: identityRosBody({ peerName: peer.name, modeConfig, comment: certName && !body.staticIp ? ipsecManagedComment("IKEv2 listener") : ipsecUserComment(body.name), authMethod: body.authMethod, certificate: certName ? serverCert!.name : undefined, remoteCertificate: body.staticIp ? certName : undefined, secret: body.psk, remoteId: body.authMethod === "pre-shared-key" ? body.remoteId ?? body.name : undefined, policyTemplateGroup: sharedIdentity?.["policy-template-group"] }) })
|
||||
if (certName) {
|
||||
if (c["/file"].some(row => row.name === `${exportPrefix}.p12`)) throw fail("Имя файла экспорта занято")
|
||||
commands.push({ action: "export", path: "/certificate/export-certificate", name: `${exportPrefix}.p12`, fields: { name: certName, type: "pkcs12", "file-name": exportPrefix, "export-passphrase": body.passphrase ?? "" } }, { action: "cleanup", path: "/file", name: `${exportPrefix}.p12`, fields: {} })
|
||||
commands.push({ action: "export", path: "/certificate/export-certificate", name: `${exportPrefix}.p12`, certificate: certName, fields: { type: "pkcs12", "file-name": exportPrefix, "export-passphrase": body.passphrase ?? "" } }, { action: "cleanup", path: "/file", name: `${exportPrefix}.p12`, fields: {} })
|
||||
}
|
||||
const kinds: Record<string, string> = { "/ip/ipsec/peer": "ipsec_peer", "/ip/ipsec/identity": "ipsec_identity", "/ip/ipsec/mode-config": "ipsec_mode_config", "/ip/pool": "ip_pool", "/certificate": "certificate", "/ip/ipsec/profile": "ipsec_profile", "/ip/ipsec/proposal": "ipsec_proposal", "/ip/ipsec/policy/group": "ipsec_policy_group", "/ip/ipsec/policy": "ipsec_policy" }
|
||||
const refs: Record<string, string> = { peer: "/ip/ipsec/peer", "mode-config": "/ip/ipsec/mode-config", "address-pool": "/ip/pool", certificate: "/certificate", "remote-certificate": "/certificate", ca: "/certificate", profile: "/ip/ipsec/profile", proposal: "/ip/ipsec/proposal", "policy-template-group": "/ip/ipsec/policy/group" }
|
||||
@@ -120,7 +120,7 @@ export function projectIpsecUserCreate(state: IpsecUserCreateState, command: Ips
|
||||
} else if (command.action === "sign") {
|
||||
const row = rows.find(item => item.name === command.name), observed = options.observedRow
|
||||
if (!row || !options.ownedCertificateIds?.has(row[".id"]) || !observed || observed[".id"] !== row[".id"] || !observed["invalid-after"]?.trim() || !observed.fingerprint?.trim()) throw fail("Не подтверждена подпись нового сертификата", "VERIFICATION_FAILED")
|
||||
const generated = new Set(["ca", "ca-crl-host", "serial-number", "fingerprint", "invalid-before", "invalid-after", "expires-after", "akid", "skid", "issuer", "private-key", "issued", "status", "trusted"])
|
||||
const generated = new Set(ipsecSignedCertificateFields)
|
||||
for (const key of new Set([...Object.keys(row), ...Object.keys(observed)])) if (!generated.has(key) && observed[key] !== row[key]) throw fail("При подписи изменены исходные поля сертификата", "VERIFICATION_FAILED")
|
||||
if (observed.ca !== command.fields.ca) throw fail("CA подписи не подтверждён", "VERIFICATION_FAILED")
|
||||
rows[rows.indexOf(row)] = structuredClone(observed)
|
||||
|
||||
@@ -47,7 +47,13 @@ export async function createIpsecUserGuarded(server: ServerRow, raw: unknown, ex
|
||||
response = await client.delete(`/file/${encodeURIComponent(assignedId)}`, 10000, fence)
|
||||
} else if (command.action === "create") response = await client.put(command.path, command.fields, 30000, fence)
|
||||
else if (command.action === "update") response = await client.patch(`${command.path}/${encodeURIComponent(command.id!)}`, command.fields, 15000, fence)
|
||||
else response = await client.post(command.path, command.fields, command.action === "sign" ? 120000 : 60000, undefined, fence)
|
||||
else {
|
||||
// RouterOS signs and exports by native id only; the certificate is the one this run created and ACKed.
|
||||
const certificate = command.action === "sign" ? command.name : command.certificate
|
||||
const id = state.catalogs["/certificate"].find(row => row.name === certificate && ownedCertificateIds.has(row[".id"]))?.[".id"]
|
||||
if (!id) throw new McpError("STATE_CONFLICT", "Не подтверждён сертификат команды IPsec", 409)
|
||||
response = await client.post(command.path, { ".id": id, ...command.fields }, command.action === "sign" ? 120000 : 60000, undefined, fence)
|
||||
}
|
||||
confirmedWrites++
|
||||
} catch (error) {
|
||||
if (!dispatched && !completedCommands && error instanceof McpError) throw error
|
||||
|
||||
@@ -1303,21 +1303,11 @@ export class MikrotikClient {
|
||||
async signCertificate(params: {
|
||||
name: string
|
||||
ca?: string
|
||||
daysValid?: number
|
||||
}, timeoutMs = 120_000): Promise<unknown> {
|
||||
const body: Record<string, string> = { name: params.name }
|
||||
if (params.ca) body.ca = params.ca
|
||||
if (params.daysValid != null) body["days-valid"] = String(params.daysValid)
|
||||
try {
|
||||
return await this.postTolerant("/certificate/sign", body, timeoutMs)
|
||||
} catch (e) {
|
||||
// Некоторые версии REST принимают цель подписи только как .id.
|
||||
const certs = await this.getCertificates()
|
||||
const row = certs.find((c) => String(c.name ?? "") === params.name)
|
||||
const id = row?.[".id"]
|
||||
if (!id) throw e
|
||||
return await this.postTolerant("/certificate/sign", { ".id": id, ...body }, timeoutMs)
|
||||
}
|
||||
// RouterOS 7.24 signs by .id only and refuses `name` and `days-valid` (the template carries the validity).
|
||||
const id = (await this.getCertificates()).find((c) => String(c.name ?? "") === params.name)?.[".id"]
|
||||
if (!id) throw new Error(`Сертификат ${params.name} не найден для подписи`)
|
||||
return this.postTolerant("/certificate/sign", { ".id": String(id), ...(params.ca ? { ca: params.ca } : {}) }, timeoutMs)
|
||||
}
|
||||
|
||||
/** Экспорт сертификата в файл на роутере (pkcs12/pem); возвращает созданный файл. */
|
||||
@@ -1326,18 +1316,12 @@ export class MikrotikClient {
|
||||
type: "pkcs12" | "pem"
|
||||
passphrase?: string
|
||||
}, timeoutMs = 60_000): Promise<{ fileName: string; fileId: string; size: number }> {
|
||||
const body: Record<string, string> = { name: params.name, type: params.type }
|
||||
// RouterOS 7.24 addresses the certificate by .id only and refuses `name` here.
|
||||
const id = (await this.getCertificates()).find((c) => String(c.name ?? "") === params.name)?.[".id"]
|
||||
if (!id) throw new Error(`Сертификат ${params.name} не найден для экспорта`)
|
||||
const body: Record<string, string> = { ".id": String(id), type: params.type }
|
||||
if (params.passphrase?.trim()) body["export-passphrase"] = params.passphrase.trim()
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = await this.postTolerant("/certificate/export-certificate", body, timeoutMs)
|
||||
} catch (e) {
|
||||
const certs = await this.getCertificates()
|
||||
const id = certs.find((c) => String(c.name ?? "") === params.name)?.[".id"]
|
||||
if (!id) throw e
|
||||
raw = await this.postTolerant("/certificate/export-certificate", { ".id": id, ...body }, timeoutMs)
|
||||
}
|
||||
void raw
|
||||
await this.postTolerant("/certificate/export-certificate", body, timeoutMs)
|
||||
// RouterOS создаёт cert_export_<name>.p12 либо <name>.p12 — ищем по списку файлов.
|
||||
const ext = params.type === "pkcs12" ? "p12" : "crt"
|
||||
const wanted = [`${params.name}.${ext}`, `cert_export_${params.name}.${ext}`]
|
||||
|
||||
Reference in new issue
Block a user