mirage / mirage-crypto

Cryptographic primitives for OCaml, in OCaml (also used in MirageOS)
ISC License
77 stars 43 forks source link

Wipe secret key data #237

Open hannesm opened 3 months ago

hannesm commented 3 months ago

At the moment, secret keys are in memory and derivatives thereof as well. It would be great to have a good way on how they can be wiped once they're no longer in use. One way is to store them as bigarray values (sic) to avoid the GC copying and moving them around.

We may want to think and address the "storing secret keys in memory (with a GC around)", as raised in https://discuss.ocaml.org/t/ann-mirage-crypto-0-11-3-with-more-speed-for-elliptic-curves-and-the-future-roadmap-of-mirage-crypto/14200/7 (e.g. rust has https://github.com/cesarb/clear_on_drop).

At the time being, it is as it is, the way forward may be to add OCaml runtime supprt for such values (read: bigarrays could when finalized (collected by the GC) use a hook to clean up memory, but there's issues in respect to (a) zarith / gmp usage of values (and derivatives), (b) in a quicker fashion than "waiting for the GC to collect", we may already know in the code that a certain secret key will no longer be needed.

hannesm commented 3 months ago

Prior art is e.g. ttweetnacl which provides both interfaces -- using bigarray and bytes -- https://erratique.ch/software/ttweetnacl/doc/Ttweetnacl/index.html

hannesm commented 2 months ago

And for what it is worth, cryptokit uses strings for the private keys.

hannesm commented 1 month ago

To add another train of thought: if only mirage-crypto does something in this corner, this won't be sufficient. Since after all, the memory storing the secrets should be wiped. This means the private key needs to come from somewhere, maybe from a (EC)DH exchange - here the private should be kept and wiped. Another path to receive the secret is via some KDF (password, ...) - where in turn the input to the KDF already should be wipe-able memory.

My perspective is just doing something in here is not sufficient, and instead we should when required sit back and take a deep look what and where and how to protect secrets.