You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1257 lines
39 KiB

4 years ago
  1. /**
  2. * Javascript implementation of PKCS#7 v1.5.
  3. *
  4. * @author Stefan Siegl
  5. * @author Dave Longley
  6. *
  7. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  8. * Copyright (c) 2012-2015 Digital Bazaar, Inc.
  9. *
  10. * Currently this implementation only supports ContentType of EnvelopedData,
  11. * EncryptedData, or SignedData at the root level. The top level elements may
  12. * contain only a ContentInfo of ContentType Data, i.e. plain data. Further
  13. * nesting is not (yet) supported.
  14. *
  15. * The Forge validators for PKCS #7's ASN.1 structures are available from
  16. * a separate file pkcs7asn1.js, since those are referenced from other
  17. * PKCS standards like PKCS #12.
  18. */
  19. var forge = require('./forge');
  20. require('./aes');
  21. require('./asn1');
  22. require('./des');
  23. require('./oids');
  24. require('./pem');
  25. require('./pkcs7asn1');
  26. require('./random');
  27. require('./util');
  28. require('./x509');
  29. // shortcut for ASN.1 API
  30. var asn1 = forge.asn1;
  31. // shortcut for PKCS#7 API
  32. var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {};
  33. /**
  34. * Converts a PKCS#7 message from PEM format.
  35. *
  36. * @param pem the PEM-formatted PKCS#7 message.
  37. *
  38. * @return the PKCS#7 message.
  39. */
  40. p7.messageFromPem = function(pem) {
  41. var msg = forge.pem.decode(pem)[0];
  42. if(msg.type !== 'PKCS7') {
  43. var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +
  44. 'header type is not "PKCS#7".');
  45. error.headerType = msg.type;
  46. throw error;
  47. }
  48. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  49. throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');
  50. }
  51. // convert DER to ASN.1 object
  52. var obj = asn1.fromDer(msg.body);
  53. return p7.messageFromAsn1(obj);
  54. };
  55. /**
  56. * Converts a PKCS#7 message to PEM format.
  57. *
  58. * @param msg The PKCS#7 message object
  59. * @param maxline The maximum characters per line, defaults to 64.
  60. *
  61. * @return The PEM-formatted PKCS#7 message.
  62. */
  63. p7.messageToPem = function(msg, maxline) {
  64. // convert to ASN.1, then DER, then PEM-encode
  65. var pemObj = {
  66. type: 'PKCS7',
  67. body: asn1.toDer(msg.toAsn1()).getBytes()
  68. };
  69. return forge.pem.encode(pemObj, {maxline: maxline});
  70. };
  71. /**
  72. * Converts a PKCS#7 message from an ASN.1 object.
  73. *
  74. * @param obj the ASN.1 representation of a ContentInfo.
  75. *
  76. * @return the PKCS#7 message.
  77. */
  78. p7.messageFromAsn1 = function(obj) {
  79. // validate root level ContentInfo and capture data
  80. var capture = {};
  81. var errors = [];
  82. if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {
  83. var error = new Error('Cannot read PKCS#7 message. ' +
  84. 'ASN.1 object is not an PKCS#7 ContentInfo.');
  85. error.errors = errors;
  86. throw error;
  87. }
  88. var contentType = asn1.derToOid(capture.contentType);
  89. var msg;
  90. switch(contentType) {
  91. case forge.pki.oids.envelopedData:
  92. msg = p7.createEnvelopedData();
  93. break;
  94. case forge.pki.oids.encryptedData:
  95. msg = p7.createEncryptedData();
  96. break;
  97. case forge.pki.oids.signedData:
  98. msg = p7.createSignedData();
  99. break;
  100. default:
  101. throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +
  102. contentType + ' is not (yet) supported.');
  103. }
  104. msg.fromAsn1(capture.content.value[0]);
  105. return msg;
  106. };
  107. p7.createSignedData = function() {
  108. var msg = null;
  109. msg = {
  110. type: forge.pki.oids.signedData,
  111. version: 1,
  112. certificates: [],
  113. crls: [],
  114. // TODO: add json-formatted signer stuff here?
  115. signers: [],
  116. // populated during sign()
  117. digestAlgorithmIdentifiers: [],
  118. contentInfo: null,
  119. signerInfos: [],
  120. fromAsn1: function(obj) {
  121. // validate SignedData content block and capture data.
  122. _fromAsn1(msg, obj, p7.asn1.signedDataValidator);
  123. msg.certificates = [];
  124. msg.crls = [];
  125. msg.digestAlgorithmIdentifiers = [];
  126. msg.contentInfo = null;
  127. msg.signerInfos = [];
  128. if(msg.rawCapture.certificates) {
  129. var certs = msg.rawCapture.certificates.value;
  130. for(var i = 0; i < certs.length; ++i) {
  131. msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]));
  132. }
  133. }
  134. // TODO: parse crls
  135. },
  136. toAsn1: function() {
  137. // degenerate case with no content
  138. if(!msg.contentInfo) {
  139. msg.sign();
  140. }
  141. var certs = [];
  142. for(var i = 0; i < msg.certificates.length; ++i) {
  143. certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));
  144. }
  145. var crls = [];
  146. // TODO: implement CRLs
  147. // [0] SignedData
  148. var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  149. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  150. // Version
  151. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  152. asn1.integerToDer(msg.version).getBytes()),
  153. // DigestAlgorithmIdentifiers
  154. asn1.create(
  155. asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  156. msg.digestAlgorithmIdentifiers),
  157. // ContentInfo
  158. msg.contentInfo
  159. ])
  160. ]);
  161. if(certs.length > 0) {
  162. // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL
  163. signedData.value[0].value.push(
  164. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));
  165. }
  166. if(crls.length > 0) {
  167. // [1] IMPLICIT CertificateRevocationLists OPTIONAL
  168. signedData.value[0].value.push(
  169. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));
  170. }
  171. // SignerInfos
  172. signedData.value[0].value.push(
  173. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  174. msg.signerInfos));
  175. // ContentInfo
  176. return asn1.create(
  177. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  178. // ContentType
  179. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  180. asn1.oidToDer(msg.type).getBytes()),
  181. // [0] SignedData
  182. signedData
  183. ]);
  184. },
  185. /**
  186. * Add (another) entity to list of signers.
  187. *
  188. * Note: If authenticatedAttributes are provided, then, per RFC 2315,
  189. * they must include at least two attributes: content type and
  190. * message digest. The message digest attribute value will be
  191. * auto-calculated during signing and will be ignored if provided.
  192. *
  193. * Here's an example of providing these two attributes:
  194. *
  195. * forge.pkcs7.createSignedData();
  196. * p7.addSigner({
  197. * issuer: cert.issuer.attributes,
  198. * serialNumber: cert.serialNumber,
  199. * key: privateKey,
  200. * digestAlgorithm: forge.pki.oids.sha1,
  201. * authenticatedAttributes: [{
  202. * type: forge.pki.oids.contentType,
  203. * value: forge.pki.oids.data
  204. * }, {
  205. * type: forge.pki.oids.messageDigest
  206. * }]
  207. * });
  208. *
  209. * TODO: Support [subjectKeyIdentifier] as signer's ID.
  210. *
  211. * @param signer the signer information:
  212. * key the signer's private key.
  213. * [certificate] a certificate containing the public key
  214. * associated with the signer's private key; use this option as
  215. * an alternative to specifying signer.issuer and
  216. * signer.serialNumber.
  217. * [issuer] the issuer attributes (eg: cert.issuer.attributes).
  218. * [serialNumber] the signer's certificate's serial number in
  219. * hexadecimal (eg: cert.serialNumber).
  220. * [digestAlgorithm] the message digest OID, as a string, to use
  221. * (eg: forge.pki.oids.sha1).
  222. * [authenticatedAttributes] an optional array of attributes
  223. * to also sign along with the content.
  224. */
  225. addSigner: function(signer) {
  226. var issuer = signer.issuer;
  227. var serialNumber = signer.serialNumber;
  228. if(signer.certificate) {
  229. var cert = signer.certificate;
  230. if(typeof cert === 'string') {
  231. cert = forge.pki.certificateFromPem(cert);
  232. }
  233. issuer = cert.issuer.attributes;
  234. serialNumber = cert.serialNumber;
  235. }
  236. var key = signer.key;
  237. if(!key) {
  238. throw new Error(
  239. 'Could not add PKCS#7 signer; no private key specified.');
  240. }
  241. if(typeof key === 'string') {
  242. key = forge.pki.privateKeyFromPem(key);
  243. }
  244. // ensure OID known for digest algorithm
  245. var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1;
  246. switch(digestAlgorithm) {
  247. case forge.pki.oids.sha1:
  248. case forge.pki.oids.sha256:
  249. case forge.pki.oids.sha384:
  250. case forge.pki.oids.sha512:
  251. case forge.pki.oids.md5:
  252. break;
  253. default:
  254. throw new Error(
  255. 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +
  256. digestAlgorithm);
  257. }
  258. // if authenticatedAttributes is present, then the attributes
  259. // must contain at least PKCS #9 content-type and message-digest
  260. var authenticatedAttributes = signer.authenticatedAttributes || [];
  261. if(authenticatedAttributes.length > 0) {
  262. var contentType = false;
  263. var messageDigest = false;
  264. for(var i = 0; i < authenticatedAttributes.length; ++i) {
  265. var attr = authenticatedAttributes[i];
  266. if(!contentType && attr.type === forge.pki.oids.contentType) {
  267. contentType = true;
  268. if(messageDigest) {
  269. break;
  270. }
  271. continue;
  272. }
  273. if(!messageDigest && attr.type === forge.pki.oids.messageDigest) {
  274. messageDigest = true;
  275. if(contentType) {
  276. break;
  277. }
  278. continue;
  279. }
  280. }
  281. if(!contentType || !messageDigest) {
  282. throw new Error('Invalid signer.authenticatedAttributes. If ' +
  283. 'signer.authenticatedAttributes is specified, then it must ' +
  284. 'contain at least two attributes, PKCS #9 content-type and ' +
  285. 'PKCS #9 message-digest.');
  286. }
  287. }
  288. msg.signers.push({
  289. key: key,
  290. version: 1,
  291. issuer: issuer,
  292. serialNumber: serialNumber,
  293. digestAlgorithm: digestAlgorithm,
  294. signatureAlgorithm: forge.pki.oids.rsaEncryption,
  295. signature: null,
  296. authenticatedAttributes: authenticatedAttributes,
  297. unauthenticatedAttributes: []
  298. });
  299. },
  300. /**
  301. * Signs the content.
  302. * @param options Options to apply when signing:
  303. * [detached] boolean. If signing should be done in detached mode. Defaults to false.
  304. */
  305. sign: function(options) {
  306. options = options || {};
  307. // auto-generate content info
  308. if(typeof msg.content !== 'object' || msg.contentInfo === null) {
  309. // use Data ContentInfo
  310. msg.contentInfo = asn1.create(
  311. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  312. // ContentType
  313. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  314. asn1.oidToDer(forge.pki.oids.data).getBytes())
  315. ]);
  316. // add actual content, if present
  317. if('content' in msg) {
  318. var content;
  319. if(msg.content instanceof forge.util.ByteBuffer) {
  320. content = msg.content.bytes();
  321. } else if(typeof msg.content === 'string') {
  322. content = forge.util.encodeUtf8(msg.content);
  323. }
  324. if (options.detached) {
  325. msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);
  326. } else {
  327. msg.contentInfo.value.push(
  328. // [0] EXPLICIT content
  329. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  330. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  331. content)
  332. ]));
  333. }
  334. }
  335. }
  336. // no signers, return early (degenerate case for certificate container)
  337. if(msg.signers.length === 0) {
  338. return;
  339. }
  340. // generate digest algorithm identifiers
  341. var mds = addDigestAlgorithmIds();
  342. // generate signerInfos
  343. addSignerInfos(mds);
  344. },
  345. verify: function() {
  346. throw new Error('PKCS#7 signature verification not yet implemented.');
  347. },
  348. /**
  349. * Add a certificate.
  350. *
  351. * @param cert the certificate to add.
  352. */
  353. addCertificate: function(cert) {
  354. // convert from PEM
  355. if(typeof cert === 'string') {
  356. cert = forge.pki.certificateFromPem(cert);
  357. }
  358. msg.certificates.push(cert);
  359. },
  360. /**
  361. * Add a certificate revokation list.
  362. *
  363. * @param crl the certificate revokation list to add.
  364. */
  365. addCertificateRevokationList: function(crl) {
  366. throw new Error('PKCS#7 CRL support not yet implemented.');
  367. }
  368. };
  369. return msg;
  370. function addDigestAlgorithmIds() {
  371. var mds = {};
  372. for(var i = 0; i < msg.signers.length; ++i) {
  373. var signer = msg.signers[i];
  374. var oid = signer.digestAlgorithm;
  375. if(!(oid in mds)) {
  376. // content digest
  377. mds[oid] = forge.md[forge.pki.oids[oid]].create();
  378. }
  379. if(signer.authenticatedAttributes.length === 0) {
  380. // no custom attributes to digest; use content message digest
  381. signer.md = mds[oid];
  382. } else {
  383. // custom attributes to be digested; use own message digest
  384. // TODO: optimize to just copy message digest state if that
  385. // feature is ever supported with message digests
  386. signer.md = forge.md[forge.pki.oids[oid]].create();
  387. }
  388. }
  389. // add unique digest algorithm identifiers
  390. msg.digestAlgorithmIdentifiers = [];
  391. for(var oid in mds) {
  392. msg.digestAlgorithmIdentifiers.push(
  393. // AlgorithmIdentifier
  394. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  395. // algorithm
  396. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  397. asn1.oidToDer(oid).getBytes()),
  398. // parameters (null)
  399. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  400. ]));
  401. }
  402. return mds;
  403. }
  404. function addSignerInfos(mds) {
  405. var content;
  406. if (msg.detachedContent) {
  407. // Signature has been made in detached mode.
  408. content = msg.detachedContent;
  409. } else {
  410. // Note: ContentInfo is a SEQUENCE with 2 values, second value is
  411. // the content field and is optional for a ContentInfo but required here
  412. // since signers are present
  413. // get ContentInfo content
  414. content = msg.contentInfo.value[1];
  415. // skip [0] EXPLICIT content wrapper
  416. content = content.value[0];
  417. }
  418. if(!content) {
  419. throw new Error(
  420. 'Could not sign PKCS#7 message; there is no content to sign.');
  421. }
  422. // get ContentInfo content type
  423. var contentType = asn1.derToOid(msg.contentInfo.value[0].value);
  424. // serialize content
  425. var bytes = asn1.toDer(content);
  426. // skip identifier and length per RFC 2315 9.3
  427. // skip identifier (1 byte)
  428. bytes.getByte();
  429. // read and discard length bytes
  430. asn1.getBerValueLength(bytes);
  431. bytes = bytes.getBytes();
  432. // digest content DER value bytes
  433. for(var oid in mds) {
  434. mds[oid].start().update(bytes);
  435. }
  436. // sign content
  437. var signingTime = new Date();
  438. for(var i = 0; i < msg.signers.length; ++i) {
  439. var signer = msg.signers[i];
  440. if(signer.authenticatedAttributes.length === 0) {
  441. // if ContentInfo content type is not "Data", then
  442. // authenticatedAttributes must be present per RFC 2315
  443. if(contentType !== forge.pki.oids.data) {
  444. throw new Error(
  445. 'Invalid signer; authenticatedAttributes must be present ' +
  446. 'when the ContentInfo content type is not PKCS#7 Data.');
  447. }
  448. } else {
  449. // process authenticated attributes
  450. // [0] IMPLICIT
  451. signer.authenticatedAttributesAsn1 = asn1.create(
  452. asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
  453. // per RFC 2315, attributes are to be digested using a SET container
  454. // not the above [0] IMPLICIT container
  455. var attrsAsn1 = asn1.create(
  456. asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);
  457. for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {
  458. var attr = signer.authenticatedAttributes[ai];
  459. if(attr.type === forge.pki.oids.messageDigest) {
  460. // use content message digest as value
  461. attr.value = mds[signer.digestAlgorithm].digest();
  462. } else if(attr.type === forge.pki.oids.signingTime) {
  463. // auto-populate signing time if not already set
  464. if(!attr.value) {
  465. attr.value = signingTime;
  466. }
  467. }
  468. // convert to ASN.1 and push onto Attributes SET (for signing) and
  469. // onto authenticatedAttributesAsn1 to complete SignedData ASN.1
  470. // TODO: optimize away duplication
  471. attrsAsn1.value.push(_attributeToAsn1(attr));
  472. signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));
  473. }
  474. // DER-serialize and digest SET OF attributes only
  475. bytes = asn1.toDer(attrsAsn1).getBytes();
  476. signer.md.start().update(bytes);
  477. }
  478. // sign digest
  479. signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');
  480. }
  481. // add signer info
  482. msg.signerInfos = _signersToAsn1(msg.signers);
  483. }
  484. };
  485. /**
  486. * Creates an empty PKCS#7 message of type EncryptedData.
  487. *
  488. * @return the message.
  489. */
  490. p7.createEncryptedData = function() {
  491. var msg = null;
  492. msg = {
  493. type: forge.pki.oids.encryptedData,
  494. version: 0,
  495. encryptedContent: {
  496. algorithm: forge.pki.oids['aes256-CBC']
  497. },
  498. /**
  499. * Reads an EncryptedData content block (in ASN.1 format)
  500. *
  501. * @param obj The ASN.1 representation of the EncryptedData content block
  502. */
  503. fromAsn1: function(obj) {
  504. // Validate EncryptedData content block and capture data.
  505. _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);
  506. },
  507. /**
  508. * Decrypt encrypted content
  509. *
  510. * @param key The (symmetric) key as a byte buffer
  511. */
  512. decrypt: function(key) {
  513. if(key !== undefined) {
  514. msg.encryptedContent.key = key;
  515. }
  516. _decryptContent(msg);
  517. }
  518. };
  519. return msg;
  520. };
  521. /**
  522. * Creates an empty PKCS#7 message of type EnvelopedData.
  523. *
  524. * @return the message.
  525. */
  526. p7.createEnvelopedData = function() {
  527. var msg = null;
  528. msg = {
  529. type: forge.pki.oids.envelopedData,
  530. version: 0,
  531. recipients: [],
  532. encryptedContent: {
  533. algorithm: forge.pki.oids['aes256-CBC']
  534. },
  535. /**
  536. * Reads an EnvelopedData content block (in ASN.1 format)
  537. *
  538. * @param obj the ASN.1 representation of the EnvelopedData content block.
  539. */
  540. fromAsn1: function(obj) {
  541. // validate EnvelopedData content block and capture data
  542. var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);
  543. msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);
  544. },
  545. toAsn1: function() {
  546. // ContentInfo
  547. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  548. // ContentType
  549. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  550. asn1.oidToDer(msg.type).getBytes()),
  551. // [0] EnvelopedData
  552. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  553. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  554. // Version
  555. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  556. asn1.integerToDer(msg.version).getBytes()),
  557. // RecipientInfos
  558. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  559. _recipientsToAsn1(msg.recipients)),
  560. // EncryptedContentInfo
  561. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,
  562. _encryptedContentToAsn1(msg.encryptedContent))
  563. ])
  564. ])
  565. ]);
  566. },
  567. /**
  568. * Find recipient by X.509 certificate's issuer.
  569. *
  570. * @param cert the certificate with the issuer to look for.
  571. *
  572. * @return the recipient object.
  573. */
  574. findRecipient: function(cert) {
  575. var sAttr = cert.issuer.attributes;
  576. for(var i = 0; i < msg.recipients.length; ++i) {
  577. var r = msg.recipients[i];
  578. var rAttr = r.issuer;
  579. if(r.serialNumber !== cert.serialNumber) {
  580. continue;
  581. }
  582. if(rAttr.length !== sAttr.length) {
  583. continue;
  584. }
  585. var match = true;
  586. for(var j = 0; j < sAttr.length; ++j) {
  587. if(rAttr[j].type !== sAttr[j].type ||
  588. rAttr[j].value !== sAttr[j].value) {
  589. match = false;
  590. break;
  591. }
  592. }
  593. if(match) {
  594. return r;
  595. }
  596. }
  597. return null;
  598. },
  599. /**
  600. * Decrypt enveloped content
  601. *
  602. * @param recipient The recipient object related to the private key
  603. * @param privKey The (RSA) private key object
  604. */
  605. decrypt: function(recipient, privKey) {
  606. if(msg.encryptedContent.key === undefined && recipient !== undefined &&
  607. privKey !== undefined) {
  608. switch(recipient.encryptedContent.algorithm) {
  609. case forge.pki.oids.rsaEncryption:
  610. case forge.pki.oids.desCBC:
  611. var key = privKey.decrypt(recipient.encryptedContent.content);
  612. msg.encryptedContent.key = forge.util.createBuffer(key);
  613. break;
  614. default:
  615. throw new Error('Unsupported asymmetric cipher, ' +
  616. 'OID ' + recipient.encryptedContent.algorithm);
  617. }
  618. }
  619. _decryptContent(msg);
  620. },
  621. /**
  622. * Add (another) entity to list of recipients.
  623. *
  624. * @param cert The certificate of the entity to add.
  625. */
  626. addRecipient: function(cert) {
  627. msg.recipients.push({
  628. version: 0,
  629. issuer: cert.issuer.attributes,
  630. serialNumber: cert.serialNumber,
  631. encryptedContent: {
  632. // We simply assume rsaEncryption here, since forge.pki only
  633. // supports RSA so far. If the PKI module supports other
  634. // ciphers one day, we need to modify this one as well.
  635. algorithm: forge.pki.oids.rsaEncryption,
  636. key: cert.publicKey
  637. }
  638. });
  639. },
  640. /**
  641. * Encrypt enveloped content.
  642. *
  643. * This function supports two optional arguments, cipher and key, which
  644. * can be used to influence symmetric encryption. Unless cipher is
  645. * provided, the cipher specified in encryptedContent.algorithm is used
  646. * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key
  647. * is (re-)used. If that one's not set, a random key will be generated
  648. * automatically.
  649. *
  650. * @param [key] The key to be used for symmetric encryption.
  651. * @param [cipher] The OID of the symmetric cipher to use.
  652. */
  653. encrypt: function(key, cipher) {
  654. // Part 1: Symmetric encryption
  655. if(msg.encryptedContent.content === undefined) {
  656. cipher = cipher || msg.encryptedContent.algorithm;
  657. key = key || msg.encryptedContent.key;
  658. var keyLen, ivLen, ciphFn;
  659. switch(cipher) {
  660. case forge.pki.oids['aes128-CBC']:
  661. keyLen = 16;
  662. ivLen = 16;
  663. ciphFn = forge.aes.createEncryptionCipher;
  664. break;
  665. case forge.pki.oids['aes192-CBC']:
  666. keyLen = 24;
  667. ivLen = 16;
  668. ciphFn = forge.aes.createEncryptionCipher;
  669. break;
  670. case forge.pki.oids['aes256-CBC']:
  671. keyLen = 32;
  672. ivLen = 16;
  673. ciphFn = forge.aes.createEncryptionCipher;
  674. break;
  675. case forge.pki.oids['des-EDE3-CBC']:
  676. keyLen = 24;
  677. ivLen = 8;
  678. ciphFn = forge.des.createEncryptionCipher;
  679. break;
  680. default:
  681. throw new Error('Unsupported symmetric cipher, OID ' + cipher);
  682. }
  683. if(key === undefined) {
  684. key = forge.util.createBuffer(forge.random.getBytes(keyLen));
  685. } else if(key.length() != keyLen) {
  686. throw new Error('Symmetric key has wrong length; ' +
  687. 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');
  688. }
  689. // Keep a copy of the key & IV in the object, so the caller can
  690. // use it for whatever reason.
  691. msg.encryptedContent.algorithm = cipher;
  692. msg.encryptedContent.key = key;
  693. msg.encryptedContent.parameter = forge.util.createBuffer(
  694. forge.random.getBytes(ivLen));
  695. var ciph = ciphFn(key);
  696. ciph.start(msg.encryptedContent.parameter.copy());
  697. ciph.update(msg.content);
  698. // The finish function does PKCS#7 padding by default, therefore
  699. // no action required by us.
  700. if(!ciph.finish()) {
  701. throw new Error('Symmetric encryption failed.');
  702. }
  703. msg.encryptedContent.content = ciph.output;
  704. }
  705. // Part 2: asymmetric encryption for each recipient
  706. for(var i = 0; i < msg.recipients.length; ++i) {
  707. var recipient = msg.recipients[i];
  708. // Nothing to do, encryption already done.
  709. if(recipient.encryptedContent.content !== undefined) {
  710. continue;
  711. }
  712. switch(recipient.encryptedContent.algorithm) {
  713. case forge.pki.oids.rsaEncryption:
  714. recipient.encryptedContent.content =
  715. recipient.encryptedContent.key.encrypt(
  716. msg.encryptedContent.key.data);
  717. break;
  718. default:
  719. throw new Error('Unsupported asymmetric cipher, OID ' +
  720. recipient.encryptedContent.algorithm);
  721. }
  722. }
  723. }
  724. };
  725. return msg;
  726. };
  727. /**
  728. * Converts a single recipient from an ASN.1 object.
  729. *
  730. * @param obj the ASN.1 RecipientInfo.
  731. *
  732. * @return the recipient object.
  733. */
  734. function _recipientFromAsn1(obj) {
  735. // validate EnvelopedData content block and capture data
  736. var capture = {};
  737. var errors = [];
  738. if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {
  739. var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +
  740. 'ASN.1 object is not an PKCS#7 RecipientInfo.');
  741. error.errors = errors;
  742. throw error;
  743. }
  744. return {
  745. version: capture.version.charCodeAt(0),
  746. issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
  747. serialNumber: forge.util.createBuffer(capture.serial).toHex(),
  748. encryptedContent: {
  749. algorithm: asn1.derToOid(capture.encAlgorithm),
  750. parameter: capture.encParameter.value,
  751. content: capture.encKey
  752. }
  753. };
  754. }
  755. /**
  756. * Converts a single recipient object to an ASN.1 object.
  757. *
  758. * @param obj the recipient object.
  759. *
  760. * @return the ASN.1 RecipientInfo.
  761. */
  762. function _recipientToAsn1(obj) {
  763. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  764. // Version
  765. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  766. asn1.integerToDer(obj.version).getBytes()),
  767. // IssuerAndSerialNumber
  768. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  769. // Name
  770. forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
  771. // Serial
  772. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  773. forge.util.hexToBytes(obj.serialNumber))
  774. ]),
  775. // KeyEncryptionAlgorithmIdentifier
  776. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  777. // Algorithm
  778. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  779. asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),
  780. // Parameter, force NULL, only RSA supported for now.
  781. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  782. ]),
  783. // EncryptedKey
  784. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  785. obj.encryptedContent.content)
  786. ]);
  787. }
  788. /**
  789. * Map a set of RecipientInfo ASN.1 objects to recipient objects.
  790. *
  791. * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).
  792. *
  793. * @return an array of recipient objects.
  794. */
  795. function _recipientsFromAsn1(infos) {
  796. var ret = [];
  797. for(var i = 0; i < infos.length; ++i) {
  798. ret.push(_recipientFromAsn1(infos[i]));
  799. }
  800. return ret;
  801. }
  802. /**
  803. * Map an array of recipient objects to ASN.1 RecipientInfo objects.
  804. *
  805. * @param recipients an array of recipientInfo objects.
  806. *
  807. * @return an array of ASN.1 RecipientInfos.
  808. */
  809. function _recipientsToAsn1(recipients) {
  810. var ret = [];
  811. for(var i = 0; i < recipients.length; ++i) {
  812. ret.push(_recipientToAsn1(recipients[i]));
  813. }
  814. return ret;
  815. }
  816. /**
  817. * Converts a single signer from an ASN.1 object.
  818. *
  819. * @param obj the ASN.1 representation of a SignerInfo.
  820. *
  821. * @return the signer object.
  822. */
  823. function _signerFromAsn1(obj) {
  824. // validate EnvelopedData content block and capture data
  825. var capture = {};
  826. var errors = [];
  827. if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {
  828. var error = new Error('Cannot read PKCS#7 SignerInfo. ' +
  829. 'ASN.1 object is not an PKCS#7 SignerInfo.');
  830. error.errors = errors;
  831. throw error;
  832. }
  833. var rval = {
  834. version: capture.version.charCodeAt(0),
  835. issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
  836. serialNumber: forge.util.createBuffer(capture.serial).toHex(),
  837. digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),
  838. signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),
  839. signature: capture.signature,
  840. authenticatedAttributes: [],
  841. unauthenticatedAttributes: []
  842. };
  843. // TODO: convert attributes
  844. var authenticatedAttributes = capture.authenticatedAttributes || [];
  845. var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];
  846. return rval;
  847. }
  848. /**
  849. * Converts a single signerInfo object to an ASN.1 object.
  850. *
  851. * @param obj the signerInfo object.
  852. *
  853. * @return the ASN.1 representation of a SignerInfo.
  854. */
  855. function _signerToAsn1(obj) {
  856. // SignerInfo
  857. var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  858. // version
  859. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  860. asn1.integerToDer(obj.version).getBytes()),
  861. // issuerAndSerialNumber
  862. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  863. // name
  864. forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
  865. // serial
  866. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  867. forge.util.hexToBytes(obj.serialNumber))
  868. ]),
  869. // digestAlgorithm
  870. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  871. // algorithm
  872. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  873. asn1.oidToDer(obj.digestAlgorithm).getBytes()),
  874. // parameters (null)
  875. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  876. ])
  877. ]);
  878. // authenticatedAttributes (OPTIONAL)
  879. if(obj.authenticatedAttributesAsn1) {
  880. // add ASN.1 previously generated during signing
  881. rval.value.push(obj.authenticatedAttributesAsn1);
  882. }
  883. // digestEncryptionAlgorithm
  884. rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  885. // algorithm
  886. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  887. asn1.oidToDer(obj.signatureAlgorithm).getBytes()),
  888. // parameters (null)
  889. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  890. ]));
  891. // encryptedDigest
  892. rval.value.push(asn1.create(
  893. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));
  894. // unauthenticatedAttributes (OPTIONAL)
  895. if(obj.unauthenticatedAttributes.length > 0) {
  896. // [1] IMPLICIT
  897. var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);
  898. for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {
  899. var attr = obj.unauthenticatedAttributes[i];
  900. attrsAsn1.values.push(_attributeToAsn1(attr));
  901. }
  902. rval.value.push(attrsAsn1);
  903. }
  904. return rval;
  905. }
  906. /**
  907. * Map a set of SignerInfo ASN.1 objects to an array of signer objects.
  908. *
  909. * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF).
  910. *
  911. * @return an array of signers objects.
  912. */
  913. function _signersFromAsn1(signerInfoAsn1s) {
  914. var ret = [];
  915. for(var i = 0; i < signerInfoAsn1s.length; ++i) {
  916. ret.push(_signerFromAsn1(signerInfoAsn1s[i]));
  917. }
  918. return ret;
  919. }
  920. /**
  921. * Map an array of signer objects to ASN.1 objects.
  922. *
  923. * @param signers an array of signer objects.
  924. *
  925. * @return an array of ASN.1 SignerInfos.
  926. */
  927. function _signersToAsn1(signers) {
  928. var ret = [];
  929. for(var i = 0; i < signers.length; ++i) {
  930. ret.push(_signerToAsn1(signers[i]));
  931. }
  932. return ret;
  933. }
  934. /**
  935. * Convert an attribute object to an ASN.1 Attribute.
  936. *
  937. * @param attr the attribute object.
  938. *
  939. * @return the ASN.1 Attribute.
  940. */
  941. function _attributeToAsn1(attr) {
  942. var value;
  943. // TODO: generalize to support more attributes
  944. if(attr.type === forge.pki.oids.contentType) {
  945. value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  946. asn1.oidToDer(attr.value).getBytes());
  947. } else if(attr.type === forge.pki.oids.messageDigest) {
  948. value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  949. attr.value.bytes());
  950. } else if(attr.type === forge.pki.oids.signingTime) {
  951. /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049
  952. (inclusive) MUST be encoded as UTCTime. Any dates with year values
  953. before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]
  954. UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST
  955. include seconds (i.e., times are YYMMDDHHMMSSZ), even where the
  956. number of seconds is zero. Midnight (GMT) must be represented as
  957. "YYMMDD000000Z". */
  958. // TODO: make these module-level constants
  959. var jan_1_1950 = new Date('1950-01-01T00:00:00Z');
  960. var jan_1_2050 = new Date('2050-01-01T00:00:00Z');
  961. var date = attr.value;
  962. if(typeof date === 'string') {
  963. // try to parse date
  964. var timestamp = Date.parse(date);
  965. if(!isNaN(timestamp)) {
  966. date = new Date(timestamp);
  967. } else if(date.length === 13) {
  968. // YYMMDDHHMMSSZ (13 chars for UTCTime)
  969. date = asn1.utcTimeToDate(date);
  970. } else {
  971. // assume generalized time
  972. date = asn1.generalizedTimeToDate(date);
  973. }
  974. }
  975. if(date >= jan_1_1950 && date < jan_1_2050) {
  976. value = asn1.create(
  977. asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,
  978. asn1.dateToUtcTime(date));
  979. } else {
  980. value = asn1.create(
  981. asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,
  982. asn1.dateToGeneralizedTime(date));
  983. }
  984. }
  985. // TODO: expose as common API call
  986. // create a RelativeDistinguishedName set
  987. // each value in the set is an AttributeTypeAndValue first
  988. // containing the type (an OID) and second the value
  989. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  990. // AttributeType
  991. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  992. asn1.oidToDer(attr.type).getBytes()),
  993. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
  994. // AttributeValue
  995. value
  996. ])
  997. ]);
  998. }
  999. /**
  1000. * Map messages encrypted content to ASN.1 objects.
  1001. *
  1002. * @param ec The encryptedContent object of the message.
  1003. *
  1004. * @return ASN.1 representation of the encryptedContent object (SEQUENCE).
  1005. */
  1006. function _encryptedContentToAsn1(ec) {
  1007. return [
  1008. // ContentType, always Data for the moment
  1009. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  1010. asn1.oidToDer(forge.pki.oids.data).getBytes()),
  1011. // ContentEncryptionAlgorithmIdentifier
  1012. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1013. // Algorithm
  1014. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  1015. asn1.oidToDer(ec.algorithm).getBytes()),
  1016. // Parameters (IV)
  1017. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  1018. ec.parameter.getBytes())
  1019. ]),
  1020. // [0] EncryptedContent
  1021. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  1022. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  1023. ec.content.getBytes())
  1024. ])
  1025. ];
  1026. }
  1027. /**
  1028. * Reads the "common part" of an PKCS#7 content block (in ASN.1 format)
  1029. *
  1030. * This function reads the "common part" of the PKCS#7 content blocks
  1031. * EncryptedData and EnvelopedData, i.e. version number and symmetrically
  1032. * encrypted content block.
  1033. *
  1034. * The result of the ASN.1 validate and capture process is returned
  1035. * to allow the caller to extract further data, e.g. the list of recipients
  1036. * in case of a EnvelopedData object.
  1037. *
  1038. * @param msg the PKCS#7 object to read the data to.
  1039. * @param obj the ASN.1 representation of the content block.
  1040. * @param validator the ASN.1 structure validator object to use.
  1041. *
  1042. * @return the value map captured by validator object.
  1043. */
  1044. function _fromAsn1(msg, obj, validator) {
  1045. var capture = {};
  1046. var errors = [];
  1047. if(!asn1.validate(obj, validator, capture, errors)) {
  1048. var error = new Error('Cannot read PKCS#7 message. ' +
  1049. 'ASN.1 object is not a supported PKCS#7 message.');
  1050. error.errors = error;
  1051. throw error;
  1052. }
  1053. // Check contentType, so far we only support (raw) Data.
  1054. var contentType = asn1.derToOid(capture.contentType);
  1055. if(contentType !== forge.pki.oids.data) {
  1056. throw new Error('Unsupported PKCS#7 message. ' +
  1057. 'Only wrapped ContentType Data supported.');
  1058. }
  1059. if(capture.encryptedContent) {
  1060. var content = '';
  1061. if(forge.util.isArray(capture.encryptedContent)) {
  1062. for(var i = 0; i < capture.encryptedContent.length; ++i) {
  1063. if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {
  1064. throw new Error('Malformed PKCS#7 message, expecting encrypted ' +
  1065. 'content constructed of only OCTET STRING objects.');
  1066. }
  1067. content += capture.encryptedContent[i].value;
  1068. }
  1069. } else {
  1070. content = capture.encryptedContent;
  1071. }
  1072. msg.encryptedContent = {
  1073. algorithm: asn1.derToOid(capture.encAlgorithm),
  1074. parameter: forge.util.createBuffer(capture.encParameter.value),
  1075. content: forge.util.createBuffer(content)
  1076. };
  1077. }
  1078. if(capture.content) {
  1079. var content = '';
  1080. if(forge.util.isArray(capture.content)) {
  1081. for(var i = 0; i < capture.content.length; ++i) {
  1082. if(capture.content[i].type !== asn1.Type.OCTETSTRING) {
  1083. throw new Error('Malformed PKCS#7 message, expecting ' +
  1084. 'content constructed of only OCTET STRING objects.');
  1085. }
  1086. content += capture.content[i].value;
  1087. }
  1088. } else {
  1089. content = capture.content;
  1090. }
  1091. msg.content = forge.util.createBuffer(content);
  1092. }
  1093. msg.version = capture.version.charCodeAt(0);
  1094. msg.rawCapture = capture;
  1095. return capture;
  1096. }
  1097. /**
  1098. * Decrypt the symmetrically encrypted content block of the PKCS#7 message.
  1099. *
  1100. * Decryption is skipped in case the PKCS#7 message object already has a
  1101. * (decrypted) content attribute. The algorithm, key and cipher parameters
  1102. * (probably the iv) are taken from the encryptedContent attribute of the
  1103. * message object.
  1104. *
  1105. * @param The PKCS#7 message object.
  1106. */
  1107. function _decryptContent(msg) {
  1108. if(msg.encryptedContent.key === undefined) {
  1109. throw new Error('Symmetric key not available.');
  1110. }
  1111. if(msg.content === undefined) {
  1112. var ciph;
  1113. switch(msg.encryptedContent.algorithm) {
  1114. case forge.pki.oids['aes128-CBC']:
  1115. case forge.pki.oids['aes192-CBC']:
  1116. case forge.pki.oids['aes256-CBC']:
  1117. ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key);
  1118. break;
  1119. case forge.pki.oids['desCBC']:
  1120. case forge.pki.oids['des-EDE3-CBC']:
  1121. ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key);
  1122. break;
  1123. default:
  1124. throw new Error('Unsupported symmetric cipher, OID ' +
  1125. msg.encryptedContent.algorithm);
  1126. }
  1127. ciph.start(msg.encryptedContent.parameter);
  1128. ciph.update(msg.encryptedContent.content);
  1129. if(!ciph.finish()) {
  1130. throw new Error('Symmetric decryption failed.');
  1131. }
  1132. msg.content = ciph.output;
  1133. }
  1134. }