Skip to main content

DevelopmentNodeEnvironment_MicrosoftVSCodeDependency_22NodeVersion_Bundle_Clean_Debug_ElectronProfile_EsbuildCompiler_Mountain/IPC/Enhanced/SecureMessageChannel/
Channel.rs

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