<ulclass="tags-list"><li><ahref="/tags.html#tag-OCaml">OCaml</a></li><li><ahref="/tags.html#tag-MirageOS">MirageOS</a></li><li><ahref="/tags.html#tag-cryptography">cryptography</a></li><li><ahref="/tags.html#tag-security">security</a></li></ul><p>TL;DR: replacing cstruct with string, we gain a factor of 2.5 in performance.</p>
<p>In April 2021 We published our implementation of <ahref="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 <ahref="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 "free of timing side-channels", but this is a huge challenge, and as <ahref="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 <ahref="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 & 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>
<h2id="memory-allocation-and-calls-to-c"><aclass="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 "let's use another memory area where the GC doesn't mess around with", "do not run any GC while executing the C code" (read further in the OCaml <ahref="https://v2.ocaml.org/releases/4.14/htmlman/intfc.html#ss:c-direct-call">cheaper C calls</a> manual), "deeply copy the arguments to a non-moving memory area before executing C code", 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>
<p>In the <ahref="https://mirage.io">MirageOS</a> ecosystem, a core library is <ahref="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 "retrieve a big-endian unsigned 32 bit integer from offset X in this buffer" 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>
<h2id="putting-it-together"><aclass="anchor"aria-hidden="true"href="#putting-it-together"></a>Putting it together</h2>
<p>Already in October 2021, Romain <ahref="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 <ahref="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 "use bytes instead of cstruct" 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 "use bytes instead of cstruct" 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><imgsrc="../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 "do_sign", 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><imgsrc="../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>
<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>
<divrole="region"><table>
<tr>
<th>op</th>
<th>0.11.2</th>
<th>PR#146</th>
<th>speedup</th>
<th>OpenSSL</th>
<th>speedup</th>
</tr>
<tr>
<td>sign</td>
<td>748</td>
<td>1806</td>
<td>2.41x</td>
<td>34392</td>
<td>19.04x</td>
</tr>
<tr>
<td>verify</td>
<td>285</td>
<td>655</td>
<td>2.30x</td>
<td>12999</td>
<td>19.85x</td>
</tr>
<tr>
<td>ecdh</td>
<td>858</td>
<td>1785</td>
<td>2.08x</td>
<td>16514</td>
<td>9.25x</td>
</tr>
</table></div><p>Curve 25519</p>
<divrole="region"><table>
<tr>
<th>op</th>
<th>0.11.2</th>
<th>PR#146</th>
<th>speedup</th>
<th>OpenSSL</th>
<th>speedup</th>
</tr>
<tr>
<td>sign</td>
<td>10713</td>
<td>11560</td>
<td>1.08x</td>
<td>21943</td>
<td>1.90x</td>
</tr>
<tr>
<td>verify</td>
<td>7600</td>
<td>8314</td>
<td>1.09x</td>
<td>7081</td>
<td>0.85x</td>
</tr>
<tr>
<td>ecdh</td>
<td>12144</td>
<td>13457</td>
<td>1.11x</td>
<td>26201</td>
<td>1.95x</td>
</tr>
</table></div><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 <ahref="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 <ahref="https://github.com/mirage/mirage-crypto/pull/191">Virgile's PR</a> using pre-computed tables also for NIST curves.</p>
<h2id="the-road-ahead-for-2024"><aclass="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 <ahref="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-deductable - at least in the EU) <ahref="https://aenderwerk.de/donate/">donation</a> (select "DONATION robur" 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>
<ahref="https://github.com/xhtmlboi/yocaml">Powered by <strong>YOCaml</strong></a>