Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5cc6128086 | ||
|
|
569b6be2b4 | ||
|
|
752256f12e |
@@ -1,6 +1,7 @@
|
||||
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
||||
import type { FastifyReply } from "fastify"
|
||||
import {
|
||||
IPSEC_MIN_PASSPHRASE,
|
||||
ipsecCertDeleteRequestSchema,
|
||||
ipsecCertExportByNameRequestSchema,
|
||||
ipsecCertExportRequestSchema,
|
||||
@@ -97,6 +98,22 @@ function errReply(reply: FastifyReply, e: unknown) {
|
||||
return reply.status(502).send({ error: `RouterOS: ${msg}` })
|
||||
}
|
||||
|
||||
/**
|
||||
* 400 по невалидному телу. Для короткого пароля .p12 — понятный текст вместо generic-сообщения:
|
||||
* RouterOS отклоняет `export-passphrase` короче 8 символов.
|
||||
*/
|
||||
function badBodyReply(reply: FastifyReply, error: z.ZodError) {
|
||||
const shortPassphrase = error.issues.some(
|
||||
(issue) => issue.path[0] === "passphrase" && issue.code === "too_small",
|
||||
)
|
||||
if (shortPassphrase) {
|
||||
return reply.status(400).send({
|
||||
error: `Пароль архива .p12 должен быть не короче ${IPSEC_MIN_PASSPHRASE} символов (требование RouterOS)`,
|
||||
})
|
||||
}
|
||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: error.flatten() })
|
||||
}
|
||||
|
||||
async function recordIpsec(
|
||||
server: NonNullable<Awaited<ReturnType<typeof getEnabledIpsecServerById>>>,
|
||||
source: ConfigRevisionSource,
|
||||
@@ -122,7 +139,7 @@ async function buildCertBundle(
|
||||
args: { userName: string; certName?: string; serverEndpoint: string; passphrase: string; dns?: string },
|
||||
): Promise<IpsecCertBundle> {
|
||||
const certName = args.certName?.trim() || clientCertName(args.userName)
|
||||
const { fileName, content } = await exportCertificateP12ByName(client, certName, args.passphrase)
|
||||
const { fileName, content, passphrase } = await exportCertificateP12ByName(client, certName, args.passphrase)
|
||||
const p12B64 = content.toString("base64")
|
||||
return {
|
||||
user: args.userName,
|
||||
@@ -130,7 +147,7 @@ async function buildCertBundle(
|
||||
filename: fileName,
|
||||
contentB64: p12B64,
|
||||
mime: "application/x-pkcs12",
|
||||
passphrase: args.passphrase,
|
||||
passphrase,
|
||||
sswanFilename: `${certName}.sswan`,
|
||||
sswanContent: buildSswanConfig({
|
||||
name: `IKEv2 ${args.serverEndpoint}`,
|
||||
@@ -142,7 +159,7 @@ async function buildCertBundle(
|
||||
userName: args.userName,
|
||||
serverEndpoint: args.serverEndpoint,
|
||||
p12Filename: fileName,
|
||||
passphrase: args.passphrase,
|
||||
passphrase,
|
||||
dns: args.dns,
|
||||
}),
|
||||
}
|
||||
@@ -243,7 +260,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
app.post("/ipsec/users", async (req, reply) => {
|
||||
const parsed = ipsecUserCreateRequestSchema.safeParse(req.body ?? {})
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
||||
return badBodyReply(reply, parsed.error)
|
||||
}
|
||||
const body = parsed.data
|
||||
const server = await getEnabledIpsecServerById(body.serverId)
|
||||
@@ -608,7 +625,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const { serverId, rosId } = req.params as { serverId: string; rosId: string }
|
||||
const parsed = ipsecCertExportRequestSchema.safeParse({ ...(req.body as object), serverId, clientId: rosId })
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
||||
return badBodyReply(reply, parsed.error)
|
||||
}
|
||||
const body = parsed.data
|
||||
const server = await getEnabledIpsecServerById(serverIdParam(serverId))
|
||||
@@ -629,7 +646,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const sharedMc = state.modeConfigs.find((m) => (m.name ?? "").trim() === IPSEC_COMMON_NAME)
|
||||
const dns = sharedMc?.["static-dns"]?.trim() || undefined
|
||||
// export работает по имени сертификата (certName), не по userName
|
||||
const { fileName, content } = await client.exportCertificatePkcs12({
|
||||
const { fileName, content, passphrase } = await client.exportCertificatePkcs12({
|
||||
name: certName,
|
||||
passphrase: body.passphrase,
|
||||
})
|
||||
@@ -640,7 +657,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
filename: fileName,
|
||||
contentB64: p12B64,
|
||||
mime: "application/x-pkcs12",
|
||||
passphrase: body.passphrase,
|
||||
passphrase,
|
||||
sswanFilename: `${certName}.sswan`,
|
||||
sswanContent: buildSswanConfig({
|
||||
name: `IKEv2 ${serverEndpoint}`,
|
||||
@@ -652,7 +669,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
userName,
|
||||
serverEndpoint,
|
||||
p12Filename: fileName,
|
||||
passphrase: body.passphrase,
|
||||
passphrase,
|
||||
dns,
|
||||
}),
|
||||
}
|
||||
@@ -667,7 +684,7 @@ const ipsecRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const { serverId } = req.params as { serverId: string }
|
||||
const parsed = ipsecCertExportByNameRequestSchema.safeParse(req.body ?? {})
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
||||
return badBodyReply(reply, parsed.error)
|
||||
}
|
||||
const { name, passphrase } = parsed.data
|
||||
const server = await getEnabledIpsecServerById(serverIdParam(serverId))
|
||||
|
||||
@@ -112,12 +112,12 @@ export async function exportCertificateP12ByName(
|
||||
client: MikrotikClient,
|
||||
certName: string,
|
||||
passphrase: string,
|
||||
): Promise<{ fileName: string; content: Buffer; certName: string }> {
|
||||
): Promise<{ fileName: string; content: Buffer; certName: string; passphrase: string }> {
|
||||
const name = certName.trim()
|
||||
const cert = await findCertificate(client, name)
|
||||
if (!cert) throw new Error(`Сертификат ${name} не найден на роутере`)
|
||||
const { fileName, content } = await client.exportCertificatePkcs12({ name, passphrase })
|
||||
return { fileName, content, certName: name }
|
||||
const { fileName, content, passphrase: effective } = await client.exportCertificatePkcs12({ name, passphrase })
|
||||
return { fileName, content, certName: name, passphrase: effective }
|
||||
}
|
||||
|
||||
/** Экспорт клиентского .p12 (сертификат + ключ; CA в цепочке) с роутера. */
|
||||
@@ -125,6 +125,6 @@ export async function exportClientP12(
|
||||
client: MikrotikClient,
|
||||
userName: string,
|
||||
passphrase: string,
|
||||
): Promise<{ fileName: string; content: Buffer; certName: string }> {
|
||||
): Promise<{ fileName: string; content: Buffer; certName: string; passphrase: string }> {
|
||||
return exportCertificateP12ByName(client, clientCertName(userName), passphrase)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import http from "node:http"
|
||||
import https from "node:https"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import type { Server } from "../db/schema.js"
|
||||
import { parseRosDataSizeBytes } from "./ros-metric-parse.js"
|
||||
import type {
|
||||
@@ -422,6 +423,31 @@ function unknownParameterName(error: MikrotikError): string | undefined {
|
||||
return match?.[1]
|
||||
}
|
||||
|
||||
/**
|
||||
* RouterOS отклоняет `export-passphrase` короче 8 символов:
|
||||
* `Failure: If used, passphrase must be at least 8 chars long!`.
|
||||
* Та же ошибка приходит, если политика `sensitive` не даёт применить sensitive-параметр.
|
||||
*/
|
||||
export function isPassphraseTooShortError(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof MikrotikError &&
|
||||
error.statusCode === 400 &&
|
||||
/passphrase/i.test(error.body) &&
|
||||
/at least\s*8/i.test(error.body)
|
||||
)
|
||||
}
|
||||
|
||||
/** Пароль .p12, который RouterOS примет гарантированно (≥8 символов). */
|
||||
function generateExportPassphrase(): string {
|
||||
return randomBytes(12).toString("base64url")
|
||||
}
|
||||
|
||||
const EXPORT_PASSPHRASE_HINT =
|
||||
"RouterOS отклонил пароль .p12. Экспорт приватного ключа (export-passphrase — sensitive-параметр) " +
|
||||
"разрешён только пользователю, у которого в политике группы есть «sensitive». " +
|
||||
"Проверьте: /user print → группа API-пользователя → /user group print; добавьте sensitive в policy группы " +
|
||||
"(в группе full она уже есть)."
|
||||
|
||||
export class MikrotikClient {
|
||||
constructor(private readonly params: MikrotikConnectParams) {}
|
||||
|
||||
@@ -774,10 +800,25 @@ export class MikrotikClient {
|
||||
}
|
||||
|
||||
/** Скачивание .p12 (сертификат + ключ + цепочка) как бинарный Buffer. */
|
||||
async exportCertificatePkcs12(params: { name: string; passphrase?: string }): Promise<{ fileName: string; content: Buffer }> {
|
||||
const fileName = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase: params.passphrase })
|
||||
async exportCertificatePkcs12(params: { name: string; passphrase?: string }): Promise<{ fileName: string; content: Buffer; passphrase: string }> {
|
||||
let passphrase = params.passphrase?.trim() || generateExportPassphrase()
|
||||
let fileName: string
|
||||
try {
|
||||
fileName = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase })
|
||||
} catch (error) {
|
||||
if (!isPassphraseTooShortError(error)) throw error
|
||||
// RouterOS мог отклонить пароль пользователя — повторяем со сгенерированным и отдаём его в бандл.
|
||||
const forced = generateExportPassphrase()
|
||||
try {
|
||||
fileName = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase: forced })
|
||||
passphrase = forced
|
||||
} catch (retryError) {
|
||||
if (isPassphraseTooShortError(retryError)) throw new Error(EXPORT_PASSPHRASE_HINT)
|
||||
throw retryError
|
||||
}
|
||||
}
|
||||
const content = await this.downloadFile(fileName)
|
||||
return { fileName, content }
|
||||
return { fileName, content, passphrase }
|
||||
}
|
||||
|
||||
async removeCertificate(nameOrId: string, timeoutMs = 30_000): Promise<void> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import type { IpsecCertBundle } from "@mmapp/contracts/ipsec"
|
||||
import { IPSEC_MIN_PASSPHRASE, type IpsecCertBundle } from "@mmapp/contracts/ipsec"
|
||||
import { FormField, SectionTitle } from "@/components/form-kit"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
@@ -33,7 +33,8 @@ function downloadB64(filename: string, b64: string, mime: string) {
|
||||
}
|
||||
|
||||
function randomPassphrase(): string {
|
||||
const bytes = new Uint8Array(9)
|
||||
// RouterOS требует ≥ IPSEC_MIN_PASSPHRASE символов
|
||||
const bytes = new Uint8Array(IPSEC_MIN_PASSPHRASE + 1)
|
||||
crypto.getRandomValues(bytes)
|
||||
let s = ""
|
||||
for (const b of bytes) s += "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"[b % 56]
|
||||
@@ -62,7 +63,10 @@ function IpsecCertSheet({
|
||||
queueMicrotask(() => setPassphrase(initial))
|
||||
}, [open, bundle])
|
||||
|
||||
const canDownload = useMemo(() => Boolean(bundle && passphrase.trim().length >= 4), [bundle, passphrase])
|
||||
const canDownload = useMemo(
|
||||
() => Boolean(bundle && passphrase.trim().length >= IPSEC_MIN_PASSPHRASE),
|
||||
[bundle, passphrase],
|
||||
)
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
@@ -83,7 +87,15 @@ function IpsecCertSheet({
|
||||
<>
|
||||
<div className="flex flex-col gap-4">
|
||||
<SectionTitle>Пароль архива .p12</SectionTitle>
|
||||
<FormField label="Passphrase" required hint="Нужна при импорте .p12 на устройстве">
|
||||
<FormField
|
||||
label="Passphrase"
|
||||
required
|
||||
hint={
|
||||
passphrase.trim().length > 0 && passphrase.trim().length < IPSEC_MIN_PASSPHRASE
|
||||
? `Минимум ${IPSEC_MIN_PASSPHRASE} символов — требование RouterOS`
|
||||
: `Нужна при импорте .p12 на устройстве (минимум ${IPSEC_MIN_PASSPHRASE} символов)`
|
||||
}
|
||||
>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
className="font-mono"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import type { IpsecClientDto } from "@mmapp/contracts/ipsec"
|
||||
import { IPSEC_MIN_PASSPHRASE, type IpsecClientDto } from "@mmapp/contracts/ipsec"
|
||||
import { FormField, FormToggle, SectionTitle } from "@/components/form-kit"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
@@ -91,6 +91,9 @@ function IpsecUserSheet({
|
||||
if (!form.name.trim()) return false
|
||||
if (!editing && form.authMethod === "pre-shared-key" && form.psk.trim().length < 8) return false
|
||||
if (form.useStaticIp && form.staticIp.trim() && !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(form.staticIp.trim())) return false
|
||||
// RouterOS отклоняет export-passphrase короче 8 символов
|
||||
const passphrase = form.passphrase.trim()
|
||||
if (!editing && passphrase.length > 0 && passphrase.length < IPSEC_MIN_PASSPHRASE) return false
|
||||
return true
|
||||
}, [form, editing])
|
||||
|
||||
@@ -201,7 +204,14 @@ function IpsecUserSheet({
|
||||
</>
|
||||
) : (
|
||||
!editing ? (
|
||||
<FormField label="Пароль архива .p12" hint="Пусто — сгенерируем автоматически">
|
||||
<FormField
|
||||
label="Пароль архива .p12"
|
||||
hint={
|
||||
form.passphrase.trim().length > 0 && form.passphrase.trim().length < IPSEC_MIN_PASSPHRASE
|
||||
? `Минимум ${IPSEC_MIN_PASSPHRASE} символов — требование RouterOS`
|
||||
: `Пусто — сгенерируем автоматически (минимум ${IPSEC_MIN_PASSPHRASE} символов)`
|
||||
}
|
||||
>
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="например MySecret123"
|
||||
|
||||
@@ -2,6 +2,12 @@ import { z } from "zod"
|
||||
|
||||
export const ipsecAuthMethodSchema = z.enum(["certificate", "pre-shared-key"])
|
||||
|
||||
/**
|
||||
* Минимальная длина пароля .p12. Ограничение RouterOS REST:
|
||||
* `Failure: If used, passphrase must be at least 8 chars long!` (см. /certificate/export-certificate).
|
||||
*/
|
||||
export const IPSEC_MIN_PASSPHRASE = 8
|
||||
|
||||
/** Клиент IKEv2 — /ip/ipsec/identity (+ опциональный персональный mode-config). */
|
||||
export const ipsecClientDtoSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
@@ -166,8 +172,8 @@ export const ipsecUserCreateRequestSchema = z.object({
|
||||
remoteId: z.string().optional(),
|
||||
/** Конкретный IP клиента; без — выдаётся из пула. */
|
||||
staticIp: z.string().optional(),
|
||||
/** Пароль на экспортируемый .p12. */
|
||||
passphrase: z.string().min(4).optional(),
|
||||
/** Пароль на экспортируемый .p12 (RouterOS требует ≥ IPSEC_MIN_PASSPHRASE). */
|
||||
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE).optional(),
|
||||
daysValid: z.number().int().positive().optional(),
|
||||
})
|
||||
|
||||
@@ -183,13 +189,13 @@ export const ipsecUserPatchSchema = z.object({
|
||||
export const ipsecCertExportRequestSchema = z.object({
|
||||
serverId: z.union([z.string(), z.number()]),
|
||||
clientId: z.string().min(1),
|
||||
passphrase: z.string().min(4),
|
||||
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE),
|
||||
})
|
||||
|
||||
/** Экспорт .p12 существующего клиентского сертификата по имени (client1/anakondra и т.п.). */
|
||||
export const ipsecCertExportByNameRequestSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
passphrase: z.string().min(4),
|
||||
passphrase: z.string().min(IPSEC_MIN_PASSPHRASE),
|
||||
})
|
||||
|
||||
/** Бандл для авторизации клиента: .p12 (+ strongSwan .sswan + инструкция). */
|
||||
|
||||
Reference in New Issue
Block a user