initial commit
Some checks failed
CI / lint (push) Successful in 1m37s
CI / test-python (push) Successful in 1m49s
CI / test-zig (push) Successful in 1m39s
CI / test-wasm (push) Successful in 1m54s
CI / test (push) Successful in 14m44s
CI / miri (push) Successful in 14m18s
CI / build (push) Successful in 1m9s
CI / fuzz-regression (push) Successful in 9m9s
CI / publish (push) Failing after 1m10s
CI / publish-python (push) Failing after 1m46s
CI / publish-wasm (push) Has been cancelled

Signed-off-by: Kamal Tufekcic <kamal@lo.sh>
This commit is contained in:
Kamal Tufekcic 2026-04-02 23:48:10 +03:00
commit 1d99048c95
No known key found for this signature in database
165830 changed files with 79062 additions and 0 deletions

View file

@ -0,0 +1,48 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::primitives::argon2::{argon2id, Argon2Params};
fuzz_target!(|data: &[u8]| {
// Wire layout: [m_cost (4)] [t_cost (4)] [p_cost (4)] [out_len (2)] [salt_len (1)] [salt (..)] [password (..)]
// Minimum: 15 bytes (4+4+4+2+1).
if data.len() < 15 {
return;
}
let m_cost = u32::from_le_bytes(data[0..4].try_into().unwrap());
let t_cost = u32::from_le_bytes(data[4..8].try_into().unwrap());
let p_cost = u32::from_le_bytes(data[8..12].try_into().unwrap());
let out_len = u16::from_le_bytes(data[12..14].try_into().unwrap()) as usize;
let salt_len = data[14] as usize;
let rest = &data[15..];
if rest.len() < salt_len {
return;
}
let salt = &rest[..salt_len];
let password = &rest[salt_len..];
// Cap m_cost to prevent actual multi-GiB allocation during fuzzing.
// The validation boundary is at 4_194_304 — we test up to 2× that
// but never allocate: invalid params are rejected before allocation.
// For valid params, cap at 1024 KiB (1 MiB) to keep fuzzing fast.
let m_cost = if m_cost > 8_388_608 { m_cost } else { m_cost.min(1024) };
// Cap out_len to prevent large allocation.
let out_len = out_len.min(4097);
if out_len == 0 {
return;
}
let params = Argon2Params {
m_cost,
t_cost,
p_cost,
};
let mut out = vec![0u8; out_len];
// argon2id must never panic regardless of parameters. Exercises:
// salt minimum check, output length bounds, cost parameter caps,
// argon2 library parameter validation, error-path output zeroization.
let _ = argon2id(password, salt, params, &mut out);
});

View file

@ -0,0 +1,33 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::{
auth::auth_respond,
identity::{generate_identity, GeneratedIdentity, IdentitySecretKey},
primitives::xwing,
};
use std::sync::LazyLock;
struct ClientKeys {
sk: IdentitySecretKey,
}
// Fixed client identity — keygen is expensive, amortise across corpus runs.
static CLIENT: LazyLock<ClientKeys> = LazyLock::new(|| {
let GeneratedIdentity { secret_key: sk, .. } = generate_identity().unwrap();
ClientKeys { sk }
});
const CT_SIZE: usize = 1120;
fuzz_target!(|data: &[u8]| {
if data.len() < CT_SIZE {
return;
}
let Ok(ct) = xwing::Ciphertext::from_bytes(data[..CT_SIZE].to_vec()) else { return; };
// auth_respond must never panic regardless of ciphertext content.
// Exercises: X-Wing decapsulation with arbitrary ct, HMAC-SHA256 derivation.
// KEM decapsulation always "succeeds" (returns some shared secret); the HMAC
// path always runs and the result is returned as Zeroizing<[u8; 32]>.
let _ = auth_respond(&CLIENT.sk, &ct);
});

View file

@ -0,0 +1,20 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::auth::auth_verify;
fuzz_target!(|data: &[u8]| {
// Feed adversarial 32-byte pairs to auth_verify. Confirms it never
// panics for any bit pattern and always returns a deterministic bool.
if data.len() < 64 {
return;
}
let expected: &[u8; 32] = data[..32].try_into().unwrap();
let proof: &[u8; 32] = data[32..64].try_into().unwrap();
let result = auth_verify(expected, proof);
// Correctness: auth_verify is constant-time equality. Verify it
// returns the correct answer — catches regressions where verify
// always returns true or always returns false.
assert_eq!(result, expected == proof, "auth_verify returned wrong result");
});

View file

@ -0,0 +1,44 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::call::derive_call_keys;
// Fixed root key — exercises the HKDF-based key derivation without restricting
// the fuzz input space for the fields that drive branching (kem_ss, fp_a, fp_b).
const ROOT_KEY: [u8; 32] = [0x11; 32];
// Wire layout:
// kem_ss (32) | call_id (16) | fp_a (32) | fp_b (32)
// derive_call_keys returns Err(InvalidData) when kem_ss is all-zeros or
// fp_a == fp_b; those inputs exercise the guard paths without reaching advance().
const MIN: usize = 32 + 16 + 32 + 32; // 112 bytes
fuzz_target!(|data: &[u8]| {
if data.len() < MIN {
return;
}
let kem_ss: &[u8; 32] = data[0..32].try_into().unwrap();
let call_id: &[u8; 16] = data[32..48].try_into().unwrap();
let fp_a: &[u8; 32] = data[48..80].try_into().unwrap();
let fp_b: &[u8; 32] = data[80..112].try_into().unwrap();
// derive_call_keys and advance must never panic regardless of input.
// Exercises: kem_ss zero-check, fingerprint equality guard, HKDF key
// derivation, HMAC-SHA3-256 rekeying, and old-field zeroization in advance().
// Both role-assignment branches of advance() are covered by corpus seeds:
// fp_a < fp_b (lower_role=true) and fp_a > fp_b (lower_role=false).
if let Ok(mut keys_ab) = derive_call_keys(&ROOT_KEY, kem_ss, call_id, fp_a, fp_b) {
// Symmetry property: swapping fingerprints must swap send/recv keys.
// This catches edge cases near the fingerprint comparison boundary
// that the unit-level proptest may miss with different input distributions.
let keys_ba = derive_call_keys(&ROOT_KEY, kem_ss, call_id, fp_b, fp_a).unwrap();
assert_eq!(keys_ab.send_key(), keys_ba.recv_key(), "symmetry: send/recv mismatch");
assert_eq!(keys_ab.recv_key(), keys_ba.send_key(), "symmetry: recv/send mismatch");
// Verify advance() succeeds and produces different keys.
let pre_send = keys_ab.send_key().to_vec();
let pre_recv = keys_ab.recv_key().to_vec();
keys_ab.advance().expect("advance must succeed on valid call keys");
assert_ne!(&*keys_ab.send_key(), &pre_send[..], "advance must change send_key");
assert_ne!(&*keys_ab.recv_key(), &pre_recv[..], "advance must change recv_key");
}
});

