native-ossl 0.1.1

Native Rust idiomatic bindings to OpenSSL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Random number generation — `Rand` (simple), `RandAlg`, and `RandCtx`.
//!
//! Phase 3.4 delivers `RandAlg`; Phase 4.4 extends this module with
//! `Rand` and `RandCtx`.

use crate::error::ErrorStack;
use native_ossl_sys as sys;
use std::ffi::CStr;
use std::sync::Arc;

// ── RandAlg — algorithm descriptor ───────────────────────────────────────────

/// An OpenSSL RAND algorithm descriptor (`EVP_RAND*`).
///
/// Fetched once and reused to create `RandCtx` instances.
pub struct RandAlg {
    ptr: *mut sys::EVP_RAND,
    /// Keeps the library context alive for the lifetime of this descriptor.
    /// `EVP_RAND*` is bound to the context it was fetched from; dropping the
    /// context before the algorithm descriptor would leave the pointer dangling.
    _lib_ctx: Option<Arc<crate::lib_ctx::LibCtx>>,
}

impl RandAlg {
    /// Fetch a RAND algorithm from the global default library context.
    ///
    /// Common algorithm names: `c"CTR-DRBG"`, `c"HASH-DRBG"`, `c"HMAC-DRBG"`.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the algorithm is not available.
    pub fn fetch(name: &CStr, props: Option<&CStr>) -> Result<Self, ErrorStack> {
        let props_ptr = props.map_or(std::ptr::null(), CStr::as_ptr);
        let ptr = unsafe { sys::EVP_RAND_fetch(std::ptr::null_mut(), name.as_ptr(), props_ptr) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(RandAlg {
            ptr,
            _lib_ctx: None,
        })
    }

    /// Fetch a RAND algorithm within an explicit library context.
    ///
    /// Use this when the DRBG must be bound to a specific provider set
    /// (e.g. a FIPS-isolated `LibCtx`).
    ///
    /// The `Arc<LibCtx>` is retained for the lifetime of the `RandAlg` to
    /// ensure the context outlives the algorithm descriptor.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the algorithm is not available in `ctx`.
    pub fn fetch_in(
        ctx: &Arc<crate::lib_ctx::LibCtx>,
        name: &CStr,
        props: Option<&CStr>,
    ) -> Result<Self, ErrorStack> {
        let props_ptr = props.map_or(std::ptr::null(), CStr::as_ptr);
        let ptr = unsafe { sys::EVP_RAND_fetch(ctx.as_ptr(), name.as_ptr(), props_ptr) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(RandAlg {
            ptr,
            _lib_ctx: Some(Arc::clone(ctx)),
        })
    }

    /// Return the raw `EVP_RAND*` pointer.  Valid for the lifetime of `self`.
    #[must_use]
    pub(crate) fn as_ptr(&self) -> *mut sys::EVP_RAND {
        self.ptr
    }
}

impl Drop for RandAlg {
    fn drop(&mut self) {
        unsafe { sys::EVP_RAND_free(self.ptr) };
    }
}

// SAFETY: `EVP_RAND*` is reference-counted and immutable after fetch.
unsafe impl Send for RandAlg {}
unsafe impl Sync for RandAlg {}

// ── Rand — simple fill helpers (Phase 4.4) ────────────────────────────────────

/// Zero-size type with static methods wrapping `RAND_bytes` / `RAND_priv_bytes`.
pub struct Rand;

impl Rand {
    /// Fill `buf` with cryptographically random bytes.
    ///
    /// Zero-copy: writes directly into the caller's buffer.
    ///
    /// # Panics
    ///
    /// Panics if `buf.len() > i32::MAX`.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the PRNG fails (e.g. not seeded).
    pub fn fill(buf: &mut [u8]) -> Result<(), crate::error::ErrorStack> {
        let n = i32::try_from(buf.len()).expect("buffer too large for RAND_bytes");
        let rc = unsafe { sys::RAND_bytes(buf.as_mut_ptr(), n) };
        if rc != 1 {
            return Err(crate::error::ErrorStack::drain());
        }
        Ok(())
    }

    /// Fill `buf` with private (non-predictable) random bytes.
    ///
    /// # Panics
    ///
    /// Panics if `buf.len() > i32::MAX`.
    ///
    /// # Errors
    pub fn fill_private(buf: &mut [u8]) -> Result<(), crate::error::ErrorStack> {
        let n = i32::try_from(buf.len()).expect("buffer too large for RAND_priv_bytes");
        let rc = unsafe { sys::RAND_priv_bytes(buf.as_mut_ptr(), n) };
        if rc != 1 {
            return Err(crate::error::ErrorStack::drain());
        }
        Ok(())
    }

    /// Allocate and fill a `Vec<u8>` of `n` random bytes.
    ///
    /// Prefer `fill` when the destination buffer is already allocated.
    ///
    /// # Errors
    pub fn bytes(n: usize) -> Result<Vec<u8>, crate::error::ErrorStack> {
        let mut buf = vec![0u8; n];
        Self::fill(&mut buf)?;
        Ok(buf)
    }

    /// Allocate and fill a `Vec<u8>` of `n` private random bytes.
    ///
    /// Equivalent to `bytes` but uses `RAND_priv_bytes` — suitable for key
    /// material and other values that must not be disclosed.
    ///
    /// # Errors
    pub fn bytes_private(n: usize) -> Result<Vec<u8>, crate::error::ErrorStack> {
        let mut buf = vec![0u8; n];
        Self::fill_private(&mut buf)?;
        Ok(buf)
    }
}

// ── GenerateRequest — named struct for EVP_RAND_generate parameters ───────────

/// Parameters for `RandCtx::generate`.
///
/// Use struct update syntax for partial overrides:
/// ```ignore
/// GenerateRequest { prediction_resistance: true, ..Default::default() }
/// ```
pub struct GenerateRequest<'a> {
    /// Requested security strength in bits (e.g. 256).
    pub strength: u32,
    /// If `true`, OpenSSL reseeds before generating.
    pub prediction_resistance: bool,
    /// Optional additional input bytes fed into the DRBG.
    pub additional_input: Option<&'a [u8]>,
}

impl Default for GenerateRequest<'_> {
    fn default() -> Self {
        GenerateRequest {
            strength: 256,
            prediction_resistance: false,
            additional_input: None,
        }
    }
}

