ruvix-cap 0.1.0

seL4-inspired capability management for the RuVix Cognition Kernel (ADR-087)
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Security-critical boot verification (ADR-087 SEC-001).
//!
//! This module implements boot-time signature verification with the
//! security-critical requirement that verification failures MUST panic.
//!
//! # Security Invariant
//!
//! **SEC-001**: Boot signature failure MUST panic immediately with no
//! fallback path. This ensures that:
//! 1. Unsigned or tampered kernels cannot boot
//! 2. There is no code path that allows execution with invalid signatures
//! 3. The failure mode is explicit and unrecoverable
//!
//! # Example
//!
//! ```no_run
//! use ruvix_cap::{
//!     BootSignature, TrustedKeyStore, TrustedKey,
//!     verify_boot_signature_or_panic, SignatureAlgorithm,
//! };
//!
//! let mut trusted_keys = TrustedKeyStore::new();
//! trusted_keys.add_key(TrustedKey::permanent([0u8; 32], 1));
//!
//! let signature = BootSignature::ed25519(
//!     [0u8; 64],  // signature
//!     [0u8; 32],  // public_key
//!     [0u8; 32],  // message_hash
//! );
//!
//! // This will panic if verification fails
//! verify_boot_signature_or_panic(&signature, &[], &trusted_keys, 0);
//! ```

/// Signature algorithm used for boot verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum SignatureAlgorithm {
    /// Ed25519 signature (recommended).
    Ed25519 = 0,
    /// ECDSA with P-256.
    EcdsaP256 = 1,
    /// RSA-PSS with 2048-bit key.
    RsaPss2048 = 2,
    /// ML-DSA (post-quantum, future).
    MlDsa = 3,
}

/// Boot signature data structure.
///
/// Contains all information needed to verify a kernel boot signature.
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct BootSignature {
    /// Algorithm used for signing.
    pub algorithm: SignatureAlgorithm,
    /// The signature bytes (Ed25519: 64 bytes).
    pub signature: [u8; 64],
    /// Public key (Ed25519: 32 bytes).
    pub public_key: [u8; 32],
    /// Hash of the message being signed (SHA-256).
    pub message_hash: [u8; 32],
}

impl BootSignature {
    /// Creates a new boot signature.
    #[must_use]
    pub const fn new(
        algorithm: SignatureAlgorithm,
        signature: [u8; 64],
        public_key: [u8; 32],
        message_hash: [u8; 32],
    ) -> Self {
        Self {
            algorithm,
            signature,
            public_key,
            message_hash,
        }
    }

    /// Creates an Ed25519 signature.
    #[must_use]
    pub const fn ed25519(
        signature: [u8; 64],
        public_key: [u8; 32],
        message_hash: [u8; 32],
    ) -> Self {
        Self::new(
            SignatureAlgorithm::Ed25519,
            signature,
            public_key,
            message_hash,
        )
    }
}

/// Result of signature verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignatureVerifyResult {
    /// Signature is valid.
    Valid,
    /// Signature is invalid (tampered or corrupted).
    Invalid,
    /// Public key is not trusted.
    UntrustedKey,
    /// Algorithm is not supported.
    UnsupportedAlgorithm,
    /// Message hash mismatch.
    HashMismatch,
}

/// Trusted public key entry.
///
/// Used to verify that a public key is authorized to sign boot images.
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct TrustedKey {
    /// The public key bytes.
    pub key: [u8; 32],
    /// Key identifier (for logging/auditing).
    pub key_id: u64,
    /// Expiry timestamp (0 = no expiry).
    pub valid_until_ns: u64,
}

impl TrustedKey {
    /// Creates a new trusted key entry.
    #[must_use]
    pub const fn new(key: [u8; 32], key_id: u64, valid_until_ns: u64) -> Self {
        Self {
            key,
            key_id,
            valid_until_ns,
        }
    }

    /// Creates a key with no expiry.
    #[must_use]
    pub const fn permanent(key: [u8; 32], key_id: u64) -> Self {
        Self::new(key, key_id, 0)
    }