View file

@ -0,0 +1,14 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::ratchet::RatchetState;
use zeroize::Zeroizing;
fuzz_target!(|data: &[u8]| {
let ck: [u8; 32] = [0x22; 32];
let aad = b"lo-dm-v1";
// decrypt_first_message must never panic regardless of input.
// Exercises: random-nonce AEAD decrypt path (distinct from counter-based
// decrypt in fuzz_ratchet_decrypt).
let _ = RatchetState::decrypt_first_message(Zeroizing::new(ck), data, aad);
});

View file

@ -0,0 +1,26 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::storage::{decrypt_dm_queue_blob, StorageKey, StorageKeyRing};
// Distinct keys per version — catches version-routing bugs that identical keys would hide.
const FUZZ_KEY_V1: [u8; 32] = [0x42; 32];
const FUZZ_KEY_V2: [u8; 32] = [0x43; 32];
const FUZZ_KEY_V3: [u8; 32] = [0x44; 32];
fuzz_target!(|data: &[u8]| {
// Build a keyring with versions 1-3 so version routing is exercised.
let key1 = StorageKey::new(1, FUZZ_KEY_V1).unwrap();
let key2 = StorageKey::new(2, FUZZ_KEY_V2).unwrap();
let key3 = StorageKey::new(3, FUZZ_KEY_V3).unwrap();
let mut ring = StorageKeyRing::new(key1).unwrap();
let _ = ring.add_key(key2, false);
let _ = ring.add_key(key3, false);
let recipient_fp: [u8; 32] = [0xAA; 32];
// decrypt_dm_queue_blob must never panic regardless of input.
// Exercises: DM queue AAD construction (build_dm_queue_aad binds
// recipient_fp + batch_id), version routing, flag validation,
// decompression, length checks, AEAD decryption.
let _ = decrypt_dm_queue_blob(&ring, data, &recipient_fp, "fuzz-batch");
});

View file

@ -0,0 +1,59 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::storage::{encrypt_dm_queue_blob, decrypt_dm_queue_blob, StorageKey, StorageKeyRing};
const FUZZ_KEY: [u8; 32] = [0x42; 32];
fuzz_target!(|data: &[u8]| {
// Wire layout: [compress_flag (1)] [batch_id_len (1)] [batch_id (..)] [plaintext (..)]
// Minimum: 2 bytes (compress flag + batch_id_len).
if data.len() < 2 {
return;
}
// Cap input size to prevent OOM — compress_to_vec allocates working
// buffers proportional to input size.
if data.len() > 1_048_576 {
return;
}
let compress = data[0] & 0x01 != 0;
let batch_len = data[1] as usize;
// batch_id must be valid UTF-8 — use a fixed string to avoid
// rejecting most fuzz inputs on UTF-8 validation.
let batch_id = if batch_len == 0 { "fuzz-batch" } else { "fuzz-batch-alt" };
let plaintext = if data.len() > 2 { &data[2..] } else { &[] };
let recipient_fp: [u8; 32] = [0xAA; 32];
let key = StorageKey::new(1, FUZZ_KEY).unwrap();
// encrypt_dm_queue_blob must never panic. Exercises: DM queue AAD
// construction (build_dm_queue_aad binds recipient_fp + batch_id),
// compression, nonce generation, XChaCha20-Poly1305 encryption.
let blob = match encrypt_dm_queue_blob(&key, plaintext, &recipient_fp, batch_id, compress) {
Ok(b) => b,
Err(_) => return,
};
// Roundtrip: decrypt must recover the original plaintext.
// Catches AAD mismatch, length-prefix errors, compression flag bugs.
let keyring = StorageKeyRing::new(StorageKey::new(1, FUZZ_KEY).unwrap()).unwrap();
let recovered = decrypt_dm_queue_blob(&keyring, &blob, &recipient_fp, batch_id)
.expect("decrypt_dm_queue_blob failed on freshly encrypted blob");
assert_eq!(&*recovered, plaintext, "DM queue roundtrip mismatch");
// Wrong recipient fingerprint must fail — verifies AAD binding.
let wrong_fp: [u8; 32] = [0xBB; 32];
assert!(
decrypt_dm_queue_blob(&keyring, &blob, &wrong_fp, batch_id).is_err(),
"decrypt must fail with wrong recipient_fp"
);
// Wrong batch_id must fail — verifies AAD binding.
assert!(
decrypt_dm_queue_blob(&keyring, &blob, &recipient_fp, "wrong-batch").is_err(),
"decrypt must fail with wrong batch_id"
);
});

View file

@ -0,0 +1,23 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::primitives::ed25519;
fuzz_target!(|data: &[u8]| {
// Need at least 32 (pk) + 64 (sig) = 96 bytes.
if data.len() < 96 {
return;
}
let pk_bytes: [u8; 32] = data[..32].try_into().unwrap();
let sig: [u8; 64] = data[32..96].try_into().unwrap();
let msg = &data[96..];
// Attempt to construct a VerifyingKey from the fuzz input — from_bytes
// rejects non-canonical encodings and points not on the curve.
let Ok(vk) = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes) else {
return;
};
// verify must never panic regardless of input.
// Exercises: Ed25519 point decompression, strict signature verification.
let _ = ed25519::verify(&vk, msg, &sig);
});

View file

@ -0,0 +1,21 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::identity::{hybrid_verify, HybridSignature, IdentityPublicKey};
fuzz_target!(|data: &[u8]| {
// pk (3200) + sig (3373) = 6573 minimum bytes.
if data.len() < 3200 + 3373 {
return;
}
let Ok(pk) = IdentityPublicKey::from_bytes(data[..3200].to_vec()) else {
return;
};
let Ok(sig) = HybridSignature::from_bytes(data[3200..3200 + 3373].to_vec()) else {
return;
};
let msg = &data[3200 + 3373..];
// hybrid_verify must never panic regardless of input.
// Exercises: Ed25519 verify + ML-DSA verify (pure-Rust ml-dsa crate).
let _ = hybrid_verify(&pk, msg, &sig);
});

View file

