Files
canina/backend/src/admin/ssl.service.ts
T
devops ddbf1ca026
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation.
- Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings.
- Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors.
- Fixed unmount lifecycle guards, promise error handling, and component edge cases.
2026-10-13 16:01:00 +00:00

353 lines
10 KiB
TypeScript

import { Injectable, Logger, BadRequestException } from "@nestjs/common";
import * as fs from "fs";
import * as path from "path";
import * as crypto from "crypto";
import * as tls from "tls";
import * as dns from "dns/promises";
import { BlockList, isIP } from "net";
function isPublicAddress(address: string): boolean {
const blocked = new BlockList();
for (const [network, prefix] of [
["0.0.0.0", 8],
["10.0.0.0", 8],
["100.64.0.0", 10],
["127.0.0.0", 8],
["169.254.0.0", 16],
["172.16.0.0", 12],
["192.0.0.0", 24],
["192.0.2.0", 24],
["192.168.0.0", 16],
["198.18.0.0", 15],
["198.51.100.0", 24],
["203.0.113.0", 24],
["224.0.0.0", 3],
] as const)
blocked.addSubnet(network, prefix, "ipv4");
if (isIP(address) === 4) return !blocked.check(address, "ipv4");
if (isIP(address) !== 6) return false;
const global = new BlockList();
global.addSubnet("2000::", 3, "ipv6");
for (const [network, prefix] of [
["2001::", 23],
["2001:db8::", 32],
["2002::", 16],
["3fff::", 20],
] as const)
blocked.addSubnet(network, prefix, "ipv6");
return global.check(address, "ipv6") && !blocked.check(address, "ipv6");
}
export interface SslCertInfo {
exists: boolean;
subject?: string;
issuer?: string;
validFrom?: string;
validTo?: string;
validFromShamsi?: string;
validToShamsi?: string;
daysRemaining?: number;
isExpired?: boolean;
domains?: string[];
fingerprint?: string;
serialNumber?: string;
}
@Injectable()
export class SslService {
private readonly logger = new Logger(SslService.name);
private readonly certsDir =
process.env.SSL_CERTS_DIR || path.join(process.cwd(), "ssl_certs");
constructor() {
if (!fs.existsSync(this.certsDir)) {
try {
fs.mkdirSync(this.certsDir, { recursive: true });
} catch (err) {
this.logger.warn(
`Could not create ssl_certs dir at ${this.certsDir}: ${err}`,
);
}
}
}
private getCertPath(): string {
return path.join(this.certsDir, "fullchain.pem");
}
private getKeyPath(): string {
return path.join(this.certsDir, "privateKey.pem");
}
private toShamsi(date: Date): string {
try {
return new Intl.DateTimeFormat("fa-IR", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(date);
} catch {
return date.toLocaleDateString("fa-IR");
}
}
public getStatus(): SslCertInfo {
const certPath = this.getCertPath();
if (!fs.existsSync(certPath)) {
return { exists: false };
}
try {
const certPem = fs.readFileSync(certPath, "utf8");
const cert = new crypto.X509Certificate(certPem);
const validFromDate = new Date(cert.validFrom);
const validToDate = new Date(cert.validTo);
const now = new Date();
const diffMs = validToDate.getTime() - now.getTime();
const daysRemaining = Math.max(
0,
Math.floor(diffMs / (1000 * 60 * 60 * 24)),
);
const isExpired = diffMs <= 0;
// Extract SAN domains
let domains: string[] = [];
if (cert.subjectAltName) {
domains = cert.subjectAltName
.split(",")
.map((s) => s.trim().replace(/^DNS:/, ""))
.filter(Boolean);
} else if (cert.subject) {
domains = [cert.subject];
}
return {
exists: true,
subject: cert.subject,
issuer: cert.issuer,
validFrom: validFromDate.toISOString(),
validTo: validToDate.toISOString(),
validFromShamsi: this.toShamsi(validFromDate),
validToShamsi: this.toShamsi(validToDate),
daysRemaining,
isExpired,
domains,
fingerprint: cert.fingerprint256 || cert.fingerprint,
serialNumber: cert.serialNumber,
};
} catch (error) {
this.logger.error("Failed to parse SSL certificate", error);
return { exists: false };
}
}
public updateCertificates(certContent: string, keyContent: string) {
const cleanCert = certContent.trim();
const cleanKey = keyContent.trim();
if (!cleanCert || !cleanKey) {
throw new BadRequestException(
"محتوای گواهی (Certificate) و کلید خصوصی (Private Key) الزامی است.",
);
}
// 1. Validate Certificate format
let cert: crypto.X509Certificate;
try {
cert = new crypto.X509Certificate(cleanCert);
} catch (err: unknown) {
const errObj = err as Error;
throw new BadRequestException(
`فرمت گواهی نامعتبر است: ${errObj.message}`,
);
}
// 2. Validate Private Key format
try {
const key = crypto.createPrivateKey(cleanKey);
if (!cert.checkPrivateKey(key)) {
throw new Error("Certificate and private key do not match");
}
} catch (err: unknown) {
const errObj = err as Error;
throw new BadRequestException(
`فرمت کلید خصوصی نامعتبر است: ${errObj.message}`,
);
}
// 3. Ensure certs directory exists
if (!fs.existsSync(this.certsDir)) {
fs.mkdirSync(this.certsDir, { recursive: true });
}
// Stage both files before changing either live pathname. Synchronous execution
// prevents interleaved updates in this process; failed replacement restores both.
const certPath = this.getCertPath();
const keyPath = this.getKeyPath();
const suffix = `.${crypto.randomUUID()}.tmp`;
const stagedCert = certPath + suffix;
const stagedKey = keyPath + suffix;
const hadCert = fs.existsSync(certPath);
const hadKey = fs.existsSync(keyPath);
let certReplaced = false;
let keyReplaced = false;
try {
fs.writeFileSync(stagedCert, cleanCert, {
encoding: "utf8",
mode: 0o600,
flag: "wx",
});
fs.writeFileSync(stagedKey, cleanKey, {
encoding: "utf8",
mode: 0o600,
flag: "wx",
});
if (hadCert) fs.copyFileSync(certPath, `${certPath}.bak`);
if (hadKey) fs.copyFileSync(keyPath, `${keyPath}.bak`);
fs.renameSync(stagedCert, certPath);
certReplaced = true;
fs.renameSync(stagedKey, keyPath);
keyReplaced = true;
} catch (error) {
if (certReplaced) {
if (hadCert) fs.renameSync(`${certPath}.bak`, certPath);
else fs.unlinkSync(certPath);
}
if (keyReplaced) {
if (hadKey) fs.renameSync(`${keyPath}.bak`, keyPath);
else fs.unlinkSync(keyPath);
}
throw error;
} finally {
for (const file of [stagedCert, stagedKey]) {
try {
fs.unlinkSync(file);
} catch {
/* Already renamed or not created. */
}
}
}
this.logger.log(
`SSL Certificates updated successfully. Subject: ${cert.subject}`,
);
return {
success: true,
message: "گواهی SSL با موفقیت به‌روزرسانی و در سرور ذخیره شد.",
status: this.getStatus(),
};
}
public async testOnlineDomainSsl(
domain: string,
): Promise<Record<string, unknown>> {
const cleanDomainForDns = domain
.replace(/^https?:\/\//, "")
.replace(/\/.*$/, "")
.trim()
.toLowerCase();
let addresses: { address: string; family: number }[];
try {
if (
!/^(?!-)[a-z0-9-]{1,63}(?<!-)(\.[a-z0-9-]{1,63})*\.[a-z]{2,}$/.test(
cleanDomainForDns,
) ||
/\.(local|internal)$/.test(cleanDomainForDns)
) {
return { onlineCheck: false, error: "فرمت نام دامنه نامعتبر است" };
}
addresses = await dns.lookup(cleanDomainForDns, { all: true });
if (
!addresses.length ||
addresses.some(({ address }) => !isPublicAddress(address))
)
return {
onlineCheck: false,
error: "DNS target is not a public address",
};
} catch {
return { onlineCheck: false, error: "DNS lookup failed" };
}
return new Promise((resolve) => {
const cleanDomain = domain
.replace(/^https?:\/\//, "")
.replace(/\/.*$/, "")
.trim()
.toLowerCase();
// SEC-009: Strict domain validation preventing SSRF
const DOMAIN_REGEX =
/^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(\.[a-zA-Z0-9-]{1,63})*\.[a-zA-Z]{2,}$/;
const IP_REGEX =
/^(?:\d{1,3}\.){3}\d{1,3}$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
if (
!cleanDomain ||
!DOMAIN_REGEX.test(cleanDomain) ||
IP_REGEX.test(cleanDomain) ||
cleanDomain === "localhost" ||
cleanDomain.endsWith(".local") ||
cleanDomain.endsWith(".internal")
) {
return resolve({
onlineCheck: false,
error:
"فرمت نام دامنه نامعتبر است یا آدرس‌های IP و داخلی مجاز نیستند.",
});
}
const socket = tls.connect(
{
// Pin the validated numeric address: TLS must not resolve DNS again.
host: addresses[0].address,
port: 443,
servername: cleanDomain,
rejectUnauthorized: false,
timeout: 5000,
},
() => {
const peerCert = socket.getPeerCertificate(true);
socket.end();
if (!peerCert || Object.keys(peerCert).length === 0) {
return resolve({
onlineCheck: false,
message: "گواهی SSL بر روی پورت ۴۴۳ این دامنه یافت نشد.",
});
}
const validTo = new Date(peerCert.valid_to);
resolve({
onlineCheck: true,
domain: cleanDomain,
authorized: socket.authorized,
validTo: validTo.toISOString(),
validToShamsi: this.toShamsi(validTo),
issuer: peerCert.issuer?.O || peerCert.issuer?.CN,
subject: peerCert.subject?.CN,
});
},
);
socket.on("error", (err: Error) => {
resolve({
onlineCheck: false,
error: err.message,
});
});
socket.on("timeout", () => {
socket.destroy();
resolve({
onlineCheck: false,
error: "مهلت اتصال (Timeout) به پایان رسید.",
});
});
});
}
}