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