Mountain/IPC/Enhanced/SecureMessageChannel/
Channel.rs1#![allow(non_snake_case)]
2
3use std::{
9 collections::HashMap,
10 marker::PhantomData,
11 sync::Arc,
12 time::{Duration, SystemTime},
13};
14
15use bincode::serde::{decode_from_slice, encode_to_vec};
16use ring::{
17 aead::{self, AES_256_GCM, NONCE_LEN},
18 hmac,
19 rand::{SecureRandom, SystemRandom},
20};
21use serde::{Deserialize, Serialize};
22use tokio::sync::RwLock;
23
24use crate::{
25 IPC::Enhanced::SecureMessageChannel::{
26 EncryptedMessage::Struct as EncryptedMessage,
27 EncryptionKey::Struct as EncryptionKey,
28 SecureMessage::Struct as SecureMessage,
29 SecurityConfig::Struct as SecurityConfig,
30 SecurityStats::Struct as SecurityStats,
31 },
32 dev_log,
33};
34
35pub struct Struct {
36 pub config:SecurityConfig,
37
38 pub current_key:Arc<RwLock<EncryptionKey>>,
39
40 pub previous_keys:Arc<RwLock<HashMap<String, EncryptionKey>>>,
41
42 pub hmac_key:Arc<RwLock<Vec<u8>>>,
43
44 pub rng:SystemRandom,
45
46 pub key_rotation_task:Arc<RwLock<Option<tokio::task::JoinHandle<()>>>>,
47}
48
49impl Struct {
50 pub fn new(config:SecurityConfig) -> Result<Self, String> {
51 let rng = SystemRandom::new();
52
53 let mut encryption_key_bytes = vec![0u8; 32];
54
55 rng.fill(&mut encryption_key_bytes)
56 .map_err(|e| format!("Failed to generate encryption key: {}", e))?;
57
58 let encryption_key = EncryptionKey::new(&encryption_key_bytes)?;
59
60 let mut hmac_key = vec![0u8; 32];
61
62 rng.fill(&mut hmac_key)
63 .map_err(|e| format!("Failed to generate HMAC key: {}", e))?;
64
65 let channel = Self {
66 config,
67
68 current_key:Arc::new(RwLock::new(encryption_key)),
69
70 previous_keys:Arc::new(RwLock::new(HashMap::new())),
71
72 hmac_key:Arc::new(RwLock::new(hmac_key)),
73
74 rng,
75
76 key_rotation_task:Arc::new(RwLock::new(None)),
77 };
78
79 dev_log!(
80 "ipc",
81 "[SecureMessageChannel] Created secure channel with {} encryption",
82 channel.config.encryption_algorithm
83 );
84
85 Ok(channel)
86 }
87
88 pub async fn start(&self) -> Result<(), String> {
89 self.start_key_rotation().await;
90
91 dev_log!("ipc", "[SecureMessageChannel] Secure channel started");
92
93 Ok(())
94 }
95
96 pub async fn stop(&self) -> Result<(), String> {
97 {
98 let mut rotation_task = self.key_rotation_task.write().await;
99
100 if let Some(task) = rotation_task.take() {
101 task.abort();
102 }
103 }
104
105 {
106 let mut current_key = self.current_key.write().await;
107
108 *current_key = EncryptionKey::new(&[0u8; 32]).unwrap();
109 }
110
111 {
112 let mut previous_keys = self.previous_keys.write().await;
113
114 previous_keys.clear();
115 }
116
117 {
118 let mut hmac_key = self.hmac_key.write().await;
119
120 hmac_key.fill(0);
121 }
122
123 dev_log!("ipc", "[SecureMessageChannel] Secure channel stopped");
124
125 Ok(())
126 }
127
128 pub async fn encrypt_message<T:Serialize>(&self, message:&T) -> Result<EncryptedMessage, String> {
129 let serialized_data = encode_to_vec(message, bincode::config::standard())
130 .map_err(|e| format!("Failed to serialize message: {}", e))?;
131
132 if serialized_data.len() > self.config.max_message_size_bytes {
133 return Err(format!("Message too large: {} bytes", serialized_data.len()));
134 }
135
136 let mut current_key = self.current_key.write().await;
137
138 current_key.increment_usage();
139
140 let mut nonce = vec![0u8; self.config.nonce_size_bytes];
141
142 self.rng
143 .fill(&mut nonce)
144 .map_err(|e| format!("Failed to generate nonce: {}", e))?;
145
146 let mut in_out = serialized_data.clone();
147
148 let nonce_slice:&[u8] = &nonce;
149
150 let nonce_array:[u8; NONCE_LEN] = nonce_slice.try_into().map_err(|_| "Invalid nonce length".to_string())?;
151
152 let aead_nonce = aead::Nonce::assume_unique_for_key(nonce_array);
153
154 current_key
155 .key
156 .seal_in_place_append_tag(aead_nonce, aead::Aad::empty(), &mut in_out)
157 .map_err(|e| format!("Encryption failed: {}", e))?;
158
159 let hmac_key = self.hmac_key.read().await;
160
161 let hmac_key = hmac::Key::new(hmac::HMAC_SHA256, &hmac_key);
162
163 let hmac_tag = hmac::sign(&hmac_key, &in_out);
164
165 let encrypted_message = EncryptedMessage {
166 key_id:current_key.key_id.clone(),
167
168 nonce:nonce.to_vec(),
169
170 ciphertext:in_out,
171
172 hmac_tag:hmac_tag.as_ref().to_vec(),
173
174 timestamp:SystemTime::now()
175 .duration_since(SystemTime::UNIX_EPOCH)
176 .unwrap_or_default()
177 .as_millis() as u64,
178 };
179
180 dev_log!(
181 "ipc",
182 "[SecureMessageChannel] Message encrypted (size: {} bytes)",
183 encrypted_message.ciphertext.len()
184 );
185
186 Ok(encrypted_message)
187 }
188
189 pub async fn decrypt_message<T:for<'de> Deserialize<'de>>(&self, encrypted:&EncryptedMessage) -> Result<T, String> {
190 let hmac_key = self.hmac_key.read().await;
191
192 let hmac_key = hmac::Key::new(hmac::HMAC_SHA256, &hmac_key);
193
194 hmac::verify(&hmac_key, &encrypted.ciphertext, &encrypted.hmac_tag)
195 .map_err(|_| "HMAC verification failed".to_string())?;
196
197 let encryption_key = self.get_encryption_key(&encrypted.key_id).await?;
198
199 let mut in_out = encrypted.ciphertext.clone();
200
201 let nonce_slice:&[u8] = &encrypted.nonce;
202
203 let nonce_array:[u8; NONCE_LEN] = nonce_slice.try_into().map_err(|_| "Invalid nonce length".to_string())?;
204
205 let nonce = aead::Nonce::assume_unique_for_key(nonce_array);
206
207 encryption_key
208 .key
209 .open_in_place(nonce, aead::Aad::empty(), &mut in_out)
210 .map_err(|e| format!("Decryption failed: {}", e))?;
211
212 let plaintext_len = in_out.len() - AES_256_GCM.tag_len();
213
214 in_out.truncate(plaintext_len);
215
216 let (message, _) = decode_from_slice(&in_out, bincode::config::standard())
217 .map_err(|e| format!("Failed to deserialize message: {}", e))?;
218
219 dev_log!("ipc", "[SecureMessageChannel] Message decrypted successfully");
220
221 Ok(message)
222 }
223
224 pub async fn rotate_keys(&self) -> Result<(), String> {
225 dev_log!("ipc", "[SecureMessageChannel] Rotating encryption keys");
226
227 let mut new_key_bytes = vec![0u8; 32];
228
229 self.rng
230 .fill(&mut new_key_bytes)
231 .map_err(|e| format!("Failed to generate new encryption key: {}", e))?;
232
233 let new_key = EncryptionKey::new(&new_key_bytes)?;
234
235 {
236 let mut current_key = self.current_key.write().await;
237
238 let mut previous_keys = self.previous_keys.write().await;
239
240 previous_keys.insert(current_key.key_id.clone(), current_key.clone());
241
242 *current_key = new_key;
243 }
244
245 self.cleanup_old_keys().await;
246
247 dev_log!("ipc", "[SecureMessageChannel] Key rotation completed");
248
249 Ok(())
250 }
251
252 async fn get_encryption_key(&self, key_id:&str) -> Result<EncryptionKey, String> {
253 let current_key = self.current_key.read().await;
254
255 if current_key.key_id == key_id {
256 return Ok(current_key.clone());
257 }
258
259 let previous_keys = self.previous_keys.read().await;
260
261 if let Some(key) = previous_keys.get(key_id) {
262 return Ok(key.clone());
263 }
264
265 Err(format!("Encryption key not found: {}", key_id))
266 }
267
268 async fn start_key_rotation(&self) {
269 let channel = Arc::new(self.clone());
270
271 let rotation_interval = Duration::from_secs(self.config.key_rotation_interval_hours * 3600);
272
273 let task = tokio::spawn(async move {
274 let mut interval = tokio::time::interval(rotation_interval);
275
276 loop {
277 interval.tick().await;
278
279 if let Err(e) = channel.rotate_keys().await {
280 dev_log!("ipc", "error: [SecureMessageChannel] Automatic key rotation failed: {}", e);
281 }
282 }
283 });
284
285 {
286 let mut rotation_task = self.key_rotation_task.write().await;
287
288 *rotation_task = Some(task);
289 }
290 }
291
292 async fn cleanup_old_keys(&self) {
293 let rotation_interval = Duration::from_secs(self.config.key_rotation_interval_hours * 3600);
294
295 let max_age = rotation_interval * 2;
296
297 let mut previous_keys = self.previous_keys.write().await;
298
299 previous_keys.retain(|_, key| !key.is_expired(max_age));
300
301 dev_log!("ipc", "[SecureMessageChannel] Cleaned up {} old keys", previous_keys.len());
302 }
303
304 pub async fn get_stats(&self) -> SecurityStats {
305 let current_key = self.current_key.read().await;
306
307 let previous_keys = self.previous_keys.read().await;
308
309 SecurityStats {
310 current_key_id:current_key.key_id.clone(),
311
312 current_key_age_seconds:current_key.created_at.elapsed().unwrap_or_default().as_secs(),
313
314 current_key_usage_count:current_key.usage_count,
315
316 previous_keys_count:previous_keys.len(),
317
318 config:self.config.clone(),
319 }
320 }
321
322 pub async fn validate_message_integrity(&self, encrypted:&EncryptedMessage) -> Result<bool, String> {
323 let message_time = SystemTime::UNIX_EPOCH + Duration::from_millis(encrypted.timestamp);
324
325 let current_time = SystemTime::now();
326
327 if current_time.duration_since(message_time).unwrap_or_default() > Duration::from_secs(300) {
328 return Ok(false);
329 }
330
331 let hmac_key = self.hmac_key.read().await;
332
333 let hmac_key = hmac::Key::new(hmac::HMAC_SHA256, &hmac_key);
334
335 match hmac::verify(&hmac_key, &encrypted.ciphertext, &encrypted.hmac_tag) {
336 Ok(_) => Ok(true),
337
338 Err(_) => Ok(false),
339 }
340 }
341
342 pub fn default_channel() -> Result<Self, String> { Self::new(SecurityConfig::default()) }
343
344 pub fn high_security_channel() -> Result<Self, String> {
345 Self::new(SecurityConfig {
346 key_rotation_interval_hours:1,
347 max_message_size_bytes:1024 * 1024,
348 ..Default::default()
349 })
350 }
351
352 pub fn generate_secure_key(key_size_bytes:usize) -> Result<Vec<u8>, String> {
353 let rng = SystemRandom::new();
354
355 let mut key = vec![0u8; key_size_bytes];
356
357 rng.fill(&mut key)
358 .map_err(|e| format!("Failed to generate secure key: {}", e))?;
359
360 Ok(key)
361 }
362
363 pub fn calculate_encryption_overhead(_message_size:usize) -> usize { NONCE_LEN + AES_256_GCM.tag_len() + 16 }
364
365 pub fn estimate_encrypted_size(original_size:usize) -> usize {
366 original_size + Self::calculate_encryption_overhead(original_size)
367 }
368
369 pub async fn create_secure_message<T:Serialize>(
370 &self,
371
372 message:&T,
373
374 additional_headers:HashMap<String, String>,
375 ) -> Result<SecureMessage<T>, String> {
376 let encrypted = self.encrypt_message(message).await?;
377
378 Ok(SecureMessage::<T> {
379 encrypted,
380 headers:additional_headers,
381 version:"1.0".to_string(),
382 _marker:PhantomData,
383 })
384 }
385}
386
387impl Clone for Struct {
388 fn clone(&self) -> Self {
389 Self {
390 config:self.config.clone(),
391
392 current_key:self.current_key.clone(),
393
394 previous_keys:self.previous_keys.clone(),
395
396 hmac_key:self.hmac_key.clone(),
397
398 rng:SystemRandom::new(),
399
400 key_rotation_task:Arc::new(RwLock::new(None)),
401 }
402 }
403}