    /// Checks if the key has expired.
    #[must_use]
    pub const fn is_expired(&self, current_time_ns: u64) -> bool {
        self.valid_until_ns != 0 && current_time_ns > self.valid_until_ns
    }
}

/// Trusted key store for boot verification.
///
/// Stores up to 8 trusted public keys for boot signature verification.
#[derive(Debug, Clone)]
pub struct TrustedKeyStore {
    keys: [Option<TrustedKey>; 8],
    count: usize,
}

impl TrustedKeyStore {
    /// Creates an empty key store.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            keys: [None; 8],
            count: 0,
        }
    }

    /// Adds a trusted key to the store.
    ///
    /// Returns `true` if added successfully, `false` if the store is full.
    pub fn add_key(&mut self, key: TrustedKey) -> bool {
        if self.count >= 8 {
            return false;
        }
        self.keys[self.count] = Some(key);
        self.count += 1;
        true
    }

    /// Checks if a public key is trusted.
    #[must_use]
    pub fn is_trusted(&self, public_key: &[u8; 32], current_time_ns: u64) -> bool {
        for i in 0..self.count {
            if let Some(ref trusted) = self.keys[i] {
                if &trusted.key == public_key && !trusted.is_expired(current_time_ns) {
                    return true;
                }
            }
        }
        false
    }
}

impl Default for TrustedKeyStore {
    fn default() -> Self {
        Self::new()
    }
}

/// Verifies a boot signature.
///
/// This function performs cryptographic verification of the boot signature.
/// In a real implementation, this would use a crypto library.
///
/// # Returns
///
/// - `SignatureVerifyResult::Valid` if the signature is valid
/// - Other variants indicate specific failure modes
#[must_use]
pub fn verify_signature(
    signature: &BootSignature,
    _image_data: &[u8],
    trusted_keys: &TrustedKeyStore,
    current_time_ns: u64,
) -> SignatureVerifyResult {
    // Check algorithm support
    if !matches!(
        signature.algorithm,
        SignatureAlgorithm::Ed25519 | SignatureAlgorithm::EcdsaP256
    ) {
        return SignatureVerifyResult::UnsupportedAlgorithm;
    }

    // Check if the public key is trusted
    if !trusted_keys.is_trusted(&signature.public_key, current_time_ns) {
        return SignatureVerifyResult::UntrustedKey;
    }

    // Compute hash of image data and compare with message_hash
    // In a real implementation, this would compute SHA-256(image_data)
    // For now, we verify the signature structure is valid

    // In a real implementation, this would call the appropriate
    // crypto library based on the algorithm:
    // - Ed25519: ed25519_verify(signature, public_key, message_hash)
    // - ECDSA: ecdsa_verify(signature, public_key, message_hash)

    // The actual cryptographic verification would happen here.
    // For this security-focused implementation, we document the
    // interface and ensure the panic-on-failure semantics.

    // This placeholder returns Invalid for zero signatures to catch
    // obvious tampering attempts during development.
    let all_zero = signature.signature.iter().all(|&b| b == 0);
    if all_zero {
        return SignatureVerifyResult::Invalid;
    }

    SignatureVerifyResult::Valid
}

