"use strict";
/*
 * Wire
 * Copyright (C) 2018 Wire Swiss GmbH
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 *
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyPinning = exports.hostnameShouldBePinned = exports.getFingerprint = exports.buildCert = void 0;
const crypto = __importStar(require("crypto"));
const rs = require("jsrsasign");
const pinningData_1 = require("./pinningData");
function buildCert(buffer) {
    return `-----BEGIN CERTIFICATE-----\n${buffer.toString('base64')}\n-----END CERTIFICATE-----`;
}
exports.buildCert = buildCert;
function getFingerprint(derCert) {
    const derBinary = derCert.toString('binary');
    const hexDerFileContents = rs.rstrtohex(derBinary);
    const pemString = rs.KJUR.asn1.ASN1Util.getPEMStringFromHex(hexDerFileContents, 'CERTIFICATE');
    const publicKey = rs.X509.getPublicKeyInfoPropOfCertPEM(pemString);
    const publicKeyBytes = Buffer.from(publicKey.keyhex, 'hex').toString('binary');
    return crypto.createHash('sha256').update(publicKeyBytes).digest('base64');
}
exports.getFingerprint = getFingerprint;
function hostnameShouldBePinned(hostname) {
    return pinningData_1.KNOWN_PINS.some(pin => pin.url.test(hostname.toLowerCase().trim()));
}
exports.hostnameShouldBePinned = hostnameShouldBePinned;
function verifyPinning(hostname, remoteCertificate) {
    if (!remoteCertificate) {
        return {
            errorMessage: 'No certificate provided by Electron.',
        };
    }
    if (!remoteCertificate.issuerCert) {
        return {
            errorMessage: 'No issuer certificate in certificate.',
        };
    }
    const { data: certData, issuerCert } = remoteCertificate;
    function getRemoteIssuerCertData(remoteIssuerCert = issuerCert) {
        return remoteIssuerCert.issuerCert ? getRemoteIssuerCertData(remoteIssuerCert.issuerCert) : remoteIssuerCert;
    }
    let remoteIssuerCertHex;
    let remotePublicKey;
    let remotePublicKeyBytes;
    let remotePublicKeyFingerprint;
    const errorMessages = [];
    try {
        remoteIssuerCertHex = rs.pemtohex(getRemoteIssuerCertData().data);
        remotePublicKey = rs.X509.getPublicKeyInfoPropOfCertPEM(certData);
        remotePublicKeyBytes = Buffer.from(remotePublicKey.keyhex, 'hex').toString('binary');
        remotePublicKeyFingerprint = crypto.createHash('sha256').update(remotePublicKeyBytes).digest('base64');
    }
    catch (error) {
        return {
            decoding: false,
            errorMessage: error.message,
        };
    }
    const result = {};
    for (const knownPin of pinningData_1.KNOWN_PINS) {
        const { url, publicKeyInfo: localPublicKeyInfo = [], issuerRootCerts: knownIssuerRootCerts = [] } = knownPin;
        if (url.test(hostname.toLowerCase().trim())) {
            if (knownIssuerRootCerts.length > 0) {
                result.verifiedIssuerRootCerts = knownIssuerRootCerts.some(knownRootCert => remoteIssuerCertHex === rs.pemtohex(knownRootCert));
                if (!result.verifiedIssuerRootCerts) {
                    const knownCertsCombined = knownIssuerRootCerts.join(', ').replace(/[\r\n]/g, '');
                    const errorMessage = `Issuer root certificates: none of "${knownCertsCombined}" could be verified against "${getRemoteIssuerCertData().data}.`;
                    errorMessages.push(errorMessage);
                }
            }
            result.verifiedPublicKeyInfo = localPublicKeyInfo
                .reduce((arr, localPubKey) => {
                const { algorithmID: localAlgorithmID, algorithmParam: localAlgorithmParam, fingerprints: localFingerprints, } = localPubKey;
                const fingerprintCheck = localFingerprints.length > 0 &&
                    localFingerprints.some(knownFingerprint => knownFingerprint === remotePublicKeyFingerprint);
                const algorithmIDCheck = localAlgorithmID === remotePublicKey.algoid;
                const algorithmParamCheck = localAlgorithmParam === remotePublicKey.algparam;
                if (!fingerprintCheck) {
                    const fingerprintsCombined = localFingerprints.join(', ');
                    const errorMessage = `Public key fingerprints: "${remotePublicKeyFingerprint}" could not be verified with any of the known fingerprints "${fingerprintsCombined}".`;
                    errorMessages.push(errorMessage);
                }
                if (!algorithmIDCheck) {
                    const algorithmID = remotePublicKey.algoid;
                    const errorMessage = `Algorithm ID: "${algorithmID}" could not be verified with the known ID "${localAlgorithmID}".`;
                    errorMessages.push(errorMessage);
                }
                if (!algorithmParamCheck) {
                    const algorithmParam = remotePublicKey.algparam;
                    const errorMessage = `Algorithm parameter: "${algorithmParam}" could not be verified with the known parameter "${localAlgorithmParam}".`;
                    errorMessages.push(errorMessage);
                }
                arr.push(fingerprintCheck, algorithmIDCheck, algorithmParamCheck);
                return arr;
            }, [])
                .every(value => Boolean(value));
            break;
        }
    }
    if (errorMessages.length > 0) {
        result.errorMessage = errorMessages.join('\n');
        result.certificate = remoteCertificate;
    }
    return result;
}
exports.verifyPinning = verifyPinning;
//# sourceMappingURL=CertUtil.js.map