Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 | 24x 24x 24x 24x 24x 12x 72x 24x 24x 24x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 4x 8x 12x 12x 12x 12x 12x 8x 12x 4x 4x 4x 4x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 4x 4x 12x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 12x 12x | import * as asn1js from "asn1js";
import { getParametersValue, isEqualBuffer } from "pvutils";
import {
getAlgorithmByOID,
getAlgorithmParameters,
getCrypto,
getEngine,
createECDSASignatureFromCMS,
getHashAlgorithm
} from "./common.js";
import ResponseData from "./ResponseData.js";
import AlgorithmIdentifier from "./AlgorithmIdentifier.js";
import Certificate from "./Certificate.js";
import CertID from "./CertID.js";
import RSASSAPSSParams from "./RSASSAPSSParams.js";
import RelativeDistinguishedNames from "./RelativeDistinguishedNames.js";
import CertificateChainValidationEngine from "./CertificateChainValidationEngine.js";
//**************************************************************************************
/**
* Class from RFC6960
*/
export default class BasicOCSPResponse
{
//**********************************************************************************
/**
* Constructor for BasicOCSPResponse class
* @param {Object} [parameters={}]
* @property {Object} [schema] asn1js parsed value
*/
constructor(parameters = {})
{
//region Internal properties of the object
/**
* @type {ResponseData}
* @description tbsResponseData
*/
this.tbsResponseData = getParametersValue(parameters, "tbsResponseData", BasicOCSPResponse.defaultValues("tbsResponseData"));
/**
* @type {AlgorithmIdentifier}
* @description signatureAlgorithm
*/
this.signatureAlgorithm = getParametersValue(parameters, "signatureAlgorithm", BasicOCSPResponse.defaultValues("signatureAlgorithm"));
/**
* @type {BitString}
* @description signature
*/
this.signature = getParametersValue(parameters, "signature", BasicOCSPResponse.defaultValues("signature"));
Iif("certs" in parameters)
/**
* @type {Array.<Certificate>}
* @description certs
*/
this.certs = getParametersValue(parameters, "certs", BasicOCSPResponse.defaultValues("certs"));
//endregion
//region If input argument array contains "schema" for this object
if("schema" in parameters)
this.fromSchema(parameters.schema);
//endregion
}
//**********************************************************************************
/**
* Return default values for all class members
* @param {string} memberName String name for a class member
*/
static defaultValues(memberName)
{
switch(memberName)
{
case "tbsResponseData":
return new ResponseData();
case "signatureAlgorithm":
return new AlgorithmIdentifier();
case "signature":
return new asn1js.BitString();
case "certs":
return [];
default:
throw new Error(`Invalid member name for BasicOCSPResponse class: ${memberName}`);
}
}
//**********************************************************************************
/**
* Compare values with default values for all class members
* @param {string} memberName String name for a class member
* @param {*} memberValue Value to compare with default value
*/
static compareWithDefault(memberName, memberValue)
{
switch(memberName)
{
case "type":
{
let comparisonResult = ((ResponseData.compareWithDefault("tbs", memberValue.tbs)) &&
(ResponseData.compareWithDefault("responderID", memberValue.responderID)) &&
(ResponseData.compareWithDefault("producedAt", memberValue.producedAt)) &&
(ResponseData.compareWithDefault("responses", memberValue.responses)));
if("responseExtensions" in memberValue)
comparisonResult = comparisonResult && (ResponseData.compareWithDefault("responseExtensions", memberValue.responseExtensions));
return comparisonResult;
}
case "signatureAlgorithm":
return ((memberValue.algorithmId === "") && (("algorithmParams" in memberValue) === false));
case "signature":
return (memberValue.isEqual(BasicOCSPResponse.defaultValues(memberName)));
case "certs":
return (memberValue.length === 0);
default:
throw new Error(`Invalid member name for BasicOCSPResponse class: ${memberName}`);
}
}
//**********************************************************************************
/**
* Return value of asn1js schema for current class
* @param {Object} parameters Input parameters for the schema
* @returns {Object} asn1js schema object
*/
static schema(parameters = {})
{
//BasicOCSPResponse ::= SEQUENCE {
// tbsResponseData ResponseData,
// signatureAlgorithm AlgorithmIdentifier,
// signature BIT STRING,
// certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
/**
* @type {Object}
* @property {string} [blockName]
* @property {string} [tbsResponseData]
* @property {string} [signatureAlgorithm]
* @property {string} [signature]
* @property {string} [certs]
*/
const names = getParametersValue(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || "BasicOCSPResponse"),
value: [
ResponseData.schema(names.tbsResponseData || {
names: {
blockName: "BasicOCSPResponse.tbsResponseData"
}
}),
AlgorithmIdentifier.schema(names.signatureAlgorithm || {
names: {
blockName: "BasicOCSPResponse.signatureAlgorithm"
}
}),
new asn1js.BitString({ name: (names.signature || "BasicOCSPResponse.signature") }),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Sequence({
value: [new asn1js.Repeated({
name: "BasicOCSPResponse.certs",
value: Certificate.schema(names.certs || {})
})]
})
]
})
]
}));
}
//**********************************************************************************
/**
* Convert parsed asn1js object into current class
* @param {!Object} schema
*/
fromSchema(schema)
{
//region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
BasicOCSPResponse.schema()
);
Iif(asn1.verified === false)
throw new Error("Object's schema was not verified against input data for OCSP_BASIC_RESPONSE");
//endregion
//region Get internal properties from parsed schema
this.tbsResponseData = new ResponseData({ schema: asn1.result["BasicOCSPResponse.tbsResponseData"] });
this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result["BasicOCSPResponse.signatureAlgorithm"] });
this.signature = asn1.result["BasicOCSPResponse.signature"];
Eif("BasicOCSPResponse.certs" in asn1.result)
this.certs = Array.from(asn1.result["BasicOCSPResponse.certs"], element => new Certificate({ schema: element }));
//endregion
}
//**********************************************************************************
/**
* Convert current object to asn1js object and set correct values
* @returns {Object} asn1js object
*/
toSchema()
{
//region Create array for output sequence
const outputArray = [];
outputArray.push(this.tbsResponseData.toSchema());
outputArray.push(this.signatureAlgorithm.toSchema());
outputArray.push(this.signature);
//region Create array of certificates
Eif("certs" in this)
{
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Sequence({
value: Array.from(this.certs, element => element.toSchema())
})
]
}));
}
//endregion
//endregion
//region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//endregion
}
//**********************************************************************************
/**
* Convertion for the class to JSON object
* @returns {Object}
*/
toJSON()
{
const _object = {
tbsResponseData: this.tbsResponseData.toJSON(),
signatureAlgorithm: this.signatureAlgorithm.toJSON(),
signature: this.signature.toJSON()
};
if("certs" in this)
_object.certs = Array.from(this.certs, element => element.toJSON());
return _object;
}
//**********************************************************************************
/**
* Get OCSP response status for specific certificate
* @param {Certificate} certificate Certificate to be checked
* @param {Certificate} issuerCertificate Certificate of issuer for certificate to be checked
* @returns {Promise}
*/
getCertificateStatus(certificate, issuerCertificate)
{
//region Initial variables
let sequence = Promise.resolve();
const result = {
isForCertificate: false,
status: 2 // 0 = good, 1 = revoked, 2 = unknown
};
const hashesObject = {};
const certIDs = [];
const certIDPromises = [];
//endregion
//region Create all "certIDs" for input certificates
for(const response of this.tbsResponseData.responses)
{
const hashAlgorithm = getAlgorithmByOID(response.certID.hashAlgorithm.algorithmId);
if(("name" in hashAlgorithm) === false)
return Promise.reject(`Wrong CertID hashing algorithm: ${response.certID.hashAlgorithm.algorithmId}`);
if((hashAlgorithm.name in hashesObject) === false)
{
hashesObject[hashAlgorithm.name] = 1;
const certID = new CertID();
certIDs.push(certID);
certIDPromises.push(certID.createForCertificate(certificate, {
hashAlgorithm: hashAlgorithm.name,
issuerCertificate
}));
}
}
sequence = sequence.then(() =>
Promise.all(certIDPromises)
);
//endregion
//region Compare all response's "certIDs" with identifiers for input certificate
sequence = sequence.then(() =>
{
for(const response of this.tbsResponseData.responses)
{
for(const id of certIDs)
{
if(response.certID.isEqual(id))
{
result.isForCertificate = true;
try
{
switch(response.certStatus.idBlock.isConstructed)
{
case true:
if(response.certStatus.idBlock.tagNumber === 1)
result.status = 1; // revoked
break;
case false:
switch(response.certStatus.idBlock.tagNumber)
{
case 0: // good
result.status = 0;
break;
case 2: // unknown
result.status = 2;
break;
default:
}
break;
default:
}
}
catch(ex)
{
}
return result;
}
}
}
return result;
});
//endregion
return sequence;
}
//**********************************************************************************
/**
* Make signature for current OCSP Basic Response
* @param {Object} privateKey Private key for "subjectPublicKeyInfo" structure
* @param {string} [hashAlgorithm="SHA-1"] Hashing algorithm. Default SHA-1
* @returns {Promise}
*/
sign(privateKey, hashAlgorithm = "SHA-1")
{
//region Initial checking
//region Get a private key from function parameter
Iif(typeof privateKey === "undefined")
return Promise.reject("Need to provide a private key for signing");
//endregion
//endregion
//region Initial variables
let sequence = Promise.resolve();
let parameters;
const engine = getEngine();
//endregion
//region Get a "default parameters" for current algorithm and set correct signature algorithm
sequence = sequence.then(() => engine.subtle.getSignatureParameters(privateKey, hashAlgorithm));
sequence = sequence.then(result =>
{
parameters = result.parameters;
this.signatureAlgorithm = result.signatureAlgorithm;
});
//endregion
//region Create TBS data for signing
sequence = sequence.then(() =>
{
this.tbsResponseData.tbs = this.tbsResponseData.toSchema(true).toBER(false);
});
//endregion
//region Signing TBS data on provided private key
sequence = sequence.then(() => engine.subtle.signWithPrivateKey(this.tbsResponseData.tbs, privateKey, parameters));
sequence = sequence.then(result =>
{
this.signature = new asn1js.BitString({ valueHex: result });
});
//endregion
return sequence;
}
//**********************************************************************************
/**
* Verify existing OCSP Basic Response
* @param {Object} parameters Additional parameters
* @returns {Promise}
*/
verify(parameters = {})
{
//region Check amount of certificates
Iif(("certs" in this) === false)
return Promise.reject("No certificates attached to the BasicOCSPResponce");
//endregion
//region Global variables (used in "promises")
let signerCert = null;
const tbsView = new Uint8Array(this.tbsResponseData.tbs);
let certIndex = -1;
let sequence = Promise.resolve();
let shaAlgorithm = "";
let trustedCerts = [];
//endregion
//region Get input values
Eif("trustedCerts" in parameters)
trustedCerts = parameters.trustedCerts;
//endregion
//region Get a "crypto" extension
const crypto = getCrypto();
Iif(typeof crypto === "undefined")
return Promise.reject("Unable to create WebCrypto object");
//endregion
//region Find a correct hashing algorithm
shaAlgorithm = getHashAlgorithm(this.signatureAlgorithm);
Iif(shaAlgorithm === "")
return Promise.reject(`Unsupported signature algorithm: ${this.signatureAlgorithm.algorithmId}`);
//endregion
//region Find correct value for "responderID"
let responderType = 0;
let responderId = {};
Eif(this.tbsResponseData.responderID instanceof RelativeDistinguishedNames) // [1] Name
{
responderType = 0;
responderId = this.tbsResponseData.responderID;
}
else
{
if(this.tbsResponseData.responderID instanceof asn1js.OctetString) // [2] KeyHash
{
responderType = 1;
responderId = this.tbsResponseData.responderID;
}
else
return Promise.reject("Wrong value for responderID");
}
//endregion
//region Compare responderID with all certificates one-by-one
Eif(responderType === 0) // By Name
{
sequence = sequence.then(() =>
{
for(const [index, certificate] of this.certs.entries())
{
Eif(certificate.subject.isEqual(responderId))
{
certIndex = index;
break;
}
}
});
}
else // By KeyHash
{
sequence = sequence.then(() => Promise.all(Array.from(this.certs, element =>
crypto.digest({ name: "sha-1" }, new Uint8Array(element.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHex)))).then(results =>
{
for(const [index, certificate] of this.certs.entries())
{
if(isEqualBuffer(results[index], responderId.valueBlock.valueHex))
{
certIndex = index;
break;
}
}
}));
}
//endregion
//region Make additional verification for signer's certificate
/**
* Check CA flag for the certificate
* @param {Certificate} cert Certificate to find CA flag for
* @returns {*}
*/
function checkCA(cert)
{
//region Do not include signer's certificate
Eif((cert.issuer.isEqual(signerCert.issuer) === true) && (cert.serialNumber.isEqual(signerCert.serialNumber) === true))
return null;
//endregion
let isCA = false;
for(const extension of cert.extensions)
{
if(extension.extnID === "2.5.29.19") // BasicConstraints
{
if("cA" in extension.parsedValue)
{
if(extension.parsedValue.cA === true)
isCA = true;
}
}
}
if(isCA)
return cert;
return null;
}
sequence = sequence.then(() =>
{
Iif(certIndex === (-1))
return Promise.reject("Correct certificate was not found in OCSP response");
signerCert = this.certs[certIndex];
return Promise.all(Array.from(this.certs, element => checkCA(element))).then(promiseResults =>
{
const additionalCerts = [];
additionalCerts.push(signerCert);
for(const promiseResult of promiseResults)
{
Iif(promiseResult !== null)
additionalCerts.push(promiseResult);
}
const certChain = new CertificateChainValidationEngine({
certs: additionalCerts,
trustedCerts
});
return certChain.verify().then(verificationResult =>
{
Eif(verificationResult.result === true)
return Promise.resolve();
return Promise.reject("Validation of signer's certificate failed");
}, error =>
Promise.reject(`Validation of signer's certificate failed with error: ${((error instanceof Object) ? error.resultMessage : error)}`)
);
}, promiseError =>
Promise.reject(`Error during checking certificates for CA flag: ${promiseError}`)
);
});
//endregion
//region Import public key from responder certificate
sequence = sequence.then(() =>
{
//region Get information about public key algorithm and default parameters for import
let algorithmId;
if(this.certs[certIndex].signatureAlgorithm.algorithmId === "1.2.840.113549.1.1.10")
algorithmId = this.certs[certIndex].signatureAlgorithm.algorithmId;
else
algorithmId = this.certs[certIndex].subjectPublicKeyInfo.algorithm.algorithmId;
const algorithmObject = getAlgorithmByOID(algorithmId);
Iif(("name" in algorithmObject) === false)
return Promise.reject(`Unsupported public key algorithm: ${algorithmId}`);
const algorithmName = algorithmObject.name;
const algorithm = getAlgorithmParameters(algorithmName, "importkey");
if("hash" in algorithm.algorithm)
algorithm.algorithm.hash.name = shaAlgorithm;
//region Special case for ECDSA
if(algorithmName === "ECDSA")
{
//region Get information about named curve
Iif((this.certs[certIndex].subjectPublicKeyInfo.algorithm.algorithmParams instanceof asn1js.ObjectIdentifier) === false)
return Promise.reject("Incorrect type for ECDSA public key parameters");
const curveObject = getAlgorithmByOID(this.certs[certIndex].subjectPublicKeyInfo.algorithm.algorithmParams.valueBlock.toString());
Iif(("name" in curveObject) === false)
return Promise.reject(`Unsupported named curve algorithm: ${this.certs[certIndex].subjectPublicKeyInfo.algorithm.algorithmParams.valueBlock.toString()}`);
//endregion
algorithm.algorithm.namedCurve = curveObject.name;
}
//endregion
//endregion
const publicKeyInfoSchema = this.certs[certIndex].subjectPublicKeyInfo.toSchema();
const publicKeyInfoBuffer = publicKeyInfoSchema.toBER(false);
const publicKeyInfoView = new Uint8Array(publicKeyInfoBuffer);
return crypto.importKey("spki", publicKeyInfoView, algorithm.algorithm, true, algorithm.usages);
});
//endregion
//region Verifying TBS part of BasicOCSPResponce
sequence = sequence.then(publicKey =>
{
//region Get default algorithm parameters for verification
const algorithm = getAlgorithmParameters(publicKey.algorithm.name, "verify");
Eif("hash" in algorithm.algorithm)
algorithm.algorithm.hash.name = shaAlgorithm;
//endregion
//region Special case for ECDSA signatures
let signatureValue = this.signature.valueBlock.valueHex;
if(publicKey.algorithm.name === "ECDSA")
{
const asn1 = asn1js.fromBER(signatureValue);
signatureValue = createECDSASignatureFromCMS(asn1.result);
}
//endregion
//region Special case for RSA-PSS
if(publicKey.algorithm.name === "RSA-PSS")
{
let pssParameters;
try
{
pssParameters = new RSASSAPSSParams({ schema: this.signatureAlgorithm.algorithmParams });
}
catch(ex)
{
return Promise.reject(ex);
}
Eif("saltLength" in pssParameters)
algorithm.algorithm.saltLength = pssParameters.saltLength;
else
algorithm.algorithm.saltLength = 20;
let hashAlgo = "SHA-1";
Eif("hashAlgorithm" in pssParameters)
{
const hashAlgorithm = getAlgorithmByOID(pssParameters.hashAlgorithm.algorithmId);
Iif(("name" in hashAlgorithm) === false)
return Promise.reject(`Unrecognized hash algorithm: ${pssParameters.hashAlgorithm.algorithmId}`);
hashAlgo = hashAlgorithm.name;
}
algorithm.algorithm.hash.name = hashAlgo;
}
//endregion
return crypto.verify(algorithm.algorithm,
publicKey,
new Uint8Array(signatureValue),
tbsView);
});
//endregion
return sequence;
}
//**********************************************************************************
}
//**************************************************************************************
|