@ -0,0 +1,10 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::identity::{HybridSignature, IdentityPublicKey, IdentitySecretKey};
fuzz_target!(|data: &[u8]| {
// All three from_bytes must never panic regardless of input.
let _ = IdentityPublicKey::from_bytes(data.to_vec());
let _ = IdentitySecretKey::from_bytes(data.to_vec());
let _ = HybridSignature::from_bytes(data.to_vec());
});

View file

@ -0,0 +1,37 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::identity::{generate_identity, hybrid_sign, hybrid_verify, GeneratedIdentity, IdentityPublicKey, IdentitySecretKey};
use std::sync::LazyLock;
struct SignerKeys {
pk: IdentityPublicKey,
sk: IdentitySecretKey,
}
// Fixed signer — keygen is expensive, amortise across corpus runs.
static SIGNER: LazyLock<SignerKeys> = LazyLock::new(|| {
let GeneratedIdentity { public_key: pk, secret_key: sk, .. } = generate_identity().unwrap();
SignerKeys { pk, sk }
});
fuzz_target!(|data: &[u8]| {
if data.is_empty() {
return;
}
// Property 1: sign(msg) → verify(msg, sig) must always succeed.
let Ok(sig) = hybrid_sign(&SIGNER.sk, data) else {
panic!("hybrid_sign failed on a valid key");
};
if hybrid_verify(&SIGNER.pk, data, &sig).is_err() {
panic!("hybrid_verify rejected a freshly-signed message");
}
// Property 2: verify(tampered_msg, sig) must always fail.
// Flip the LSB of the first byte — always changes the message content.
let mut tampered = data.to_vec();
tampered[0] ^= 0x01;
if hybrid_verify(&SIGNER.pk, &tampered, &sig).is_ok() {
panic!("hybrid_verify accepted a message that differs by exactly one bit");
}
});

View file

@ -0,0 +1,43 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::{
identity::{generate_identity, GeneratedIdentity, HybridSignature, IdentityPublicKey, IdentitySecretKey},
kex::{decode_session_init, receive_session},
primitives::xwing,
};
use std::sync::LazyLock;
struct BobKeys {
ik_pk: IdentityPublicKey,
ik_sk: IdentitySecretKey,
spk_sk: xwing::SecretKey,
}
static BOB: LazyLock<BobKeys> = LazyLock::new(|| {
let GeneratedIdentity { public_key: ik_pk, secret_key: ik_sk, .. } = generate_identity().unwrap();
let (_spk_pk, spk_sk) = xwing::keygen().unwrap();
BobKeys { ik_pk, ik_sk, spk_sk }
});
static ALICE_PK: LazyLock<IdentityPublicKey> = LazyLock::new(|| generate_identity().unwrap().public_key);
const SIG: usize = 3373;
fuzz_target!(|data: &[u8]| {
// Chained fuzz target: decode_session_init → receive_session.
// Catches bugs in the interaction between wire parsing and session
// establishment that separate harnesses cannot reach.
//
// Wire layout: sig (3373) | encoded_session_init (rest)
if data.len() < SIG {
return;
}
let Ok(sig) = HybridSignature::from_bytes(data[..SIG].to_vec()) else { return; };
let encoded = &data[SIG..];
let Ok(si) = decode_session_init(encoded) else { return; };
// receive_session must never panic regardless of decoded input.
let _ = receive_session(&BOB.ik_pk, &BOB.ik_sk, &ALICE_PK, &si, &sig, &BOB.spk_sk, None);
});

View file

@ -0,0 +1,101 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::{
identity::{generate_identity, GeneratedIdentity, HybridSignature, IdentityPublicKey, IdentitySecretKey},
kex::{receive_session, SessionInit},
primitives::xwing,
};
use std::sync::LazyLock;
struct BobKeys {
ik_pk: IdentityPublicKey,
ik_sk: IdentitySecretKey,
spk_sk: xwing::SecretKey,
}
// Fixed Bob identity + SPK keypair — keygen is expensive, amortise across runs.
static BOB: LazyLock<BobKeys> = LazyLock::new(|| {
let GeneratedIdentity { public_key: ik_pk, secret_key: ik_sk, .. } = generate_identity().unwrap();
let (_spk_pk, spk_sk) = xwing::keygen().unwrap();
BobKeys { ik_pk, ik_sk, spk_sk }
});
// Fixed Alice identity (the "known sender" Bob trusts).
static ALICE_PK: LazyLock<IdentityPublicKey> = LazyLock::new(|| generate_identity().unwrap().public_key);
const SIG: usize = 3373;
const FP: usize = 32;
const XPK: usize = 1216;
const XCT: usize = 1120;
// Wire layout:
// sig (3373) | sender_fp (32) | recipient_fp (32) | sender_ek (1216)
// | ct_ik (1120) | ct_spk (1120) | spk_id (4 BE) | has_opk (1)
// | [ct_opk (1120) | opk_id (4 BE)] ← only if has_opk & 0x01
// | crypto_version (rest, strict UTF-8; bail if invalid)
const MIN: usize = SIG + FP + FP + XPK + XCT + XCT + 4 + 1;
fuzz_target!(|data: &[u8]| {
if data.len() < MIN {
return;
}
let mut off = 0;
let Ok(sig) = HybridSignature::from_bytes(data[off..off + SIG].to_vec()) else { return; };
off += SIG;
let sender_ik_fingerprint: [u8; FP] = data[off..off + FP].try_into().unwrap();
off += FP;
let recipient_ik_fingerprint: [u8; FP] = data[off..off + FP].try_into().unwrap();
off += FP;
let Ok(sender_ek) = xwing::PublicKey::from_bytes(data[off..off + XPK].to_vec()) else { return; };
off += XPK;
let Ok(ct_ik) = xwing::Ciphertext::from_bytes(data[off..off + XCT].to_vec()) else { return; };
off += XCT;
let Ok(ct_spk) = xwing::Ciphertext::from_bytes(data[off..off + XCT].to_vec()) else { return; };
off += XCT;
let spk_id = u32::from_be_bytes(data[off..off + 4].try_into().unwrap());
off += 4;
let has_opk = data[off] & 0x01 != 0;
off += 1;
let (ct_opk, opk_id) = if has_opk {
if data.len() < off + XCT + 4 {
return;
}
let Ok(ct) = xwing::Ciphertext::from_bytes(data[off..off + XCT].to_vec()) else { return; };
off += XCT;
let id = u32::from_be_bytes(data[off..off + 4].try_into().unwrap());
off += 4;
(Some(ct), Some(id))
} else {
(None, None)
};
// Use strict from_utf8 to match decode_session_init, which rejects
// non-UTF-8 bytes with Error::InvalidData. Lossy decoding would allow
// replacement-character strings that can never reach receive_session in
// real protocol flow (the wire parser rejects them first).
let Ok(crypto_version) = String::from_utf8(data[off..].to_vec()) else { return; };
let si = SessionInit {
crypto_version,
sender_ik_fingerprint,
recipient_ik_fingerprint,
sender_ek,
ct_ik,
ct_spk,
spk_id,
ct_opk,
opk_id,
};
// receive_session must never panic regardless of input.
// Exercises: crypto_version check, fingerprint checks, hybrid signature
// verification, KEM decapsulation, HKDF, and rollback on failure.
let _ = receive_session(&BOB.ik_pk, &BOB.ik_sk, &ALICE_PK, &si, &sig, &BOB.spk_sk, None);
});

