Skip to main content

base64_ng_sanitization/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![deny(unsafe_code)]
3#![deny(missing_docs)]
4#![deny(clippy::all)]
5#![deny(clippy::pedantic)]
6
7//! Optional `sanitization` integration helpers for `base64-ng`.
8//!
9//! This crate deliberately lives outside the core `base64-ng` package so the
10//! base crate keeps its zero-runtime-dependency contract. Applications that
11//! already admit `sanitization` can opt into this companion crate and decode
12//! secret-bearing Base64 directly into `sanitization` secret containers.
13//!
14//! The extension trait targets [`base64_ng::ct::CtEngine`] rather than the
15//! ordinary strict decoder. `sanitization` 2.1.0's native [`ct`] primitives are
16//! re-exported for callers that want `Choice`-based verification after decode.
17//! Enable `memory-lock` or `high-assurance` for locked secret containers on
18//! supported native targets.
19//!
20//! ```
21//! use base64_ng::ct;
22//! use base64_ng_sanitization::{CtDecodeSanitizationExt, SanitizationCtEqExt};
23//!
24//! let secret = ct::STANDARD
25//!     .decode_secret_bytes::<5>(b"aGVsbG8=")
26//!     .unwrap();
27//! assert!(secret.sanitization_verify(b"hello", "example declassifies equality"));
28//! ```
29
30#[cfg(feature = "alloc")]
31extern crate alloc;
32
33#[cfg(feature = "alloc")]
34mod bounded_decode;
35#[cfg(all(test, feature = "alloc"))]
36mod bounded_decode_tests;
37mod compare;
38#[cfg(test)]
39mod compare_tests;
40mod decode_impl;
41mod error;
42#[cfg(feature = "memory-lock")]
43mod locked;
44#[cfg(test)]
45mod locked_tests;
46#[cfg(feature = "memory-lock")]
47mod locked_vec;
48mod preflight;
49#[cfg(test)]
50mod preflight_tests;
51#[cfg(feature = "memory-lock")]
52mod protected_decode;
53#[cfg(test)]
54mod protected_tests;
55mod stack;
56#[cfg(all(
57    feature = "memory-lock",
58    any(
59        all(
60            target_os = "linux",
61            any(target_arch = "x86_64", target_arch = "aarch64")
62        ),
63        target_os = "macos",
64        target_os = "ios",
65        target_os = "android",
66        target_os = "windows",
67        target_os = "freebsd",
68        target_os = "openbsd",
69        target_os = "netbsd",
70        target_os = "dragonfly",
71    ),
72    not(miri)
73))]
74mod v2_protected;
75
76#[cfg(feature = "alloc")]
77pub use bounded_decode::CtDecodeSanitizationBoundedExt;
78pub use compare::{LockedSanitizationCtEqExt, SanitizationCtEqExt, sanitization_ct_eq_public_len};
79pub use error::{LockedDecodeError, SanitizationDecodeError, SecretVecDecodeError};
80pub use preflight::DEFAULT_SECRET_VEC_DECODE_MAX_LEN;
81#[cfg(feature = "memory-lock")]
82pub use protected_decode::CtDecodeSanitizationProtectedExt;
83use sanitization::SecretBytes;
84#[cfg(all(
85    feature = "memory-lock",
86    any(
87        all(
88            target_os = "linux",
89            any(target_arch = "x86_64", target_arch = "aarch64")
90        ),
91        target_os = "macos",
92        target_os = "ios",
93        target_os = "android",
94        target_os = "windows",
95        target_os = "freebsd",
96        target_os = "openbsd",
97        target_os = "netbsd",
98        target_os = "dragonfly",
99    ),
100    not(miri)
101))]
102pub use v2_protected::{
103    ProtectedAllocation, SanitizationProtectedDecodeError, SanitizationProtectedDecodeExt,
104};
105
106#[cfg(feature = "alloc")]
107use sanitization::SecretVec;
108
109#[cfg(all(
110    feature = "memory-lock",
111    any(
112        all(
113            target_os = "linux",
114            any(target_arch = "x86_64", target_arch = "aarch64")
115        ),
116        target_os = "macos",
117        target_os = "ios",
118        target_os = "android",
119        target_os = "windows",
120        target_os = "freebsd",
121        target_os = "openbsd",
122        target_os = "netbsd",
123        target_os = "dragonfly",
124        all(target_arch = "wasm32", feature = "wasm-compat"),
125    )
126))]
127use sanitization::{LockedSecretBytes, LockedSecretBytesFillError, LockedSecretBytesGenerateError};
128
129#[cfg(all(
130    feature = "memory-lock",
131    any(
132        all(
133            target_os = "linux",
134            any(target_arch = "x86_64", target_arch = "aarch64")
135        ),
136        target_os = "macos",
137        target_os = "ios",
138        target_os = "android",
139        target_os = "windows",
140        target_os = "freebsd",
141        target_os = "openbsd",
142        target_os = "netbsd",
143        target_os = "dragonfly",
144    ),
145    not(miri)
146))]
147use sanitization::{LockedSecretVec, LockedSecretVecFillError};
148
149pub use sanitization::ct;
150pub use stack::MAX_SANITIZATION_STACK_SECRET_BYTES;
151
152/// Extension helpers for decoding with [`base64_ng::ct::CtEngine`] into
153/// `sanitization` secret containers.
154///
155/// These helpers use `decode_slice_staged_clear_tail` for fixed-size
156/// [`SecretBytes`] output so the public final container is only populated after
157/// the constant-time-oriented decode succeeds.
158pub trait CtDecodeSanitizationExt {
159    /// Decode `input` into a fixed-size clear-on-drop secret.
160    ///
161    /// The decoded length must exactly match `N`. A length mismatch returns
162    /// [`SanitizationDecodeError::LengthMismatch`] and no secret container is
163    /// returned.
164    ///
165    /// This method uses a private stack staging buffer and clears temporary
166    /// buffers before returning. `N` may not exceed
167    /// [`MAX_SANITIZATION_STACK_SECRET_BYTES`].
168    ///
169    /// # Errors
170    ///
171    /// Returns [`SanitizationDecodeError::EncodedInputLimit`] before validation
172    /// if encoded input exceeds the public limit derived from `N`.
173    /// Returns [`SanitizationDecodeError::Decode`] if Base64 decoding fails.
174    /// Returns [`SanitizationDecodeError::LengthMismatch`] if the decoded
175    /// length does not exactly equal `N`.
176    fn decode_secret_bytes<const N: usize>(
177        &self,
178        input: &[u8],
179    ) -> Result<SecretBytes<N>, SanitizationDecodeError>;
180
181    /// Decode `input` directly into fixed-size locked secret storage.
182    ///
183    /// Enable the `memory-lock` feature, or `high-assurance` for
184    /// the hardened native controls used by `high-assurance`, to use this
185    /// helper on supported native targets. Decode uses private stack staging,
186    /// then copies into locked storage only after the full decode succeeds.
187    /// `N` may not exceed [`MAX_SANITIZATION_STACK_SECRET_BYTES`].
188    ///
189    /// The decoded length must exactly match `N`. A length mismatch returns
190    /// [`SanitizationDecodeError::LengthMismatch`] inside the
191    /// `sanitization` generation error.
192    ///
193    /// # Errors
194    ///
195    /// Returns a `sanitization` memory error if locked storage cannot be
196    /// created. Returns [`SanitizationDecodeError::EncodedInputLimit`] before
197    /// allocation and validation if input exceeds the limit derived from `N`,
198    /// [`SanitizationDecodeError::Decode`] if Base64 decoding fails, or
199    /// [`SanitizationDecodeError::LengthMismatch`] if the decoded length does
200    /// not exactly equal `N`.
201    ///
202    /// # Security
203    ///
204    /// Successful construction does not prove that preferred dump and fork
205    /// controls were established. Inspect `protection_report()` or use
206    /// [`Self::decode_locked_secret_bytes_checked`].
207    #[cfg(all(
208        feature = "memory-lock",
209        any(
210            all(
211                target_os = "linux",
212                any(target_arch = "x86_64", target_arch = "aarch64")
213            ),
214            target_os = "macos",
215            target_os = "ios",
216            target_os = "android",
217            target_os = "windows",
218            target_os = "freebsd",
219            target_os = "openbsd",
220            target_os = "netbsd",
221            target_os = "dragonfly",
222            all(target_arch = "wasm32", feature = "wasm-compat"),
223        )
224    ))]
225    fn decode_locked_secret_bytes<const N: usize>(
226        &self,
227        input: &[u8],
228    ) -> Result<LockedSecretBytes<N>, LockedSecretBytesGenerateError<SanitizationDecodeError>>;
229
230    /// Decode through stack staging and initialize fixed-size locked storage
231    /// through sanitization's integrity-checked fill API.
232    ///
233    /// This method exposes `sanitization` 2.0's integrity-aware fill error.
234    /// Implementers must define the fill behavior explicitly; 2.0 provides no
235    /// compatibility default that can discard integrity failures.
236    /// `N` may not exceed [`MAX_SANITIZATION_STACK_SECRET_BYTES`].
237    ///
238    /// For allocation-time fail-closed protection, use
239    /// [`Self::decode_locked_secret_bytes_checked`].
240    ///
241    /// # Errors
242    ///
243    /// Returns a `sanitization` memory or integrity error when locked storage
244    /// cannot be initialized. Encoded-input-limit, decode, and exact-length
245    /// failures are returned in the fill error's generator branch.
246    #[cfg(all(
247        feature = "memory-lock",
248        any(
249            all(
250                target_os = "linux",
251                any(target_arch = "x86_64", target_arch = "aarch64")
252            ),
253            target_os = "macos",
254            target_os = "ios",
255            target_os = "android",
256            target_os = "windows",
257            target_os = "freebsd",
258            target_os = "openbsd",
259            target_os = "netbsd",
260            target_os = "dragonfly",
261            all(target_arch = "wasm32", feature = "wasm-compat"),
262        )
263    ))]
264    fn decode_locked_secret_bytes_fill<const N: usize>(
265        &self,
266        input: &[u8],
267    ) -> Result<LockedSecretBytes<N>, LockedSecretBytesFillError<SanitizationDecodeError>>;
268
269    /// Decode into fixed-size locked storage and reject degraded protection.
270    ///
271    /// In the provided [`base64_ng::ct::CtEngine`] implementation, this
272    /// fail-closed helper requires memory locking, dump exclusion, and fork
273    /// exclusion before the decoder receives the destination mapping. When
274    /// canaries are enabled, they are required too. Plaintext is decoded
275    /// directly into the already protected mapping, without an ordinary stack
276    /// plaintext buffer.
277    ///
278    /// Implementers must establish and admit the requested protections before
279    /// decoding. 2.0 provides no post-construction compatibility default.
280    ///
281    /// # Errors
282    ///
283    /// Returns [`LockedDecodeError::DegradedProtection`] when a required
284    /// control cannot be established before decoding or integrity validation
285    /// fails. This intentionally preserves the existing public error shape.
286    /// Returns [`LockedDecodeError::Operation`] for decode or exact-length
287    /// failures. Use
288    /// [`CtDecodeSanitizationProtectedExt::decode_locked_secret_bytes_checked_detailed`]
289    /// when protection and integrity failures require distinct incident
290    /// handling.
291    #[cfg(all(
292        feature = "memory-lock",
293        any(
294            all(
295                target_os = "linux",
296                any(target_arch = "x86_64", target_arch = "aarch64")
297            ),
298            target_os = "macos",
299            target_os = "ios",
300            target_os = "android",
301            target_os = "windows",
302            target_os = "freebsd",
303            target_os = "openbsd",
304            target_os = "netbsd",
305            target_os = "dragonfly",
306            all(target_arch = "wasm32", feature = "wasm-compat"),
307        )
308    ))]
309    fn decode_locked_secret_bytes_checked<const N: usize>(
310        &self,
311        input: &[u8],
312    ) -> Result<
313        LockedSecretBytes<N>,
314        LockedDecodeError<LockedSecretBytesGenerateError<SanitizationDecodeError>>,
315    >;
316
317    /// Decode `input` into a heap-backed clear-on-drop secret vector.
318    ///
319    /// Enable the `alloc` feature to use this helper. For shared-memory or
320    /// enclave-adjacent deployments where the final heap allocation must not
321    /// contain transient plaintext from rejected input, prefer
322    /// [`Self::decode_secret_vec_staged`] with a stack staging capacity large
323    /// enough for the decoded value. This convenience method rejects more
324    /// than [`DEFAULT_SECRET_VEC_DECODE_MAX_LEN`] decoded bytes and reserves
325    /// allocation fallibly. Use
326    /// [`CtDecodeSanitizationBoundedExt::decode_secret_vec_bounded`] for a
327    /// protocol-specific limit.
328    ///
329    /// # Errors
330    ///
331    /// Returns [`SecretVecDecodeError`] for encoded input above the derived
332    /// public ceiling, malformed input, output above the default ceiling, or
333    /// allocation failure.
334    #[cfg(feature = "alloc")]
335    fn decode_secret_vec(&self, input: &[u8]) -> Result<SecretVec, SecretVecDecodeError>;
336
337    /// Decode `input` through a private stack staging buffer into a
338    /// heap-backed clear-on-drop secret vector.
339    ///
340    /// `STAGE` must be at least the decoded byte length of `input` and may not
341    /// exceed [`MAX_SANITIZATION_STACK_SECRET_BYTES`]. Staging capacity is
342    /// checked before heap allocation.
343    ///
344    /// # Errors
345    ///
346    /// Returns [`SecretVecDecodeError`] for encoded input above the tighter
347    /// output/staging ceiling, malformed input, output above the default
348    /// ceiling, allocation failure, or insufficient staging capacity.
349    #[cfg(feature = "alloc")]
350    fn decode_secret_vec_staged<const STAGE: usize>(
351        &self,
352        input: &[u8],
353    ) -> Result<SecretVec, SecretVecDecodeError>;
354
355    /// Decode `input` directly into heap-backed locked secret storage.
356    ///
357    /// Enable the `memory-lock` feature, or `high-assurance` for the hardened
358    /// native controls used by `high-assurance`, to use this helper on
359    /// supported native targets. The locked mapping is created at the exact
360    /// decoded capacity and bytes are written directly into that mapping
361    /// through `sanitization::LockedSecretVec::try_from_capacity`.
362    ///
363    /// This compatibility convenience method rejects encoded input beyond the
364    /// ceiling derived from [`DEFAULT_SECRET_VEC_DECODE_MAX_LEN`] before full
365    /// validation. It also rejects valid decoded output larger than that
366    /// default. Use
367    /// [`CtDecodeSanitizationProtectedExt::decode_locked_secret_vec_checked_bounded`]
368    /// when the protocol requires a different public limit.
369    ///
370    /// # Errors
371    ///
372    /// Returns `LockedSecretVecFillError::Fill(DecodeError::InvalidLength)`
373    /// when encoded input exceeds the compatibility ceiling. Returns
374    /// `LockedSecretVecFillError::Length` when valid decoded output exceeds
375    /// [`DEFAULT_SECRET_VEC_DECODE_MAX_LEN`]. Returns the remaining memory,
376    /// integrity, and decoding failures from the locked-secret constructor.
377    ///
378    /// # Security
379    ///
380    /// Successful construction does not prove that preferred dump and fork
381    /// controls were established. Inspect `protection_report()` or use
382    /// [`Self::decode_locked_secret_vec_checked`].
383    #[cfg(all(
384        feature = "memory-lock",
385        any(
386            all(
387                target_os = "linux",
388                any(target_arch = "x86_64", target_arch = "aarch64")
389            ),
390            target_os = "macos",
391            target_os = "ios",
392            target_os = "android",
393            target_os = "windows",
394            target_os = "freebsd",
395            target_os = "openbsd",
396            target_os = "netbsd",
397            target_os = "dragonfly",
398        ),
399        not(miri)
400    ))]
401    fn decode_locked_secret_vec(
402        &self,
403        input: &[u8],
404    ) -> Result<LockedSecretVec, LockedSecretVecFillError<base64_ng::DecodeError>>;
405
406    /// Decode into dynamic locked storage and reject degraded protection.
407    ///
408    /// This compatibility convenience method rejects encoded input beyond the
409    /// ceiling derived from [`DEFAULT_SECRET_VEC_DECODE_MAX_LEN`] before full
410    /// validation. It also rejects valid decoded output larger than that
411    /// default. Use
412    /// [`CtDecodeSanitizationProtectedExt::decode_locked_secret_vec_checked_bounded`]
413    /// when the protocol requires a different public limit.
414    ///
415    /// # Errors
416    ///
417    /// In the built-in implementation, encoded input beyond the compatibility
418    /// ceiling returns [`LockedDecodeError::Operation`] containing
419    /// `LockedSecretVecFillError::Fill(DecodeError::InvalidLength)`. Valid
420    /// decoded output beyond [`DEFAULT_SECRET_VEC_DECODE_MAX_LEN`] returns
421    /// `Operation` containing `LockedSecretVecFillError::Length`. Other decode
422    /// or construction failures also return `Operation`, while
423    /// [`LockedDecodeError::DegradedProtection`] is returned when a required control
424    /// cannot be established or integrity validation fails. The compatibility
425    /// default also reports construction failures through `Operation`. Use
426    /// [`CtDecodeSanitizationProtectedExt::decode_locked_secret_vec_checked_detailed`]
427    /// for distinct protection and integrity failures, or
428    /// [`CtDecodeSanitizationProtectedExt::decode_locked_secret_vec_checked_bounded`]
429    /// to enforce a decoded-capacity limit before allocation.
430    ///
431    /// # Security
432    ///
433    /// In the provided [`base64_ng::ct::CtEngine`] implementation, the
434    /// `sanitization` 2.1.0 protected-capacity constructor requires memory
435    /// locking, dump exclusion, and fork exclusion before its fill closure can
436    /// run. Canaries are required when enabled. A required-control failure
437    /// therefore returns before decoded plaintext can enter the mapping.
438    ///
439    /// Implementers must establish and admit the requested protections before
440    /// decoding. 2.0 provides no post-construction compatibility default.
441    #[cfg(all(
442        feature = "memory-lock",
443        any(
444            all(
445                target_os = "linux",
446                any(target_arch = "x86_64", target_arch = "aarch64")
447            ),
448            target_os = "macos",
449            target_os = "ios",
450            target_os = "android",
451            target_os = "windows",
452            target_os = "freebsd",
453            target_os = "openbsd",
454            target_os = "netbsd",
455            target_os = "dragonfly",
456        ),
457        not(miri)
458    ))]
459    fn decode_locked_secret_vec_checked(
460        &self,
461        input: &[u8],
462    ) -> Result<LockedSecretVec, LockedDecodeError<LockedSecretVecFillError<base64_ng::DecodeError>>>;
463}
464
465#[cfg(test)]
466mod tests;