279 points · by todsacerdoti · 2y ago · 104 comments
If you're willing to take the performance hit, Chromium actually allows you to disable JIT easily in the Settings and add exceptions for certain sites. Open the Settings and search for V8 Optimiser.
Notably memory safe languages wouldn't really help with the garbage collector since it would have to use unsafe Rust & the confusion about lifetime would still exist or you'd be using something like Java/C# where you're just relying on the robustness of that language's runtime GC.
However, the runtime functions, interpreter and parser would be secured by something like Rust & I fail to see how well-written Rust would introduce a 1.5-10x overhead.
Using something like a slotmap to store the languages objects in is what I would do, and your GC would just involve removing values from the map after marking everything that's reachable.
The popular slotmap crate on crates.io does contain unsafe code but nothing about the data structure inherently requires unsafe.
>and removing JIT compilers
If you read the article it makes more sense.
https://9to5mac.com/2022/07/25/lockdown-mode-ios-16-restrict...
And the downside being?
Seriously, JS was never meant to be performant. In the real world, it's very rarely used for anything computationally intensive.
If you mean “wasn’t originally meant”, that might be true. But it’s been meant to be performant for quite a long time, with huge investments behind the realization of that intent.
It’s fine if you have nostalgia for whatever you think was the original vision behind JS. But that hasn’t been the operating vision for it for many years.
Making ajax requests and doing things to the DOM tree isn't a "computational workload" because there's hardly any computation happening in that JS code.
Now multiply that by 1.5x.
I wonder how this impacts (positively) Cloudflare Workers/Fly.io-style isolation (both use very different isolation mechanisms I guess).
Perhaps, thinking out loud, CF Workers had the right level of isolation to begin with (i.e. pure V8 isolation)?
When you create a Worker with the worker_threads module, Node spawns a new V8 isolate in the same process: https://github.com/nodejs/node/blob/v20.12.1/src/node_worker...
It’s much more isolation than C threads – the entry point for a thread is a whole module (not a function), and threads must use message passing to communicate. They can share memory, but only via [Shared]ArrayBuffer objects. They're in the same OS process, but each have their own global process object.
But I think it'd meet your need for an in-process isolated execution environment, which you can terminate from the main thread after a timeout.
But I don't know of any other way this would happen.
> The V8 Sandbox has already been enabled by default on 64-bit (specifically x64 and arm64) versions of Chrome on Android, ChromeOS, Linux, macOS, and Windows for roughly the last two years.
IIRC, Cloudflare Workers are based on V8 sandboxing ... which is in part why the cold starts are so fast.
https://developers.cloudflare.com/workers/reference/how-work...
```js
let array = new Array(100);
let evil = { [Symbol.toPrimitive]() { array.length = 1; return 15; } };
array.push(evil);
// At index 100, the @@toPrimitive callback of |evil| is invoked in
// line 3 above, shrinking the array to length 1 and reallocating its
// backing buffer. The subsequent write (line 5) goes out-of-bounds.
array.fizzbuzz();
```
I'm probably missing the point, but I thought indexing into an array in Javascript outside its bounds would result in an exception or an error or something?
It's easy enough to rewrite this C++ code to do the right bounds checking. Writing the code in Rust would give even stronger guarantees. The key point, though, is that those guarantees don't extend to any code that you generate at runtime via just-in-time compilation. Rust is smart, but not nearly smart enough to verify that the arbitrary instructions you've emitted will perform the necessary bounds checks. If your optimizing compiler decides it can omit a bounds check because the index is already guaranteed to be in-bounds, and it's wrong, then there's no backstop to swoop in and return undefined instead of reading arbitrary memory.
In short, JIT compilation means that it's ~impossible to make any safety guarantees about JS engines using compile-time static analysis, because a lot of the code they run doesn't exist until runtime.
They're actually not. Out of bounds indexing is fine, you just get undefined as the result.
What is the reason for omitting OOB checks at all? Is it a big performance hit?
I think the technically correct responses you’ve gotten so far may be missing an insight here: wouldn’t the V8 example code be just as safe as the equivalent JS if it used the JS array’s own semantics? More to the point: presumably those JS semantics are themselves implemented in C++ somewhere else, and this example is reimplementing an incorrect subset of them. While it’s likely inefficient to add another native/JS round trip through JSValue to get at the expected JS array functionality, it seems reasonably safe to assume the correct behavior could be achieved with predictable performance by calling into whatever other part of V8 would implement those same JS array semantics.
In other words, it doesn’t seem like you’re missing the point. It seems like this kind of vulnerability could be at least isolated by applying exactly the thinking you’ve expressed.
Yes, but imagine that the code we are talking about here is JIT code that the compiler emitted. If the compiler JITed code that was safe Rust then it could be safe. But JITs emit machine code and a big part of their performance is exactly in the "dangerous" areas like removing unneeded bounds checks.
Say you have a bounds check in a loop. In some cases a JIT can remove it, if it can prove it's the same check in each iteration. Never removing the check would be safer, of course, but also slower.
The point of the article here is that a lower-level sandboxing technique can help such JIT code: even if a pass has a logic bug (a bug Rust would not help with) and removes a necessary check then the sandboxing limits what can be exploited.
for(var i = 0; i < arr.length; ++i)
...
then the array's length is not read once at the beginning of the loop; it is read every loop iteration. So if the code inside the loop (or inside the getter for `length` itself) modifies the length of the array, then it will be caught when the condition is evaluated. The problem is that the C++ code makes assumptions about JS (reading the length of an array cannot change the array's length) that don't hold. But it's an easy mistake to make.And here I thought Rust would fix my security issues ...
> V8 vulnerabilities are rarely "classic" memory corruption bugs (use-after-frees, out-of-bounds accesses, etc.) but instead subtle logic issues which can in turn be exploited to corrupt memory. As such, existing memory safety solutions are, for the most part, not applicable to V8. In particular, neither switching to a memory safe language, such as Rust, nor using current or future hardware memory safety features, such as memory tagging, can help with the security challenges faced by V8 today.
But looking at the awesome list they provided:
https://docs.google.com/spreadsheets/d/1lkNJ0uQwbeC1ZTRrxdtu...
There are a lot of use-after-frees and out-of-bounds accesses, buffer overflow in there...
Yes, and they’re in the runtime itself, which rust cannot protect you from. Rust cannot protect lifetime enforcement for GC objects any more than C++ already does, it can’t protect you against OoB when the reason for the OoB is the runtime is wrong about the object size, etc.
Rust does not magically make it impossible to have errors, it makes it harder by default, but the cases where these go wrong are already largely using c++ to provide the same level of memory safety rust can in the environment.
The easiest way to understand this is if you use `vec` you won’t get unsafe oob, but if there’s a bug in `vec` rust (or any language) cannot protect you. Eg if there’s a JVM bug that breaks arrays then the fact that Java is memory safe isn’t relevant.
This would allow writing the system with either very little or no unsafe code (depending on the accessing method and heap structure chosen), and Rust's borrow checker would actually correctly tell you that you cannot hold an Array's buffer borrowed while calling some unknown function because the function can mutate anything in the heap and thus needs to take exclusive access to it.
EDIT: Also note that V8's "sandboxed pointers" access all already goes through the Isolate indirectly: All compressed pointers as part of their decompression use a "base" pointer. The same could be written (with unsafe) in Rust in such a way that the "base" pointer is the heap pointer that carries all ownership of the heap, and now decompressing pointers would be equal to taking a borrow of the whole heap.
One option would be to use an existing gc crate: It checks at runtime that Rust's borrowing rules are upheld, so it would abort the program instead of doing the OoB access. This is of course not nice but it is memory safe. Obviously this would also make the engine less performant as now we're doing extra work on every read and write into a GC object.
Another option is to let go of our idea about GC objects holding mutable pointer access to one another. V8 already uses offsets from a 4 GB offset to find the item; these are "compressed pointers" because they always know they need to just upshift a bit to get the actual pointer, and because C++ doesn't care about multiple objects holding pointers to one another. A Rusty alternative to this would be that the "compressed pointers" are considered only 32-bit offsets from some base pointer that is held by the Isolate: Now Rust would not allow these to be actual pointers or become references. Instead you'd need to implement some API at the Isolate that gives you a reference to an item based on that offset, and the reference's lifetime is determined by your Isolate's lifetime.
Now, any call to JavaScript is always (in a theoretical sense) capable of mutating anything within the Isolate's heap. This means that calling a JS function would require an exclusive `&mut Isolate` reference: This now means that Rust understands that it cannot hold a reference to the Array's buffer (which it got a reference to from the Isolate heap) during a call to a JS function.
This sort of API would internally need some unsafe because it is a pointer offset we're doing here. If you don't like that, you can also go a step further and build your heap as a collection of vectors and then have your "pointers" be a combination of a type key and an index an index into that type's vector. With this sort of heap structure there is no unsafe usage needed as getting a reference is just borrowing from a Vec within the heap.
These "Rusty" ways of building the heap offer some interesting philosophical thoughts to ponder: The V8 way is kind of a faithful structuring of the ECMAScript concept of "object ownership" in C++: Items refer to each other directly, and can even do it recursively. Ownership of the memory is just kind of... there. It's obvious, right? This object refers to that, so it owns it. Except maybe if they're recursive and not accessible elsewhere... I mean, just don't think about it! (Unless you're building the GC algorithm.) The safe Rust heap structures make the memory ownership quite concrete: The Isolate owns all of its GC objects / everything in its heap. GC objects and references between them are NOT actual memory ownership relations! This JS object referring to that JS object means nothing to the memory ownership. A JS object exists as long as the Isolate thinks it exists, even if no other object refers to it.
So, the C++ / unsafe Rust way to write the Heap tries to unify JS ownership logic and the host language ownership logic into one. When these two don't agree, bugs can happen (like in the simple example provided: JS Array semantics written naively in C++ cause issues because C++ has different expectations). The safe Rust way instead throws the JS ownership logic out of the host language entirely and forces the engine to implement that runtime ownership logic on its own.
Source: I am writing a JS engine in (safe) Rust using the "heap is a collection of vectors of Ts" method.
It can't protect you from lifetime issues with GC objects, but it can for almost everything else you're doing. They indicate 50% vulns are JIT and 50% are memory safety issues in the runtime, where GC is only part of it. If the bulk of the runtime issues are around GC lifetime confusion, I agree that Rust maybe wouldn't help. It might help to make sure you don't misuse the GC machinery which might be a significant mitigation, but given the bugs I've seen in the field around integrating with the GC, I doubt Rust would help with that class of bugs.
It has nothing to do with the built-in data structures because it doesn't even exist in the same space as them. The flaws themselves are in an algorithm's reasoning, it's not an issue that exists because somewhere in the codebase there's an out-of-bounds access on a vector. The issues are caused by said flawed reasoning generating bad machine code with erronious pointer arithmetic. Note that it's the reasoning itself generating bad pointer arithmetic, not pointer arithmetic that exists explicitly in the codebase.
It's the kind of problem you need proof systems to solve. A substructural type system (or a near-approximation like Rust's ownership semantics) is simply not robust enough for the problem domain, you need full blown dependent types for this kind of thing, something that can guarantee logical safety.
ATS can handle the job, but Rust can't.
I was using `vec` as an example of runtime code that is fundamentally implemented in unsafe code. The errors that are being discussed are errors in the runtime - eg the unsafe{} blocks of rust. It’s very difficult to write code in v8/blink (or JSC/webkit) that interacts with the relevant JS runtime in ways that make the code unsafe - just as you cannot normally interact with `vec` in a way that causes a memory safety error - however the runtime’s implementation of the safe interface is still has to eventually perform unsafe operations. The bugs that you see in V8, JSC, etc are almost invariably in code that would necessarily be unsafe region in rust that would not be preventable in rust.
Another example: `Arc`, `Rc`, and `Box` etc all allocate memory, and all your rust code can be built on those, and be safe (assuming no bugs in the refcounting, no compiler lifetime errors, etc), but the allocator beneath them still has to do everything correctly and the operations it performs are largely unsafe. There’s nothing rust can do to prevent a logic error from returning overlapping pointers. You can create lots of abstractions to make it harder to screw up, but you are the runtime at this point so the code that is requiring safety rules is also the thing specifying those rules. Eg if the erroneous state/logic that leads to an incorrect allocation is the same state/logic you are testing against to ensure you aren’t making an erroneous allocation. You can see how that impacts the safety profile of the code.
When JSC or V8 have a use after free vulnerability it’s almost always a runtime error because the overwhelming majority of allocations made by both engines are via their own GCs, and so definitionally should be sound. But if there’s a bug in the runtime (a missing barrier, or a scanning error in JSC), then objects can be erroneously collected and that’s how a UaF happens. There’s nothing rust or any safe language can do to make those errors impossible or unexploitable. All the runtime can do is structure the code to make errors as hard as possible, in rust that means minimizing the amount of time in unsafe{}, and add mitigations such that any error that does happen is hard to exploit.
When V8 and JSC have buffer overflows it’s because the metadata for an object says “there is this much memory available” but that is incorrect. Again rust cannot protect against this: you’re in the position of a `vec` with incorrect bounds information.
And that goes on for all the types of bug class. The vast majority of the security benefits rust offers for a language and vm runtime are available - and used - in c++. The bugs are in the code that would necessarily be unsafe{}.
Now in blink/webkit the moment you get beyond the relevant JS runtime you run straight into the standard C++ nightmare that rust, swift, JS, C#,… prevent so that’s another thing altogether.
But those attacks would basically not be possible against a runtime built on top of Java or C#.
The JVM - especially in the era of applets - had an illustrious history of VM bugs. We don’t know how bad they would have been because in the era of extremely complex exploits applets essentially do no exist. Neither .net nor the jvm are exposed to the degree of attacks the js engines are, and there’s no strong reason to believe they don’t have similar bugs today.
Of course once you start jitting native code, all of that is off the table. Unless you jit to java/.net bytecode, I guess.
JIT code contains code that accesses the data structures they are sandboxing. By sandboxing those objects, the JIT code is limited in what it can do.
This might help you understand: An example the article gives is if an optimization pass has a bug that forgets a check. Then it may emit JIT code that will access a data structure that it should not. But, thanks to this sandboxing, that object cannot be outside the sandbox, nor refer to anything outside the sandbox, so a JIT exploit is limited in what it can achieve.
In multiple decades I can think of a handful of engine bugs that would have been prevented by rust - and those were largely preventable (and now are) in c++ as well.
It is possible for rust to be a safer language than c++ and to also not meaningfully change the security profile of the language.
It’s not just the jit, the interpreter and GCs are also subject largely - necessarily - no more protected by rust than c++.
In other words, even if you write a JS engine in Rust you could benefit greatly from this technique.
>why not work on isolating it behind it’s own process (there must be ways to do this securely while not giving up too much performance)?
Well, you make it sound like the easy answer. A good exercise would be to try implementing what you're proposing in a comment. Not necessarily going all the way, but enough to know why it might not be as straightforward as you think.
The people working on V8 are not completely clueless, the concept of moving things out of process or using a memory safe language is not going to be a novel idea that they'll just start working on now that someone clever thought of it.
> However, assuming these numbers are simply stored as integers somewhere in the JSObject, an attacker could corrupt one of them to break this invariant. Subsequently, the access into the (out-of-sandbox) std::vector would go out of bounds. Adding an explicit bounds check, for example with an SBXCHECK, would fix this.
Or use Rust
> Encouragingly, nearly all "sandbox violations" discovered so far are like this: trivial (1st order) memory corruption bugs such as use-after-frees or out-of-bounds accesses due to lack of a bounds check
Or use Rust
> Contrary to the 2nd order vulnerabilities typically found in V8, these sandbox bugs could actually be prevented or mitigated by the approaches discussed earlier. In fact, the particular bug above would already be mitigated today due to Chrome's libc++ hardening
Or use Rust
I'm not saying rewrite the entire thing in Rust, too expensive & would introduce new bugs in the JIT for questionable benefit. But at least mention that & also discuss the technical challenges why the sandbox mechanism isn't written in Rust & what it would take to address those.
Look, I'm not saying the V8 team is making the wrong decisions. My questions are an indication of the shallowness of the blog write-up - why not explain some obvious questions that come up for someone who reads it?
Take the fizzbuzz example with a missing bounds check. Rust can't prevent you from generating JIT code that omits a bounds check on an array and reads/writes out-of-bounds. The sandbox doesn't prevent out-of-bounds reads/writes, but it guarantees that they will only be able to access data inside the sandbox.
This means that logic bugs in the JIT compiler are no longer immediately exploitable. They must be combined with bugs in the sandbox implementation. The article's claim is that, unlike compiler bugs, sandbox bugs tend to be amenable to standard mitigation techniques.
This article isn't dismissing the value of memory-safe languages. It's identifying a problem space where current memory-safe languages can't help, and providing an alternative solution. Currently, every browser JS engine is written in C++, in part because Rust doesn't solve the big correctness problems. If the sandbox approach works, then using Rust for other parts of the engine becomes more appealing.
What hardening technique discussed in this article would be helped by Rust, and what specific feature of Rust would help?
> Encouragingly, nearly all "sandbox violations" discovered so far are like this: trivial (1st order) memory corruption bugs such as use-after-frees or out-of-bounds accesses due to lack of a bounds check. Contrary to the 2nd order vulnerabilities typically found in V8, these sandbox bugs could actually be prevented or mitigated by the approaches discussed earlier. In fact, the particular bug above would already be mitigated today due to Chrome's libc++ hardening. As such, the hope is that in the long run, the sandbox becomes a more defensible security boundary than V8 itself