All files / src PFX.js

59.01% Statements 95/161
42.45% Branches 45/106
61.54% Functions 16/26
59.01% Lines 95/161

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                                                                  19x         19x   19x             19x         11x       19x 8x                   49x     19x   19x       11x                                                                                                     8x   8x                                                   8x                                     8x         8x 8x   8x 8x                     11x         11x 10x   11x                                                           11x     11x     11x         11x       11x 11x           11x       11x           10x     10x     10x     10x         10x 10x   10x   10x 10x   10x             10x   10x     10x 10x                     10x     10x                               10x           1x     1x     1x                 1x       1x                       1x 1x         1x       1x       1x               1x               1x                 1x                                     1x 1x         1x     1x                 1x                 11x           8x     8x         8x       8x 8x         8x   8x           8x         8x       8x         8x   8x           8x       8x 8x         8x       8x     7x         7x 7x         7x   7x 7x                       7x     7x                 8x                                                                                                                                   8x 8x                
import * as asn1js from "asn1js";
import { getParametersValue, utilConcatBuf } from "pvutils";
import { getCrypto, getEngine, getRandomValues, getOIDByAlgorithm, getAlgorithmByOID } from "./common.js";
import ContentInfo from "./ContentInfo.js";
import MacData from "./MacData.js";
import DigestInfo from "./DigestInfo.js";
import AlgorithmIdentifier from "./AlgorithmIdentifier.js";
import SignedData from "./SignedData.js";
import EncapsulatedContentInfo from "./EncapsulatedContentInfo.js";
import Attribute from "./Attribute.js";
import SignerInfo from "./SignerInfo.js";
import IssuerAndSerialNumber from "./IssuerAndSerialNumber.js";
import SignedAndUnsignedAttributes from "./SignedAndUnsignedAttributes.js";
import AuthenticatedSafe from "./AuthenticatedSafe.js";
//**************************************************************************************
/**
 * Class from RFC7292
 */