View file

@ -0,0 +1,89 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::{
identity::{generate_identity, HybridSignature, IdentityPublicKey},
kex::{verify_bundle, PreKeyBundle},
primitives::xwing,
};
use std::sync::LazyLock;
// KNOWN_IK is used as BOTH the "trusted" key AND the bundle's ik_pub.
// verify_bundle's first check is `bundle.ik_pub == known_ik`; a mismatch
// returns BundleVerificationFailed immediately without reaching the SPK
// signature check. Supplying the same value for both ensures the IK check
// always passes, so every input exercises the OPK co-presence guard,
// crypto_version validation, and hybrid_verify — the SPK sig-forge surface.
static KNOWN_IK: LazyLock<IdentityPublicKey> =
LazyLock::new(|| generate_identity().unwrap().public_key);
const SPK: usize = 1216;
const SIG: usize = 3373;
// Wire layout (ik_pub is always KNOWN_IK — not part of fuzz input):
// spk_pub (1216) | spk_sig (3373) | spk_id (4 BE)
// | has_opk (1) | [opk_pub (1216) | opk_id (4 BE)]
// | crypto_version (rest, strict UTF-8; bail if invalid)
const MIN: usize = SPK + SIG + 4 + 1;
fuzz_target!(|data: &[u8]| {
if data.len() < MIN {
return;
}
let mut off = 0;
let Ok(spk_pub) = xwing::PublicKey::from_bytes(data[off..off + SPK].to_vec()) else { return; };
off += SPK;
let Ok(spk_sig) = HybridSignature::from_bytes(data[off..off + SIG].to_vec()) else { return; };
off += SIG;
let spk_id = u32::from_be_bytes(data[off..off + 4].try_into().unwrap());
off += 4;
// Two independent bits control opk_pub and opk_id presence, allowing
// the fuzzer to reach the co-presence guard in verify_bundle (one Some,
// the other None). Bit 0 = has_opk_pub, bit 1 = has_opk_id.
let opk_flags = data[off];
let has_opk_pub = opk_flags & 0x01 != 0;
let has_opk_id = opk_flags & 0x02 != 0;
off += 1;
let opk_pub = if has_opk_pub {
if data.len() < off + SPK {
return;
}
let Ok(opk) = xwing::PublicKey::from_bytes(data[off..off + SPK].to_vec()) else { return; };
off += SPK;
Some(opk)
} else {
None
};
let opk_id = if has_opk_id {
if data.len() < off + 4 {
return;
}
let id = u32::from_be_bytes(data[off..off + 4].try_into().unwrap());
off += 4;
Some(id)
} else {
None
};
let Ok(crypto_version) = String::from_utf8(data[off..].to_vec()) else { return; };
let bundle = PreKeyBundle {
ik_pub: KNOWN_IK.clone(),
crypto_version,
spk_pub,
spk_id,
spk_sig,
opk_pub,
opk_id,
};
// verify_bundle must never panic regardless of input.
// Exercises: crypto_version validation, OPK co-presence guard (mismatched
// opk_pub/opk_id via independent flag bits), and SPK signature verification
// (hybrid_verify) — the main sig-forge attack surface.
let _ = verify_bundle(bundle, &KNOWN_IK);
});

View file

@ -0,0 +1,76 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::primitives::xwing;
use soliton::ratchet::{RatchetHeader, RatchetState};
// Fixed keys for deterministic Bob state construction.
const ROOT_KEY: [u8; 32] = [0x11; 32];
const CHAIN_KEY: [u8; 32] = [0x22; 32];
const FP_A: [u8; 32] = [0xAA; 32];
const FP_B: [u8; 32] = [0xBB; 32];
fuzz_target!(|data: &[u8]| {
// Parse fuzzer input into:
// peer_ek (1216) | ratchet_pk (1216) | has_kem_ct (1) | [kem_ct (1120)] | n (4) | pn (4) | ciphertext
// peer_ek is Bob's initial recv_ratchet_pk (set at init_bob time).
// ratchet_pk is the value in the incoming header.
// When they differ (the common case with random fuzz input), need_ratchet = true
// and the ratchet-step path fires; when they happen to be identical, the
// same-chain path fires. Both slices are independently fuzz-controlled.
// Minimum: 1216 + 1216 + 1 + 4 + 4 + 16 = 2457 bytes (no kem_ct, 16 for Poly1305 tag)
if data.len() < 2457 {
return;
}
let Ok(peer_ek) = xwing::PublicKey::from_bytes(data[..1216].to_vec()) else {
return;
};
let Ok(ratchet_pk) = xwing::PublicKey::from_bytes(data[1216..2432].to_vec()) else {
return;
};
let Ok(mut bob) = RatchetState::init_bob(ROOT_KEY, CHAIN_KEY, FP_B, FP_A, peer_ek) else {
return;
};
let rest = &data[2432..];
let has_kem_ct = rest[0] & 0x01 != 0;
let (kem_ct, counter_start) = if has_kem_ct {
// Need 1120 bytes for kem_ct after the flag byte
if rest.len() < 1 + 1120 + 8 {
return;
}
match xwing::Ciphertext::from_bytes(rest[1..1121].to_vec()) {
// counter_start = 1 (flag) + 1120 (kem_ct) = 1121
Ok(ct) => (Some(ct), 1121),
Err(_) => return,
}
} else {
// counter_start = 1 (flag byte only; no kem_ct bytes)
(None, 1)
};
if rest.len() < counter_start + 8 {
return;
}
let n = u32::from_be_bytes(rest[counter_start..counter_start + 4].try_into().unwrap());
let pn = u32::from_be_bytes(rest[counter_start + 4..counter_start + 8].try_into().unwrap());
let ciphertext = &rest[counter_start + 8..];
let header = RatchetHeader { ratchet_pk, kem_ct, n, pn };
// decrypt must never panic regardless of input. When ratchet_pk differs
// from peer_ek (the common case), need_ratchet = true and the ratchet-step
// path fires, exercising KEM ciphertext validation, root/recv-epoch KDF,
// and rollback on decapsulation failure. When they are identical, the
// same-chain path fires and AEAD rejects almost all inputs. Both code
// paths are reachable from fuzz input. Rollback execution is exercised
// here; rollback correctness — that all 9 state fields (root_key,
// recv_epoch_key, recv_count, recv_ratchet_pk, ratchet_pending,
// recv_seen, prev_recv_epoch_key, prev_recv_ratchet_pk,
// prev_recv_seen) are fully restored on failure — is verified by the
// unit tests in ratchet/mod.rs, not by this harness.
let _ = bob.decrypt(&header, ciphertext);
});