// ── RandState ─────────────────────────────────────────────────────────────────

/// Lifecycle state of a `RandCtx` DRBG instance.
///
/// Returned by [`RandCtx::state`]. Maps the `EVP_RAND_STATE_*` constants
/// from `<openssl/evp.h>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RandState {
    /// Context created but not yet instantiated (seeded).
    Uninitialised,
    /// Context is seeded and ready to generate.
    Ready,
    /// Context entered an unrecoverable error state.
    Error,
    /// Unrecognised value returned by OpenSSL (forward-compat guard).
    Unknown(i32),
}

// ── RandCtx — EVP_RAND_CTX wrapper ───────────────────────────────────────────

/// A seeded DRBG context (`EVP_RAND_CTX*`).
///
/// Has `up_ref` so `Clone` is implemented; wrapping in `Arc<RandCtx>` is safe.
pub struct RandCtx {
    ptr: *mut sys::EVP_RAND_CTX,
}

impl RandCtx {
    /// Create a new uninstantiated DRBG context from an algorithm descriptor.
    ///
    /// Provide `parent = None` to seed from the global PRNG.
    ///
    /// # Errors
    pub fn new(alg: &RandAlg, parent: Option<&RandCtx>) -> Result<Self, crate::error::ErrorStack> {
        let parent_ptr = parent.map_or(std::ptr::null_mut(), |p| p.ptr);
        let ptr = unsafe { sys::EVP_RAND_CTX_new(alg.as_ptr(), parent_ptr) };
        if ptr.is_null() {
            return Err(crate::error::ErrorStack::drain());
        }
        Ok(RandCtx { ptr })
    }