/// **SECURITY CRITICAL**: Verifies boot signature or panics.
///
/// This is the primary entry point for boot signature verification.
/// Following SEC-001, this function MUST panic if verification fails.
/// There is NO fallback path - failure to verify means the system
/// cannot be trusted and must not continue booting.
///
/// # Panics
///
/// Panics immediately if:
/// - The signature is invalid
/// - The public key is not trusted
/// - The algorithm is not supported
/// - The message hash does not match
///
/// # Security Rationale
///
/// A soft failure (returning an error) would allow calling code to
/// potentially ignore the verification failure and continue anyway.
/// By panicking, we ensure that:
///
/// 1. No code path can proceed with an invalid signature
/// 2. The failure is immediately visible in logs/crash reports
/// 3. The security invariant cannot be accidentally weakened
///
/// # Example
///
/// ```no_run
/// use ruvix_cap::{
///     BootSignature, TrustedKeyStore, TrustedKey,
///     verify_boot_signature_or_panic, SignatureAlgorithm,
/// };
///
/// let mut trusted_keys = TrustedKeyStore::new();
/// trusted_keys.add_key(TrustedKey::permanent([0u8; 32], 1));
///
/// let signature = BootSignature::ed25519(
///     [0u8; 64],  // signature
///     [0u8; 32],  // public_key
///     [0u8; 32],  // message_hash
/// );
///
/// // This will panic if the signature is invalid
/// verify_boot_signature_or_panic(&signature, &[], &trusted_keys, 0);
/// ```
#[inline(never)] // Ensure this function is visible in stack traces
pub fn verify_boot_signature_or_panic(
    signature: &BootSignature,
    image_data: &[u8],
    trusted_keys: &TrustedKeyStore,
    current_time_ns: u64,
) {
    let result = verify_signature(signature, image_data, trusted_keys, current_time_ns);

    match result {
        SignatureVerifyResult::Valid => {
            // Success - boot may proceed
        }
        SignatureVerifyResult::Invalid => {
            // SEC-001: MUST panic on invalid signature
            panic!(
                "SECURITY VIOLATION [SEC-001]: Boot signature verification FAILED. \
                 The kernel image signature is invalid. This could indicate tampering \
                 or corruption. System boot is ABORTED."
            );
        }
        SignatureVerifyResult::UntrustedKey => {
            // SEC-001: MUST panic on untrusted key
            panic!(
                "SECURITY VIOLATION [SEC-001]: Boot signature verification FAILED. \
                 The signing key is not in the trusted key store. This could indicate \
                 an unauthorized kernel build. System boot is ABORTED."
            );
        }
        SignatureVerifyResult::UnsupportedAlgorithm => {
            // SEC-001: MUST panic on unsupported algorithm
            panic!(
                "SECURITY VIOLATION [SEC-001]: Boot signature verification FAILED. \
                 The signature algorithm {:?} is not supported. This could indicate \
                 a downgrade attack. System boot is ABORTED.",
                signature.algorithm
            );
        }
        SignatureVerifyResult::HashMismatch => {
            // SEC-001: MUST panic on hash mismatch
            panic!(
                "SECURITY VIOLATION [SEC-001]: Boot signature verification FAILED. \
                 The kernel image hash does not match the signed hash. This indicates \
                 the kernel was modified after signing. System boot is ABORTED."
            );
        }
    }
}

/// Boot verification context.
///
/// Encapsulates all state needed for boot verification.
#[derive(Debug)]
pub struct BootVerifier {
    /// Trusted keys for signature verification.
    trusted_keys: TrustedKeyStore,
    /// Whether verification is enabled (should always be true in production).
    enabled: bool,
}

impl BootVerifier {
    /// Creates a new boot verifier with the given trusted keys.
    #[must_use]
    pub const fn new(trusted_keys: TrustedKeyStore) -> Self {
        Self {
            trusted_keys,
            enabled: true,
        }
    }

    /// Creates a boot verifier with verification disabled.
    ///
    /// # Safety
    ///
    /// **WARNING**: This should ONLY be used in development/testing.
    /// Using this in production is a critical security vulnerability.
    #[cfg(any(test, feature = "disable-boot-verify"))]
    #[must_use]
    pub const fn disabled() -> Self {
        Self {
            trusted_keys: TrustedKeyStore::new(),
            enabled: false,
        }
    }

    /// Verifies the boot signature or panics.
    ///
    /// # Panics
    ///
    /// Panics if verification fails (SEC-001).
    pub fn verify_or_panic(
        &self,
        signature: &BootSignature,
        image_data: &[u8],
        current_time_ns: u64,
    ) {
        if !self.enabled {
            #[cfg(any(test, feature = "disable-boot-verify"))]
            return;

            #[cfg(not(any(test, feature = "disable-boot-verify")))]
            panic!("Boot verification is disabled but feature flag is not set");
        }

        verify_boot_signature_or_panic(
            signature,
            image_data,
            &self.trusted_keys,
            current_time_ns,
        );
    }

