515 points · by Morgawr · 12y ago · 302 comments
For connoisseurs of bogus conspiracy theories, it's worth noting that the coding flaw that produced the bug is much more subtle than "goto fail", but the bug is equally simplistic. Where "goto fail" required a duplicate line, GnuTLS required only a single switched token; not only that, but the bug comes from a mismatch between two common C error checking regimes (a zero-return error and a negative-return error).
I think what I like least about the bug is that it was found by the GnuTLS maintainer, long after the code shipped. That's a signal of how much attention GnuTLS gets.
It's a signal of how much attention the dark and dusty corners of all open source code gets. My "favourite" FreeBSD advisory was the 2011 telnetd "christmas present" -- remote root to any system running telnetd with the default options. The bug was in routines for setting up encrypted telnet sessions... who even knew that telnet had encryption? The bug was a blindingly obvious buffer overflow, but nobody goes digging through telnetd looking for encryption code.
About six months after that advisory, I heard from a major aircraft manufacturer that they had been using the BSD telnetd code to provide a channel for in-flight tuning of engine performance.
This is why I award bug bounties for punctuation errors in comments in the Tarsnap source code -- it encourages people to read all the code, not just the interesting bits.
I did. Most of the ftp, telnet, rsh, etc. utilities shipped with BSD and Linux had Kerberos and encryption support. I also suspect that these had at least wider use in larger environments than many people knew, because before OpenSSH had Kerberos support, you could integrate encryption and authentication in useful ways.
http://www.openldap.org/lists/openldap-devel/200802/msg00072...
https://en.wikipedia.org/wiki/Linus's_Law
Linus's Law as described by Raymond is a claim about software development, named in honor of Linus Torvalds and formulated by Raymond in his essay and book "The Cathedral and the Bazaar" (1999). The law states that "given enough eyeballs, all bugs are shallow"; or more formally: "Given a large enough beta-tester and co-developer base, almost every problem will be characterized quickly and the fix will be obvious to someone." Presenting the code to multiple developers with the purpose of reaching consensus about its acceptance is a simple form of software reviewing. Researchers and practitioners have repeatedly shown the effectiveness of various types of reviewing process in finding bugs and security issues, and also that reviews may be more efficient than testing.
In Facts and Fallacies about Software Engineering, Robert Glass refers to the law as a "mantra" of the open source movement, but calls it a fallacy due to the lack of supporting evidence and because research has indicated that the rate at which additional bugs are uncovered does not scale linearly with the number of reviewers; rather, there is a small maximum number of useful reviewers, between two and four, and additional reviewers above this number uncover bugs at a much lower rate. While closed-source practitioners also promote stringent, independent code analysis during a software project's development, they focus on in-depth review by a few and not primarily the number of "eyeballs".
I think that people who argue over Raymond's quip are just being pedants. It's true that not all bugs will be shallow, no matter how many eyes are on software, but I don't think the expression was meant to be taken literally.
great_success = sum([i.debug_skill * log(i.audit_time) for i in code_reviewers]) My favorite part of the "many eyes" argument is how few bugs
were found by the two eyes of Eric (the originator of the
statement). All the many eyes are apparently attached to a
lot of hands that type lots of words about many eyes, and
never actually audit code.I mean shit, I don't need to be an aeronautical engineer or work in the FAA to say that several people investigating an airliner crash will be more effective than one single dude sifting through a literal field of debris.
ESR's quote isn't wrong (perhaps hyperbolic, but in spirit it isn't wrong). It's just an uninteresting observation. What do you do when something has you stumped at work? You ask the guy across the hall to look over your shoulder for a second... It's just common sense.
People simultaneously revere and hate the quote only because ESR said it. If Joe Shmoe had said it all those years ago, it would have just been met with "no shit" and never given second thought.
The problem with ESR's view here is that it occurs in a more general essay on this matter come up with the idea that open source has the advantage because of eyeballs, distributed design and so forth. But you can only distribute design so far, and almost every successful open source project has a small design and engineering team.
This being said there are plenty of cases where I do in fact rely on many eyes. It's not that it makes the bugs shallower but that repetitive review and discussion helps to shake out both design flaws and software bugs. I tend to push a lot of security stuff to the underlying platform for this reason. But part of it is also trusting the design team.
Code auditing is tough work and I generally assume it doesn't get done. What is good however is that a lot of other people are depending on software that is professionally developed in a relatively transparent manner and so chances are somewhat better that people will audit the code at some point.
I don't personally know Theo De Raadt but if he spends his time bringing down other people, he's probably not a very happy person himself.
ESR is making a completely valid point, and the underlying premise of his theory---that having software open to review can help---is only confirmed by this incident, not rejected.
Specifically: If GnuTLS were closed source, this problem would likely never be publicly discovered and disclosed.
So overall, ESR's theory is accurate and useful.
Note the word "almost" in the theory, which serves as a (completely valid) escape hatch (that you are mistakenly neglecting) for incidents like this---which fit the underlying premise, but are "corner cases" rather than "common cases."
If it is open source, as in a Debian release, an end user's recourse is to fix it themselves.
If it is commercial, be it closed source or not, an end user's recourse is to sue the supplier (or something similar).
The commercial supplier has a financial incentive to get it right, the open source developer has an intellectual and street cred incentive to get it right. I'm not sure which one actually works better, I know that the popular opinion is the ESR eyeballs claim but it's not clear to me which gets it more correct. Seems like they both fail at times.
But this is anything but true. The reality is that code review is far less common than code use, with many defects impacting many users as the logical consequence.
There are always edge cases where beta testing and multiple eyes fall short of mathematical possibility [never mind sophisticated attacks]. That such a bug as this matters 17 years after Raymond made his remarks is a testimony to the robustness of the mechanism he described.
Unless you're talking about an IBM mainframe, validated at EAL 5, there are security bugs all over the place. With open source, you don't get a platoon of elves scanning the code, but you have a much better chance of someone happening across a defect or identifying the responsible party.
For all we know, bugs are found in closed sourced systems all of the time and are fixed frequently; the only difference is that they're not publicised.
And your tax dollars are paying for all of that work. And you can be sure those elves have known about those bugs for years.
And those bugs have caused many unfortunate consequences. So it's just not wise to go around giving people a false sense of security in order to promote your brand.
What a facetious and unsupported assertion you have made.
You are seemingly purposefully disingenuous.
The simple fact of the matter is, ESR is still right. Perhaps because few people use a piece of s/w these things slip through. The seriousness of this flaw is limited and thus not subject to the fierce post humous questioning you give it.
Please define how many eyes saw or used or benefited from this code. I certainly live in the world of this code and don't depend on it.
There is a chance you are talking shit.
ESR is not completely mistaken here, but the problem is that he's not exhaustively right with "Linus's Law".
It's more a description of why beta testing with access to source code is good, than a description of why open source is inherently good (and before you flip out, I've contributed to open source longer than I've done my day job).
Some types of code flaws will simply never show up to the kind of beta testing that introducing software to a wide population provides. E.g. proving that a X.509 certificate which is faulty in a certain way is actually caught by a software library; few people run into that in practice.
What these types of bugs require is code auditing (after the fact) or before-the-fact code review that prevents their entry into the source in the first place. But neither auditing nor pre-commit review are inherent to open-source, and in fact it could be argued that closed-source software companies are better able to ensure sure things happen.
The saving grace for open source is that these companies optimize for market success and not code quality (except to the bare extent needed for market success). Additionally you can pay to audit open source code much more easily than you can closed source (e.g. Google's audit teams that do exactly this).
But "bugs are shallow in the presence of sufficient eyeballs" is not unique to open source, either in theory or in practice.
Security vulnerabilities have never worked like that. This "nail" is not new.
Linus was directly aiming to maximize the number of person-hours thrown at debugging and development, even at the possible cost of instability in the code and user-base burnout if any serious bug proved intractable. Linus was behaving as though he believed something like this:
8. Given a large enough beta-tester and co-developer base, almost every problem will be characterized quickly and the fix obvious to someone.
Or, less formally, ``Given enough eyeballs, all bugs are shallow.'' I dub this: ``Linus's Law''.
My original formulation was that every problem ``will be transparent to somebody''. Linus demurred that the person who understands and fixes the problem is not necessarily or even usually the person who first characterizes it. ``Somebody finds the problem,'' he says, ``and somebody else understands it. And I'll go on record as saying that finding it is the bigger challenge.'' That correction is important; we'll see how in the next section, when we examine the practice of debugging in more detail. But the key point is that both parts of the process (finding and fixing) tend to happen rapidly.
In Linus's Law, I think, lies the core difference underlying the cathedral-builder and bazaar styles. In the cathedral-builder view of programming, bugs and development problems are tricky, insidious, deep phenomena. It takes months of scrutiny by a dedicated few to develop confidence that you've winkled them all out. Thus the long release intervals, and the inevitable disappointment when long-awaited releases are not perfect.
In the bazaar view, on the other hand, you assume that bugs are generally shallow phenomena—or, at least, that they turn shallow pretty quickly when exposed to a thousand eager co-developers pounding on every single new release. Accordingly you release often in order to get more corrections, and as a beneficial side effect you have less to lose if an occasional botch gets out the door.
And that's it. That's enough. If ``Linus's Law'' is false, then any system as complex as the Linux kernel, being hacked over by as many hands as the that kernel was, should at some point have collapsed under the weight of unforseen bad interactions and undiscovered ``deep'' bugs. If it's true, on the other hand, it is sufficient to explain Linux's relative lack of bugginess and its continuous uptimes spanning months or even years.
One can only conclude that either ESR is wrong (it wouldn't be the first time), or that ESR's beloved open source "bazaar" has become a cathedral.Linus was directly aiming to maximize the number of person-hours thrown at debugging and development, even at the possible cost of instability in the code and user-base burnout if any serious bug proved intractable. Linus was behaving as though he believed something like this:
8. Given a large enough beta-tester and co-developer base, almost every problem will be characterized quickly and the fix obvious to someone.
Or, less formally, ``Given enough eyeballs, all bugs are shallow.'' I dub this: ``Linus's Law''.
My original formulation was that every problem ``will be transparent to somebody''. Linus demurred that the person who understands and fixes the problem is not necessarily or even usually the person who first characterizes it. ``Somebody finds the problem,'' he says, ``and somebody else understands it. And I'll go on record as saying that finding it is the bigger challenge.'' That correction is important; we'll see how in the next section, when we examine the practice of debugging in more detail. But the key point is that both parts of the process (finding and fixing) tend to happen rapidly.
In Linus's Law, I think, lies the core difference underlying the cathedral-builder and bazaar styles. In the cathedral-builder view of programming, bugs and development problems are tricky, insidious, deep phenomena. It takes months of scrutiny by a dedicated few to develop confidence that you've winkled them all out. Thus the long release intervals, and the inevitable disappointment when long-awaited releases are not perfect.
In the bazaar view, on the other hand, you assume that bugs are generally shallow phenomena—or, at least, that they turn shallow pretty quickly when exposed to a thousand eager co-developers pounding on every single new release. Accordingly you release often in order to get more corrections, and as a beneficial side effect you have less to lose if an occasional botch gets out the door.
And that's it. That's enough. If ``Linus's Law'' is false, then any system as complex as the Linux kernel, being hacked over by as many hands as the that kernel was, should at some point have collapsed under the weight of unforseen bad interactions and undiscovered ``deep'' bugs. If it's true, on the other hand, it is sufficient to explain Linux's relative lack of bugginess and its continuous uptimes spanning months or even years.
In this case it looks like the GnuTLS bug was introduced and fixed by the same person, but I didn't go look to see how many others there were.
Maybe cryptography should be handled exclusively by the OS. Software would communicate through a protocol that can be easily audited (like normal http with special headers). Firewalls could be used to verify what is going on and normal tools could be used to inspect the data. That kind of checking is essential and doesn't require the talent needed for code review.
One of Ars's commenters linked to http://www.openldap.org/lists/openldap-devel/200802/msg00072...
edit: acc00 provided a link to the commit introducing the bug: https://www.gitorious.org/gnutls/gnutls/commit/0fba2d908da6d...
it's a bit more than 10 years old.
https://www.gitorious.org/gnutls/gnutls/commit/12f135e099a57...
That was 2003-03-03, 11 years almost to the day.
This one on the other hand, is a logical bug (interpretation of return codes) which is relatively harder to track especially when the use of said return codes is not consistent throughout the project
I really don't understand why anyone would return an int and have 0 indicate failure. OpenSSL does this too, and it makes no sense to me. I don't know how far this goes back, but clearly we have a long tradition of programs returning 0 to the OS to indicate no error.
if(somefunc()) goto fail;
Additionally, if the return is a fail/pass status, there is only one success (0), and you can use all the nonzero values for error codes.Returning int(0) as a failure is often done in C if the return value is a boolean since C lacks a true boolean type.
[1] NULL should never be used in actual code because it is ambiguous.
Nonzero: error code, zero: success
Nonzero: one of many possible success values, zero: error (e.g. malloc())
Negative: error code, positive: one of many possible success values
And each has its tradeoffs.
If we can't write perfect software, at least being able to quantify the damage would be a good start.
https://www.eff.org/observatory
I'm not sure if the data dumps contain the data needed to search for this bug in particular (but I suppose it should)?
I wonder if moving most logic from these libraries to lua or guile might be a good idea -- and keep only the bare minimum in C/assembler (as I understand it, the key crypto algorithms need to be in something like C in order to be able to guarantee (as much as possible) against side-channel attacks). But I don't know if there are any real reasons to keep everything else in C (other than possibly that making things easier to port/compile/etc?).
Conspiracy theorists would postulate that the iPhone is a much more enticing target for the NSA.
The fact that GnuTLS is extraordinarily unlikely to host an NSA backdoor helps my point, which is why I brought it up.
Orders of magnitude different degrees of harm.
However, I would agree with a hypothetical conspiracy theorist who would disagree with your assumption: Linux may be the platform for many high-value targets and companies, so it's not quantity, but..."quality" of a sort.
So, chalk this up as another triumph for security-critical C?
Actually people seem to need frequent reminding that we don't live in the best of all possible worlds, and that some of the difficulties in working with the best-available current tools aren't inescapable but rather shortcomings that can and should get fixed sometime. It's great if everyone now knows how suboptimal C-everywhere-forever is on security grounds, at least—but tbh 'security-conscious developer' sounds a little like 'true Scotsman' here. A hae me doots.
There is nothing wrong with developing security-critical code in C if you're an experienced C programmer and know what you're doing. The GnuTLS programmers were neither experienced C programmers nor knowledgeable about security; they should not have been writing security-critical code in the first place. And no one should have ever believed that their code was trustworthy.
How many critical and ancient bugs still remain undiscovered?
Everyday there is a new Telegram, Cryptocat, etc. all presumably being constructed on top of insecure libraries. What progress can we make with such shaky foundations?
There has been word that the Linux kernel devs are considering slowing new feature adoption for a time while focusing on bug discovery and elimination.
PLEASE, EVERYONE ELSE CONSIDER DOING THE SAME.
For example, Ubuntu 12.04 LTS uses an older version of OpenSSH and OpenSSL. There should be no reason why Ubuntu (and others) can't commit to updating to the latest versions so that features in say OpenSSH 6.5p1 are avail. BTW, saying that you can compile and install this yourself is noted beforehand but honestly, how many people do that on a regular basis?
What I'm getting at is that security software can and should be held to a higher and current standard precisely because it affects so many other pieces of software in fundamental ways. It's not a big deal if the latest version of bc is not installed but it sure is if GnuTLS or OpenSSL is broken.
https://www.gitorious.org/gnutls/gnutls/commit/0fba2d908da6d...
"Improved the certificate generation stuff."
In both of these cases, it seems the code starts with the assumption that the cert is valid and then tries to find various conditions to invalidate it. Isn't that backwards? Why not start with an assumption that the cert is untrusted until you've proven otherwise?
Additionally, it seems that in certain situations having several plain-if conditionals set the valid state to `1` would be less robust than having several conditionals set it to `0`. In the first case if any one of the conditions have bugs the false valid state can happen, whereas in the second case the last conditional to execute would have to contain the bug.
Can anyone else comment on this? Are there relevant theories and/or best practices which have been discussed in the security community?
That does sound like a good idea as long as the meaning of `1` and `0` do not get confused, and as long as we're not talking about some niche context where extra overhead for the sake of code maintainability would be a problem.
Read Schneier and Ferguson describing in _Cryptographic Engineering_ the steps required to validate a bignum arithmetic library. That's one of the smaller problems in getting a TLS stack right, and it's complicated.
If you demand that your browser implement protocols the same way ActiveRecord implements SQL join generation, you should just stop using browsers; none of them are built the way you'd want them to be.
I have a hard time not being dismissive about TDD's role in improving systems software security. If you're going to propose a radical change in the way systems code is written (or, worse, hold systems developers to a nonexistent standard), be intellectually coherent about it: demand that security-critical code be implemented in a rigorous language, like idiomatic Haskell. Don't propose monumental changes that promise only that the resulting code will be asymptotically secure as Ruby on Rails.
If I implement a network protocol I will make sure to write automated test involving clients and servers. Setting this up on localhost or on a virtual network using TUN/TAP is not that hard. And this has made me find TONS of bug ahead of time.
I hear a lot of arguments as to why testing networked or otherwise distributed things isn't necessary. But just look at Aphyrs complete destruction of well-known distributed systems by using realistic testing.
And don't claim that the kernel network stack isn't tested. It's just tested by hand. Plus, there are projects like autotest. Without testing, I don't think there's any chance that the kernel devs could release any more versions.
Safe languages, formal verification, using proven methodologies and testing are all separate methods of improving code quality. But I don't believe any one precludes the other.
I'll end with a famous quote from Knuth: "Beware of bugs in the above code; I have only proved it correct, not tried it."
I agree that it's helpful, but the problem is coverage. Your test code, most likely, doesn't cover EVERY single possible condition that can happen with a simple TCP/IP connection. Especially once you get out of localhost land, where you're dealing not only with your code, but all the hardware and software between the two systems
The fundamental problem is that even with a rigorous test suite, you're probably going to run into things you didn't even think were possible once the code is out in the wild. For example, we just ran into a scenario where we were seeing corruption through a TCP connection. Knowing the wire, it was impossible for the packets to be appearing in the way that they were(there was some packet level corruption). After going through multiple wireshark logs, we found that the culprit was a hardware firewall in between the server and client. Thankfully, our code didn't crash, but it's also something that we never tested for, because(in theory, at least), it should never be possible for that specific corruption to be sent in the first place.
A TCP stack can be written in a way that makes it simple to test, and getting full branch coverage isn't that onerous a task. Does that catch all bugs? Of course not. But it'll still catch many simple logic errors like this one. Such logic errors do creep into code quite often, can be hard to trigger or detect during manual testing, and will be hellish to debug if they manage to get all the way through to a live system.
(This isn't idle speculation. I'm the lead engineer for a high performance userspace TCP stack that's handled petabytes of data, probably for millions of endpoints. We have deterministic unit tests for a large proportion of TCP behavior. Getting into a position where we could do proper testing took a while since the initial version was not written with testability in mind, but that work was definitely worth it.
But I'll take your word on TLS.)
What I read him as saying (and agree with) is that he's surprised that GnuTLS isn't tested against known-bad certificates in a simple integration test that doesn't require a Ph.D. to set up, as you imply.
The fallacy that you could have easily written a test case for this bug appears neatly encapsulates the weakness of "TDD" as a mitigation for programming flaws.
Define "known-bad" in a general enough way that a specific test can be created to cover the entire range of "bad" certs. That's quite difficult, and, probably isn't realistically possible to go through all the "known-bad" if you want your tests to run quickly.
Realistically, all you can do is have regression tests to make sure that the found bugs aren't repeated in future releases.
For certificate verification, you craft various correct and incorrect certificates to cover the various scenarios involved in certificate verification.
For communication related code, you talk to the tested code over TCP or internally as a transport layer implementation (assuming the TLS library supports user defined transport layers). Same as above, you identify the various code paths and attempt to test them all.
> for the same reason that the kernel TCP/IP stack isn't built with TDD
I believe the primary reason why testing kernels is hard is that they are intended to run on real hardware and often with strict timing expectations. This is not the case for TLS libraries, which normally run in user space.
I know I could come up with a very basic set of test cases, and my only experience with TLS is reading parts of some book I found in my company's library. Heck, OpenSSL has a ton of tests it runs on every build, I know this much.
And even in Haskell you'd need tests. At no time will you ever be able to write code without testing it.
Most CPAN Perl modules for almost two decades have such tests for much less critical stuff. There's no excuse for not having such methods for security critical code.
Tptacek is muddying the waters by claiming it's hard. It's not. We have more different implementations of the same protocols so it's even easier to cross-verify.
- Here's a library that claims to validate certificates.
- Here's a TLS httpd with a forged commonName.
- for ciphersuite in $supported; do
Completing this test is an exercise for the reader, yet we're waxing philosophical about the perils of Ruby on Rails in this thread for some reason. If I'm being told by a security expert that such a framework would not be helpful, that's concerning and makes me wonder how many bugs such a framework would uncover (given that this one remained untouched for a decade).https://www.gitorious.org/gnutls/gnutls/commit/855127da290a2...
Basically, the code said
bool isOk() {
result = someCheckReturningNegativeOnFailure()
if (result < 0) goto cleanup;
cleanup:
...
return result;
}
The issue is that failure is communicated with a negative number in one case and 0 in another, and the wires got crossed.But seriously, I'm amazed that code this critical uses sloppy typing. I mean, they might as well use Python ffs. Maybe it's historical burden?
Code that supports GnuTLS can easily be made to support OpenSSL (or several other such libraries). It really is a matter of which license you prefer, and licensing should never be a consideration in security.
root@teacup:/home/keith# apt-get upgrade
The following packages will be upgraded:
libgnutls26
Not quite 9 hours but fairly quick on gNewSense 3 as well, no doubt pushed through from Debian Squeeze.https://www.schneier.com/blog/archives/2014/02/was_the_ios_s...
1) consider installing the "unattended-upgrades" tool, to install security updates via cron. https://help.ubuntu.com/community/AutomaticSecurityUpdates
2) specific Ubuntu Security Notice on GnuTLS: http://www.ubuntu.com/usn/usn-2121-1/
3) List specific package affected:
dpkg-query -W libgnutls*
libgnutls-openssl27:amd64 2.12.23-1ubuntu4 libgnutls26:amd64 2.12.23-1ubuntu4
I'm on Linux Mint, and the above seem to show that I'm protected. Yay!
.../ubuntu/+source/gnutls26/2.12.23-1ubuntu4.2
Yours is:
.../ubuntu/+source/gnutls26/2.12.23-1ubuntu4
See:
https://launchpad.net/ubuntu/+source/gnutls26/2.12.23-1ubunt...
The only thing I really know I use TLS for is email server connections via Thunderbird however.
In Arch Linux very few packages depends on GnuTlS.
The "goto considered harmful" article by Dijkstra is more nuanced (and that wasn't even its intended title) and doesn't really address the way the goto you are seeing are used.
They are a very common pattern in C, for error checking and cleanup in case of error. It's much more readable than to nest conditional statements.
if (some_parameter > max_valid_value)
goto error;
if (some_function() <= )
goto error;
...
...
if (some_alloc() == NULL)
goto error;
...
...
...
...
error:
// cleanup what needs to be freed,...
It can also be quite useful to exit nested loops for example. It's commonly used in low-level C.However, when you start goto'ing backwards instead of always forwards, it becomes terrible for readability, so it is avoided (well, most of the time).
For more reading on the subject, this excerpt from Code Complete by Steve McConnell discusses the subject further : http://www.stevemcconnell.com/ccgoto.htm
e.g. https://stackoverflow.com/questions/788903/valid-use-of-goto...
In response to Dijkstra's letter, Knuth wrote the article 'Structured Programming with go to Statements' (http://cs.sjsu.edu/~mak/CS185C/KnuthStructuredProgrammingGoT...). He defends certain uses of goto, such as error exits.
Both cannot be wrong can they? It is a logical impossibility.
And in other words, nobody should be writing anything in C. Ever. The need to be compatible with programs written in C violates my rule against writing anything in C and is therefore not a valid reason to write crypto stacks in C.
And in other words, nobody should be listening to thrownaway2424. Ever.
In Apple's case "goto" made it possible for the bug to occur, but there's no reason a different statement (or other typo) could cause equivalent damage.
I think a common thread with both of these bugs is testing the failure cases, but to be fair to both validating software by finding bugs and/or validating functionality is affirming the consequent and you eventually need to ship.
Bad software engineering. Their internal routines return negative value to indicate failure, but to the caller they translate it to true/false.
Or do you just mean that its abused a lot? (in which case, I'm less interested.. :) )
/s
#it_comes_in_threes
* Checks if the issuer of a certificate is a
* Certificate Authority, or if the certificate is the same
* as the issuer (and therefore it doesn't need to be a CA).
*
* Returns true or false, if the issuer is a CA,
* or not.
*/
static int
check_if_ca (gnutls_x509_crt_t cert, gnutls_x509_crt_t issuer,
unsigned int flags)
{
Sure, returns "true" or "false" which are not things in C. This actually returns either 0 or 1. Many C library functions return 0 for OK and non-zero for error. This one returns 0 for error and 1 for OK.Imagine you are reviewing the a call site of this code:
if (check_if_ca(...)) {
// CA is valid, proceed
}
vs. if (check_if_ca(...) == 0) {
// CA is valid, proceed
}
To the reviewer who is accustomed to strcmp, either of these might appear to be fine, meaning that the reviewer (or even the author) has to carefully check the documentation of this function.What else is wrong with this signature? For one thing it would be easy to swap the arguments around:
if (check_if_ca(cert, issuer, flags)) ...
if (check_if_ca(issuer, cert, flags)) ...
What's the difference? They both look reasonable. What are the valid/relevant values of |flags|?Would it be easier to comprehend |flags| if it were an options struct, e.g.
GNUTLSCertificateVerificationOptions opts;
opts.set_allow_rsa_md2(true);
...
cert.Verify(opts);
?Would it be easier to verify the correctness of a call site of check_if_ca if it looked like this:
if (issuer_cert.IsCA() || cert == issuer_cert) ...
Where are the unit tests. The unit tests should be right here in the lib directory as whatever_unittest.c, adjacent to the source file they are testing, so you don't have to go groping around in the tree trying to find the relevant test, if it even exists. By the way, I found no test that calls this function.Basically this code has all the same problems as the Apple code, except for the mixed tabs/spaces stuff (as far as I can tell). It would be shameful for any professional programmer or organization of programmers to create this code.
#include <stdbool.h>
Available since C99.
[EDIT - maybe pride in the bad C-isms?]
A lot of the rest is just sugar (e.g., C++-style comments). Moreover, many code bases already evolved patterns for dealing with the problems that many C99 features are supposed to address. Booleans are a good example: many environments already have a fine boolean_t definition, and it's not really worth it to convert existing code or introduce a second pattern for representing boolean values.
Variable-length arrays are another good example. They're fine, but alloca() is a perfectly reasonable solution to the same problem, and it's already widely used. IMO, the safety issues usually brought up around alloca() are neither more likely nor more serious than problems like allocating a gigabyte-sized object on the stack or returning a pointer to stack memory. Since competent C programmers don't generally make those mistakes (IME, of course -- I think I've never debugged a problem that turned out to be a misuse of alloca()), I find the added complexity of a new language primitive isn't worth it. (Incidentally, that's the same reason I dislike nearly all of C++.)
The code absolutely should have had clearer comments, since if every step were commented then some of the return value confusion may have been avoided. The style of the code itself probably isn't as terrible as it seems at first glance, though.
It's also not easy to write useful unit tests for a security stack.
Both of the recent bugs do not require a cryptographer to find. They are just logic bugs that any reasonable unit test would find.
It's probably tempting to think that unit testing might save us from security failures. People have written many words on both sides. But how many of us have actually tried it? No one who hasn't tried (and tried hard) to see whether unit testing works has any business arguing for (or against) unit testing. We simply don't have enough data to know whether it's valuable. And the fact that unit testing works in domains other than security isn't evidence that unit testing would produce any kind of benefit in computer security.
What's getting lost in the noise here, I think, is that it's important to zoom out and think about a broad overview of how difficult compsec is. Think about all the different situations that require security. Even something as seemingly simple and straightforward as an OS-level copy-paste mechanism requires thinking about security.
Could you write unit tests to cover all security situations? How about all possible situations? If not all possible situations, then why? What's the difference between a situation that you can unit test and one that you can't? Is it possible to write a unit test that checks whether there's a sequence of steps a user could take to exploit an OS-level copy-paste mechanism? Can you unit test the efficacy of a TCP/IP stack? Is it possible to unit test whether the Debian OpenSSL PRNG is being fed with sufficient bits of entropy? Can you unit test whether the colors of your website are pleasing?
The most interesting answer to those questions isn't "yes" or "no." The most interesting answer is "maybe." Because "maybe" means nobody knows, and that's fundamentally interesting. It's possible that it's possible to write unit tests for domains that nobody has thought of yet. (Yes, even tests that automatically infer whether your website's colors are pleasing to humans.)
Could unit testing have saved us from this one particular case? Maybe. But is it possible to write unit tests in the general case? Maybe not. But you, I, and everyone else doesn't know until we actually try. It could be impossible, or if not impossible then infeasible, or if not infeasible in a dynamic language then infeasible in C libraries. On the flipside, if you investigate, and you come up with a way of writing unit tests in the general case for security libraries, then you may have just discovered a breakthrough in how cryptographers can write security libraries. Because if it's possible to write useful unit tests in the general case for security libraries, then you will have demonstrated something that most cryptographers generally disbelieve, the same way that people disbelieve that it's possible to unit test whether colors are pleasing.
So get to work! There's nobody stopping anyone from right now going and trying to write those unit tests. Try it, write a blog post about your experience and the hardships, write about what you've learned. I guarantee it will be interesting.
All I'm saying is that we should be experienced before we advocate or dismiss an idea, and the only way to get experience is to try it out.
Sorry for picking on your comment in particular. I could have replied to any number of comments in this thread.
Incidentally, would this bug have been flagged by a compiler warning?