[Cryptography] Making sure memory erasure is not optimized away

nagendra modadugu nagendra at cs.stanford.edu
Sat Aug 27 11:37:30 EDT 2022


On Sat, Aug 27, 2022 at 12:51 AM Phillip Hallam-Baker <phill at hallambaker.com>
wrote:

> [Before we start, use language X instead is not an answer here.]
>
> We all know array bounds checking etc. is a good thing to have to write
> any application code. But the cost of abstracting away memory management is
> that cryptographic code has the very particular property that we want to
> ensure data is cleared AFTER USE rather than BEFORE REUSE.
>
> A lot of applications written in high level languages are vulnerable to
> attacks when someone uses portable assembly language, aka C to write a
> program that allocates large chunks of memory and then greps through it
> looking for 'good stuff'.
>
> So the question is how to ensure this does not happen by implementing
> disposal mechanisms THAT DO NOT GET OPTIMIZED AWAY.
>

There are generally no absolute guarantees that the generated code is not
optimized away - a future compiler may get smarter about memory lifetimes.

That said, I wrote an implementation that's worked pretty well across
various versions of gcc and clang:
https://chromium.googlesource.com/chromiumos/third_party/cryptoc/+/refs/heads/main/util.c.
The basic idea is to trick the compiler into not optimizing away writes to
a memory destination marked volatile.

Here's a demo on arm gcc -O2:
https://godbolt.org/z/q9v8dTrPb (destination range marked as 'volatile char
*')
https://godbolt.org/z/WE7q8sa1z (destination range marked as 'char *')


>
> See here is the thing. I can check my code and check my code but I can
> only check the current version of the compiler/optimizer. And some of the
> things I know the C# optimizer is now doing are pretty hard core. Yes, when
> generating assemblies, it can optimize across assembly boundaries now.
>
> I am pretty sure most other high level languages suffer from the same
> thing unless there is a mechanism to explicitly state 'do not optimize'.
> Same goes for things like the Montgomery ladder which isn't as reliably
> constant time as some people might imagine.
>
> Has anyone got pointers to ways to make sure this is done right?
>
>
> _______________________________________________
> The cryptography mailing list
> cryptography at metzdowd.com
> https://www.metzdowd.com/mailman/listinfo/cryptography
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.metzdowd.com/pipermail/cryptography/attachments/20220827/eb8f1da6/attachment.htm>


More information about the cryptography mailing list