UNPKG

@citrineos/util

Version:

The OCPP util module which supplies helpful utilities like cache and queue connectors, etc.

291 lines 15.2 kB
"use strict"; // Copyright Contributors to the CitrineOS Project // // SPDX-License-Identifier: Apache 2.0 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CertificateAuthorityService = void 0; const base_1 = require("@citrineos/base"); const hubject_1 = require("./client/hubject"); const acme_1 = require("./client/acme"); const tslog_1 = require("tslog"); const jsrsasign_1 = __importStar(require("jsrsasign")); var OCSPRequest = jsrsasign_1.default.KJUR.asn1.ocsp.OCSPRequest; var Request = jsrsasign_1.default.KJUR.asn1.ocsp.Request; const moment_1 = __importDefault(require("moment")); const CertificateUtil_1 = require("./CertificateUtil"); const pkijs = __importStar(require("pkijs")); const webcrypto_1 = require("@peculiar/webcrypto"); const cryptoEngine = new pkijs.CryptoEngine({ crypto: new webcrypto_1.Crypto(), }); pkijs.setEngine('crypto', cryptoEngine); class CertificateAuthorityService { constructor(config, logger, chargingStationClient, v2gClient) { this._logger = logger ? logger.getSubLogger({ name: this.constructor.name }) : new tslog_1.Logger({ name: this.constructor.name }); this._chargingStationClient = chargingStationClient || this._instantiateChargingStationClient(config, this._logger); this._v2gClient = v2gClient || this._instantiateV2GClient(config); } /** * Retrieves the certificate chain for V2G- and Charging Station certificates. * * @param {string} csrString - The Certificate Signing Request string. * @param {string} stationId - The station identifier. * @param {CertificateSigningUseEnumType} [certificateType] - The type of certificate to retrieve. * @return {Promise<string>} The certificate chain without the root certificate. */ getCertificateChain(csrString, stationId, certificateType) { return __awaiter(this, void 0, void 0, function* () { this._logger.info(`Getting certificate chain for certificateType: ${certificateType} and stationId: ${stationId}`); switch (certificateType) { case base_1.OCPP2_0_1.CertificateSigningUseEnumType.V2GCertificate: { const signedCert = yield this._v2gClient.getSignedCertificate((0, CertificateUtil_1.extractEncodedContentFromCSR)(csrString)); const caCerts = yield this._v2gClient.getCACertificates(); return this._createCertificateChainWithoutRootCA(signedCert, caCerts); } case base_1.OCPP2_0_1.CertificateSigningUseEnumType.ChargingStationCertificate: { return yield this._chargingStationClient.getCertificateChain(csrString); } default: { throw new Error(`Unsupported certificate type: ${certificateType}`); } } }); } signedSubCaCertificateByExternalCA(csrString) { return __awaiter(this, void 0, void 0, function* () { return yield this._chargingStationClient.signCertificateByExternalCA(csrString); }); } getSignedContractData(iso15118SchemaVersion, exiRequest) { return __awaiter(this, void 0, void 0, function* () { return yield this._v2gClient.getSignedContractData(iso15118SchemaVersion, exiRequest); }); } getRootCACertificateFromExternalCA(certificateType) { return __awaiter(this, void 0, void 0, function* () { switch (certificateType) { case base_1.OCPP2_0_1.InstallCertificateUseEnumType.V2GRootCertificate: { const caCerts = yield this._v2gClient.getCACertificates(); const rootCACert = (0, CertificateUtil_1.extractCertificateArrayFromEncodedString)(caCerts).pop(); if (rootCACert) { return (0, CertificateUtil_1.createPemBlock)('CERTIFICATE', Buffer.from(rootCACert.toSchema().toBER(false)).toString('base64')); } else { throw new Error(`V2GRootCertificate not found from ${caCerts}`); } } case base_1.OCPP2_0_1.InstallCertificateUseEnumType.CSMSRootCertificate: return yield this._chargingStationClient.getRootCACertificate(); default: throw new Error(`Certificate type: ${certificateType} not implemented.`); } }); } updateSecurityCertChainKeyMap(serverId, certificateChain, privateKey) { this._chargingStationClient.updateCertificateChainKeyMap(serverId, certificateChain, privateKey); } /* * Validate the certificate chain using real time OCSP check. * * @param certificateChainPem - certificate chain pem * @return AuthorizeCertificateStatusEnumType */ validateCertificateChainPem(certificateChainPem) { return __awaiter(this, void 0, void 0, function* () { var _a; const certificatePems = (0, CertificateUtil_1.parseCertificateChainPem)(certificateChainPem); this._logger.debug(`Found ${certificatePems.length} certificates in chain.`); if (certificatePems.length < 1) { return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.NoCertificateAvailable; } try { // Find the root certificate of the certificate chain const rootCerts = yield this._v2gClient.getRootCertificates(); const lastCertInChain = new jsrsasign_1.X509(); lastCertInChain.readCertPEM(certificatePems[certificatePems.length - 1]); let rootCertPem; for (const rootCert of rootCerts) { const root = new jsrsasign_1.X509(); root.readCertPEM(rootCert); if (root.getSubjectString() === lastCertInChain.getIssuerString() && root.getExtSubjectKeyIdentifier().kid.hex === lastCertInChain.getExtAuthorityKeyIdentifier().kid.hex) { rootCertPem = rootCert; break; } } if (!rootCertPem) { this._logger.error(`Cannot find root certificate for certificate ${lastCertInChain}`); return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.NoCertificateAvailable; } else { certificatePems.push(rootCertPem); } // OCSP validation for each certificate for (let i = 0; i < certificatePems.length - 1; i++) { const subjectCert = new jsrsasign_1.X509(); subjectCert.readCertPEM(certificatePems[i]); this._logger.debug(`Subject Certificate: ${subjectCert.getInfo()}`); const notAfter = (0, moment_1.default)(subjectCert.getNotAfter(), CertificateUtil_1.dateTimeFormat); if (notAfter.isBefore((0, moment_1.default)())) { return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.CertificateExpired; } const ocspUrls = (_a = subjectCert.getExtAIAInfo()) === null || _a === void 0 ? void 0 : _a.ocsp; if (ocspUrls && ocspUrls.length > 0) { const ocspRequest = new OCSPRequest({ reqList: [ { issuerCert: certificatePems[i + 1], subjectCert: certificatePems[i], }, ], }); this._logger.debug(`OCSP response URL: ${ocspUrls[0]}`); const ocspResponse = jsrsasign_1.KJUR.asn1.ocsp.OCSPUtil.getOCSPResponseInfo(yield (0, CertificateUtil_1.sendOCSPRequest)(ocspRequest, ocspUrls[0])); const certStatus = ocspResponse.certStatus; if (certStatus === 'revoked') { return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.CertificateRevoked; } else if (certStatus !== 'good') { return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.NoCertificateAvailable; } } else { this._logger.error(`Certificate ${certificatePems[i]} has no OCSP URL.`); return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.CertChainError; } } } catch (error) { this._logger.error(`Failed to validate certificate chain: ${error}`); return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.NoCertificateAvailable; } return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.Accepted; }); } validateCertificateHashData(ocspRequestData) { return __awaiter(this, void 0, void 0, function* () { for (const reqData of ocspRequestData) { const ocspRequest = new Request({ alg: reqData.hashAlgorithm, keyhash: reqData.issuerKeyHash, namehash: reqData.issuerNameHash, serial: reqData.serialNumber, }); this._logger.debug(`OCSP request: ${JSON.stringify(ocspRequest)}`); try { const ocspResponse = jsrsasign_1.KJUR.asn1.ocsp.OCSPUtil.getOCSPResponseInfo(yield (0, CertificateUtil_1.sendOCSPRequest)(ocspRequest, reqData.responderURL)); // Cert statuses: good, revoked, unknown // source: https://kjur.github.io/jsrsasign/api/symbols/KJUR.asn1.ocsp.OCSPUtil.html#.getOCSPResponseInfo const certStatus = ocspResponse.certStatus; if (certStatus === 'revoked') { return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.CertificateRevoked; } else if (certStatus !== 'good') { return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.NoCertificateAvailable; } } catch (error) { this._logger.error(`Failed to fetch OCSP response: ${error}`); return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.NoCertificateAvailable; } } return base_1.OCPP2_0_1.AuthorizeCertificateStatusEnumType.Accepted; }); } /** * Create a certificate chain including leaf and sub CA certificates except for the root certificate. * * @param {string} signedCert - The leaf certificate. * @param {string} caCerts - CA certificates. * @return {string} The certificate chain pem. */ _createCertificateChainWithoutRootCA(signedCert, caCerts) { let certificateChain = ''; // Add Cert const leafRaw = (0, CertificateUtil_1.extractCertificateArrayFromEncodedString)(signedCert)[0]; if (leafRaw) { certificateChain += (0, CertificateUtil_1.createPemBlock)('CERTIFICATE', Buffer.from(leafRaw.toSchema().toBER(false)).toString('base64')); } else { throw new Error(`Cannot extract leaf certificate from the pem: ${signedCert}`); } // Add Chain without Root CA Certificate const chainWithoutRoot = (0, CertificateUtil_1.extractCertificateArrayFromEncodedString)(caCerts).slice(0, -1); chainWithoutRoot.forEach((certItem) => { const cert = certItem; certificateChain += (0, CertificateUtil_1.createPemBlock)('CERTIFICATE', Buffer.from(cert.toSchema().toBER(false)).toString('base64')); }); return certificateChain; } _instantiateV2GClient(config) { switch (config.util.certificateAuthority.v2gCA.name) { case 'hubject': { return new hubject_1.Hubject(config); } default: { throw new Error(`Unsupported V2G CA: ${config.util.certificateAuthority.v2gCA.name}`); } } } _instantiateChargingStationClient(config, logger) { switch (config.util.certificateAuthority.chargingStationCA.name) { case 'acme': { return new acme_1.Acme(config, logger); } default: { throw new Error(`Unsupported Charging Station CA: ${config.util.certificateAuthority.chargingStationCA.name}`); } } } } exports.CertificateAuthorityService = CertificateAuthorityService; //# sourceMappingURL=CertificateAuthority.js.map