View file

@ -0,0 +1,84 @@
#![no_main]
#![allow(deprecated)]
use libfuzzer_sys::fuzz_target;
use soliton::ratchet::{RatchetHeader, RatchetState};
use soliton::primitives::xwing;
fuzz_target!(|data: &[u8]| {
// Stateful decrypt: deserialize Bob from the first chunk, then parse a
// header + ciphertext from the remainder and attempt decryption.
//
// Unlike fuzz_ratchet_decrypt (which constructs a fresh Bob via init_bob
// and can never reach a successful decrypt-with-ratchet-step), this harness
// can start from any serialized state — including post-exchange states where
// send_ratchet_sk is Some, making the full ratchet-step decrypt path
// reachable. Corpus seeds include states with populated recv_seen sets,
// exercising the duplicate-detection and out-of-order paths that would take
// the fuzzer a long time to discover through mutation alone.
//
// Input layout:
// state_len (4 BE) | state (state_len) | ratchet_pk (1216)
// | has_kem_ct (1) | [kem_ct (1120)] | n (4) | pn (4) | ciphertext
//
// The practical minimum for reaching decrypt() is ~5000+ bytes (valid
// serialized state + header + ciphertext). The early returns below are
// fast-path rejections for obviously-too-short input, not the true minimum
// for interesting coverage.
//
// Because state_len is fuzzer-controlled, the fuzzer naturally explores
// degenerate cases: state_len=0 (from_bytes rejects), state_len=data.len()-4
// (rest is empty, minimum-size check rejects), and state_len > data.len()-4
// (second guard rejects). All three are handled by the guards below.
if data.len() < 4 {
return;
}
let state_len = u32::from_be_bytes(data[..4].try_into().unwrap()) as usize;
if data.len() < 4 + state_len {
return;
}
let Ok(mut bob) = RatchetState::from_bytes(&data[4..4 + state_len]) else {
return;
};
let rest = &data[4 + state_len..];
// ratchet_pk (1216) + has_kem_ct (1) + n (4) + pn (4) + tag (16) = 1241 minimum
if rest.len() < 1216 + 1 + 4 + 4 + 16 {
return;
}
let Ok(ratchet_pk) = xwing::PublicKey::from_bytes(rest[..1216].to_vec()) else {
return;
};
let has_kem_ct = rest[1216] & 0x01 != 0;
let (kem_ct, counter_start) = if has_kem_ct {
if rest.len() < 1216 + 1 + 1120 + 8 {
return;
}
match xwing::Ciphertext::from_bytes(rest[1217..2337].to_vec()) {
Ok(ct) => (Some(ct), 2337),
Err(_) => return,
}
} else {
(None, 1217)
};
if rest.len() < counter_start + 8 {
return;
}
let n = u32::from_be_bytes(rest[counter_start..counter_start + 4].try_into().unwrap());
let pn = u32::from_be_bytes(rest[counter_start + 4..counter_start + 8].try_into().unwrap());
let ciphertext = &rest[counter_start + 8..];
let header = RatchetHeader { ratchet_pk, kem_ct, n, pn };
// decrypt must never panic. This harness covers the full state machine:
// same-chain path (ratchet_pk matches recv_ratchet_pk), ratchet-step path
// with real decapsulation (send_ratchet_sk present in deserialized state),
// counter-mode key derivation, recv_seen duplicate detection, previous-epoch
// grace period, and rollback on any failure.
let _ = bob.decrypt(&header, ciphertext);
});

View file

@ -0,0 +1,19 @@
#![no_main]
#![allow(deprecated)]
use libfuzzer_sys::fuzz_target;
use soliton::ratchet::RatchetState;
fuzz_target!(|data: &[u8]| {
// Deserialize adversarial state, then encrypt.
// Exercises: ChainExhausted guard,
// perform_kem_ratchet_send (keygen + encaps + kdf_root),
// kdf_msg_key, nonce construction, AAD building, AEAD encrypt,
// and the session-fatal zeroize path on AEAD failure.
let Ok(mut state) = RatchetState::from_bytes(data) else {
return;
};
// Fixed plaintext — fingerprints are stored in the deserialized state,
// not passed as parameters.
let _ = state.encrypt(b"fuzz");
});

View file

@ -0,0 +1,18 @@
#![no_main]
#![allow(deprecated)]
use libfuzzer_sys::fuzz_target;
use soliton::ratchet::RatchetState;
fuzz_target!(|data: &[u8]| {
// Exercises from_bytes_with_min_epoch with fuzz-controlled min_epoch.
// The first 8 bytes are the min_epoch threshold; the remainder is the
// serialized ratchet state. This covers the epoch validation gate and
// its interaction with field parsing — a distinct attack surface from
// plain from_bytes.
if data.len() < 8 {
return;
}
let min_epoch = u64::from_be_bytes(data[..8].try_into().unwrap());
let _ = RatchetState::from_bytes_with_min_epoch(&data[8..], min_epoch);
});

View file

