Dr.-Ing. Mario Heiderich, Cure53
Bielefelder Str. 14
D 10709 Berlin
cure53.de · mario@cure53.deAudit-Report Threema Rust Crypto Libraries 02.2022
Cure53, Dr.-Ing. M. Heiderich, Dr. A. Pirker, Dipl.-Ing. D. Gstir, R. Weinberger

Index
Introduction
Scope
Test Methodology
Miscellaneous Issues
3MA-02-001 WP1/2: Potentially insufficient protection of in-memory secrets (Info)
Conclusions

Introduction
This report - entitled 3MA-02 - details the scope, results, and conclusory summaries of acryptography review and code audit against two community-maintained libraries written
in Rust, namely the XSalsa20Poly1305 (aka crypto_secretbox) and the Rust reimplementation of the NaCl crypto_box. The work was requested by the Threema GmbHin November 2021 and initiated by Cure53 in February 2022, namely in CW06. A total ofthree days were invested to reach the coverage expected for this project.
The testing conducted for 3MA-02 was divided into two separate work packages (WPs)for execution efficiency, as follows:••

WP1: Cryptography Review against XSalsa20Poly1305 aka crypto_secretbox
WP2: Cryptography Review against re-implementation of NaCl crypto_box

Cure53 was granted source-code access to both libraries and any other pertinent
information required to complete the reviews. For these purposes, the methodology
chosen was white-box; notably, all software in scope is open-source software.
A team of four senior testers was assigned to this project’s preparation, execution, andfinalization. All preparatory actions were completed in early February 2022, namely in
CW05, to ensure that the testing phase could proceed without hindrance.

Cure53, Berlin · 02/16/22

1/8

Dr.-Ing. Mario Heiderich, Cure53
Bielefelder Str. 14
D 10709 Berlin
cure53.de · mario@cure53.deCommunications were facilitated via the dedicated Threema channel originally deployed
to combine the workspaces of Threema and Cure53 during a previous audit, thereby
allowing an optimal collaborative working environment to flourish. All participatory
personnel from both parties were invited to partake throughout the test preparations anddiscussions. One can denote that communications proceeded smoothly on the whole.
The scope was well-prepared and clear, no noteworthy roadblocks were encounteredthroughout testing, and cross-team queries were kept to a minimum as a result.
Threema delivered excellent test preparation and assisted the Cure53 team in every
respect to procure maximum coverage and depth levels for this exercise.
Cure53 gave frequent status updates concerning the test and any related findings, whilst
simultaneously offering prompt queries and receiving efficient, effective answers fromthe maintainers. Live reporting was not requested, which in hindsight proved a sufficientdecision considering the relatively low severity levels of the findings detected. Regarding
the findings in particular, the Cure53 team achieved comprehensive coverage over theWP1 and WP2 scope items, identifying a grand total of one sole finding. Positively, thiswas merely deemed a general weakness with lower exploitation potential.
Even though a small volume of findings was expected prior to the audit - owing to thehighly-specific scope and limited timeframe within which to complete testing nevertheless, that only one finding was unearthed remains a positive indication
regarding the security posture of both cryptography libraries. Furthermore, thecategorization of the miscellaneous issue with a mere Info severity rating corroborates
the strong impression gained, and should be trivially easy to address and mitigate.
The report will now shed more light on the scope and testing setup as well as provide acomprehensive breakdown of the available materials. Subsequently, the report will
outline the assigned testing methodology and then list all findings in chronological order;
first the vulnerabilities, followed by the general weaknesses detected. Each finding will
be accompanied by a technical description and Proof of Concepts (PoCs) whereapplicable, plus any relevant mitigatory or preventative advice to action.
In summation, the report will finalize with a conclusion in which the Cure53 team will
elaborate on the impressions gained toward the general security posture of the two
pertinent libraries written in Rust, giving high-level hardening advice where applicable.

Cure53, Berlin · 02/16/22

2/8

Dr.-Ing. Mario Heiderich, Cure53
Bielefelder Str. 14
D 10709 Berlin
cure53.de · mario@cure53.deScope•

Cryptography review and source code audits against two libraries written in Rust◦ WP1: Cryptography review against XSalsa20Poly1305 aka crypto_secretbox▪ All sources have been shared with Cure53 and are available as OSS• https://github.com/RustCrypto/AEADs/tree/master/xsalsa20poly1305▪ Version in scope:• 0.8.0▪ Commit in scope:• 53a4d5736a7697ab489edae9e66701c72be5bc05◦ WP2: Cryptography review against re-implementation of NaCl crypto_box▪ All sources have been shared with Cure53 and are available as OSS• https://github.com/RustCrypto/nacl-compat/tree/master/crypto_box▪ Version in scope:• 0.7.1▪ Commit in scope:•95506c5d8cce56c69a92d45a253139443131d1ac

