ciphern 0.2.1

Enterprise-grade cryptographic library
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
// Copyright (c) 2025 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

//! Cache-based attack protection
//!
//! This module provides protection against cache-timing attacks and cache-based
//! side-channel attacks through cache flushing, prefetching, and access randomization.

use crate::error::{CryptoError, Result};
use rand::{RngCore, SeedableRng};
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use std::arch::asm;
use std::ptr;
use std::sync::atomic;
use std::time::Duration;

/// Cache protection configuration
#[derive(Debug, Clone)]
pub struct CacheProtectionConfig {
    /// Enable cache flushing
    pub flush_enabled: bool,
    /// Enable cache prefetching
    pub prefetch_enabled: bool,
    /// Enable access randomization
    pub randomization_enabled: bool,
    /// Number of dummy cache lines to access
    pub dummy_access_count: usize,
}

impl Default for CacheProtectionConfig {
    fn default() -> Self {
        Self {
            flush_enabled: true,
            prefetch_enabled: true,
            randomization_enabled: true,
            dummy_access_count: 8,
        }
    }
}

/// Cache protection guard
pub struct CacheProtectionGuard {
    config: CacheProtectionConfig,
    _dummy_data: Vec<u8>,
}

#[allow(dead_code)]
impl CacheProtectionGuard {
    pub fn new(config: CacheProtectionConfig) -> Self {
        let dummy_data = vec![0u8; config.dummy_access_count * 64]; // 64 bytes per cache line

        Self {
            config,
            _dummy_data: dummy_data,
        }
    }

    /// Protect memory access operation
    pub fn protect_access<F, R>(&self, operation: F) -> Result<R>
    where
        F: FnOnce() -> Result<R>,
    {
        if self.config.flush_enabled {
            self.flush_cache_lines()?;
        }

        if self.config.randomization_enabled {
            self.randomize_cache_access()?;
        }

        if self.config.prefetch_enabled {
            self.prefetch_cache_lines()?;
        }

        let result = operation();

        if self.config.flush_enabled {
            self.flush_cache_lines()?;
        }

        result
    }

    fn flush_cache_lines(&self) -> Result<()> {
        // Flush cache lines for dummy data
        for chunk in self._dummy_data.chunks(64) {
            if let Some(ptr) = chunk.first() {
                flush_cache_line(ptr as *const u8);
            }
        }

        Ok(())
    }

    fn randomize_cache_access(&self) -> Result<()> {
        // Use thread-local RNG to avoid global lock contention
        thread_local! {
            static THREAD_RNG: std::cell::RefCell<rand::rngs::SmallRng> = std::cell::RefCell::new(
                rand::rngs::SmallRng::from_entropy()
            );
        }

        let mut indices = vec![0usize; self.config.dummy_access_count];
        THREAD_RNG.with(|rng| {
            let mut rng = rng.borrow_mut();
            let byte_slice = unsafe {
                std::slice::from_raw_parts_mut(
                    indices.as_mut_ptr() as *mut u8,
                    indices.len() * std::mem::size_of::<usize>(),
                )
            };
            rng.fill_bytes(byte_slice);
        });

        // Normalize indices to valid range
        for idx in &mut indices {
            *idx %= self.config.dummy_access_count;
        }

        // Access cache lines in random order
        for &index in &indices {
            let offset = index * 64;
            if offset < self._dummy_data.len() {
                // Touch the cache line to create random access pattern
                let _ = self._dummy_data[offset];
            }
        }

        Ok(())
    }

    fn prefetch_cache_lines(&self) -> Result<()> {
        // Prefetch cache lines to reduce timing variations
        for chunk in self._dummy_data.chunks(64) {
            if let Some(ptr) = chunk.first() {
                prefetch_cache_line(ptr as *const u8);
            }
        }

        Ok(())
    }
}

/// Flush a specific cache line (CLFLUSH instruction)
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn flush_cache_line(ptr: *const u8) {
    unsafe {
        asm!(
            "clflush [{0}]",
            in(reg) ptr,
            options(nostack, preserves_flags)
        );
    }
}

/// Prefetch a cache line (PREFETCHT0 instruction)
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn prefetch_cache_line(ptr: *const u8) {
    unsafe {
        asm!(
            "prefetcht0 [{0}]",
            in(reg) ptr,
            options(nostack, preserves_flags)
        );
    }
}

/// Empty implementation for non-x86 architectures
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
pub fn flush_cache_line(_ptr: *const u8) {
    // No cache flushing on non-x86 architectures
}

/// Empty implementation for non-x86 architectures
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
pub fn prefetch_cache_line(_ptr: *const u8) {
    // No cache prefetching on non-x86 architectures
}

/// Memory access pattern randomization
#[allow(dead_code)]
pub struct AccessPatternRandomizer {
    stride: usize,
    mask: usize,
}

#[allow(dead_code)]
impl AccessPatternRandomizer {
    pub fn new(data_size: usize) -> Result<Self> {
        // Use thread-local RNG to avoid global lock contention
        thread_local! {
            static THREAD_RNG: std::cell::RefCell<rand::rngs::SmallRng> = std::cell::RefCell::new(
                rand::rngs::SmallRng::from_entropy()
            );
        }

        let mut stride_bytes = [0u8; std::mem::size_of::<usize>()];
        THREAD_RNG.with(|rng| {
            let mut rng = rng.borrow_mut();
            rng.fill_bytes(&mut stride_bytes);
        });

        let stride = usize::from_le_bytes(stride_bytes) % 64 + 1; // Ensure non-zero stride
        let mask = data_size.next_power_of_two() - 1;

        Ok(Self { stride, mask })
    }

