'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var fs = require('fs'); var path = require('path'); var util = require('util'); var which = _interopDefault(require('async-which')); var x509 = require('@fidm/x509'); var execRoot = require('exec-root'); var child_process = require('child_process'); var os = require('os'); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __awaiter(thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var _this = undefined; var nonSudoExec = util.promisify(child_process.exec); var lstatAsync = util.promisify(fs.lstat); var isDirectory = function (source) { return __awaiter(_this, void 0, void 0, function () { var stats, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, lstatAsync(source)]; case 1: stats = _a.sent(); return [2 /*return*/, stats.isDirectory()]; case 2: e_1 = _a.sent(); return [2 /*return*/, false]; case 3: return [2 /*return*/]; } }); }); }; var isFile = function (source) { return __awaiter(_this, void 0, void 0, function () { var stats, e_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, lstatAsync(source)]; case 1: stats = _a.sent(); return [2 /*return*/, stats.isFile()]; case 2: e_2 = _a.sent(); return [2 /*return*/, false]; case 3: return [2 /*return*/]; } }); }); }; var getCertCommonName = function (certPath) { return __awaiter(_this, void 0, void 0, function () { var cert; return __generator(this, function (_a) { // Check cert exists fs.accessSync(certPath); cert = x509.Certificate.fromPEM(fs.readFileSync(certPath)); return [2 /*return*/, cert.issuer.commonName]; }); }); }; function generateTrust(platform, appName) { if (platform === void 0) { platform = os.platform(); } if (appName === void 0) { appName = 'Certificate Trust'; } if (platform === 'darwin') { return new MacOsTrust(appName); } else if (platform === 'win32') { return new WindowsTrust(appName); } else if (platform === 'linux') { return new LinuxTrust(appName); } else if (platform === 'nss') { return new NssTrust(appName); } else { throw new Error('Only MacOs, Linux and Windows supported'); } } var Trust = /** @class */ (function () { function Trust(appName) { this.name = ''; this.appName = ''; this.appName = appName; } Trust.prototype.handleInstallResult = function (stderr, adding) { if (stderr) { throw { message: "Could not " + (adding ? 'add cert to' : 'remove cert from') + " " + this.name + " store", err: stderr }; } else { console.log("Certificate successfully " + (adding ? 'added to' : 'removed from') + " " + this.name + "!"); return true; } }; return Trust; }()); var MacOsTrust = /** @class */ (function (_super) { __extends(MacOsTrust, _super); function MacOsTrust() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = 'MacOs'; return _this; } MacOsTrust.prototype.installFromFile = function (certPath) { return __awaiter(this, void 0, void 0, function () { var stderr; return __generator(this, function (_a) { switch (_a.label) { case 0: // Check cert exists fs.accessSync(certPath); return [4 /*yield*/, execRoot.exec("security add-trusted-cert -d -k /Library/Keychains/System.keychain \"" + certPath + "\"", { name: this.appName })]; case 1: stderr = (_a.sent()).stderr; this.handleInstallResult(stderr, true); return [2 /*return*/]; } }); }); }; MacOsTrust.prototype.uninstall = function (certPath) { return __awaiter(this, void 0, void 0, function () { var stderr, _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: _a = execRoot.exec; _b = "security delete-certificate -c \""; return [4 /*yield*/, getCertCommonName(certPath)]; case 1: return [4 /*yield*/, _a.apply(void 0, [_b + (_c.sent()) + "\"", { name: this.appName }])]; case 2: stderr = (_c.sent()).stderr; this.handleInstallResult(stderr, false); return [2 /*return*/]; } }); }); }; MacOsTrust.prototype.exists = function (certPath) { return __awaiter(this, void 0, void 0, function () { var _a, _b, e_3; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 3, , 4]); _a = nonSudoExec; _b = "security find-certificate -c "; return [4 /*yield*/, getCertCommonName(certPath)]; case 1: return [4 /*yield*/, _a.apply(void 0, [_b + (_c.sent()) + " \"/Library/Keychains/System.keychain\""])]; case 2: _c.sent(); return [2 /*return*/, true]; case 3: e_3 = _c.sent(); return [2 /*return*/, false]; case 4: return [2 /*return*/]; } }); }); }; return MacOsTrust; }(Trust)); var WindowsTrust = /** @class */ (function (_super) { __extends(WindowsTrust, _super); function WindowsTrust() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = 'Windows'; return _this; } WindowsTrust.prototype.installFromFile = function (certPath) { return __awaiter(this, void 0, void 0, function () { var newCertPath, stderr; return __generator(this, function (_a) { switch (_a.label) { case 0: // Check cert exists fs.accessSync(certPath); newCertPath = this.convertPathToCer(certPath); // Copy cert to trust path fs.copyFileSync(certPath, newCertPath); return [4 /*yield*/, execRoot.exec("certutil -addstore \"Root\" \"" + newCertPath + "\"", { name: this.appName })]; case 1: stderr = (_a.sent()).stderr; this.handleInstallResult(stderr, true); return [2 /*return*/]; } }); }); }; WindowsTrust.prototype.uninstall = function (certPath) { return __awaiter(this, void 0, void 0, function () { var _a, stdout, stderr, _b, serialNumber, stderr_1; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, nonSudoExec("certutil.exe -dump \"" + certPath + "\" | find \"Serial\"")]; case 1: _a = _c.sent(), stdout = _a.stdout, stderr = _a.stderr; if (!stdout) return [3 /*break*/, 3]; _b = stdout.split(' '), serialNumber = _b[2]; return [4 /*yield*/, execRoot.exec("certutil -delstore \"Root\" \"" + serialNumber.trim() + "\"", { name: this.appName })]; case 2: stderr_1 = (_c.sent()).stderr; this.handleInstallResult(stderr_1, false); return [3 /*break*/, 4]; case 3: this.handleInstallResult(stderr, false); _c.label = 4; case 4: return [2 /*return*/]; } }); }); }; WindowsTrust.prototype.exists = function (certPath) { return __awaiter(this, void 0, void 0, function () { var _a, stdout, stderr, e_4; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2, , 3]); return [4 /*yield*/, nonSudoExec("certutil.exe -verify \"" + certPath + "\"") // ? ]; case 1: _a = _b.sent(), stdout = _a.stdout, stderr = _a.stderr; // ? if (stdout) { return [2 /*return*/, !/UNTRUSTED root/.test(stdout) // Does not exist ]; // Does not exist } else if (stderr) { return [2 /*return*/, false // Exists ]; // Exists } else { return [2 /*return*/, true]; } return [3 /*break*/, 3]; case 2: e_4 = _b.sent(); return [2 /*return*/, false]; case 3: return [2 /*return*/]; } }); }); }; WindowsTrust.prototype.convertPathToCer = function (oldCertPath) { return oldCertPath.substr(0, oldCertPath.lastIndexOf('.')) + '.cer'; }; return WindowsTrust; }(Trust)); var LinuxTrust = /** @class */ (function (_super) { __extends(LinuxTrust, _super); function LinuxTrust(appName) { var _this = _super.call(this, appName) || this; _this.name = 'Linux'; // SystemTrustFilename is the format used to name the root certificates. _this.systemTrustFilename = ''; // systemTrustCommands is the command used to update the system truststore. _this.systemTrustCommands = []; if (fs.existsSync('/etc/pki/ca-trust/source/anchors/')) { _this.systemTrustFilename = '/etc/pki/ca-trust/source/anchors/%s.pem'; _this.systemTrustCommands = ['update-ca-trust', 'extract']; } else if (fs.existsSync('/usr/local/share/ca-certificates/')) { _this.systemTrustFilename = '/usr/local/share/ca-certificates/%s.crt'; _this.systemTrustCommands = ['update-ca-certificates']; } else if (fs.existsSync('/etc/ca-certificates/trust-source/anchors/')) { _this.systemTrustFilename = '/etc/ca-certificates/trust-source/anchors/%s.crt'; _this.systemTrustCommands = ['trust', 'extract-compat']; } if (_this.systemTrustCommands) { var resolved = which(_this.systemTrustCommands[0]); if (!resolved) { _this.systemTrustCommands = []; } } return _this; } LinuxTrust.prototype.installFromFile = function (certPath) { return __awaiter(this, void 0, void 0, function () { var stderr; return __generator(this, function (_a) { switch (_a.label) { case 0: // Check cert exists and copy cert to trust path fs.existsSync(certPath); fs.copyFileSync(certPath, this.getNewCertPath(certPath)); return [4 /*yield*/, execRoot.exec(this.systemTrustCommands.join(' '), { name: this.appName })]; case 1: stderr = (_a.sent()).stderr; this.handleInstallResult(stderr, true); return [2 /*return*/]; } }); }); }; LinuxTrust.prototype.uninstall = function (certPath) { return __awaiter(this, void 0, void 0, function () { var stderr; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, execRoot.exec("rm -f " + this.getNewCertPath(certPath), { name: this.appName })]; case 1: stderr = (_a.sent()).stderr; this.handleInstallResult(stderr, false); return [2 /*return*/]; } }); }); }; LinuxTrust.prototype.exists = function (certPath) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, isFile(this.getNewCertPath(certPath))]; }); }); }; LinuxTrust.prototype.getNewCertPath = function (certPath) { var certFileName = path.basename(certPath, path.extname(certPath)); return this.systemTrustFilename.replace('%s', certFileName); }; return LinuxTrust; }(Trust)); var NssTrust = /** @class */ (function (_super) { __extends(NssTrust, _super); function NssTrust() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = 'Nss'; _this.nssProfileDir = _this.getNssProfileDir(); _this.certutilPath = _this.getCertutilPath(); return _this; } NssTrust.prototype.installFromFile = function (certPath) { return __awaiter(this, void 0, void 0, function () { var _i, _a, db, stderr, _b, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: _i = 0; return [4 /*yield*/, this.getFirefoxDatabases()]; case 1: _a = _d.sent(); _d.label = 2; case 2: if (!(_i < _a.length)) return [3 /*break*/, 6]; db = _a[_i]; _b = execRoot.exec; _c = this.certutilPath + " -A -d \"" + db + "\" -t C,, -n \""; return [4 /*yield*/, getCertCommonName(certPath)]; case 3: return [4 /*yield*/, _b.apply(void 0, [_c + (_d.sent()) + "\" -i \"" + certPath + "\"", { name: this.appName }])]; case 4: stderr = (_d.sent()).stderr; this.handleInstallResult(stderr, true); _d.label = 5; case 5: _i++; return [3 /*break*/, 2]; case 6: return [2 /*return*/]; } }); }); }; NssTrust.prototype.uninstall = function (certPath) { return __awaiter(this, void 0, void 0, function () { var _i, _a, db, stderr, _b, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: _i = 0; return [4 /*yield*/, this.getFirefoxDatabases()]; case 1: _a = _d.sent(); _d.label = 2; case 2: if (!(_i < _a.length)) return [3 /*break*/, 6]; db = _a[_i]; _b = execRoot.exec; _c = this.certutilPath + " -D -d \"" + db + "\" -n \""; return [4 /*yield*/, getCertCommonName(certPath)]; case 3: return [4 /*yield*/, _b.apply(void 0, [_c + (_d.sent()) + "\"", { name: this.appName }])]; case 4: stderr = (_d.sent()).stderr; this.handleInstallResult(stderr, false); _d.label = 5; case 5: _i++; return [3 /*break*/, 2]; case 6: return [2 /*return*/]; } }); }); }; NssTrust.prototype.exists = function (certPath) { return __awaiter(this, void 0, void 0, function () { var firefoxDbs, allExist, _i, firefoxDbs_1, db, _a, _b, e_5; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, this.getFirefoxDatabases()]; case 1: firefoxDbs = _c.sent(); allExist = firefoxDbs.length > 0; _i = 0, firefoxDbs_1 = firefoxDbs; _c.label = 2; case 2: if (!(_i < firefoxDbs_1.length)) return [3 /*break*/, 8]; db = firefoxDbs_1[_i]; _c.label = 3; case 3: _c.trys.push([3, 6, , 7]); _a = nonSudoExec; _b = this.certutilPath + " -V -d \"" + db + "\" -n \""; return [4 /*yield*/, getCertCommonName(certPath)]; case 4: return [4 /*yield*/, _a.apply(void 0, [_b + (_c.sent()) + "\" -u L"])]; case 5: _c.sent(); return [3 /*break*/, 7]; case 6: e_5 = _c.sent(); allExist = false; return [3 /*break*/, 7]; case 7: _i++; return [3 /*break*/, 2]; case 8: return [2 /*return*/, allExist]; } }); }); }; NssTrust.prototype.getFirefoxDatabases = function () { return __awaiter(this, void 0, void 0, function () { var profiles, profileDirs, _i, profiles_1, profile, dbLinks, _a, profileDirs_1, profile; var _this = this; return __generator(this, function (_b) { switch (_b.label) { case 0: profiles = fs.readdirSync(this.nssProfileDir).map(function (profile) { return path.join(_this.nssProfileDir, profile); }); profileDirs = []; _i = 0, profiles_1 = profiles; _b.label = 1; case 1: if (!(_i < profiles_1.length)) return [3 /*break*/, 4]; profile = profiles_1[_i]; return [4 /*yield*/, isDirectory(profile)]; case 2: if (_b.sent()) { profileDirs.push(profile); } _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: if (!profileDirs.length) return [3 /*break*/, 11]; dbLinks = []; _a = 0, profileDirs_1 = profileDirs; _b.label = 5; case 5: if (!(_a < profileDirs_1.length)) return [3 /*break*/, 10]; profile = profileDirs_1[_a]; return [4 /*yield*/, isFile(path.join(profile, 'cert9.db'))]; case 6: if (!_b.sent()) return [3 /*break*/, 7]; dbLinks.push("sql:" + profile); return [3 /*break*/, 9]; case 7: return [4 /*yield*/, isFile(path.join(profile, 'cert8.db'))]; case 8: if (_b.sent()) { dbLinks.push("dbm:" + profile); } _b.label = 9; case 9: _a++; return [3 /*break*/, 5]; case 10: return [2 /*return*/, dbLinks]; case 11: console.log('No profiles with cert8 or cert9 dbs found in firefox directory.'); return [2 /*return*/, []]; } }); }); }; NssTrust.prototype.getNssProfileDir = function () { var platform = os.platform(); if (platform === 'win32') { return process.env['USERPROFILE'] + '\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles'; } else if (platform === 'darwin') { return process.env['HOME'] + '/Library/Application Support/Firefox/Profiles/'; } else if (platform === 'linux') { return process.env['HOME'] + '/.mozilla/firefox/'; } else { return ''; } }; NssTrust.prototype.getCertutilPath = function () { if (process.platform === 'win32') { if (process.arch === 'x64') { return path.join(__dirname, '..', 'nss', 'win64', 'certutil.exe'); // ia32 } else { return path.join(__dirname, '..', 'nss', 'win32', 'certutil.exe'); } } else if (process.platform === 'darwin') { return path.join(__dirname, '..', 'nss', 'mac', 'certutil'); } else if (process.platform === 'linux') { if (process.arch === 'x64') { return path.join(__dirname, '..', 'nss', 'linux64', 'certutil'); } else { return path.join(__dirname, '..', 'nss', 'linux32', 'certutil'); } } else { throw new Error('NSS only supported on MacOs, Linux and Windows'); } }; return NssTrust; }(Trust)); exports.isDirectory = isDirectory; exports.generateTrust = generateTrust; exports.Trust = Trust; exports.MacOsTrust = MacOsTrust; exports.WindowsTrust = WindowsTrust; exports.LinuxTrust = LinuxTrust; exports.NssTrust = NssTrust; //# sourceMappingURL=trust-cert.cjs.map