UNPKG

iocane

Version:
434 lines (433 loc) 21 kB
"use strict"; var __extends = (this && this.__extends) || (function () { 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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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 __generator = (this && this.__generator) || function (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 (g && (g = 0, op[0] && (_ = 0)), _) 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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createEncryptStream = exports.createDecryptStream = void 0; var crypto_1 = __importDefault(require("crypto")); var stream_1 = require("stream"); var events_1 = __importDefault(require("events")); var duplexer_1 = __importDefault(require("duplexer")); var stream_each_1 = __importDefault(require("stream-each")); var encryption_1 = require("./encryption"); var dataPacking_1 = require("./dataPacking"); var signature_1 = require("../shared/signature"); var timing_1 = require("../shared/timing"); var symbols_1 = require("../symbols"); var types_1 = require("../types"); var CONTENT_READAHEAD = 256 * 1024; var CONTENT_READ = CONTENT_READAHEAD - (0, signature_1.getBinaryContentBorder)().length * 2; var Streamer = /** @class */ (function (_super) { __extends(Streamer, _super); function Streamer(stream) { var _this = _super.call(this) || this; _this._buffer = null; _this._bytesRead = 0; _this._finished = false; _this._target = -1; _this._stream = stream; return _this; } Object.defineProperty(Streamer.prototype, "bytesRead", { get: function () { return this._bytesRead; }, enumerable: false, configurable: true }); Object.defineProperty(Streamer.prototype, "finished", { get: function () { return this._finished; }, enumerable: false, configurable: true }); Streamer.prototype.peek = function (bytes) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this._read(bytes, false)]; }); }); }; Streamer.prototype.read = function (bytes) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this._read(bytes, true)]; }); }); }; Streamer.prototype._init = function () { var _this = this; if (this._target !== -1) return; this._target = 0; (0, stream_each_1.default)(this._stream, function (data, next) { _this._buffer = _this._buffer ? Buffer.concat([_this._buffer, data]) : data; if (_this._target > 0) { if (_this._buffer.length >= _this._target) { _this.emit("target"); } else { next(); return; } } _this.once("wait", function () { next(); }); }, function (err) { if (err) { _this.emit("error", err); _this._stream.emit("error", err); } _this._finished = true; _this.emit("finished"); }); }; Streamer.prototype._read = function (bytes, remove, skipTargetCheck) { if (skipTargetCheck === void 0) { skipTargetCheck = false; } return __awaiter(this, void 0, void 0, function () { var readBytes, outBuff; var _this = this; return __generator(this, function (_a) { this._init(); if (!bytes || bytes <= 0) { throw new Error("Invalid number of bytes: ".concat(bytes)); } if (!skipTargetCheck && this._target > 0) { throw new Error("Existing stream peek/read operation already in progress"); } this._target = bytes; if (!this._buffer || this._buffer.length < this._target) { return [2 /*return*/, new Promise(function (resolve, reject) { var finishedCB = function () { _this.removeListener("target", finishedCB); _this._read(_this._buffer.length, remove, true).then(resolve, reject); }; var targetReachedCB = function () { _this.removeListener("finished", finishedCB); _this._read(bytes, remove, true).then(resolve, reject); }; _this.once("finished", finishedCB); _this.once("target", targetReachedCB); _this.emit("wait"); })]; } readBytes = Math.min(this._target, this._buffer.length); outBuff = Buffer.alloc(readBytes); this._buffer.copy(outBuff, 0, 0, readBytes); if (remove) { this._buffer = this._buffer.slice(readBytes); } this._target = 0; this._bytesRead += outBuff.length; return [2 /*return*/, outBuff]; }); }); }; return Streamer; }(events_1.default)); function createDecryptStream(adapter, password) { // Setup exposed streams var inStream = new stream_1.PassThrough(); var outStream = new stream_1.PassThrough(); var output = (0, duplexer_1.default)(inStream, outStream); // Reader var processor = new Streamer(inStream); (function () { return __awaiter(this, void 0, void 0, function () { var header, footer, contentBorderReference, expectedSignature, sigLen, buff, sizeBuff, headerSize, headerBuff, cipher, keyDerivationInfo, iv, decrypt, hmacTool, sizeBuff, borderSize, borderBuff, finalSegment, peekBuffer, contentBorderIndex, finalContent, finalSegSizeBuff, finalSegSize, intermediateBuffer, newHmacHex; return __generator(this, function (_a) { switch (_a.label) { case 0: header = null, footer = null; contentBorderReference = Buffer.from((0, signature_1.getBinaryContentBorder)()); expectedSignature = Buffer.from((0, signature_1.getBinarySignature)()); sigLen = expectedSignature.length; return [4 /*yield*/, processor.read(sigLen)]; case 1: buff = _a.sent(); if (!buff.equals(expectedSignature)) { throw new Error("Failed unpacking data: Signature mismatch"); } return [4 /*yield*/, processor.read(symbols_1.SIZE_ENCODING_BYTES)]; case 2: sizeBuff = _a.sent(); headerSize = sizeBuff.readUInt32BE(0); return [4 /*yield*/, processor.read(headerSize)]; case 3: headerBuff = _a.sent(); header = JSON.parse(headerBuff.toString("utf8")); // Setup decrypt tool adapter.setAlgorithm(header.method); adapter.setDerivationRounds(header.rounds); switch (header.method) { case types_1.EncryptionAlgorithm.CBC: cipher = symbols_1.NODE_ENC_ALGORITHM_CBC; break; case types_1.EncryptionAlgorithm.GCM: cipher = symbols_1.NODE_ENC_ALGORITHM_GCM; break; default: throw new Error("Invalid algo: ".concat(header.method)); } return [4 /*yield*/, adapter.deriveKey(password, header.salt)]; case 4: keyDerivationInfo = _a.sent(); iv = Buffer.from(header.iv, "hex"); decrypt = crypto_1.default.createDecipheriv(cipher, keyDerivationInfo.key, iv); hmacTool = null; if (header.method === types_1.EncryptionAlgorithm.CBC) { hmacTool = crypto_1.default.createHmac(symbols_1.NODE_HMAC_ALGORITHM, keyDerivationInfo.hmac); } else if (header.method === types_1.EncryptionAlgorithm.GCM) { decrypt.setAAD(Buffer.from("".concat(header.iv).concat(keyDerivationInfo.salt), "utf8")); } return [4 /*yield*/, processor.read(symbols_1.SIZE_ENCODING_BYTES)]; case 5: sizeBuff = _a.sent(); borderSize = sizeBuff.readUInt32BE(0); return [4 /*yield*/, processor.read(borderSize)]; case 6: borderBuff = _a.sent(); if (!borderBuff.equals(contentBorderReference)) { throw new Error("Failed unpacking data: Content border invalid"); } finalSegment = null; _a.label = 7; case 7: return [4 /*yield*/, processor.peek(CONTENT_READAHEAD)]; case 8: peekBuffer = _a.sent(); contentBorderIndex = peekBuffer.indexOf(contentBorderReference); if (!(contentBorderIndex >= 0)) return [3 /*break*/, 13]; return [4 /*yield*/, processor.read(contentBorderIndex)]; case 9: finalContent = _a.sent(); // Write to decrypt stream if (hmacTool) { hmacTool.update(finalContent); } outStream.write(decrypt.update(finalContent)); // Pass border return [4 /*yield*/, processor.read(contentBorderReference.length)]; case 10: // Pass border _a.sent(); return [4 /*yield*/, processor.read(symbols_1.SIZE_ENCODING_BYTES)]; case 11: finalSegSizeBuff = _a.sent(); finalSegSize = finalSegSizeBuff.readUInt32BE(0); return [4 /*yield*/, processor.read(finalSegSize)]; case 12: finalSegment = _a.sent(); if (!processor.finished) { throw new Error("Expected end of stream"); } return [3 /*break*/, 16]; case 13: return [4 /*yield*/, processor.read(CONTENT_READ)]; case 14: intermediateBuffer = _a.sent(); if (hmacTool) { hmacTool.update(intermediateBuffer); } outStream.write(decrypt.update(intermediateBuffer)); _a.label = 15; case 15: if (true) return [3 /*break*/, 7]; _a.label = 16; case 16: // Parse footer footer = JSON.parse(finalSegment.toString("utf8")); // Set auth tag if (header.method === types_1.EncryptionAlgorithm.CBC) { hmacTool.update(header.iv); hmacTool.update(header.salt); newHmacHex = hmacTool.digest("hex"); if ((0, timing_1.constantTimeCompare)(footer.auth, newHmacHex) !== true) { throw new Error("Authentication failed while decrypting content"); } } else if (header.method === types_1.EncryptionAlgorithm.GCM) { decrypt.setAuthTag(Buffer.from(footer.auth, "hex")); } // Finalise decryption inStream.destroy(); outStream.end(decrypt.final()); return [2 /*return*/]; } }); }); })().catch(function (err) { output.emit("error", err); output.destroy(); }); return output; } exports.createDecryptStream = createDecryptStream; function createEncryptStream(adapter, password) { // Setup exposed streams var inStream = new stream_1.PassThrough(); var outStream = new stream_1.PassThrough(); var output = (0, duplexer_1.default)(inStream, outStream); // Internal streams prepareComponents(adapter, password) .then(function (_a) { var iv = _a.iv, keyDerivationInfo = _a.keyDerivationInfo; var ivHex = iv.toString("hex"); var header = (0, dataPacking_1.prepareHeader)({ iv: ivHex, salt: keyDerivationInfo.salt, rounds: keyDerivationInfo.rounds, method: adapter.algorithm }); // Write header (no compression etc.) outStream.write(header); // Write content border outStream.write((0, dataPacking_1.itemsToBuffer)([Buffer.from((0, signature_1.getBinaryContentBorder)())])); // Setup crypto streams var hmac, final, authTag; if (adapter.algorithm === types_1.EncryptionAlgorithm.CBC) { var encrypt_1 = crypto_1.default.createCipheriv(symbols_1.NODE_ENC_ALGORITHM_CBC, keyDerivationInfo.key, iv); hmac = crypto_1.default.createHmac(symbols_1.NODE_HMAC_ALGORITHM, keyDerivationInfo.hmac); final = inStream .pipe(new stream_1.Transform({ flush: function (callback) { this.push(encrypt_1.final()); callback(); }, transform: function (chunk, encoding, callback) { callback(null, encrypt_1.update(chunk)); } })) .pipe(new stream_1.Transform({ flush: function (callback) { this.push(Buffer.from((0, signature_1.getBinaryContentBorder)())); callback(); }, transform: function (chunk, encoding, callback) { hmac.update(chunk); callback(null, chunk); } })); } else if (adapter.algorithm === types_1.EncryptionAlgorithm.GCM) { var encrypt_2 = crypto_1.default.createCipheriv(symbols_1.NODE_ENC_ALGORITHM_GCM, keyDerivationInfo.key, iv); encrypt_2.setAAD(Buffer.from("".concat(ivHex).concat(keyDerivationInfo.salt), "utf8")); final = inStream.pipe(new stream_1.Transform({ flush: function (callback) { this.push(encrypt_2.final()); this.push(Buffer.from((0, signature_1.getBinaryContentBorder)())); authTag = encrypt_2.getAuthTag(); callback(); }, transform: function (chunk, encoding, callback) { callback(null, encrypt_2.update(chunk)); } })); } else { throw new Error("Invalid encryption algorithm: ".concat(adapter.algorithm)); } // Handle transform (footer write) var footerTransform = new stream_1.Transform({ flush: function (callback) { if (hmac) { hmac.update(ivHex); hmac.update(keyDerivationInfo.salt); this.push((0, dataPacking_1.prepareFooter)({ auth: hmac.digest("hex") })); } else if (authTag) { this.push((0, dataPacking_1.prepareFooter)({ auth: authTag.toString("hex") })); } callback(); }, transform: function (chunk, encoding, callback) { callback(null, chunk); } }); final.pipe(footerTransform).pipe(outStream); }) .catch(function (err) { output.emit("error", err); output.destroy(); }); return output; } exports.createEncryptStream = createEncryptStream; function prepareComponents(adapter, password) { return __awaiter(this, void 0, void 0, function () { var salt, _a, keyDerivationInfo, iv; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, (0, encryption_1.generateSalt)(symbols_1.SALT_LENGTH)]; case 1: salt = _b.sent(); return [4 /*yield*/, Promise.all([ adapter.deriveKey(password, salt), (0, encryption_1.generateIV)() ])]; case 2: _a = _b.sent(), keyDerivationInfo = _a[0], iv = _a[1]; return [2 /*return*/, { iv: iv, keyDerivationInfo: keyDerivationInfo }]; } }); }); }