simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

more_secure_eval.js (1643B)


      1 // Expression parser security
      2 //
      3 // Executing arbitrary expressions like enabled by the expression parser of
      4 // mathjs involves a risk in general. When you're using mathjs to let users
      5 // execute arbitrary expressions, it's good to take a moment to think about
      6 // possible security and stability implications, especially when running the
      7 // code server side.
      8 //
      9 // There is a small number of functions which yield the biggest security risk
     10 // in the expression parser of math.js:
     11 //
     12 // - `import` and `createUnit` which alter the built-in functionality and allow
     13 //   overriding existing functions and units.
     14 // - `evaluate`, `parse`, `simplify`, and `derivative` which parse arbitrary input
     15 //   into a manipulable expression tree.
     16 //
     17 // To make the expression parser less vulnerable whilst still supporting most
     18 // functionality, these functions can be disabled, as demonstrated in this
     19 // example.
     20 
     21 const { create, all } = require('../..')
     22 const math = create(all)
     23 
     24 const limitedEvaluate = math.evaluate
     25 
     26 math.import({
     27   import: function () { throw new Error('Function import is disabled') },
     28   createUnit: function () { throw new Error('Function createUnit is disabled') },
     29   evaluate: function () { throw new Error('Function evaluate is disabled') },
     30   parse: function () { throw new Error('Function parse is disabled') },
     31   simplify: function () { throw new Error('Function simplify is disabled') },
     32   derivative: function () { throw new Error('Function derivative is disabled') }
     33 }, { override: true })
     34 
     35 console.log(limitedEvaluate('sqrt(16)')) // Ok, 4
     36 console.log(limitedEvaluate('parse("2+3")')) // Error: Function parse is disabled