Cure53, Berlin · 02/16/22

3/8

Dr.-Ing. Mario Heiderich, Cure53
Bielefelder Str. 14D 10709 Berlin
cure53.de · mario@cure53.de

Test Methodology
This source code audit constituted a review of two repositories implemented in Rust,
namely:••The reimplementation of NaCl crypto_box1
The XSalsa20Poly1305 aka crypto_secretbox2

The security assessment was conducted via a manual source-code inspection. Before
commencing the review, the confirmation was made that the dependencies of the crateswere out-of-scope for this audit. Therefore, only the provided source was subject totesting here.
The NaCl crypto_box pertains to a reimplementation of the Networking andCryptography library (NaCl)3 and primarily constitutes a thin wrapper layer for alternative
crates such as x25519_dalek4. The NaCl crypto_box offers an implementation to support
an elliptic-curve integrated encryption scheme, which utilizes an X25519 Diffie-Hellman
key exchange to establish a shared secret. This consequently serves as input to a keyderivation step using either HSalsa20 or HChaCha20.
The implementation utilizes this shared key as the key parameter to create an instanceof either XSalsa20Poly1305 or XChaCha20Poly1305 after key derivation. The crate wassubject to deep-dive assessments regarding the creation of both secret and keys, which
garnered a positive impression as their respective implementations were consideredsound and correct following testing. Said implementations block attackers from altering
key material after creation, and the secret is cleared after dropping. Furthermore, theDiffie-Hellman key exchange is sufficiently implemented through correct usage of thex25519_dalek crate.
The XSalsa20Poly1305 implementation corresponds to a wrapper crate for alternative
existing crates such as salsa205 and poly13056 for example, which initiates bydelegating the cryptographic computations to said crates. The verification was made thatthe implementation invokes the functions of alternate crates correctly.

https://github.com/RustCrypto/AEADs/tree/master/xsalsa20poly1305
https://github.com/RustCrypto/nacl-compat/tree/master/crypto_box
3
https://nacl.cr.yp.to/index.html
4https://docs.rs/x25519-dalek/latest/x25519_dalek/
5
https://lib.rs/crates/salsa20
6https://starry-network.github.io/starry_node/poly1305/index.html
12Cure53, Berlin · 02/16/22

4/8

Dr.-Ing. Mario Heiderich, Cure53
Bielefelder Str. 14
D 10709 Berlin
cure53.de · mario@cure53.de

Both implementations were assessed for common attack scenarios against libraries,
including:
••

•

•

Timing attacks on authentication tag comparisons for the XSalsa20Poly1305
implementation. The comparison of the authentication tag is achieved using atime-constant approach, which does not provide any side-channel information toa would-be attacker.
Absent or insufficient input-data validation, such as key-length validation andsimilar. A validation deficiency of this nature often leads to unintended usage ofthe library and therefore facilitates the proliferation of a multitude ofvulnerabilities. Due to the correct usage of Rust and fixed size arrays, the testingteam was able to confirm that the provided input data is sufficiently validated.
Sensitive information leakage via incorrectly-implemented wiping processes.
This should be considered an essential function for libraries, considering that
secret keys are utilized for encryption. Regarding this, insufficient data removal
may result in data leakage of any magnitude. Therefore, assessments weremade to determine whether the implementations correctly clear sensitive
information of any kind. Positively, one could confirm that all sensitive information
is wiped from memory. However, depending on the target platform and the use
case, some issues could potentially arise with the usage of the zeroize crate, asdetailed in ticket 3MA-02-001.
Incorrect usage of cryptographic primitives, which could have severe
consequences. On some occasions, the API of the low-level library would not be
concise enough to prevent misuse. Testing was initiated to determine whether
the cryptographic primitives offered by the dependencies - namely X25519,
XSalsa20, HSalsa20, and HChaCha Poly1305 - were integrated correctly.
Positively, no issues were detected in this area.

Cure53, Berlin · 02/16/22

5/8

Dr.-Ing. Mario Heiderich, Cure53
Bielefelder Str. 14
D 10709 Berlin
cure53.de · mario@cure53.deMiscellaneous Issues
This section covers any and all noteworthy findings that did not lead to an exploit but
might assist an attacker in successfully achieving malicious objectives in the future. Mostof these results are vulnerable code snippets that did not provide an easy way to becalled. Conclusively, while a vulnerability is present, an exploit might not always be
possible.

