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

488 lines
18 KiB

4 years ago
  1. # ssri [![npm version](https://img.shields.io/npm/v/ssri.svg)](https://npm.im/ssri) [![license](https://img.shields.io/npm/l/ssri.svg)](https://npm.im/ssri) [![Travis](https://img.shields.io/travis/zkat/ssri.svg)](https://travis-ci.org/zkat/ssri) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/zkat/ssri?svg=true)](https://ci.appveyor.com/project/zkat/ssri) [![Coverage Status](https://coveralls.io/repos/github/zkat/ssri/badge.svg?branch=latest)](https://coveralls.io/github/zkat/ssri?branch=latest)
  2. [`ssri`](https://github.com/zkat/ssri), short for Standard Subresource
  3. Integrity, is a Node.js utility for parsing, manipulating, serializing,
  4. generating, and verifying [Subresource
  5. Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) hashes.
  6. ## Install
  7. `$ npm install --save ssri`
  8. ## Table of Contents
  9. * [Example](#example)
  10. * [Features](#features)
  11. * [Contributing](#contributing)
  12. * [API](#api)
  13. * Parsing & Serializing
  14. * [`parse`](#parse)
  15. * [`stringify`](#stringify)
  16. * [`Integrity#concat`](#integrity-concat)
  17. * [`Integrity#toString`](#integrity-to-string)
  18. * [`Integrity#toJSON`](#integrity-to-json)
  19. * [`Integrity#match`](#integrity-match)
  20. * [`Integrity#pickAlgorithm`](#integrity-pick-algorithm)
  21. * [`Integrity#hexDigest`](#integrity-hex-digest)
  22. * Integrity Generation
  23. * [`fromHex`](#from-hex)
  24. * [`fromData`](#from-data)
  25. * [`fromStream`](#from-stream)
  26. * [`create`](#create)
  27. * Integrity Verification
  28. * [`checkData`](#check-data)
  29. * [`checkStream`](#check-stream)
  30. * [`integrityStream`](#integrity-stream)
  31. ### Example
  32. ```javascript
  33. const ssri = require('ssri')
  34. const integrity = 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo'
  35. // Parsing and serializing
  36. const parsed = ssri.parse(integrity)
  37. ssri.stringify(parsed) // === integrity (works on non-Integrity objects)
  38. parsed.toString() // === integrity
  39. // Async stream functions
  40. ssri.checkStream(fs.createReadStream('./my-file'), integrity).then(...)
  41. ssri.fromStream(fs.createReadStream('./my-file')).then(sri => {
  42. sri.toString() === integrity
  43. })
  44. fs.createReadStream('./my-file').pipe(ssri.createCheckerStream(sri))
  45. // Sync data functions
  46. ssri.fromData(fs.readFileSync('./my-file')) // === parsed
  47. ssri.checkData(fs.readFileSync('./my-file'), integrity) // => 'sha512'
  48. ```
  49. ### Features
  50. * Parses and stringifies SRI strings.
  51. * Generates SRI strings from raw data or Streams.
  52. * Strict standard compliance.
  53. * `?foo` metadata option support.
  54. * Multiple entries for the same algorithm.
  55. * Object-based integrity hash manipulation.
  56. * Small footprint: no dependencies, concise implementation.
  57. * Full test coverage.
  58. * Customizable algorithm picker.
  59. ### Contributing
  60. The ssri team enthusiastically welcomes contributions and project participation!
  61. There's a bunch of things you can do if you want to contribute! The [Contributor
  62. Guide](CONTRIBUTING.md) has all the information you need for everything from
  63. reporting bugs to contributing entire new features. Please don't hesitate to
  64. jump in if you'd like to, or even ask us questions if something isn't clear.
  65. ### API
  66. #### <a name="parse"></a> `> ssri.parse(sri, [opts]) -> Integrity`
  67. Parses `sri` into an `Integrity` data structure. `sri` can be an integrity
  68. string, an `Hash`-like with `digest` and `algorithm` fields and an optional
  69. `options` field, or an `Integrity`-like object. The resulting object will be an
  70. `Integrity` instance that has this shape:
  71. ```javascript
  72. {
  73. 'sha1': [{algorithm: 'sha1', digest: 'deadbeef', options: []}],
  74. 'sha512': [
  75. {algorithm: 'sha512', digest: 'c0ffee', options: []},
  76. {algorithm: 'sha512', digest: 'bad1dea', options: ['foo']}
  77. ],
  78. }
  79. ```
  80. If `opts.single` is truthy, a single `Hash` object will be returned. That is, a
  81. single object that looks like `{algorithm, digest, options}`, as opposed to a
  82. larger object with multiple of these.
  83. If `opts.strict` is truthy, the resulting object will be filtered such that
  84. it strictly follows the Subresource Integrity spec, throwing away any entries
  85. with any invalid components. This also means a restricted set of algorithms
  86. will be used -- the spec limits them to `sha256`, `sha384`, and `sha512`.
  87. Strict mode is recommended if the integrity strings are intended for use in
  88. browsers, or in other situations where strict adherence to the spec is needed.
  89. ##### Example
  90. ```javascript
  91. ssri.parse('sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo') // -> Integrity object
  92. ```
  93. #### <a name="stringify"></a> `> ssri.stringify(sri, [opts]) -> String`
  94. This function is identical to [`Integrity#toString()`](#integrity-to-string),
  95. except it can be used on _any_ object that [`parse`](#parse) can handle -- that
  96. is, a string, an `Hash`-like, or an `Integrity`-like.
  97. The `opts.sep` option defines the string to use when joining multiple entries
  98. together. To be spec-compliant, this _must_ be whitespace. The default is a
  99. single space (`' '`).
  100. If `opts.strict` is true, the integrity string will be created using strict
  101. parsing rules. See [`ssri.parse`](#parse).
  102. ##### Example
  103. ```javascript
  104. // Useful for cleaning up input SRI strings:
  105. ssri.stringify('\n\rsha512-foo\n\t\tsha384-bar')
  106. // -> 'sha512-foo sha384-bar'
  107. // Hash-like: only a single entry.
  108. ssri.stringify({
  109. algorithm: 'sha512',
  110. digest:'9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==',
  111. options: ['foo']
  112. })
  113. // ->
  114. // 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo'
  115. // Integrity-like: full multi-entry syntax. Similar to output of `ssri.parse`
  116. ssri.stringify({
  117. 'sha512': [
  118. {
  119. algorithm: 'sha512',
  120. digest:'9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==',
  121. options: ['foo']
  122. }
  123. ]
  124. })
  125. // ->
  126. // 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo'
  127. ```
  128. #### <a name="integrity-concat"></a> `> Integrity#concat(otherIntegrity, [opts]) -> Integrity`
  129. Concatenates an `Integrity` object with another IntegrityLike, or an integrity
  130. string.
  131. This is functionally equivalent to concatenating the string format of both
  132. integrity arguments, and calling [`ssri.parse`](#ssri-parse) on the new string.
  133. If `opts.strict` is true, the new `Integrity` will be created using strict
  134. parsing rules. See [`ssri.parse`](#parse).
  135. ##### Example
  136. ```javascript
  137. // This will combine the integrity checks for two different versions of
  138. // your index.js file so you can use a single integrity string and serve
  139. // either of these to clients, from a single `<script>` tag.
  140. const desktopIntegrity = ssri.fromData(fs.readFileSync('./index.desktop.js'))
  141. const mobileIntegrity = ssri.fromData(fs.readFileSync('./index.mobile.js'))
  142. // Note that browsers (and ssri) will succeed as long as ONE of the entries
  143. // for the *prioritized* algorithm succeeds. That is, in order for this fallback
  144. // to work, both desktop and mobile *must* use the same `algorithm` values.
  145. desktopIntegrity.concat(mobileIntegrity)
  146. ```
  147. #### <a name="integrity-to-string"></a> `> Integrity#toString([opts]) -> String`
  148. Returns the string representation of an `Integrity` object. All hash entries
  149. will be concatenated in the string by `opts.sep`, which defaults to `' '`.
  150. If you want to serialize an object that didn't come from an `ssri` function,
  151. use [`ssri.stringify()`](#stringify).
  152. If `opts.strict` is true, the integrity string will be created using strict
  153. parsing rules. See [`ssri.parse`](#parse).
  154. ##### Example
  155. ```javascript
  156. const integrity = 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo'
  157. ssri.parse(integrity).toString() === integrity
  158. ```
  159. #### <a name="integrity-to-json"></a> `> Integrity#toJSON() -> String`
  160. Returns the string representation of an `Integrity` object. All hash entries
  161. will be concatenated in the string by `' '`.
  162. This is a convenience method so you can pass an `Integrity` object directly to `JSON.stringify`.
  163. For more info check out [toJSON() behavior on mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON%28%29_behavior).
  164. ##### Example
  165. ```javascript
  166. const integrity = '"sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo"'
  167. JSON.stringify(ssri.parse(integrity)) === integrity
  168. ```
  169. #### <a name="integrity-match"></a> `> Integrity#match(sri, [opts]) -> Hash | false`
  170. Returns the matching (truthy) hash if `Integrity` matches the argument passed as
  171. `sri`, which can be anything that [`parse`](#parse) will accept. `opts` will be
  172. passed through to `parse` and [`pickAlgorithm()`](#integrity-pick-algorithm).
  173. ##### Example
  174. ```javascript
  175. const integrity = 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A=='
  176. ssri.parse(integrity).match(integrity)
  177. // Hash {
  178. // digest: '9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A=='
  179. // algorithm: 'sha512'
  180. // }
  181. ssri.parse(integrity).match('sha1-deadbeef')
  182. // false
  183. ```
  184. #### <a name="integrity-pick-algorithm"></a> `> Integrity#pickAlgorithm([opts]) -> String`
  185. Returns the "best" algorithm from those available in the integrity object.
  186. If `opts.pickAlgorithm` is provided, it will be passed two algorithms as
  187. arguments. ssri will prioritize whichever of the two algorithms is returned by
  188. this function. Note that the function may be called multiple times, and it
  189. **must** return one of the two algorithms provided. By default, ssri will make
  190. a best-effort to pick the strongest/most reliable of the given algorithms. It
  191. may intentionally deprioritize algorithms with known vulnerabilities.
  192. ##### Example
  193. ```javascript
  194. ssri.parse('sha1-WEakDigEST sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1').pickAlgorithm() // sha512
  195. ```
  196. #### <a name="integrity-hex-digest"></a> `> Integrity#hexDigest() -> String`
  197. `Integrity` is assumed to be either a single-hash `Integrity` instance, or a
  198. `Hash` instance. Returns its `digest`, converted to a hex representation of the
  199. base64 data.
  200. ##### Example
  201. ```javascript
  202. ssri.parse('sha1-deadbeef').hexDigest() // '75e69d6de79f'
  203. ```
  204. #### <a name="from-hex"></a> `> ssri.fromHex(hexDigest, algorithm, [opts]) -> Integrity`
  205. Creates an `Integrity` object with a single entry, based on a hex-formatted
  206. hash. This is a utility function to help convert existing shasums to the
  207. Integrity format, and is roughly equivalent to something like:
  208. ```javascript
  209. algorithm + '-' + Buffer.from(hexDigest, 'hex').toString('base64')
  210. ```
  211. `opts.options` may optionally be passed in: it must be an array of option
  212. strings that will be added to all generated integrity hashes generated by
  213. `fromData`. This is a loosely-specified feature of SRIs, and currently has no
  214. specified semantics besides being `?`-separated. Use at your own risk, and
  215. probably avoid if your integrity strings are meant to be used with browsers.
  216. If `opts.strict` is true, the integrity object will be created using strict
  217. parsing rules. See [`ssri.parse`](#parse).
  218. If `opts.single` is true, a single `Hash` object will be returned.
  219. ##### Example
  220. ```javascript
  221. ssri.fromHex('75e69d6de79f', 'sha1').toString() // 'sha1-deadbeef'
  222. ```
  223. #### <a name="from-data"></a> `> ssri.fromData(data, [opts]) -> Integrity`
  224. Creates an `Integrity` object from either string or `Buffer` data, calculating
  225. all the requested hashes and adding any specified options to the object.
  226. `opts.algorithms` determines which algorithms to generate hashes for. All
  227. results will be included in a single `Integrity` object. The default value for
  228. `opts.algorithms` is `['sha512']`. All algorithm strings must be hashes listed
  229. in `crypto.getHashes()` for the host Node.js platform.
  230. `opts.options` may optionally be passed in: it must be an array of option
  231. strings that will be added to all generated integrity hashes generated by
  232. `fromData`. This is a loosely-specified feature of SRIs, and currently has no
  233. specified semantics besides being `?`-separated. Use at your own risk, and
  234. probably avoid if your integrity strings are meant to be used with browsers.
  235. If `opts.strict` is true, the integrity object will be created using strict
  236. parsing rules. See [`ssri.parse`](#parse).
  237. ##### Example
  238. ```javascript
  239. const integrityObj = ssri.fromData('foobarbaz', {
  240. algorithms: ['sha256', 'sha384', 'sha512']
  241. })
  242. integrity.toString('\n')
  243. // ->
  244. // sha256-l981iLWj8kurw4UbNy8Lpxqdzd7UOxS50Glhv8FwfZ0=
  245. // sha384-irnCxQ0CfQhYGlVAUdwTPC9bF3+YWLxlaDGM4xbYminxpbXEq+D+2GCEBTxcjES9
  246. // sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1+9vBnypkYWg==
  247. ```
  248. #### <a name="from-stream"></a> `> ssri.fromStream(stream, [opts]) -> Promise<Integrity>`
  249. Returns a Promise of an Integrity object calculated by reading data from
  250. a given `stream`.
  251. It accepts both `opts.algorithms` and `opts.options`, which are documented as
  252. part of [`ssri.fromData`](#from-data).
  253. Additionally, `opts.Promise` may be passed in to inject a Promise library of
  254. choice. By default, ssri will use Node's built-in Promises.
  255. If `opts.strict` is true, the integrity object will be created using strict
  256. parsing rules. See [`ssri.parse`](#parse).
  257. ##### Example
  258. ```javascript
  259. ssri.fromStream(fs.createReadStream('index.js'), {
  260. algorithms: ['sha1', 'sha512']
  261. }).then(integrity => {
  262. return ssri.checkStream(fs.createReadStream('index.js'), integrity)
  263. }) // succeeds
  264. ```
  265. #### <a name="create"></a> `> ssri.create([opts]) -> <Hash>`
  266. Returns a Hash object with `update(<Buffer or string>[,enc])` and `digest()` methods.
  267. The Hash object provides the same methods as [crypto class Hash](https://nodejs.org/dist/latest-v6.x/docs/api/crypto.html#crypto_class_hash).
  268. `digest()` accepts no arguments and returns an Integrity object calculated by reading data from
  269. calls to update.
  270. It accepts both `opts.algorithms` and `opts.options`, which are documented as
  271. part of [`ssri.fromData`](#from-data).
  272. If `opts.strict` is true, the integrity object will be created using strict
  273. parsing rules. See [`ssri.parse`](#parse).
  274. ##### Example
  275. ```javascript
  276. const integrity = ssri.create().update('foobarbaz').digest()
  277. integrity.toString()
  278. // ->
  279. // sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1+9vBnypkYWg==
  280. ```
  281. #### <a name="check-data"></a> `> ssri.checkData(data, sri, [opts]) -> Hash|false`
  282. Verifies `data` integrity against an `sri` argument. `data` may be either a
  283. `String` or a `Buffer`, and `sri` can be any subresource integrity
  284. representation that [`ssri.parse`](#parse) can handle.
  285. If verification succeeds, `checkData` will return the name of the algorithm that
  286. was used for verification (a truthy value). Otherwise, it will return `false`.
  287. If `opts.pickAlgorithm` is provided, it will be used by
  288. [`Integrity#pickAlgorithm`](#integrity-pick-algorithm) when deciding which of
  289. the available digests to match against.
  290. If `opts.error` is true, and verification fails, `checkData` will throw either
  291. an `EBADSIZE` or an `EINTEGRITY` error, instead of just returning false.
  292. ##### Example
  293. ```javascript
  294. const data = fs.readFileSync('index.js')
  295. ssri.checkData(data, ssri.fromData(data)) // -> 'sha512'
  296. ssri.checkData(data, 'sha256-l981iLWj8kurw4UbNy8Lpxqdzd7UOxS50Glhv8FwfZ0')
  297. ssri.checkData(data, 'sha1-BaDDigEST') // -> false
  298. ssri.checkData(data, 'sha1-BaDDigEST', {error: true}) // -> Error! EINTEGRITY
  299. ```
  300. #### <a name="check-stream"></a> `> ssri.checkStream(stream, sri, [opts]) -> Promise<Hash>`
  301. Verifies the contents of `stream` against an `sri` argument. `stream` will be
  302. consumed in its entirety by this process. `sri` can be any subresource integrity
  303. representation that [`ssri.parse`](#parse) can handle.
  304. `checkStream` will return a Promise that either resolves to the
  305. `Hash` that succeeded verification, or, if the verification fails
  306. or an error happens with `stream`, the Promise will be rejected.
  307. If the Promise is rejected because verification failed, the returned error will
  308. have `err.code` as `EINTEGRITY`.
  309. If `opts.size` is given, it will be matched against the stream size. An error
  310. with `err.code` `EBADSIZE` will be returned by a rejection if the expected size
  311. and actual size fail to match.
  312. If `opts.pickAlgorithm` is provided, it will be used by
  313. [`Integrity#pickAlgorithm`](#integrity-pick-algorithm) when deciding which of
  314. the available digests to match against.
  315. ##### Example
  316. ```javascript
  317. const integrity = ssri.fromData(fs.readFileSync('index.js'))
  318. ssri.checkStream(
  319. fs.createReadStream('index.js'),
  320. integrity
  321. )
  322. // ->
  323. // Promise<{
  324. // algorithm: 'sha512',
  325. // digest: 'sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1'
  326. // }>
  327. ssri.checkStream(
  328. fs.createReadStream('index.js'),
  329. 'sha256-l981iLWj8kurw4UbNy8Lpxqdzd7UOxS50Glhv8FwfZ0'
  330. ) // -> Promise<Hash>
  331. ssri.checkStream(
  332. fs.createReadStream('index.js'),
  333. 'sha1-BaDDigEST'
  334. ) // -> Promise<Error<{code: 'EINTEGRITY'}>>
  335. ```
  336. #### <a name="integrity-stream"></a> `> integrityStream([opts]) -> IntegrityStream`
  337. Returns a `Transform` stream that data can be piped through in order to generate
  338. and optionally check data integrity for piped data. When the stream completes
  339. successfully, it emits `size` and `integrity` events, containing the total
  340. number of bytes processed and a calculated `Integrity` instance based on stream
  341. data, respectively.
  342. If `opts.algorithms` is passed in, the listed algorithms will be calculated when
  343. generating the final `Integrity` instance. The default is `['sha512']`.
  344. If `opts.single` is passed in, a single `Hash` instance will be returned.
  345. If `opts.integrity` is passed in, it should be an `integrity` value understood
  346. by [`parse`](#parse) that the stream will check the data against. If
  347. verification succeeds, the integrity stream will emit a `verified` event whose
  348. value is a single `Hash` object that is the one that succeeded verification. If
  349. verification fails, the stream will error with an `EINTEGRITY` error code.
  350. If `opts.size` is given, it will be matched against the stream size. An error
  351. with `err.code` `EBADSIZE` will be emitted by the stream if the expected size
  352. and actual size fail to match.
  353. If `opts.pickAlgorithm` is provided, it will be passed two algorithms as
  354. arguments. ssri will prioritize whichever of the two algorithms is returned by
  355. this function. Note that the function may be called multiple times, and it
  356. **must** return one of the two algorithms provided. By default, ssri will make
  357. a best-effort to pick the strongest/most reliable of the given algorithms. It
  358. may intentionally deprioritize algorithms with known vulnerabilities.
  359. ##### Example
  360. ```javascript
  361. const integrity = ssri.fromData(fs.readFileSync('index.js'))
  362. fs.createReadStream('index.js')
  363. .pipe(ssri.integrityStream({integrity}))
  364. ```