@ -0,0 +1,32 @@
#![no_main]
#![allow(deprecated)] // Fuzz targets exercise from_bytes directly.
use libfuzzer_sys::fuzz_target;
use soliton::ratchet::RatchetState;
fuzz_target!(|data: &[u8]| {
// from_bytes → to_bytes → from_bytes round-trip:
// any serializable state must re-serialize to identical bytes
// (except the epoch field at bytes 1..9, which increments on each to_bytes).
//
// States near the epoch ceiling are legitimately non-serializable
// (can_serialize() returns false). These are usable for encrypt/decrypt
// but not persistable — skip them.
let Ok(state1) = RatchetState::from_bytes(data) else { return; };
if !state1.can_serialize() { return; }
let Ok((bytes1, epoch1)) = state1.to_bytes() else {
panic!("to_bytes failed on a state where can_serialize() returned true");
};
let Ok(state2) = RatchetState::from_bytes(&bytes1) else {
panic!("from_bytes rejected bytes produced by to_bytes");
};
if !state2.can_serialize() { return; }
let Ok((bytes2, epoch2)) = state2.to_bytes() else {
panic!("second to_bytes failed on a serializable round-tripped state");
};
// Version byte must match.
assert_eq!(bytes1[0], bytes2[0], "version byte mismatch after round-trip");
// All fields after epoch must match.
assert_eq!(bytes1[9..], bytes2[9..], "fields after epoch diverged after round-trip");
// Epoch must advance by exactly 1 per to_bytes call.
assert_eq!(epoch2, epoch1 + 1, "epoch did not advance by 1");
});

View file

@ -0,0 +1,142 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::error::Error;
use soliton::primitives::{random, xwing};
use soliton::ratchet::RatchetState;
use std::collections::HashSet;
// Action-sequence fuzzer for the ratchet state machine.
//
// Keeps Alice and Bob as live cryptographic states and uses fuzz input to
// drive a sequence of protocol operations — sends, deliveries (possibly
// out-of-order), direction changes, and replays. Because the harness
// performs real crypto (generating valid AEAD tags), the fuzzer is not
// blocked by AEAD authentication barriers and can freely explore recv_seen
// boundaries, duplicate detection, KEM ratchet transitions, previous-epoch
// grace periods, rollback, and counter exhaustion.
//
// Unlike crash-only fuzz targets, this harness asserts protocol correctness:
// - If decrypt returns Ok, the message must not have been previously delivered
// - If decrypt returns DuplicateMessage, the message must have been previously delivered
// - Decrypted plaintext must match the original
//
// Input format: each byte is an action opcode.
// 0x00..0x3F Alice sends (plaintext = &[opcode])
// 0x40..0x7F Bob sends (plaintext = &[opcode])
// 0x80..0xBF Deliver from Alice's outbox to Bob (index = opcode & 0x3F)
// 0xC0..0xFF Deliver from Bob's outbox to Alice (index = opcode & 0x3F)
fuzz_target!(|data: &[u8]| {
if data.len() > 200 { return; }
let fp_a = [0xAA_u8; 32];
let fp_b = [0xBB_u8; 32];
let rk: [u8; 32] = random::random_array();
let ck: [u8; 32] = random::random_array();
let (ek_pk, ek_sk) = xwing::keygen().unwrap();
let mut alice = RatchetState::init_alice(
rk, ck, fp_a, fp_b, ek_pk.clone(), ek_sk,
).unwrap();
let mut bob = RatchetState::init_bob(rk, ck, fp_b, fp_a, ek_pk).unwrap();
// Outboxes hold (header, ciphertext, original_plaintext) triples.
let mut alice_outbox: Vec<(soliton::ratchet::RatchetHeader, Vec<u8>, Vec<u8>)> = Vec::new();
let mut bob_outbox: Vec<(soliton::ratchet::RatchetHeader, Vec<u8>, Vec<u8>)> = Vec::new();
// Track which outbox indices have been successfully delivered.
// A second delivery of the same index must return DuplicateMessage (or
// AeadFailed if the previous-epoch grace window expired).
let mut bob_delivered: HashSet<usize> = HashSet::new();
let mut alice_delivered: HashSet<usize> = HashSet::new();
for &opcode in data {
match opcode {
// Alice sends
0x00..=0x3F => {
let pt = vec![opcode];
match alice.encrypt(&pt) {
Ok(enc) => alice_outbox.push((enc.header, enc.ciphertext, pt)),
Err(_) => {} // ChainExhausted, dead session — expected
}
}
// Bob sends
0x40..=0x7F => {
let pt = vec![opcode];
match bob.encrypt(&pt) {
Ok(enc) => bob_outbox.push((enc.header, enc.ciphertext, pt)),
Err(_) => {}
}
}
// Deliver Alice's message to Bob
0x80..=0xBF => {
let idx = (opcode & 0x3F) as usize;
if let Some((header, ct, expected_pt)) = alice_outbox.get(idx) {
match bob.decrypt(header, ct) {
Ok(pt) => {
// First successful delivery — plaintext must match.
assert_eq!(
pt.as_slice(), expected_pt.as_slice(),
"plaintext mismatch at alice_outbox[{idx}]"
);
// Must not have been delivered before.
assert!(
bob_delivered.insert(idx),
"decrypt returned Ok for already-delivered alice_outbox[{idx}]"
);
}
Err(Error::DuplicateMessage) => {
// Duplicate — must have been delivered before.
assert!(
bob_delivered.contains(&idx),
"DuplicateMessage for never-delivered alice_outbox[{idx}]"
);
}
Err(Error::AeadFailed) => {
// Valid if the previous-epoch grace window expired
// (two KEM ratchet steps since this message's epoch).
// Also valid for genuinely corrupted state. Not assertable.
}
Err(Error::ChainExhausted) => {
// recv_seen cap reached — valid.
}
Err(Error::InvalidData) => {
// Dead session (root_key zeroed) — valid after
// a prior session-fatal error.
}
Err(e) => {
panic!("unexpected error delivering alice_outbox[{idx}] to bob: {e:?}");
}
}
}
}
// Deliver Bob's message to Alice
0xC0..=0xFF => {
let idx = (opcode & 0x3F) as usize;
if let Some((header, ct, expected_pt)) = bob_outbox.get(idx) {
match alice.decrypt(header, ct) {
Ok(pt) => {
assert_eq!(
pt.as_slice(), expected_pt.as_slice(),
"plaintext mismatch at bob_outbox[{idx}]"
);
assert!(
alice_delivered.insert(idx),
"decrypt returned Ok for already-delivered bob_outbox[{idx}]"
);
}
Err(Error::DuplicateMessage) => {
assert!(
alice_delivered.contains(&idx),
"DuplicateMessage for never-delivered bob_outbox[{idx}]"
);
}
Err(Error::AeadFailed | Error::ChainExhausted | Error::InvalidData) => {}
Err(e) => {
panic!("unexpected error delivering bob_outbox[{idx}] to alice: {e:?}");
}
}
}
}
}
}
});

View file

