blog.robur.coop/articles/speeding-ec-string.html
2024-10-04 10:48:33 +00:00

82 lines
12 KiB
HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>
Robur's blogSpeeding elliptic curve cryptography
</title>
<meta name="description" content="How we improved the performance of elliptic curves by only modifying the underlying byte array">
<link type="text/css" rel="stylesheet" href="https://blog.robur.coop/css/hl.css">
<link type="text/css" rel="stylesheet" href="https://blog.robur.coop/css/style.css">
<script src="https://blog.robur.coop/js/hl.js"></script>
<link rel="alternate" type="application/rss+xml" href="https://blog.robur.coop/feed.xml" title="blog.robur.coop">
</head>
<body>
<header>
<h1>blog.robur.coop</h1>
<blockquote>
The <strong>Robur</strong> cooperative blog.
</blockquote>
</header>
<main><a href="https://blog.robur.coop/index.html">Back to index</a>
<article>
<h1>Speeding elliptic curve cryptography</h1>
<ul class="tags-list"><li>OCaml</li><li>MirageOS</li><li>cryptography</li><li>security</li></ul><p>TL;DR: replacing cstruct with string, we gain a factor of 2.5 in performance.</p>
<h2 id="mirage-crypto-ec"><a class="anchor" aria-hidden="true" href="#mirage-crypto-ec"></a>Mirage-crypto-ec</h2>
<p>In April 2021 We published our implementation of <a href="https://hannes.robur.coop/Posts/EC">elliptic curve cryptography</a> (as <code>mirage-crypto-ec</code> opam package) - this is DSA and DH for NIST curves P224, P256, P384, and P521, and also Ed25519 (EdDSA) and X25519 (ECDH). We use <a href="https://github.com/mit-plv/fiat-crypto/">fiat-crypto</a> for the cryptographic primitives, which emits C code that by construction is correct (note: earlier we stated &quot;free of timing side-channels&quot;, but this is a huge challenge, and as <a href="https://discuss.systems/@edwintorok/111925959867297453">reported by Edwin Török</a> likely impossible on current x86 hardware). More C code (such as <code>point_add</code>, <code>point_double</code>, and further 25519 computations including tables) have been taken from the BoringSSL code base. A lot of OCaml code originates from our TLS 1.3 work in 2018, where Etienne Millon, Nathan Rebours, and Clément Pascutto interfaced <a href="https://github.com/mirage/fiat/">elliptic curves for OCaml</a> (with the goal of being usable with MirageOS).</p>
<p>The goal of mirage-crypto-ec was: develop elliptic curve support for OCaml &amp; MirageOS quickly - which didn't leave much time to focus on performance. As time goes by, our mileage varies, and we're keen to use fewer resources - and thus fewer CPU time and a smaller memory footprint is preferable.</p>
<h2 id="memory-allocation-and-calls-to-c"><a class="anchor" aria-hidden="true" href="#memory-allocation-and-calls-to-c"></a>Memory allocation and calls to C</h2>
<p>OCaml uses managed memory with a generational copying collection. To safely call a C function at any point in time when the arguments are OCaml values (memory allocated on the OCaml heap), it is crucial that while the C function is executed, the arguments should stay at the same memory location, and not being moved by the GC. Otherwise the C code may be upset retrieving wrong data or accessing unmapped memory.</p>
<p>There are several strategies to achieve this, ranging from &quot;let's use another memory area where the GC doesn't mess around with&quot;, &quot;do not run any GC while executing the C code&quot; (read further in the OCaml <a href="https://v2.ocaml.org/releases/4.14/htmlman/intfc.html#ss:c-direct-call">cheaper C calls</a> manual), &quot;deeply copy the arguments to a non-moving memory area before executing C code&quot;, and likely others.</p>
<p>For our elliptic curve operations, the C code is pretty simple - there are no memory allocations happening in C, neither are exceptions raised. Also, the execution time of the code is constant and pretty small.</p>
<h2 id="ocaml-cstruct"><a class="anchor" aria-hidden="true" href="#ocaml-cstruct"></a>ocaml-cstruct</h2>
<p>In the <a href="https://mirage.io">MirageOS</a> ecosystem, a core library is <a href="https://github.com/mirage/ocaml-cstruct">cstruct</a> - which purpose is manifold: provide ppx rewriters to define C structure layouts in OCaml (getter/setter functions are generated), as well as enums; also a fundamental idea is to use OCaml bigarray which is non-moving memory not allocated on the OCaml heap but directly by calling <code>malloc</code>. The memory can even be page-aligned, as required by some C software, such as Xen. Convenient functionality, such as &quot;retrieve a big-endian unsigned 32 bit integer from offset X in this buffer&quot; are provided as well.</p>
<p>But there's a downside to it - as time moves along, Xen is no longer the only target for MirageOS, and other virtualization mechanisms (such as KVM / virtio) do not require page-aligned memory ranges that are retained at a given memory address. It also turns out that cstruct spends a lot of time in bounds checks. Another huge downside is that OCaml tooling (such as statmemprof) was for a long time (maybe still is not?) unaware of out-of-OCaml-GC allocated memory (cstruct uses bigarray as underlying buffer). Freeing up the memory requires finalizers to be executed - after all pretty tedious (expensive) and against the OCaml runtime philosophy.</p>
<p>As time moves forward, also the OCaml standard library got support for (a) strings are immutable byte vectors now (since 4.06 - released in 2017 -- there's as well an interface for mutable/immutable cstruct, but that is not used as far as I can tell), (b) retrieve a certain amount of octets in a string or byte as (unsigned) integer number (since 4.08 - released in 2019, while some additional functionality is only available in 4.13).</p>
<p>Still, bigarrays are necessary in certain situations - if you need to have a non-moving (shared) area of memory, as in the Xen interface, but also e.g. when you compute in parallel in different processes, or when you need mmap()ed files.</p>
<h2 id="putting-it-together"><a class="anchor" aria-hidden="true" href="#putting-it-together"></a>Putting it together</h2>
<p>Already in October 2021, Romain <a href="https://github.com/mirage/mirage-crypto/pull/146">proposed</a> to not use cstruct, but bytes for mirage-crypto-ec. The PR was sitting around since there were benchmarks missing, and developer time was small. But recently, Virgile Robles <a href="https://github.com/mirage/mirage-crypto/pull/191">proposed</a> another line of work to use pre-computed tables for NIST curves to speed up the elliptic curve cryptography. Conducting performance evaluation resulted that the &quot;use bytes instead of cstruct&quot; combined with pre-computed tables made a huge difference (factor of 6) compared to the latest release.</p>
<p>To ease reviewing changes, we decided to focus on landing the &quot;use bytes instead of cstruct&quot; first, and gladly Pierre Alain had already rebased the existing patch onto the latest release of mirage-crypto-ec. We also went further and use string where applicable instead of bytes. For safety reasons we also introduced an API layer which (a) allocates a byte vector for the result (b) calls the primitive, and (c) transforms the byte vector into an immutable string. This API is more in line with functional programming (immutable values), and since allocations and deallocations of values are cheap, there's no measurable performance decrease.</p>
<p>All the changes are internal, there's no external API that needs to be adjusted - still there's at the API boundary one conversion of cstruct to string (and back for the return value) done.</p>
<p>We used <code>perf</code> to construct some flame graphs (of the ECDSA P256 sign), shown below.</p>
<p><img src="../images/trace-cstruct-440.svg" alt="Flamegraph of ECDSA sign with cstruct" ></p>
<p>The flame graph of P256 ECDSA sign using the mirage-crypto release 0.11.2. The majority of time is spent in &quot;do_sign&quot;, which calls <code>inv</code> (inversion), <code>scalar_mult</code> (majority of time), and <code>x_of_finite_point_mod_n</code>. The scalar multiplication spends time in <code>add</code>, <code>double</code> and <code>select</code>. Several towers starting at <code>Cstruct.create_919</code> are visible.</p>
<p>With PR#146, the flame graph looks different:</p>
<p><img src="../images/trace-string-770.svg" alt="Flamegraph of ECDSA sign with string" ></p>
<p>Now, the allocation towers do not exist anymore. The time of a sign operation is spend in <code>inv</code>, <code>scalar_mult</code>, and <code>x_of_finite_point_mod_n</code>. There's still room for improvements in these operations.</p>
<h2 id="performance-numbers"><a class="anchor" aria-hidden="true" href="#performance-numbers"></a>Performance numbers</h2>
<p>All numbers were gathered on a Lenovo X250 laptop with a Intel i7-5600U CPU @ 2.60GHz. We used OCaml 4.14.1 as compiler. The baseline is OpenSSL 3.0.12. All numbers are in operations per second.</p>
<p>NIST P-256</p>
<p>| op | 0.11.2 | PR#146 | speedup | OpenSSL | speedup |
| - | - | - | - | - | - |
| sign | 748 | 1806 | 2.41x | 34392 | 19.04x |
| verify | 285 | 655 | 2.30x | 12999 | 19.85x |
| ecdh | 858 | 1785 | 2.08x | 16514 | 9.25x |</p>
<p>Curve 25519</p>
<p>| op | 0.11.2 | PR#146 | speedup | OpenSSL | speedup |
| - | - | - | - | - | - |
| sign | 10713 | 11560 | 1.08x | 21943 | 1.90x |
| verify | 7600 | 8314 | 1.09x | 7081 | 0.85x |
| ecdh | 12144 | 13457 | 1.11x | 26201 | 1.95x |</p>
<p>Note: to re-create the performance numbers, you can run <code>openssl speed ecdsap256 ecdhp256 ed25519 ecdhx25519</code> - for the OCaml site, use <code>dune bu bench/speed.exe --rel</code> and <code>_build/default/bench/speed.exe ecdsa-sign ecdsa-verify ecdh-share</code>.</p>
<p>The performance improvements are up to 2.5 times compared to the latest mirage-crypto-ec release (look at the 4th column). In comparison to OpenSSL, we still lack a factor of 20 for the NIST curves, and up to a factor of 2 for 25519 computations (look at the last column).</p>
<p>If you have ideas for improvements, let us know via an issue, eMail, or a pull request :) We started to <a href="https://github.com/mirage/mirage-crypto/issues/193">gather some</a> for 25519 by comparing our code with changes in BoringSSL over the last years.</p>
<p>As a spoiler, for P-256 sign there's another improvement of around 4.5 with <a href="https://github.com/mirage/mirage-crypto/pull/191">Virgile's PR</a> using pre-computed tables also for NIST curves.</p>
<h2 id="the-road-ahead-for-2024"><a class="anchor" aria-hidden="true" href="#the-road-ahead-for-2024"></a>The road ahead for 2024</h2>
<p>Remove all cstruct, everywhere, apart from in mirage-block-xen and mirage-net-xen ;). It was a fine decision in the early MirageOS days, but from a performance point of view, and for making our packages more broadly usable without many dependencies, it is time to remove cstruct. Earlier this year we already <a href="https://github.com/mirage/ocaml-tar/pull/137">removed cstruct from ocaml-tar</a> for similar reasons.</p>
<p>Our MirageOS work is only partially funded, we cross-fund our work by commercial contracts and public (EU) funding. We are part of a non-profit company, you can make a (tax-deducable - at least in the EU) <a href="https://aenderwerk.de/donate/">donation</a> (select &quot;DONATION robur&quot; in the dropdown menu).</p>
<p>We're keen to get MirageOS deployed in production - if you would like to do that, don't hesitate to reach out to us via eMail team at robur.coop</p>
</article>
</main>
<footer>
<a href="https://github.com/xhtmlboi/yocaml">Powered by <strong>YOCaml</strong></a>
<br />
</footer>
<script>hljs.highlightAll();</script>
</body>
</html>