136 points · by nfltn · 7y ago · 56 comments
I don’t think that’s correct. The compiler is allowed to assume that functions marked noreturn do not return, but it’s not allowed to assume that functions not marked noreturn do return. In other words, it’s not undefined behavior for a function to call abort(), enter an infinite loop, etc. instead of returning. It would be very strange if it were!
There’s a somewhat related spec clause that lets the compiler assume that certain types of loops will eventually terminate [1], but that doesn’t apply here. Therefore I think the mentioned compiler optimization is illegal. The issue was reported back in 2011; it would be interesting to see whether newer versions of GCC, or Clang, behave the same way.
[1] https://stackoverflow.com/questions/16436237/is-while1-undef...
struct sock *sk = tun->sk;
unsigned int mask = 0;
if (!tun)
Obviously "sk" is not used until after the null check, but if we read it line by line as we would expect a naive compiler with no optimization to act, the pointer is followed before the null check, and null should produce a crashing program. It would seem that anyone expecting it to work would assume the evaluation of the initial assignment of sk to be lazy at first use, which is a very strange assumption.Still, I remember in 2009 people writing about that snippet as if it is a surprising result and the compiler did something wrong.
The reasoning is that, since the pointer has already been dereferenced (and has not been changed), it cannot be NULL. So there is no point in checking it. This logic makes perfect sense except that in the case of the kernel where NULL might actually be a valid pointer. The default selinux module allowed mapping the zero page, converting this bug into a privilege escalation flaw. This was however later corrected by preventing processes running as unconfined_t from being able to map low memory in the kernel.
EDIT: On rereading your comment, I think I realized you might be getting at something a bit different, which is that even if NULL is a valid address, no one in their right mind should be dereferencing it so this code is still illogical from a human perspective (to do a NULL check after derefencing) and there is no good reason to do so. That seems to make sense to me, but I don't have any production C experience.
(1) Recent C standards have peddled back a bit on ‘it should be possible to write a confirming C compiler for every CPU ever made’ (for example, IIRC, by fixing a char to be 8 bits), so that might be a thing of the past.
On a read it's a completely valid address. Write generates a bus fault.
Atmel ATMega parts it's the reset vector. A write does nothing.
There are systems, typically older ones, where all addresses are valid, including whichever NULL corresponds to. Real mode x86 is one such system - the bottom of memory there contains the vector table.
On later x86 you can map that page to whatever you want in kernel mode and it will work. But expect C programs to do weird things for what should be crashing bugs.
If nothing is mapped at 0, the kernel will fault just like userland would. This results in a kernel panic.
However, the kernel and userland share an address space. On a 32-bit x86 system with the default configuration, Linux allocates addresses 0 to 0xc0000000 to userland, and 0xc0000000 to 0xffffffff to the kernel. [1] (Each userland process had its own page table, but the kernel mapped itself into every page table.) This is unavoidable to some extent, because an interrupt or system call switches the system to kernel mode and jumps to a kernel-provided address, but does not automatically swap the page table, so at least the interrupt handler needs to be mapped into every page table. [2] x86-64 is similar, but with the upper half of the address space reserved for the kernel.
So why can't user code mess with the kernel's data? Each entry in the page table has a single privilege level bit. If it's set, both user and kernel code can access the page; if it's clear, only kernel code can access it. [3] At the time, there was no way to make memory accessible from user code but not the kernel, as that was considered unnecessary. Thus, userland couldn't access kernel pointers, but the kernel could directly load/store pointers belonging to the current user process. This was used intentionally when the kernel needed to copy data in or out of the process, but it also meant that if the kernel code accidentally dereferenced a bad pointer, it could end up referring to userland data.
That included the null pointer: accesses to it would succeed if and only if the current user program had previously mapped something at address 0, via mmap() with the MAP_FIXED flag. And that's what the exploit code did.
The page tables are under the kernel's control, so the kernel could make null pointer dereferences unexploitable (resulting in a kernel panic but nothing more) simply by refusing to allow user processes to map memory at address 0 – and in fact Linux already had an setting to do so (mmap_min_addr). But it was an setting rather than simply hardcoded into the kernel, because... well, some real software actually depends on mapping address 0 for silly reasons, mostly pseudo-emulation software like dosemu and wine which directly runs the emulated code in its address space. So not all systems had the setting enabled, and there was also a separate issue where enabling SELinux would cause mmap_min_addr to be ignored. [4]
Years later, Intel added an extension in newer CPUs called SMAP (Supervisor Mode Access Protection), which is simply a flag that makes the kernel fault if it tries to access pages marked as accessible to userland. In other words, the privilege bit now selects between kernel only and user only. Much saner – after all, even with mmap_min_addr blocking exploitation of null pointers, other garbage pointers could still end up pointing to userland, which made it easier to exploit the kernel (though, compared to the situation with null pointers, it's more often a question of "how easy is it to write an exploit" or "how reliable is the exploit" than of exploitable versus unexploitable). The kernel and userland still share an address space, though, so the kernel can just toggle off the flag when it's intentionally accessing userland data.
(Even later, the Meltdown hardware vulnerability triggered the implementation of kernel page-table isolation, but that's another story.)
[1] https://lwn.net/Articles/75174/
[2] https://stackoverflow.com/questions/32598810/does-cr3-change...
[3] https://webcache.googleusercontent.com/search?q=cache:b5g4ss...
[4] https://blog.namei.org/2009/07/18/a-brief-note-on-the-2630-k...
The surprise is that the if (!tun) check is optimized sway because if tun is NULL the assignment causes undefined behavior which the compiler does not have to take into account.
While we are debugging things like this, people are writing servers in JavaScript and web services in Python :O No need to optimize so heavily, they will waste it anyway :)
It definitely feels like as compiler writers continue to gleefully add more footguns to C/C++. Application programmers vote with their feet by using slower or much slower interpreted languages like Java, C#, JavaScript, Python Ruby, and PHP. Meanwhile system programmers are eyeing golang and rust for infrastructure.
One of my suspicions is that at the low end where I operate the marginal cost of higher speed is essentially zero. My firmware spends more than 9.99% of the time sleeping. Micro optimizations of a few percent is meaningless. At the other end superscalar processors are a moving target for micro optimizations. And further a lot of tasks look like init -> process data -> clean up. Over time the process data part has gotten very large. Making the init and clean up parts of the code a smaller and smaller percentage of the execution time. Micro optimizations in those parts of the code provide no value. Next is the constant movement to push the data processing into either specialized CPU instructions or GPU's.
Quite honestly, after a more years of experience: Cache smart and batch-query. Network latency, aka lightspeed in fiber or coppper is our enemy. Not a JVM GC'ing in a controllble way. If the CPU cache is your issue, you can either correct me, or you're abusing the network without realizing it.
Somewhat related: there's a recent paper that develops a language with syntax for marking data as secret; the compiler then goes even further and avoids timing side-channel leaks:
Cauligi, Sunjay, et al. "FaCT: A flexible, constant-time programming language." 2017 IEEE Cybersecurity Development (SecDev). IEEE, 2017. http://www.sysnet.ucsd.edu/~bjohanne/assets/papers/2017secde...
Often, what constitutes undefined behavior is non-obvious (and not well justified). For example, when adding two signed integers results in an overflow, it is undefined behavior even if your program never uses the result.
Due to C's definition of "undefined" behavior, it means that all of the guarantees we rely on to ensure security go out the window whenever the programmer steps on one of these land mines.
It seems to me that the problem is that trying to define undefined behavior is an inherent contradiction.
Setting aside the question of what exactly "undefined behavior" means, why does a language spec have to include it? If there is behavior that cannot be defined, why not just omit it from the standard?
You can use my safeclib, which implements the Annex K extensions.