Skip to main content

Mountain/IPC/Enhanced/SecureMessageChannel/
Channel.rs

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