Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. 'use strict'
  2. const crypto = require('crypto')
  3. const figgyPudding = require('figgy-pudding')
  4. const Transform = require('stream').Transform
  5. const SPEC_ALGORITHMS = ['sha256', 'sha384', 'sha512']
  6. const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i
  7. const SRI_REGEX = /^([^-]+)-([^?]+)([?\S*]*)$/
  8. const STRICT_SRI_REGEX = /^([^-]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)*$/
  9. const VCHAR_REGEX = /^[\x21-\x7E]+$/
  10. const SsriOpts = figgyPudding({
  11. algorithms: {default: ['sha512']},
  12. error: {default: false},
  13. integrity: {},
  14. options: {default: []},
  15. pickAlgorithm: {default: () => getPrioritizedHash},
  16. Promise: {default: () => Promise},
  17. sep: {default: ' '},
  18. single: {default: false},
  19. size: {},
  20. strict: {default: false}
  21. })
  22. class Hash {
  23. get isHash () { return true }
  24. constructor (hash, opts) {
  25. opts = SsriOpts(opts)
  26. const strict = !!opts.strict
  27. this.source = hash.trim()
  28. // 3.1. Integrity metadata (called "Hash" by ssri)
  29. // https://w3c.github.io/webappsec-subresource-integrity/#integrity-metadata-description
  30. const match = this.source.match(
  31. strict
  32. ? STRICT_SRI_REGEX
  33. : SRI_REGEX
  34. )
  35. if (!match) { return }
  36. if (strict && !SPEC_ALGORITHMS.some(a => a === match[1])) { return }
  37. this.algorithm = match[1]
  38. this.digest = match[2]
  39. const rawOpts = match[3]
  40. this.options = rawOpts ? rawOpts.slice(1).split('?') : []
  41. }
  42. hexDigest () {
  43. return this.digest && Buffer.from(this.digest, 'base64').toString('hex')
  44. }
  45. toJSON () {
  46. return this.toString()
  47. }
  48. toString (opts) {
  49. opts = SsriOpts(opts)
  50. if (opts.strict) {
  51. // Strict mode enforces the standard as close to the foot of the
  52. // letter as it can.
  53. if (!(
  54. // The spec has very restricted productions for algorithms.
  55. // https://www.w3.org/TR/CSP2/#source-list-syntax
  56. SPEC_ALGORITHMS.some(x => x === this.algorithm) &&
  57. // Usually, if someone insists on using a "different" base64, we
  58. // leave it as-is, since there's multiple standards, and the
  59. // specified is not a URL-safe variant.
  60. // https://www.w3.org/TR/CSP2/#base64_value
  61. this.digest.match(BASE64_REGEX) &&
  62. // Option syntax is strictly visual chars.
  63. // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-option-expression
  64. // https://tools.ietf.org/html/rfc5234#appendix-B.1
  65. (this.options || []).every(opt => opt.match(VCHAR_REGEX))
  66. )) {
  67. return ''
  68. }
  69. }
  70. const options = this.options && this.options.length
  71. ? `?${this.options.join('?')}`
  72. : ''
  73. return `${this.algorithm}-${this.digest}${options}`
  74. }
  75. }
  76. class Integrity {
  77. get isIntegrity () { return true }
  78. toJSON () {
  79. return this.toString()
  80. }
  81. toString (opts) {
  82. opts = SsriOpts(opts)
  83. let sep = opts.sep || ' '
  84. if (opts.strict) {
  85. // Entries must be separated by whitespace, according to spec.
  86. sep = sep.replace(/\S+/g, ' ')
  87. }
  88. return Object.keys(this).map(k => {
  89. return this[k].map(hash => {
  90. return Hash.prototype.toString.call(hash, opts)
  91. }).filter(x => x.length).join(sep)
  92. }).filter(x => x.length).join(sep)
  93. }
  94. concat (integrity, opts) {
  95. opts = SsriOpts(opts)
  96. const other = typeof integrity === 'string'
  97. ? integrity
  98. : stringify(integrity, opts)
  99. return parse(`${this.toString(opts)} ${other}`, opts)
  100. }
  101. hexDigest () {
  102. return parse(this, {single: true}).hexDigest()
  103. }
  104. match (integrity, opts) {
  105. opts = SsriOpts(opts)
  106. const other = parse(integrity, opts)
  107. const algo = other.pickAlgorithm(opts)
  108. return (
  109. this[algo] &&
  110. other[algo] &&
  111. this[algo].find(hash =>
  112. other[algo].find(otherhash =>
  113. hash.digest === otherhash.digest
  114. )
  115. )
  116. ) || false
  117. }
  118. pickAlgorithm (opts) {
  119. opts = SsriOpts(opts)
  120. const pickAlgorithm = opts.pickAlgorithm
  121. const keys = Object.keys(this)
  122. if (!keys.length) {
  123. throw new Error(`No algorithms available for ${
  124. JSON.stringify(this.toString())
  125. }`)
  126. }
  127. return keys.reduce((acc, algo) => {
  128. return pickAlgorithm(acc, algo) || acc
  129. })
  130. }
  131. }
  132. module.exports.parse = parse
  133. function parse (sri, opts) {
  134. opts = SsriOpts(opts)
  135. if (typeof sri === 'string') {
  136. return _parse(sri, opts)
  137. } else if (sri.algorithm && sri.digest) {
  138. const fullSri = new Integrity()
  139. fullSri[sri.algorithm] = [sri]
  140. return _parse(stringify(fullSri, opts), opts)
  141. } else {
  142. return _parse(stringify(sri, opts), opts)
  143. }
  144. }
  145. function _parse (integrity, opts) {
  146. // 3.4.3. Parse metadata
  147. // https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
  148. if (opts.single) {
  149. return new Hash(integrity, opts)
  150. }
  151. return integrity.trim().split(/\s+/).reduce((acc, string) => {
  152. const hash = new Hash(string, opts)
  153. if (hash.algorithm && hash.digest) {
  154. const algo = hash.algorithm
  155. if (!acc[algo]) { acc[algo] = [] }
  156. acc[algo].push(hash)
  157. }
  158. return acc
  159. }, new Integrity())
  160. }
  161. module.exports.stringify = stringify
  162. function stringify (obj, opts) {
  163. opts = SsriOpts(opts)
  164. if (obj.algorithm && obj.digest) {
  165. return Hash.prototype.toString.call(obj, opts)
  166. } else if (typeof obj === 'string') {
  167. return stringify(parse(obj, opts), opts)
  168. } else {
  169. return Integrity.prototype.toString.call(obj, opts)
  170. }
  171. }
  172. module.exports.fromHex = fromHex
  173. function fromHex (hexDigest, algorithm, opts) {
  174. opts = SsriOpts(opts)
  175. const optString = opts.options && opts.options.length
  176. ? `?${opts.options.join('?')}`
  177. : ''
  178. return parse(
  179. `${algorithm}-${
  180. Buffer.from(hexDigest, 'hex').toString('base64')
  181. }${optString}`, opts
  182. )
  183. }
  184. module.exports.fromData = fromData
  185. function fromData (data, opts) {
  186. opts = SsriOpts(opts)
  187. const algorithms = opts.algorithms
  188. const optString = opts.options && opts.options.length
  189. ? `?${opts.options.join('?')}`
  190. : ''
  191. return algorithms.reduce((acc, algo) => {
  192. const digest = crypto.createHash(algo).update(data).digest('base64')
  193. const hash = new Hash(
  194. `${algo}-${digest}${optString}`,
  195. opts
  196. )
  197. if (hash.algorithm && hash.digest) {
  198. const algo = hash.algorithm
  199. if (!acc[algo]) { acc[algo] = [] }
  200. acc[algo].push(hash)
  201. }
  202. return acc
  203. }, new Integrity())
  204. }
  205. module.exports.fromStream = fromStream
  206. function fromStream (stream, opts) {
  207. opts = SsriOpts(opts)
  208. const P = opts.Promise || Promise
  209. const istream = integrityStream(opts)
  210. return new P((resolve, reject) => {
  211. stream.pipe(istream)
  212. stream.on('error', reject)
  213. istream.on('error', reject)
  214. let sri
  215. istream.on('integrity', s => { sri = s })
  216. istream.on('end', () => resolve(sri))
  217. istream.on('data', () => {})
  218. })
  219. }
  220. module.exports.checkData = checkData
  221. function checkData (data, sri, opts) {
  222. opts = SsriOpts(opts)
  223. sri = parse(sri, opts)
  224. if (!Object.keys(sri).length) {
  225. if (opts.error) {
  226. throw Object.assign(
  227. new Error('No valid integrity hashes to check against'), {
  228. code: 'EINTEGRITY'
  229. }
  230. )
  231. } else {
  232. return false
  233. }
  234. }
  235. const algorithm = sri.pickAlgorithm(opts)
  236. const digest = crypto.createHash(algorithm).update(data).digest('base64')
  237. const newSri = parse({algorithm, digest})
  238. const match = newSri.match(sri, opts)
  239. if (match || !opts.error) {
  240. return match
  241. } else if (typeof opts.size === 'number' && (data.length !== opts.size)) {
  242. const err = new Error(`data size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${data.length}`)
  243. err.code = 'EBADSIZE'
  244. err.found = data.length
  245. err.expected = opts.size
  246. err.sri = sri
  247. throw err
  248. } else {
  249. const err = new Error(`Integrity checksum failed when using ${algorithm}: Wanted ${sri}, but got ${newSri}. (${data.length} bytes)`)
  250. err.code = 'EINTEGRITY'
  251. err.found = newSri
  252. err.expected = sri
  253. err.algorithm = algorithm
  254. err.sri = sri
  255. throw err
  256. }
  257. }
  258. module.exports.checkStream = checkStream
  259. function checkStream (stream, sri, opts) {
  260. opts = SsriOpts(opts)
  261. const P = opts.Promise || Promise
  262. const checker = integrityStream(opts.concat({
  263. integrity: sri
  264. }))
  265. return new P((resolve, reject) => {
  266. stream.pipe(checker)
  267. stream.on('error', reject)
  268. checker.on('error', reject)
  269. let sri
  270. checker.on('verified', s => { sri = s })
  271. checker.on('end', () => resolve(sri))
  272. checker.on('data', () => {})
  273. })
  274. }
  275. module.exports.integrityStream = integrityStream
  276. function integrityStream (opts) {
  277. opts = SsriOpts(opts)
  278. // For verification
  279. const sri = opts.integrity && parse(opts.integrity, opts)
  280. const goodSri = sri && Object.keys(sri).length
  281. const algorithm = goodSri && sri.pickAlgorithm(opts)
  282. const digests = goodSri && sri[algorithm]
  283. // Calculating stream
  284. const algorithms = Array.from(
  285. new Set(opts.algorithms.concat(algorithm ? [algorithm] : []))
  286. )
  287. const hashes = algorithms.map(crypto.createHash)
  288. let streamSize = 0
  289. const stream = new Transform({
  290. transform (chunk, enc, cb) {
  291. streamSize += chunk.length
  292. hashes.forEach(h => h.update(chunk, enc))
  293. cb(null, chunk, enc)
  294. }
  295. }).on('end', () => {
  296. const optString = (opts.options && opts.options.length)
  297. ? `?${opts.options.join('?')}`
  298. : ''
  299. const newSri = parse(hashes.map((h, i) => {
  300. return `${algorithms[i]}-${h.digest('base64')}${optString}`
  301. }).join(' '), opts)
  302. // Integrity verification mode
  303. const match = goodSri && newSri.match(sri, opts)
  304. if (typeof opts.size === 'number' && streamSize !== opts.size) {
  305. const err = new Error(`stream size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${streamSize}`)
  306. err.code = 'EBADSIZE'
  307. err.found = streamSize
  308. err.expected = opts.size
  309. err.sri = sri
  310. stream.emit('error', err)
  311. } else if (opts.integrity && !match) {
  312. const err = new Error(`${sri} integrity checksum failed when using ${algorithm}: wanted ${digests} but got ${newSri}. (${streamSize} bytes)`)
  313. err.code = 'EINTEGRITY'
  314. err.found = newSri
  315. err.expected = digests
  316. err.algorithm = algorithm
  317. err.sri = sri
  318. stream.emit('error', err)
  319. } else {
  320. stream.emit('size', streamSize)
  321. stream.emit('integrity', newSri)
  322. match && stream.emit('verified', match)
  323. }
  324. })
  325. return stream
  326. }
  327. module.exports.create = createIntegrity
  328. function createIntegrity (opts) {
  329. opts = SsriOpts(opts)
  330. const algorithms = opts.algorithms
  331. const optString = opts.options.length
  332. ? `?${opts.options.join('?')}`
  333. : ''
  334. const hashes = algorithms.map(crypto.createHash)
  335. return {
  336. update: function (chunk, enc) {
  337. hashes.forEach(h => h.update(chunk, enc))
  338. return this
  339. },
  340. digest: function (enc) {
  341. const integrity = algorithms.reduce((acc, algo) => {
  342. const digest = hashes.shift().digest('base64')
  343. const hash = new Hash(
  344. `${algo}-${digest}${optString}`,
  345. opts
  346. )
  347. if (hash.algorithm && hash.digest) {
  348. const algo = hash.algorithm
  349. if (!acc[algo]) { acc[algo] = [] }
  350. acc[algo].push(hash)
  351. }
  352. return acc
  353. }, new Integrity())
  354. return integrity
  355. }
  356. }
  357. }
  358. const NODE_HASHES = new Set(crypto.getHashes())
  359. // This is a Best Effort™ at a reasonable priority for hash algos
  360. const DEFAULT_PRIORITY = [
  361. 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
  362. // TODO - it's unclear _which_ of these Node will actually use as its name
  363. // for the algorithm, so we guesswork it based on the OpenSSL names.
  364. 'sha3',
  365. 'sha3-256', 'sha3-384', 'sha3-512',
  366. 'sha3_256', 'sha3_384', 'sha3_512'
  367. ].filter(algo => NODE_HASHES.has(algo))
  368. function getPrioritizedHash (algo1, algo2) {
  369. return DEFAULT_PRIORITY.indexOf(algo1.toLowerCase()) >= DEFAULT_PRIORITY.indexOf(algo2.toLowerCase())
  370. ? algo1
  371. : algo2
  372. }