bantou 0.1.0 → 0.2.0

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