    /// Instantiate (seed) the DRBG at the requested security strength.
    ///
    /// Must be called before `generate` if the context was not auto-seeded.
    /// When `parent = None` was used in `new`, pass `strength ≤ 128` to stay
    /// within the system seed-source's entropy ceiling.
    ///
    /// # Errors
    pub fn instantiate(
        &mut self,
        strength: u32,
        prediction_resistance: bool,
        params: Option<&crate::params::Params<'_>>,
    ) -> Result<(), crate::error::ErrorStack> {
        let params_ptr = params.map_or(crate::params::null_params(), crate::params::Params::as_ptr);
        let rc = unsafe {
            sys::EVP_RAND_instantiate(
                self.ptr,
                strength,
                i32::from(prediction_resistance),
                std::ptr::null(),
                0,
                params_ptr,
            )
        };
        if rc != 1 {
            return Err(crate::error::ErrorStack::drain());
        }
        Ok(())
    }

    /// Generate random bytes into `out`.
    ///
    /// Zero-copy: writes directly into the caller's slice.
    ///
    /// # Errors
    pub fn generate(
        &mut self,
        out: &mut [u8],
        req: &GenerateRequest<'_>,
    ) -> Result<(), crate::error::ErrorStack> {
        let (ai_ptr, ai_len) = req
            .additional_input
            .map_or((std::ptr::null(), 0), |s| (s.as_ptr(), s.len()));

        let rc = unsafe {
            sys::EVP_RAND_generate(
                self.ptr,
                out.as_mut_ptr(),
                out.len(),
                req.strength,
                i32::from(req.prediction_resistance),
                ai_ptr,
                ai_len,
            )
        };
        if rc != 1 {
            return Err(crate::error::ErrorStack::drain());
        }
        Ok(())
    }

    /// Generate random bytes with default parameters (strength=256, no prediction
    /// resistance, no additional input).
    ///
    /// Equivalent to calling `generate` with [`GenerateRequest::default`].
    /// Call [`Self::instantiate`] before the first `fill`.
    ///
    /// # Errors
    pub fn fill(&mut self, out: &mut [u8]) -> Result<(), crate::error::ErrorStack> {
        self.generate(out, &GenerateRequest::default())
    }

    /// Security strength of this DRBG instance in bits.
    #[must_use]
    pub fn strength(&self) -> u32 {
        unsafe { sys::EVP_RAND_get_strength(self.ptr) }
    }

    /// Current lifecycle state of this DRBG context.
    ///
    /// Returns [`RandState::Ready`] after a successful [`Self::instantiate`].
    #[must_use]
    pub fn state(&self) -> RandState {
        match unsafe { sys::EVP_RAND_get_state(self.ptr) } {
            0 => RandState::Uninitialised,
            1 => RandState::Ready,
            2 => RandState::Error,
            n => RandState::Unknown(n),
        }
    }

    /// Return a reference to the process-wide **public** DRBG.
    ///
    /// The returned [`GlobalRandCtx`] does **not** free the pointer when dropped —
    /// the global DRBG is owned by the OpenSSL runtime.
    ///
    /// Pass `Some(global.as_rand_ctx())` as the `parent` argument to
    /// [`RandCtx::new`] to chain a child DRBG off the global instance.
    ///
    /// Requires OpenSSL 3.2+.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the global DRBG is not yet initialised.
    #[cfg(ossl320)]
    pub fn public() -> Result<GlobalRandCtx, crate::error::ErrorStack> {
        let ptr = unsafe { sys::RAND_get0_public(std::ptr::null_mut()) };
        if ptr.is_null() {
            return Err(crate::error::ErrorStack::drain());
        }
        Ok(GlobalRandCtx(std::mem::ManuallyDrop::new(RandCtx { ptr })))
    }

    /// Return a reference to the process-wide **private** DRBG.
    ///
    /// Same semantics as [`RandCtx::public`].
    ///
    /// Requires OpenSSL 3.2+.
    ///
    /// # Errors
    #[cfg(ossl320)]
    pub fn private_global() -> Result<GlobalRandCtx, crate::error::ErrorStack> {
        let ptr = unsafe { sys::RAND_get0_private(std::ptr::null_mut()) };
        if ptr.is_null() {
            return Err(crate::error::ErrorStack::drain());
        }
        Ok(GlobalRandCtx(std::mem::ManuallyDrop::new(RandCtx { ptr })))
    }
}