    /// Generate randomized access indices
    pub fn randomize_indices(&self, count: usize) -> Vec<usize> {
        let mut indices = Vec::with_capacity(count);
        let mut current = 0;

        for _ in 0..count {
            current = (current + self.stride) & self.mask;
            indices.push(current);
        }

        indices
    }
}

/// Cache partitioning to isolate sensitive data
#[allow(dead_code)]
pub struct CachePartition {
    partition_size: usize,
    partition_index: usize,
}

impl CachePartition {
    #[allow(dead_code)]
    pub fn new(partition_size: usize, partition_index: usize) -> Self {
        Self {
            partition_size,
            partition_index,
        }
    }

    /// Allocate memory in specific cache partition
    #[allow(dead_code)]
    pub fn allocate_in_partition(&self, size: usize) -> Vec<u8> {
        let total_size = size * self.partition_size * 64; // Each element is 64 bytes (cache line)
        let mut data = vec![0u8; total_size];

        // Touch every cache line within the specified partition
        // Partition index determines which cache lines to use
        for i in (self.partition_index * 64..total_size).step_by(self.partition_size * 64) {
            if i < data.len() {
                data[i] = 0xFF; // Touch the memory to allocate cache line
            }
        }

        data
    }
}

/// Cache timing measurement for detection
#[allow(dead_code)]
pub struct CacheTimingMeasurer {
    measurements: Vec<Duration>,
    threshold: Duration,
}

#[allow(dead_code)]
impl CacheTimingMeasurer {
    #[allow(dead_code)]
    pub fn new(threshold: Duration) -> Self {
        Self {
            measurements: Vec::new(),
            threshold,
        }
    }

    /// Measure cache access time
    #[allow(dead_code)]
    pub fn measure_access_time<F>(&mut self, operation: F) -> Result<Duration>
    where
        F: FnOnce(),
    {
        use std::time::Instant;

        let start = Instant::now();
        operation();
        let duration = start.elapsed();

        self.measurements.push(duration);

        // Keep only recent measurements
        if self.measurements.len() > 100 {
            self.measurements.remove(0);
        }

        Ok(duration)
    }

    /// Detect cache timing anomalies
    pub fn detect_anomaly(&self) -> Result<bool> {
        if self.measurements.len() < 10 {
            return Ok(false);
        }

        // Calculate average and standard deviation
        let sum: Duration = self.measurements.iter().sum();
        let average = sum / self.measurements.len() as u32;

        let variance_sum: f64 = self
            .measurements
            .iter()
            .map(|&d| {
                let diff = d.abs_diff(average);
                diff.as_nanos() as f64 * diff.as_nanos() as f64
            })
            .sum();

        let variance = variance_sum / self.measurements.len() as f64;
        let std_dev = Duration::from_nanos(variance.sqrt() as u64);

        // Check if any measurement is outside threshold
        for &measurement in &self.measurements {
            let deviation = measurement.abs_diff(average);

            if deviation > self.threshold || deviation > std_dev * 3 {
                return Ok(true);
            }
        }

        Ok(false)
    }
}

/// Flush entire CPU cache
#[allow(dead_code)]
pub fn flush_entire_cache() -> Result<()> {
    // Allocate large buffer to flush cache
    let size = 1024 * 1024; // 1MB
    let mut buffer = vec![0u8; size];

    // Access every cache line to force flush
    for i in (0..size).step_by(64) {
        buffer[i] = 0xFF;
    }

    // Memory barrier to ensure all writes complete
    std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);

    Ok(())
}

/// Non-temporal memory access to bypass cache
#[allow(dead_code)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn non_temporal_store(data: &[u8], dest: &mut [u8]) -> Result<()> {
    if data.len() != dest.len() {
        return Err(CryptoError::InvalidParameter("Size mismatch".into()));
    }

    // Use volatile write to prevent compiler optimizations
    unsafe {
        for (i, &byte) in data.iter().enumerate() {
            // Use volatile write to ensure memory access pattern
            let ptr = &mut dest[i] as *mut u8;
            ptr::write_volatile(ptr, byte);
            // Memory fence to ensure ordering
            atomic::compiler_fence(atomic::Ordering::SeqCst);
        }
    }

    // Memory fence to ensure all writes complete
    atomic::fence(atomic::Ordering::SeqCst);

    Ok(())
}

#[allow(dead_code)]
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
pub fn non_temporal_store(data: &[u8], dest: &mut [u8]) -> Result<()> {
    // Fallback for non-x86 architectures
    dest.copy_from_slice(data);
    Ok(())
}

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

    #[test]
    fn test_access_pattern_randomizer() {
        let randomizer = AccessPatternRandomizer::new(1024).unwrap();
        let indices = randomizer.randomize_indices(10);

        assert_eq!(indices.len(), 10);
        for &index in &indices {
            assert!(index < 1024);
        }
    }

    #[test]
    fn test_cache_partition() {
        let partition = CachePartition::new(4, 2);
        let data = partition.allocate_in_partition(256);

        assert_eq!(data.len(), 256 * 4 * 64); // 每个元素是64字节缓存行

        // Check that only partition-aligned locations are touched
        let mut touched_count = 0;
        for item in &data {
            if *item == 0xFF {
                touched_count += 1;
            }
        }

        // 计算期望的缓存行数量
        // partition_size=4, partition_index=2, size=256
        // 从索引2*64=128开始,每4*64=256个元素标记1个
        // 总共有256个缓存行需要标记
        let expected_count = 256;

        // Debug output
        println!(
            "Touched count: {}, Expected count: {}",
            touched_count, expected_count
        );

        assert_eq!(touched_count, expected_count);
    }

    #[test]
    fn test_cache_protection_guard() {
        let config = CacheProtectionConfig::default();
        let guard = CacheProtectionGuard::new(config);

        let result = guard.protect_access(|| Ok::<_, CryptoError>(42));

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
    }
}