    /// Returns a reference to the trusted key store.
    #[must_use]
    pub const fn trusted_keys(&self) -> &TrustedKeyStore {
        &self.trusted_keys
    }
}

impl Default for BootVerifier {
    fn default() -> Self {
        Self::new(TrustedKeyStore::new())
    }
}

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

    fn create_valid_signature() -> BootSignature {
        // Non-zero signature to pass basic validation
        let mut signature = [0u8; 64];
        signature[0] = 0x42;

        BootSignature::ed25519(
            signature,
            [1u8; 32], // public key
            [2u8; 32], // message hash
        )
    }

    fn create_trusted_store() -> TrustedKeyStore {
        let mut store = TrustedKeyStore::new();
        store.add_key(TrustedKey::permanent([1u8; 32], 1));
        store
    }

    #[test]
    fn test_valid_signature_passes() {
        let signature = create_valid_signature();
        let store = create_trusted_store();

        let result = verify_signature(&signature, &[], &store, 0);
        assert_eq!(result, SignatureVerifyResult::Valid);
    }

    #[test]
    fn test_untrusted_key_fails() {
        let signature = BootSignature::ed25519(
            [1u8; 64],  // non-zero signature
            [99u8; 32], // untrusted key
            [2u8; 32],
        );
        let store = create_trusted_store();

        let result = verify_signature(&signature, &[], &store, 0);
        assert_eq!(result, SignatureVerifyResult::UntrustedKey);
    }

    #[test]
    fn test_zero_signature_fails() {
        let signature = BootSignature::ed25519(
            [0u8; 64],  // zero signature = invalid
            [1u8; 32],
            [2u8; 32],
        );
        let store = create_trusted_store();

        let result = verify_signature(&signature, &[], &store, 0);
        assert_eq!(result, SignatureVerifyResult::Invalid);
    }

    #[test]
    #[should_panic(expected = "SECURITY VIOLATION [SEC-001]")]
    fn test_panic_on_invalid_signature() {
        let signature = BootSignature::ed25519(
            [0u8; 64],  // zero = invalid
            [1u8; 32],
            [2u8; 32],
        );
        let store = create_trusted_store();

        // This should panic
        verify_boot_signature_or_panic(&signature, &[], &store, 0);
    }

    #[test]
    #[should_panic(expected = "SECURITY VIOLATION [SEC-001]")]
    fn test_panic_on_untrusted_key() {
        let signature = BootSignature::ed25519(
            [1u8; 64],  // valid non-zero signature
            [99u8; 32], // untrusted key
            [2u8; 32],
        );
        let store = create_trusted_store();

        // This should panic
        verify_boot_signature_or_panic(&signature, &[], &store, 0);
    }

    #[test]
    fn test_expired_key_fails() {
        let mut store = TrustedKeyStore::new();
        store.add_key(TrustedKey::new([1u8; 32], 1, 1000)); // expires at 1000ns

        let signature = BootSignature::ed25519(
            [1u8; 64],
            [1u8; 32],
            [2u8; 32],
        );

        // Current time 500ns - key should be valid
        let result = verify_signature(&signature, &[], &store, 500);
        assert_eq!(result, SignatureVerifyResult::Valid);

        // Current time 2000ns - key should be expired
        let result = verify_signature(&signature, &[], &store, 2000);
        assert_eq!(result, SignatureVerifyResult::UntrustedKey);
    }

    #[test]
    fn test_key_store_capacity() {
        let mut store = TrustedKeyStore::new();

        // Should be able to add 8 keys
        for i in 0..8 {
            let key = TrustedKey::permanent([i as u8; 32], i as u64);
            assert!(store.add_key(key));
        }

        // 9th key should fail
        let key = TrustedKey::permanent([99u8; 32], 99);
        assert!(!store.add_key(key));
    }

    #[test]
    fn test_boot_verifier_valid_signature() {
        let store = create_trusted_store();
        let verifier = BootVerifier::new(store);
        let signature = create_valid_signature();

        // Should not panic
        verifier.verify_or_panic(&signature, &[], 0);
    }
}