import * as plugins from './plugins.js'; import * as path from 'path'; import * as crypto from 'crypto'; import * as nodeForge from 'node-forge'; import { NotImplementedError } from './skr.errors.js'; export interface ISigningOptions { certificatePem?: string; privateKeyPem?: string; privateKeyPassphrase?: string; timestampServerUrl?: string; includeTimestamp?: boolean; } export interface ISignatureResult { signature: string; signatureFormat: 'CAdES-B' | 'CAdES-T' | 'CAdES-LT'; signingTime: string; certificateChain?: string[]; timestampToken?: string; timestampTime?: string; } export interface ITimestampResponse { token: string; time: string; serverUrl: string; hashAlgorithm: string; } export class SecurityManager { private options: ISigningOptions; private logger: plugins.smartlog.ConsoleLog; constructor(options: ISigningOptions = {}) { this.options = { timestampServerUrl: options.timestampServerUrl || 'http://timestamp.digicert.com', includeTimestamp: options.includeTimestamp !== false, ...options }; this.logger = new plugins.smartlog.ConsoleLog(); } /** * Creates a CAdES-B (Basic) signature for data */ public async createCadesSignature( data: Buffer | string, certificatePem?: string, privateKeyPem?: string ): Promise { const cert = certificatePem || this.options.certificatePem; const key = privateKeyPem || this.options.privateKeyPem; if (!cert || !key) { throw new Error('Certificate and private key are required for signing'); } try { // Parse certificate and key const certificate = nodeForge.pki.certificateFromPem(cert); const privateKey = this.options.privateKeyPassphrase ? nodeForge.pki.decryptRsaPrivateKey(key, this.options.privateKeyPassphrase) : nodeForge.pki.privateKeyFromPem(key); // Create PKCS#7 signed data (CMS) const p7 = nodeForge.pkcs7.createSignedData(); // Add content if (typeof data === 'string') { p7.content = nodeForge.util.createBuffer(data, 'utf8'); } else { p7.content = nodeForge.util.createBuffer(data.toString('latin1')); } // Add certificate p7.addCertificate(certificate); // Add signer p7.addSigner({ key: privateKey, certificate: certificate, digestAlgorithm: nodeForge.pki.oids.sha256, authenticatedAttributes: [ { type: nodeForge.pki.oids.contentType, value: nodeForge.pki.oids.data }, { type: nodeForge.pki.oids.messageDigest }, { type: nodeForge.pki.oids.signingTime, value: new Date().toISOString() } ] }); // Sign the data p7.sign({ detached: true }); // Convert to PEM const pem = nodeForge.pkcs7.messageToPem(p7); // Extract base64 signature const signature = pem .replace(/-----BEGIN PKCS7-----/, '') .replace(/-----END PKCS7-----/, '') .replace(/\r?\n/g, ''); const result: ISignatureResult = { signature: signature, signatureFormat: 'CAdES-B', signingTime: new Date().toISOString(), certificateChain: [cert] }; // Add timestamp if requested — no silent downgrade: if a timestamp was // asked for and cannot be produced, the signing call fails loudly. if (this.options.includeTimestamp && this.options.timestampServerUrl) { const timestampResponse = await this.requestTimestamp(signature); result.timestampToken = timestampResponse.token; result.timestampTime = timestampResponse.time; result.signatureFormat = 'CAdES-T'; } return result; } catch (error) { throw new Error(`Failed to create CAdES signature: ${error}`); } } /** * RFC 3161 timestamping — NOT implemented. * * The previous implementation posted a JSON blob pretending to be an ASN.1 * TimeStampReq — every real TSA rejects that, and failures were silently * swallowed (fake CAdES-T). Until a real RFC 3161 client (DER-encoded TSQ) * exists, this fails loudly; use CAdES-B (includeTimestamp: false). */ public async requestTimestamp(dataHash: string | Buffer): Promise { void dataHash; throw new NotImplementedError( 'RFC 3161 timestamping is not implemented — CAdES-T/LT unavailable, use CAdES-B (includeTimestamp: false)', ); } /** * Verifies a CAdES signature */ public async verifyCadesSignature( data: Buffer | string, signature: string, certificatePem?: string ): Promise { try { // Add PEM headers if not present let pemSignature = signature; if (!signature.includes('BEGIN PKCS7')) { pemSignature = `-----BEGIN PKCS7-----\n${signature}\n-----END PKCS7-----`; } // Parse the PKCS#7 message const p7 = nodeForge.pkcs7.messageFromPem(pemSignature); // Prepare content for verification let content: nodeForge.util.ByteStringBuffer; if (typeof data === 'string') { content = nodeForge.util.createBuffer(data, 'utf8'); } else { content = nodeForge.util.createBuffer(data.toString('latin1')); } // Verify the signature const verified = (p7 as any).verify({ content: content, detached: true }); return verified; } catch (error) { this.logger.log('error', `Signature verification failed: ${error}`); return false; } } /** * Generates a self-signed certificate for testing */ public async generateSelfSignedCertificate( commonName: string = 'SKR Export System', validDays: number = 365 ): Promise<{ certificate: string; privateKey: string }> { const keys = nodeForge.pki.rsa.generateKeyPair(2048); const cert = nodeForge.pki.createCertificate(); cert.publicKey = keys.publicKey; cert.serialNumber = '01'; cert.validity.notBefore = new Date(); cert.validity.notAfter = new Date(); cert.validity.notAfter.setDate(cert.validity.notAfter.getDate() + validDays); const attrs = [ { name: 'commonName', value: commonName }, { name: 'countryName', value: 'DE' }, { name: 'organizationName', value: 'SKR Export System' }, { shortName: 'OU', value: 'Accounting' } ]; cert.setSubject(attrs); cert.setIssuer(attrs); cert.setExtensions([ { name: 'basicConstraints', cA: true }, { name: 'keyUsage', keyCertSign: true, digitalSignature: true, nonRepudiation: true, keyEncipherment: true, dataEncipherment: true }, { name: 'extKeyUsage', serverAuth: true, clientAuth: true, codeSigning: true, emailProtection: true, timeStamping: true }, { name: 'nsCertType', client: true, server: true, email: true, objsign: true, sslCA: true, emailCA: true, objCA: true }, { name: 'subjectAltName', altNames: [ { type: 2, value: commonName } ] } ]); // Self-sign certificate cert.sign(keys.privateKey, nodeForge.md.sha256.create()); // Convert to PEM const certificatePem = nodeForge.pki.certificateToPem(cert); const privateKeyPem = nodeForge.pki.privateKeyToPem(keys.privateKey); return { certificate: certificatePem, privateKey: privateKeyPem }; } /** * Creates a detached signature file */ public async createDetachedSignature( dataPath: string, outputPath: string ): Promise { const data = await plugins.smartfile.fs.toBuffer(dataPath); const signature = await this.createCadesSignature(data); const signatureData = { signature: signature.signature, format: signature.signatureFormat, signingTime: signature.signingTime, timestamp: signature.timestampToken, timestampTime: signature.timestampTime, algorithm: 'SHA256withRSA', signedFile: path.basename(dataPath) }; await plugins.smartfile.memory.toFs( JSON.stringify(signatureData, null, 2), outputPath ); } /** * Verifies a detached signature file */ public async verifyDetachedSignature( dataPath: string, signaturePath: string ): Promise { try { const data = await plugins.smartfile.fs.toBuffer(dataPath); const signatureJson = await plugins.smartfile.fs.toStringSync(signaturePath); const signatureData = JSON.parse(signatureJson); return await this.verifyCadesSignature(data, signatureData.signature); } catch (error) { this.logger.log('error', `Failed to verify detached signature: ${error}`); return false; } } /** * Adds Long-Term Validation (LTV) information */ public async addLtvInformation( signature: ISignatureResult, ocspResponse?: Buffer, crlData?: Buffer ): Promise { // Add OCSP response and CRL data for long-term validation const ltv = { ...signature, signatureFormat: 'CAdES-LT' as const, ocsp: ocspResponse?.toString('base64'), crl: crlData?.toString('base64'), ltvTime: new Date().toISOString() }; return ltv; } }