618 points · by brundolf · 3y ago · 594 comments
Defenders of C/C++ frequently note that memory safety bugs aren't a significant percentage of the total bug count, and argue that this means it's not worth the hassle of switching to a new language.
Google's data suggests that while this is true, almost all severe vulnerabilities are related to memory safety. Their switch to memory-safe languages has led to a dramatic decrease in critical-severity and remotely-exploitable vulnerabilities even as the total number of vulnerabilities has remained steady.
On top of that, memory safety vulnerabilities are disproportionately high severity: "Memory safety vulnerabilities disproportionately represent our most severe vulnerabilities. In 2022, despite only representing 36% of vulnerabilities in the security bulletin (NOTE: down to 36% from 65% because of moving from C++ to Rust and other memory safe languages), memory-safety vulnerabilities accounted for 86% of our critical severity security vulnerabilities, our highest rating, and 89% of our remotely exploitable vulnerabilities. Over the past few years, memory safety vulnerabilities have accounted for 78% of confirmed exploited “in-the-wild” vulnerabilities on Android devices."
Imagine if in any other field, a process or technology were developed that cuts the number of high-severity issues in half.
For example, a modification to the standard anesthesia protocols that demonstrably reduces anesthesia-related fatalities by 50% in clinical practice.
And now imagine, in reaction to this revolutionary development, thousands of anesthesiologists publicly said things like "what matters is not the technique but the skill of the physician", "good anesthesiologists don't make mistakes like that in the first place", "but this new technique takes 1%-3% longer than the previous one" or similar.
Utterly unthinkable, isn't it?
Yet in software engineering, this is exactly what has been happening every day for more than a decade.
No. Ignaz Semmelweis faced it in the 1800s for daring to suggest (what we know know as germs) made people sick and hand washing could drastically reduce medical complications. He was able to prove it too.
By the end was locked up in an asylum for his ‘crimes’.
Want more recent?
How many stories have you heard of instruments or gauze or whatever left in surgical patients? Of operating on the wrong part or person?
People are fallible. But checklists help a ton. We know that for sure. Why is aviation obsessed with following them? Because they work to increase safety.
Surgeons have resisted them. I don’t know the current state of it, but they were making that exact “good surgeons don’t need it” argument. I remember it being a plot point on an episode of a medical drama (ER? Or maybe Grey’s Anatomy).
There are probably tons of other examples in other fields.
Software is not terribly different from that. The cost of replacing foundational software is tremendous, much higher than just "adopting a new protocol".
Of course, new software should still take heed of this and try to improve.
Not really. Rust is the first major attempt to achieve c/c++ performance & capability while also being safe.
Prior to that nearly every memory safe language came with crippling tradeoffs, and that is why people rejected them. Especially as performance and efficiency took center stage again with the massive increase in battery powered devices & the general plateau of single core CPU performance over the last decade
> Yet in software engineering, this is exactly what has been happening every day for more than a decade.
Consider what happened to poor Semmelweis when he discovered in the middle of the 19th century that hand-washing improved medical outcomes: doctors of the time were too proud to accept his results and drove him out of the profession (and to his early grave) rather than change their practices.
All these people who insist on continuing to write new C programs have the same mentality as those doctors who refused to wash their hands.
This says more about those C++ defenders.
Now Google has put this to the test and has the data to prove it. We should not allow the worlds technology security to be held hostage by a group of people too lazy to adapt with the times.
Nitpick, this is not quite true. Memory safe languages are what you should be using in contexts where security and reliability are critical. This is generally the case but there are some contexts where other concerns are genuinely more important. Of course when this is necessary is often misrepresented but these cases do exist.
Not everybody is writing security-critical code. For some things productivity and time-to-market is more important and security is not enough of a concern to justify dealing with a language with horrible compile times and a self-righteous, dogmatic community.
Defenders of C++ argue that there's no reason to change the language, because new features around safety guarantees are being introduced into every C++ standard starting from C++11 at a remarkable pace, so remarkable that compilers implement them faster than the existing adoption rate. And the adoption rate speaks volumes about existing capacity to port/rewrite big codebases in entirely new stacks. The new stacks also tend to have fewer custom static code quality analyzers from third-party vendors, and they are used a lot in mission-critical C++ codebases.
Are these static code quality analyzers detecting code quality problems that Rust and company are also vulnerable to? Or are they mostly looking out for the hundreds of legacy footguns that C++ still officially supports?
If they’re saying that C++ can’t be saved, maybe they’re worth listening to.
It might be true, but it also sounds like an appeal to authority. I suspect there also might be voices that are being silenced or aren't given a similar platform to speak up and provide an alternative viewpoint on the matter within the same organisation, because <team budget/political reasons why>. After all, there are greenfield projects that are being started in C++20 and people are enthusiastic about their prospects. I wouldn't just blindly dismiss their reasons in favour of Google ones.
Modern C++ is indeed a huge upgrade on what came before and with a good amount of static and dynamic analysis the state of low-level programming is much better now, but there really is no reason for new programs to be written with these. Besides the bottom of the stack, managed languages are more than fast enough for nigh everything.
It seems plausible that splashy projects in new languages are better for careers than grinding through "stable" codebases using "boring" engineering practices.
I also gather that Google has a challenge, possibly for similar reasons, keeping their third party dependencies updated and up to standards. A lot of those are written in C and C++, probably.
You’re merely reading what you want between the lines.
Google's one of the worst C++ shops because their code standard basically forbids using modern C++, and their C++ is more like 90s Java than modern C++. It's no wonder they want to get away from it.
Modern C++ has many memory safety features. If a company has learned that its people fail to use them, then bad for them.
Of course, there are languages that abstract memory safety to the point that they eliminate those types of mistakes. But languages are tools for a job, and only some tools are applicable where C++ is applicable. We should not bury C++ prematurely before answering the question - "what else is as fast and efficient as to replace it for OOP?" And if a project doesn't need fast and efficient code, then why is it using C or C++ in the first place?
Overall, selecting the correct tool for a job is more important than figuring out which tool is better in some abstract way.
The same question comes up when an existing system is rewritten from language A to language B and big performance gains are seen. The language could be the big cause, but so could the extra engineering effort itself -- updated design, fresh attention to the requirements, etc.
Yes, things have gotten better. Smart pointers are a godsend. Sanitizers are a godsend. Various static analysis tools work pretty well.
But even codebases that adopt all of these things religiously still are riddled with security vulns.
Well, first of all, this is said but not proven.
But it's easy to prove that memory safety bugs are not a significant percentage of the total number of bugs, even Google agrees.
Vulnerabilities are not the same thing as bugs, a vulnerability like spectre or meltdown are not due to a bug in the software, have an ubiquitous immediate impact on 100% of the devices and are much harder to fix or mitigate, sometimes it's could even prove impossible.
The same bias can be explained using the exact same words used in the article
"Despite most of the existing code in Android being in C/C++, most of Android’s API surface is implemented in Java. This means that Java is disproportionately represented in the OS’s attack surface that is reachable by apps."
It can be read as: of course most of the vulnerabilities are due to memory safety bugs, it's much harder to gain root privileges exploiting a bug on the colors of a specific element of the UI, assuming it would be possible.
It can also be read as: most of the userland software is based on Java, which is memory safe by default, assuming there are no bugs in the implementation of the JVM, which is entirely not Java.
Given that, the problems become
- rewriting the entire ecosystem in memory safe languages requires rewriting everything from scratch, which is a task that even Google will have huge problems to complete (reminder: Google is the number one killer of its own projects) in reasonable time or without wasting more money that it's worth on it. Is an half complete not battle tested complete rewrite actually safer? Historical data says it usually isn't.
- are the user actually safer when memory is safe? I mean, memory safety bugs gave us jailbreaking for locked devices, memory safe languages gave us bugs like CVE-2021-44832
I wouldn't classify the issue as black/white, there's a lot of grey to be considered.
Using language-independent bug example in discussion about language-caused bug vectors isn't exactly honest.
Rust would stop Heartbleed for example, and that was one of huge vulnerabilities
using a low budget project with few developers maintaining one of the most used libraries in the whole World as an example of non memory safe languages perils is not exactly honest.
Heartbleed could have been easily fixed if the companies profiting from using OpenSSL donated a few more eyes to look at the code.
Similarly to what happened to Log4j bug, which had an enormous impact, similar to the heartbleed one and affected a fully memory safe language.
#RustForTheWin
1) The most cost-effective way to eliminate the majority of memory bugs is to just start writing all new code in a memory-safe language. If you were going to write new code anyway, you may as well do it safely.
2) Going back and re-writing existing code that doesn't need to be changed may solve latent memory bugs, but it will likely introduce other regressions that could be worse for security or for user experience. If code doesn't need to change, it's often better to leave it as is.
Not that a rewrite is never called for, but it's not necessarily the best course of action by any metric (even when neglecting the cost).
People tend to forget that they don't have to live with those problems, but they still have a cost
Defenders of C might note that Android is java and IOS is not and compare the security of those two systems and say clearly memory-safe is focusing on the wrong thing. This is equally true but no more valid an argument.
The one that really bothers me in all these language-booster discussions (that we should and need to have) is the functional programming formal verification claims. We have no ssl library written in a memory-safe, functional language that has been proven correct that has dominated the space. Heartbleed wasn't yesterday.
I look down the list here: https://en.wikipedia.org/wiki/Comparison_of_TLS_implementati...
And I think something is not being discussed as far as replacing memory unsafe languages of critical security infrastructure. What is it?
You will find at the bottom of that page C implementations of curve25519 that are proofed and derived from F* and Coq. Curve25519 is a relatively simple implementation and only one part of any system that uses it. As you can see in both of these implementations the papers recognize a team of contributors each - this should provide some insight as to the cost of such work. That doesn't make it unimportant, it just makes it rare.
Wireguard seems to be written almost entirely in C, is that right?
Heartbleed didn't affect https://hackage.haskell.org/package/tls even though it isn't formally verified.
Why hasn't this really good result meant _everybody_ now uses that library by default and has to justify using something else?
There is something here not being discussed, what is it?
And I don't know about "used at scale" but we use it in production for Pernosco.
Even more evidence that the negative performance impact of bounds checking is minimal, nay, it can even be positive.
But if "security" isn't remotely a concern for a given project (like almost anything graphics / gaming related), this is not at all evidence for changing anything. It could be that Rust's optimizer eliminates the bounds checking so regularly as to be a moot point, but this isn't saying anything of the sort. It's saying that the cost, whatever it was, was judged to be worth paying for the improved security for these projects
Gaming platforms have gotten a lot less lenient over time, and with pretty much every game these days having online components, "security isn't remotely a concern" has become a lot less true.
I'm sure it's possible to construct such a thing, but I cannot imagine it ever being common enough to show up on any sort of head to head comparison.
And so you save the overhead of the extra refcounting or the re-entrant locks (though that would be unsound anyway), and you can safely use anything which works off of references.
These games would go on sale once a year or whatever and attract new players, and people would post warnings in the steam forums and whatnot to try to stop people from being effected by the issue, but I am sure some people either didn't listen or didn't notice the warnings.
I haven't looked into the issue in a few years at this point, but it's very possible that the games are still unpatched and being listed in the store to this day.
Anything that connects to the internet needs to be strongly concerned about security!
But especially desktop linux.. every random bash script could encrypt your documents, or leak out your browser cache, do whatever it wants..
Though that makes non-memory safe code more reliable in the case of a bit flip. (this is not a serious advantage - only some bit flips can be prevented this way)
It didn't on its own, but it is worth noting that with type-safe languages, you can protect yourself from this by encoding that invariant into the type system.
Using Rust as an example, take a &std::path::Path (or &camino::Utf8Path or whatever) in your public API; have custom InternalPathBuf and InternalPath types that perform validation to ensure they aren't using relative paths to "break out" during construction, and then pass those around in your internal API. Bingo bango, now there's no way (short of transmuting, an `unsafe` operation) to pass invalid paths to the functions that hit the filesystem without a compile error. No redundant runtime checks required, and no need for you as the developer to keep track of which codepaths have already validated a Path and which haven't.
I'm sure you already know this, and I would imagine that Java can do the same, but it's a big step above languages like Python where you can do whatever you want to anything you want.
EDIT: lol while I was typing this you made a post about the same thing below.
I'm still thinking about how we could integrate something like that in a language or the languages package manager. I'm unsure if it's possible.
> which makes it easier for developers to compartmentalize code to achieve memory-safety
The problem here is that this is incomplete. Many many many languages have achieved this before Rust. Where Rust is (somewhat although not entirely) unique is bringing this compartmentalization into a context that (mostly) lacks a runtime and garbage collection.
I have no problems calling Rust a "memory safe language" precisely because I have no problems calling Java or Python "memory safe languages." What matters isn't whether the language is "entirely" memory safe. What matters is what its default is. C and C++ are by default unsafe everywhere. Rust, Java, Python and many others are all safe by default everywhere. This notion is, IMO, synonymous with the more pithy "memory safe language."
This isn't possible. Eventually you are sitting at a block of memory and need to write the allocator. Maybe (like python) your allocator is written in C and you hide it, but there is always something that isn't memory safe sitting under your language.
You could write a language for an actual Turing machine which since it has infinite memory is by definition memory safe. However as soon as you need to run on real hardware you have to work with something unsafe.
You can of course prove a memory allocator is correct, but it would still have to use unsafe in rust. I supposed you could them implement this alloator in hardware, and make rust use that - but since this doesn't seem like it will happen I'm going with all languages have unsafe somewhere at the bottom.
Yep, ctypes is part of the stdlib and lets you corrupt the VM on the fly. Fun stuff like changing the value of cached integers and everything.
But ctypes being a terrifying pain in the ass, people tread very carefully around it. Cffi’s a lot better though it requires an external package. At the end of the day I think I’d be more enclined to bind through pyo3 or cython than write C in python (which is what ctypes has you do without even what little type system C has, to say nothing of -Wall -Weverything).
The JVM has well-defined bad execution as well, e.g. data racing is well-defined. Safe Rust does prevent data races statically, but if they do happen due to a bad unsafe block, you are entirely on your own. While memory safety can abruptly stop both processes, FFI is very rare in Java, it is an almost completely pure platform being Java all the ways down, so in my experience the former is safer from this aspect.
Playing devil's advocate, I can think of at least one language which has no escape hatches: Javascript running within a web page.
I think it's fair to call Rust a memory safe language. But I don't think it's on the same tier as a fully managed language like python.
Whatever can be compiled to BPF meets this requirement. The price though is that it wouldn't be very useful.
No language can prevent a person from allocating a writable buffer, then reusing it without cleaning it. Do that on a server, and you have step 1 to a security vulnerability.
If requests to allocate memory come faster than the garbage can be collected.
Or a data container holding many/large references that will never be used. The difference between that and a lost pointer in C are moot in a practical sense.
All of these _can_ be prevented. But it's programmer care, rather than the language, that prevents them. Hence, the term "memory safe" is inaccurate. "Memory safer" would be more accurate, but far less catchy.
I think this has always been the goal, but it wasn't obvious at the outset that it would be achievable. The fact that we now have empirical evidence in real shipping products is significant.
But i am completely baffled by arguments that count number of unsafe blocks or code lines. Like this:
>the number of unsafe sections is a small fraction of the total code size
Code execution combinatorial effects makes number of sections or code size completely useless metrics to judge security. They do help mechanical part of auditing security in sense that they help to locate things. But locating things was never enough to judge if security is there.
- great standard library, especially all the iter methods. having 'obscure' stuff like `try_for_each` just makes me so happy as a dev
- unit tests built into the lang
- tooling is great
- docs are top notch
The memory safety aspect is... sometimes helpful, sometimes irritating. I prefer zig solution (BYO allocator, special one for testing that reports errors) over rusts, which simplifies a lot of stuff and lets you make cyclical data structures without a lot of hoop jumping.
However, I appreciate that Rust tries to achieve safety through improving program correctness, not merely crashing sooner.
Of course Rust has run-time panics (hasn't solved the halting problem yet), but it also has many patterns catching problems at compile-time. For example, a hardened allocator can detect use-after-free bugs when they happen, but borrow checking can prevent them from existing in the code in the first place.
That was my concern that I had when I started learning the language. I think it is true, but I was surprised how quickly I managed to get used to the Rust way.
Of course, that's just "often," not nearly "always." There are many valid programs that the borrow checker struggles with, and in those cases, the "Rust way" is just needlessly convoluted. There are many problems for which the most common answer is "just store all this data in a list and use list indices like pointers." (Thankfully there has been a lot of progress on a new borrow checker that's less easily startled.)
I mean I've improved but I still have a lot of "wtf" moments. End up doing a lot of deep copying and heap allocations just to shut the compiler up, which makes me question just how "zero cost" the safety is.
It's because Rust hits the spot for MANY different domains and people. System programmers, functional programmers, backend, db engineers, GUI, devs from the formal verification/mission critical camp, OS devs, graphics and even frontend with WASM.
For me personally, the thing I miss in Rust is better const fn/comptime/metaprogramming (like in C++). Without them, I find writing generic high-perf data structures quite tedious (and proc macros just aren't a suitable replacement for generics)
- It has the best parts of C (code generation is predictable, no mandatory extra thread for GC or similar, interoperates very well with C code)
- It also has some of the niceties that were popularized after C (type inference, an equivalent of unions that isn't terrible, macros that are not terrible, functional features)
- The thread safety stuff. Async has issues, but the core thread safety constructs (send, sync, mutex vs atomic, etc) are just so well designed that rust is by far my favorite language for writing synchronous, shared-memory threaded code. It's quite possible to mess it up, but it's far easier to keep that system in my head than any comparable one that I've used. Of course shared-nothing is even easier, and rust lets you do that too!
I don't use it for everything, but when I do encounter a thing rust is good at, it's just a treat.
traverse_ :: Foldable t => (a -> ExceptT e IO b) -> t a -> ExceptT e IO ()
Of course I'm not saying Rust should have this (there are good reasons why this isn't a good fit for Rust, see http://smallcultfollowing.com/babysteps/blog/2016/11/09/asso...) but it really caught my eye that you called `try_for_each` obscure; it could have been an everyday function if it had a bit more expressiveness.And it's possible the lack of higher kinded types, forcing reimplementation, actually gave the opportunity to look for frindlier names.
There are some ways to get around it, by simulation and using ‘as’ but it isn’t particularly safe.
No experience with haskell - sometimes I try and learn it and give up when stack complains about version conflicts - but regardless I try not to get too many hangups about functions not being super generic, just that they are there when I need them.
and
> As we noted in the original announcement, our goal is not to convert existing C/C++ to Rust, but rather to shift development of new code to memory safe languages over time.
For those working on C/C++ code bases, how does the incremental addition of Rust work in practice? What strategies and tools come in handy? Also, what are some good case studies where Rust was introduced to add new features, but still needed to work within a system mainly composed of C/C++? I've seen some of the first steps with Linux, but I'm thinking of a project where more substantial additions have been made.
Many informal rules of C libraries like: "don't call read() after close()", "pointer must never be null", or "keep this data alive for as long as the handle is in use" in Rust can be expressed using the type system, and enforced at compile time. Cleanup can be automated. This catches bugs in user code and shields the library form misuse.
An informal rule would be “don’t use gets” before it was deprecated, or “don’t use the str* functions”, or “don’t pass a user-provided format to printf”.
The most famous example of that is AFAIK Firefox. There's a (perhaps outdated) list at https://wiki.mozilla.org/Oxidation#Rust_Components of places where Rust was used to replace some component in Firefox; the most famous of these are probably the CSS style calculation which came from the Servo project (https://hacks.mozilla.org/2017/08/inside-a-super-fast-css-en...), and a renderer also from the Servo project (https://hacks.mozilla.org/2017/10/the-whole-web-at-maximum-f...).
Brave is definitely not aiming to convert the entire browser to Rust, but it's increasingly chosen for new development.
[1] https://cxx.rs/
I can tell you that bad programmers can write bad code in Rust.
Of course. The question rust users seem to put forth is that bad programmers write _better_ (not good) rust code than C code.
That bad programmers write bad code is to expected. That is, after all, a likely explanation for why they're bad.
Rust has no null/nil pointers. Instead, it has nullable types (Option<T>), which are harder to misuse. If you want to "dereference" a Option, you either use unwrap() (which panics) or you handle the None case properly. While `.unwrap().foo()` is still just as crashy as an unguarded `x->foo()` in other languages, a code review can catch misuse of .unwrap() much more readily than a missing null/nil check.
As another example, the Send/Sync traits provide strong guarantees about thread safety; using these traits properly lets you make data structures that cannot be misused in a multithreaded program. Although deadlock is still possible (hello, halting problem), many types of data races are simply eliminated.
Perhaps this is an obvious point, but I found it interesting .
This probably also applies to the Linux kernal work in Rust too; if only new device drivers get written in Rust and the core remains C, it could still be a major win for kernel security.
> how does the incremental addition of Rust work in practice?
Probably a good starting point: https://firefox-source-docs.mozilla.org/writing-rust-code/cp...
I think folks who write languages should have a typographer on their team because something like this:
use std::collections::HashMap
Is a typographic nightmare. While I understand “form follows function”, it’s tough to be excited to program in something like this.
Dot is way better
It’s the difference that makes the difference between Rust-like and C++-like gibberish and poetry.
But that use statement is not a good example of it, and if that's the biggest criticism then Rust is faring fantastically well.
https://www.doverbooks.co.uk/point-and-line-to-plane
Consider h::i::j::k versus h.i.j.k
Two :’s is an extremely loud combination of visual elements compared to the subtle point. :: drags the eye away from the content and says “look at me oscillate”
In addition, humans group similar visual elements together so a combination of anything::doesnt::matter::what::between::clumps it is impossible to escape the common pattern and the eye jumps between the ::’s. Therefore it takes double the cognitive load to read.
What’s worse, the eye gets trapped within each :: because it’s a combination of four dots, which naturally creates an implied circular pattern which draws the viewer in further.
Compare to something like: use HashMap from std.collections
Or… more obviously the python import statements.
https://dwrensha.github.io/capnproto-rust/2022/11/30/out_of_...
Another explanation is that fuzzing is generally expensive and it's easier to focus on unsafe parts of Rust programs than whole C++ programs.
That said, there are a ton of ways that auditing for vulnerabilities is just as easy or way easier. In particular, most tooling for C/C++ can be applied to rust - fuzzers and sanitizers, for example. Additionally, one only has to "grep for unsafe" and work from there to find Rust vulns, which largely amounts to "what are the assertions for this unsafe block, are they complete, are they held?".
Most of the graphs here are about new code.
[1]: https://security.googleblog.com/2021/04/rust-in-android-plat...
> As Android migrates away from C/C++ to Java/Kotlin/Rust, we expect the number of memory safety vulnerabilities to continue to fall. Here’s to a future where memory corruption bugs on Android are rare!
(Not that it's easy to tell from the pie chart, which colors one orange and the other red, in similar shades. Do better, guys.)
To meet the goals of improving security, stability, and quality Android-wide, we need to be able to use Rust anywhere in the codebase that native code is required. We’re implementing userspace HALs in Rust. We’re adding support for Rust in Trusted Applications. We’ve migrated VM firmware in the Android Virtualization Framework to Rust.
With support for Rust landing in Linux 6.1 we’re excited to bring memory-safety to the kernel, starting with kernel drivers."
The push for Rust to replace C and C++ continues.
This is confirmation of the NSA recommendation to discontinue using C and C++:
https://media.defense.gov/2022/Nov/10/2003112742/-1/-1/0/CSI...
If you do not know Rust, now is the time to learn:
https://doc.rust-lang.org/book/
Here are some fun holiday-themed exercises to learn with:
I plan on doing Advent of Code in Rust this year.
The article states:
"We continue to invest in tools to improve the safety of our C/C++. ... Vulnerabilities found using these tools contributed both to prevention of vulnerabilities in new code as well as vulnerabilities found in old code that are included in the above evaluation."
"These are important tools, and critically important for our C/C++ code. However, these alone do not account for the large shift in vulnerabilities that we’re seeing, and other projects that have deployed these technologies have not seen a major shift in their vulnerability composition. We believe Android’s ongoing shift from memory-unsafe to memory-safe languages is a major factor."
"our Rust code is proving to be significantly safer than pure C/C++ implementations."
C++ is great if you do not have alternatives.
If you can use Rust instead of C / C++, you should because of the greater safety it offers with similar performance characteristics.
Nice, I'm doing it in chatGPT this year [0].
Many of the higher level constructs are then in Java/Kotlin, though, like the builtin apps, system ui, activity & window managers, etc...
I was very enthusiastic about Rust about 4 years ago but decided to learn Swift instead as a new “cool non-Lisp language” to learn. Seeing an recent article on writing Python in Rust made me wish that I had chosen differently.
I found this article made me feel better about security. I expect that increasing use of memory safe languages will lock down public infrastructure and software, making everyone safer.
When comparing the safety of Swift and Rust, it is important to note that both languages employ strict type systems and compile-time checks to prevent common memory-related bugs such as buffer overflows and access violations. However, the way they handle memory safety in multi-threaded environments differs.
In Swift, memory is managed using automatic reference counting (ARC), which tracks and manages the lifetime of objects in order to prevent memory leaks. However, ARC is only effective in single-threaded environments. In a multi-threaded environment, multiple threads can access the same memory simultaneously, which can lead to race conditions and other memory-related issues. In order to avoid these problems in a multi-threaded Swift environment, developers must use synchronization techniques such as locks or atomic operations to ensure that memory is accessed in a safe and predictable way.
Rust, on the other hand, uses a borrowing and ownership model to ensure memory safety in both single-threaded and multi-threaded environments. In this model, any value in Rust has a single owner, and the owner is responsible for managing the value's lifetime. When a value is borrowed, the borrower is given a temporary, read-only view of the value, and the original owner continues to be responsible for managing the value's lifetime. This ensures that memory is always accessed in a safe and predictable way, even in a multi-threaded environment.
Overall, both Swift and Rust offer strong guarantees of memory safety, but Rust's borrowing and ownership model may provide better guarantees in a multi-threaded environment.
I hope this helps to clear up any confusion.
I’m not looking for an explanation; I understand the theory. I’m just not super familiar with Swift — I’m looking for an example program that has a (potential) data race which leads to memory y safety.
Memory safety, oh so sweet
Reducing vulnerabilities, a feat
Google switches to Rust
Security improved, a must
Memory corruption, a thing of the past
Safe coding, a task at last
I don't need to program in an environment where a systems programming language is required, so for me a languages debugability and introspective capabilities are the most important. So far I think Pharo hits the sweet spot for me, but it still has a long way to go documentation wise before I think it will see any sort of adoption. I'm rooting for it though.
As someone who has been in the Rust community since a couple of months after 1.0, I only see growth, year after year. At the start the community was small. Nowadays even the OSS part of it, which is a subset of the total community, is so big you can't have an overview of it any more. Even for the Rust project itself it's hard to have an overview over everything that's happening (but it's still possible to some degree).
crates.io downloads keep growing exponentially, although recently growth rate dipped from 2× to 1.9× (not sure if that's a trend or noise). Ratio of weekday to weekend downloads keeps going up, so presumably professional adoption of Rust keeps growing.
Something like Rust which can ahead of time verify that these issues aren't present is a better solution imo. Maybe then we can use this as a last resort check that the usages of unsafe didn't cause issues.
They were warned many years ago about ownership/concurrency/compile speed, they didn't listen at all
A vision alone doesn't matter, you need skilled engineers and a dedicated team who understand what "taste" for great things is
What could have been the Swift for android will end up just being the "java" alternative, i suspect they'll get rid of the JVM, or whatever the tech is, altogether and focus on Rust for whatever they plan next (maybe Fuschia), maybe there is still hope for Swift, we'll see
It would require rearchitecting everything to work with separate processes and IPC, and that’s got some overhead(s).
It also has memory safety issues around concurrency, and its limited allowance for abstractions makes papering over those complicated.
In Rust, overflow is not undefined behavior (neither signed nor unsigned). Today, arithmetic wraps in release mode (panics in debug mode), but it may panic in release mode in the future.
The other point is that, since overflow wraps, that may indeed result in logic bugs. And in theory that logic bug could be used to lead to exploit, such as a buffer overrun. But Rust uses bounds checking by default everywhere, so the worst case you'll usually end up with here is a panic or a DoS vulnerability. Not great, but probably preferable to other types of vulns that grant access to sensitive data.
So I think two things would need to happen, at minimum, to get a non-DoS vulnerability here. You'd need to find a bug that caused arithmetic to overflow where it otherwise shouldn't, and you need to find some way to connect that to an explicitly `unsafe` unchecked access into memory.
Also Rust allows enabling overflow checking in release, it’s a perfectly valid configuration.
Yes, it's particularly a dangerous problem when doing FFI. Eg you have a `data: &[u8]` and you need to call `extern "C" fn foo(data: *const u8` and `data_len_in_bits: usize)`, you could write `data.len() * 8` for the second parameter and Rust wouldn't stop you.
It's also annoying that the only way to do checked arithmetic is replace all the simple arithmetic operators with `.checked_*()?` function calls. libstd doesn't have a `std::num::Checked<T>` like it has `Wrapping` that would implement all the arithmetic traits in terms of `checked_*` and return `Result<>`. But at least it's not hard to do yourself. ( https://github.com/Arnavion/terminal/blob/475d917377eea43b52... )
https://android.googlesource.com/platform/build/soong/+/refs...
Not an expert, but a file named "global.go" makes me confident :).
https://doc.rust-lang.org/std/primitive.u32.html#method.chec...
So this is not an issue at all.
For comparison, in Swift normal arithmetic operations check for overflow.
[1] https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1773
Until "the nukes are on our side", I don't think this should be celebrated or praised.
If the Rust community can be insufferable when trying to sell Rust at any and every opportunity, Lord have mercy when they see any kind of success because the preening and puffing will have no end. This blog post will live forever in the annals of Rust.
On the other hand I’m not surprised to see that it’s written by the security team and not a development team. Same pattern as with Microsoft: security specialists tend to get obsessed by their subject matter (just like many Rust programmers), end up hating C and C++ and see them as the source of all problems (just like many Rust programmers).
In reality, C and C++ were the saviors of Android and Google reluctantly had to conjure the NDK to make up for a severe lack of performance compared to the iPhone. Note how even in the current Android they mention improving the UI performance and having less “jank”. Without C++ Android would have been DoA, but it doesn’t look like there will be a blog post thanking C++ any time soon :-)
I can’t take seriously reports about the benefits of a tool that don’t mention any of the downsides. When the devs post a blog cursing the troubles they had getting Java and C++ and Rust to work together and pitying themselves for having to read both C++ and Rust, then we’ll be getting closer to the truth.
What should they do instead, write an eulogy to C++?
They should have the dev teams write about the good, the bad and the ugly of using Rust instead of having the security team write a sanitized rainbows and sunshine story.
As an Android developer though, I have to be the one bitter old man yelling at cloud. I was spoiled by Java and Kotlin to the point where I cannot look at Rust and think it's a nice modern language.
Yes, I will start a language war today. Rust is like a truck driver who tried to make a race car that doesn't blow up. It's safe but it does not look refined. I wish you knew how weird Rust looks to me. I tried to learn it 3 times and had to give up after all the WTFs. I said it in the past, and I'll say it again:
* What the hell kind of language choice is to force everyone to type "#[derive(Debug)]" for annotations? I'd rather write past the end of an array and have someone steal my Bitcoin wallet than press "shift 3 bracket shift 9 shift 0 bracket" at the top of my structs. What's wrong with @? Nothing. @derive(debug). 2java4u? Ok, [derive debug] then.
* What's with the ' everywhere? Not the quote, the piece of dirt on your display. Why are our displays so dirty?
* Going for super short keywords "let", "fn", "mod", but then, "let mut" could have been "var". When is typing speed the bottleneck in writing software where you can't take the time to type out "module" or even 'function'? Come on now.
* print! now! fast! it's! a! macro! why! are! we! yelling!
* Passing "self" as the first argument was bullshit in Python, and it's bullshit in Rust too. Don't look at me like that - the compiler can inject it as the first parameter without requiring you to type it in.
* What does "::" do that "." can't? That's right. Nothing. All hail D.
D got language design right. Syntax better than Rust. CTFE better than Rust. Templates better than Rust. Marketing worse than Rust, though.
I'll try to learn Rust a 4th time now to stay relevant in the Android world, because I have bills to pay, but I want you to know that I blame each and everyone of you weirdos for not holding language designers to a higher bar.
Edit: if you downvote, reply with a link to the last compiler you wrote.
The aesthetics of syntax is a personal matter, but when the critique of a language focuses exclusively on its syntax, it tells me that the critique is skin deep. Semantics are way more important to what code "feels" like to write.
Why not @derive? @ was a reserved token for something else before 1.0 and today is still used in patterns. Now it's too late to change.
The ' lifetime syntax was borrowed from another language. Some way of differentiating types and lifetimes is necessary, ' is not any worse than most others we could have chosen.
We try to make things that are common and safe terse, and things that are uncommon and potentially problematic more verbose. ? is common and safe, .unwrap() is less common and potentially problematic. Mutable bindings are not exactly unidiomatic, but mildly discouraged.
println! is a macro because it 1) is a compiler intrinsic to do compile time magic like the recent addition of capturing bindings directly in the formatting string and 2) it takes a variable number of arguments. Differentiating between macros and function calls is important if you want to get a sense for what the code you're reading can do. You can choose another way of differentiating them, but whatever you choose will be subjective and has to mesh well with the rest of the language.
Explicit self makes it easy syntax to differentiate between associated functions (part of the type) and methods (part of the instance), while also making very clear when you're accessing the current instance's data. And because Rust cares about mutability and ownership, you still need to communicate the differences between self, &self and &mut self. It also provides syntactic space for arbitrary self types: fn foo(self: Pin<&mut Self>)
> press "shift 3 bracket shift 9 shift 0 bracket" at the top of my structs
Just use an IDE and you can press alt+enter. Same thing you do in Java when writing getters and setters for your AbstractFactoryBeans.
> "let mut" could have been "var"
The "mut" does not belong to the "let", it belongs to the variable name.
let (read_only, mut read_write) = (1, 2);
> Passing "self" as the first argument was bullshitExplicit is better than implicit. I quite like the names in the argument list to match the set of names available in the function, rather than having an extra keyword (`static`) that you add to remove a function parameter.
Not only that, but in Rust it actually has a meaning. Self can be &self or &mut self, which impacts the calling conventions.
The alternative would be fully typing anything but owned method calls which would just not have a self parameter, which would be incredibly weird.
It also shows that as in Python (and really even more so) "methods" are little more than syntactic sugar for functions. It would also require a new and separate syntax to declare non-instance methods.
Nope, that would be a static function on your struct. By using self you let the compiler know that you want to use an instance function.
Rust could have taken the C++ route here: `fn static foo()`, `fn foo()`, `fn mut foo()`, `fn &mut foo()`, etc. but I feel like the explicit `self` is very clear and easy to understand.
`fn Box foo()`? `fn Arc foo()`? It also requires more parser lookahead.
The `mut` case is also very odd, as it's not part of the function API (it just configures the binding of the internal local). Plus if self was implicit it likely would need to be a keyword, so that wouldn't be a usecase at all anymore.
I prefer an explicit `this` or `self` being passed, so that I know where it's defined. Something close enough, Kotlin uses `it` in lambdas. If you're nesting your lambdas, it can be tricky to review the code when just staring at it (when the IDE isn't helping you with types).
impl Foo {
// static
fn foo() {}
}
impl Foo {
// instance, owned
fn foo(self) {}
}
impl Foo {
// instance, borrowed
fn foo(&self) {}
}
impl Foo {
// instance, boxed
fn foo(self: Box<Self>) {}
}
impl Foo {
// instance, refcounted
fn foo(self: Rc<Self>) {}
}When I choose languages, I choose them based on semantics, tooling, community/ecosystem, UX, and then maybe syntax
I really dislike both the semantics and syntax of python. However, the scientific computing libraries (pandas, numpy, scipy, scikit-learn, matplotlib, seaborn, etc) are just too productive to turn away from for quick data analysis tasks. If these libraries didn't exist, I wouldn't touch python with a 500-foot pole.
Lamborghini originally made tractors.
Don't have anything against Rust though, except the syntax can be a bit obtuse.
let mut line = String::new();
stdin().read_line(&mut line)?;
println!("input: {}", line);
I suspect that there _have_ been some changes since you last looked - for example, the ? operator lets you propagate errors in a more compact way. let mut line = String::new();
stdin().read_line(&mut line)?;
This is what I'm talking about. This is so ugly and clunky and needlessly verbose like Java compared to C++ where you can do std::string input;
std::cin >> input;
and have it Just Work. Why can't Rust do something similar?this post have nothing to do with writing apps for android. They are talking about developing the android system itself. They are writing new system code in Rust instead of C++. Userspace code is still enoraged to be written in Kotlin.
edit2: wow mods hard at work, already removed one dissenting post.
How is any language supposed to grow if you're only allowed to use it once everybody does? Somebody has to be first (and google isn't, not by a long shot)
It sounds like you didn't read the blog post. The whole point is that they are not rewriting code, but writing new code in memory-safe languages (including "niche" languages like Java). This strategy is paying off with fewer severe vulnerabilities due to memory safety bugs.
where did you get the impression they are not rewriting code in rust? because the author cited some other blog post saying they should focus on new code and not rewriting it? How does that translate to "The whole point is that they are not rewriting code," ???
Obviously they're going to be rewriting whatever they see fit. If YOU actually read the article you would have seen they have "keystore2" listed as new rust code. I WONDER what was keystore1 implemented in? Nice try, but no cookie.
Yes, one is named "keystore2" but you don't seem to actually know anything about it (nor do I). It seems doubtful to me that they would rewrite a perfectly working component in Rust just for fun. Most likely the original keystore, whatever language it was written in, was not meeting its requirements and needed to be replaced.
Some people are posting the article around the Internet as evidence that Rust solved security. Instead, there are many other memory safe languages around and there has been thousands in the past. Additionally, many security issues are not due to memory safety. Please keep that in mind when making comparisons.
EDIT: of course, 2 minutes and I'm downvoted down to -2
Yes, and in fact they write about how they are replacing C/C++ with Kotlin or Java. All three are memory safe languages. But Rust is the only low level language of the three. This is Rust's killer feature. Of course, JavaScript is memory safe and so is Lua. But they are high level languages.
> Additionally, many security issues are not due to memory safety.
I think it depends on the domain the program is in. If you are a program managing some security property, like e.g. TLS encryption, then virtually any bug you have might be a security issue. Same goes for OS kernels. But if you are e.g. an image decoder library, then there is little security impact if your output is a weirdly colored image. But memory safety issues might still be a problem for your decoder library.
Overall the number being cited is 70/30, as in, 70% of security issues are memory safety ones, and 30% are ones which are not about memory safety.
https://www.zdnet.com/article/microsoft-70-percent-of-all-se...
So you can reduce the number of security issues by 70%, isn't that great?
> Some people are posting the article around the Internet as evidence that Rust solved security.
OK, so show me. Let's see all these people declaring that this is "evidence that Rust solved security."
I think it's far more likely that you're exaggerating what folks are saying to make them appear far more unreasonable than they actually are. But we can't know that unless you actually show your work, now can we?
That doesn't make you a martyr.
- D, Nim: neither provide strong memory safety guarantees. D has a safe subset, but it's not default (see https://news.ycombinator.com/item?id=12391720). Nim allows you to turn checks off at runtime. Both Nim and D generally use a GC.
- Java/Kotlin are not low-level: requires GC, and not often used for low-level systems programming. Great languages, but different niche.
And even in those toy level benchmarks (like https://benchmarksgame-team.pages.debian.net/benchmarksgame/... ), there's a clear divide between C/C++/Rust & everything else.
- https://www.infoq.com/news/2021/11/rudra-rust-safety/
- https://cve.report/vendor/rust-lang
And you can find online similar links and research on the topic.
All it takes is that you use that specific piece of code at the wrong time, and that’s it: your system which you once believed to be safe is not anymore safe. And you know what? You don’t even know what a sanitizer is, because they told you that Rust is a memory safe language and you don’t need anything else than the rust compiler - this is how I find 99% of today’s articles about Rust.
Sure, today being Rust less used than C/C++ will clearly show less CVEs.
The question is … once it’s in the wild (and by this I mean “major” libs or serious shit done in Rust) how can you prevent such bugs without a runtime sanitizer?
Beware that such CVEs can affect Rust Standard library as well, not just an unknown library.
Again, there is no way of escaping bad programming and bad practices, no matter which language you use. Someone might argue that in Python or Java you can still do bad stuff, however, the likelihood is way lower, especially because most of your Java libraries will very likely be written in Java - unless you know it’s using JNI under the hood etc.
It is - as long as you don't use unsafe. Which is very rare, so we've made huge progress here already. Validation for cases where unsafe is necessary is needed and welcomed, but doesn't change the fact that 99% safe Rust is much better than 100% unsafe C/C++.
> Again, there is no way of escaping bad programming and bad practices, no matter which language you use.
Escape entirely maybe not. Eliminate most of it - definitely.
That's what I tried to show in the previous post: it's just not true, because if you rely even on an unsafe function from the standard library affected by a CVE, you're just fucked as if it was in C, C++ or other languages. The only difference is that you don't know what's happening under the hood and you feel "safe" because that's how they sold the language to you. Until you get hacked and "hey we didn't know...".
You just use that "unsafe zip/unzip" function you find in the docs, and with maybe with the wrong input (a weird filename or so) it happens to create undefined behavior that opens up the door to vulnerabilities.
I really believe that Rust, Swift and lots of new[er] programming languages improve in terms of memory safety (at least on the high level), however, we need to admit that they are being sold for what they are not -> memory safe. When I read memory safe it means that it cannot happen at all, and therefore I don't have to think about that kind of stuff when I write a program.
It'd be more honest to say: it's memory safe until:
- you use unsafe
- the libs you rely on use unsafe (and go figure once you start to pull a lib that pulls another lib etc.)
- the standard library functions you use use unsafe
It's an important remark, because the next generations of programmers will build programs based on a false assumption - that they don't have to worry about certain types of errors, while it's just not true.
EDIT: maybe it's just my definition of memory safe too "strict", not sure. Memory safe to me means -> it just can't happen. That's it.
I'd suggest rethinking this definition. You are always at the mercy of the lower-levels of your system, both in the runtime and the compiler. By this definition, nothing is memory-safe, since it is possible for your code in a "memory safe" language to encounter memory-safety issues in its runtime or the operating system.
Memory-safe means the bug won't happen in YOUR CODE. If your safe Rust code calls a library that uses unsafe incorrectly, yes you can encounter a memory-safety issue. But the memory safety bug is in the library, not your code. It is even possible to encounter a memory-safety issue in Rust if you never use unsafe, but in that case the memory safety bug is in the Rust compiler, not your code.
And this is really the only meaning for "memory safe" that can apply to anything that runs on real world hardware and operating systems. It's always conditional on the correctness of the compiler checks, the runtime, and in Rust the unsafe blocks.
An important factor here is that, because this scheme makes the trusted/human-verified part of the codebase a bit more extensible than usual, a lot of things that would typically live in the compiler or runtime get moved into libraries, just as a matter of flexibility and architecture.
So as long as people understand that these guarantees are conditional on the correctness of that trusted code, "memory safe" is a pretty reasonable name for what's going on. And I don't think people really expect to be immune to bugs in their compiler or runtime just because the language is "safe"!
I've never needed to use unsafe in my Rust applications, which means that my code is 100% memory safe (by Rust definition of course). I expect libraries I am using to provide safe abstractions over unsafe, if there is any there. Sure, there were bugs (including Rust stdlib), but such small scale effectively means that this problems disappeared comparing to languages that aren't safe and that means all I need to do is maybe update some dependency once a year. It's that rare, so I will call it safe and solved problem. We can move to next one (and there are many).
> It'd be more honest to say: it's memory safe until:
Which is what most Rust introductions I've seen will say. I don't think anyone misunderstood this part.
> It could appear that these results undermine the belief that Rust safety model represents an improvement over other languages, e.g. C++, but this would not be correct, say the researchers behind Rudra, who still consider Rust safety a supreme improvement.
They found ~100 security issues in 45k packages. That's clearly better than C++.
Does Rust provide a way to check if you’re using unsafe code? What if I want to disable that? If I need to make a mission critical software I need to be aware of what I am deploying. If on the other hand we want Rust to be the new JS for backend, then yes so be it, we improved over c++, well done.
You… almost literally did?
> I am happy that we are moving towards a future where there are less memory bugs, but… are we really?
Note that the half Rust would prevent tends to be less impactful, still a CVE, but the exploit is less impactful to end users.
They found 250 bugs after analyzing the entirety of rust and all of it's packages.
There are probably more memory safety bugs in the python standard library and top 50k packages.
Essentially, the Rust standard is that more or less every line of the C++ standard is a CVE.
Hell, the Rust project releases CVE for things other languages literally just shrug about e.g. https://blog.rust-lang.org/2022/01/20/cve-2022-21658.html
The C++ people just go "lol nothing in std::filesystem is safe we don't give a shit". The spec pretty much says it's UB to have other programs interact with the filesystem: http://eel.is/c++draft/fs.race.behavior#1.sentence-2
That said things that happen in the language or standard libraries like the one you linked, are often (but not always!) filed by the project.