Skip to content

Commit 38acde5

Browse files
rbenzingclaude
andcommitted
release: v2.7.0 — key-handling and Double Ratchet security fixes
Fixes two critical key-handling defects, three Double Ratchet deviations from the Signal specification, and a password-KDF weakness. Critical: - KeyConversion identified key format by trial validation. Ed25519 and X25519 public keys are both 32 opaque bytes and ~12.4% of X25519 keys (2486/20000 measured) also decode as valid Ed25519 points, so that fraction was silently converted into a different key. Added an explicit ConvertPublicKeyToX25519(key, inputIsEd25519) and made device lookup match the sender hint verbatim before attempting conversion. - CryptoProvider.ConvertEd25519PrivateKeyToX25519 returned the caller's array for 32-byte input; all four call sites clear the result in a finally, so the call zeroed the live private key. Returns a copy now. Protocol: - Standard rotation strategy no longer rotates the DH ratchet key on a send counter. Rotating before the peer holds the new key diverges the DH inputs and permanently breaks the session. - Implemented the PN header field (EncryptedMessage.PreviousChainLength) and SkipReceiverMessageKeys, so messages arriving out of order across a ratchet step are recoverable instead of lost. - Stopped retaining used message keys in SentMessages, which is serialized to disk and defeated forward secrecy. Also: per-key random Argon2id salt for password-protected key storage (breaking blob-layout change), full 12-entry X25519 small-order point blocklist replacing one that decoded a hex string as base64 and could never match, full deep-clone of session key material, secure-clear of superseded root/chain/ratchet keys, age-ordered skipped-key eviction, and a nonce overload that threw on every call. Repo housekeeping: move CLAUDE.md to .claude/CLAUDE.md and ignore docs/superpowers and docs/plans. Build clean (0 warnings, 0 errors). 546/546 tests pass on net8.0 and net10.0; the previously intermittent multi-device sync test now passes 6/6 consecutive isolated runs. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 988ccd6 commit 38acde5

14 files changed

Lines changed: 441 additions & 99 deletions

File tree

