58 points · by pjmlp · 3y ago · 143 comments
After all statistics just isn't on his side. Even the top engineers hired by Google create around 1 memory error every 1000 lines. And they didn't have one yet in 1.5 million lines of Rust [1] This is with all of the analysis tools at their disposal and in use for C++. And most companies can't afford the same top talent that Google can.
I've been working in safety critical software for a long time now. C and C++ will never be safe because their safety model relies on human infallibility. Ada and Rust IMO have the most potential here.
[1] https://security.googleblog.com/2022/12/memory-safe-language...
Using C++ for a greenfield project today should require some very good justification though.
Having to maintain legacy C++ applications is all the justification you need to have to understand that staring greenfield projects in C++ is quite frequently and by far the best option on the table
It makes absolutely no sense at all to multiply the tech stacks that a team needs to work on, let alone master, just because naive platitudes have been said about any novel tech stack. You do not make any application better or more secure if you get clueless developers onboarding onto new technologies and forcing them to maintain N+1 code bases and 2*n bindings.
This irrational dislike of C++ ignores the fact that adopting the latest C++ release and toggling static code analysis in your project, which nowadays comes for free, already gets any project way ahead of where naive retractors believe C++ is.
Except that security must be on by default, and it must be made hard (or shameful) to circumvent it. We all know any kind of protection is easy to bypass in C++.
I remember an article from a Julia developer quitting over the culture of using unsafe code that had installed in the community.
A mindset change is required by this profession. Too often (unverified) performance reasons have been used to justify risky code.
I'm not against improvements to C++ safety, I just think making C++ a safe language has provably failed.
The blog you linked to is a PR piece. A real study would go in-depth and look at the quality of the C and C++, particularities of the affected subsystems (such as a requirement to interact directly with HW, etc), split findings by subsystem and components and also link snippets of source code to CVEs. Hopefully Google will publish such a study someday instead of a few pieces of data and graphs.
But that’s not the major issue.
You’re taking as fact that Google’s Android C++ programmers are particularly interested in safety or are significantly more competent than average. Based on my occasional perusal of Android C++ code in a professional context I cannot confirm either assumption: Android C++ is not modern (not even C++11 modern) and is very pointer heavy. It’s an eclectic mix of C functions and C data types with C++ constructs.
Take a look at some random fixes for CVEs that I took from the December security bulletin:
* https://android.googlesource.com/platform/frameworks/minikin...
* https://android.googlesource.com/platform/packages/modules/B...
* https://android.googlesource.com/platform/packages/modules/B...
That looks like C with classes to me.
Perhaps it’s for the best if projects such as Android or Chrome, etc are rewritten in Rust. Catching stuff after the fact with sanitizers, fuzzing, etc will never work if the code is ignoring or can’t use most of the advances that Stroustrup was talking about.
Mostly because in the end they aren't doing what gets preached in spite of the in-house experts.
So how much hope have the regular C++ devs that don't take part in ISO C++ and compiler development tasks?
Under these circumstances, using C++ over decades has the results that can be seen - they can’t produce secure software.
I don’t think that Google or any other company can create secure products. I was actually surprised how many Java bugs were present in the December list.
The market, the incentives are not set up for that. Sure, using safe languages would help in a narrow sense, why not give it a try, but this is turning into scapegoating and silver bullet activism. Once they get rid of the most C and C++ code I bet their products will still be insecure, because the culture, the processes, the market and the people won’t have changed.
It would be more interesting to compare only the code of C++ and Rust written in the same timeframe. My expectation is that C++ wouldn't look as bad as stated in the article.
I agree. The article reads like it started with w conclusion and cherry-picked data to fit that.
In high-quality C and C++ projects, about 70% of vulnerabilities are caused by memory errors. (https://alexgaynor.net/2020/may/27/science-on-memory-unsafet...)
It is to be expected that there is no bug in the very thing that Rust is supposed to prevent. The same can be said of Java, JS or even PHP. What surprises me a little though is that there is zero memory error even in unsafe Rust. There has to be some unsafe code somewhere, for low level data structures and things like that.
Even unsafe Rust has more strict typing and borrow checking which C++ doesn't have. It does allow raw pointers, but it's still safer than C++.
The other thing is that if say 1% of your loc is unsafe Rust, it's much easier to put this under more scrutiny than the whole C++ codebase.
And 1% is a lot if you ask me. I almost never need unsafe at all.
>There has to be some unsafe code somewhere, for low level data structures and things like that.
In most cases you can just use the standard library code for these. They do contain unsafe of course, but it's in one of the most battle tested places.
However memory errors in C++ account for 70% of vulnerabilities. I'd expect 30% to thus remain.
Edit: meant to write memory errors not vulns.
The good thing is that since this code was written in a memory safe language, at least that eliminates an entire class of bugs.
Chrome was 2008. No idea if the code base has been completely "modernised" or not.
They are some of the most hardened codebases, and still fail in light of the issues with C and C++.
Oodles of vulns in linux that are made possible by C's lack of safety guarantees.
One memory error per 1000 LOC? I think they probably either use old style C++ or something else weird and ignore all static and runtime memory safety tooling to get to this error rate in their releases.
>"And they didn't have one yet in 1.5 million lines of Rust"
I assume that those 1.5 "million lines" do not contain any unsafe features Rust allows for. Am I correct here?
From his link: "Historical vulnerability density is greater than 1/kLOC (1 vulnerability per thousand lines of code) in many of Android’s C/C++ components (e.g. media, Bluetooth, NFC, etc). Based on this historical vulnerability density, it’s likely that using Rust has already prevented hundreds of vulnerabilities from reaching production."
Because as Rust grows it is easier to model more behavior and less unsafe is needed. They mention this in the article.
> There are exactly two uses of unsafe in the UWB code: one to materialize a reference to a Rust object stored inside a Java object, and another for the teardown of the same. Unsafe was actively helpful in this situation because the extra attention on this code allowed us to discover a possible race condition and guard against it.
> In general, use of unsafe in Android’s Rust appears to be working as intended. It’s used rarely, and when it is used, it’s encapsulating behavior that’s easier to reason about and review for safety.
https://security.googleblog.com/2022/12/memory-safe-language...
I would assume that there are a few `unsafe` lines of code in these 1.5 MLoC. Which still makes it easier to trust than 1.5MLoC of C++ in which (by Rust definitions of `unsafe`) every line makes use of `unsafe` features.
(insert usual caveats about tradeoffs, etc.)
(Yes, C++ core guidelines exist but they are complicated and don't guarantee safety in many cases.)
These, on the other hand: "Don't return a T&&", "Don't use a variable for two unrelated purposes" (in the context provided), "Don't define a (C-style) variadic function" and many others can be excluded from the language. Yes, you can forbid reusing loop variables. It's in your hands, Bjarne. Remove these constructions from C++.
You can't just cull old variadic functions because some old stuff won't work. It's easy to say "just get rid of it!" but that's never going to happen because it's backwards compatible. People really should be using parameter packs now instead of old variadics but I have worked with "developers" who hadn't a clue about them. The senior developers dismissed the new features as syntactic sugar and insisted on writing old-style code. They detested std::pair. They were unaware of move semantics. An rvalue reference was unknown. Lambdas were pointless to them.
It also isn't in Bjarne's hands - it's the committee. He fought against various things (as I recall from his talks at cppcon) but they ended up in the language anyway.
Ask Stroustrup. It's his example, and in this case avoidable.
> You can't just cull old variadic functions because some old stuff won't work.
Yes, you can. They've removed quite a few features from older C++ versions. You can turn them back on, if you want. So for C++x24 or whatever, they could say: for loop variables are always local, C variadic is no longer permitted, etc., and use some compiler flag to re-enable it.
> It also isn't in Bjarne's hands
But that's probably the person with most influence on the language. And if he would propose a C++safer version, which deviates from the standard by eliminating as many bad practices as he sees fit, people would follow, and the two would probably merge at some point.
But that won't happen, which makes the core guidelines a bit of a joke. "Here's an apple. Don't eat it."
Imagine I'm a function and I've got a pointer to some object. I know the object is owned by something else. Let's say I want to be extra safe and check whether the pointer is valid before accessing it. How do I do this? I cannot dereference it. I can't compare it against something useful. I could have a custom allocator that tracks the status of all allocated and freed regions of memory, cast my pointer to a void pointer, and check with the allocator (I think this isn't UB). But now I've also got to make sure that freed regions of memory are never reused for any reason. Thanks Bjarne.
You seem to be proposing that there's some magical bug-less language we should be using instead?
I feel that it's pretty much a consensus in the software security world that C and C++ should be avoided. Not sure why he omitted Rust from the list, it is in the original document, and is pretty much a drop-in replacement for C++. Also using a dynamic language like Ruby for anything secure or safe sounds like a terrible idea.
He didn't remove Rust from the quote though. The NSA document[1] contains two lists of languages considered safe and for some reasons Rust is only included in one:
> Examples of memory safe language include C#, Go, Java®, Ruby™, Rust®, and Swift®.
> Some examples of memory safe languages are C#, Go, Java, Ruby™, and Swift®
[1] https://media.defense.gov/2022/Nov/10/2003112742/-1/-1/0/CSI...
Nice observation, that seems to change the meaning of the paper substantially. OP might be privately admitting that you should use Rust if you can (not much that's new here, the Carbon folks said the same thing) and everything else just silently assumes that you can't do that for some reason - be it legacy or perhaps concerns about Rust's supposedly challenging learning curve. (It goes without saying that we shouldn't expect a C/C++ committee paper to outright advocate for Rust.)
I don't believe this. That's a reasonable claim for many other languages, but C/C++ are in a category of their own.
And yes, I aware of all the bells and whistles modern c++ can bring to alleviate some of that burden - but people can and do subvert those mechanisms intentionally and unintentionally, especially over refactors.
If one wants to know it all then yes. C++ is huge language. In practice except few people nobody really needs to. Subset of modern C++ enough to solve many real world tasks is very easy to learn in my opinion.
With Rust one must first train brain to wrap around those ownership rules and this might not be easy.
Fortunately or not I do not know even remotely enough of Rust to do the real comparison of "mental load" but at some point I will.
There are very good reasons to use C++ rather than Rust for some projects, typically interoperability, or developer already having experience in C++, as you mention.
However, having coded in both C++ and Rust professionally, my experience is that switching Rust has liberated much of my brainpower to concentrate on actually implementing useful stuff, so I have to strongly disagree on "mental load".
What is true is that, for a while after switching, getting code to compile in C++ is easier than in Rust. Took me maybe 6 months to 1 year before it became natural? However, as we all know, there is a huge difference between writing code that builds and writing code that works. In my experience, that difference is order of magnitudes larger in C++ than in Rust.
Performance and "low-levelness" wise it most likely is. From high level point of view it messes with how one must think when writing code and is missing some features / paradigms found in modern C++ (for better or worse, not gonna dwell on it here).
In my opinion it is closer to "drop-in replacement" for C.
> Also using a dynamic language like Ruby for anything secure or safe sounds like a terrible idea
afaik, it depends on how you use Ruby right? I agree that using metaprogramming could lead to issues, but i would like to hear your view points on security?
Static audits (including, but not limited to static typing) are very strong barriers against entire classes of safety issues. Not supporting them doesn't automatically make code bad, but it prevents lots of defense-in-depth (what the Rust community calls "fearless programming").
Languages like Ruby are indeed nightmares for static analysis. Even constructing a call graph is a disaster. But "safety properties" includes a huge amount of stuff that isn't necessarily security relevant. Do you want to prove that your Ruby program won't crash? Good luck. But do you want to prove that your Ruby program won't read key material out of memory when it shouldn't? Pretty easy. The security problems in these sorts of managed languages tend to either be logical errors (also present in a C++ codebase) or dynamic code loading / unsafe deserialization (not present often in C++ codebases, but much easier to eliminate in principle).
> Examples of memory safe language include C#, Go, Java®, Ruby™, Rust®, and Swift®.
> Some examples of memory safe languages are C#, Go, Java, Ruby™, and Swift®.
https://media.defense.gov/2022/Nov/10/2003112742/-1/-1/0/CSI...
Stroustrup quotes the second one without Rust.
Sure write some more planned improvements, double down, that’s fine, but if you’re presented with the kind of history and data we’re looking at, would you bet on them?
The performance topic is hyperbole. We’re not talking about bounds checking - that topic is irrelevant and has well understood solutions in written systems. There are swaths of code now demonstrating direct competition in large practical systems and small benchmarks. Lots. The performance argument is so unsubstantiated it’s almost dishonest.
There’s an implication buried in here that there is some set of problems that only c++ can solve. I’d like to see those written down in a focused manner, just the problem and it’s c++ solution. We can take it from there to see if the problems are truly unsolvable with any other tool.
Not sure about that. But the c/c++ community is still larger than, e.g. rust hence some worthwhile innovations (most recently e.g. co-routines, also executor interfaces for accelerated compute) show up first in c/c++. Then hopefully the rust folks figure out how to expose them to developers in a safe way.
They're not standardized in C and Rust. And in C++, the only feedback I've seen is https://probablydance.com/2021/10/31/c-coroutines-do-not-spa..., which didn't look very good.
C++ currently still needs to figure out its executor's story, as so far it also needs to depend on third party implementations.
I can attest that C++/WinRT story is quite painful, unless one is really deep down into co-routines and how they might interact with various COM/WinRT process models.
See The Old New Thing blog about them.
I think guidelines are poor ass method to improve security, especially when you can see that projects like Chromium still have a lot of mem. related safety.
Chrome might suffer from being a Google project. At least the old Google C++ style guides heavily pushed a C with classes approach and where outright hostile to every improvement over C new versions of the language brought along.
When you have restrictive conventions, it is easier for a new dev to get onboard, as well as for creating static analysis tools.
I haven't built anything out of choice in a C derivative since the late 1980s, unless I explicitly wanted to break something or do something naughty or talk to hardware directly.
While it does sound like Bjarne is being a bit of a sore loser of some popularity contest, he's still right in that exactly memory safety is too specific of an idea to be meaningful in the long term. Personally, I love arbitrary memory access. I can have a Julia server running in linux, expose a pointer address to stdout, pipe it to an SDL renderer, and the whole time be confident in my ability to make it work because it's C all the way down. If these languages were half as anal as say Java about their ideology I'd be downright insulted to use them at all.
C++ is interesting because it's really anal about its semantics, which turns into a sort of anti-ideology. There's comfort in not knowing what the big picture is when the language itself also has no clue, but lets you do whatever you want anyway. The mental weight of having to track lifetimes is just exercise.
Ultimately I think there are attackers and defenders. People who don't mind getting shot and people who do. Why is Bjarne worried about what the defense has to say about him? The N.S.A. (ffs) is simply playing a way different game than, dunno, arch, clang, llvm, Forth, Mathematica, whatever. It doesn't really matter.
C++ does not really permit this. It is incredibly hard to do type punning from void* without hitting UB. You really are only allowed to access objects through their names according to their lifetimes.
Here (https://www.youtube.com/watch?v=IAdLwUXRUvg) is a fun talk that involves trying to do a pretty basic kind of arbitrary memory access and concluding that it is simply not possible in C++.
I'm sure with C++ it's more complicated, but not impossible. With Rust it gets really funny. You have to subscribe to a completely unrelated mental model to read some numbers from a tape.
Case in point, ideology. I guess I don't care about bugs as much as I care about product? And I don't really have to, it's not like I get paid for this.
Time spent abstracting data iterators >>> time spent memorizing warning flags
But most of the ruby language is tested at trunk by the big companies like shopify, github etc to patch any issues.
I largely agree with this though: > even “safe” code (in any language) will have to call traditional C or C++ code or be called by traditional code that does not offer specific safety guarantees.
https://shopify.engineering/shopify-rust-systems-programming
https://shopify.engineering/porting-yjit-ruby-compiler-to-ru...
* smart_ptr
* RIAA
* Address-Sanitizer
But C++ allows for legacy code compatibility (a strength) but at the same time we don't have a compiler switch like "unsafe" and operator[] without bounds-checking (a weakness). I want it like in Rust, default mode is "safe" and the option to be "unsafe" when necessary. Is it late? Yes. Is it to late? Never.
I want the compiler to tell me "You're doing dangerous stuff. Sure?".Interestingly they don't mention Rust. Java and C# are designed for completely different usages.
RAII is good enough for automatically managing some simple parts of your data structures (some auto-freed vectors and strings are convenient), but it becomes haywire when you’re using it to manage more complex data structures, or something other than conventional memory (Like GPU buffers, handles from external systems like the OS, etc…) Single ownership of data can be too much of an ideal in reality, and shared_ptr semantics can be undesirable for expressing shared ownership in many scenarios.
I'm curious what weaknesses of shared_ptr you've found. With the addition of weak_ptr and enable_shared_from_this, they're a pretty versatile tool.