Simple Linux kernel memory corruption bug can lead to complete system compromise
googleprojectzero.blogspot.com
googleprojectzero.blogspot.com
https://lists.debian.org/debian-security-announce/2021/msg00...
https://tracker.debian.org/news/1226431/accepted-linux-41917...
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/lin...
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/lin...
At least the second one says "... leading to use-after-free errors." But style in the Linux community is to not mention security impact and just to give a dense explanation of the bug itself. (Jann Horn, as a person who does care about security, tends to be better about this than most kernel developers; if the fix were from the average subsystem maintainer, I wouldn't expect to even see a mention of "use-after-free.")
Also, if you look at the Project Zero bug log (https://bugs.chromium.org/p/project-zero/issues/detail?id=21...), it's clear that Horn wasn't totally sure whether/how this could be exploited, just that it seemed funny.
(This should probably lead you to question whether "stable" kernels are a meaningful concept and whether the hypothesis that stable kernels are patched / otherwise do what they claim to do is even falsifiable.)
For example suppose for some crazy reason, on Sundays all USB audio devices have stereo flipped by mistake. That's a bug. Is it a security bug? At first glance you may think "No". It's just a weird logic bug. But the user is entitled to reason that if they routed stereo left from their USB digital audio feed to the mono "Security Announcements" PA in the building, and their "security announcements" code is silent on stereo right, that's fine, that will still cause the announcements to come from their PA system as desired. It's astonishing that on Sunday this Linux bug silences the PA and they don't get PA announcements that there's a seismic alarm down in gold vaults D, E and F because somebody has drilled into them. It was a security bug after all.
But here we're talking about the Linux kernel and so we needn't stretch that far. "The buck stops here" so to speak, if you can't trust the OS kernel to do what it promised, you're pretty much screwed.
All you have left are broader physical or mathematical guarantees e.g. even a Linux kernel bug at Let's Encrypt can't leak your TLS server private keys because they don't have your private keys and so mathematically that can't happen - or even if there's a really drastic Linux kernel zero day this Android phone can't travel faster than the speed of light because physics doesn't rely on kernel code.
Is that still the case or am I just old?
https://ssd-disclosure.com/ssd-advisory-overlayfs-pe/
https://blog.qualys.com/vulnerabilities-threat-research/2021...
[0] https://github.com/varnishcache/varnish-cache/blob/4ae73a5b1...
Usually a more thorough approach is to turn on malloc scribbling, ASAN or valgrind which is something Darwin’s allocator can be told to do (it’ll scribble separate uninitialized and freed patterns).
I could see the appeal of there being a magic value though. I think that’s what memset_s is for so hopefully your favorite project is doing that properly.
[1] http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buf...
The magic field is reset before returning the pointer to the allocator, so it’s definitely a live write to a valid pointer.
FWIW most of what you're referring to (reaching a free'd pointer via pointer arithmetic, or going straight to its address) is actually undefined behavior according to the C standard, what you're allowed to do with pointers is more limited than that. There are ways of getting around some of that (obviously, since it's necessary in embedded and other low-level situations), but it requires knowledge about your specific compiler and/or potentially the use of extensions or similar things not part of the standard.
Interestingly enough, if you were to incorrectly use stack memory in this scenario, the magic checks should trigger, pointing out improper memory usage.
I'm pretty sure you can get similar optimization behavior when you mark functions with special attributes, I'm not 100% sure on that point though. So for the Linux Kernel I'm not sure that kind of optimization would ever be done since obviously it's not using the standard defined functions and the compiler might not be given enough information to know the functions have the same semantics as 'malloc()' and 'free()'.
I personally was able to get the exact behavior described here by compiling the below code using `-O2`. The volatile write just ensures the first constant write and the malloc itself cannot be optimized out (and that does happen! Take out the volatile and there are no calls to malloc in the result), but gcc is still free to do whatever it wants with the other write and for me it's completely gone in the resulting program.
int main()
{
int *p = malloc(sizeof(*p));
*(volatile int *)p = 20;
printf("p=%d\n", *p);
*p = 30; /* this is gone from the -O2 compiled code */
free(p);
return 0;
}
The relevant part of the assembly looks like this, I don't think I'm missing anything in that the 30 assignment is completely gone: push $0x4
call 460 <malloc@plt>
movl $0x14,(%eax) # Assignment of 20
mov %eax,%esi
pop %eax
lea -0x1930(%ebx),%eax
pop %edx
pushl (%esi) # push the 20
push %eax
call 440 <printf@plt>
mov %esi,(%esp) # load address to pass to free(), no assignment between printf() and free()
call 450 <free@plt>Edit note: allocators are user space libraries (stdlib) and not part of the C spec. Use-after-free is extremely unsafe, however its completely valid C.
2nd note: running all programs below give me the expected result, writes to pointers are live, regardless if they are freed. So please provide more concrete steps to reproduce your results.
I'm not sure why you think this, but the C standard includes a whole section defining the behavior of the standard library functions, including malloc and free. And it includes this note as undefined behavior:
> The value of a pointer that refers to space deallocated by a call to the free or realloc function is used (7.20.3)
So it is undefined behavior to access memory passed to free, or IE use-after-free is undefined behavior if you're using the standard library.
> 2nd note: running all programs below give me the expected result, writes to pointers are live, regardless if they are freed. So please provide more concrete steps to reproduce your results.
I would check that you're compiling them with `-O2`, and also check the assembly output. However as someone linked, you can already see from the online compiler output that clearly gcc is capable of optimizing the assignment out. Here's my second program in the same compiler, notice how printf is called twice but the 30 assignment (which is what is supposed to set your magic number) is still completely gone: https://godbolt.org/z/9reErcbGK
Edit: Sorry, I previously included the wrong quote from the standard (it was about a double-free being UB, slightly different), I have the right one now. I got it from here if you want to look at it, it's a draft but practically the same as the actual one: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
memset_s is the only function that would be defined to work precisely because this was needed for crypto so it is solvable but just take it on faith that if it’s not explicitly called out as forcing the compiler to not do dead store elimination, it will happen.
I think that's your best bet but volatile does bring its own set of problems with it (how it works differs from compiler to compiler). That said it should probably work fine, this is a pretty simple use of volatile. You might check the documentation for your particular compiler though if you have one in mind, it should tell you what it does and if it does anything undesirable (or if there's a better way to do this). Also the volatile cast like I did may be a better approach than actually making the member itself volatile.
FWIW, the whole idea is that whether this happens or not has no impact on your program, so in theory you shouldn't ever notice this happens. Detecting use-after-free like this is not really standards compliant so that's a big reason why it's problematic to implement.
Also, if you're not using the standard allcator then most of this logic doesn't apply because the compiler won't know your special allocator has the semantics of 'free()'. There are `malloc` attributes in gcc that might trigger similar optimization behavior, but you'd have to be using them, and even then I'm not really sure as I haven't looked into what all they do.
Trying to structure code to trick the compiler is a bad idea. The compiler authors know the standard better than you and eventually the compiler will exploit your misunderstanding.
I think there's been godbolt links posted in this thread showing this assumption is wrong. Dead store elimination applies just fine to volatiles.
As context, the Linux Kernel uses volatile to ensure loads and stores happen, that's ultimately how READ_ONCE and WRITE_ONCE work[1]. If that's actually broken in such a simple case I think they'd like to know xD
[0]: https://gcc.gnu.org/onlinedocs/gcc/Volatiles.html
[1]: https://elixir.bootlin.com/linux/latest/source/tools/include...
Edit: To be clear, I looked for the example you mentioned but couldn't find it. I'm somewhat wondering if you were thinking of the example I posted, since I used volatile to get gcc to not optimize the store out :P
I’m genuinely amazed at the response. There’s literally an API defined that has the contract you want and your response is “yeah, but I want to write it a totally other way the standard doesn’t allow”. Just use memset_s. It’s a compiler builtin so the generated code is as efficient (more so) as compared with a volatile version except actually safe. Volatile has a totally different purpose and isn’t suitable to try to write a value before calling free.
I’ll leave writing a godbolt example of writing to a volatile right before a free in the same compilation unit at O3 for you to try out.
[1] http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buf...
As far as that article goes, the example for `secure_memzero` works and you will not find any compiler that will 'optimize that out', it would be a bug. And as I linked, the gcc documentation says as much. With that, memory allocation is not as special as you're making it out to be, normal memory can be volatile in perfectly valid situations (even ones mentioned in the standard), and just because it's related to a free() does not mean the compiler is now allowed to remove a volatile dead store - and even if you think it does, gcc will not do that.
Here's an example of such a case[0]. A signal handler is able to view the object being set right before the free() call, and a signal could trigger at that point, but the compiler still optimizes it out (which is correct). Using volatile on the variable to ensure all loads and stores actually happen (and are visible to the signal handler) is the suggested way, and if you do that then the code does set the value before the free().
As for your suggestion of writing to a volatile right before a free(), I'm not sure if you tried but it works just fine as expected, look[1]. I am perfectly confident in saying you will never find an example where the volatile store doesn't happen. With that, if it was willing to make such an optimization in the first place, don't you think my original example that used it to avoid dead store elimination and memory allocation elimination wouldn't have worked in the first place? ;)
[0]: https://godbolt.org/z/WWPz5Gqjo [1]: https://godbolt.org/z/anc1cfnPs
volatile bool doCheck = false;
if (doCheck)
{
// code I want to enable at some point during debugging
}
The idea is that I attach a debugger, and then only at a certain point enable doCheck.I was baffled to learn that MSVC will happily constant-fold the false into the if, as long as the variable is function-local. The variable still exists and I can change it in the debugger, but it doesn't actually impact control flow as intended. The "solution" is to move it to e.g. global scope (this is a debugging hack, remember).
Not an exact match for what you asked, but I think a good reminder that optimizers work in mysterious ways, and sprinkling in volatile may confuse the programmer more than the optimizer...
To show this even more, if you add an extra printf to print the value of p after the `free()` (so add a literal use-after-free to check the 'magic' value) the 30 assignment is still gone. It prints zero for me because free() clears that memory, but the assembly does not include the 30 assignment even though I'm clearly reading the value it assigned after the `free()` statement, which is exactly the behavior you're attempting to catch. If `free()` didn't touch the value I'd still see 20.
With a little finessing I got my code to print 20 both times (the larger struct gets malloc() to leave the magic value alone) even with the 30 assignment still in the code:
struct foo {
char bar[35];
int p;
};
int main()
{
struct foo *p = malloc(sizeof(*p));
*(volatile int *)(&p->p) = 20;
printf("p=%d\n", p->p);
p->p = 30;
free(p);
printf("p=%d\n", p->p); /* Prints 20 for me, the 30 assignment is optimized out completely */
return 0;
}If you have the function
void free_ws(struct ws *ptr) {
ptr->magic = 0xdeadc0de;
free(ptr);
}
there is no possible circumstance, in valid C, where ptr->magic could be read and have its value equal to 0xdeadc0de. That object is freed immediately after that write.If you do a read in some other function, say
char read_from_ws(struct ws *ptr) {
if (ptr->magic != WS_MAGIC) {
exit(1);
}
return ptr->s[0];
}
it is impossible for the pointer passed into read_from_ws to be a pointer that has passed through free_ws, i.e., it is impossible for ptr->magic to have been set to 0xdeadc0de by free_ws. Therefore, free_ws doesn't need to actually do the write.You're right that the correct magic check is not dead, and cannot be eliminated by the same logic. But the effect there is that the magic check always succeeds!
Here's a piece of code that would go slower if you turned it off:
for (i = 0; i < 1000; i++) {
struct foobar *ptr = malloc(sizeof(struct foobar));
ptr->this = a[i];
ptr->that = b[i];
if (ptr->this > 0) {
do_stuff(ptr);
}
free(ptr);
}
You only need to write to ptr->that if the condition succeeds. (And frankly you only need to do the allocation at all if a[i] > 0.)Compilers that don't do this get rejected for compilers that do.
If they can do that, they can very easily fill in the magic numbers too. It's even easier than pointers because it doesn't require inferring information about the running program - the magic number is the same across all instances of Varnish and right there in the source.
"Heap spray" attacks are a generalization of this where the attacker doesn't have precise enough control about what happens between the unwanted free and the reuse, but they can allocate a very large buffer (e.g., send a lot of data in from the network, or open a lot of connections) and put their data in that way. This approach would be basically perfect for defeating the "magic number" approach.
(The blog post itself has a discussion of a number of more advanced variants on the "magic number" approach - see the mention of "tagging pointers with a small number of bits that are checked against object metadata on access".)
Here's an excerpt from an old Stratus presentation[0] on writing robust software.
Add TYPE, SIZE, VERSION, and OWNER to data structure
TYPE: Unique number for each different structure
SIZE: in bytes
VERSION: Changed whenever structure declaration changes
OWNER: Unique ID of owner, must be independent of structure contents; can be UID, least significant bits of clock, etc.
[0] https://web.archive.org/web/20170303065858/http://ftp.stratu...
Right, recreating the magic does side step this defense.
The context for software security these days is defense in depth and not something like “total defense” anymore. In this case, the use of magics is more of a dev testing mechanism than a runtime protect, although it does provide great runtime protection. What this means is if you use magics with proper testing and load testing, errors should surface before you release.
Better IMHO to design a language in such a way that dangerous errors like this are completely impossible.
(I mean... this is basically why I switched from Ruby to Elixir for web dev, eliminating an entire class of bugs... If the language itself doesn't provide an error-reduction feature, then you are reliant on other developers to "do the right thing" and lose any guarantees)
Can we stop having tabloid titles for technical matters?
The bug itself is small and it lead to a whole system compromise, and the title is very good to guide us to the point they are trying to make… memory corruption is a problem and that needs to be addressed at early stages even, even if the overhead seems not worth it.
It would be nice if the article stated what's affected more clearly, and importantly, that patches were rolled out long ago for most distros.
So compiler optimizers get to take advantage of UB for that last mile optimization, which in a language like C always expect the developer to be a ISO C expert, and when they aren't or are too tired trying to meet project deadlines, surprises happen.
"Oh, it was quite a while ago. I kind of stopped when C came out. That was a big blow. We were making so much good progress on optimizations and transformations. We were getting rid of just one nice problem after another. When C came out, at one of the SIGPLAN compiler conferences, there was a debate between Steve Johnson from Bell Labs, who was supporting C, and one of our people, Bill Harrison, who was working on a project that I had at that time supporting automatic optimization...The nubbin of the debate was Steve's defense of not having to build optimizers anymore because the programmer would take care of it. That it was really a programmer's issue.... Seibel: Do you think C is a reasonable language if they had restricted its use to operating-system kernels? Allen: Oh, yeah. That would have been fine. And, in fact, you need to have something like that, something where experts can really fine-tune without big bottlenecks because those are key problems to solve. By 1960, we had a long list of amazing languages: Lisp, APL, Fortran, COBOL, Algol 60. These are higher-level than C. We have seriously regressed, since C developed. C has destroyed our ability to advance the state of the art in automatic optimization, automatic parallelization, automatic mapping of a high-level language to the machine. This is one of the reasons compilers are ... basically not taught much anymore in the colleges and universities."
-- Fran Allen interview, Excerpted from: Peter Seibel. Coders at Work: Reflections on the Craft of Programming
This can be the case now, but then later someone adds new code that you did need that null check.
> If you think you do need them then it's a sign you've screwed up somewhere and should fix it!
Hm, so instead of
> Wouldn't it be better to have compile errors if the compiler figures out that it can remove a null check?
you wanted the opposite: warn when a null check is there and was actually required :).
Not sure if this is a working solution either. Maybe if it was behind a macro, JUST_CHECKING_IF_NULL(x)..
I mean obviously the solution is to use a sane language but you know...
Rust would certainly not help in this instance, because nobody is writing pty handling code in Rust. I.e., using Rust in place B does not help with bugs in place A. Any expectation that Linux would get more secure if some new code were Rust is optimistic to the point of fantasy.
The best possible outcome of allowing Rust in kernel code is that the kernel would not become even more insecure as a result of the added Rust code. That would be good, by itself, even if not what we really want. But whether even that would be achieved in practice is still to be demonstrated.
But I am waiting for the Rust-OS to complete -- if one is under construction now. We can check how that stands when released.
Citation needed, since all evidence points to the contrary.
Could you please point us to a Rust application (there are hundreds of thousands at this point) that gets noticeably faster when disabling bound checks?
In servo, a whole web browser written in Rust, the cost of doing this was negligible, to the point that it was barely measurable (1-3%, noise levels for such a big app).
Same for Firefox which has a substantial amount of Rust.
Go ahead and give Fuchsia a try. You can enable bound checks for a substantial part of Android's user space and not really notice it.
Same for Redox, or any operating system kernel written in Rust.
You have many large applications to choose from, so please, just point us to 1 for which this is the case.
---
Compared with other mitigations already in the kernel, that can cost you up to 50% perf, and that people seem to be ok with, bound checking all the array accesses seems like a no brainer, given that ~70% of CVE are caused by memory issues.
When most people think about bound checking all array accesses, they think, for some "i can only think inside the box" reason, that this happens on hardware, for every memory access.
But that is not how Rust works. Rust adds bound checks "in Rust", and the Rust compiler and LLVM are really good at removing duplicates, hoisting many bound checks out of a loop into a single bound check at the beginning of the loop, etc.
People also think that this is an all or nothing approach, but Rust allows you to manually access without bound checks and do the hoisting manually. So if you find a function in which this makes a big difference, you can just fix the performance issue there manually.
So, in general, the idiomatic Rust "twiddle all these doodads" compiles to the same machine code as the idiomatic C++ for that problem, even though Rust bounds checked it and C++ didn't care. Lots of Rust checks are like this, they compile away to nothing, so long as what you did is necessarily correct. The Option<NonZeroU64> stuff a few days ago is another example. Same machine code as a C++ long integer using zero as a signal value, but with type safety.
Naturally this only kind of works when everyone on the team goes safety first.
Doing some C style coding will just bork it, similarly to any unsafe block or FFI call in other better suited languages.
But in the subject of making juice with lemons, is way better than plain C.
This is, after all, why Godbolt was first invented as I suspect you know (Matt Godbolt wondered if C++ iterators really do produce the same machine code as a hand-rolled C-style for loop, and rather than just trust an expert he built the earliest Compiler Explorer to show that yes, with real C++ code you get the same machine code, any time spent hand-rolling such loops is time wasted)
By the way, this should be a nice update about the state of affairs on Android (I am yet to watch it).
"Improving Memory Safety in Android 12 Using MTE"
Memory tagging (which is what MTE is about) reminds me of ASLR and password entropy requirements. They're slightly raising the bar which is not something I have much time for. I prefer to put the effort in to solve problems permanently so I can worry about something else instead. Whether that's a practical opportunity here is unclear though, and I think Rust is a big part of finding out.
The bounds check wasn't being elided either. I checked and it was there in the assembly, so I figured that the function is so hot that an unchecked access might help things. Apparently not. The only thing I can think of is that the reduction in code-size for that function had an unintended effect elsewhere, either for the optimizer or that it resulted in a hot bit of code crossing a cache line?
The very few cases where it actually mattered for project delivery acceptance, were proven with a profiler, and fixed on those single cases only.
Most of the time it is just cargo cult taken from C into other languages.
Multics had a better DoD security profile assessment than UNIX, thanks to PL/I being bounds checked by default.
Mac OS used Object Pascal until they decided to switch to C++ around 1992, it also hardly impacted their sales, using a language with bounds checking.
I have not found this, at least in application code. There is usually at most a few percent different between v[i] and v.at(i) (the latter checks bounds) with C++ std::vector, for example. So I almost always use .at() these days, and it does catch bugs.
https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros...
And before STL was a thing, all the custom types I had were bounds checked by default.
spin_lock_irq(&tty->ctrl_lock);
put_pid(real_tty->pgrp);
real_tty->pgrp = get_pid(pgrp);
spin_unlock_irq(&tty->ctrl_lock);
rustifying this would be let mut tty_lock = tty.ctrl_lock();
put_pid(real_tty);
real_tty.pgrp = get_pid(pgrp);
std::mem::drop(tty_lock);
Which would give an error that you are not allowed to mutate real_tty.pgrp.Rust could prevent this issue by requiring that all non-exclusive accesses to the shared data acquire the mutex (and if you use Mutex<T> which wraps the data, you'll always acquire the right mutex). The & vs. &mut system can model exclusive access ("initialization/destruction functions that have exclusive access to the entire object and can access members without locking"). It doesn't help with RCU vs. refcounted references, or "non-RCU members are exclusively owned by thread performing teardown" or "RCU callback pending, non-RCU members are uninitialized" or "exclusive access to RCU-protected members granted to thread performing teardown, other members are uninitialized". And Rust is worse than C at working with uninitialized memory (Rust not using the same type for initialized vs. uninitialized memory/references is a feature, but uninitialized memory references are too awkward IMO).
my takeaway was essentially that you get sweet perf wins from semantics that are hard to replicate with a type system that's also making really strong guarantees without making the code SUPER gross.