File renamed without changes.

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
*.user
1010
*.userosscache
1111
*.sln.docstates
12+
docs/superpowers/*
13+
docs/plans/*
1214

1315
# User-specific files (MonoDevelop/Xamarin Studio)
1416
*.userprefs

‎CHANGELOG.md‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,71 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
## [2.7.0] - 2026-08-02
11+
12+
Security and protocol-correctness release. Fixes two key-handling defects that could zero or
13+
corrupt live private keys, three Double Ratchet deviations from the Signal specification, and a
14+
password-KDF weakness. All 546 unit tests pass on `net8.0` and `net10.0`.
15+
16+
### Added
17+
- **Double Ratchet `PN` header field**: `EncryptedMessage.PreviousChainLength` and
18+
`DoubleRatchetSession.PreviousSendChainLength` implement the Signal header's previous-chain-length
19+
field, which is required to recover message keys left unclaimed in a receiving chain when a DH
20+
ratchet step replaces it. Absent on messages from older versions, where it defaults to `0`.
21+
- **Explicit key-format conversion**: `KeyConversion.ConvertPublicKeyToX25519(byte[], bool inputIsEd25519)`
22+
converts a public key using a caller-declared format instead of guessing. Prefer it over the
23+
format-sniffing `ConvertEd25519PublicKeyToX25519(byte[])`.
24+
25+
### Fixed
26+
- **Ed25519/X25519 key type confusion (critical)**: `KeyConversion.ConvertEd25519PublicKeyToX25519()`
27+
identified a key's format by trying Ed25519 validation first. Ed25519 and X25519 public keys are
28+
both 32 opaque bytes, and roughly **12.4%** of X25519 public keys (measured 2 486 / 20 000) also
29+
decode as valid Ed25519 points, so that fraction of already-X25519 keys was silently converted into
30+
a different key. `DeviceManager.ProcessSyncMessage()` now matches a sender hint against the stored
31+
key verbatim before attempting any conversion, making device lookup deterministic. This was the
32+
cause of intermittent `MultiDeviceSynchronization_ShouldRecoverFromMessageLoss` failures.
33+
- **Private key destroyed by its own callers (critical)**: `CryptoProvider.ConvertEd25519PrivateKeyToX25519()`
34+
returned the caller's array unchanged when given a 32-byte key. All four call sites clear the
35+
returned buffer in a `finally` block, so the call zeroed the live device/identity private key. It
36+
now returns a copy. `MailboxManager` likewise no longer aliases `_identityKeyPair.PrivateKey`.
37+
- **Unilateral ratchet rotation broke sessions**: `KeyRotationStrategy.Standard` rotated the sender's
38+
DH ratchet key every 20 messages regardless of whether the peer had received it. A DH ratchet step
39+
is only valid as a *response* to a new peer ratchet key; when both parties rotated before receiving
40+
the other's key, their DH inputs diverged and the session became permanently unrecoverable.
41+
Rotation is now driven solely by `Decrypt()` on receipt of a new `SenderDHKey`.
42+
- **Out-of-order messages lost across ratchet steps**: `SkipReceiverMessageKeysAsync()` was a no-op.
43+
It is replaced by `SkipReceiverMessageKeys()`, which uses the new `PN` field to derive and retain
44+
the unclaimed keys of the outgoing chain before it is discarded.
45+
- **Sent message keys retained (forward secrecy)**: `Encrypt()` stored up to 100 used message keys in
46+
`DoubleRatchetSession.SentMessages`, which is serialized to disk. Anyone obtaining a persisted
47+
session could decrypt previously sent traffic. Message keys are no longer retained after use.
48+
- **Fixed application-wide Argon2id salt**: `StoreKeyAsync()`/`RetrieveKeyAsync()` derived their
49+
encryption key with a hardcoded salt, so every user sharing a password shared an encryption key and
50+
a single precomputation table applied to all installations. Each stored key now carries a fresh
51+
random 16-byte salt. **Breaking:** the stored blob layout changed from `nonce‖ciphertext` to
52+
`salt‖nonce‖ciphertext`; password-protected keys written by earlier versions cannot be read.
53+
- **X25519 small-order point blocklist was inert**: one of the three entries in
54+
`Sodium.SMALL_ORDER_POINTS` was a hex string passed to `Convert.FromBase64String()`, decoding to 48
55+
bytes and therefore never matching a 32-byte key. Replaced with the full 12-entry libsodium
56+
blacklist, hex-decoded, including the non-canonical high-bit-set encodings.
57+
- **Session clone shared key material**: `DeepCloneSession()` copied every byte array except
58+
`RootKey` and the ratchet key pair, which were shared by reference — so clearing the clone destroyed
59+
the caller's session state. All arrays are now copied.
60+
- **Superseded keys left in memory**: retired root keys, chain keys, ratchet private keys, evicted
61+
skipped-message keys, and decrypted plaintext buffers are now zeroed via `SecureMemory.SecureClear()`
62+
on both success and failure paths.
63+
- **Skipped-key eviction order**: the skipped-message-key cache evicted via `Dictionary.Keys.Take()`,
64+
whose enumeration order is unspecified and unrelated to age. Eviction is now ordered by message
65+
number, and every evicted key is zeroed.
66+
- **Skipped-key consumption on failure**: a skipped message key was removed from the cache before
67+
decryption was attempted, discarding it if decryption failed. It is now consumed only on success.
68+
- **`Nonce.GenerateNonce(ReadOnlySpan<byte>, uint)` always threw**: the method allocated a
69+
`Constants.NONCE_SIZE` (12-byte) buffer and then sliced `[..16]`, guaranteeing
70+
`ArgumentOutOfRangeException`. The salt buffer is now sized independently of the nonce.
71+
- **Redundant key copies in `AES`**: `Decrypt()` called `key.ToArray()` twice — once purely as a null
72+
check on a freshly allocated array, which can never be null — leaving both copies of the key on the
73+
heap unzeroed. Both `Encrypt()` and `Decrypt()` now use a single copy, cleared in a `finally`.
74+
1075
## [2.6.2] - 2026-06-19
1176

1277
### Added

‎Directory.Build.props‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<Copyright>Copyright © $(Company) $([System.DateTime]::Now.Year)</Copyright>
77
<Authors>Russell Benzing</Authors>
88
<Company>Russell Benzing Inc</Company>
9-
<VersionPrefix>2.6.2</VersionPrefix>
9+
<VersionPrefix>2.7.0</VersionPrefix>
1010
<VersionSuffix></VersionSuffix>
1111
<PackageLicenseExpression>MIT</PackageLicenseExpression>
1212
<PackageProjectUrl>https://github.com/rbenzing/LibEmiddle</PackageProjectUrl>

‎LibEmiddle.Domain/DoubleRatchetSession.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,14 @@ public class DoubleRatchetSession
6262
/// </summary>
6363
public uint ReceiveMessageNumber { get; set; }
6464

65+
/// <summary>
66+
/// Gets or sets the number of messages sent in the previous sending chain, i.e. the value
67+
/// <see cref="SendMessageNumber"/> held immediately before the most recent DH ratchet step.
68+
/// Emitted on outgoing messages as the Double Ratchet header's <c>PN</c> field so the peer
69+
/// can drain its old receiving chain before replacing it.
70+
/// </summary>
71+
public uint PreviousSendChainLength { get; set; }
72+
6573
/// <summary>
6674
/// Gets or sets the dictionary of message keys for sent messages.
6775
/// Used for handling out-of-order messages.

‎LibEmiddle.Domain/EncryptedMessage.cs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,17 @@ public class EncryptedMessage
3939
/// </summary>
4040
public uint SenderMessageNumber { get; set; }
4141

42+
/// <summary>
43+
/// Gets or sets the number of messages the sender sent in the PREVIOUS sending chain
44+
/// before performing the DH ratchet step that produced <see cref="SenderDHKey"/>.
45+
/// This is the Double Ratchet header's <c>PN</c> field: it tells the receiver how many
46+
/// message keys remain unclaimed in the old receiving chain so they can be derived and
47+
/// retained before the chain is replaced. Without it, messages that arrive out of order
48+
/// across a ratchet step are permanently undecryptable.
49+
/// Defaults to 0 for messages produced before this field existed.
50+
/// </summary>
51+
public uint PreviousChainLength { get; set; }
52+
4253
/// <summary>
4354
/// Gets or sets the encrypted message content.
4455
/// </summary>
@@ -74,6 +85,7 @@ public EncryptedMessage Clone()
7485
SenderIdentityKey = SenderIdentityKey?.ToArray(),
7586
SenderDHKey = SenderDHKey?.ToArray(),
7687
SenderMessageNumber = SenderMessageNumber,
88+
PreviousChainLength = PreviousChainLength,
7789
Ciphertext = Ciphertext?.ToArray(),
7890
Nonce = Nonce?.ToArray(),
7991
Timestamp = Timestamp,
@@ -130,6 +142,7 @@ public int GetEstimatedSize()
130142

131143
// Other fields
132144
size += sizeof(uint); // SenderMessageNumber
145+
size += sizeof(uint); // PreviousChainLength
133146
size += sizeof(long); // Timestamp
134147

135148
// Headers
@@ -214,6 +227,19 @@ public static EncryptedMessage FromDictionary(Dictionary<string, object>? dictio
214227
}
215228
}
216229

230+
// Handle PreviousChainLength (Double Ratchet PN); absent on legacy messages
231+
if (dictionary.TryGetValue("PreviousChainLength", out var pnObj))
232+
{
233+
message.PreviousChainLength = pnObj switch
234+
{
235+
uint pn => pn,
236+
int intPn when intPn >= 0 => (uint)intPn,
237+
long longPn when longPn >= 0 && longPn <= uint.MaxValue => (uint)longPn,
238+
string pnStr when uint.TryParse(pnStr, out uint parsedPn) => parsedPn,
239+
_ => throw new FormatException("Invalid PreviousChainLength format")
240+
};
241+
}
242+
217243
// Optional fields with defaults
218244
if (dictionary.TryGetValue("Timestamp", out var timestampObj))
219245
{
@@ -346,6 +372,7 @@ public Dictionary<string, object> ToDictionary()
346372
["Ciphertext"] = Convert.ToBase64String(Ciphertext),
347373
["Nonce"] = Convert.ToBase64String(Nonce),
348374
["SenderMessageNumber"] = SenderMessageNumber,
375+
["PreviousChainLength"] = PreviousChainLength,
349376
["SenderDHKey"] = Convert.ToBase64String(SenderDHKey),
350377
["Timestamp"] = Timestamp
351378
};

‎LibEmiddle/Core/KeyConversion.cs‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,5 +50,48 @@ public static byte[] ConvertEd25519PublicKeyToX25519(byte[] ed25519PublicKey)
5050
"Invalid public key — neither Ed25519 nor X25519 validation passed.",
5151
nameof(ed25519PublicKey));
5252
}
53+
54+
/// <summary>
55+
/// Converts a public key to X25519 format using an explicitly declared input format.
56+
/// </summary>
57+
/// <remarks>
58+
/// Prefer this over <see cref="ConvertEd25519PublicKeyToX25519(byte[])"/> whenever the
59+
/// caller knows the key's format. Ed25519 and X25519 public keys are both 32 opaque bytes
60+
/// and cannot be reliably told apart by inspection: roughly one in eight X25519 public keys
61+
/// also decodes as a valid Ed25519 point, so format sniffing silently converts those keys
62+
/// into a different (wrong) key.
63+
/// </remarks>
64+
/// <param name="publicKey">A 32-byte public key.</param>
65+
/// <param name="inputIsEd25519">
66+
/// True when <paramref name="publicKey"/> is an Ed25519 key that must be converted;
67+
/// false when it is already an X25519 key and should only be validated and copied.
68+
/// </param>
69+
/// <returns>The key in X25519 format.</returns>
70+
/// <exception cref="ArgumentNullException">Thrown when <paramref name="publicKey"/> is null.</exception>
71+
/// <exception cref="ArgumentException">Thrown when the key length is wrong or validation fails.</exception>
72+
public static byte[] ConvertPublicKeyToX25519(byte[] publicKey, bool inputIsEd25519)
73+
{
74+
ArgumentNullException.ThrowIfNull(publicKey);
75+
76+
if (publicKey.Length != Constants.ED25519_PUBLIC_KEY_SIZE)
77+
{
78+
throw new ArgumentException(
79+
$"Invalid public key length: {publicKey.Length}. Expected 32 bytes.",
80+
nameof(publicKey));
81+
}
82+
83+
if (inputIsEd25519)
84+
{
85+
if (!Sodium.ValidateEd25519PublicKey(publicKey))
86+
throw new ArgumentException("Key failed Ed25519 validation.", nameof(publicKey));
87+
88+
return Sodium.ConvertEd25519PublicKeyToX25519(publicKey);
89+
}
90+
91+
if (!Sodium.ValidateX25519PublicKey(publicKey))
92+
throw new ArgumentException("Key failed X25519 validation.", nameof(publicKey));
93+
94+
return (byte[])publicKey.Clone();
95+
}
5396
}
5497
}

‎LibEmiddle/Core/Sodium.cs‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1573,12 +1573,35 @@ public static bool ValidateX25519PublicKey(ReadOnlySpan<byte> x25519PublicKey)
15731573
return true;
15741574
}
15751575

1576-
private static readonly byte[][] SMALL_ORDER_POINTS = {
1577-
new byte[32], // All zeros
1578-
Convert.FromBase64String("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE="), // Order 2
1579-
Convert.FromBase64String("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"), // Order 8
1580-
// Add other small order points
1581-
};
1576+
/// <summary>
1577+
/// The complete set of X25519 small-order / low-order public keys that must be rejected,
1578+
/// as published by libsodium (crypto_scalarmult_curve25519_ref10 blacklist). Values are
1579+
/// hex-encoded; a previous revision parsed one of these as base64, which silently produced
1580+
/// a 48-byte array that could never match a 32-byte key.
1581+
/// </summary>
1582+
private static readonly byte[][] SMALL_ORDER_POINTS =
1583+
[
1584+
// 0 (order 1)
1585+
Convert.FromHexString("0000000000000000000000000000000000000000000000000000000000000000"),
1586+
// 1 (order 1)
1587+
Convert.FromHexString("0100000000000000000000000000000000000000000000000000000000000000"),
1588+
// 325606250916557431795983626356110631294008115727848805560023387167927233504 (order 8)
1589+
Convert.FromHexString("e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800"),
1590+
// 39382357235489614581723060781553021112529911719440698176882885853963445705823 (order 8)
1591+
Convert.FromHexString("5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157"),
1592+
// p-1 (order 2)
1593+
Convert.FromHexString("ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"),
1594+
// p (order 4)
1595+
Convert.FromHexString("edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"),
1596+
// p+1 (order 1)
1597+
Convert.FromHexString("eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"),
1598+
// Non-canonical encodings of the above with the high bit set
1599+
Convert.FromHexString("cdeb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b8ff"),
1600+
Convert.FromHexString("4c9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7"),
1601+
Convert.FromHexString("d9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
1602+
Convert.FromHexString("daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
1603+
Convert.FromHexString("dbffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
1604+
];
15821605

15831606
/// <summary>
15841607
/// Signs a message using Ed25519.

‎LibEmiddle/Crypto/AES.cs‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,18 @@ public static EncryptedMessage Encrypt(string message, ReadOnlySpan<byte> key)
114114

115115
byte[] plaintext = Encoding.UTF8.GetBytes(message); // Changed from Encoding.Default
116116
byte[] nonce = Nonce.GenerateNonce();
117-
byte[] ciphertext = AESEncrypt(plaintext, key.ToArray(), nonce);
117+
118+
byte[] keyCopy = key.ToArray();
119+
byte[] ciphertext;
120+
try
121+
{
122+
ciphertext = AESEncrypt(plaintext, keyCopy, nonce);
123+
}
124+
finally
125+
{
126+
SecureMemory.SecureClear(keyCopy);
127+
SecureMemory.SecureClear(plaintext);
128+
}
118129

119130
return new EncryptedMessage
120131
{
@@ -136,14 +147,18 @@ public static string Decrypt(EncryptedMessage encryptedMessage, ReadOnlySpan<byt
136147
ArgumentNullException.ThrowIfNull(encryptedMessage, nameof(encryptedMessage));
137148
ArgumentNullException.ThrowIfNull(encryptedMessage.Ciphertext, "Ciphertext cannot be null");
138149
ArgumentNullException.ThrowIfNull(encryptedMessage.Nonce, "Nonce cannot be null");
139-
ArgumentNullException.ThrowIfNull(key.ToArray(), nameof(key));
140150

141151
if (key.Length != Constants.AES_KEY_SIZE)
142152
throw new ArgumentException($"Key must be {Constants.AES_KEY_SIZE} bytes long", nameof(key));
143153

154+
// Single working copy of the key, zeroed on every path. The previous code called
155+
// key.ToArray() twice — once purely as a null check on a freshly allocated array,
156+
// which can never be null — and left both copies of the key on the heap.
157+
byte[] keyCopy = key.ToArray();
158+
144159
try
145160
{
146-
byte[] plaintext = AESDecrypt(encryptedMessage.Ciphertext, key.ToArray(), encryptedMessage.Nonce);
161+
byte[] plaintext = AESDecrypt(encryptedMessage.Ciphertext, keyCopy, encryptedMessage.Nonce);
147162

148163
// Validate the plaintext before converting to string
149164
if (plaintext == null || plaintext.Length == 0)
@@ -168,6 +183,10 @@ public static string Decrypt(EncryptedMessage encryptedMessage, ReadOnlySpan<byt
168183
{
169184
throw new CryptographicException("Message decryption failed. The key may be incorrect.", ex);
170185
}
186+
finally
187+
{
188+
SecureMemory.SecureClear(keyCopy);
189+
}
171190
}
172191

173192
/// <summary>

0 commit comments

Comments
 (0)