@ -0,0 +1,18 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::kex::{decode_session_init, encode_session_init};
// No keygen, no crypto operations — pure wire-format parser test.
// Property: encode(decode(data)) == data for any data that parses successfully.
fuzz_target!(|data: &[u8]| {
let Ok(si) = decode_session_init(data) else {
return;
};
let re_encoded =
encode_session_init(&si).expect("encode_session_init cannot fail on a valid SessionInit");
assert_eq!(
data,
re_encoded.as_slice(),
"encode(decode(wire)) != wire — format malleability detected"
);
});

View file

@ -0,0 +1,23 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::storage::{decrypt_blob, StorageKey, StorageKeyRing};
// Distinct keys per version — catches version-routing bugs that identical keys would hide.
const FUZZ_KEY_V1: [u8; 32] = [0x42; 32];
const FUZZ_KEY_V2: [u8; 32] = [0x43; 32];
const FUZZ_KEY_V3: [u8; 32] = [0x44; 32];
fuzz_target!(|data: &[u8]| {
// Build a keyring with versions 1-3 so version routing is exercised.
let key1 = StorageKey::new(1, FUZZ_KEY_V1).unwrap();
let key2 = StorageKey::new(2, FUZZ_KEY_V2).unwrap();
let key3 = StorageKey::new(3, FUZZ_KEY_V3).unwrap();
let mut ring = StorageKeyRing::new(key1).unwrap();
let _ = ring.add_key(key2, false);
let _ = ring.add_key(key3, false);
// decrypt_blob must never panic regardless of input.
// AEAD rejects most mutations; the pre-AEAD parsing paths
// (version routing, flag validation, length checks) are the target.
let _ = decrypt_blob(&ring, data, "fuzz-channel", "fuzz-segment");
});

View file

@ -0,0 +1,35 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::storage::{encrypt_blob, decrypt_blob, StorageKey, StorageKeyRing};
const FUZZ_KEY: [u8; 32] = [0x42; 32];
fuzz_target!(|data: &[u8]| {
if data.is_empty() {
return;
}
// Cap input size to prevent OOM on CI runners — compress_to_vec allocates
// working buffers proportional to input size (~2× for zstd).
if data.len() > 1_048_576 {
return;
}
let key = StorageKey::new(1, FUZZ_KEY).unwrap();
let compress = data[0] & 0x01 != 0;
let plaintext = &data[1..];
// encrypt_blob must never panic regardless of plaintext size, content, or
// compress flag. Exercises: capacity calculation, optional ruzstd compression,
// nonce generation, AAD construction, XChaCha20-Poly1305 encryption.
let blob = match encrypt_blob(&key, plaintext, "fuzz-channel", "fuzz-segment", compress) {
Ok(b) => b,
Err(_) => return,
};
// Roundtrip verification: decrypt must recover the original plaintext.
// Catches malformed blob layout, wrong AAD, header byte errors, and
// compression flag mismatches that a crash-only target would miss.
let keyring = StorageKeyRing::new(StorageKey::new(1, FUZZ_KEY).unwrap()).unwrap();
let recovered = decrypt_blob(&keyring, &blob, "fuzz-channel", "fuzz-segment")
.expect("decrypt_blob failed on freshly encrypted blob");
assert_eq!(&*recovered, plaintext, "roundtrip mismatch");
});

View file

@ -0,0 +1,43 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::streaming::stream_decrypt_init;
const FUZZ_KEY: [u8; 32] = [0x42; 32];
fuzz_target!(|data: &[u8]| {
// Fuzz the streaming decryptor with adversarial header + chunk data.
// Exercises header parsing (version, flags, reserved-bit rejection),
// AEAD authentication, decompression bounds, and tag-byte validation.
if data.len() < 26 + 2 {
return;
}
let header: [u8; 26] = data[..26].try_into().unwrap();
let rest = &data[26..];
let mut dec = match stream_decrypt_init(&FUZZ_KEY, &header, b"fuzz-aad") {
Ok(d) => d,
Err(_) => return,
};
// Variable-length chunk splitting: each iteration consumes a 2-byte BE
// length prefix followed by that many bytes as a chunk. This allows the
// fuzzer to discover valid chunk sizes (including STREAM_CHUNK_SIZE + 17
// for non-final chunks) through mutation, unlike fixed-size splitting.
let mut cursor = 0;
while cursor + 2 <= rest.len() {
let chunk_len =
u16::from_be_bytes([rest[cursor], rest[cursor + 1]]) as usize;
cursor += 2;
if cursor + chunk_len > rest.len() {
break;
}
let chunk_data = &rest[cursor..cursor + chunk_len];
cursor += chunk_len;
match dec.decrypt_chunk(chunk_data) {
Ok((_, true)) => return, // finalized
Ok((_, false)) => {}
Err(_) => return,
}
}
});

View file

@ -0,0 +1,34 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::streaming::stream_decrypt_init;
const FUZZ_KEY: [u8; 32] = [0x42; 32];
fuzz_target!(|data: &[u8]| {
// Fuzz the random-access decrypt path (decrypt_chunk_at) with adversarial
// (index, chunk) pairs. Exercises index-derived nonce/AAD construction,
// tag-byte validation, and framing guards through the random-access API
// which skips the sequential state guards (next_index, finalized).
if data.len() < 26 + 8 {
return;
}
let header: [u8; 26] = data[..26].try_into().unwrap();
let rest = &data[26..];
let dec = match stream_decrypt_init(&FUZZ_KEY, &header, b"fuzz-at-aad") {
Ok(d) => d,
Err(_) => return,
};
// Each iteration: consume 8 bytes as u64 index, then up to 2048 bytes as chunk.
let mut cursor = 0;
while cursor + 8 < rest.len() {
let index = u64::from_be_bytes(rest[cursor..cursor + 8].try_into().unwrap());
cursor += 8;
let chunk_end = (cursor + 2048).min(rest.len());
let chunk_data = &rest[cursor..chunk_end];
cursor = chunk_end;
let _ = dec.decrypt_chunk_at(index, chunk_data);
}
});

View file