// ── GlobalRandCtx (OpenSSL 3.2+) ─────────────────────────────────────────────

/// A borrowed handle to one of the process-wide global DRBGs.
///
/// Obtained from [`RandCtx::public`] or [`RandCtx::private_global`].
///
/// **Does not implement `Clone` or `Drop`** — the global DRBG is owned by the
/// OpenSSL runtime and must not be freed through this handle.  Implements
/// `Deref<Target = RandCtx>` so all read-only `RandCtx` operations are available,
/// and `as_rand_ctx()` provides a `&RandCtx` to pass as a parent to [`RandCtx::new`].
#[cfg(ossl320)]
pub struct GlobalRandCtx(std::mem::ManuallyDrop<RandCtx>);

// SAFETY: the underlying EVP_RAND_CTX* is the global DRBG; it is safe to move
// this handle to another thread.
#[cfg(ossl320)]
unsafe impl Send for GlobalRandCtx {}

#[cfg(ossl320)]
impl std::ops::Deref for GlobalRandCtx {
    type Target = RandCtx;
    fn deref(&self) -> &RandCtx {
        &self.0
    }
}

#[cfg(ossl320)]
impl GlobalRandCtx {
    /// Borrow as `&RandCtx` for use as the `parent` argument in [`RandCtx::new`].
    #[must_use]
    pub fn as_rand_ctx(&self) -> &RandCtx {
        &self.0
    }
}

// EVP_RAND_CTX_up_ref was added in OpenSSL 3.1.0.
#[cfg(ossl310)]
impl Clone for RandCtx {
    fn clone(&self) -> Self {
        unsafe { sys::EVP_RAND_CTX_up_ref(self.ptr) };
        RandCtx { ptr: self.ptr }
    }
}

impl Drop for RandCtx {
    fn drop(&mut self) {
        unsafe { sys::EVP_RAND_CTX_free(self.ptr) };
    }
}

unsafe impl Send for RandCtx {}
unsafe impl Sync for RandCtx {}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fetch_ctr_drbg_succeeds() {
        let alg = RandAlg::fetch(c"CTR-DRBG", None).unwrap();
        drop(alg);
    }

    #[test]
    fn fetch_nonexistent_fails() {
        assert!(RandAlg::fetch(c"NONEXISTENT_RAND_XYZ", None).is_err());
    }

    #[test]
    fn rand_fill_nonzero() {
        let mut buf = [0u8; 32];
        Rand::fill(&mut buf).unwrap();
        // Probability of all-zero is 2^(-256) — treat as impossible.
        assert_ne!(buf, [0u8; 32]);
    }

    #[test]
    fn rand_bytes_len() {
        let v = Rand::bytes(64).unwrap();
        assert_eq!(v.len(), 64);
    }

    #[test]
    fn rand_ctx_two_outputs_differ() {
        let alg = RandAlg::fetch(c"CTR-DRBG", None).unwrap();
        let mut ctx = RandCtx::new(&alg, None).unwrap();
        // The default CTR-DRBG uses AES-256-CTR, which requires 256-bit entropy
        // from SEED-SRC.  Many systems cap at 128 bits without a parent DRBG.
        // Explicitly configure AES-128-CTR (128-bit strength) so instantiation
        // succeeds against the system SEED-SRC.
        let params = crate::params::ParamBuilder::new()
            .unwrap()
            .push_utf8_string(c"cipher", c"AES-128-CTR")
            .unwrap()
            .build()
            .unwrap();
        ctx.instantiate(128, false, Some(&params)).unwrap();

        let req = GenerateRequest {
            strength: 128,
            ..Default::default()
        };
        let mut a = [0u8; 32];
        let mut b = [0u8; 32];
        ctx.generate(&mut a, &req).unwrap();
        ctx.generate(&mut b, &req).unwrap();
        // Two consecutive generates should produce different output.
        assert_ne!(a, b);
    }
}