all files / core/security/digital-signature/signature/ signature-dictionary.js

8.68% Statements 27/311
0% Branches 0/149
7.41% Functions 2/27
8.71% Lines 27/310
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
define(["require", "exports", "../../../enumerator", "../../../pdf-document", "../../../pdf-primitives", "../pdf-certificate", "../x509/x509-certificate-parser", "./signature-privatekey", "./cryptographic-signer", "../../../utils"], function (require, exports, enumerator_1, pdf_document_1, pdf_primitives_1, pdf_certificate_1, x509_certificate_parser_1, signature_privatekey_1, cryptographic_signer_1, utils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var _PdfSignatureDictionary = (function () {
        function _PdfSignatureDictionary(arg1, arg2) {
            this._dictionary = new pdf_primitives_1._PdfDictionary();
            this._transParam = 'TransformParams';
            this._signaturePermissionsDictionary = 'DocMDP';
            this._cryptographicFilterType = 'adbe.pkcs7.detached';
            this._advanceFilterType = 'ETSI.CAdES.detached';
            this._requestForCommentsFilterType = 'ETSI.RFC3161';
            this._estimatedSize = 8192;
            if (!arg1) {
                throw new Error('A valid argument must be provided.');
            }
            if (!arg2) {
                throw new Error('Argument signature is null or undefined.');
            }
            if (arg1 instanceof pdf_document_1.PdfDocument) {
                this._document = arg1;
                this._crossReference = arg1._crossReference;
            }
            else {
                this._dictionary = arg1;
            }
            this._signature = arg2;
            this._certificate = arg2._certificate;
        }
        _PdfSignatureDictionary.prototype._parsePdfContents = function (contents) {
            var result;
            if (contents instanceof Uint8Array) {
                return contents;
            }
            else if (typeof contents === 'string') {
                var trimmed = contents.trim();
                var isHexFormat = trimmed.startsWith('<') && trimmed.endsWith('>');
                if (isHexFormat) {
                    var hex = trimmed.slice(1, -1).replace(/[^0-9a-fA-F]/g, '');
                    if (hex.length % 2 !== 0) {
                        hex += '0';
                    }
                    result = new Uint8Array(hex.length / 2);
                    for (var i = 0; i < hex.length; i += 2) {
                        result[i / 2] = parseInt(hex.slice(i, i + 2), 16);
                    }
                    return result;
                }
                result = new Uint8Array(trimmed.length);
                for (var i = 0; i < trimmed.length; i++) {
                    result[i] = trimmed.charCodeAt(i) & 0xff;
                }
                return result;
            }
            return result;
        };
        _PdfSignatureDictionary.prototype._parseDigestAlgorithm = function () {
            var digest;
            var cmsSigner;
            if (this._dictionary.has('Contents')) {
                var contents = this._dictionary.get('Contents');
                var bytes = this._parsePdfContents(contents);
                var isDeferredSigning = bytes && bytes.length > 0 && bytes.every(function (byte) { return byte === 0; });
                if (bytes && bytes.length > 0 && !isDeferredSigning) {
                    var parser = new x509_certificate_parser_1._PdfX509CertificateParser();
                    var certificateChain = parser._readCertificate(bytes, true);
                    var certificate = new pdf_certificate_1._PdfCertificate(certificateChain);
                    this._certificate = certificate;
                    cmsSigner = new cryptographic_signer_1._PdfCryptographicMessageSyntaxSigner(bytes);
                }
            }
            if (cmsSigner) {
                var messageDigest = cmsSigner._getHashAlgorithm();
                switch (messageDigest) {
                    case 'SHA512':
                        digest = enumerator_1.DigestAlgorithm.sha512;
                        break;
                    case 'SHA384':
                        digest = enumerator_1.DigestAlgorithm.sha384;
                        break;
                    case 'SHA1':
                        digest = enumerator_1.DigestAlgorithm.sha1;
                        break;
                    case 'RIPEMD160':
                        digest = enumerator_1.DigestAlgorithm.ripemd160;
                        break;
                    default:
                        digest = enumerator_1.DigestAlgorithm.sha256;
                        break;
                }
            }
            return digest;
        };
        _PdfSignatureDictionary.prototype._parseDirect = function (key) {
            var value;
            if (this._dictionary.has(key)) {
                value = this._dictionary.get(key);
            }
            return value;
        };
        _PdfSignatureDictionary.prototype._parseSignedDate = function () {
            var signedDate;
            if (this._dictionary.has('M')) {
                var dateEntry = this._dictionary.get('M');
                signedDate = this._parsePdfDate(dateEntry);
            }
            return signedDate;
        };
        _PdfSignatureDictionary.prototype._parsePdfDate = function (v) {
            if (typeof v !== 'string' || v.length === 0) {
                return undefined;
            }
            var s = v.trim();
            if (s.startsWith('D:')) {
                s = s.slice(2);
            }
            var year = Number(s.slice(0, 4));
            var month = Number(s.slice(4, 6) || '01');
            var day = Number(s.slice(6, 8) || '01');
            var hour = Number(s.slice(8, 10) || '00');
            var minute = Number(s.slice(10, 12) || '00');
            var second = Number(s.slice(12, 14) || '00');
            var offsetMinutes = 0;
            var tzStart = 14;
            if (s.length > tzStart) {
                var tzRaw = s.slice(tzStart).replace(/'/g, '');
                if (tzRaw.toUpperCase() !== 'Z') {
                    var sign = tzRaw.startsWith('-') ? -1 : 1;
                    var hh = Number(tzRaw.slice(1, 3));
                    var mm = tzRaw.length >= 5 ? Number(tzRaw.slice(3, 5)) : 0;
                    offsetMinutes = sign * (hh * 60 + mm);
                }
            }
            var millisLocal = Date.UTC(year, month - 1, day, hour, minute, second);
            var time = millisLocal - offsetMinutes * 60000;
            var dt = new Date(time);
            return isNaN(dt.getTime()) ? undefined : dt;
        };
        _PdfSignatureDictionary.prototype._dictionarySave = function (buffer) {
            if (!this._dictionary || buffer.length <= 0) {
                throw new Error('dictionary or writer is null.');
            }
            if (this._signature) {
                this._addRequiredItems();
                this._addOptionalItems();
            }
            this._addContents(buffer);
            this._addRange(buffer);
            if (this._signature && this._signature._certify) {
                this._addDigest(buffer);
            }
        };
        _PdfSignatureDictionary.prototype._addDigest = function (buffer) {
            if (this._signature && this._signature._certify && this._allowMessageDigestProcessing()) {
                var writer = this._document._crossReference;
                writer._writeString("/Reference[<</TransformParams<<\r\n/V /1.2\r\n/P " + this._signature._documentPermissions + "\r\n /Type /TransformParams\r\n>>\r\n/TransformMethod/DocMDP/Type/SigRef/DigestValue", buffer);
                var offset = buffer.length + writer._currentLength;
                writer._writeString('<', buffer);
                for (var i = 0; i < 32; i++) {
                    writer._writeString('0', buffer);
                }
                var reference = this._document._catalog._catalogDictionary.objId.toString();
                writer._writeString('>/DigestLocation[' + offset + ' 34]/DigestMethod/MD5/Data ' + reference + ' R>><</TransformParams<<\r\n/V /1.2\r\n/Fields [(Signature)]\r\n/Type /TransformParams\r\n/Action /Include\r\n>>\r\n/TransformMethod/FieldMDP/Type/SigRef/DigestValue', buffer);
                offset = buffer.length + writer._currentLength;
                writer._writeString('<', buffer);
                for (var i = 0; i < 32; i++) {
                    writer._writeString('0', buffer);
                }
                writer._writeString('>/DigestLocation[' + offset + ' 34]/DigestMethod/MD5/Data ' + reference + ' R>>]\r\n', buffer);
            }
        };
        _PdfSignatureDictionary.prototype._addRequiredItems = function () {
            if (this._signature && this._signature._certify && this._allowMessageDigestProcessing()) {
                this._addReference();
            }
            this._addType();
            this._addDate();
            this._addFilter();
            this._addSubFilter();
        };
        _PdfSignatureDictionary.prototype._allowMessageDigestProcessing = function () {
            var dictionary = this._document._catalog._catalogDictionary.get('Perms');
            if (typeof dictionary !== 'undefined' && dictionary !== null) {
                var docMDP = dictionary.get('DocMDP');
                if (docMDP instanceof pdf_primitives_1._PdfReference) {
                    var docMDPDictionary = this._document._crossReference._fetch(docMDP);
                    var signatureDictionary = this._dictionary;
                    if (signatureDictionary.has('Reference') || docMDPDictionary.has('Reference')) {
                        return false;
                    }
                }
                else if (docMDP instanceof pdf_primitives_1._PdfDictionary) {
                    if (docMDP.objId !== this._dictionary.objId) {
                        return false;
                    }
                }
            }
            return true;
        };
        _PdfSignatureDictionary.prototype._addOptionalItems = function () {
            if (this._signature) {
                if (this._signature._reason) {
                    this._dictionary.update('Reason', this._signature._reason);
                }
                if (this._signature._locationInfo) {
                    this._dictionary.update('Location', this._signature._locationInfo);
                }
                if (this._signature._contactInfo) {
                    this._dictionary.update('ContactInfo', this._signature._contactInfo);
                }
                if (this._signature._signedName) {
                    this._dictionary.update('Name', this._signature._signedName);
                    var tempDictionary = new pdf_primitives_1._PdfDictionary();
                    var appDictionary = new pdf_primitives_1._PdfDictionary();
                    tempDictionary.update('Name', this._signature._signedName);
                    var ref = this._document._crossReference._getNextReference();
                    this._document._crossReference._cacheMap.set(ref, tempDictionary);
                    appDictionary.update('App', ref);
                    ref = this._document._crossReference._getNextReference();
                    this._document._crossReference._cacheMap.set(ref, appDictionary);
                    this._dictionary.update('Prop_Build', ref);
                }
            }
        };
        _PdfSignatureDictionary.prototype._addReference = function () {
            var trans = new pdf_primitives_1._PdfDictionary();
            var reference = new pdf_primitives_1._PdfDictionary();
            var array = [];
            trans.update('V', pdf_primitives_1._PdfName.get('1.2'));
            trans.update('P', this._signature._documentPermissions);
            trans.update('Type', pdf_primitives_1._PdfName.get(this._transParam));
            reference.update('TransformMethod', pdf_primitives_1._PdfName.get(this._signaturePermissionsDictionary));
            reference.update('Type', pdf_primitives_1._PdfName.get('SigRef'));
            reference.update(this._transParam, trans);
            reference.update(this._transParam, trans);
            array.push(reference);
            this._dictionary.update('Reference', array);
        };
        _PdfSignatureDictionary.prototype._addType = function () {
            if (this._certificate) {
                this._dictionary.update('Type', new pdf_primitives_1._PdfName('Sig'));
            }
        };
        _PdfSignatureDictionary.prototype._addDate = function () {
            var dateTime = new Date();
            if (this._signature && this._signature._signedDate) {
                dateTime = this._signature._signedDate;
            }
            var year = dateTime.getFullYear().toString();
            var month = utils_1._padStart((dateTime.getMonth() + 1).toString(), 2, '0');
            var day = utils_1._padStart(dateTime.getDate().toString(), 2, '0');
            var hours = utils_1._padStart(dateTime.getHours().toString(), 2, '0');
            var minutes = utils_1._padStart(dateTime.getMinutes().toString(), 2, '0');
            var seconds = utils_1._padStart(dateTime.getSeconds().toString(), 2, '0');
            var totalMinutesOffset = dateTime.getTimezoneOffset();
            var offsetHours = utils_1._padStart(Math.floor(Math.abs(totalMinutesOffset) / 60).toString(), 2, '0');
            var offsetMinutes = utils_1._padStart((Math.abs(totalMinutesOffset) % 60).toString(), 2, '0');
            var offsetSign = totalMinutesOffset > 0 ? '-' : '+';
            this._dictionary.update('M', "D:" + year + month + day + hours + minutes + seconds + offsetSign + offsetHours + "'" + offsetMinutes + "'");
        };
        _PdfSignatureDictionary.prototype._addFilter = function () {
            this._dictionary.update('Filter', new pdf_primitives_1._PdfName('Adobe.PPKLite'));
        };
        _PdfSignatureDictionary.prototype._addSubFilter = function () {
            if (this._signature && this._signature._cryptographicStandard === enumerator_1.CryptographicStandard.cades) {
                this._dictionary.update('SubFilter', new pdf_primitives_1._PdfName(this._advanceFilterType));
            }
            else {
                this._dictionary.update('SubFilter', new pdf_primitives_1._PdfName(this._cryptographicFilterType));
            }
        };
        _PdfSignatureDictionary.prototype._getLength = function () {
            var length = 0;
            if (this._crossReference._uint8Chunks.length > 0) {
                for (var i = 0; i < this._crossReference._uint8Chunks.length; i++) {
                    var arr = this._crossReference._uint8Chunks[i];
                    length += arr.length;
                }
            }
            return length;
        };
        _PdfSignatureDictionary.prototype._addContents = function (buffer) {
            var chunksLength = this._getLength();
            var writer = this._crossReference;
            writer._writeString('/Contents ', buffer);
            this._firstRangeLength = this._crossReference._currentLength + buffer.length + chunksLength;
            var length = this._estimatedSize * 2;
            if (this._signature && this._certificate) {
                length = this._estimatedSize;
            }
            writer._writeString('<' + ' '.repeat(length * 2) + '>', buffer);
            this._secondRangeIndex = buffer.length + chunksLength + this._crossReference._currentLength;
            writer._writeString('\r\n', buffer);
        };
        _PdfSignatureDictionary.prototype._addRange = function (buffer) {
            var chunksLength = this._getLength();
            var writer = this._crossReference;
            writer._writeString("" + '/' + 'ByteRange' + ' ' + '[', buffer);
            this._startPositionByteRange = buffer.length + this._document._crossReference._currentLength + chunksLength;
            for (var i = 0; i < 32; i++) {
                writer._writeString(' ', buffer);
            }
            writer._writeString("" + ']' + '\r\n', buffer);
        };
        _PdfSignatureDictionary.prototype._documentSaved = function (buffer) {
            var secondRangeLength = buffer.length - this._secondRangeIndex;
            var byteRangeStrings = ['0 ', this._firstRangeLength + " ",
                this._secondRangeIndex + " ",
                secondRangeLength.toString()
            ];
            var currentPosition = this._saveRangeItem(buffer, byteRangeStrings[0], this._startPositionByteRange);
            currentPosition = this._saveRangeItem(buffer, byteRangeStrings[1], currentPosition);
            currentPosition = this._saveRangeItem(buffer, byteRangeStrings[2], currentPosition);
            this._saveRangeItem(buffer, byteRangeStrings[3], currentPosition);
            var buf1 = buffer.subarray(0, this._firstRangeLength);
            var buf2 = buffer.subarray(this._secondRangeIndex);
            var combined = new Uint8Array(buf1.length + buf2.length);
            combined.set(buf1, 0);
            combined.set(buf2, buf1.length);
            var pkcs7Content = this._getCryptographicStandardContent(combined);
            var hexEncodedSignature = utils_1._bytesToHex(pkcs7Content);
            var signatureStartPos = this._firstRangeLength;
            buffer[signatureStartPos] = '<'.charCodeAt(0) & 0xff;
            for (var i = 0; i < hexEncodedSignature.length; i++) {
                buffer[signatureStartPos + 1 + i] = hexEncodedSignature.charCodeAt(i) & 0xff;
            }
            var signatureEndPos = signatureStartPos + 1 + hexEncodedSignature.length;
            var paddingLength = this._secondRangeIndex - signatureEndPos - 1;
            if (paddingLength > 0) {
                buffer.fill('0'.charCodeAt(0) & 0xff, signatureEndPos, signatureEndPos + paddingLength);
            }
            buffer[this._secondRangeIndex - 1] = '>'.charCodeAt(0) & 0xff;
        };
        _PdfSignatureDictionary.prototype._getCryptographicStandardContent = function (data) {
            try {
                var hashAlgorithm = '';
                var externalSignature = void 0;
                var crlBytes = void 0;
                var ocspByte = void 0;
                var chain_1 = [];
                if (this._signature._externalSignatureCallback) {
                    if (this._signature._externalChain && this._signature._externalChain.length > 0) {
                        hashAlgorithm = enumerator_1.DigestAlgorithm[this._signature._digestAlgorithm];
                        var pks = new signature_privatekey_1._PdfSignaturePrivateKey(hashAlgorithm);
                        externalSignature = pks;
                        chain_1.push.apply(chain_1, this._signature._externalChain);
                    }
                    else {
                        var value = this._signature._externalSignatureCallback(data, {
                            algorithm: this._signature._digestAlgorithm,
                            cryptographicStandard: enumerator_1.CryptographicStandard.cms
                        });
                        return value.signedData;
                    }
                }
                else {
                    var certificateAlias_1 = '';
                    var pk_1;
                    var keys = this._certificate._publicKeyCryptographyCertificate._keys;
                    keys.forEach(function (keyEntry, alias) {
                        var entry = keyEntry;
                        if (entry.privateKey) {
                            certificateAlias_1 = alias;
                            pk_1 = entry;
                        }
                    });
                    var certificates = this._certificate._publicKeyCryptographyCertificate._getCertificateChain(certificateAlias_1);
                    certificates.forEach(function (c) {
                        chain_1.push(c._certificate);
                    });
                    var digest = enumerator_1.DigestAlgorithm[this._signature._digestAlgorithm];
                    var pks = new signature_privatekey_1._PdfSignaturePrivateKey(digest, pk_1.privateKey);
                    hashAlgorithm = digest;
                    externalSignature = pks;
                }
                var pkcs7 = new cryptographic_signer_1._PdfCryptographicMessageSyntaxSigner(null, chain_1, hashAlgorithm, false);
                var hash = pkcs7._getDigestAlgorithm()._digest(data, hashAlgorithm);
                var sequenceDataSet = pkcs7._getSequenceDataSet(hash, ocspByte, crlBytes, this._signature._cryptographicStandard);
                var extSignature = void 0;
                if (this._signature._externalChain && this._signature._externalChain.length > 0) {
                    var value = this._signature._externalSignatureCallback(sequenceDataSet, { algorithm: this._signature._digestAlgorithm,
                        cryptographicStandard: this._signature._cryptographicStandard });
                    if (value && value.signedData) {
                        extSignature = value.signedData;
                    }
                    if (!value.signedData) {
                        return new Uint8Array(this._estimatedSize).fill(0);
                    }
                }
                else {
                    extSignature = externalSignature._sign(sequenceDataSet);
                }
                pkcs7._setSignedData(extSignature, null, externalSignature._getEncryptionAlgorithm());
                var cryptographicStandard = void 0;
                if (this._signature && this._signature._cryptographicStandard) {
                    cryptographicStandard = this._signature._cryptographicStandard;
                }
                else {
                    cryptographicStandard = enumerator_1.CryptographicStandard.cms;
                }
                return pkcs7._sign(hash, null, ocspByte, crlBytes, cryptographicStandard, hashAlgorithm);
            }
            catch (error) {
                return new Uint8Array(this._estimatedSize).fill(0);
            }
        };
        _PdfSignatureDictionary.prototype._saveRangeItem = function (buffer, str, startPosition) {
            var utf8Bytes = [];
            for (var i = 0; i < str.length; i++) {
                utf8Bytes.push(str.charCodeAt(i) & 0xff);
            }
            buffer.set(utf8Bytes, startPosition);
            return startPosition + str.length;
        };
        return _PdfSignatureDictionary;
    }());
    exports._PdfSignatureDictionary = _PdfSignatureDictionary;
});