@ -0,0 +1,87 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::streaming::{stream_decrypt_init, stream_encrypt_init};
fuzz_target!(|data: &[u8]| {
// Fuzz encrypt_chunk_at: encrypt all chunks via the random-access API,
// assemble in index order, then decrypt sequentially and verify round-trip.
//
// Exercises the index-derived nonce/AAD construction under adversarial
// plaintext, validates that out-of-order encryption produces valid streams,
// and confirms that size validation rejects malformed inputs without panic.
if data.is_empty() {
return;
}
// First byte: compression flag (bit 0), encrypt order (bit 1 = reversed).
let compress = data[0] & 0x01 != 0;
let reversed = data[0] & 0x02 != 0;
let plaintext = &data[1..];
let key = [0x42u8; 32];
let aad = b"fuzz-at";
let enc = match stream_encrypt_init(&key, aad, compress) {
Ok(e) => e,
Err(_) => return,
};
let header = enc.header();
let chunk_size = soliton::constants::STREAM_CHUNK_SIZE;
// Compute chunk boundaries.
let full_count = plaintext.len() / chunk_size;
let total_chunks = full_count + 1;
let mut index_order: Vec<usize> = (0..total_chunks).collect();
if reversed {
index_order.reverse();
}
// Encrypt each chunk via encrypt_chunk_at in the selected order.
let mut chunks: Vec<Option<Vec<u8>>> = vec![None; total_chunks];
for &i in &index_order {
let is_last = i == full_count;
let slice = if i < full_count {
&plaintext[i * chunk_size..(i + 1) * chunk_size]
} else {
&plaintext[full_count * chunk_size..]
};
match enc.encrypt_chunk_at(i as u64, is_last, slice) {
Ok(ct) => chunks[i] = Some(ct),
Err(_) => return,
}
}
// Assemble in index order and decrypt sequentially.
let mut dec = match stream_decrypt_init(&key, &header, aad) {
Ok(d) => d,
Err(_) => return,
};
for (i, maybe_ct) in chunks.iter().enumerate() {
let ct = match maybe_ct {
Some(c) => c,
None => return,
};
let is_last_expected = i == full_count;
match dec.decrypt_chunk(ct) {
Ok((pt, is_last)) => {
// Plaintext must match the original slice.
let expected = if i < full_count {
&plaintext[i * chunk_size..(i + 1) * chunk_size]
} else {
&plaintext[full_count * chunk_size..]
};
assert_eq!(&*pt, expected, "round-trip mismatch at chunk {i}");
assert_eq!(
is_last, is_last_expected,
"is_last mismatch at chunk {i}"
);
if is_last {
return;
}
}
Err(_) => return,
}
}
});

View file

@ -0,0 +1,73 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::streaming::{stream_decrypt_init, stream_encrypt_init};
fuzz_target!(|data: &[u8]| {
// Round-trip fuzz: encrypt arbitrary data, then decrypt and verify.
// Exercises the full encrypt→decrypt pipeline with variable-size inputs,
// compression toggle, and multi-chunk splitting.
if data.is_empty() {
return;
}
// First byte selects compression mode; rest is plaintext.
let compress = data[0] & 0x01 != 0;
let plaintext = &data[1..];
let key = [0x42u8; 32];
let aad = b"fuzz-rt";
let mut enc = match stream_encrypt_init(&key, aad, compress) {
Ok(e) => e,
Err(_) => return,
};
let header = enc.header();
let chunk_size = soliton::constants::STREAM_CHUNK_SIZE;
let mut chunks: Vec<Vec<u8>> = Vec::new();
// Encrypt in STREAM_CHUNK_SIZE pieces.
if plaintext.len() > chunk_size {
let full_chunks = plaintext.len() / chunk_size;
for i in 0..full_chunks {
let start = i * chunk_size;
let end = start + chunk_size;
let is_last = end >= plaintext.len();
match enc.encrypt_chunk(&plaintext[start..end], is_last) {
Ok(ct) => chunks.push(ct),
Err(_) => return,
}
if is_last {
break;
}
}
if !enc.is_finalized() {
let start = (plaintext.len() / chunk_size) * chunk_size;
match enc.encrypt_chunk(&plaintext[start..], true) {
Ok(ct) => chunks.push(ct),
Err(_) => return,
}
}
} else {
match enc.encrypt_chunk(plaintext, true) {
Ok(ct) => chunks.push(ct),
Err(_) => return,
}
}
// Decrypt sequentially.
let mut dec = match stream_decrypt_init(&key, &header, aad) {
Ok(d) => d,
Err(_) => panic!("decrypt_init failed on valid header"),
};
let mut recovered = Vec::new();
for ct in &chunks {
match dec.decrypt_chunk(ct) {
Ok((pt, _)) => recovered.extend_from_slice(&pt),
Err(e) => panic!("decrypt_chunk failed: {e:?}"),
}
}
assert_eq!(recovered, plaintext, "round-trip mismatch");
});

View file

@ -0,0 +1,18 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::verification::verification_phrase;
fuzz_target!(|data: &[u8]| {
// verification_phrase validates exact size (3200 bytes each).
// Fixed split: inputs ≥ 6400 bytes always produce two exact 3200-byte
// halves regardless of total length, so the SHA-512 word derivation and
// rejection-sampling loop (20-rehash cap) are reachable from any input
// of 6400+ bytes. A midpoint split would only reach that path for
// inputs of exactly 6400 bytes.
const PK_SIZE: usize = 3200; // SOLITON_PUBLIC_KEY_SIZE
const MIN: usize = 2 * PK_SIZE;
if data.len() < MIN {
return;
}
let _ = verification_phrase(&data[..PK_SIZE], &data[PK_SIZE..MIN]);
});

View file

@ -0,0 +1,37 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use soliton::primitives::xwing;
use std::sync::LazyLock;
// Fixed keypair for ciphertext mutation testing — keygen is expensive.
static KP: LazyLock<(xwing::PublicKey, xwing::SecretKey)> =
LazyLock::new(|| xwing::keygen().unwrap());
const CT_SIZE: usize = 1120;
// Two modes selected by data[0] & 0x01:
// 0 (even) — encapsulate + decapsulate roundtrip: proves freshly produced
// ciphertexts always decapsulate without error.
// 1 (odd) — fuzz ciphertext bytes: decapsulate must never panic on any ct.
fuzz_target!(|data: &[u8]| {
if data.is_empty() {
return;
}
if data[0] & 0x01 != 0 {
// Mode A: arbitrary ciphertext → decapsulate must not panic.
if data.len() < 1 + CT_SIZE {
return;
}
let Ok(ct) = xwing::Ciphertext::from_bytes(data[1..1 + CT_SIZE].to_vec()) else { return; };
let _ = xwing::decapsulate(&KP.1, &ct);
} else {
// Mode B: encapsulate → decapsulate → must succeed.
// Exercises the full KEM path with freshly-generated randomness.
let Ok((ct, _ss)) = xwing::encapsulate(&KP.0) else {
panic!("encapsulate failed on a valid public key");
};
if xwing::decapsulate(&KP.1, &ct).is_err() {
panic!("decapsulate failed on a ciphertext produced by encapsulate");
}
}
});