export default class PFX 
{
	//**********************************************************************************
	/**
	 * Constructor for PFX class
	 * @param {Object} [parameters={}]
	 * @property {Object} [schema] asn1js parsed value
	 */
	constructor(parameters = {})
	{
		//region Internal properties of the object
		/**
		 * @type {number}
		 * @description version
		 */
		this.version = getParametersValue(parameters, "version", PFX.defaultValues("version"));
		/**
		 * @type {ContentInfo}
		 * @description authSafe
		 */
		this.authSafe = getParametersValue(parameters, "authSafe", PFX.defaultValues("authSafe"));
		
		Iif("macData" in parameters)
			/**
			 * @type {MacData}
			 * @description macData
			 */
			this.macData = getParametersValue(parameters, "macData", PFX.defaultValues("macData"));
		
		if("parsedValue" in parameters)
			/**
			 * @type {*}
			 * @description parsedValue
			 */
			this.parsedValue = getParametersValue(parameters, "parsedValue", PFX.defaultValues("parsedValue"));
		//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 "version":
				return 3;
			case "authSafe":
				return (new ContentInfo());
			case "macData":
				return (new MacData());
			case "parsedValue":
				return {};
			default:
				throw new Error(`Invalid member name for PFX 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 "version":
				return (memberValue === PFX.defaultValues(memberName));
			case "authSafe":
				return ((ContentInfo.compareWithDefault("contentType", memberValue.contentType)) &&
				(ContentInfo.compareWithDefault("content", memberValue.content)));
			case "macData":
				return ((MacData.compareWithDefault("mac", memberValue.mac)) &&
				(MacData.compareWithDefault("macSalt", memberValue.macSalt)) &&
				(MacData.compareWithDefault("iterations", memberValue.iterations)));
			case "parsedValue":
				return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0));
			default:
				throw new Error(`Invalid member name for PFX 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 = {})
	{
		//PFX ::= SEQUENCE {
		//    version		INTEGER {v3(3)}(v3,...),
		//    authSafe	ContentInfo,
		//    macData    	MacData OPTIONAL
		//}
		
		/**
		 * @type {Object}
		 * @property {string} [blockName]
		 * @property {string} [version]
		 * @property {string} [authSafe]
		 * @property {string} [macData]
		 */
		const names = getParametersValue(parameters, "names", {});
		
		return (new asn1js.Sequence({
			name: (names.blockName || ""),
			value: [
				new asn1js.Integer({ name: (names.version || "version") }),
				ContentInfo.schema(names.authSafe || {
					names: {
						blockName: "authSafe"
					}
				}),
				MacData.schema(names.macData || {
					names: {
						blockName: "macData",
						optional: true
					}
				})
			]
		}));
	}
	//**********************************************************************************
	/**
	 * Convert parsed asn1js object into current class
	 * @param {!Object} schema
	 */
	fromSchema(schema)
	{
		//region Check the schema is valid
		const asn1 = asn1js.compareSchema(schema,
			schema,
			PFX.schema({
				names: {
					version: "version",
					authSafe: {
						names: {
							blockName: "authSafe"
						}
					},
					macData: {
						names: {
							blockName: "macData"
						}
					}
				}
			})
		);
		
		Iif(asn1.verified === false)
			throw new Error("Object's schema was not verified against input data for PFX");
		//endregion
		
		//region Get internal properties from parsed schema
		this.version = asn1.result.version.valueBlock.valueDec;
		this.authSafe = new ContentInfo({ schema: asn1.result.authSafe });
		
		Eif("macData" in asn1.result)
			this.macData = new MacData({ schema: asn1.result.macData });
		//endregion
	}
	//**********************************************************************************
	/**
	 * Convert current object to asn1js object and set correct values
	 * @returns {Object} asn1js object
	 */
	toSchema()
	{
		//region Construct and return new ASN.1 schema for this object
		const outputArray = [
			new asn1js.Integer({ value: this.version }),
			this.authSafe.toSchema()
		];
		
		if("macData" in this)
			outputArray.push(this.macData.toSchema());
		
		return (new asn1js.Sequence({
			value: outputArray
		}));
		//endregion
	}
	//**********************************************************************************
	/**
	 * Convertion for the class to JSON object
	 * @returns {Object}
	 */
	toJSON()
	{
		const output = {
			version: this.version,
			authSafe: this.authSafe.toJSON()
		};
		
		if("macData" in this)
			output.macData = this.macData.toJSON();
		
		return output;
	}
	//**********************************************************************************
	/**
	 * Making ContentInfo from "parsedValue" object
	 * @param {Object} parameters Parameters, specific to each "integrity mode"
	 */
	makeInternalValues(parameters = {})
	{
		//region Check mandatory parameter
		Iif((parameters instanceof Object) === false)
			return Promise.reject("The \"parameters\" must has \"Object\" type");
		
		Iif(("parsedValue" in this) === false)
			return Promise.reject("Please call \"parseValues\" function first in order to make \"parsedValue\" data");
		
		Iif(("integrityMode" in this.parsedValue) === false)
			return Promise.reject("Absent mandatory parameter \"integrityMode\" inside \"parsedValue\"");
		//endregion
		
		//region Initial variables
		let sequence = Promise.resolve();
		//endregion
		
		//region Get a "crypto" extension
		const crypto = getCrypto();
		Iif(typeof crypto === "undefined")
			return Promise.reject("Unable to create WebCrypto object");
		//endregion
		
		//region Makes values for each particular integrity mode
		//region Check that we do have neccessary fields in "parsedValue" object
		Iif(("authenticatedSafe" in this.parsedValue) === false)
			return Promise.reject("Absent mandatory parameter \"authenticatedSafe\" in \"parsedValue\"");
		//endregion
		
		switch(this.parsedValue.integrityMode)
		{
			//region HMAC-based integrity
			case 0:
				{
					//region Check additional mandatory parameters
					Iif(("iterations" in parameters) === false)
						return Promise.reject("Absent mandatory parameter \"iterations\"");
				
					Iif(("pbkdf2HashAlgorithm" in parameters) === false)
						return Promise.reject("Absent mandatory parameter \"pbkdf2HashAlgorithm\"");
				
					Iif(("hmacHashAlgorithm" in parameters) === false)
						return Promise.reject("Absent mandatory parameter \"hmacHashAlgorithm\"");
				
					Iif(("password" in parameters) === false)
						return Promise.reject("Absent mandatory parameter \"password\"");
					//endregion
				
					//region Initial variables
					const saltBuffer = new ArrayBuffer(64);
					const saltView = new Uint8Array(saltBuffer);
				
					getRandomValues(saltView);
					
					const data = this.parsedValue.authenticatedSafe.toSchema().toBER(false);
					const view = new Uint8Array(data);
 
					this.authSafe = new ContentInfo({
						contentType: "1.2.840.113549.1.7.1",
						content: new asn1js.OctetString({ valueHex: data })
					});
					//endregion
					
					//region Call current crypto engine for making HMAC-based data stamp
					const engine = getEngine();
					
					Iif(("stampDataWithPassword" in engine.subtle) === false)
						return Promise.reject(`No support for \"stampDataWithPassword\" in current engine \"${engine.name}\"`);
					
					sequence = sequence.then(() =>
						engine.subtle.stampDataWithPassword({
							password: parameters.password,
							hashAlgorithm: parameters.hmacHashAlgorithm,
							salt: saltBuffer,
							iterationCount: parameters.iterations,
							contentToStamp: data
						})
					);
					//endregion
					
					//region Make "MacData" values
					sequence = sequence.then(
						result =>
						{
							this.macData = new MacData({
								mac: new DigestInfo({
									digestAlgorithm: new AlgorithmIdentifier({
										algorithmId: getOIDByAlgorithm({ name: parameters.hmacHashAlgorithm })
									}),
									digest: new asn1js.OctetString({ valueHex: result })
								}),
								macSalt: new asn1js.OctetString({ valueHex: saltBuffer }),
								iterations: parameters.iterations
							});
						},
					error => Promise.reject(error)
					);
					//endregion
					//endregion
				}
				break;
			//endregion
			//region publicKey-based integrity
			case 1:
				{
					//region Check additional mandatory parameters
					Iif(("signingCertificate" in parameters) === false)
						return Promise.reject("Absent mandatory parameter \"signingCertificate\"");
				
					Iif(("privateKey" in parameters) === false)
						return Promise.reject("Absent mandatory parameter \"privateKey\"");
				
					Iif(("hashAlgorithm" in parameters) === false)
						return Promise.reject("Absent mandatory parameter \"hashAlgorithm\"");
					//endregion
				
					//region Making data to be signed
					// NOTE: all internal data for "authenticatedSafe" must be already prepared.
					// Thus user must call "makeValues" for all internal "SafeContent" value with appropriate parameters.
					// Or user can choose to use values from initial parsing of existing PKCS#12 data.
				
					const toBeSigned = this.parsedValue.authenticatedSafe.toSchema().toBER(false);
					//endregion
					
					//region Initial variables
					const cmsSigned = new SignedData({
						version: 1,
						encapContentInfo: new EncapsulatedContentInfo({
							eContentType: "1.2.840.113549.1.7.1", // "data" content type
							eContent: new asn1js.OctetString({ valueHex: toBeSigned })
						}),
						certificates: [parameters.signingCertificate]
					});
					//endregion
					
					//region Making additional attributes for CMS Signed Data
					//region Create a message digest
					sequence = sequence.then(
						() => crypto.digest({ name: parameters.hashAlgorithm }, new Uint8Array(toBeSigned))
					);
					//endregion
				
					//region Combine all signed extensions
					sequence = sequence.then(
						result =>
						{
							//region Initial variables
							const signedAttr = [];
							//endregion
							
							//region contentType
							signedAttr.push(new Attribute({
								type: "1.2.840.113549.1.9.3",
								values: [
									new asn1js.ObjectIdentifier({ value: "1.2.840.113549.1.7.1" })
								]
							}));
							//endregion
							//region signingTime
							signedAttr.push(new Attribute({
								type: "1.2.840.113549.1.9.5",
								values: [
									new asn1js.UTCTime({ valueDate: new Date() })
								]
							}));
							//endregion
							//region messageDigest
							signedAttr.push(new Attribute({
								type: "1.2.840.113549.1.9.4",
								values: [
									new asn1js.OctetString({ valueHex: result })
								]
							}));
							//endregion
							
							//region Making final value for "SignerInfo" type
							cmsSigned.signerInfos.push(new SignerInfo({
								version: 1,
								sid: new IssuerAndSerialNumber({
									issuer: parameters.signingCertificate.issuer,
									serialNumber: parameters.signingCertificate.serialNumber
								}),
								signedAttrs: new SignedAndUnsignedAttributes({
									type: 0,
									attributes: signedAttr
								})
							}));
							//endregion
						},
						error => Promise.reject(`Error during making digest for message: ${error}`)
					);
					//endregion
					//endregion
				
					//region Signing CMS Signed Data
					sequence = sequence.then(
						() => cmsSigned.sign(parameters.privateKey, 0, parameters.hashAlgorithm)
					);
					//endregion
				
					//region Making final CMS_CONTENT_INFO type
					sequence = sequence.then(
						() =>
						{
							this.authSafe = new ContentInfo({
								contentType: "1.2.840.113549.1.7.2",
								content: cmsSigned.toSchema(true)
							});
						},
						error => Promise.reject(`Error during making signature: ${error}`)
					);
					//endregion
				}
				break;
			//endregion
			//region default
			default:
				return Promise.reject(`Parameter \"integrityMode\" has unknown value: ${parameters.integrityMode}`);
			//endregion
		}
		//endregion
		
		return sequence;
	}
	//**********************************************************************************
	parseInternalValues(parameters)
	{
		//region Check input data from "parameters" 
		Iif((parameters instanceof Object) === false)
			return Promise.reject("The \"parameters\" must has \"Object\" type");
		
		Iif(("checkIntegrity" in parameters) === false)
			parameters.checkIntegrity = true;
		//endregion 
		
		//region Initial variables 
		let sequence = Promise.resolve();
		//endregion 
		
		//region Get a "crypto" extension 
		const crypto = getCrypto();
		Iif(typeof crypto === "undefined")
			return Promise.reject("Unable to create WebCrypto object");
		//endregion 
		
		//region Create value for "this.parsedValue.authenticatedSafe" and check integrity 
		this.parsedValue = {};
		
		switch(this.authSafe.contentType)
		{
			//region data 
			case "1.2.840.113549.1.7.1":
				{
					//region Check additional mandatory parameters
					Iif(("password" in parameters) === false)
						return Promise.reject("Absent mandatory parameter \"password\"");
					//endregion
				
					//region Integrity based on HMAC
					this.parsedValue.integrityMode = 0;
					//endregion
				
					//region Check that we do have OCTETSTRING as "content"
					Iif((this.authSafe.content instanceof asn1js.OctetString) === false)
						return Promise.reject("Wrong type of \"this.authSafe.content\"");
					//endregion
					
					//region Check we have "constructive encoding" for AuthSafe content
					let authSafeContent = new ArrayBuffer(0);
					
					Iif(this.authSafe.content.valueBlock.isConstructed)
					{
						for(const contentValue of this.authSafe.content.valueBlock.value)
							authSafeContent = utilConcatBuf(authSafeContent, contentValue.valueBlock.valueHex);
					}
					else
						authSafeContent = this.authSafe.content.valueBlock.valueHex;
					//endregion
					
					//region Parse internal ASN.1 data
					const asn1 = asn1js.fromBER(authSafeContent);
					Iif(asn1.offset === (-1))
						return Promise.reject("Error during parsing of ASN.1 data inside \"this.authSafe.content\"");
					//endregion
				
					//region Set "authenticatedSafe" value
					this.parsedValue.authenticatedSafe = new AuthenticatedSafe({ schema: asn1.result });
					//endregion
				
					//region Check integrity
					if(parameters.checkIntegrity)
					{
						//region Check that "MacData" exists
						Iif(("macData" in this) === false)
							return Promise.reject("Absent \"macData\" value, can not check PKCS#12 data integrity");
						//endregion
						
						//region Initial variables
						const hashAlgorithm = getAlgorithmByOID(this.macData.mac.digestAlgorithm.algorithmId);
						Iif(("name" in hashAlgorithm) === false)
							return Promise.reject(`Unsupported digest algorithm: ${this.macData.mac.digestAlgorithm.algorithmId}`);
						//endregion
						
						//region Call current crypto engine for verifying HMAC-based data stamp
						const engine = getEngine();
						
						sequence = sequence.then(() =>
							engine.subtle.verifyDataStampedWithPassword({
								password: parameters.password,
								hashAlgorithm: hashAlgorithm.name,
								salt: this.macData.macSalt.valueBlock.valueHex,
								iterationCount: this.macData.iterations,
								contentToVerify: authSafeContent,
								signatureToVerify: this.macData.mac.digest.valueBlock.valueHex
							})
						);
						//endregion
 
						//region Verify HMAC signature
						sequence = sequence.then(
							result =>
							{
								Iif(result === false)
									return Promise.reject("Integrity for the PKCS#12 data is broken!");
							},
							error => Promise.reject(error)
						);
						//endregion
					}
					//endregion
				}
				break;
			//endregion 
			//region signedData 
			case "1.2.840.113549.1.7.2":
				{
					//region Integrity based on signature using public key
					this.parsedValue.integrityMode = 1;
					//endregion
				
					//region Parse CMS Signed Data
					const cmsSigned = new SignedData({ schema: this.authSafe.content });
					//endregion
				
					//region Check that we do have OCTETSTRING as "content"
					if(("eContent" in cmsSigned.encapContentInfo) === false)
						return Promise.reject("Absent of attached data in \"cmsSigned.encapContentInfo\"");
				
					if((cmsSigned.encapContentInfo.eContent instanceof asn1js.OctetString) === false)
						return Promise.reject("Wrong type of \"cmsSigned.encapContentInfo.eContent\"");
					//endregion
				
					//region Create correct data block for verification
					let data = new ArrayBuffer(0);
				
					if(cmsSigned.encapContentInfo.eContent.idBlock.isConstructed === false)
						data = cmsSigned.encapContentInfo.eContent.valueBlock.valueHex;
					else
					{
						for(let i = 0; i < cmsSigned.encapContentInfo.eContent.valueBlock.value.length; i++)
							data = utilConcatBuf(data, cmsSigned.encapContentInfo.eContent.valueBlock.value[i].valueBlock.valueHex);
					}
					//endregion
				
					//region Parse internal ASN.1 data
					const asn1 = asn1js.fromBER(data);
					if(asn1.offset === (-1))
						return Promise.reject("Error during parsing of ASN.1 data inside \"this.authSafe.content\"");
					//endregion
				
					//region Set "authenticatedSafe" value
					this.parsedValue.authenticatedSafe = new AuthenticatedSafe({ schema: asn1.result });
					//endregion
				
					//region Check integrity
					sequence = sequence.then(
						() => cmsSigned.verify({ signer: 0, checkChain: false })
					).then(
						result =>
						{
							if(result === false)
								return Promise.reject("Integrity for the PKCS#12 data is broken!");
						},
						error => Promise.reject(`Error during integrity verification: ${error}`)
					);
					//endregion
				}
				break;
			//endregion   
			//region default 
			default:
				return Promise.reject(`Incorrect value for \"this.authSafe.contentType\": ${this.authSafe.contentType}`);
			//endregion 
		}
		//endregion 
		
		//region Return result of the function 
		return sequence.then(
			() => this,
			error => Promise.reject(`Error during parsing: ${error}`)
		);
		//endregion   
	}
	//**********************************************************************************
}
//**************************************************************************************