276 points · by fanf2 · 8y ago · 183 comments
The code is also wrong because of strict aliasing. This is a real problem, your program can in fact exhibit undefined behavior because of this (it happened to me).
Some time ago I wrote some code to make these things simpler in C++. It allows you to define "structures" (which however are not real structs, it's an abstraction) and then directly access an arbitrary buffer through setters/getters. The code is here with documentation: https://github.com/ambrop72/aipstack/blob/master/src/aipstac... . In fact this is part of my own TCP/IP stack and it includes DHCP code (here are my DHCP structure definitions: https://github.com/ambrop72/aipstack/blob/master/src/aipstac...).
Consider this example of extracting a 32-bit int encoded as little endian:
#include <stdio.h>
int main(void)
{
unsigned char data[4] = { 0, 0, 0, 128 };
unsigned int i;
// the line of code from the article:
i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
printf("%x\n", i);
}
Compiling this with either gcc or clang using "-fsanitize=undefined" triggers this runtime error: test.c:9:61: runtime error: left shift of 128 by 24 places cannot be represented in type 'int'
That happens because, even though the bytes are unsigned as the article requires (using uint8_t instead of unsigned char has the same problem), they are promoted to (signed) int before the left shift as part of automatic integer promotion. When the left shift by 24 happens, it puts an 1 into the sign bit of the int, which is undefined behavior. Later the int is converted to unsigned (using implementation-defined behavior, which luckily is sane on all popular compilers), but by then it's already too late.The solution is to change the code slightly:
i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | ((unsigned)data[3]<<24);
This prevents the promotion from unsigned char (or uint8_t) to int by explicitly casting it to an unsigned int, which can then be safely shifted left by 24.But I think it is better to cast all the bytes to the final type (e.g. uint32) before shifting, not unknown types like unsigned int.
To reproduce you have to compile with "-fsanitize=undefined", as in:
gcc -fsanitize=undefined -o test test.c
./test
(clang also works with the exact same command line)You're right, these streams should be interpreted as uint8_t to avoid undefined behavior when shifting, masking, and ORing, and anyone doing this should tuck it behind some abstraction layer. It should never bleed into parsing.
Packed structs are slow on 1990's RISC processors. Packed structs are not slow on 2010 era super scalar processors.
I think that all compilers consider this to be a bit of defect in the relevant standards, and they'll compile your code the way you expect.
Are you sure the provision doesn't say "char *"?
Many OS network APIs are "char based" because the C standard requires that sizeof char be exactly one byte, so it used to be a convenient shorthand, but that's not the case anymore.
That's at least 1, not exactly 1.
It's POSIX that requires char to be 8bit.
Now, upon further researching it looks like uint8_t always has size 1 (as does char), but I'm still not positive that the second expression is technically valid.
They are not. Not every "C" compiler complies with whatever standard you care to cite. There are DSP platforms[1], for instance, where char is 16 bits. Obviously any hypothetical pointer arithmetic on such a platform must differ between (u)int8_t and char.
The intent of (u)int8_t is that such a platform will either a.) correctly implement (u)int_8 and operate on exactly 8 bits as intended or b.) fail to compile. This is demonstrably different than assuming char is 8 bits and yet compiling when it is not.
[1] for sale here: https://www.digikey.com/en/product-highlight/t/texas-instrum...
This statement is to generic to mean anything helpful.
I think the point our friend Rob Pike is making is that you could write general purpose code which accomplishes the task, and on a sufficiently advanced compiler, the swap may be eliminated where applicable; but when the point is made this way, it surely just pisses off people who know better.
C programmers are not (quite) children, you don't need to eradicate nuance to keep people reading.
"This code has no redeeming features. It must be thrown away and rewritten yet again. This time by an experienced programmer who know what error codes mean, how to use asserts properly, and most of all, who has experience at network programming."
The code in question quite clearly doesn't use C's standard assert macro, but a custom macro called assert_return (which I guess checks for a condition, and returns from the function instead of aborting the program).
So basically:
if (!condition) {
return err;
}
How else would one check for invalid input to the function?Asserts should only be used to signal "this code is broken" but that is not how they are used here.
A long while ago the GTK+ library used to suffer from a similar affliction. Mainstay GTK+ programs such as GEdit and Totem would print lots of warnings on the console. Since the GTK+ developers used the same facility (g_warning) for reporting both coding errors and for user errors like "file not found," debugging code was hard. Was the warning "supposed to be there" or was it a bug? GTK+ programs are much cleaner these days even if some programs still fails to make the distinction between user and programmer errors.
Assert already has a meaning and using it in this context is not great.
i.e. "assert" meaning "check something in this code is algorithmically correct"
Whereas when you're checking user input, use a very different term - i.e. validate or something.
So a fix would be to rename the macro to be obvious about it's usage - "validate_return" or "valid_or_return" or something.
To be fair I can see the problem because I do tend to write code comments saying "assert everything makes sense" when checking user input sometimes and "assert" itself doesn't properly convey the outcome if it fails - i.e. "abort_if" or "crash_if" would be a much more descriptive term.
If assert isn't assert, and if return values are also abused, why can I assume get is get, sort is sort and so on? Sort might check inputs, get might delete the customer account, who knows at this point. And that makes anything but a tiny code base pretty much unmanageable, or at least very very hard to learn.
At one point and older coder who I looked up to even complemented and adopted this pattern. 1998 was a good year.
I sometimes use a bunch of Ensure*() methods in C# if I need to validate input data. They throw exceptions if condition fails. If I only do this once I don't create those methods.
One drawback is the stacktrace has these Ensure names in it.
I would go so far as to say that using asserts in input validation is a good thing, in very limited quantities. I use them in places where the input should have been validated so long ago, so many functions back, that if something isn't as I expect here, I seriously fucked up somewhere else and the whole system has a good likelihood of being compromised by something unrelated to the condition I'm asserting. In that scenario I'd rather log and abort.
He provides constructive examples for all of the items that he criticizes.
- Instead of pointer arithmetic, base_ptr, offset, len.
- Instead of casting to internal structs, parsing into internal structs.
- Instead of network byte order, buf[offset] + buf[offset+1] * 256 .
- Instead of the wrong error codes, the right ones.
- Instead of random asserts over internal data structures, validation at parse time.
And you got it wrong. Shows that there is no silver bullet.
- In order to make a good decision about what to do next, you need a lot of context: what you need to clean up, what any calling function expects you to do, any internal state you need to update, etc. You either end up passing a lot of extraneous context info around, or you make everything global.
- Alternatively you bail with a status code and mutter "yolo" to yourself, or you throw an assert -- but crashing a system daemon with input is the essence of a DoS, so only the truly ignorant or lazy resort to it.
- Building a reasonable framework is hard when all your concerns are entwined like this. If at some point you decide asserts on input are bad, it's very hard to change that convention in this code. Essentially all your function signatures and your entire call graph change. There's an extraordinary amount of technical debt here; just look at all the places Lennart had to change the size/offset stuff. The logic for this is scattered all over the place.
People have focused on some of the tactical issues -- asserts on input, byte order conversion, etc. -- but the real issue is that when you write code in this style those things don't jump out at you because you have to do them everywhere. If your code had a better separation of concerns, as soon as you saw 'offsetof' in a parsing function you'd immediately see a red flag. It's so much easier to think in these specific contexts, where you're assured previous steps are complete, rather than in every single function having to get the entire conversion/validation/parsing flow correct every single time, keeping the entire thing in your head always.
Possibly a bad idea on systemd's part to reuse the name assert, but the code isn't doing what the blog assumes it does.
I guess someone felt like it shouldn’t be a meme headline on HN, but the result is nonsense.
;-D
One question: any smell of intentional obfuscation for this vulnerability, or is it impossible to tell?
If this were not buried in systemd, but was part of a standalone dhcpd package, would it have been done better or caught earlier?
One of the major criticisms of systemd is that it wants to take over all system management functions. In order to do that it needs to offer at least minimally functional versions of all the services it pushes out. It should not be news to anyone that trying to do everything instead of integrating with existing projects leads to sloppiness.
This incident is evidence suggesting that other serious issues are lurking in systemd as a result of the actions naturally arising from their policy.
If one is going to rewrite all of these things, I would expect one to learn from the history and not make the same mistakes over again.
One of the more popular DHCP clients is 'dhcpcd', which was created and is maintained by Roy Marples, the creator of OpenRC. It's fine when someone wants to work on DHCP clients and init systems, unless that init system is systemd?
(And for the record, systemd integrates wonderfully with dhcpcd.)
Centralized management/monitoring in general sucks. People don't seem to understand the problem and keep reinventing new centralized architectures suitable for their own special cases, instead of addressing that on architecture level.
Systemd didn't invent a DSL. It uses the existing config language from D-Bus (whether or not you think that's a good language is another matter).
> uses proper architecture with clearly defined boundaries
What boundaries in systemd aren't clearly defined?
> allowing custom application-specific management
What do you mean by this?
I always think that anytime there's an interesting bug in ANYTHING. I'm not an expert, but I would think it would be nearly impossible to tell the difference between "someone made a mistake" and "someone made this look like a mistake". I would think any decent programmer with malicious intent could do that anytime they wanted.
What? It was known well in advance.
Now what I don't understand is that for C you are not allowed to disable this, -fpermissive is not allowed for C, whereas for C++ you can. Anyone knows the reason why? The compiler error says "command line option "-fpermissive" is valid for C++/ObjC++ but not for C" - why is the compiler having this distinction?
I think Facebook in particular made a bunch of noise in that direction and celebrates how prioritizing IPv6 has let them make huge improvements in load times etc, but at this point you're as likely to find good information about that on Google as I am so I'll spare you any links.
So while IPv6 might not have taken over the Internet in any particularly observable manner so far, I think it's fair to say it has huge momentum at this point and has buy-in way beyond some IETF nerds and protocol fetishists.
I'd be curious to know how much time you can actually save because really, honestly, in the case of Facebook this particular aspect should be the last of their concerns as far as page load times are concerned.
Yeah - only 21% of all traffic handled by Google is over IPv6...
I think the only way to have high assurances is to program under a system that doesn't have these classes of errors. I don't care if it's a c static checker or a new language or what.
Unfortunately the long term solution to these problems in system programming seems to be rust. But it's going to take decades for it to be established and I'm going to look like a language hipster member of the rust evangelism strike force every time I bring it up.
But seriously, it's been decades and decades and we're still writing buffer overflows. What is the long term final nail in the coffin for buffer overflows?
I wouldn't be so pessimistic. Software is becoming increasingly complex and many people are starting to see that it is starting to get a little ridiculous. All we need is a tipping point in the form of a well designed kernel that works well. It doesn't need any hype, no HN announcements, nor major corporate backing. It just has to work and work well. That's how Linux got started. It filled a vacuum. We still have a vacuum in the form of crusty OS designs patched over with layers of code miles deep. That vacuum is the need for a new clean system for the networked distributed resource internet age.
What we need are more passionate hackers who work on this for the pure enjoyment and self satisfaction instead of selfish ego fueling; meaning don't code with the end goal of getting something on the front page of HN/Reddit or super git committer. Just code for the sheer enjoyment and challenge of it. Besides when you post these ambitious projects you get all sorts of jealous reactionary posts that attempt to pick apart your ideas and stomp on them. That can discourage people from making true progress.
What. That's a horrible idea. Not only would that require your hardware to understand abstractions several layers above what it actually operates on, it would also mean it'd have to check bounds of - for example - an array on every instruction accessing it. That is something compilers can do at more strategic places.
Please keep that complexity out of my CPUs, they're buggy enough already. At least with software we can fix issues later, which isn't a given with hardware.
And, of course, the added complexity of doing that in two instructions is also negligible. The entire problem seems to be that arrays are on a more abstract level than C operates. It looks like entirely a language problem.
> several layers above what it actually operates on
The instruction set is something of an abstraction bottleneck - C is tied to machines that look something like a PDP-11, while a lot of the stuff that the machine is doing is invisible at the instruction set layer.
I am not sure whether the experience from these machines was negative. It may be that when you move beyond one-dimensional arrays, bounds checking becomes more complicated.
Perhaps performance suffers too. Languages which do bounds checking often have intelligent compilers which can skip the bounds check in a variety of conditions. So even if the hardware is faster, it may be doing unnecessary checks. See for example : https://www.ardanlabs.com/blog/2018/04/bounds-check-eliminat...
x86 has bounds checking in hardware. it's called a page fault.
[edit: formatting]
Also what the other person said about burning down x86 and starting over.
It seems unlikely to me that the answer is going to be ATS, or "we burned down x86".
Honestly, this is a pointless rant. "Do this, but don't do that (because that's stupid)".
> "No other language has it, because it's bad"
The reason you "don't have pointer arithmetic in other languages" is - it's been abstracted away from you, for your convenience, so that you can just concentrate on your business logic and not have to worry about the rest. You may not deal with pointer arithmetic, but the people developing your JVM/CPython/V8/Chakra sure do. Author is simply ranting about the possibility of abusing/misusing the mechanisms offered by C/C++.
The rest of the comment is good, it adds to the argument, and I even agree with it, but there is no reason for this to be here. It doesn't add anything; it's just like calling names. From the HN guidelines:
> Don't be snarky.
> When disagreeing, please reply to the argument instead of calling names. "That is idiotic; 1 + 1 is 2, not 3" can be shortened to "1 + 1 is 2, not 3."
EDIT: To be downvoted like so for reminding people of the guidelines, HN sure is changing. I guess no good thing lasts forever.
https://stackoverflow.com/questions/32700999/pointer-arithme...
Sure, it's ranty and, like, maybe closer to op-ed than computer science publication, but I think even among the rarefied breed of people developing your JVM/CPython/V8/Chakra, you could easily find approval for the notion that pointer arithmetic is bad(*) and should be avoided as much as possible.
It seems kind of nuts to say array indexing isn't just a fancier version of pointer arithmetic.
But not in C.
I agree.
FWIW, from https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=912008 it looks like the vulnerable code is not enabled by default on Debian.
systemd works, that's why people use it. If it needs improving, then improve it, or file these. Somebody will probably agree and at least look into them, rather than a gaggle of strangers pointing and laughing.
https://commandcenter.blogspot.com/2012/04/byte-order-fallac...
And will a compiler make use of native byte swapping instructions with the code proposed by the author?
I think this is also the main point of the post you linked: the "bad" example has a numeric value and then performs byte swapping on it, the "good" examples only ever construct "correctly ordered" numeric values.
If you can possibly get to a place where you have a uint16 but the value is "in the wrong byte order", you've done something wrong already.
Admitting the possibility of values with the wrong byte order into your system casts every single value into doubt. Of course it's possible to resolve that doubt on a case-by-case basis by carefully identifying the right places to insert ntohs()/htons() calls, but to me that sounds like creating extra chores for yourself while working against the language.
A proper abstraction is the one where you specify both the size and the endianness at the point where you extract the value - i.e. where you just call a function like read_int16_be(byte_stream).
That isn't guaranteed. sizeof(short) and sizeof(int) are both allowed to be 1 on a system with chars at least 16 or 32 bits wide, respectively.
Whether there's a endianness conditional anywhere there or not is a bit of pedantry, I think.