384 points · by jwilk · 5y ago · 275 comments
If there's one place other than the kernel where truly defensive programming should be applied, it is systemd.
strdupa(input) without any length check
Fix is to replace it with unbounded malloc() instead of checking for sane length first.
I also do never understand why some libraries use "faster" methods everywhere, unless safer ones. it's not like all interfaces to systemd would need to be fast. but they should be secure.
This is likely because Unix semantics treat the init process specially: any process whose parent dies is re-parented to the init process. It's not clear what should happen to these processes if the init process itself went away, so the kernel just gives up.
[1] https://elixir.bootlin.com/linux/latest/source/kernel/exit.c...
"Ummm, lets not do that, it's not such a great idea..." -- Windows Vista team, 2006
A proper init system similar to runit or s6 would be written in something safer (minimum unsafe) like Rust, be modular, simpler, follow UNIX philosophy, and not try to do everything in one process. Microkernel-style.
My "systemK" joke was indeed implying what you said, that systemd is "a key place in the stack where you would need to be super careful." (Almost Kernel-like.)
And my question was legitimate, although poorly-researched. Answering myself: CVE-2021-33910 only affects systemd, not all FUSE in general.
For me it crashes into the fork_userns:177
PS: don't need to downvote. Sometimes managers want you to prove that there's a need to patch. It's dumb but it's what it is
Is this the type of things that could be caught by a linter or strict compilation rules? This seems to be to be a failure of the type system.
https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidel...
But strict compilation rules (eg, clang's -Weverything) mainly only work if you treat them as errors (so -Werror), and then some of those strict are then also questionable at best, and just outright annoyingly wrong at worst. For example, unused parameter warnings on virtual methods are a waste of time to deal with. It's not a symptom of a bug most of the time, so it being an error just generates workaround churn or you end up just disabling the warning and then maybe that bites you the few times it would have pointed out an actual issue.
Beyond the blanket ones like clang's -Weverything, it can otherwise be a job to keep up with compiler upgrades and the vast number of warning options they have.
Why is that even a warning? If at least one of the implementers use a parameter and a warning is shown the warning itself is wrong. That’s just broken implementation of the warning?
typedef struct {
unsigned value : 4;
} S;
void foo(S* s, unsigned value) {
// error: conversion from 'unsigned int' to 'unsigned char:4' may change value
s->value = value;
}
I mean, I guess I can see the rationale.. it's just annoying to have to resort to using pragmas to turn off -Wconversion whenever I need to assign to a bitfield. #include "stddef.h"
short foo(short a) { return a % 42; }
size_t bar(void) {
size_t sz = ~0UL;
return foo(sz);
}
https://godbolt.org/z/3ec9v8Pa4 warning C4267: 'argument': conversion from 'size_t' to 'short', possible loss of data
https://godbolt.org/z/nYeWT7zv6 (/W3 is the default warning level when creating a new project)I saw these warnings so often that I assumed that every compiler had them.
https://clang.llvm.org/docs/DiagnosticsReference.html#wshort...
The more general-purpose -Wconversion has many false positives, often around int to char conversion. Some functions like int toupper(int) have an unexpected int return type to deal with special out-of-bound values like EOF.
And it's because the kernel does a lot of non-standard things, mostly because it has to. It is not a normal program.
(Some Rust developers argue that even "size as i32" should be avoided, and "size.try_into()" should be used instead, since it forces the programmer to treat an overflow explicitly at runtime, instead of silently wrapping.)
It's important to still have the option for efficient truncating semantics, though; some software (e.g. emulators) needs to chunk large integers into 2/4/8 smaller ones, and rotation + truncating assignment is usually the cheapest way to do that.
But, importantly, this is a rare case. Most software that does demoting casts does not mean to achieve these semantics.
So I wonder — are there any low-level/systems languages where a demoting cast with a generated runtime check gets the simple/clean syntax-sugared semantics (to encourage/favor its use), while truncating demotion requires a clumsier syntax (to discourage its use)?
let x = size as i32;
... even if what you meant was closer to let x: i32 = size.try_into().expect("We are 100% sure size is small enough to fit into x");
But at least it isn't C or C++ where you might accidentally write x = size;
... and the compiler doesn't even warn you that size is bigger than x and you need to think about what you intended.It's really hard to fix this in C++. Some of the Epoch proponents want to do so using epochs to get there, basically you'd have a "new" epoch of C++ in which narrowing must be explicit, and old code would continue to have implicit narrowing so it doesn't break.
That's not true tho, compiler with reasonable flags set will definitely warn you and if you really don't like this kind of code you can force compiler to issue an error instead
x = { size };
// a is a UInt64
let a = Int.random(in: 0..<Int.max)
// causes a fatal runtime error if out of range, halts execution
let b = UInt32(a)
// returns a UInt32?, which will be nil if out of range
let c = UInt32(exactly: a)
// another approach for exact conversion:
guard let d = UInt32(exactly: a) else {
// conversion failed
// handle error and return
return
}
// 'd' is a UInt32 without any bits lost
// always succeeds, will return a UInt32, either clamped or truncated. Truncation just cuts off the high bits.
let e = UInt32(clamping: a)
let f = UInt32(truncatingIfNeeded: a)The "as" operator is often considered to have been a mistake. Both because of unchecked casts and because of "doing to much".
So I wouldn't be surprised if in the (very) long term there will be a rust edition deprecating `as` casts (after we have alternatives to all cast done with `as`, which are: Pointer casts, dyn casts/explicit coercion and truncating integer casts, for some we already have alternatives for on stable for other not).
And for all who want to not have `as` today you can combine extension traits (which internally still use `as`) + clippy lint against any usage of `as`.
EDIT: I forgot widening integer casts in the list above ;-).
Not exactly the same thing, but in a related area C++ does this a bit.
In C++ you can always still do a c-style cast `(int) some_var` (and the implicit casts obviously), but in general you're meant to use the C++ style explicit casts like `static_cast` and `const_cast`. These are generally tidy, but the most powerful and dangerous of these casts is deliberately awkwardly named as `reinterpret_cast<int>(some_var)` rather than something terse.
It's always easy to spot during a code review.
edit: a cast will throw an exception if it fails, in case that was not clear from context.
Then safety is free...
I know Erlang's BEAM VM has a "fail jump pointer register", where instructions that can fail have relative-jump offsets encoded as immediates for those instructions, and if the instruction "fails" in whatever semantic sense, it takes the jump.
But most CPUs don't have anything like that.
Would you want it to trap, like with integer division by zero?
CPU traps are pretty hard to handle in most language runtimes, such that most compilers generate runtime checks to work around them, rather than attempting to handle them.
We consider it best practice to try and organize the types such that explicit casts are minimized.
I thought about this very, very carefully when designing Virgil[1]'s numerical tower, which has both fixed-size signed and unsigned integers, as well as floating point. Like other new language designs, Virgil doesn't have any implicit narrowing conversions (even between float and int). Also, any conversions between numbers include range/representability checks that will throw if out-of-range or rounding occurs. If you want to reinterpret the bits, then there's an operator to view the bits. But conversions that have to do with "numbers" then all make sense in that numbers then exist on a single number line and have different representations in different types. Conversion between always preserve numbers and where they lie on the number line, whereas "view" is a bit-level operation, which generally compiles to a no-op. Unfortunately, the implications of this for floating point is that -0 is not actually an integer, so you can't cast it to an int. You must round it. But that's fine, because you always want to round floats to int, never cast them.
While some folks aren't too fussed about warnings like this, those folks generally aren't writing secure code like kernels. I'm very surprised that kind of conversion was permitted in the code.
https://rust-lang.github.io/rust-clippy/v0.0.212/#cast_possi...
Adding .into() works though, which is the recommended method if the conversion can be statically guaranteed (otherwise try_into should be used, which will become easier in the 2021 edition as the TryInto trait will become part of the prelude).
class TimestampedObject implements Comparable<TimestampedObject> { long timestamp; int compareTo(TimestampedObject other) { return (int)(timestamp - other.timestamp); } ... }
ErrorProne catches this: https://errorprone.info/bugpattern/BadComparable
This os why in C it is a good practice to enable all compiler warnings and to have the compiler treat warnings as errors.
If you write for C compiler Foo 8, there's a decent chance Foo 9 will raise a warning which didn't exist before. Now you have to handle "why doesn't this compile" issues and distributions have to patch your sources to do future releases. And that's ignoring bugs like GCC in the past where in some versions you could not satisfy specific warnings.
But never ever leave -Werror enabled for building in Release mode. You'll be preventing your code from building as soon as a new compiler version goes out. Maintainers or code archeologist will have a much worse time than if this option was simply disabled to start with.
IMHO one should always be using C99 types instead of int, but Linux predates that.
Also, shouldn't that implicit conversion cause a compiler warning?
ILP64 causes a lot of problems, most notably needlessly-increased memory usage and, in C, the inconvenience of requesting a 32-bit type when int is 64-bit. It's rather uncommon to actually need the extra 64-bit range except when describing pointer addresses and memory/disk sizes, both of which benefit from an explicit intptr_t/size_t type for readability if nothing else.
But of course getting C programmers to use these integer types rather than the ones they grew up with isn't easy.
"Always" is a strong way of putting it, there are often times where it makes sense to use the platform's "natural" word sizes (which is the entire point of having `int` `long` `long long` etc.)
In those cases we probably don't care about the full range of the larger types, so it doesn't hurt to use the smallest type for a range of expected values. If it does make a difference, the program will behave differently when compiled on a different arch or even a different compiler.
But maybe "generally" instead of "always". OTOH even I am guilty of using an int to loop over an array.
That would lead to a hole in the type sequence (char <= short <= int <= long <= long long) for 64-bit targets (where int is the 32-bit type while size_t is 64 bits).
> IMHO one should always be using C99 types instead of int, but Linux predates that.
On the other hand, on Linux "long" has always been defined as the same size as size_t, so using "long" instead of "int" everywhere could also be an option.
In Haskell I would use an exception, and mark the function as unsafe, but the stdlib seems to disagree with me here.
I'm clueless about security: where does this fall on the scale of non-issue to critical? It strikes me as tending towards the latter, given that it enables unprivileged users to become root. Any insight into past Linux Kernel vulnerabilities that were severe?
If the attacker already has that level of unauthorized access, you're already doomed.
It also breaks sandboxing. To whatever extent you're trying to run programs that are somehow jailed, so you can download and run them without worrying about them taking over your system, kernel LPEs break those assurances.
https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux...
Got unrootable old (but still fully working) phone there, might try to play with it.
m->size must be of type size_t. It's slightly mind-blowing to me that casting to a smaller unsigned int can cause a vulnerability. But I guess unintended behavior (not undefined) can do that.
Should we be afraid developers will stop caring? Did they even care in the first place?
...so basically 32-bit systems are totally unaffected (and I believe size_t and int are the same size there anyway), but I think bugs like this are easily prevented by simply imposing sane limits --- there is zero reason to even consider allowing a path more than a few K in length, and IMHO even that is overly generous.
While I know there's a lot of hate for Windows' traditional 260-char limit, I personally haven't run into it as a developer except by accident (e.g. runaway recursion) and it's very comforting to know that the limit is there so code will fail before it consumes the disk or memory entirely.
Clearly not a nodejs developer then! npm's insanely nested dependency graph caused me to hit the 260 character limit relatively regularly. (though this was several years ago, so maybe they have mitigations for that now)
C:/current/working/directory/that/is/reasonably/deep/testrun/YYYY_MM_DD_hh_mm_ss/code/moduleName/src/build/bin/../../../../../../outputs/moduleName/YYYY_MM_DD_hh_mm_ss/outputFolder/moduleName_testrun_results.txt
or some garbage like that (you get the picture). Yes, half the path was taken by descending into some directory that it went out of again straight away. Test runs would fail because of the 260 char limit unless we cut down the module name length. (Thankfully this did not need to be done in the code itself, just in the test run invocation.)In general, no. Attackers are clever and can usually find their way around arbitrary limits when a bug exists. Sometimes such a restriction might stop them, but more often than not they’ll bypass it some other way.
That's over 9MB, running in supervisor mode.
2021, and people are still surprised every time a kernel bug with security implications is found.
Maybe it is time to look at different OS designs. Large companies such as Google (Fuchsia) or Huawei (HarmonyOS) have begun to pick up on this.
Making the kernel as small as possible, and having components and drivers run unprivileged is the primary way to achieve this.
Some real examples that do this: Minix3, Haiku, Genode, Fuchsia, Harmony.
It’s like you sent a 1kg package through the postal service, and then the recipient gets an envelope containing a piece of cardboard from the original packaging.. And everyone involved is somehow A-OK with all of this.
If your programming language silently converts between types (in any direction), just to accommodate the programmer, instead of them specifying what they actually want to compute, you simply have failed as a programming language designer.
That's some hubris. The C language is 49 years old. Dennis Ritchie made reasonable design decisions for the time he found himself in. I think we should be understanding of that, and the network effects that lead to large parts of the world's critical software infrastructure being implemented in C. I don't think he failed at anything.
I used to be a C developer. I know how easy it is shoot your foot off in C. I think that, arguably, as an industry we should think twice before building more big and/or critical systems in C. There are better tools now.
But we are where we are and it's important to understand how we got here. Castigating our predecessors as failures does them a disservice.
However with the painful experience that was the Python 2 to 3 debacle, it's clear to me that the only way to do such upgrade is with an all-in commitment. See Ruby: breaking compatibility hasn't ever been as discussed and polemic as in Python. You just upgrade and tell the world: here's the new version, and the old one will be supported for not a day further than 4 years.
People would complain but at the end of the day the world keeps turning. We could be already at C 3.0 and be much happier without all the old compatibility baggage that the language drags with it.
"Although we entertained occasional thoughts about implementing one of the major languages of the time like Fortran, PL/I, or Algol 68, such a project seemed hopelessly large for our resources: much simpler and smaller tools were called for. All these languages influenced our work, but it was more fun to do things on our own. "
How?
Or have you, completely on your own, decided that my criticism of programming language design in the 2020s is somehow applicable to languages “literally” designed in the 1970s?
Why not go one step further and deny Alan Turing and Alonzo Church, and their achievements…?
That’s my point, no shade on K&R though.
age is orthogonal to good design.
Also, tangentially related is the signed/unsigned business which tends to get in the way frequently. For example, OpenMP 2.0 (the only OpenMP version you get to use with MSVC) requires loop indices to be signed, but both std::vector::size and std::vector::operator[] deal with unsigned integers. Casts guaranteed!
Oh, I didn't know Linux supports GB long path name. On Windows it's limited to something like MAX_PATH_LENGTH which was defined as 200+ chars when I worked on it.
Since W10 Anniversary Update, there is a setting to disable the MAX_PATH limitation in various APIs, but applications still have to opt into long path awareness via a manifest key.
IIRC, its a mess because it was lifted inconsistently for different access methods (APIs, and as a consequence UI/CLI methods that depend on them), and at least for some in ways which also are or were dependent on how paths are expressed.
So it is, or at least has historically been after it was first “lifted”, a minefield of inconsistent, surprising behaviors with plenty of gotchas if you didn’t treat it as if it were still a limit.
* the system must have LongPathsEnabled set (though it might be the default nowadays, not sure)
* the application itself must have `{http://schemas.microsoft.com/SMI/2016/WindowsSettings}longPa...` set in its manifest
>PATCH 3.12 108/142] fs/seq_file: fallback to vmalloc allocation
>Signed-off-by: Linus Torvalds <torvalds@xxxxxxxxxxxxxxxxxxxx>
Oh maybe not this time :-)
Try this:
>> const x = 288230376151711740;
>> x == x + 1
true
Or this: >> 2\*1024
Infinity
JS doesn't even have integers. It only has floats. JS is by far the worst language I know of when it comes to integer support.If you want a better example of arbitrary precision integers, try Python, for example.
I also worked on a project once where unique IDs of objects could get quite large (because they were random u64 integers). Those IDs were serialized and sent to a browser. Sometimes two objects were viewed as "the same" in the browser application because their IDs were truncated by the floating point precision issue.
Math.pow(2, 53) == Math.pow(2, 53) + 1
This is a bit clearer I think. The addition just barely overflows the 53 mantissa bits of the IEEE 754 double precision floating point number.By the way, JS has BigInts these days, which are supported by all major browsers: https://caniuse.com/bigint
>> const x = 288230376151711740n;
>> x == x + 1n
false 2**53 == 2**53+1
^^ even more clear.That's why Number.isSafeInteger(a) exists.
Integers up to +/- 9007199254740991 (Number.MAX_SAFE_INTEGER) are fine.
I for one am tired of the chicken & egg issue of "CPUs don't support efficient overflow checking because nobody uses it, so it's slow" and "Overflow checking is slow because the CPU doesn't support it, so nobody uses it". For all the other good security work done in both software and hardware, much for things far more complex than this, this seems like an absolutely batshit insane oversight considering the cost/benefits for fixing this.
Would it be possible to just silently replace with arbitrary sized integer and not break any code like safeintadd?
You may not be able to turn enforcement on for all code immediately. There's even the rare bits of code that depend on current overflow behavior. (Due to our human brains and the fact that we can easily name these bits of code, making the cognitively available, people often grotesquely overestimate the amount of code that operates this way. I'm sure it's only a matter of how many zeros belong in the 0.001%.) But we need this support to be available for code to be turn on easily and cheaply.
But what really boggles my mind, again given all the security work we've done, is that the reaction to this remains a combination of silence and "we can't do that!", when it seems to me the reaction ought to be "well duh jerf we all know that already." I don't get this. I don't get this attitude at all. This is a huge source of errors, a good fraction of which are security bugs, and nobody seems to care. Incomprehensible. This is, arguably, the number one thing that could be getting changed right now to fix security issues, and I just get slack-jawed "whaaaa?" in response to the idea.
One hundred plus one hundred is not negative fifty six! Here we are trying to hold together megabytes upon megabytes of security-critical code in a world where 100 + 100 = -56. Is it any wonder that writing any sort of code to maintain security invariants is tough in an environment where 100 + 100 = -56?
Null pointers are also handled by the kernel, not the CPU. Its called a segmentation fault because you are trying to access a memory segment that the OS doesn't want you to.
The x86 assembly uses fixed width immediates. CPU registers are a fixed width. For any code to compile and run, it needs to make decisions about how large stack frames need to be, and how much heap memory to allocate.
This was the parent's point about abstractions. You can make a library that pretends to be a variable sized integer, but to implement such a library you need to make a decision about how much space to allocate and the width of variables in order to compile. There is no getting away from how the hardware works.
I thought js "integers" are just floating point numbers?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
A newly designed OS kernel could perhaps take on this kind of feature. This would be the kind of OS that could be formally verified and would be willing to pay that runtime cost for arbitrary precision.
typedef struct { /* TODO */ } arb_int;
arb_int *new_arb_int(void);
void delete_arb_int(arb_int *);
arb_int *arb_int_add(arb_int *, arb_int *);
arb_int *arb_int_sub(arb_int *, arb_int *);
arb_int *arb_int_mul(arb_int *, arb_int *);
arb_int *arb_int_div(arb_int *, arb_int *);
bool arb_int_gt(arb_int *, arb_int *);
bool arb_int_lt(arb_int *, arb_int *);
bool arb_int_gte(arb_int *, arb_int *);
bool arb_int_lte(arb_int *, arb_int *);
bool arb_int_eq(arb_int *, arb_int *);