Eval All The Strings!
Hardening JavaScript
@naugtur, 2022/2023
Wouldn't it be great to fearlessly use them like we did back in 2015?
Let's generalize
var code = `trustMe("I'm an engineer")`
Let's generalize to running someone else's code regardless of where it comes from.
exfiltration
fetch, process.env
prototype pollution
RCE
fs
event-stream
process
process
Lambda function
ClFl worker
vm.Script
thread
process
process
process
ClFl worker
vm.Script
thread
process
process
process
What if a package turns malicious?
```js [11|22|4-7|3|13-17|2|18-20|2-9]
function evaluator() {
with (this.scopeGuard) {
with (this.evalOnce) {
return function () {
'use strict';
return eval(arguments[0])
}
}
}
}
exports.good = (sourceCode, globalObject = Object.create(null)) => {
const evaluate = evaluator.call({
evalOnce: Object.freeze(
Object.defineProperty(Object.create(null), 'eval', {
get: Array.prototype.pop.bind([eval]),
})
),
scopeGuard: new Proxy(globalObject, {
has: () => true
}),
})
return evaluate.call(globalObject, sourceCode);
}
```
```js [2-4|5|6]
exports.lockdown = () => {
Object.freeze(Object.prototype)
Object.freeze(Array.prototype)
Object.freeze(Promise.prototype)
Object.defineProperty(Function.prototype, 'constructor', {
get: () => () => () => { throw Error('why so eval?π€‘') }
})
}
```
### Object Capability
vs identity based security
- code gets references to capable objects
- code doesn't "work on your behalf"
### Object Capability
You already know how to use it
```js
import { lint } from 'some-linter'
import { readFile } from 'node:fs/promises'
const fs = { readFile }
lint({ fs })
```
### Object Capability
This is called attenuation BTW
```js
import { lint } from 'some-linter'
import { readFile } from 'node:fs/promises'
const fs = {
readFile: async (path) => {
if(!allowed(path)) { throw Error('nope') }
return readFile(path)
},
}
lint({ fs })
```
### SES makes OCap work
- `Compartment` - scope isolation
- `lockdown` - makes your Realm secure
- `harden` - protects capable objects
# π€―
### JS design is good for security?
- Take ECMA + W3C
- Add Conway's Law
- Separation between language and APIs
- Power only reachable through scope
- Compartment controls scope
### Want more?
[Mark Miller on F5 Tech Talks](https://www.youtube.com/watch?v=u-XETUbxNUU)
Here's how it compares:
```txt
Mark's talk: "Here's how we discovered cocoa trees and how
we now produce delicious chocolate in a beautiful process
with incredible machines!"
```
```txt
Zb's talk: "It basically grows on trees!"
>>throws handfuls of candy at the audience
```