380 points · by loup-vaillant · 9y ago · 386 comments
The thing that I said was "table stakes" for implementing cryptography was passing the algorithm test vectors, which this author's previous post claimed as a security feature.
If you're unfamiliar with the concept, a test vector is a series of strings and intermediate values used to ensure that your (say) OCB3 is the same as everyone else's OCB3.
Had he asked, I'd further claim that not having dumb C bugs is also table stakes for cryptography, since serious crypto vulnerabilities happen at a higher level of abstraction. The author grazes past (somewhat disconcertingly) one such class of bugs when he discusses carry propagation and limb scheduling in the context of Poly1305. Improper carry propagation is an example of the kind of security vulnerability for which there are no test vectors and no memory safety validation tools.
You just have to know what a carry propagation bug is, where to look for them (not Poly1305), and what the impact of one is.
Hopefully, the author of this library does.
This is one of the things that drives me nuts about the crypto community. The natural response upon reading, "You just have to know X" if you don't already know is to go search for X. Well, if you go search for "carry propagation bug" you will find lots of examples of carry propagation bugs being found and fixed, but no explanation of what one is. The thing that "you just have to know" is not so easy to find. The courteous thing to do when mentioning something that "you just have to know" but which is not easy to find is to provide a pointer or a short in-line explanation. When you don't do that you leave your reader with no choice but to publicly expose their ignorance of this purportedly crucial knowledge by asking, which I will now proceed to do as a public service: What the hell is a carry propagation bug? Where do you look for them? And what is their impact?
And while we're at it, what are "table stakes"?
Bignum is what you need when you have one number that you're splitting between multiple variables (because it's a 256-bit number, and you want your library to work on 32-bit PCs, for example).
Carry propagation is if part of your result is too large for one part of your number and needs to overflow into the next part.
Actual carry propagation bug and bugfix available here: https://news.ycombinator.com/item?id=8857363
Sean, Marcin, and I spent the better part of a year individually replying to tens of thousands of emails from people doing the Cryptopals challenges that we wrote and published for free. Do you know how much work that was? Here's a hint: it was a lot of work.
There are a lot of charges you can level at me to try to win a dumb message board argument, but the one where I want cryptography to be a secret priesthood known only to the anointed select is not one of them --- nor is the argument that I haven't taken the time to help make these kinds of cryptographic attacks easier for people to learn about.
Please immediately find one of those other arguments to substitute for this one, and, if you have it in you, take a moment to retract.
Thanks in advance.
Nonetheless, I still stand by the substance of my comment: when you (not you specifically, but anyone) say, "You have to know X" you should check that doing a Google search for X yields some reasonable results, and if it doesn't, provide a hint on how to proceed.
This is more an indictment of the whole community that there aren’t clear glossaries or other introductory resources with good google juice, and doesn’t necessarily reflect much on your specific comment or intent.
He could have phrased it much better, but I think you’re also overreacting.
There are programs that teach this, but they take years. Nobody who's passed through that is interested in creating an easy scaffolding whose levels are unclear.
This is exactly the sort of thing I'm talking about. This is semantically equivalent to, "If you don't already know this, then you are too stupid, and my time is too valuable, for me to do anything beyond pointing out that you are stupid and my time is valuable." That may be true, but it's not helpful.
> There are programs that teach this
But you aren't going to tell me what they are or how to go about finding them? Again, this is not helpful.
The reason is that the statements is wrong and is probably encourage exactly what it wants to discourage. Crypto is hard is not factually incorrect. The problem is that it is trivially correct, because programming is always hard. Every algorithm and design is hard to get right.
The correct statement, and the one that should be repeated instead is that crypto's stakes are high. Getting it wrong carries bigger consequences than a normal program.
So stop propagating that crypto is hard. (Because people do hard stuff everyday and might thus think they've got the right stuff to write crypto.)
Say that crypto has too high stakes to be done off the cuff.
(business) minimum entry requirement for a market or business arrangement OR (poker) limit on the amount a player can win or lose in the play of a single hand [1]
http://www.urbandictionary.com/define.php?term=table%20stake...
The crypto community has repeatedly been burned by overeager beginners with false senses of competence making rather nasty mistakes. Consequences can be dire, from destroying companies to getting people killed. On the lighter end, you have things like Decrytocat.
In some arenas, it's appropriate and a good practice to assume that everyone reading is a beginner who needs 101-level info on everything. Webdev is a good example - CSS, or cascading style sheets, are good for handling the display logic of semantic markup. The stakes are low and the costs for screwing up trivial. With cryptography, it needs to be driven home to the idle reader that this is serious stuff.
Not at all. I'm not actually expecting anything. All I'm saying is that as a matter of common courtesy (in any field) if you're going to say, "You just have to know X" then you should do at least one of the following:
1. Check that if someone doesn't know X that they can get at least a lead on how to learn about it by searching for X.
2. Provide a pointer for someone who wants to learn about X to follow as a starting point
3. Provide a brief in-line primer on X
If none of those conditions hold then it's not constructive to say, "You just have to know X." What you're really doing in that case is not providing useful information, but rubbing your audience's nose in the fact that they are ignorant and you are not, and worse, that you acquired your knowledge through some privileged channel to which they do not have ready access.
Honestly, what possible reaction could you reasonably expect other than frustration?
Now you see the issue!
So this old movie cliché where the protagonist has lost almost all his chips and needs a huge win, so he casually throws in his car keys and the title to his house in the middle of play is not allowed. Neither is grabbing your wallet and throwing cash in.
The idea is that (a) rich people cannot bully others around at will with their huge wealth "in the background" and also (b) players are protected from losing possessions extraneous to the game.
When used as an analogy, the table stakes are just features expected of anyone, not something special to advertise. For example, you wouldn’t say “I’m the best driver because I have a driver’s license and car insurance” – those things are just “table stakes” for drivers.
And, taking my own advice, here's the link everyone should be pointing to:
I beg your pardon?
Some tests vectors from the RFC are designed specifically to handle some overflow that if handled improperly will give you the wrong results. I have checked, this hits the relevant paths. Or were you talking about something else?
By the way, I haven't attempted to implement curve25519 field arithmetic myself, that would have been suicide (compared to curve25519, Poly1305 is a piece of cake). It all comes from ref10, minus the left shift UB it had.
> which this author's previous post claimed as a security feature.
Here's my current view on security: correct software is secure, period. Vulnerable software is incorrect, period.
Which means that anything that helps assert correctness is a security feature. Test vectors, sanitisers, static analysis, Valgrind… are all security tools, and passing any one of them increases confidence in the product, thus making it more secure. Add enough of these, and confidence gets close enough to 100% that we can deem it ready for production.
So, yeah, test vectors are a security feature. Laughably insufficient by themselves, but still necessary to assert the security of a crypto suite.
> Had he asked, I'd further claim that not having dumb C bugs is also table stakes for cryptography
Yeah, sorry about that. I assumed the same, but I thought Valgrind had me covered at the time —oops. Using sanitisers on Monocypher has been quite the eye opener. I didn't realise how dangerous I used to be.
I still have my doubts, by the way. While I would gladly trust Monocypher with my data by now, I don't dare openly recommending it over Libsodium just yet. That may have to wait for a serious external audit.
And yes, I believe I'm talking about a more complicated class of bugs than you are. For instance: OpenSSL's algorithm implementations pass test vectors (OpenSSL is FIPS certified, too). But OpenSSL has had recent carry propagation bugs.
I am not concerned about your use of C, or about the presence of memory corruption bugs in your library. If I was going to harp on about that, I'd also have to go after everyone who's written a Markdown library. My concern is that the kinds of things you say you've done to ensure the security of your cryptography don't address real cryptographic vulnerabilities.
You may have done other things and I just haven't read about them! I don't really care about your library one way or the other; the only thing I care about is the idea that if you pass test vectors and Valgrind is OK with your binary, you're probably OK. No!
Also, didn't the carry propagation bug reports come with failing tests vectors? Or are they hard to find even if one knows of the bug?
> the only thing I care about is the idea that if you pass test vectors and Valgrind is OK with your binary, you're probably OK. No!
Definitely agree. Even test vectors + safe Rust aren't enough. Which is why I added random comparison tests with libsodium (for every possible length input between 0 and a couple times the size of the block), and property based tests.
I'm still a bit uneasy about carry propagation in Poly1305, but I really checked the hell out of my code.
I know "don't roll your own crypto" comes across as dismissive or patronising. I'm not a huge fan of the phrasing. But as a first-order approximation, it is correct. If you want to roll your own crypto, that needs to be your _thing_. It's very unlikely you're going to be a fantastic full-stack web developer _and_ be able to do that. If it's really what you want to do then awesome! Go study it, learn it, practice it. But if you're doing it as a side-hobby, never put it into production.
"Almost certainly you will get the urge to invent new cryptographic algorithms, and will believe that they are unbreakable. Don't resist the urge; this is one of the fun parts. But resist the belief; almost certainly your creations will be breakable, and almost certainly no one will spend the time breaking them for you. You can break them yourself as you get better."[1]
The problem that Schneier is referring to is that doing a careful analysis (that is required if you want to use your crypto in production) is tedious, time consuming, and requires expertise in the area to know most blank spots of the algorithms (heck a single one is hard enough). That's why he recommends you to be have enough experience breaking many algorithms before you make any serious claim about your the safety of your crypto.
So all in all it's great that you got the interest in the area, there is a lot of work needed in OSS. But be very careful about claiming that your lib is ready for production. What you got is a bunch of volunteers to glance at your code. Few cryptographers (if any) will seriously try to break it.
[1] https://www.schneier.com/crypto-gram/archives/1999/1015.html...
Surely people who invent and implement cryptographic algorithms for a living can be expected to be better than your run-off-the-mill programmer, but as I've said elsewhere implementing crypto is also not a black art. It requires about the same level of skill as e.g. implementing a production-ready low-level network protocol or a file system. That rules out many programmers but not all. That concerns implementations. As for algorithms, their development requires extensive experience in cryptanalysis (not just applied cryptography!). Some pros have that, others don't.
Last but not least, many popular and widely used crypto libraries started as a side hobby. For example, libtomcrypt started that way. In fact, many widely respected cryptographers started as hobbyists. For example, Bruce Schneier. Of course, the ones who are widely accepted as peers are also those who are in the 'hire me as a consultant, not the other guy' business, and they will naturally advise everyone to not roll their own crypto but to rely on their expertise...
Sidenote: how we started these things historically is not relevant anymore. We have learned a lot since then. Failing to "stand on the shoulders of giants" and learn from history is one the biggest factors that makes home-rolled crypto so easy to break - they are doomed to repeat the mistakes of history. Mistakes that are nowadays well documented and well known.
You're right that the code written by professionals has lots of bugs. Bug is a term that describes a problem in code that has been found. With crypto software, the danger isn't the problems that get found (and then addressed), it's the problems that aren't found. "Roll your own" solutions have problems that never get found. That's the danger and it has nothing to do with the skill of the programmer.
Rolling a usable crypto library is not a single person endeavor. Your own crypto won't be peer reviewed, thus you should not trust it.
> Take a look at so-called 'professional' cryptographers and their libraries, and you'll find that practically all of their code had severe bugs. Professionals make errors like everyone else, 'professional' just means you're being paid for it. You will have a hard time finding a professional and widely used crypto library that wasn't essentially compromised in one of its functions at one time or another. Not only that, professionals from the closed-source department have a long history of coming up with compromised or bogus, sometimes even ridiculous cryptographic algorithms and implementations. Two typical examples: CMEA cell phone encryption, and the Crypto AG backdoor debacle.
This doesn't diminish the claim that the modal individual should not attempt to "roll their own crypto." You're pointing out that professionals make mistakes, but of course they do - that indicates nothing about the propensity for amateurs to make mistakes.
> It requires about the same level of skill as e.g. implementing a production-ready low-level network protocol or a file system.
I have never implemented a low level network protocol or a file system (although at least the former sounds like a fun project) - so I cannot claim you're wrong here. However, I will point out that a network protocol is not designed to be error-proof in an intentionally antagonistic environment, which is a difficulty unique to cryptographic software. There are incentives involved in breaking crypto code that do not present themselves in other areas of software development, even if the programming difficulty itself is not entirely dissimilar.
> Last but not least, many popular and widely used crypto libraries started as a side hobby. For example, libtomcrypt started that way. In fact, many widely respected cryptographers started as hobbyists. For example, Bruce Schneier. Of course, the ones who are widely accepted as peers are also those who are in the 'hire me as a consultant, not the other guy' business, and they will naturally advise everyone to not roll their own crypto but to rely on their expertise...
They can start as side hobbies, but they are not going to remain that way for any meaningful amount of time if they are to be widely deployed and safe. You can only choose two out of those three.
More importantly, there is no cabal of cryptographers spreading FUD to line their own pockets with consulting fees. The cryptography consulting industry is very small compared to the actual security consulting industry. In the application security consulting industry I do believe there are firms that try to secure business this way, but that industry is much larger (and has firms which try to misrepresent cryptographic competency). I have had significant interactions with engineers at Riscure and NCC Crypto, which is a sizable portion of all the "real" cryptanalytic consulting work that occurs (at least in the United States) - they never struck me as being the sort to suggest what you're saying. That leaves Rambus/CR and a select few other firms doing real crypto consulting, which leads me to believe the industry is, on the whole, very legitimate.
Err, really? That may be the case sometimes. Also these days many things can be antagonistic: anything online is exposed to adversaries. So is anything that routinely reads untrusted input on everyone's computer (like a video player, or a pdf reader).
Thinking of the sheer amount of potentially vulnerable code out there makes me a little scared.
But that's actually not true, at least not anymore. People attack protocols on the internet all the time, and it's a difficult task to harden them against that.
That said, it doesn't really take aware from your point, I think; but rather confirms it: Think twice before rolling your own network protocols (at least if they are meant to be used in large scale on the open internet), be aware of all the complicated pitfalls.
Just wanted to point out that "individual-should-not-attempt-to-roll-their-own-crypto" is ambiguous and unnecessarily antagonistic while the paragraph quoted above from Schneier is clear and difficult to argue with.
"As simple as possible but no simpler" applies quite well to summaries, esp. when they regard cryptography.
Our "field" of programming is so weak in its preservation of institutional knowledge, that we have to occasionally fight the recurrence of bad ideas about very basic things, like using string filtering to avoid SQL injection. Yes, this happens, even in "hip" new parts of the field, like the communities around newer languages. (I have a specific example in mind, but I don't want to deal with the resulting war.)
The trick is to have a second person helping you, who has all your mathematics notes, a copy of your source code, physical access to your hardware, and the ability to run your program inside a debugger. You don't even get to know whether they put cream in their coffee.
If you can keep a secret from them, you're doing okay. So then you rent a smarter person to do the same thing to make sure all the tricks and shortcuts have been attempted.
If someone manages to break it in the wild after that, you're still doing about as well as some of the highest-paid professionals in the industry.
Defense is difficult.
It means that normal citizens won't be completely helpless against tyrannic governments and it helps to educate that writing crypto from scratch is most definitely something that criminals can do. The government making it illegal or backdooring it will only help against lowest-effort criminals, not against organized terrorist groups. Sure, those probably won't write unbreakable encryption, but it'll be enough to bypass a government that's expecting everything to be in plain text.
On the contrary, this is -exactly- why you don't want to roll your own crypto. Because they can and will break it. Good crypto takes serious thought and effort from people who put a lot of thought and effort into it.
Normally I wouldn't speak against what you said because the critique is only very minor, but I heard this too often. Your warning is too strong. People should try their own crypto and with little care it is not unsafer. Maybe giving a list of do's for that would be a good start.
No, you really can't, unless you stretch the definition of "side-hobby" to the point of breaking at the seams. I'd be shocked if a single person who professionally works in security or cryptography is going to agree with you in this thread. You need far more than a "little care" to assure that a new cryptographic library is safe. It's an endeavor suited to a collaborative academic or corporate environment, with robust human capital and strong oversight.
I'm willing to accept that someone can safely implement a primitive or a construction in a new library with significant time, effort and feedback from others. But that level of effort doesn't really qualify as a side-hobby, and until the implementation was formally checked by professional cryptographers I'd consider it suspect.
This is to say nothing of designing novel primitives or constructions, which I would consider as far removed from a "side-hobby" as a local 5K is to the Olympics.
However, I absolutely think people should attempt to implement their own cryptography if they're curious about it and want to learn. Just don't use it in production and assume it's unsafe. People who work in the industry don't make these claims because we think it's fun, we do it because we've all seen the consequences.
- You can just use any recommended (by whom?) tool.
- Or you encrypt it with recommended tool with it's own dedicated key. Then you encrypt it again by whatever way you made up in five minutes, and you need only to ensure you didn't use the key material of the recommended tool. Then there you go, you just rolled your own not-unsafer crypto.
This cowboy-programming attitude being extended to security is no small part of why we are so vulnerable as a society to attacks on our computer systems that can compromise our core infrastructure[1], our secrets[2], and our economic security[3].
[1] Think weeks-long country-wide power outages
[2] Think juicy blackmail material on anyone with their hands on levers of power. Look at the damage that North Korea's attacks did to Sony Pictures, for example.
[3] Think small-scale attacks on services that even a single major company, or many small companies, rely on.
GCHQ loves people who think this.
Have a look at some of the game console cryptography. These are companies with strong financial incentive to get it right. They're large well funded multinational organisations. They still get it wrong.
1) they invest 6 or 7 figures in this (piracy prevention is big money)
2) they still get it wrong
3) they not only get it wrong, they get in wrong in ways that teenagers still in high school can break, let alone the NSA
a) Well known, well studied but also attractive targets for attackers to study
b) Unknown (aside from the developer) until an attacker encounters a specific piece of encrypted data
It is a common assumption that well-known methods are better (and it is the assumption I work under) but does empirical data on security breaches back that up? There are plenty of examples of security breaches where 'standard' methods were being used. Are there similar examples where people using previously unknown methods have been compromised?
GCHQ and others invest a huge amount of resources in finding vulnerabilities in well known encryption methods. When they find one, everyone who used that method is vulnerable.
I have no doubt that if they really wanted a piece of data that I had encrypted with a homemade method, they would be able to break it.
However, are they going to invest the resources to do that if I am not being specifically targeted? Are they going to invest the resources to crack hundreds of different people's home-made encryption methods? Thousands? Hundreds of thousands?
If am being specifically targeted by something like GCHQ, they will get what they want one way or another.
They just need to make it hard enough to delay pirated games.
But then you can combine stuff as I've for example written in another comment to roll your own crypto in five minutes, which is not-unsafer.
There is cult around "Don't roll your own crypto" that is thought-policing.
The author's lack of practical familiarity with the memory hierarchy, caching, and pipelining—evidenced by his surprise by the speed gained by fetching more than a byte at a time—also makes me suspicious of his understanding of the semantics of his program. (I understand that this is a form of ad hominem as it relates to arguing the correctness of software, but it's a consideration worth noting in a broader context of trust.)
It would be great if this was written in another language.
[0] Most "portable" code written in C is not portable. Look at any mature C project and see the layers and layers of macros and hacks to make things portable.
Maybe I didn't express myself clearly. I knew loading stuff word by word would be much faster, thanks to my knowledge of the memory hierarchy, caching, and pipelining.
What I didn't expect was the magnitude of the overall impact. The core round functions are much, much faster that I had anticipated. I didn't think the loading code, even in its slow version, would account for a significant percentage of the total running time.
> It would be great if this was written in another language.
Easier said than done. I aim for easy integration in projects written in basically anything: C, C++, OCaml, Rust, Python… What would you suggest? Rust? That's a possibility, but (i) it's LLVM only at the moment, and (ii) I believe there's an impedance mismatch between Rust and a C compatible ABI.
I would totally recommend to rewrite the whole thing in Rust for Rust projects, though.
If you're curious, check this out: https://doc.rust-lang.org/1.5.0/book/ffi.html
> I would totally recommend to rewrite the whole thing in Rust for Rust projects, though.
Any time you rewrite anything, you run the risk of introducing new and unexpected bugs, and you're just doing unnecessary, complex work fraught with pitfalls (doubly so here) -- generally a Rust project would create a wrapper around the C code, invoke the methods and expose idiomatic APIs on top to avoid just that.
This is my go-to article on re-writing things and why not to: https://www.joelonsoftware.com/2000/04/06/things-you-should-...
To be clear I'm not saying you made a mis-step, just that your arguments for it don't seem at first glance to support your decision.
I was just telling one has to write a wrapper either way. Idiomatic Rust is not idiomatic C, so you would need to have a "C ABI" interface in addition to the clean Rust interface.
> That it's LLVM only appears to me irrelevant […]
Not if it targets less platforms than GCC. Though that will likely matter less and less in the future.
> So long as you get rustc up and running, what does it matter it's architecture?
You have to get it up and running. You have another build step. You have to use a binary library (can't just include the source code). It's not much, but I want to maximise ease of deployment.
Portability does not equal 'without blemishes'. It simply means that when compiled across platforms it will perform as expected.
But from a rather philosophical point of view, C is basically Portability 1.0, it was one of the first truly portable "fast" languages. I'd like to think that we could do better than C with 40 years or CS research and industry experience.
Of course, there's the whole second-system syndrome so it's a wicked problem :)
Yeah, you don't even need a new, hip language to avoid C's pitfalls.
> Portability does not equal 'without blemishes'. It simply means that when compiled across platforms it will perform as expected.
By that measure, C is not portable, since it will behave differently across multiple platforms – or multiple compilers, multiple compiler versions, even multiple optimization settings.
So.. it's portable, then?
C is meant to map easily to a wide range of hardware without overhead, conceptually it's almost the opposite of portability since it precludes creating standard abstractions that would hold true across architectures as those could not map to native functionality across the board.
It's easy to compile C programs on a different architecture however, which is probably where this argument stems from. Remember when we switched from 32 to 64bits? How many codebases managed to make the jump painlessly?
The problem is that it returns an "int" which contains a negative value on errors and the number of character written on success.
Of course that means that it's possible to write a string whose size doesn't fit in an int.
For instance if you have a 64bit computer (and enough RAM) you can try the following code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
int main(void) {
size_t len = 0x80000001UL;
char *str = malloc(len);
assert(str);
memset(str, 'a', len);
str[len - 1] = '\0';
fprintf(stderr, "\n%d\n", printf(str));
return 0;
}
Don't forget to redirect stdout to /dev/null. You can pipe through `wc -c` if you want to make sure the billion 'a's are printed.On my computer the "printf" manages to print the whole string successfully but it returns... -1, signaling an error.
The size shouldn't be returned that way, it should be a "size_t" as an output parameter (since you also need a special value for errors). In Rust you'd use "Result<usize>" and you'd have a more elegant solution. Of course you can't really do that in C (except by returning a struct, which is a bit cumbersome) so I guess they said "meh, who prints that much text anyway?" and assumed an int would be good enough.
C provided "at least N bits" guarantees for its integer types since its first standard (for the curious: char at least 8-bit, short at least 16-bit, long at least 32-bit; in C99, long long as least 64-bit). This is the most that you can get if you want absolute portability, because there are architectures out there where you simply can't address memory in, say, 8-bit chunks (see SHARC for an example).
Consequently, while stdint.h defines types like int32_t, they are "conditionally supported", and so a C program that has a hard dependency on them is not universally portable. Types like int32_least_t and int32_fast_t are unconditionally supported, but they don't give you anything that you didn't have before.
Also, portability isn't a binary attribute. For every way two platforms vary, there are often a subset of states and transitions that are identical, and two disjoint subsets that are different.
As long as your inputs start out in the identical subset and don't wander too far, you're good to go. For example, if you never put a value above 32767 into an int, you don't really care whether your int is 16 or 32 bits in size. If that int is e.g. line number in a file, it may mean that your program works fine on most files, but only the 32-bit version works correctly on large files. And of course the cleverer you are the closer you're likely to skate to the edge of the common intersection.
Something that is, in some sense, truly portable is one that has a single specification that runs on all platforms the base implementation supports. Virtual machines and certain styles of language standard are often able to accomplish portability for a vast number of applications.
I would argue that the C preprocessor is, for all intents and purposes, part of the C language. C is not quite practical without its preprocessor, and the preprocessor is not quite practical with any language other than C (or a derivative like C++).
Are there any practical alternatives when that kind of portability is needed?
What about transpiling to C? I know Haskell and OCaml can be made to compile their code into C code that you can then pass on to a C compiler.
1. Manage resources with RAII (though, in C you could use non-portable attribute cleanup in similar manner).
2. Use type safe wrappers around builtin types like in [0] and [1].
3. Use containers with more extensive bounds checking and iteration validity checks [1].
This could help detect some of those bugs at runtime, or even possibly prevent them from being written in the first place. Use of uninitialized value could be prevented with types that require explicit initialization or have default one (Bug 1). Left shifting a negative value could have been caught at runtime (Bug 2). Bounds check could prevent uninitialized memory read (Bug 3) Type safe wrappers could prevent an accidental promotion from being written in the first place (Bug 5).
Though, you need to go out of your way to actually do all those things, not to mention that your code would integrate poorly with existing library ecosystem. IMHO choosing C++ alone doesn't improve safety of your programs compared to ones written in C all that much.
The sort of direct control one might look for is, as far as I know, only practically found in your processor's assembly language, and your operating system's collection of syscalls.
I think Rust, Common Lisp, OCaml, D, Haskell, and other languages give you a lot of benefits that are simply not worth giving up in a new crypto library, like safety.
I think writing timing-attack resistant code in Haskell would be very hard to impossible, at least without writing very unidiomatic code (basically "C in Haskell"). I'm happy to be proven wrong, though.
The ANSI C and C++ standards define the concept of abstract machine for the language semantics, just like in most languages.
Additionally you have the concepts of sequence points, the new memory model semantics for multi-threaded code and the beloved UB.
UB which doesn't exist in most languages, because their rather leave it implementation defined or lose the opportunity to target some strange CPU not able to support the language semantics.
Also Assembly doesn't has UB, making it ironic that it is safer to write straight Assembly at the expense of portability than C or C derived languages.
You just need to know your compiler flags/configuration to produce exact assembly output (if you want that). And about assembly not having UB, BSF and BSR are pretty good examples for that.
Edit: Sorry, wrote this too hastily and want to put it in perspective. While Ada is well-suited for cryptography and has some good implementations, it is probably not as secure as C crypto libraries in practice. The reason is that the implementations I know don't do OS-specific things like locking memory or preventing core dumps, and doing this in Ada is a bit harder than in C.
found an error in the Argon2 reference implementation.
This is exactly why I like as many people writing crypto as possible[0]. Bugs like the one the writer found show up in reference implementations, and are found by absolutely no one unless someone writes an alternate implementation that behaves differently.Edit: A further example, a lot of people write crypto as part of various CTFs. This is a case of "writing crypto" that poses no threat to the community.
[0] That doesn't mean they should use it in production.
Sure, writing your own library is very difficult, but you have a simpler set of problems, which proper testing, another set of eyes and enough tools will take care of the big problems.
Now, implementing your own primitive and recommending to use it is bad. For a primitive to be deemed secure, it has to undergo years of review and testing by seasoned cryptographers.
This isn't a recommendation to write your own library, but my opinion that it is okay to do so if you want something that none of the major libraries offer.
Definitely impressed if this is your first crypto work. I really like the simplicity, reminds me of OpenSSH.
I gotta agree with some of the naysayers though - this needs more time to brew. Even if it's perfect, there still more proof to show.
My suggestions:
* A long-running interoperability test between your lib and another. Test vectors don't catch everything. Run it for a week, check results and publish the results.
* Fuzzing. You need to to catch false results, random crashes, stack overflows, etc. Fuzz every input, do it for random lengths (both underflow and overflow).
* Maybe port it and test on Win, Mac, ARM, MIPS. I find a lot of bugs shake out during ports.
* Timing. You can't prevent all side-channel attacks, but bits going out are easy attack vectors. Use a high-precision timing mechanism to catch any unusual spikes. Capture a few hours of points for each functional path, and publish the results. (crypto_aead_unlock has two return paths, it might be better to maintain timing).
* Personal preferences: Rather than using int returns, use bool. Zero your ctx vars, e.g. a_ctx ctx = {0,};
I spend more time in testing products than development, honestly. Publish as much relevant data as you can.
It is. :-)
> A long-running interoperability test between your lib and another.
Already have one for all primitives. Just tweak the parameters to make it run for a long time. The test code is in test/sodium.c and test/donna.c
> Fuzzing. You need to to catch false results, random crashes, stack overflows, etc. Fuzz every input, do it for random lengths (both underflow and overflow).
I'm not sure how to go about it. I already check every input size, from zero to several times the size of the internal block, in my comparison tests.
Of course, all inputs are correct. Incorrect inputs result in undefined behaviour, checking for that is out of scope. (That's why most functions return void.)
> Maybe port it and test on Win, Mac, ARM, MIPS. I find a lot of bugs shake out during ports.
Yeah, I only tried GCC and Clang on my Intel Ubuntu machine. But I did use Valgrind, ASan, MSan, UBSan, and the TIS-Interpreter. I also compiled under various standards: C99, C11, C++98, C++11, C++14, C++17.
> Timing. […] Use a high-precision timing mechanism to catch any unusual spikes
Isn't that a bit overkill? I'd rather manually review the source code for the absence of secret dependant branches or secret dependent array indices. I'm not implementing AES or RSA, the primitive I have chosen were specifically designed to easily avoid timing attacks.
> crypto_aead_unlock has two return paths, it might be better to maintain timing.
No. There are 2 cases to consider: failure, and success. Each path runs in constant time, so timing can only distinguish success from failure… which is revealed anyway by the return code.
> Rather than using int returns, use bool.
I'm afraid bool is a tiny bit less portable than int. I also went with the flow about error codes, which are traditionally int.
> Zero your ctx vars, e.g. a_ctx ctx = {0,};
I'm not sure how to do it portably, with zero dependency.
But, yes I wouldn't start out on writing a crypto library, then again I wouldn't attempt to build an OS or a 3D stack or even an web server either. All cases where a security breach could have devastating effects as well.
* DJB wrote NaCl
* Frank wrote libsodium / libHydrogen
* Brian wrote Ring
* Thai Duong and Bleichenbacher wrote Tink
* Eric Young wrote OpenSSL
* Jason Donenfeld wrote Wireguard
* Shoup wrote NTL
* Emily Stark, Mike Hamburg and Dan Boneh wrote SJCL
* Thomas Pornin wrote 6 SSL libraries and then BearSSL
* Adam Langley wrote everything else
* ...
Daniel Bernstein, Daniel Bleichenbacher, Dan Boneh and Thomas Pornin are professional cryptographers and world-renowned experts. Even I would feel comfortable writing crypto if Bleichenbacher was watching behind my back.
Frank "wrote" libsodium, but libsodium is effectively a port of NaCl. Frank had Daniel Bernstein watching behind his back.
Eric Young wrote OpenSSL. Look how that turned out! Has there been a class of cryptographic vulnerability that OpenSSL hasn't had?
And yet consider: for all the effort that people like Bernstein and Boneh put into writing strong, safe crypto, the entire world has blundered into vulnerability after vulnerability because the amateurish crypto in OpenSSL is the one every else ended up using.
It's as if you set out to prove my point.
Finally: you obviously know that "writing your own crypto" isn't the only way to become good at it. In fact, it's a terrible way to get good at it. The right way to get good at crypto is to learn how to break it. But that takes effort, and you can have a blog post crowing about your new crypto library just a few weeks after deciding to write one.
They were not in the beginning. And implementing crypto helped them get there. That's my point.
> Finally: you obviously know that "writing your own crypto" isn't the only way to become good at it. In fact, it's a terrible way to get good at it. The right way to get good at crypto is to learn how to break it.
I strongly disagree with you on this, but I'll add a twist: I'm mostly saying to become good in "applied" crypto you must roll your own. There are too many problems you can't understand until you actually write code and try to make it secure. If you want to become good in theoretical crypto, then don't roll your own obviously.
This works in any field btw. The best web pentesters are the people who have implemented websites on their own as well.
NaCl does not use autoconf nor even make.
It is not necessary but if someone really feels compelled to use it, why stop them?
I have never seen any author or end user comment that they dislike using autoconf, or write alternatives to it. Autoconf is loved by all, isn't it?
I think what you could say is that using NaCl in your own software is the only way to get good at using it. Maybe the existence of libsodium means that more developers will have a go at using NaCl? Is it easier to use than an SSL library? The only way to find out is to try both and compare.
There is no need to use autoconf to build libnacl.a. The original build system for NaCl is beautifully simple. But if someone misses autoconf and make, then libsodium has added in those dependencies.
More projects using NaCl:
As far as I can tell, the authors listed on the above site are not "rolling their own crypto" for their projects, they are using cryptography written by the author of NaCl.
Personal bias disclosure: I find NaCl easier to use than all the SSL libraries I have tried. If I am not mistaken, I believe this was a design goal by the author.
100,000 easy to crack implementations with obvious errors isn't really more secure than 1 super difficult, super well optimized/secured implementation, is it?
One question:
> I was shifting a uint8_t, 24 bits to the left. I failed to realise that integer promotion means this unsigned byte would be converted to a signed integer, and overflow if the byte exceeded 127.
This sounds weird to me, how is a shift (which only apply itself on the bit value, not the number value) triggering a sign extension? I don't think you're talking about integer promotion here unless you had a uint16_t = uint8_t << 24 or something like this.
uint8_t u8 = 255;
uint64_t u64 = u8 << 24;
printf("%016llx\n", (long long) u64);
prints "ffffffffff000000". If you instead do uint64_t u64 = (uint64_t) u8 << 24;
or uint64_t u64 = (uint32_t) u8 << 24;
It prints "00000000ff000000" as most people expect. (I think the second example with (uint32_t) will only work if "int" is at most 32 bits, but I might be wrong). #include <stdio.h>
#include <stdint.h>
int main(){
uint8_t start = -1;
printf("%x\n", start); // prints 0xff
uint64_t result = start << 24;
printf("%llx\n", result); // should print 00000000ff000000, but will print ffffffffff000000
result = (uint64_t)start << 24;
printf("%llx\n", result); // prints 00000000ff000000
return 0;
}If you say "foo + bar" and both are uint8_t, then both will be promoted to integer. That's how C works. Assigning the result to another uint8_t will truncate it.
Please do not write your own crypto library until you really understand how C works, especially including this kind of detail.
Your example is different, this is because you're doing an addition. I can see how this could be a problem if you want to do a rotation (a << 4) + (a >> 60) and hence why you should use a ^ instead of a + here (example: https://github.com/gvanas/KeccakCodePackage/blob/master/SnP/... )
With 32-bit ints, this operation will result in 0x80000000, shifting a bit into the sign bit, which constitutes an overflow (and undefined behavior). Think about it in terms of multiplication: you're multiplying a positive integer by 2^24, and it turns out negative!
u64 = u8 << 24
Here the integer promotion might transform u8 into a 16-bit or 32-bit int (depending on the arch). Which will then be converted to a u64 AFTER the shift. Which might have you lose half or more of the bits.
His code is not that though, it's
u32 = u8 << 24
which should work only if ints are 32-bit on the system you compile on.
> Each of the operands shall have integer type.
> The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand.
6.3.1.1 § 2
> If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.
So if you shift a uint8_t, it is first converted to a (machine-dependent) signed int, then shifted, then converted to whatever the expression type ends up being.
I should have quoted the proper part I was replying to ("I don't think you're talking about integer promotion here")
[1] https://github.com/LoupVaillant/Monocypher/commit/347189c50c...
To see the difference, you need to first modify the makefile to use UBSan instead of just GCC (just comment the active CC line, and uncomment the right one). You may want to tone down the optimisations for faster compilation as well. Then you can run `make clean` and `./test.sh`. You should have a warning on commits prior to this patch.
#include <stddef.h>
#include <inttypes.h>
int main(int argc, char **argv)
{
uint8_t msg[] = { 255 };
size_t i = 0;
size_t c_index = 255;
return msg[i] << ((c_index % 4) * 8);
}
You get: runtime error: left shift of 255 by 24 places cannot be represented in type 'int'[1]: https://github.com/LoupVaillant/Monocypher/blob/master/src/m...
libsodium also got it wrong, so that brought down my opinion of it being a trusted and well-reviewed library.
Now the question is, will they continue to use the same implementation or move to the fixed code?
I'm a bit disappointed however at their not updating the specs. I signalled the bug in January, and the latest version of the appear to have been published in March. I guess they had other priorities.
Don't be too hard on Libsodium: they only got it wrong because they reused the reference implementation. (Also, I don't see them breaking backward compatibility either.)
The few hipsters who jumped on the new hashing algorithm bandwagon can't have much users.
libsodium implemented the same behavior simply because it reused the Argon2 reference implementation.
However, as it stands now, it looks more like a cautionary tale on why he should have listened when people told him not to do it :-)
I suspect a worthier goal would have been to look for ways to improve the linking footprint of libsodium instead of rolling your own library. Maybe turn the "I want the smaller version without the huge lookup table please" in a compile time option or so. That way more people could have used it without having to commit to "I'll use this little known experimental library instead of libsodium". Commit in the sense of "people will ask why and I will have to defend my decision", not in the sense of "oh no we are locked in!!"
---
I've been careful not to lock people in. If people want to upgrade to faster primitives, they can. I don't think they will ever need to, though.
You have to consider the nature of the bug, as well as the fix. The bug was an Undefined Behaviour that had no effect on the binaries I could generate. The fix was 10 characters. Running the automated test suite took longer than fixing the bug.
If there were reasons to delay 1.0, this bug was not it.
> I believe that further fragmenting the crypto ecosystem with a new library and little commercial support to properly back it and pay for security audits is risky.
I agree fragmentation is a problem. I just couldn't satisfy myself with existing alternatives. As for support, I designed Monocypher specifically to need very little of it. Ideally, the only notable changes from now on will be about the manual and the test suite.
Apply the tools that other people used to find bugs in it and repeat blogging about how great it is.
...
In the end you get a library that is slower and smaller (because you left out the optimized code, duh). It's still not as small as the smallest.
Is this easier to audit? Dubious but it doesn't matter because if people hadn't wanted the extra speed they wouldn't have added the optimized code anyway.
Plus, that code is already audited and rolled out and works! Who cares about auditing another library that provides nothing new?
The only non obviously-garbage argument here is usability which I am too lazy to look at because it is too fuzzy to refute anyway.
By all means, write your own crypto but DON'T USE IT! And of course don't tell other people to use it either.
Monocypher vs TweetNaCl:
Good:
Monocypher uses more modern primitives (Blake2b, Chacha20)
Monocypher provides password derivation
Monocypher is a bit easier to use
Monocypher is much faster
Bad:
Monocypher is twice as big
Conclusion:
Monocypher utterly outclasses TweetNaCl.
Monocypher vs Libsodium: Good:
Monocypher is much smaller
Monocypher is easier to deploy
Monocypher is a bit easier to use
Bad:
Monocypher is a bit slower (except Argon2i, which is faster)
Conclusion:
If performance matters, use NaCl. Otherwise, use Monocypher.
Nothing new, you say?> By all means, write your own crypto but DON'T USE IT! And of course don't tell other people to use it either.
Get back to me in a couple years, we'll count the CEVs since version 1.0.
(Yes, it would take somewhere on the order of 10k LOC to prove correctness of this 1k.)
How much of those were formally proven?
Verifying some (but not all) properties of crypto is relatively (but not absolutely) easy, because it's essentially just math with pure functions. Operating systems and physical controllers with real-time constraints have different requirements and more interacting state, which means that the desired properties are not easily expressed as a mathematical expression.
Personally, I think the intention of the phrase "don't roll your own crypto" was lost over time. It was advice to companies to use standard cryptographic algorithms rather than everyone coming up with their own thing for no good reason. It doesn't mean that only some blessed individuals should be allowed to write cryptographic software. I think OpenSSL has taught us that not rolling your own crypto results in a monoculture of self-professed experts that didn't follow that advice.
The thing about the "don't roll your own" advice is it's aimed at people who don't competently know what they're doing rather than those who do.
The fact that there was no independent implementation of Argon2 that found there was a bug in the reference implementation shows that the "don't roll your own" advice is discouraging competition in crypto libraries to the point where the reference implementation wasn't sufficiently verified to produce correct output.
The advice to not roll your own crypto used to mean that you shouldn't invent your own cryptographic algorithm. That's true, unless you're an experienced cryptanalist you're likely going to come up with something bad. (Or slow, as e.g. a moderately secure Feistel cipher is easy to invent if you don't care about speed.)
As for your own implementation of standard algorithms, there are some things that can go wrong, mostly with key derivation padding and chaining modes, but it's not a secret art that only few chosen cryptographers could master. You have test vectors for the algorithms itself, and have to be extra careful about the rest. You have to get someone to audit the code. That's about it.
The fact that people no longer roll their own crypto has two major disadvantages. First, modern ciphers like AES have been designed for ridiculously low security margins. You could claim that security was subordinated to speed in NIST competitions. You can see that in the decision to choose Rijndael over Serpent and Twofish. AES ahs the lowest security margins. Second, it presumably makes life much easier for intelligence agencies all over the world. Instead of having to reverse engineer and analyze thousands of different implementations, they can focus on attacking a dozen popular crypto libraries. This saves them a lot of time and money and also makes it much easier to attack individual developers or binary distribution. (Most attacks nowadays are probably side-channel attacks anyway, but who knows...)
Nevertheless, Monocypher is pretty thoroughly tested by now. I wouldn't be surprised if Monocypher starts getting serious vetting a few months from now.
Oh come on, the chosen primitives are all designed for easy immunity against timing attacks. I haven't verified this formally, but I basically ripped off safe designs, and I tried to be careful about avoiding secret dependant branches and indices.
> I haven't looked to see if there is any sensitive memory scrubbing.
There's a whole test suite for that.
Look at the makefile, then select whatever sanitiser it lists (comment/uncomment the relevant CC line at the begining). Then run `./test.sh`. You can also run the relevant executables under Valgrind. Finally, there's a way to run it under the TIS-Interpreter, though that is veeery slow.
> by someone who doesn't know C very well
Could you tell me how you inferred that? That could help me improve.
He actually talked about avoiding side-channel attacks in his two previous articles about Chacha20 and Poly1305.
- Blood transfusion
- Steam-powered bicycles
- Rotary printing presses
- Submarines
- Luminescent paint
- Hi-speed jet-powered railcars
- Ropes /pulleys to help the user get out of bed
[1] https://en.wikipedia.org/wiki/List_of_inventors_killed_by_th...
On a first read I though "yeah, sure, looks quite dangerous indeed", then I read:
Sylvester H. Roper, inventor of the eponymous steam-powered bicycle, died of a heart attack or subsequent crash during a public speed trial in 1896. It is unknown whether the crash caused the heart attack or vice versa.
- Chocolate soufflé
- Distributed lock manager
- Autonomous war robot
- init(1) replacement
I am personally guilty of attempting four of these things without adequate preparation or expertise.
EDIT: Some interesting discussion here: http://www.dropzone.com/cgi-bin/forum/gforum.cgi?post=482241...
Another question is what make the difference in number of line of codes with libsodium ? I mean what do these lines of of libsodium that your lib doesn't have contain ?
Also, is this a fair metric ? You know we can have 1000 char long lines in C. ;)
Just check the absence of secret dependent branches, and secret dependent array indices, it's pretty simple.
> what make the difference in number of line of codes with libsodium ?
Less lines means less need for eyeballs, tests, and audits. Libraries the size of TweetNaCl (and, to a lesser extent, Monocypher), can be subjected to very rigorous audits, and increase confidence accordingly.
> what do these lines of of libsodium that your lib doesn't have contain ?
I can see 3 sources: redundant primitives (Monocypher is not redundant), alternate implementation (Monocypher sticks to portable C), and verbose implementations (Monocypher keeps it simple).
> Also, is this a fair metric ?
Not quite: I did not count the size of the header in Monocypher and TweetNaCl. Still, I don't think Libsodium has less than 22K lines of actual code. (Note: I counted everything with sloccount)
On the other hand, my lines never exceed 80 characters.
What's wrong with ZIP or 7-Zip + AES encryption? Or GPG with a GUI? Or any other existing tool that's already stable and multi-platform?
I've browsed through the code and i don't see why say it is not good in MT setting... an first view the code is completely reentrant...
Another thought: i strongly suspect that inlining these store_le... and load_le... function will show pretty significant performance boost
If I'm right about this, it would explain why this code path is never hit: it would only trigger with invalid public keys. I'll test that as soon as I can.
Note that this is the initial stage of using Frama-C. The next step would probably include writing some specifications for functional behavior (in ACSL), and then using the WP plug-in (based on weakest precondition calculus) to prove those specifications, providing much stronger guarantees.
A few Frama-C case studies are on Github (https://github.com/Frama-C/open-source-case-studies), including an old release of Monocypher, but they constitute mostly a initial parametrization of the EVA plug-in. Most advanced users of Frama-C apply it on industrial code that is not available, but academic users regularly publish papers with case studies (searching "frama-c" on Google Scholar gives good results).
Why is it so hard?
https://github.com/konovod/monocypher.cr
I think I will personally do C++, OCaml, and perhaps Lua. For the rest, either someone contributes, or you'll have to look at the FFI yourself…
Seriously though, Monocypher is getting getting past the "own crypto" stage at this point.
Is there also any plain to implement scrypt (based on the salsa), SPHINCS (uses BLAKE(1) and Chacha), Ed448-Goldilocks, Keccak or any of the CAESAR candidates? (The ones that seemed the most interesting to me were NORX, Keyak (based on keccak) and HS1-SIV (based on chacha)).
I won't add other primitives to Monocypher, that would defeat the purpose of a "one true cipher suite". One stream cipher, one authenticator, one hash, one password key derivation, one key exchange, one signature. That is enough.
When some of those primitives becomes obsolete, I'll consider writing a new, incompatible version of Monocypher. For instance, we can switch to curve448 if curve25519 isn't secure enough. I think at least a decade will pass before we come to that, though.