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.

3333 lines
103 KiB

4 years ago
  1. /**
  2. * Javascript implementation of X.509 and related components (such as
  3. * Certification Signing Requests) of a Public Key Infrastructure.
  4. *
  5. * @author Dave Longley
  6. *
  7. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  8. *
  9. * The ASN.1 representation of an X.509v3 certificate is as follows
  10. * (see RFC 2459):
  11. *
  12. * Certificate ::= SEQUENCE {
  13. * tbsCertificate TBSCertificate,
  14. * signatureAlgorithm AlgorithmIdentifier,
  15. * signatureValue BIT STRING
  16. * }
  17. *
  18. * TBSCertificate ::= SEQUENCE {
  19. * version [0] EXPLICIT Version DEFAULT v1,
  20. * serialNumber CertificateSerialNumber,
  21. * signature AlgorithmIdentifier,
  22. * issuer Name,
  23. * validity Validity,
  24. * subject Name,
  25. * subjectPublicKeyInfo SubjectPublicKeyInfo,
  26. * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
  27. * -- If present, version shall be v2 or v3
  28. * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
  29. * -- If present, version shall be v2 or v3
  30. * extensions [3] EXPLICIT Extensions OPTIONAL
  31. * -- If present, version shall be v3
  32. * }
  33. *
  34. * Version ::= INTEGER { v1(0), v2(1), v3(2) }
  35. *
  36. * CertificateSerialNumber ::= INTEGER
  37. *
  38. * Name ::= CHOICE {
  39. * // only one possible choice for now
  40. * RDNSequence
  41. * }
  42. *
  43. * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  44. *
  45. * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
  46. *
  47. * AttributeTypeAndValue ::= SEQUENCE {
  48. * type AttributeType,
  49. * value AttributeValue
  50. * }
  51. * AttributeType ::= OBJECT IDENTIFIER
  52. * AttributeValue ::= ANY DEFINED BY AttributeType
  53. *
  54. * Validity ::= SEQUENCE {
  55. * notBefore Time,
  56. * notAfter Time
  57. * }
  58. *
  59. * Time ::= CHOICE {
  60. * utcTime UTCTime,
  61. * generalTime GeneralizedTime
  62. * }
  63. *
  64. * UniqueIdentifier ::= BIT STRING
  65. *
  66. * SubjectPublicKeyInfo ::= SEQUENCE {
  67. * algorithm AlgorithmIdentifier,
  68. * subjectPublicKey BIT STRING
  69. * }
  70. *
  71. * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
  72. *
  73. * Extension ::= SEQUENCE {
  74. * extnID OBJECT IDENTIFIER,
  75. * critical BOOLEAN DEFAULT FALSE,
  76. * extnValue OCTET STRING
  77. * }
  78. *
  79. * The only key algorithm currently supported for PKI is RSA.
  80. *
  81. * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.
  82. *
  83. * PKCS#10 v1.7 describes certificate signing requests:
  84. *
  85. * CertificationRequestInfo:
  86. *
  87. * CertificationRequestInfo ::= SEQUENCE {
  88. * version INTEGER { v1(0) } (v1,...),
  89. * subject Name,
  90. * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
  91. * attributes [0] Attributes{{ CRIAttributes }}
  92. * }
  93. *
  94. * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
  95. *
  96. * CRIAttributes ATTRIBUTE ::= {
  97. * ... -- add any locally defined attributes here -- }
  98. *
  99. * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
  100. * type ATTRIBUTE.&id({IOSet}),
  101. * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
  102. * }
  103. *
  104. * CertificationRequest ::= SEQUENCE {
  105. * certificationRequestInfo CertificationRequestInfo,
  106. * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
  107. * signature BIT STRING
  108. * }
  109. */
  110. var forge = require('./forge');
  111. require('./aes');
  112. require('./asn1');
  113. require('./des');
  114. require('./md');
  115. require('./mgf');
  116. require('./oids');
  117. require('./pem');
  118. require('./pss');
  119. require('./rsa');
  120. require('./util');
  121. // shortcut for asn.1 API
  122. var asn1 = forge.asn1;
  123. /* Public Key Infrastructure (PKI) implementation. */
  124. var pki = module.exports = forge.pki = forge.pki || {};
  125. var oids = pki.oids;
  126. // short name OID mappings
  127. var _shortNames = {};
  128. _shortNames['CN'] = oids['commonName'];
  129. _shortNames['commonName'] = 'CN';
  130. _shortNames['C'] = oids['countryName'];
  131. _shortNames['countryName'] = 'C';
  132. _shortNames['L'] = oids['localityName'];
  133. _shortNames['localityName'] = 'L';
  134. _shortNames['ST'] = oids['stateOrProvinceName'];
  135. _shortNames['stateOrProvinceName'] = 'ST';
  136. _shortNames['O'] = oids['organizationName'];
  137. _shortNames['organizationName'] = 'O';
  138. _shortNames['OU'] = oids['organizationalUnitName'];
  139. _shortNames['organizationalUnitName'] = 'OU';
  140. _shortNames['E'] = oids['emailAddress'];
  141. _shortNames['emailAddress'] = 'E';
  142. // validator for an SubjectPublicKeyInfo structure
  143. // Note: Currently only works with an RSA public key
  144. var publicKeyValidator = forge.pki.rsa.publicKeyValidator;
  145. // validator for an X.509v3 certificate
  146. var x509CertificateValidator = {
  147. name: 'Certificate',
  148. tagClass: asn1.Class.UNIVERSAL,
  149. type: asn1.Type.SEQUENCE,
  150. constructed: true,
  151. value: [{
  152. name: 'Certificate.TBSCertificate',
  153. tagClass: asn1.Class.UNIVERSAL,
  154. type: asn1.Type.SEQUENCE,
  155. constructed: true,
  156. captureAsn1: 'tbsCertificate',
  157. value: [{
  158. name: 'Certificate.TBSCertificate.version',
  159. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  160. type: 0,
  161. constructed: true,
  162. optional: true,
  163. value: [{
  164. name: 'Certificate.TBSCertificate.version.integer',
  165. tagClass: asn1.Class.UNIVERSAL,
  166. type: asn1.Type.INTEGER,
  167. constructed: false,
  168. capture: 'certVersion'
  169. }]
  170. }, {
  171. name: 'Certificate.TBSCertificate.serialNumber',
  172. tagClass: asn1.Class.UNIVERSAL,
  173. type: asn1.Type.INTEGER,
  174. constructed: false,
  175. capture: 'certSerialNumber'
  176. }, {
  177. name: 'Certificate.TBSCertificate.signature',
  178. tagClass: asn1.Class.UNIVERSAL,
  179. type: asn1.Type.SEQUENCE,
  180. constructed: true,
  181. value: [{
  182. name: 'Certificate.TBSCertificate.signature.algorithm',
  183. tagClass: asn1.Class.UNIVERSAL,
  184. type: asn1.Type.OID,
  185. constructed: false,
  186. capture: 'certinfoSignatureOid'
  187. }, {
  188. name: 'Certificate.TBSCertificate.signature.parameters',
  189. tagClass: asn1.Class.UNIVERSAL,
  190. optional: true,
  191. captureAsn1: 'certinfoSignatureParams'
  192. }]
  193. }, {
  194. name: 'Certificate.TBSCertificate.issuer',
  195. tagClass: asn1.Class.UNIVERSAL,
  196. type: asn1.Type.SEQUENCE,
  197. constructed: true,
  198. captureAsn1: 'certIssuer'
  199. }, {
  200. name: 'Certificate.TBSCertificate.validity',
  201. tagClass: asn1.Class.UNIVERSAL,
  202. type: asn1.Type.SEQUENCE,
  203. constructed: true,
  204. // Note: UTC and generalized times may both appear so the capture
  205. // names are based on their detected order, the names used below
  206. // are only for the common case, which validity time really means
  207. // "notBefore" and which means "notAfter" will be determined by order
  208. value: [{
  209. // notBefore (Time) (UTC time case)
  210. name: 'Certificate.TBSCertificate.validity.notBefore (utc)',
  211. tagClass: asn1.Class.UNIVERSAL,
  212. type: asn1.Type.UTCTIME,
  213. constructed: false,
  214. optional: true,
  215. capture: 'certValidity1UTCTime'
  216. }, {
  217. // notBefore (Time) (generalized time case)
  218. name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',
  219. tagClass: asn1.Class.UNIVERSAL,
  220. type: asn1.Type.GENERALIZEDTIME,
  221. constructed: false,
  222. optional: true,
  223. capture: 'certValidity2GeneralizedTime'
  224. }, {
  225. // notAfter (Time) (only UTC time is supported)
  226. name: 'Certificate.TBSCertificate.validity.notAfter (utc)',
  227. tagClass: asn1.Class.UNIVERSAL,
  228. type: asn1.Type.UTCTIME,
  229. constructed: false,
  230. optional: true,
  231. capture: 'certValidity3UTCTime'
  232. }, {
  233. // notAfter (Time) (only UTC time is supported)
  234. name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',
  235. tagClass: asn1.Class.UNIVERSAL,
  236. type: asn1.Type.GENERALIZEDTIME,
  237. constructed: false,
  238. optional: true,
  239. capture: 'certValidity4GeneralizedTime'
  240. }]
  241. }, {
  242. // Name (subject) (RDNSequence)
  243. name: 'Certificate.TBSCertificate.subject',
  244. tagClass: asn1.Class.UNIVERSAL,
  245. type: asn1.Type.SEQUENCE,
  246. constructed: true,
  247. captureAsn1: 'certSubject'
  248. },
  249. // SubjectPublicKeyInfo
  250. publicKeyValidator,
  251. {
  252. // issuerUniqueID (optional)
  253. name: 'Certificate.TBSCertificate.issuerUniqueID',
  254. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  255. type: 1,
  256. constructed: true,
  257. optional: true,
  258. value: [{
  259. name: 'Certificate.TBSCertificate.issuerUniqueID.id',
  260. tagClass: asn1.Class.UNIVERSAL,
  261. type: asn1.Type.BITSTRING,
  262. constructed: false,
  263. // TODO: support arbitrary bit length ids
  264. captureBitStringValue: 'certIssuerUniqueId'
  265. }]
  266. }, {
  267. // subjectUniqueID (optional)
  268. name: 'Certificate.TBSCertificate.subjectUniqueID',
  269. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  270. type: 2,
  271. constructed: true,
  272. optional: true,
  273. value: [{
  274. name: 'Certificate.TBSCertificate.subjectUniqueID.id',
  275. tagClass: asn1.Class.UNIVERSAL,
  276. type: asn1.Type.BITSTRING,
  277. constructed: false,
  278. // TODO: support arbitrary bit length ids
  279. captureBitStringValue: 'certSubjectUniqueId'
  280. }]
  281. }, {
  282. // Extensions (optional)
  283. name: 'Certificate.TBSCertificate.extensions',
  284. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  285. type: 3,
  286. constructed: true,
  287. captureAsn1: 'certExtensions',
  288. optional: true
  289. }]
  290. }, {
  291. // AlgorithmIdentifier (signature algorithm)
  292. name: 'Certificate.signatureAlgorithm',
  293. tagClass: asn1.Class.UNIVERSAL,
  294. type: asn1.Type.SEQUENCE,
  295. constructed: true,
  296. value: [{
  297. // algorithm
  298. name: 'Certificate.signatureAlgorithm.algorithm',
  299. tagClass: asn1.Class.UNIVERSAL,
  300. type: asn1.Type.OID,
  301. constructed: false,
  302. capture: 'certSignatureOid'
  303. }, {
  304. name: 'Certificate.TBSCertificate.signature.parameters',
  305. tagClass: asn1.Class.UNIVERSAL,
  306. optional: true,
  307. captureAsn1: 'certSignatureParams'
  308. }]
  309. }, {
  310. // SignatureValue
  311. name: 'Certificate.signatureValue',
  312. tagClass: asn1.Class.UNIVERSAL,
  313. type: asn1.Type.BITSTRING,
  314. constructed: false,
  315. captureBitStringValue: 'certSignature'
  316. }]
  317. };
  318. var rsassaPssParameterValidator = {
  319. name: 'rsapss',
  320. tagClass: asn1.Class.UNIVERSAL,
  321. type: asn1.Type.SEQUENCE,
  322. constructed: true,
  323. value: [{
  324. name: 'rsapss.hashAlgorithm',
  325. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  326. type: 0,
  327. constructed: true,
  328. value: [{
  329. name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',
  330. tagClass: asn1.Class.UNIVERSAL,
  331. type: asn1.Class.SEQUENCE,
  332. constructed: true,
  333. optional: true,
  334. value: [{
  335. name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',
  336. tagClass: asn1.Class.UNIVERSAL,
  337. type: asn1.Type.OID,
  338. constructed: false,
  339. capture: 'hashOid'
  340. /* parameter block omitted, for SHA1 NULL anyhow. */
  341. }]
  342. }]
  343. }, {
  344. name: 'rsapss.maskGenAlgorithm',
  345. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  346. type: 1,
  347. constructed: true,
  348. value: [{
  349. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',
  350. tagClass: asn1.Class.UNIVERSAL,
  351. type: asn1.Class.SEQUENCE,
  352. constructed: true,
  353. optional: true,
  354. value: [{
  355. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',
  356. tagClass: asn1.Class.UNIVERSAL,
  357. type: asn1.Type.OID,
  358. constructed: false,
  359. capture: 'maskGenOid'
  360. }, {
  361. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',
  362. tagClass: asn1.Class.UNIVERSAL,
  363. type: asn1.Type.SEQUENCE,
  364. constructed: true,
  365. value: [{
  366. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',
  367. tagClass: asn1.Class.UNIVERSAL,
  368. type: asn1.Type.OID,
  369. constructed: false,
  370. capture: 'maskGenHashOid'
  371. /* parameter block omitted, for SHA1 NULL anyhow. */
  372. }]
  373. }]
  374. }]
  375. }, {
  376. name: 'rsapss.saltLength',
  377. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  378. type: 2,
  379. optional: true,
  380. value: [{
  381. name: 'rsapss.saltLength.saltLength',
  382. tagClass: asn1.Class.UNIVERSAL,
  383. type: asn1.Class.INTEGER,
  384. constructed: false,
  385. capture: 'saltLength'
  386. }]
  387. }, {
  388. name: 'rsapss.trailerField',
  389. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  390. type: 3,
  391. optional: true,
  392. value: [{
  393. name: 'rsapss.trailer.trailer',
  394. tagClass: asn1.Class.UNIVERSAL,
  395. type: asn1.Class.INTEGER,
  396. constructed: false,
  397. capture: 'trailer'
  398. }]
  399. }]
  400. };
  401. // validator for a CertificationRequestInfo structure
  402. var certificationRequestInfoValidator = {
  403. name: 'CertificationRequestInfo',
  404. tagClass: asn1.Class.UNIVERSAL,
  405. type: asn1.Type.SEQUENCE,
  406. constructed: true,
  407. captureAsn1: 'certificationRequestInfo',
  408. value: [{
  409. name: 'CertificationRequestInfo.integer',
  410. tagClass: asn1.Class.UNIVERSAL,
  411. type: asn1.Type.INTEGER,
  412. constructed: false,
  413. capture: 'certificationRequestInfoVersion'
  414. }, {
  415. // Name (subject) (RDNSequence)
  416. name: 'CertificationRequestInfo.subject',
  417. tagClass: asn1.Class.UNIVERSAL,
  418. type: asn1.Type.SEQUENCE,
  419. constructed: true,
  420. captureAsn1: 'certificationRequestInfoSubject'
  421. },
  422. // SubjectPublicKeyInfo
  423. publicKeyValidator,
  424. {
  425. name: 'CertificationRequestInfo.attributes',
  426. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  427. type: 0,
  428. constructed: true,
  429. optional: true,
  430. capture: 'certificationRequestInfoAttributes',
  431. value: [{
  432. name: 'CertificationRequestInfo.attributes',
  433. tagClass: asn1.Class.UNIVERSAL,
  434. type: asn1.Type.SEQUENCE,
  435. constructed: true,
  436. value: [{
  437. name: 'CertificationRequestInfo.attributes.type',
  438. tagClass: asn1.Class.UNIVERSAL,
  439. type: asn1.Type.OID,
  440. constructed: false
  441. }, {
  442. name: 'CertificationRequestInfo.attributes.value',
  443. tagClass: asn1.Class.UNIVERSAL,
  444. type: asn1.Type.SET,
  445. constructed: true
  446. }]
  447. }]
  448. }]
  449. };
  450. // validator for a CertificationRequest structure
  451. var certificationRequestValidator = {
  452. name: 'CertificationRequest',
  453. tagClass: asn1.Class.UNIVERSAL,
  454. type: asn1.Type.SEQUENCE,
  455. constructed: true,
  456. captureAsn1: 'csr',
  457. value: [
  458. certificationRequestInfoValidator, {
  459. // AlgorithmIdentifier (signature algorithm)
  460. name: 'CertificationRequest.signatureAlgorithm',
  461. tagClass: asn1.Class.UNIVERSAL,
  462. type: asn1.Type.SEQUENCE,
  463. constructed: true,
  464. value: [{
  465. // algorithm
  466. name: 'CertificationRequest.signatureAlgorithm.algorithm',
  467. tagClass: asn1.Class.UNIVERSAL,
  468. type: asn1.Type.OID,
  469. constructed: false,
  470. capture: 'csrSignatureOid'
  471. }, {
  472. name: 'CertificationRequest.signatureAlgorithm.parameters',
  473. tagClass: asn1.Class.UNIVERSAL,
  474. optional: true,
  475. captureAsn1: 'csrSignatureParams'
  476. }]
  477. }, {
  478. // signature
  479. name: 'CertificationRequest.signature',
  480. tagClass: asn1.Class.UNIVERSAL,
  481. type: asn1.Type.BITSTRING,
  482. constructed: false,
  483. captureBitStringValue: 'csrSignature'
  484. }
  485. ]
  486. };
  487. /**
  488. * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName
  489. * sets into an array with objects that have type and value properties.
  490. *
  491. * @param rdn the RDNSequence to convert.
  492. * @param md a message digest to append type and value to if provided.
  493. */
  494. pki.RDNAttributesAsArray = function(rdn, md) {
  495. var rval = [];
  496. // each value in 'rdn' in is a SET of RelativeDistinguishedName
  497. var set, attr, obj;
  498. for(var si = 0; si < rdn.value.length; ++si) {
  499. // get the RelativeDistinguishedName set
  500. set = rdn.value[si];
  501. // each value in the SET is an AttributeTypeAndValue sequence
  502. // containing first a type (an OID) and second a value (defined by
  503. // the OID)
  504. for(var i = 0; i < set.value.length; ++i) {
  505. obj = {};
  506. attr = set.value[i];
  507. obj.type = asn1.derToOid(attr.value[0].value);
  508. obj.value = attr.value[1].value;
  509. obj.valueTagClass = attr.value[1].type;
  510. // if the OID is known, get its name and short name
  511. if(obj.type in oids) {
  512. obj.name = oids[obj.type];
  513. if(obj.name in _shortNames) {
  514. obj.shortName = _shortNames[obj.name];
  515. }
  516. }
  517. if(md) {
  518. md.update(obj.type);
  519. md.update(obj.value);
  520. }
  521. rval.push(obj);
  522. }
  523. }
  524. return rval;
  525. };
  526. /**
  527. * Converts ASN.1 CRIAttributes into an array with objects that have type and
  528. * value properties.
  529. *
  530. * @param attributes the CRIAttributes to convert.
  531. */
  532. pki.CRIAttributesAsArray = function(attributes) {
  533. var rval = [];
  534. // each value in 'attributes' in is a SEQUENCE with an OID and a SET
  535. for(var si = 0; si < attributes.length; ++si) {
  536. // get the attribute sequence
  537. var seq = attributes[si];
  538. // each value in the SEQUENCE containing first a type (an OID) and
  539. // second a set of values (defined by the OID)
  540. var type = asn1.derToOid(seq.value[0].value);
  541. var values = seq.value[1].value;
  542. for(var vi = 0; vi < values.length; ++vi) {
  543. var obj = {};
  544. obj.type = type;
  545. obj.value = values[vi].value;
  546. obj.valueTagClass = values[vi].type;
  547. // if the OID is known, get its name and short name
  548. if(obj.type in oids) {
  549. obj.name = oids[obj.type];
  550. if(obj.name in _shortNames) {
  551. obj.shortName = _shortNames[obj.name];
  552. }
  553. }
  554. // parse extensions
  555. if(obj.type === oids.extensionRequest) {
  556. obj.extensions = [];
  557. for(var ei = 0; ei < obj.value.length; ++ei) {
  558. obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));
  559. }
  560. }
  561. rval.push(obj);
  562. }
  563. }
  564. return rval;
  565. };
  566. /**
  567. * Gets an issuer or subject attribute from its name, type, or short name.
  568. *
  569. * @param obj the issuer or subject object.
  570. * @param options a short name string or an object with:
  571. * shortName the short name for the attribute.
  572. * name the name for the attribute.
  573. * type the type for the attribute.
  574. *
  575. * @return the attribute.
  576. */
  577. function _getAttribute(obj, options) {
  578. if(typeof options === 'string') {
  579. options = {shortName: options};
  580. }
  581. var rval = null;
  582. var attr;
  583. for(var i = 0; rval === null && i < obj.attributes.length; ++i) {
  584. attr = obj.attributes[i];
  585. if(options.type && options.type === attr.type) {
  586. rval = attr;
  587. } else if(options.name && options.name === attr.name) {
  588. rval = attr;
  589. } else if(options.shortName && options.shortName === attr.shortName) {
  590. rval = attr;
  591. }
  592. }
  593. return rval;
  594. }
  595. /**
  596. * Converts signature parameters from ASN.1 structure.
  597. *
  598. * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had
  599. * no parameters.
  600. *
  601. * RSASSA-PSS-params ::= SEQUENCE {
  602. * hashAlgorithm [0] HashAlgorithm DEFAULT
  603. * sha1Identifier,
  604. * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT
  605. * mgf1SHA1Identifier,
  606. * saltLength [2] INTEGER DEFAULT 20,
  607. * trailerField [3] INTEGER DEFAULT 1
  608. * }
  609. *
  610. * HashAlgorithm ::= AlgorithmIdentifier
  611. *
  612. * MaskGenAlgorithm ::= AlgorithmIdentifier
  613. *
  614. * AlgorithmIdentifer ::= SEQUENCE {
  615. * algorithm OBJECT IDENTIFIER,
  616. * parameters ANY DEFINED BY algorithm OPTIONAL
  617. * }
  618. *
  619. * @param oid The OID specifying the signature algorithm
  620. * @param obj The ASN.1 structure holding the parameters
  621. * @param fillDefaults Whether to use return default values where omitted
  622. * @return signature parameter object
  623. */
  624. var _readSignatureParameters = function(oid, obj, fillDefaults) {
  625. var params = {};
  626. if(oid !== oids['RSASSA-PSS']) {
  627. return params;
  628. }
  629. if(fillDefaults) {
  630. params = {
  631. hash: {
  632. algorithmOid: oids['sha1']
  633. },
  634. mgf: {
  635. algorithmOid: oids['mgf1'],
  636. hash: {
  637. algorithmOid: oids['sha1']
  638. }
  639. },
  640. saltLength: 20
  641. };
  642. }
  643. var capture = {};
  644. var errors = [];
  645. if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {
  646. var error = new Error('Cannot read RSASSA-PSS parameter block.');
  647. error.errors = errors;
  648. throw error;
  649. }
  650. if(capture.hashOid !== undefined) {
  651. params.hash = params.hash || {};
  652. params.hash.algorithmOid = asn1.derToOid(capture.hashOid);
  653. }
  654. if(capture.maskGenOid !== undefined) {
  655. params.mgf = params.mgf || {};
  656. params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);
  657. params.mgf.hash = params.mgf.hash || {};
  658. params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);
  659. }
  660. if(capture.saltLength !== undefined) {
  661. params.saltLength = capture.saltLength.charCodeAt(0);
  662. }
  663. return params;
  664. };
  665. /**
  666. * Converts an X.509 certificate from PEM format.
  667. *
  668. * Note: If the certificate is to be verified then compute hash should
  669. * be set to true. This will scan the TBSCertificate part of the ASN.1
  670. * object while it is converted so it doesn't need to be converted back
  671. * to ASN.1-DER-encoding later.
  672. *
  673. * @param pem the PEM-formatted certificate.
  674. * @param computeHash true to compute the hash for verification.
  675. * @param strict true to be strict when checking ASN.1 value lengths, false to
  676. * allow truncated values (default: true).
  677. *
  678. * @return the certificate.
  679. */
  680. pki.certificateFromPem = function(pem, computeHash, strict) {
  681. var msg = forge.pem.decode(pem)[0];
  682. if(msg.type !== 'CERTIFICATE' &&
  683. msg.type !== 'X509 CERTIFICATE' &&
  684. msg.type !== 'TRUSTED CERTIFICATE') {
  685. var error = new Error(
  686. 'Could not convert certificate from PEM; PEM header type ' +
  687. 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');
  688. error.headerType = msg.type;
  689. throw error;
  690. }
  691. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  692. throw new Error(
  693. 'Could not convert certificate from PEM; PEM is encrypted.');
  694. }
  695. // convert DER to ASN.1 object
  696. var obj = asn1.fromDer(msg.body, strict);
  697. return pki.certificateFromAsn1(obj, computeHash);
  698. };
  699. /**
  700. * Converts an X.509 certificate to PEM format.
  701. *
  702. * @param cert the certificate.
  703. * @param maxline the maximum characters per line, defaults to 64.
  704. *
  705. * @return the PEM-formatted certificate.
  706. */
  707. pki.certificateToPem = function(cert, maxline) {
  708. // convert to ASN.1, then DER, then PEM-encode
  709. var msg = {
  710. type: 'CERTIFICATE',
  711. body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()
  712. };
  713. return forge.pem.encode(msg, {maxline: maxline});
  714. };
  715. /**
  716. * Converts an RSA public key from PEM format.
  717. *
  718. * @param pem the PEM-formatted public key.
  719. *
  720. * @return the public key.
  721. */
  722. pki.publicKeyFromPem = function(pem) {
  723. var msg = forge.pem.decode(pem)[0];
  724. if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {
  725. var error = new Error('Could not convert public key from PEM; PEM header ' +
  726. 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');
  727. error.headerType = msg.type;
  728. throw error;
  729. }
  730. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  731. throw new Error('Could not convert public key from PEM; PEM is encrypted.');
  732. }
  733. // convert DER to ASN.1 object
  734. var obj = asn1.fromDer(msg.body);
  735. return pki.publicKeyFromAsn1(obj);
  736. };
  737. /**
  738. * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).
  739. *
  740. * @param key the public key.
  741. * @param maxline the maximum characters per line, defaults to 64.
  742. *
  743. * @return the PEM-formatted public key.
  744. */
  745. pki.publicKeyToPem = function(key, maxline) {
  746. // convert to ASN.1, then DER, then PEM-encode
  747. var msg = {
  748. type: 'PUBLIC KEY',
  749. body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()
  750. };
  751. return forge.pem.encode(msg, {maxline: maxline});
  752. };
  753. /**
  754. * Converts an RSA public key to PEM format (using an RSAPublicKey).
  755. *
  756. * @param key the public key.
  757. * @param maxline the maximum characters per line, defaults to 64.
  758. *
  759. * @return the PEM-formatted public key.
  760. */
  761. pki.publicKeyToRSAPublicKeyPem = function(key, maxline) {
  762. // convert to ASN.1, then DER, then PEM-encode
  763. var msg = {
  764. type: 'RSA PUBLIC KEY',
  765. body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()
  766. };
  767. return forge.pem.encode(msg, {maxline: maxline});
  768. };
  769. /**
  770. * Gets a fingerprint for the given public key.
  771. *
  772. * @param options the options to use.
  773. * [md] the message digest object to use (defaults to forge.md.sha1).
  774. * [type] the type of fingerprint, such as 'RSAPublicKey',
  775. * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').
  776. * [encoding] an alternative output encoding, such as 'hex'
  777. * (defaults to none, outputs a byte buffer).
  778. * [delimiter] the delimiter to use between bytes for 'hex' encoded
  779. * output, eg: ':' (defaults to none).
  780. *
  781. * @return the fingerprint as a byte buffer or other encoding based on options.
  782. */
  783. pki.getPublicKeyFingerprint = function(key, options) {
  784. options = options || {};
  785. var md = options.md || forge.md.sha1.create();
  786. var type = options.type || 'RSAPublicKey';
  787. var bytes;
  788. switch(type) {
  789. case 'RSAPublicKey':
  790. bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();
  791. break;
  792. case 'SubjectPublicKeyInfo':
  793. bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();
  794. break;
  795. default:
  796. throw new Error('Unknown fingerprint type "' + options.type + '".');
  797. }
  798. // hash public key bytes
  799. md.start();
  800. md.update(bytes);
  801. var digest = md.digest();
  802. if(options.encoding === 'hex') {
  803. var hex = digest.toHex();
  804. if(options.delimiter) {
  805. return hex.match(/.{2}/g).join(options.delimiter);
  806. }
  807. return hex;
  808. } else if(options.encoding === 'binary') {
  809. return digest.getBytes();
  810. } else if(options.encoding) {
  811. throw new Error('Unknown encoding "' + options.encoding + '".');
  812. }
  813. return digest;
  814. };
  815. /**
  816. * Converts a PKCS#10 certification request (CSR) from PEM format.
  817. *
  818. * Note: If the certification request is to be verified then compute hash
  819. * should be set to true. This will scan the CertificationRequestInfo part of
  820. * the ASN.1 object while it is converted so it doesn't need to be converted
  821. * back to ASN.1-DER-encoding later.
  822. *
  823. * @param pem the PEM-formatted certificate.
  824. * @param computeHash true to compute the hash for verification.
  825. * @param strict true to be strict when checking ASN.1 value lengths, false to
  826. * allow truncated values (default: true).
  827. *
  828. * @return the certification request (CSR).
  829. */
  830. pki.certificationRequestFromPem = function(pem, computeHash, strict) {
  831. var msg = forge.pem.decode(pem)[0];
  832. if(msg.type !== 'CERTIFICATE REQUEST') {
  833. var error = new Error('Could not convert certification request from PEM; ' +
  834. 'PEM header type is not "CERTIFICATE REQUEST".');
  835. error.headerType = msg.type;
  836. throw error;
  837. }
  838. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  839. throw new Error('Could not convert certification request from PEM; ' +
  840. 'PEM is encrypted.');
  841. }
  842. // convert DER to ASN.1 object
  843. var obj = asn1.fromDer(msg.body, strict);
  844. return pki.certificationRequestFromAsn1(obj, computeHash);
  845. };
  846. /**
  847. * Converts a PKCS#10 certification request (CSR) to PEM format.
  848. *
  849. * @param csr the certification request.
  850. * @param maxline the maximum characters per line, defaults to 64.
  851. *
  852. * @return the PEM-formatted certification request.
  853. */
  854. pki.certificationRequestToPem = function(csr, maxline) {
  855. // convert to ASN.1, then DER, then PEM-encode
  856. var msg = {
  857. type: 'CERTIFICATE REQUEST',
  858. body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()
  859. };
  860. return forge.pem.encode(msg, {maxline: maxline});
  861. };
  862. /**
  863. * Creates an empty X.509v3 RSA certificate.
  864. *
  865. * @return the certificate.
  866. */
  867. pki.createCertificate = function() {
  868. var cert = {};
  869. cert.version = 0x02;
  870. cert.serialNumber = '00';
  871. cert.signatureOid = null;
  872. cert.signature = null;
  873. cert.siginfo = {};
  874. cert.siginfo.algorithmOid = null;
  875. cert.validity = {};
  876. cert.validity.notBefore = new Date();
  877. cert.validity.notAfter = new Date();
  878. cert.issuer = {};
  879. cert.issuer.getField = function(sn) {
  880. return _getAttribute(cert.issuer, sn);
  881. };
  882. cert.issuer.addField = function(attr) {
  883. _fillMissingFields([attr]);
  884. cert.issuer.attributes.push(attr);
  885. };
  886. cert.issuer.attributes = [];
  887. cert.issuer.hash = null;
  888. cert.subject = {};
  889. cert.subject.getField = function(sn) {
  890. return _getAttribute(cert.subject, sn);
  891. };
  892. cert.subject.addField = function(attr) {
  893. _fillMissingFields([attr]);
  894. cert.subject.attributes.push(attr);
  895. };
  896. cert.subject.attributes = [];
  897. cert.subject.hash = null;
  898. cert.extensions = [];
  899. cert.publicKey = null;
  900. cert.md = null;
  901. /**
  902. * Sets the subject of this certificate.
  903. *
  904. * @param attrs the array of subject attributes to use.
  905. * @param uniqueId an optional a unique ID to use.
  906. */
  907. cert.setSubject = function(attrs, uniqueId) {
  908. // set new attributes, clear hash
  909. _fillMissingFields(attrs);
  910. cert.subject.attributes = attrs;
  911. delete cert.subject.uniqueId;
  912. if(uniqueId) {
  913. // TODO: support arbitrary bit length ids
  914. cert.subject.uniqueId = uniqueId;
  915. }
  916. cert.subject.hash = null;
  917. };
  918. /**
  919. * Sets the issuer of this certificate.
  920. *
  921. * @param attrs the array of issuer attributes to use.
  922. * @param uniqueId an optional a unique ID to use.
  923. */
  924. cert.setIssuer = function(attrs, uniqueId) {
  925. // set new attributes, clear hash
  926. _fillMissingFields(attrs);
  927. cert.issuer.attributes = attrs;
  928. delete cert.issuer.uniqueId;
  929. if(uniqueId) {
  930. // TODO: support arbitrary bit length ids
  931. cert.issuer.uniqueId = uniqueId;
  932. }
  933. cert.issuer.hash = null;
  934. };
  935. /**
  936. * Sets the extensions of this certificate.
  937. *
  938. * @param exts the array of extensions to use.
  939. */
  940. cert.setExtensions = function(exts) {
  941. for(var i = 0; i < exts.length; ++i) {
  942. _fillMissingExtensionFields(exts[i], {cert: cert});
  943. }
  944. // set new extensions
  945. cert.extensions = exts;
  946. };
  947. /**
  948. * Gets an extension by its name or id.
  949. *
  950. * @param options the name to use or an object with:
  951. * name the name to use.
  952. * id the id to use.
  953. *
  954. * @return the extension or null if not found.
  955. */
  956. cert.getExtension = function(options) {
  957. if(typeof options === 'string') {
  958. options = {name: options};
  959. }
  960. var rval = null;
  961. var ext;
  962. for(var i = 0; rval === null && i < cert.extensions.length; ++i) {
  963. ext = cert.extensions[i];
  964. if(options.id && ext.id === options.id) {
  965. rval = ext;
  966. } else if(options.name && ext.name === options.name) {
  967. rval = ext;
  968. }
  969. }
  970. return rval;
  971. };
  972. /**
  973. * Signs this certificate using the given private key.
  974. *
  975. * @param key the private key to sign with.
  976. * @param md the message digest object to use (defaults to forge.md.sha1).
  977. */
  978. cert.sign = function(key, md) {
  979. // TODO: get signature OID from private key
  980. cert.md = md || forge.md.sha1.create();
  981. var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];
  982. if(!algorithmOid) {
  983. var error = new Error('Could not compute certificate digest. ' +
  984. 'Unknown message digest algorithm OID.');
  985. error.algorithm = cert.md.algorithm;
  986. throw error;
  987. }
  988. cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;
  989. // get TBSCertificate, convert to DER
  990. cert.tbsCertificate = pki.getTBSCertificate(cert);
  991. var bytes = asn1.toDer(cert.tbsCertificate);
  992. // digest and sign
  993. cert.md.update(bytes.getBytes());
  994. cert.signature = key.sign(cert.md);
  995. };
  996. /**
  997. * Attempts verify the signature on the passed certificate using this
  998. * certificate's public key.
  999. *
  1000. * @param child the certificate to verify.
  1001. *
  1002. * @return true if verified, false if not.
  1003. */
  1004. cert.verify = function(child) {
  1005. var rval = false;
  1006. if(!cert.issued(child)) {
  1007. var issuer = child.issuer;
  1008. var subject = cert.subject;
  1009. var error = new Error(
  1010. 'The parent certificate did not issue the given child ' +
  1011. 'certificate; the child certificate\'s issuer does not match the ' +
  1012. 'parent\'s subject.');
  1013. error.expectedIssuer = issuer.attributes;
  1014. error.actualIssuer = subject.attributes;
  1015. throw error;
  1016. }
  1017. var md = child.md;
  1018. if(md === null) {
  1019. // check signature OID for supported signature types
  1020. if(child.signatureOid in oids) {
  1021. var oid = oids[child.signatureOid];
  1022. switch(oid) {
  1023. case 'sha1WithRSAEncryption':
  1024. md = forge.md.sha1.create();
  1025. break;
  1026. case 'md5WithRSAEncryption':
  1027. md = forge.md.md5.create();
  1028. break;
  1029. case 'sha256WithRSAEncryption':
  1030. md = forge.md.sha256.create();
  1031. break;
  1032. case 'sha384WithRSAEncryption':
  1033. md = forge.md.sha384.create();
  1034. break;
  1035. case 'sha512WithRSAEncryption':
  1036. md = forge.md.sha512.create();
  1037. break;
  1038. case 'RSASSA-PSS':
  1039. md = forge.md.sha256.create();
  1040. break;
  1041. }
  1042. }
  1043. if(md === null) {
  1044. var error = new Error('Could not compute certificate digest. ' +
  1045. 'Unknown signature OID.');
  1046. error.signatureOid = child.signatureOid;
  1047. throw error;
  1048. }
  1049. // produce DER formatted TBSCertificate and digest it
  1050. var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);
  1051. var bytes = asn1.toDer(tbsCertificate);
  1052. md.update(bytes.getBytes());
  1053. }
  1054. if(md !== null) {
  1055. var scheme;
  1056. switch(child.signatureOid) {
  1057. case oids.sha1WithRSAEncryption:
  1058. scheme = undefined; /* use PKCS#1 v1.5 padding scheme */
  1059. break;
  1060. case oids['RSASSA-PSS']:
  1061. var hash, mgf;
  1062. /* initialize mgf */
  1063. hash = oids[child.signatureParameters.mgf.hash.algorithmOid];
  1064. if(hash === undefined || forge.md[hash] === undefined) {
  1065. var error = new Error('Unsupported MGF hash function.');
  1066. error.oid = child.signatureParameters.mgf.hash.algorithmOid;
  1067. error.name = hash;
  1068. throw error;
  1069. }
  1070. mgf = oids[child.signatureParameters.mgf.algorithmOid];
  1071. if(mgf === undefined || forge.mgf[mgf] === undefined) {
  1072. var error = new Error('Unsupported MGF function.');
  1073. error.oid = child.signatureParameters.mgf.algorithmOid;
  1074. error.name = mgf;
  1075. throw error;
  1076. }
  1077. mgf = forge.mgf[mgf].create(forge.md[hash].create());
  1078. /* initialize hash function */
  1079. hash = oids[child.signatureParameters.hash.algorithmOid];
  1080. if(hash === undefined || forge.md[hash] === undefined) {
  1081. throw {
  1082. message: 'Unsupported RSASSA-PSS hash function.',
  1083. oid: child.signatureParameters.hash.algorithmOid,
  1084. name: hash
  1085. };
  1086. }
  1087. scheme = forge.pss.create(forge.md[hash].create(), mgf,
  1088. child.signatureParameters.saltLength);
  1089. break;
  1090. }
  1091. // verify signature on cert using public key
  1092. rval = cert.publicKey.verify(
  1093. md.digest().getBytes(), child.signature, scheme);
  1094. }
  1095. return rval;
  1096. };
  1097. /**
  1098. * Returns true if this certificate's issuer matches the passed
  1099. * certificate's subject. Note that no signature check is performed.
  1100. *
  1101. * @param parent the certificate to check.
  1102. *
  1103. * @return true if this certificate's issuer matches the passed certificate's
  1104. * subject.
  1105. */
  1106. cert.isIssuer = function(parent) {
  1107. var rval = false;
  1108. var i = cert.issuer;
  1109. var s = parent.subject;
  1110. // compare hashes if present
  1111. if(i.hash && s.hash) {
  1112. rval = (i.hash === s.hash);
  1113. } else if(i.attributes.length === s.attributes.length) {
  1114. // all attributes are the same so issuer matches subject
  1115. rval = true;
  1116. var iattr, sattr;
  1117. for(var n = 0; rval && n < i.attributes.length; ++n) {
  1118. iattr = i.attributes[n];
  1119. sattr = s.attributes[n];
  1120. if(iattr.type !== sattr.type || iattr.value !== sattr.value) {
  1121. // attribute mismatch
  1122. rval = false;
  1123. }
  1124. }
  1125. }
  1126. return rval;
  1127. };
  1128. /**
  1129. * Returns true if this certificate's subject matches the issuer of the
  1130. * given certificate). Note that not signature check is performed.
  1131. *
  1132. * @param child the certificate to check.
  1133. *
  1134. * @return true if this certificate's subject matches the passed
  1135. * certificate's issuer.
  1136. */
  1137. cert.issued = function(child) {
  1138. return child.isIssuer(cert);
  1139. };
  1140. /**
  1141. * Generates the subjectKeyIdentifier for this certificate as byte buffer.
  1142. *
  1143. * @return the subjectKeyIdentifier for this certificate as byte buffer.
  1144. */
  1145. cert.generateSubjectKeyIdentifier = function() {
  1146. /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:
  1147. (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
  1148. value of the BIT STRING subjectPublicKey (excluding the tag,
  1149. length, and number of unused bits).
  1150. (2) The keyIdentifier is composed of a four bit type field with
  1151. the value 0100 followed by the least significant 60 bits of the
  1152. SHA-1 hash of the value of the BIT STRING subjectPublicKey
  1153. (excluding the tag, length, and number of unused bit string bits).
  1154. */
  1155. // skipping the tag, length, and number of unused bits is the same
  1156. // as just using the RSAPublicKey (for RSA keys, which are the
  1157. // only ones supported)
  1158. return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});
  1159. };
  1160. /**
  1161. * Verifies the subjectKeyIdentifier extension value for this certificate
  1162. * against its public key. If no extension is found, false will be
  1163. * returned.
  1164. *
  1165. * @return true if verified, false if not.
  1166. */
  1167. cert.verifySubjectKeyIdentifier = function() {
  1168. var oid = oids['subjectKeyIdentifier'];
  1169. for(var i = 0; i < cert.extensions.length; ++i) {
  1170. var ext = cert.extensions[i];
  1171. if(ext.id === oid) {
  1172. var ski = cert.generateSubjectKeyIdentifier().getBytes();
  1173. return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);
  1174. }
  1175. }
  1176. return false;
  1177. };
  1178. return cert;
  1179. };
  1180. /**
  1181. * Converts an X.509v3 RSA certificate from an ASN.1 object.
  1182. *
  1183. * Note: If the certificate is to be verified then compute hash should
  1184. * be set to true. There is currently no implementation for converting
  1185. * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1
  1186. * object needs to be scanned before the cert object is created.
  1187. *
  1188. * @param obj the asn1 representation of an X.509v3 RSA certificate.
  1189. * @param computeHash true to compute the hash for verification.
  1190. *
  1191. * @return the certificate.
  1192. */
  1193. pki.certificateFromAsn1 = function(obj, computeHash) {
  1194. // validate certificate and capture data
  1195. var capture = {};
  1196. var errors = [];
  1197. if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {
  1198. var error = new Error('Cannot read X.509 certificate. ' +
  1199. 'ASN.1 object is not an X509v3 Certificate.');
  1200. error.errors = errors;
  1201. throw error;
  1202. }
  1203. // get oid
  1204. var oid = asn1.derToOid(capture.publicKeyOid);
  1205. if(oid !== pki.oids.rsaEncryption) {
  1206. throw new Error('Cannot read public key. OID is not RSA.');
  1207. }
  1208. // create certificate
  1209. var cert = pki.createCertificate();
  1210. cert.version = capture.certVersion ?
  1211. capture.certVersion.charCodeAt(0) : 0;
  1212. var serial = forge.util.createBuffer(capture.certSerialNumber);
  1213. cert.serialNumber = serial.toHex();
  1214. cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);
  1215. cert.signatureParameters = _readSignatureParameters(
  1216. cert.signatureOid, capture.certSignatureParams, true);
  1217. cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);
  1218. cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,
  1219. capture.certinfoSignatureParams, false);
  1220. cert.signature = capture.certSignature;
  1221. var validity = [];
  1222. if(capture.certValidity1UTCTime !== undefined) {
  1223. validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));
  1224. }
  1225. if(capture.certValidity2GeneralizedTime !== undefined) {
  1226. validity.push(asn1.generalizedTimeToDate(
  1227. capture.certValidity2GeneralizedTime));
  1228. }
  1229. if(capture.certValidity3UTCTime !== undefined) {
  1230. validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));
  1231. }
  1232. if(capture.certValidity4GeneralizedTime !== undefined) {
  1233. validity.push(asn1.generalizedTimeToDate(
  1234. capture.certValidity4GeneralizedTime));
  1235. }
  1236. if(validity.length > 2) {
  1237. throw new Error('Cannot read notBefore/notAfter validity times; more ' +
  1238. 'than two times were provided in the certificate.');
  1239. }
  1240. if(validity.length < 2) {
  1241. throw new Error('Cannot read notBefore/notAfter validity times; they ' +
  1242. 'were not provided as either UTCTime or GeneralizedTime.');
  1243. }
  1244. cert.validity.notBefore = validity[0];
  1245. cert.validity.notAfter = validity[1];
  1246. // keep TBSCertificate to preserve signature when exporting
  1247. cert.tbsCertificate = capture.tbsCertificate;
  1248. if(computeHash) {
  1249. // check signature OID for supported signature types
  1250. cert.md = null;
  1251. if(cert.signatureOid in oids) {
  1252. var oid = oids[cert.signatureOid];
  1253. switch(oid) {
  1254. case 'sha1WithRSAEncryption':
  1255. cert.md = forge.md.sha1.create();
  1256. break;
  1257. case 'md5WithRSAEncryption':
  1258. cert.md = forge.md.md5.create();
  1259. break;
  1260. case 'sha256WithRSAEncryption':
  1261. cert.md = forge.md.sha256.create();
  1262. break;
  1263. case 'sha384WithRSAEncryption':
  1264. cert.md = forge.md.sha384.create();
  1265. break;
  1266. case 'sha512WithRSAEncryption':
  1267. cert.md = forge.md.sha512.create();
  1268. break;
  1269. case 'RSASSA-PSS':
  1270. cert.md = forge.md.sha256.create();
  1271. break;
  1272. }
  1273. }
  1274. if(cert.md === null) {
  1275. var error = new Error('Could not compute certificate digest. ' +
  1276. 'Unknown signature OID.');
  1277. error.signatureOid = cert.signatureOid;
  1278. throw error;
  1279. }
  1280. // produce DER formatted TBSCertificate and digest it
  1281. var bytes = asn1.toDer(cert.tbsCertificate);
  1282. cert.md.update(bytes.getBytes());
  1283. }
  1284. // handle issuer, build issuer message digest
  1285. var imd = forge.md.sha1.create();
  1286. cert.issuer.getField = function(sn) {
  1287. return _getAttribute(cert.issuer, sn);
  1288. };
  1289. cert.issuer.addField = function(attr) {
  1290. _fillMissingFields([attr]);
  1291. cert.issuer.attributes.push(attr);
  1292. };
  1293. cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer, imd);
  1294. if(capture.certIssuerUniqueId) {
  1295. cert.issuer.uniqueId = capture.certIssuerUniqueId;
  1296. }
  1297. cert.issuer.hash = imd.digest().toHex();
  1298. // handle subject, build subject message digest
  1299. var smd = forge.md.sha1.create();
  1300. cert.subject.getField = function(sn) {
  1301. return _getAttribute(cert.subject, sn);
  1302. };
  1303. cert.subject.addField = function(attr) {
  1304. _fillMissingFields([attr]);
  1305. cert.subject.attributes.push(attr);
  1306. };
  1307. cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject, smd);
  1308. if(capture.certSubjectUniqueId) {
  1309. cert.subject.uniqueId = capture.certSubjectUniqueId;
  1310. }
  1311. cert.subject.hash = smd.digest().toHex();
  1312. // handle extensions
  1313. if(capture.certExtensions) {
  1314. cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);
  1315. } else {
  1316. cert.extensions = [];
  1317. }
  1318. // convert RSA public key from ASN.1
  1319. cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
  1320. return cert;
  1321. };
  1322. /**
  1323. * Converts an ASN.1 extensions object (with extension sequences as its
  1324. * values) into an array of extension objects with types and values.
  1325. *
  1326. * Supported extensions:
  1327. *
  1328. * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
  1329. * KeyUsage ::= BIT STRING {
  1330. * digitalSignature (0),
  1331. * nonRepudiation (1),
  1332. * keyEncipherment (2),
  1333. * dataEncipherment (3),
  1334. * keyAgreement (4),
  1335. * keyCertSign (5),
  1336. * cRLSign (6),
  1337. * encipherOnly (7),
  1338. * decipherOnly (8)
  1339. * }
  1340. *
  1341. * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }
  1342. * BasicConstraints ::= SEQUENCE {
  1343. * cA BOOLEAN DEFAULT FALSE,
  1344. * pathLenConstraint INTEGER (0..MAX) OPTIONAL
  1345. * }
  1346. *
  1347. * subjectAltName EXTENSION ::= {
  1348. * SYNTAX GeneralNames
  1349. * IDENTIFIED BY id-ce-subjectAltName
  1350. * }
  1351. *
  1352. * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  1353. *
  1354. * GeneralName ::= CHOICE {
  1355. * otherName [0] INSTANCE OF OTHER-NAME,
  1356. * rfc822Name [1] IA5String,
  1357. * dNSName [2] IA5String,
  1358. * x400Address [3] ORAddress,
  1359. * directoryName [4] Name,
  1360. * ediPartyName [5] EDIPartyName,
  1361. * uniformResourceIdentifier [6] IA5String,
  1362. * IPAddress [7] OCTET STRING,
  1363. * registeredID [8] OBJECT IDENTIFIER
  1364. * }
  1365. *
  1366. * OTHER-NAME ::= TYPE-IDENTIFIER
  1367. *
  1368. * EDIPartyName ::= SEQUENCE {
  1369. * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,
  1370. * partyName [1] DirectoryString {ub-name}
  1371. * }
  1372. *
  1373. * @param exts the extensions ASN.1 with extension sequences to parse.
  1374. *
  1375. * @return the array.
  1376. */
  1377. pki.certificateExtensionsFromAsn1 = function(exts) {
  1378. var rval = [];
  1379. for(var i = 0; i < exts.value.length; ++i) {
  1380. // get extension sequence
  1381. var extseq = exts.value[i];
  1382. for(var ei = 0; ei < extseq.value.length; ++ei) {
  1383. rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));
  1384. }
  1385. }
  1386. return rval;
  1387. };
  1388. /**
  1389. * Parses a single certificate extension from ASN.1.
  1390. *
  1391. * @param ext the extension in ASN.1 format.
  1392. *
  1393. * @return the parsed extension as an object.
  1394. */
  1395. pki.certificateExtensionFromAsn1 = function(ext) {
  1396. // an extension has:
  1397. // [0] extnID OBJECT IDENTIFIER
  1398. // [1] critical BOOLEAN DEFAULT FALSE
  1399. // [2] extnValue OCTET STRING
  1400. var e = {};
  1401. e.id = asn1.derToOid(ext.value[0].value);
  1402. e.critical = false;
  1403. if(ext.value[1].type === asn1.Type.BOOLEAN) {
  1404. e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);
  1405. e.value = ext.value[2].value;
  1406. } else {
  1407. e.value = ext.value[1].value;
  1408. }
  1409. // if the oid is known, get its name
  1410. if(e.id in oids) {
  1411. e.name = oids[e.id];
  1412. // handle key usage
  1413. if(e.name === 'keyUsage') {
  1414. // get value as BIT STRING
  1415. var ev = asn1.fromDer(e.value);
  1416. var b2 = 0x00;
  1417. var b3 = 0x00;
  1418. if(ev.value.length > 1) {
  1419. // skip first byte, just indicates unused bits which
  1420. // will be padded with 0s anyway
  1421. // get bytes with flag bits
  1422. b2 = ev.value.charCodeAt(1);
  1423. b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;
  1424. }
  1425. // set flags
  1426. e.digitalSignature = (b2 & 0x80) === 0x80;
  1427. e.nonRepudiation = (b2 & 0x40) === 0x40;
  1428. e.keyEncipherment = (b2 & 0x20) === 0x20;
  1429. e.dataEncipherment = (b2 & 0x10) === 0x10;
  1430. e.keyAgreement = (b2 & 0x08) === 0x08;
  1431. e.keyCertSign = (b2 & 0x04) === 0x04;
  1432. e.cRLSign = (b2 & 0x02) === 0x02;
  1433. e.encipherOnly = (b2 & 0x01) === 0x01;
  1434. e.decipherOnly = (b3 & 0x80) === 0x80;
  1435. } else if(e.name === 'basicConstraints') {
  1436. // handle basic constraints
  1437. // get value as SEQUENCE
  1438. var ev = asn1.fromDer(e.value);
  1439. // get cA BOOLEAN flag (defaults to false)
  1440. if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {
  1441. e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);
  1442. } else {
  1443. e.cA = false;
  1444. }
  1445. // get path length constraint
  1446. var value = null;
  1447. if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {
  1448. value = ev.value[0].value;
  1449. } else if(ev.value.length > 1) {
  1450. value = ev.value[1].value;
  1451. }
  1452. if(value !== null) {
  1453. e.pathLenConstraint = asn1.derToInteger(value);
  1454. }
  1455. } else if(e.name === 'extKeyUsage') {
  1456. // handle extKeyUsage
  1457. // value is a SEQUENCE of OIDs
  1458. var ev = asn1.fromDer(e.value);
  1459. for(var vi = 0; vi < ev.value.length; ++vi) {
  1460. var oid = asn1.derToOid(ev.value[vi].value);
  1461. if(oid in oids) {
  1462. e[oids[oid]] = true;
  1463. } else {
  1464. e[oid] = true;
  1465. }
  1466. }
  1467. } else if(e.name === 'nsCertType') {
  1468. // handle nsCertType
  1469. // get value as BIT STRING
  1470. var ev = asn1.fromDer(e.value);
  1471. var b2 = 0x00;
  1472. if(ev.value.length > 1) {
  1473. // skip first byte, just indicates unused bits which
  1474. // will be padded with 0s anyway
  1475. // get bytes with flag bits
  1476. b2 = ev.value.charCodeAt(1);
  1477. }
  1478. // set flags
  1479. e.client = (b2 & 0x80) === 0x80;
  1480. e.server = (b2 & 0x40) === 0x40;
  1481. e.email = (b2 & 0x20) === 0x20;
  1482. e.objsign = (b2 & 0x10) === 0x10;
  1483. e.reserved = (b2 & 0x08) === 0x08;
  1484. e.sslCA = (b2 & 0x04) === 0x04;
  1485. e.emailCA = (b2 & 0x02) === 0x02;
  1486. e.objCA = (b2 & 0x01) === 0x01;
  1487. } else if(
  1488. e.name === 'subjectAltName' ||
  1489. e.name === 'issuerAltName') {
  1490. // handle subjectAltName/issuerAltName
  1491. e.altNames = [];
  1492. // ev is a SYNTAX SEQUENCE
  1493. var gn;
  1494. var ev = asn1.fromDer(e.value);
  1495. for(var n = 0; n < ev.value.length; ++n) {
  1496. // get GeneralName
  1497. gn = ev.value[n];
  1498. var altName = {
  1499. type: gn.type,
  1500. value: gn.value
  1501. };
  1502. e.altNames.push(altName);
  1503. // Note: Support for types 1,2,6,7,8
  1504. switch(gn.type) {
  1505. // rfc822Name
  1506. case 1:
  1507. // dNSName
  1508. case 2:
  1509. // uniformResourceIdentifier (URI)
  1510. case 6:
  1511. break;
  1512. // IPAddress
  1513. case 7:
  1514. // convert to IPv4/IPv6 string representation
  1515. altName.ip = forge.util.bytesToIP(gn.value);
  1516. break;
  1517. // registeredID
  1518. case 8:
  1519. altName.oid = asn1.derToOid(gn.value);
  1520. break;
  1521. default:
  1522. // unsupported
  1523. }
  1524. }
  1525. } else if(e.name === 'subjectKeyIdentifier') {
  1526. // value is an OCTETSTRING w/the hash of the key-type specific
  1527. // public key structure (eg: RSAPublicKey)
  1528. var ev = asn1.fromDer(e.value);
  1529. e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);
  1530. }
  1531. }
  1532. return e;
  1533. };
  1534. /**
  1535. * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.
  1536. *
  1537. * Note: If the certification request is to be verified then compute hash
  1538. * should be set to true. There is currently no implementation for converting
  1539. * a certificate back to ASN.1 so the CertificationRequestInfo part of the
  1540. * ASN.1 object needs to be scanned before the csr object is created.
  1541. *
  1542. * @param obj the asn1 representation of a PKCS#10 certification request (CSR).
  1543. * @param computeHash true to compute the hash for verification.
  1544. *
  1545. * @return the certification request (CSR).
  1546. */
  1547. pki.certificationRequestFromAsn1 = function(obj, computeHash) {
  1548. // validate certification request and capture data
  1549. var capture = {};
  1550. var errors = [];
  1551. if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {
  1552. var error = new Error('Cannot read PKCS#10 certificate request. ' +
  1553. 'ASN.1 object is not a PKCS#10 CertificationRequest.');
  1554. error.errors = errors;
  1555. throw error;
  1556. }
  1557. // get oid
  1558. var oid = asn1.derToOid(capture.publicKeyOid);
  1559. if(oid !== pki.oids.rsaEncryption) {
  1560. throw new Error('Cannot read public key. OID is not RSA.');
  1561. }
  1562. // create certification request
  1563. var csr = pki.createCertificationRequest();
  1564. csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;
  1565. csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);
  1566. csr.signatureParameters = _readSignatureParameters(
  1567. csr.signatureOid, capture.csrSignatureParams, true);
  1568. csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);
  1569. csr.siginfo.parameters = _readSignatureParameters(
  1570. csr.siginfo.algorithmOid, capture.csrSignatureParams, false);
  1571. csr.signature = capture.csrSignature;
  1572. // keep CertificationRequestInfo to preserve signature when exporting
  1573. csr.certificationRequestInfo = capture.certificationRequestInfo;
  1574. if(computeHash) {
  1575. // check signature OID for supported signature types
  1576. csr.md = null;
  1577. if(csr.signatureOid in oids) {
  1578. var oid = oids[csr.signatureOid];
  1579. switch(oid) {
  1580. case 'sha1WithRSAEncryption':
  1581. csr.md = forge.md.sha1.create();
  1582. break;
  1583. case 'md5WithRSAEncryption':
  1584. csr.md = forge.md.md5.create();
  1585. break;
  1586. case 'sha256WithRSAEncryption':
  1587. csr.md = forge.md.sha256.create();
  1588. break;
  1589. case 'sha384WithRSAEncryption':
  1590. csr.md = forge.md.sha384.create();
  1591. break;
  1592. case 'sha512WithRSAEncryption':
  1593. csr.md = forge.md.sha512.create();
  1594. break;
  1595. case 'RSASSA-PSS':
  1596. csr.md = forge.md.sha256.create();
  1597. break;
  1598. }
  1599. }
  1600. if(csr.md === null) {
  1601. var error = new Error('Could not compute certification request digest. ' +
  1602. 'Unknown signature OID.');
  1603. error.signatureOid = csr.signatureOid;
  1604. throw error;
  1605. }
  1606. // produce DER formatted CertificationRequestInfo and digest it
  1607. var bytes = asn1.toDer(csr.certificationRequestInfo);
  1608. csr.md.update(bytes.getBytes());
  1609. }
  1610. // handle subject, build subject message digest
  1611. var smd = forge.md.sha1.create();
  1612. csr.subject.getField = function(sn) {
  1613. return _getAttribute(csr.subject, sn);
  1614. };
  1615. csr.subject.addField = function(attr) {
  1616. _fillMissingFields([attr]);
  1617. csr.subject.attributes.push(attr);
  1618. };
  1619. csr.subject.attributes = pki.RDNAttributesAsArray(
  1620. capture.certificationRequestInfoSubject, smd);
  1621. csr.subject.hash = smd.digest().toHex();
  1622. // convert RSA public key from ASN.1
  1623. csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
  1624. // convert attributes from ASN.1
  1625. csr.getAttribute = function(sn) {
  1626. return _getAttribute(csr, sn);
  1627. };
  1628. csr.addAttribute = function(attr) {
  1629. _fillMissingFields([attr]);
  1630. csr.attributes.push(attr);
  1631. };
  1632. csr.attributes = pki.CRIAttributesAsArray(
  1633. capture.certificationRequestInfoAttributes || []);
  1634. return csr;
  1635. };
  1636. /**
  1637. * Creates an empty certification request (a CSR or certificate signing
  1638. * request). Once created, its public key and attributes can be set and then
  1639. * it can be signed.
  1640. *
  1641. * @return the empty certification request.
  1642. */
  1643. pki.createCertificationRequest = function() {
  1644. var csr = {};
  1645. csr.version = 0x00;
  1646. csr.signatureOid = null;
  1647. csr.signature = null;
  1648. csr.siginfo = {};
  1649. csr.siginfo.algorithmOid = null;
  1650. csr.subject = {};
  1651. csr.subject.getField = function(sn) {
  1652. return _getAttribute(csr.subject, sn);
  1653. };
  1654. csr.subject.addField = function(attr) {
  1655. _fillMissingFields([attr]);
  1656. csr.subject.attributes.push(attr);
  1657. };
  1658. csr.subject.attributes = [];
  1659. csr.subject.hash = null;
  1660. csr.publicKey = null;
  1661. csr.attributes = [];
  1662. csr.getAttribute = function(sn) {
  1663. return _getAttribute(csr, sn);
  1664. };
  1665. csr.addAttribute = function(attr) {
  1666. _fillMissingFields([attr]);
  1667. csr.attributes.push(attr);
  1668. };
  1669. csr.md = null;
  1670. /**
  1671. * Sets the subject of this certification request.
  1672. *
  1673. * @param attrs the array of subject attributes to use.
  1674. */
  1675. csr.setSubject = function(attrs) {
  1676. // set new attributes
  1677. _fillMissingFields(attrs);
  1678. csr.subject.attributes = attrs;
  1679. csr.subject.hash = null;
  1680. };
  1681. /**
  1682. * Sets the attributes of this certification request.
  1683. *
  1684. * @param attrs the array of attributes to use.
  1685. */
  1686. csr.setAttributes = function(attrs) {
  1687. // set new attributes
  1688. _fillMissingFields(attrs);
  1689. csr.attributes = attrs;
  1690. };
  1691. /**
  1692. * Signs this certification request using the given private key.
  1693. *
  1694. * @param key the private key to sign with.
  1695. * @param md the message digest object to use (defaults to forge.md.sha1).
  1696. */
  1697. csr.sign = function(key, md) {
  1698. // TODO: get signature OID from private key
  1699. csr.md = md || forge.md.sha1.create();
  1700. var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];
  1701. if(!algorithmOid) {
  1702. var error = new Error('Could not compute certification request digest. ' +
  1703. 'Unknown message digest algorithm OID.');
  1704. error.algorithm = csr.md.algorithm;
  1705. throw error;
  1706. }
  1707. csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;
  1708. // get CertificationRequestInfo, convert to DER
  1709. csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);
  1710. var bytes = asn1.toDer(csr.certificationRequestInfo);
  1711. // digest and sign
  1712. csr.md.update(bytes.getBytes());
  1713. csr.signature = key.sign(csr.md);
  1714. };
  1715. /**
  1716. * Attempts verify the signature on the passed certification request using
  1717. * its public key.
  1718. *
  1719. * A CSR that has been exported to a file in PEM format can be verified using
  1720. * OpenSSL using this command:
  1721. *
  1722. * openssl req -in <the-csr-pem-file> -verify -noout -text
  1723. *
  1724. * @return true if verified, false if not.
  1725. */
  1726. csr.verify = function() {
  1727. var rval = false;
  1728. var md = csr.md;
  1729. if(md === null) {
  1730. // check signature OID for supported signature types
  1731. if(csr.signatureOid in oids) {
  1732. // TODO: create DRY `OID to md` function
  1733. var oid = oids[csr.signatureOid];
  1734. switch(oid) {
  1735. case 'sha1WithRSAEncryption':
  1736. md = forge.md.sha1.create();
  1737. break;
  1738. case 'md5WithRSAEncryption':
  1739. md = forge.md.md5.create();
  1740. break;
  1741. case 'sha256WithRSAEncryption':
  1742. md = forge.md.sha256.create();
  1743. break;
  1744. case 'sha384WithRSAEncryption':
  1745. md = forge.md.sha384.create();
  1746. break;
  1747. case 'sha512WithRSAEncryption':
  1748. md = forge.md.sha512.create();
  1749. break;
  1750. case 'RSASSA-PSS':
  1751. md = forge.md.sha256.create();
  1752. break;
  1753. }
  1754. }
  1755. if(md === null) {
  1756. var error = new Error(
  1757. 'Could not compute certification request digest. ' +
  1758. 'Unknown signature OID.');
  1759. error.signatureOid = csr.signatureOid;
  1760. throw error;
  1761. }
  1762. // produce DER formatted CertificationRequestInfo and digest it
  1763. var cri = csr.certificationRequestInfo ||
  1764. pki.getCertificationRequestInfo(csr);
  1765. var bytes = asn1.toDer(cri);
  1766. md.update(bytes.getBytes());
  1767. }
  1768. if(md !== null) {
  1769. var scheme;
  1770. switch(csr.signatureOid) {
  1771. case oids.sha1WithRSAEncryption:
  1772. /* use PKCS#1 v1.5 padding scheme */
  1773. break;
  1774. case oids['RSASSA-PSS']:
  1775. var hash, mgf;
  1776. /* initialize mgf */
  1777. hash = oids[csr.signatureParameters.mgf.hash.algorithmOid];
  1778. if(hash === undefined || forge.md[hash] === undefined) {
  1779. var error = new Error('Unsupported MGF hash function.');
  1780. error.oid = csr.signatureParameters.mgf.hash.algorithmOid;
  1781. error.name = hash;
  1782. throw error;
  1783. }
  1784. mgf = oids[csr.signatureParameters.mgf.algorithmOid];
  1785. if(mgf === undefined || forge.mgf[mgf] === undefined) {
  1786. var error = new Error('Unsupported MGF function.');
  1787. error.oid = csr.signatureParameters.mgf.algorithmOid;
  1788. error.name = mgf;
  1789. throw error;
  1790. }
  1791. mgf = forge.mgf[mgf].create(forge.md[hash].create());
  1792. /* initialize hash function */
  1793. hash = oids[csr.signatureParameters.hash.algorithmOid];
  1794. if(hash === undefined || forge.md[hash] === undefined) {
  1795. var error = new Error('Unsupported RSASSA-PSS hash function.');
  1796. error.oid = csr.signatureParameters.hash.algorithmOid;
  1797. error.name = hash;
  1798. throw error;
  1799. }
  1800. scheme = forge.pss.create(forge.md[hash].create(), mgf,
  1801. csr.signatureParameters.saltLength);
  1802. break;
  1803. }
  1804. // verify signature on csr using its public key
  1805. rval = csr.publicKey.verify(
  1806. md.digest().getBytes(), csr.signature, scheme);
  1807. }
  1808. return rval;
  1809. };
  1810. return csr;
  1811. };
  1812. /**
  1813. * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.
  1814. *
  1815. * @param obj the subject or issuer (distinguished name).
  1816. *
  1817. * @return the ASN.1 RDNSequence.
  1818. */
  1819. function _dnToAsn1(obj) {
  1820. // create an empty RDNSequence
  1821. var rval = asn1.create(
  1822. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  1823. // iterate over attributes
  1824. var attr, set;
  1825. var attrs = obj.attributes;
  1826. for(var i = 0; i < attrs.length; ++i) {
  1827. attr = attrs[i];
  1828. var value = attr.value;
  1829. // reuse tag class for attribute value if available
  1830. var valueTagClass = asn1.Type.PRINTABLESTRING;
  1831. if('valueTagClass' in attr) {
  1832. valueTagClass = attr.valueTagClass;
  1833. if(valueTagClass === asn1.Type.UTF8) {
  1834. value = forge.util.encodeUtf8(value);
  1835. }
  1836. // FIXME: handle more encodings
  1837. }
  1838. // create a RelativeDistinguishedName set
  1839. // each value in the set is an AttributeTypeAndValue first
  1840. // containing the type (an OID) and second the value
  1841. set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
  1842. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1843. // AttributeType
  1844. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  1845. asn1.oidToDer(attr.type).getBytes()),
  1846. // AttributeValue
  1847. asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)
  1848. ])
  1849. ]);
  1850. rval.value.push(set);
  1851. }
  1852. return rval;
  1853. }
  1854. /**
  1855. * Gets all printable attributes (typically of an issuer or subject) in a
  1856. * simplified JSON format for display.
  1857. *
  1858. * @param attrs the attributes.
  1859. *
  1860. * @return the JSON for display.
  1861. */
  1862. function _getAttributesAsJson(attrs) {
  1863. var rval = {};
  1864. for(var i = 0; i < attrs.length; ++i) {
  1865. var attr = attrs[i];
  1866. if(attr.shortName && (
  1867. attr.valueTagClass === asn1.Type.UTF8 ||
  1868. attr.valueTagClass === asn1.Type.PRINTABLESTRING ||
  1869. attr.valueTagClass === asn1.Type.IA5STRING)) {
  1870. var value = attr.value;
  1871. if(attr.valueTagClass === asn1.Type.UTF8) {
  1872. value = forge.util.encodeUtf8(attr.value);
  1873. }
  1874. if(!(attr.shortName in rval)) {
  1875. rval[attr.shortName] = value;
  1876. } else if(forge.util.isArray(rval[attr.shortName])) {
  1877. rval[attr.shortName].push(value);
  1878. } else {
  1879. rval[attr.shortName] = [rval[attr.shortName], value];
  1880. }
  1881. }
  1882. }
  1883. return rval;
  1884. }
  1885. /**
  1886. * Fills in missing fields in attributes.
  1887. *
  1888. * @param attrs the attributes to fill missing fields in.
  1889. */
  1890. function _fillMissingFields(attrs) {
  1891. var attr;
  1892. for(var i = 0; i < attrs.length; ++i) {
  1893. attr = attrs[i];
  1894. // populate missing name
  1895. if(typeof attr.name === 'undefined') {
  1896. if(attr.type && attr.type in pki.oids) {
  1897. attr.name = pki.oids[attr.type];
  1898. } else if(attr.shortName && attr.shortName in _shortNames) {
  1899. attr.name = pki.oids[_shortNames[attr.shortName]];
  1900. }
  1901. }
  1902. // populate missing type (OID)
  1903. if(typeof attr.type === 'undefined') {
  1904. if(attr.name && attr.name in pki.oids) {
  1905. attr.type = pki.oids[attr.name];
  1906. } else {
  1907. var error = new Error('Attribute type not specified.');
  1908. error.attribute = attr;
  1909. throw error;
  1910. }
  1911. }
  1912. // populate missing shortname
  1913. if(typeof attr.shortName === 'undefined') {
  1914. if(attr.name && attr.name in _shortNames) {
  1915. attr.shortName = _shortNames[attr.name];
  1916. }
  1917. }
  1918. // convert extensions to value
  1919. if(attr.type === oids.extensionRequest) {
  1920. attr.valueConstructed = true;
  1921. attr.valueTagClass = asn1.Type.SEQUENCE;
  1922. if(!attr.value && attr.extensions) {
  1923. attr.value = [];
  1924. for(var ei = 0; ei < attr.extensions.length; ++ei) {
  1925. attr.value.push(pki.certificateExtensionToAsn1(
  1926. _fillMissingExtensionFields(attr.extensions[ei])));
  1927. }
  1928. }
  1929. }
  1930. if(typeof attr.value === 'undefined') {
  1931. var error = new Error('Attribute value not specified.');
  1932. error.attribute = attr;
  1933. throw error;
  1934. }
  1935. }
  1936. }
  1937. /**
  1938. * Fills in missing fields in certificate extensions.
  1939. *
  1940. * @param e the extension.
  1941. * @param [options] the options to use.
  1942. * [cert] the certificate the extensions are for.
  1943. *
  1944. * @return the extension.
  1945. */
  1946. function _fillMissingExtensionFields(e, options) {
  1947. options = options || {};
  1948. // populate missing name
  1949. if(typeof e.name === 'undefined') {
  1950. if(e.id && e.id in pki.oids) {
  1951. e.name = pki.oids[e.id];
  1952. }
  1953. }
  1954. // populate missing id
  1955. if(typeof e.id === 'undefined') {
  1956. if(e.name && e.name in pki.oids) {
  1957. e.id = pki.oids[e.name];
  1958. } else {
  1959. var error = new Error('Extension ID not specified.');
  1960. error.extension = e;
  1961. throw error;
  1962. }
  1963. }
  1964. if(typeof e.value !== 'undefined') {
  1965. return e;
  1966. }
  1967. // handle missing value:
  1968. // value is a BIT STRING
  1969. if(e.name === 'keyUsage') {
  1970. // build flags
  1971. var unused = 0;
  1972. var b2 = 0x00;
  1973. var b3 = 0x00;
  1974. if(e.digitalSignature) {
  1975. b2 |= 0x80;
  1976. unused = 7;
  1977. }
  1978. if(e.nonRepudiation) {
  1979. b2 |= 0x40;
  1980. unused = 6;
  1981. }
  1982. if(e.keyEncipherment) {
  1983. b2 |= 0x20;
  1984. unused = 5;
  1985. }
  1986. if(e.dataEncipherment) {
  1987. b2 |= 0x10;
  1988. unused = 4;
  1989. }
  1990. if(e.keyAgreement) {
  1991. b2 |= 0x08;
  1992. unused = 3;
  1993. }
  1994. if(e.keyCertSign) {
  1995. b2 |= 0x04;
  1996. unused = 2;
  1997. }
  1998. if(e.cRLSign) {
  1999. b2 |= 0x02;
  2000. unused = 1;
  2001. }
  2002. if(e.encipherOnly) {
  2003. b2 |= 0x01;
  2004. unused = 0;
  2005. }
  2006. if(e.decipherOnly) {
  2007. b3 |= 0x80;
  2008. unused = 7;
  2009. }
  2010. // create bit string
  2011. var value = String.fromCharCode(unused);
  2012. if(b3 !== 0) {
  2013. value += String.fromCharCode(b2) + String.fromCharCode(b3);
  2014. } else if(b2 !== 0) {
  2015. value += String.fromCharCode(b2);
  2016. }
  2017. e.value = asn1.create(
  2018. asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
  2019. } else if(e.name === 'basicConstraints') {
  2020. // basicConstraints is a SEQUENCE
  2021. e.value = asn1.create(
  2022. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2023. // cA BOOLEAN flag defaults to false
  2024. if(e.cA) {
  2025. e.value.value.push(asn1.create(
  2026. asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,
  2027. String.fromCharCode(0xFF)));
  2028. }
  2029. if('pathLenConstraint' in e) {
  2030. e.value.value.push(asn1.create(
  2031. asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2032. asn1.integerToDer(e.pathLenConstraint).getBytes()));
  2033. }
  2034. } else if(e.name === 'extKeyUsage') {
  2035. // extKeyUsage is a SEQUENCE of OIDs
  2036. e.value = asn1.create(
  2037. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2038. var seq = e.value.value;
  2039. for(var key in e) {
  2040. if(e[key] !== true) {
  2041. continue;
  2042. }
  2043. // key is name in OID map
  2044. if(key in oids) {
  2045. seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,
  2046. false, asn1.oidToDer(oids[key]).getBytes()));
  2047. } else if(key.indexOf('.') !== -1) {
  2048. // assume key is an OID
  2049. seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,
  2050. false, asn1.oidToDer(key).getBytes()));
  2051. }
  2052. }
  2053. } else if(e.name === 'nsCertType') {
  2054. // nsCertType is a BIT STRING
  2055. // build flags
  2056. var unused = 0;
  2057. var b2 = 0x00;
  2058. if(e.client) {
  2059. b2 |= 0x80;
  2060. unused = 7;
  2061. }
  2062. if(e.server) {
  2063. b2 |= 0x40;
  2064. unused = 6;
  2065. }
  2066. if(e.email) {
  2067. b2 |= 0x20;
  2068. unused = 5;
  2069. }
  2070. if(e.objsign) {
  2071. b2 |= 0x10;
  2072. unused = 4;
  2073. }
  2074. if(e.reserved) {
  2075. b2 |= 0x08;
  2076. unused = 3;
  2077. }
  2078. if(e.sslCA) {
  2079. b2 |= 0x04;
  2080. unused = 2;
  2081. }
  2082. if(e.emailCA) {
  2083. b2 |= 0x02;
  2084. unused = 1;
  2085. }
  2086. if(e.objCA) {
  2087. b2 |= 0x01;
  2088. unused = 0;
  2089. }
  2090. // create bit string
  2091. var value = String.fromCharCode(unused);
  2092. if(b2 !== 0) {
  2093. value += String.fromCharCode(b2);
  2094. }
  2095. e.value = asn1.create(
  2096. asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
  2097. } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {
  2098. // SYNTAX SEQUENCE
  2099. e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2100. var altName;
  2101. for(var n = 0; n < e.altNames.length; ++n) {
  2102. altName = e.altNames[n];
  2103. var value = altName.value;
  2104. // handle IP
  2105. if(altName.type === 7 && altName.ip) {
  2106. value = forge.util.bytesFromIP(altName.ip);
  2107. if(value === null) {
  2108. var error = new Error(
  2109. 'Extension "ip" value is not a valid IPv4 or IPv6 address.');
  2110. error.extension = e;
  2111. throw error;
  2112. }
  2113. } else if(altName.type === 8) {
  2114. // handle OID
  2115. if(altName.oid) {
  2116. value = asn1.oidToDer(asn1.oidToDer(altName.oid));
  2117. } else {
  2118. // deprecated ... convert value to OID
  2119. value = asn1.oidToDer(value);
  2120. }
  2121. }
  2122. e.value.value.push(asn1.create(
  2123. asn1.Class.CONTEXT_SPECIFIC, altName.type, false,
  2124. value));
  2125. }
  2126. } else if(e.name === 'nsComment' && options.cert) {
  2127. // sanity check value is ASCII (req'd) and not too big
  2128. if(!(/^[\x00-\x7F]*$/.test(e.comment)) ||
  2129. (e.comment.length < 1) || (e.comment.length > 128)) {
  2130. throw new Error('Invalid "nsComment" content.');
  2131. }
  2132. // IA5STRING opaque comment
  2133. e.value = asn1.create(
  2134. asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment);
  2135. } else if(e.name === 'subjectKeyIdentifier' && options.cert) {
  2136. var ski = options.cert.generateSubjectKeyIdentifier();
  2137. e.subjectKeyIdentifier = ski.toHex();
  2138. // OCTETSTRING w/digest
  2139. e.value = asn1.create(
  2140. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());
  2141. } else if(e.name === 'authorityKeyIdentifier' && options.cert) {
  2142. // SYNTAX SEQUENCE
  2143. e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2144. var seq = e.value.value;
  2145. if(e.keyIdentifier) {
  2146. var keyIdentifier = (e.keyIdentifier === true ?
  2147. options.cert.generateSubjectKeyIdentifier().getBytes() :
  2148. e.keyIdentifier);
  2149. seq.push(
  2150. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));
  2151. }
  2152. if(e.authorityCertIssuer) {
  2153. var authorityCertIssuer = [
  2154. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [
  2155. _dnToAsn1(e.authorityCertIssuer === true ?
  2156. options.cert.issuer : e.authorityCertIssuer)
  2157. ])
  2158. ];
  2159. seq.push(
  2160. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));
  2161. }
  2162. if(e.serialNumber) {
  2163. var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?
  2164. options.cert.serialNumber : e.serialNumber);
  2165. seq.push(
  2166. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));
  2167. }
  2168. } else if(e.name === 'cRLDistributionPoints') {
  2169. e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2170. var seq = e.value.value;
  2171. // Create sub SEQUENCE of DistributionPointName
  2172. var subSeq = asn1.create(
  2173. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2174. // Create fullName CHOICE
  2175. var fullNameGeneralNames = asn1.create(
  2176. asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
  2177. var altName;
  2178. for(var n = 0; n < e.altNames.length; ++n) {
  2179. altName = e.altNames[n];
  2180. var value = altName.value;
  2181. // handle IP
  2182. if(altName.type === 7 && altName.ip) {
  2183. value = forge.util.bytesFromIP(altName.ip);
  2184. if(value === null) {
  2185. var error = new Error(
  2186. 'Extension "ip" value is not a valid IPv4 or IPv6 address.');
  2187. error.extension = e;
  2188. throw error;
  2189. }
  2190. } else if(altName.type === 8) {
  2191. // handle OID
  2192. if(altName.oid) {
  2193. value = asn1.oidToDer(asn1.oidToDer(altName.oid));
  2194. } else {
  2195. // deprecated ... convert value to OID
  2196. value = asn1.oidToDer(value);
  2197. }
  2198. }
  2199. fullNameGeneralNames.value.push(asn1.create(
  2200. asn1.Class.CONTEXT_SPECIFIC, altName.type, false,
  2201. value));
  2202. }
  2203. // Add to the parent SEQUENCE
  2204. subSeq.value.push(asn1.create(
  2205. asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));
  2206. seq.push(subSeq);
  2207. }
  2208. // ensure value has been defined by now
  2209. if(typeof e.value === 'undefined') {
  2210. var error = new Error('Extension value not specified.');
  2211. error.extension = e;
  2212. throw error;
  2213. }
  2214. return e;
  2215. }
  2216. /**
  2217. * Convert signature parameters object to ASN.1
  2218. *
  2219. * @param {String} oid Signature algorithm OID
  2220. * @param params The signature parametrs object
  2221. * @return ASN.1 object representing signature parameters
  2222. */
  2223. function _signatureParametersToAsn1(oid, params) {
  2224. switch(oid) {
  2225. case oids['RSASSA-PSS']:
  2226. var parts = [];
  2227. if(params.hash.algorithmOid !== undefined) {
  2228. parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  2229. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2230. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2231. asn1.oidToDer(params.hash.algorithmOid).getBytes()),
  2232. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  2233. ])
  2234. ]));
  2235. }
  2236. if(params.mgf.algorithmOid !== undefined) {
  2237. parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [
  2238. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2239. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2240. asn1.oidToDer(params.mgf.algorithmOid).getBytes()),
  2241. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2242. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2243. asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),
  2244. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  2245. ])
  2246. ])
  2247. ]));
  2248. }
  2249. if(params.saltLength !== undefined) {
  2250. parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [
  2251. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2252. asn1.integerToDer(params.saltLength).getBytes())
  2253. ]));
  2254. }
  2255. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);
  2256. default:
  2257. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');
  2258. }
  2259. }
  2260. /**
  2261. * Converts a certification request's attributes to an ASN.1 set of
  2262. * CRIAttributes.
  2263. *
  2264. * @param csr certification request.
  2265. *
  2266. * @return the ASN.1 set of CRIAttributes.
  2267. */
  2268. function _CRIAttributesToAsn1(csr) {
  2269. // create an empty context-specific container
  2270. var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
  2271. // no attributes, return empty container
  2272. if(csr.attributes.length === 0) {
  2273. return rval;
  2274. }
  2275. // each attribute has a sequence with a type and a set of values
  2276. var attrs = csr.attributes;
  2277. for(var i = 0; i < attrs.length; ++i) {
  2278. var attr = attrs[i];
  2279. var value = attr.value;
  2280. // reuse tag class for attribute value if available
  2281. var valueTagClass = asn1.Type.UTF8;
  2282. if('valueTagClass' in attr) {
  2283. valueTagClass = attr.valueTagClass;
  2284. }
  2285. if(valueTagClass === asn1.Type.UTF8) {
  2286. value = forge.util.encodeUtf8(value);
  2287. }
  2288. var valueConstructed = false;
  2289. if('valueConstructed' in attr) {
  2290. valueConstructed = attr.valueConstructed;
  2291. }
  2292. // FIXME: handle more encodings
  2293. // create a RelativeDistinguishedName set
  2294. // each value in the set is an AttributeTypeAndValue first
  2295. // containing the type (an OID) and second the value
  2296. var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2297. // AttributeType
  2298. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2299. asn1.oidToDer(attr.type).getBytes()),
  2300. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
  2301. // AttributeValue
  2302. asn1.create(
  2303. asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)
  2304. ])
  2305. ]);
  2306. rval.value.push(seq);
  2307. }
  2308. return rval;
  2309. }
  2310. var jan_1_1950 = new Date('1950-01-01T00:00:00Z');
  2311. var jan_1_2050 = new Date('2050-01-01T00:00:00Z');
  2312. /**
  2313. * Converts a Date object to ASN.1
  2314. * Handles the different format before and after 1st January 2050
  2315. *
  2316. * @param date date object.
  2317. *
  2318. * @return the ASN.1 object representing the date.
  2319. */
  2320. function _dateToAsn1(date) {
  2321. if(date >= jan_1_1950 && date < jan_1_2050) {
  2322. return asn1.create(
  2323. asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,
  2324. asn1.dateToUtcTime(date));
  2325. } else {
  2326. return asn1.create(
  2327. asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,
  2328. asn1.dateToGeneralizedTime(date));
  2329. }
  2330. }
  2331. /**
  2332. * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.
  2333. *
  2334. * @param cert the certificate.
  2335. *
  2336. * @return the asn1 TBSCertificate.
  2337. */
  2338. pki.getTBSCertificate = function(cert) {
  2339. // TBSCertificate
  2340. var notBefore = _dateToAsn1(cert.validity.notBefore);
  2341. var notAfter = _dateToAsn1(cert.validity.notAfter);
  2342. var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2343. // version
  2344. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  2345. // integer
  2346. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2347. asn1.integerToDer(cert.version).getBytes())
  2348. ]),
  2349. // serialNumber
  2350. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2351. forge.util.hexToBytes(cert.serialNumber)),
  2352. // signature
  2353. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2354. // algorithm
  2355. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2356. asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),
  2357. // parameters
  2358. _signatureParametersToAsn1(
  2359. cert.siginfo.algorithmOid, cert.siginfo.parameters)
  2360. ]),
  2361. // issuer
  2362. _dnToAsn1(cert.issuer),
  2363. // validity
  2364. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2365. notBefore,
  2366. notAfter
  2367. ]),
  2368. // subject
  2369. _dnToAsn1(cert.subject),
  2370. // SubjectPublicKeyInfo
  2371. pki.publicKeyToAsn1(cert.publicKey)
  2372. ]);
  2373. if(cert.issuer.uniqueId) {
  2374. // issuerUniqueID (optional)
  2375. tbs.value.push(
  2376. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [
  2377. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
  2378. // TODO: support arbitrary bit length ids
  2379. String.fromCharCode(0x00) +
  2380. cert.issuer.uniqueId
  2381. )
  2382. ])
  2383. );
  2384. }
  2385. if(cert.subject.uniqueId) {
  2386. // subjectUniqueID (optional)
  2387. tbs.value.push(
  2388. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [
  2389. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
  2390. // TODO: support arbitrary bit length ids
  2391. String.fromCharCode(0x00) +
  2392. cert.subject.uniqueId
  2393. )
  2394. ])
  2395. );
  2396. }
  2397. if(cert.extensions.length > 0) {
  2398. // extensions (optional)
  2399. tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));
  2400. }
  2401. return tbs;
  2402. };
  2403. /**
  2404. * Gets the ASN.1 CertificationRequestInfo part of a
  2405. * PKCS#10 CertificationRequest.
  2406. *
  2407. * @param csr the certification request.
  2408. *
  2409. * @return the asn1 CertificationRequestInfo.
  2410. */
  2411. pki.getCertificationRequestInfo = function(csr) {
  2412. // CertificationRequestInfo
  2413. var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2414. // version
  2415. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2416. asn1.integerToDer(csr.version).getBytes()),
  2417. // subject
  2418. _dnToAsn1(csr.subject),
  2419. // SubjectPublicKeyInfo
  2420. pki.publicKeyToAsn1(csr.publicKey),
  2421. // attributes
  2422. _CRIAttributesToAsn1(csr)
  2423. ]);
  2424. return cri;
  2425. };
  2426. /**
  2427. * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.
  2428. *
  2429. * @param dn the DistinguishedName.
  2430. *
  2431. * @return the asn1 representation of a DistinguishedName.
  2432. */
  2433. pki.distinguishedNameToAsn1 = function(dn) {
  2434. return _dnToAsn1(dn);
  2435. };
  2436. /**
  2437. * Converts an X.509v3 RSA certificate to an ASN.1 object.
  2438. *
  2439. * @param cert the certificate.
  2440. *
  2441. * @return the asn1 representation of an X.509v3 RSA certificate.
  2442. */
  2443. pki.certificateToAsn1 = function(cert) {
  2444. // prefer cached TBSCertificate over generating one
  2445. var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);
  2446. // Certificate
  2447. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2448. // TBSCertificate
  2449. tbsCertificate,
  2450. // AlgorithmIdentifier (signature algorithm)
  2451. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2452. // algorithm
  2453. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2454. asn1.oidToDer(cert.signatureOid).getBytes()),
  2455. // parameters
  2456. _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)
  2457. ]),
  2458. // SignatureValue
  2459. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
  2460. String.fromCharCode(0x00) + cert.signature)
  2461. ]);
  2462. };
  2463. /**
  2464. * Converts X.509v3 certificate extensions to ASN.1.
  2465. *
  2466. * @param exts the extensions to convert.
  2467. *
  2468. * @return the extensions in ASN.1 format.
  2469. */
  2470. pki.certificateExtensionsToAsn1 = function(exts) {
  2471. // create top-level extension container
  2472. var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);
  2473. // create extension sequence (stores a sequence for each extension)
  2474. var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2475. rval.value.push(seq);
  2476. for(var i = 0; i < exts.length; ++i) {
  2477. seq.value.push(pki.certificateExtensionToAsn1(exts[i]));
  2478. }
  2479. return rval;
  2480. };
  2481. /**
  2482. * Converts a single certificate extension to ASN.1.
  2483. *
  2484. * @param ext the extension to convert.
  2485. *
  2486. * @return the extension in ASN.1 format.
  2487. */
  2488. pki.certificateExtensionToAsn1 = function(ext) {
  2489. // create a sequence for each extension
  2490. var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2491. // extnID (OID)
  2492. extseq.value.push(asn1.create(
  2493. asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2494. asn1.oidToDer(ext.id).getBytes()));
  2495. // critical defaults to false
  2496. if(ext.critical) {
  2497. // critical BOOLEAN DEFAULT FALSE
  2498. extseq.value.push(asn1.create(
  2499. asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,
  2500. String.fromCharCode(0xFF)));
  2501. }
  2502. var value = ext.value;
  2503. if(typeof ext.value !== 'string') {
  2504. // value is asn.1
  2505. value = asn1.toDer(value).getBytes();
  2506. }
  2507. // extnValue (OCTET STRING)
  2508. extseq.value.push(asn1.create(
  2509. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));
  2510. return extseq;
  2511. };
  2512. /**
  2513. * Converts a PKCS#10 certification request to an ASN.1 object.
  2514. *
  2515. * @param csr the certification request.
  2516. *
  2517. * @return the asn1 representation of a certification request.
  2518. */
  2519. pki.certificationRequestToAsn1 = function(csr) {
  2520. // prefer cached CertificationRequestInfo over generating one
  2521. var cri = csr.certificationRequestInfo ||
  2522. pki.getCertificationRequestInfo(csr);
  2523. // Certificate
  2524. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2525. // CertificationRequestInfo
  2526. cri,
  2527. // AlgorithmIdentifier (signature algorithm)
  2528. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2529. // algorithm
  2530. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2531. asn1.oidToDer(csr.signatureOid).getBytes()),
  2532. // parameters
  2533. _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)
  2534. ]),
  2535. // signature
  2536. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
  2537. String.fromCharCode(0x00) + csr.signature)
  2538. ]);
  2539. };
  2540. /**
  2541. * Creates a CA store.
  2542. *
  2543. * @param certs an optional array of certificate objects or PEM-formatted
  2544. * certificate strings to add to the CA store.
  2545. *
  2546. * @return the CA store.
  2547. */
  2548. pki.createCaStore = function(certs) {
  2549. // create CA store
  2550. var caStore = {
  2551. // stored certificates
  2552. certs: {}
  2553. };
  2554. /**
  2555. * Gets the certificate that issued the passed certificate or its
  2556. * 'parent'.
  2557. *
  2558. * @param cert the certificate to get the parent for.
  2559. *
  2560. * @return the parent certificate or null if none was found.
  2561. */
  2562. caStore.getIssuer = function(cert) {
  2563. var rval = getBySubject(cert.issuer);
  2564. // see if there are multiple matches
  2565. /*if(forge.util.isArray(rval)) {
  2566. // TODO: resolve multiple matches by checking
  2567. // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.
  2568. // FIXME: or alternatively do authority key mapping
  2569. // if possible (X.509v1 certs can't work?)
  2570. throw new Error('Resolving multiple issuer matches not implemented yet.');
  2571. }*/
  2572. return rval;
  2573. };
  2574. /**
  2575. * Adds a trusted certificate to the store.
  2576. *
  2577. * @param cert the certificate to add as a trusted certificate (either a
  2578. * pki.certificate object or a PEM-formatted certificate).
  2579. */
  2580. caStore.addCertificate = function(cert) {
  2581. // convert from pem if necessary
  2582. if(typeof cert === 'string') {
  2583. cert = forge.pki.certificateFromPem(cert);
  2584. }
  2585. ensureSubjectHasHash(cert.subject);
  2586. if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store
  2587. if(cert.subject.hash in caStore.certs) {
  2588. // subject hash already exists, append to array
  2589. var tmp = caStore.certs[cert.subject.hash];
  2590. if(!forge.util.isArray(tmp)) {
  2591. tmp = [tmp];
  2592. }
  2593. tmp.push(cert);
  2594. caStore.certs[cert.subject.hash] = tmp;
  2595. } else {
  2596. caStore.certs[cert.subject.hash] = cert;
  2597. }
  2598. }
  2599. };
  2600. /**
  2601. * Checks to see if the given certificate is in the store.
  2602. *
  2603. * @param cert the certificate to check (either a pki.certificate or a
  2604. * PEM-formatted certificate).
  2605. *
  2606. * @return true if the certificate is in the store, false if not.
  2607. */
  2608. caStore.hasCertificate = function(cert) {
  2609. // convert from pem if necessary
  2610. if(typeof cert === 'string') {
  2611. cert = forge.pki.certificateFromPem(cert);
  2612. }
  2613. var match = getBySubject(cert.subject);
  2614. if(!match) {
  2615. return false;
  2616. }
  2617. if(!forge.util.isArray(match)) {
  2618. match = [match];
  2619. }
  2620. // compare DER-encoding of certificates
  2621. var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();
  2622. for(var i = 0; i < match.length; ++i) {
  2623. var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();
  2624. if(der1 === der2) {
  2625. return true;
  2626. }
  2627. }
  2628. return false;
  2629. };
  2630. /**
  2631. * Lists all of the certificates kept in the store.
  2632. *
  2633. * @return an array of all of the pki.certificate objects in the store.
  2634. */
  2635. caStore.listAllCertificates = function() {
  2636. var certList = [];
  2637. for(var hash in caStore.certs) {
  2638. if(caStore.certs.hasOwnProperty(hash)) {
  2639. var value = caStore.certs[hash];
  2640. if(!forge.util.isArray(value)) {
  2641. certList.push(value);
  2642. } else {
  2643. for(var i = 0; i < value.length; ++i) {
  2644. certList.push(value[i]);
  2645. }
  2646. }
  2647. }
  2648. }
  2649. return certList;
  2650. };
  2651. /**
  2652. * Removes a certificate from the store.
  2653. *
  2654. * @param cert the certificate to remove (either a pki.certificate or a
  2655. * PEM-formatted certificate).
  2656. *
  2657. * @return the certificate that was removed or null if the certificate
  2658. * wasn't in store.
  2659. */
  2660. caStore.removeCertificate = function(cert) {
  2661. var result;
  2662. // convert from pem if necessary
  2663. if(typeof cert === 'string') {
  2664. cert = forge.pki.certificateFromPem(cert);
  2665. }
  2666. ensureSubjectHasHash(cert.subject);
  2667. if(!caStore.hasCertificate(cert)) {
  2668. return null;
  2669. }
  2670. var match = getBySubject(cert.subject);
  2671. if(!forge.util.isArray(match)) {
  2672. result = caStore.certs[cert.subject.hash];
  2673. delete caStore.certs[cert.subject.hash];
  2674. return result;
  2675. }
  2676. // compare DER-encoding of certificates
  2677. var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();
  2678. for(var i = 0; i < match.length; ++i) {
  2679. var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();
  2680. if(der1 === der2) {
  2681. result = match[i];
  2682. match.splice(i, 1);
  2683. }
  2684. }
  2685. if(match.length === 0) {
  2686. delete caStore.certs[cert.subject.hash];
  2687. }
  2688. return result;
  2689. };
  2690. function getBySubject(subject) {
  2691. ensureSubjectHasHash(subject);
  2692. return caStore.certs[subject.hash] || null;
  2693. }
  2694. function ensureSubjectHasHash(subject) {
  2695. // produce subject hash if it doesn't exist
  2696. if(!subject.hash) {
  2697. var md = forge.md.sha1.create();
  2698. subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);
  2699. subject.hash = md.digest().toHex();
  2700. }
  2701. }
  2702. // auto-add passed in certs
  2703. if(certs) {
  2704. // parse PEM-formatted certificates as necessary
  2705. for(var i = 0; i < certs.length; ++i) {
  2706. var cert = certs[i];
  2707. caStore.addCertificate(cert);
  2708. }
  2709. }
  2710. return caStore;
  2711. };
  2712. /**
  2713. * Certificate verification errors, based on TLS.
  2714. */
  2715. pki.certificateError = {
  2716. bad_certificate: 'forge.pki.BadCertificate',
  2717. unsupported_certificate: 'forge.pki.UnsupportedCertificate',
  2718. certificate_revoked: 'forge.pki.CertificateRevoked',
  2719. certificate_expired: 'forge.pki.CertificateExpired',
  2720. certificate_unknown: 'forge.pki.CertificateUnknown',
  2721. unknown_ca: 'forge.pki.UnknownCertificateAuthority'
  2722. };
  2723. /**
  2724. * Verifies a certificate chain against the given Certificate Authority store
  2725. * with an optional custom verify callback.
  2726. *
  2727. * @param caStore a certificate store to verify against.
  2728. * @param chain the certificate chain to verify, with the root or highest
  2729. * authority at the end (an array of certificates).
  2730. * @param options a callback to be called for every certificate in the chain or
  2731. * an object with:
  2732. * verify a callback to be called for every certificate in the
  2733. * chain
  2734. * validityCheckDate the date against which the certificate
  2735. * validity period should be checked. Pass null to not check
  2736. * the validity period. By default, the current date is used.
  2737. *
  2738. * The verify callback has the following signature:
  2739. *
  2740. * verified - Set to true if certificate was verified, otherwise the
  2741. * pki.certificateError for why the certificate failed.
  2742. * depth - The current index in the chain, where 0 is the end point's cert.
  2743. * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous
  2744. * end point.
  2745. *
  2746. * The function returns true on success and on failure either the appropriate
  2747. * pki.certificateError or an object with 'error' set to the appropriate
  2748. * pki.certificateError and 'message' set to a custom error message.
  2749. *
  2750. * @return true if successful, error thrown if not.
  2751. */
  2752. pki.verifyCertificateChain = function(caStore, chain, options) {
  2753. /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate
  2754. Section 6: Certification Path Validation
  2755. See inline parentheticals related to this particular implementation.
  2756. The primary goal of path validation is to verify the binding between
  2757. a subject distinguished name or a subject alternative name and subject
  2758. public key, as represented in the end entity certificate, based on the
  2759. public key of the trust anchor. This requires obtaining a sequence of
  2760. certificates that support that binding. That sequence should be provided
  2761. in the passed 'chain'. The trust anchor should be in the given CA
  2762. store. The 'end entity' certificate is the certificate provided by the
  2763. end point (typically a server) and is the first in the chain.
  2764. To meet this goal, the path validation process verifies, among other
  2765. things, that a prospective certification path (a sequence of n
  2766. certificates or a 'chain') satisfies the following conditions:
  2767. (a) for all x in {1, ..., n-1}, the subject of certificate x is
  2768. the issuer of certificate x+1;
  2769. (b) certificate 1 is issued by the trust anchor;
  2770. (c) certificate n is the certificate to be validated; and
  2771. (d) for all x in {1, ..., n}, the certificate was valid at the
  2772. time in question.
  2773. Note that here 'n' is index 0 in the chain and 1 is the last certificate
  2774. in the chain and it must be signed by a certificate in the connection's
  2775. CA store.
  2776. The path validation process also determines the set of certificate
  2777. policies that are valid for this path, based on the certificate policies
  2778. extension, policy mapping extension, policy constraints extension, and
  2779. inhibit any-policy extension.
  2780. Note: Policy mapping extension not supported (Not Required).
  2781. Note: If the certificate has an unsupported critical extension, then it
  2782. must be rejected.
  2783. Note: A certificate is self-issued if the DNs that appear in the subject
  2784. and issuer fields are identical and are not empty.
  2785. The path validation algorithm assumes the following seven inputs are
  2786. provided to the path processing logic. What this specific implementation
  2787. will use is provided parenthetically:
  2788. (a) a prospective certification path of length n (the 'chain')
  2789. (b) the current date/time: ('now').
  2790. (c) user-initial-policy-set: A set of certificate policy identifiers
  2791. naming the policies that are acceptable to the certificate user.
  2792. The user-initial-policy-set contains the special value any-policy
  2793. if the user is not concerned about certificate policy
  2794. (Not implemented. Any policy is accepted).
  2795. (d) trust anchor information, describing a CA that serves as a trust
  2796. anchor for the certification path. The trust anchor information
  2797. includes:
  2798. (1) the trusted issuer name,
  2799. (2) the trusted public key algorithm,
  2800. (3) the trusted public key, and
  2801. (4) optionally, the trusted public key parameters associated
  2802. with the public key.
  2803. (Trust anchors are provided via certificates in the CA store).
  2804. The trust anchor information may be provided to the path processing
  2805. procedure in the form of a self-signed certificate. The trusted anchor
  2806. information is trusted because it was delivered to the path processing
  2807. procedure by some trustworthy out-of-band procedure. If the trusted
  2808. public key algorithm requires parameters, then the parameters are
  2809. provided along with the trusted public key (No parameters used in this
  2810. implementation).
  2811. (e) initial-policy-mapping-inhibit, which indicates if policy mapping is
  2812. allowed in the certification path.
  2813. (Not implemented, no policy checking)
  2814. (f) initial-explicit-policy, which indicates if the path must be valid
  2815. for at least one of the certificate policies in the user-initial-
  2816. policy-set.
  2817. (Not implemented, no policy checking)
  2818. (g) initial-any-policy-inhibit, which indicates whether the
  2819. anyPolicy OID should be processed if it is included in a
  2820. certificate.
  2821. (Not implemented, so any policy is valid provided that it is
  2822. not marked as critical) */
  2823. /* Basic Path Processing:
  2824. For each certificate in the 'chain', the following is checked:
  2825. 1. The certificate validity period includes the current time.
  2826. 2. The certificate was signed by its parent (where the parent is either
  2827. the next in the chain or from the CA store). Allow processing to
  2828. continue to the next step if no parent is found but the certificate is
  2829. in the CA store.
  2830. 3. TODO: The certificate has not been revoked.
  2831. 4. The certificate issuer name matches the parent's subject name.
  2832. 5. TODO: If the certificate is self-issued and not the final certificate
  2833. in the chain, skip this step, otherwise verify that the subject name
  2834. is within one of the permitted subtrees of X.500 distinguished names
  2835. and that each of the alternative names in the subjectAltName extension
  2836. (critical or non-critical) is within one of the permitted subtrees for
  2837. that name type.
  2838. 6. TODO: If the certificate is self-issued and not the final certificate
  2839. in the chain, skip this step, otherwise verify that the subject name
  2840. is not within one of the excluded subtrees for X.500 distinguished
  2841. names and none of the subjectAltName extension names are excluded for
  2842. that name type.
  2843. 7. The other steps in the algorithm for basic path processing involve
  2844. handling the policy extension which is not presently supported in this
  2845. implementation. Instead, if a critical policy extension is found, the
  2846. certificate is rejected as not supported.
  2847. 8. If the certificate is not the first or if its the only certificate in
  2848. the chain (having no parent from the CA store or is self-signed) and it
  2849. has a critical key usage extension, verify that the keyCertSign bit is
  2850. set. If the key usage extension exists, verify that the basic
  2851. constraints extension exists. If the basic constraints extension exists,
  2852. verify that the cA flag is set. If pathLenConstraint is set, ensure that
  2853. the number of certificates that precede in the chain (come earlier
  2854. in the chain as implemented below), excluding the very first in the
  2855. chain (typically the end-entity one), isn't greater than the
  2856. pathLenConstraint. This constraint limits the number of intermediate
  2857. CAs that may appear below a CA before only end-entity certificates
  2858. may be issued. */
  2859. // if a verify callback is passed as the third parameter, package it within
  2860. // the options object. This is to support a legacy function signature that
  2861. // expected the verify callback as the third parameter.
  2862. if(typeof options === 'function') {
  2863. options = {verify: options};
  2864. }
  2865. options = options || {};
  2866. // copy cert chain references to another array to protect against changes
  2867. // in verify callback
  2868. chain = chain.slice(0);
  2869. var certs = chain.slice(0);
  2870. var validityCheckDate = options.validityCheckDate;
  2871. // if no validityCheckDate is specified, default to the current date. Make
  2872. // sure to maintain the value null because it indicates that the validity
  2873. // period should not be checked.
  2874. if(typeof validityCheckDate === 'undefined') {
  2875. validityCheckDate = new Date();
  2876. }
  2877. // verify each cert in the chain using its parent, where the parent
  2878. // is either the next in the chain or from the CA store
  2879. var first = true;
  2880. var error = null;
  2881. var depth = 0;
  2882. do {
  2883. var cert = chain.shift();
  2884. var parent = null;
  2885. var selfSigned = false;
  2886. if(validityCheckDate) {
  2887. // 1. check valid time
  2888. if(validityCheckDate < cert.validity.notBefore ||
  2889. validityCheckDate > cert.validity.notAfter) {
  2890. error = {
  2891. message: 'Certificate is not valid yet or has expired.',
  2892. error: pki.certificateError.certificate_expired,
  2893. notBefore: cert.validity.notBefore,
  2894. notAfter: cert.validity.notAfter,
  2895. // TODO: we might want to reconsider renaming 'now' to
  2896. // 'validityCheckDate' should this API be changed in the future.
  2897. now: validityCheckDate
  2898. };
  2899. }
  2900. }
  2901. // 2. verify with parent from chain or CA store
  2902. if(error === null) {
  2903. parent = chain[0] || caStore.getIssuer(cert);
  2904. if(parent === null) {
  2905. // check for self-signed cert
  2906. if(cert.isIssuer(cert)) {
  2907. selfSigned = true;
  2908. parent = cert;
  2909. }
  2910. }
  2911. if(parent) {
  2912. // FIXME: current CA store implementation might have multiple
  2913. // certificates where the issuer can't be determined from the
  2914. // certificate (happens rarely with, eg: old certificates) so normalize
  2915. // by always putting parents into an array
  2916. // TODO: there's may be an extreme degenerate case currently uncovered
  2917. // where an old intermediate certificate seems to have a matching parent
  2918. // but none of the parents actually verify ... but the intermediate
  2919. // is in the CA and it should pass this check; needs investigation
  2920. var parents = parent;
  2921. if(!forge.util.isArray(parents)) {
  2922. parents = [parents];
  2923. }
  2924. // try to verify with each possible parent (typically only one)
  2925. var verified = false;
  2926. while(!verified && parents.length > 0) {
  2927. parent = parents.shift();
  2928. try {
  2929. verified = parent.verify(cert);
  2930. } catch(ex) {
  2931. // failure to verify, don't care why, try next one
  2932. }
  2933. }
  2934. if(!verified) {
  2935. error = {
  2936. message: 'Certificate signature is invalid.',
  2937. error: pki.certificateError.bad_certificate
  2938. };
  2939. }
  2940. }
  2941. if(error === null && (!parent || selfSigned) &&
  2942. !caStore.hasCertificate(cert)) {
  2943. // no parent issuer and certificate itself is not trusted
  2944. error = {
  2945. message: 'Certificate is not trusted.',
  2946. error: pki.certificateError.unknown_ca
  2947. };
  2948. }
  2949. }
  2950. // TODO: 3. check revoked
  2951. // 4. check for matching issuer/subject
  2952. if(error === null && parent && !cert.isIssuer(parent)) {
  2953. // parent is not issuer
  2954. error = {
  2955. message: 'Certificate issuer is invalid.',
  2956. error: pki.certificateError.bad_certificate
  2957. };
  2958. }
  2959. // 5. TODO: check names with permitted names tree
  2960. // 6. TODO: check names against excluded names tree
  2961. // 7. check for unsupported critical extensions
  2962. if(error === null) {
  2963. // supported extensions
  2964. var se = {
  2965. keyUsage: true,
  2966. basicConstraints: true
  2967. };
  2968. for(var i = 0; error === null && i < cert.extensions.length; ++i) {
  2969. var ext = cert.extensions[i];
  2970. if(ext.critical && !(ext.name in se)) {
  2971. error = {
  2972. message:
  2973. 'Certificate has an unsupported critical extension.',
  2974. error: pki.certificateError.unsupported_certificate
  2975. };
  2976. }
  2977. }
  2978. }
  2979. // 8. check for CA if cert is not first or is the only certificate
  2980. // remaining in chain with no parent or is self-signed
  2981. if(error === null &&
  2982. (!first || (chain.length === 0 && (!parent || selfSigned)))) {
  2983. // first check keyUsage extension and then basic constraints
  2984. var bcExt = cert.getExtension('basicConstraints');
  2985. var keyUsageExt = cert.getExtension('keyUsage');
  2986. if(keyUsageExt !== null) {
  2987. // keyCertSign must be true and there must be a basic
  2988. // constraints extension
  2989. if(!keyUsageExt.keyCertSign || bcExt === null) {
  2990. // bad certificate
  2991. error = {
  2992. message:
  2993. 'Certificate keyUsage or basicConstraints conflict ' +
  2994. 'or indicate that the certificate is not a CA. ' +
  2995. 'If the certificate is the only one in the chain or ' +
  2996. 'isn\'t the first then the certificate must be a ' +
  2997. 'valid CA.',
  2998. error: pki.certificateError.bad_certificate
  2999. };
  3000. }
  3001. }
  3002. // basic constraints cA flag must be set
  3003. if(error === null && bcExt !== null && !bcExt.cA) {
  3004. // bad certificate
  3005. error = {
  3006. message:
  3007. 'Certificate basicConstraints indicates the certificate ' +
  3008. 'is not a CA.',
  3009. error: pki.certificateError.bad_certificate
  3010. };
  3011. }
  3012. // if error is not null and keyUsage is available, then we know it
  3013. // has keyCertSign and there is a basic constraints extension too,
  3014. // which means we can check pathLenConstraint (if it exists)
  3015. if(error === null && keyUsageExt !== null &&
  3016. 'pathLenConstraint' in bcExt) {
  3017. // pathLen is the maximum # of intermediate CA certs that can be
  3018. // found between the current certificate and the end-entity (depth 0)
  3019. // certificate; this number does not include the end-entity (depth 0,
  3020. // last in the chain) even if it happens to be a CA certificate itself
  3021. var pathLen = depth - 1;
  3022. if(pathLen > bcExt.pathLenConstraint) {
  3023. // pathLenConstraint violated, bad certificate
  3024. error = {
  3025. message:
  3026. 'Certificate basicConstraints pathLenConstraint violated.',
  3027. error: pki.certificateError.bad_certificate
  3028. };
  3029. }
  3030. }
  3031. }
  3032. // call application callback
  3033. var vfd = (error === null) ? true : error.error;
  3034. var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;
  3035. if(ret === true) {
  3036. // clear any set error
  3037. error = null;
  3038. } else {
  3039. // if passed basic tests, set default message and alert
  3040. if(vfd === true) {
  3041. error = {
  3042. message: 'The application rejected the certificate.',
  3043. error: pki.certificateError.bad_certificate
  3044. };
  3045. }
  3046. // check for custom error info
  3047. if(ret || ret === 0) {
  3048. // set custom message and error
  3049. if(typeof ret === 'object' && !forge.util.isArray(ret)) {
  3050. if(ret.message) {
  3051. error.message = ret.message;
  3052. }
  3053. if(ret.error) {
  3054. error.error = ret.error;
  3055. }
  3056. } else if(typeof ret === 'string') {
  3057. // set custom error
  3058. error.error = ret;
  3059. }
  3060. }
  3061. // throw error
  3062. throw error;
  3063. }
  3064. // no longer first cert in chain
  3065. first = false;
  3066. ++depth;
  3067. } while(chain.length > 0);
  3068. return true;
  3069. };