3MA-02-001 WP1/2: Potentially insufficient protection of in-memory secrets (Info)
Clearing secret data from memory once deprecated is a standard practice forcryptographic hygiene. Both crypto_box and xsalsa20poly1305 handle data clearance
via the zeroize7 crate. This crate ensures that any subsequent reads following azeroization of a memory region will only return zeroed memory. Additionally, it
guarantees that calls of this nature are not optimized away by the compiler. This canoccur when the compiler infers that a certain memory buffer is unutilized after thezeroization.
However, a few key facets remain uncovered by zeroize and can therefore instigate risk
depending on the threat model. Additional information is provided by the zeroize
documentation, which is briefly summarized as follows:••••

Certain Rust operations can retain unintentional copies of secrets in memory.
These include move and copy operations; heap reallocations when using Vecand String; and the instance whereby reference borrowers make copies of data.
Memory contents can be swapped to disk by the OS or included in core dumps.
Leakage via CPU registers.
Protection against microarchitectural attacks such as Meltdown8 and Spectre9.

In the vast majority of typical scenarios, the usage of zeroize to achieve a basic level ofcryptographic hygiene provides sufficient protection. However, certain use cases suchas embedded devices or shared systems whereby an attacker may have greater accessprivileges - and thus greater attack opportunities - require additional measures toachieve comprehensive prevention.
Therefore, it is recommended to analyze the use case of Threema regarding attack
vectors of this nature. Should they be considered negligible, no mitigatory action would
be needed here.
https://docs.rs/zeroize/latest/zeroize/
https://meltdownattack.com/
9https://spectreattack.com/
78

Cure53, Berlin · 02/16/22

6/8

Dr.-Ing. Mario Heiderich, Cure53
Bielefelder Str. 14
D 10709 Berlin
cure53.de · mario@cure53.deConclusions
The impressions gained during this report - which details and extrapolates on all findings
identified during the CW06 testing against two specific libraries written in Rust by theCure53 team - will now be discussed at length. To summarize, the confirmation can bemade that the scope items under scrutiny have garnered a positive impression.
This audit assessed two Rust libraries (crates) entitled xsalsa20poly1305 (version 0.8.0)
and crypto_box (version 0.7.1). Both libraries are components of the RustCrypto GitHubgroup, which aims to implement cryptography in pure Rust. Both crates are intended as
replacements for the crypto_secretbox* and crypto_box* functions of the NaCl C library.
The primary objective of this audit was to assess the cryptographic accuracy of theselibraries and their functional compatibility to NaCl. Compositionally, the libraries in scopeare essentially wrapper crates for other cryptographic libraries. Dependencies that
implement the basic cryptographic primitives - such as Salsa20, X25519, and Poly1305 were not in scope for this audit.
The Cure53 testing team was in constant communication with the customer throughout
the audit, frequently relaying status updates and raising any queries or concerns whenneeded. The usage of the dedicated Threema channel proved efficient and effective,
with assistance provided whenever requested. Positively, no vulnerabilities or othersevere issues could be identified during the allotted time frame of this audit. Bothlibraries appear constitutionally sound and carefully written to prevent any common
issues that blight cryptographic libraries in general.
The auditors inspected the provided source code for typical vulnerabilities relating tocryptographic implementations such as timing attacks, improper input sanitization andvalidation, and sensitive data leakage to memory. In all of these areas,
xsalsa20poly1305 and crypto_box withheld well to scrutiny, deterring any kind ofvulnerability or weakness. All sensitive data for buffers allocated by the code issufficiently wiped after use, or delegates for wiping when de-initialized by the Rust
runtime using the zeroize crate. Furthermore, the generation of cryptographicallysensitive information such as secret keys for the X25519 curve and nonces, for example,
appear sound and utilize robust random-number generators. Finally, secret-key usage even though ‘unclamped’ upon generation (similarly to other libraries such asx25519_dalek) - is implemented correctly. This owes to the clamping operation
performed on the x25519_dalek crate’s x25519 function.

Cure53, Berlin · 02/16/22

7/8

Dr.-Ing. Mario Heiderich, Cure53
Bielefelder Str. 14
D 10709 Berlin
cure53.de · mario@cure53.deWhile the code integrates common patterns to avoid sensitive information leakage, onemust note that Rust is considered a programming language still in relative infancy that
undergoes heavy and recurrent development. Any alterations made to the Rust compiler- particularly pertaining to the optimization logic - could therefore undermine thesemitigations.
In summary, excellent coverage over both work packages has been achieved, with thepositive outcome of one sole miscellaneous issue unearthed. Moving forward, from acryptography and security viewpoint it is highly recommended to perform deep-dive codeassessments against those referred dependencies, as the core functionality of bothcrates lies within them.
Cure53 would like to thank Silvan Engeler, Manuel Kasper and Danilo Bargen from theThreema team for their excellent project coordination, support and assistance, both
before and during this assignment.

Cure53, Berlin · 02/16/22

8/8