Skip to main content

fynx_proto/ssh/
crypto.rs

1//! SSH cryptographic operations.
2//!
3//! This module implements encryption and MAC algorithms for SSH:
4//! - ChaCha20-Poly1305 (AEAD cipher)
5//! - AES-128-GCM, AES-256-GCM (AEAD ciphers)
6//! - AES-128-CTR, AES-256-CTR (stream ciphers with separate MAC)
7//! - HMAC-SHA256, HMAC-SHA512 (MAC algorithms)
8//!
9//! # Security
10//!
11//! - **AEAD ciphers** - Authenticated encryption with associated data
12//! - **Nonce management** - Ensures nonce uniqueness for AEAD ciphers
13//! - **Key derivation** - Uses SSH key derivation from kex_dh module
14//!
15//! # Example
16//!
17//! ```rust,ignore
18//! use fynx_proto::ssh::crypto::Cipher;
19//!
20//! // Create ChaCha20-Poly1305 cipher
21//! let cipher = Cipher::chacha20_poly1305(&key, &iv);
22//! ```
23
24use fynx_platform::{FynxError, FynxResult};
25use hmac::{Hmac, Mac};
26use ring::aead::{
27    Aad, BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey, AES_128_GCM,
28    AES_256_GCM, CHACHA20_POLY1305,
29};
30use sha2::{Sha256, Sha512};
31use zeroize::Zeroize;
32
33/// Nonce counter for AEAD ciphers.
34///
35/// SSH uses a 64-bit packet sequence number as the nonce.
36struct Counter {
37    value: u64,
38}
39
40impl Counter {
41    fn new() -> Self {
42        Self { value: 0 }
43    }
44}
45
46impl NonceSequence for Counter {
47    fn advance(&mut self) -> Result<Nonce, ring::error::Unspecified> {
48        let mut nonce_bytes = [0u8; 12];
49        // Use packet sequence number as nonce (last 8 bytes)
50        nonce_bytes[4..12].copy_from_slice(&self.value.to_be_bytes());
51        self.value = self.value.wrapping_add(1);
52        Nonce::try_assume_unique_for_key(&nonce_bytes)
53    }
54}
55
56/// Cipher algorithm for SSH encryption.
57#[derive(Debug)]
58pub enum CipherAlgorithm {
59    /// ChaCha20-Poly1305 AEAD cipher
60    ChaCha20Poly1305,
61    /// AES-128-GCM AEAD cipher
62    Aes128Gcm,
63    /// AES-256-GCM AEAD cipher
64    Aes256Gcm,
65    /// AES-128-CTR stream cipher (requires separate MAC)
66    Aes128Ctr,
67    /// AES-256-CTR stream cipher (requires separate MAC)
68    Aes256Ctr,
69}
70
71impl CipherAlgorithm {
72    /// Returns the algorithm name.
73    pub fn name(&self) -> &'static str {
74        match self {
75            CipherAlgorithm::ChaCha20Poly1305 => "chacha20-poly1305@openssh.com",
76            CipherAlgorithm::Aes128Gcm => "aes128-gcm@openssh.com",
77            CipherAlgorithm::Aes256Gcm => "aes256-gcm@openssh.com",
78            CipherAlgorithm::Aes128Ctr => "aes128-ctr",
79            CipherAlgorithm::Aes256Ctr => "aes256-ctr",
80        }
81    }
82
83    /// Returns the key size in bytes.
84    pub fn key_size(&self) -> usize {
85        match self {
86            CipherAlgorithm::ChaCha20Poly1305 => 32,
87            CipherAlgorithm::Aes128Gcm => 16,
88            CipherAlgorithm::Aes256Gcm => 32,
89            CipherAlgorithm::Aes128Ctr => 16,
90            CipherAlgorithm::Aes256Ctr => 32,
91        }
92    }
93
94    /// Returns the IV/nonce size in bytes.
95    pub fn iv_size(&self) -> usize {
96        match self {
97            CipherAlgorithm::ChaCha20Poly1305 => 12,
98            CipherAlgorithm::Aes128Gcm => 12,
99            CipherAlgorithm::Aes256Gcm => 12,
100            CipherAlgorithm::Aes128Ctr => 16,
101            CipherAlgorithm::Aes256Ctr => 16,
102        }
103    }
104
105    /// Returns the authentication tag size in bytes (for AEAD ciphers).
106    pub fn tag_size(&self) -> usize {
107        match self {
108            CipherAlgorithm::ChaCha20Poly1305 => 16,
109            CipherAlgorithm::Aes128Gcm => 16,
110            CipherAlgorithm::Aes256Gcm => 16,
111            CipherAlgorithm::Aes128Ctr => 0,
112            CipherAlgorithm::Aes256Ctr => 0,
113        }
114    }
115
116    /// Returns true if this is an AEAD cipher.
117    pub fn is_aead(&self) -> bool {
118        matches!(
119            self,
120            CipherAlgorithm::ChaCha20Poly1305
121                | CipherAlgorithm::Aes128Gcm
122                | CipherAlgorithm::Aes256Gcm
123        )
124    }
125
126    /// Parses cipher algorithm from name.
127    pub fn from_name(name: &str) -> Option<Self> {
128        match name {
129            "chacha20-poly1305@openssh.com" => Some(CipherAlgorithm::ChaCha20Poly1305),
130            "aes128-gcm@openssh.com" => Some(CipherAlgorithm::Aes128Gcm),
131            "aes256-gcm@openssh.com" => Some(CipherAlgorithm::Aes256Gcm),
132            "aes128-ctr" => Some(CipherAlgorithm::Aes128Ctr),
133            "aes256-ctr" => Some(CipherAlgorithm::Aes256Ctr),
134            _ => None,
135        }
136    }
137}
138
139/// Encryption key for AEAD ciphers.
140pub struct EncryptionKey {
141    algorithm: CipherAlgorithm,
142    key: Option<SealingKey<Counter>>,
143}
144
145impl std::fmt::Debug for EncryptionKey {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        f.debug_struct("EncryptionKey")
148            .field("algorithm", &self.algorithm)
149            .field("key", &"<redacted>")
150            .finish()
151    }
152}
153
154impl EncryptionKey {
155    /// Creates a new encryption key.
156    pub fn new(algorithm: CipherAlgorithm, key_material: &[u8]) -> FynxResult<Self> {
157        if key_material.len() < algorithm.key_size() {
158            return Err(FynxError::Security(format!(
159                "Insufficient key material: expected {}, got {}",
160                algorithm.key_size(),
161                key_material.len()
162            )));
163        }
164
165        let key = match algorithm {
166            CipherAlgorithm::ChaCha20Poly1305 => {
167                let unbound_key = UnboundKey::new(&CHACHA20_POLY1305, &key_material[..32])
168                    .map_err(|_| {
169                        FynxError::Security("Failed to create ChaCha20-Poly1305 key".to_string())
170                    })?;
171                Some(SealingKey::new(unbound_key, Counter::new()))
172            }
173            CipherAlgorithm::Aes128Gcm => {
174                let unbound_key =
175                    UnboundKey::new(&AES_128_GCM, &key_material[..16]).map_err(|_| {
176                        FynxError::Security("Failed to create AES-128-GCM key".to_string())
177                    })?;
178                Some(SealingKey::new(unbound_key, Counter::new()))
179            }
180            CipherAlgorithm::Aes256Gcm => {
181                let unbound_key =
182                    UnboundKey::new(&AES_256_GCM, &key_material[..32]).map_err(|_| {
183                        FynxError::Security("Failed to create AES-256-GCM key".to_string())
184                    })?;
185                Some(SealingKey::new(unbound_key, Counter::new()))
186            }
187            CipherAlgorithm::Aes128Ctr | CipherAlgorithm::Aes256Ctr => {
188                // CTR mode ciphers need different implementation (not AEAD)
189                None
190            }
191        };
192
193        Ok(Self { algorithm, key })
194    }
195
196    /// Encrypts data in place (AEAD mode).
197    pub fn encrypt(&mut self, data: &mut Vec<u8>) -> FynxResult<()> {
198        if let Some(ref mut key) = self.key {
199            key.seal_in_place_append_tag(Aad::empty(), data)
200                .map_err(|_| FynxError::Security("Encryption failed".to_string()))?;
201            Ok(())
202        } else {
203            Err(FynxError::Security(
204                "CTR mode requires separate implementation".to_string(),
205            ))
206        }
207    }
208
209    /// Returns the algorithm.
210    pub fn algorithm(&self) -> &CipherAlgorithm {
211        &self.algorithm
212    }
213}
214
215impl Drop for EncryptionKey {
216    fn drop(&mut self) {
217        // Keys are zeroized by ring's Drop implementation
218    }
219}
220
221/// Decryption key for AEAD ciphers.
222pub struct DecryptionKey {
223    algorithm: CipherAlgorithm,
224    key: Option<OpeningKey<Counter>>,
225}
226
227impl std::fmt::Debug for DecryptionKey {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        f.debug_struct("DecryptionKey")
230            .field("algorithm", &self.algorithm)
231            .field("key", &"<redacted>")
232            .finish()
233    }
234}
235
236impl DecryptionKey {
237    /// Creates a new decryption key.
238    pub fn new(algorithm: CipherAlgorithm, key_material: &[u8]) -> FynxResult<Self> {
239        if key_material.len() < algorithm.key_size() {
240            return Err(FynxError::Security(format!(
241                "Insufficient key material: expected {}, got {}",
242                algorithm.key_size(),
243                key_material.len()
244            )));
245        }
246
247        let key = match algorithm {
248            CipherAlgorithm::ChaCha20Poly1305 => {
249                let unbound_key = UnboundKey::new(&CHACHA20_POLY1305, &key_material[..32])
250                    .map_err(|_| {
251                        FynxError::Security("Failed to create ChaCha20-Poly1305 key".to_string())
252                    })?;
253                Some(OpeningKey::new(unbound_key, Counter::new()))
254            }
255            CipherAlgorithm::Aes128Gcm => {
256                let unbound_key =
257                    UnboundKey::new(&AES_128_GCM, &key_material[..16]).map_err(|_| {
258                        FynxError::Security("Failed to create AES-128-GCM key".to_string())
259                    })?;
260                Some(OpeningKey::new(unbound_key, Counter::new()))
261            }
262            CipherAlgorithm::Aes256Gcm => {
263                let unbound_key =
264                    UnboundKey::new(&AES_256_GCM, &key_material[..32]).map_err(|_| {
265                        FynxError::Security("Failed to create AES-256-GCM key".to_string())
266                    })?;
267                Some(OpeningKey::new(unbound_key, Counter::new()))
268            }
269            CipherAlgorithm::Aes128Ctr | CipherAlgorithm::Aes256Ctr => {
270                // CTR mode ciphers need different implementation (not AEAD)
271                None
272            }
273        };
274
275        Ok(Self { algorithm, key })
276    }
277
278    /// Decrypts data in place (AEAD mode).
279    pub fn decrypt(&mut self, data: &mut Vec<u8>) -> FynxResult<()> {
280        if let Some(ref mut key) = self.key {
281            let plaintext_len = {
282                let plaintext = key.open_in_place(Aad::empty(), data).map_err(|_| {
283                    FynxError::Security(
284                        "Decryption failed or authentication tag mismatch".to_string(),
285                    )
286                })?;
287                plaintext.len()
288            };
289            // Truncate to remove the tag
290            data.truncate(plaintext_len);
291            Ok(())
292        } else {
293            Err(FynxError::Security(
294                "CTR mode requires separate implementation".to_string(),
295            ))
296        }
297    }
298
299    /// Returns the algorithm.
300    pub fn algorithm(&self) -> &CipherAlgorithm {
301        &self.algorithm
302    }
303}
304
305impl Drop for DecryptionKey {
306    fn drop(&mut self) {
307        // Keys are zeroized by ring's Drop implementation
308    }
309}
310
311/// MAC algorithm for SSH.
312#[derive(Debug, Clone, Copy)]
313pub enum MacAlgorithm {
314    /// HMAC-SHA256
315    HmacSha256,
316    /// HMAC-SHA512
317    HmacSha512,
318}
319
320impl MacAlgorithm {
321    /// Returns the algorithm name.
322    pub fn name(&self) -> &'static str {
323        match self {
324            MacAlgorithm::HmacSha256 => "hmac-sha2-256",
325            MacAlgorithm::HmacSha512 => "hmac-sha2-512",
326        }
327    }
328
329    /// Returns the key size in bytes.
330    pub fn key_size(&self) -> usize {
331        match self {
332            MacAlgorithm::HmacSha256 => 32,
333            MacAlgorithm::HmacSha512 => 64,
334        }
335    }
336
337    /// Returns the MAC output size in bytes.
338    pub fn mac_size(&self) -> usize {
339        match self {
340            MacAlgorithm::HmacSha256 => 32,
341            MacAlgorithm::HmacSha512 => 64,
342        }
343    }
344
345    /// Parses MAC algorithm from name.
346    pub fn from_name(name: &str) -> Option<Self> {
347        match name {
348            "hmac-sha2-256" => Some(MacAlgorithm::HmacSha256),
349            "hmac-sha2-512" => Some(MacAlgorithm::HmacSha512),
350            _ => None,
351        }
352    }
353}
354
355/// MAC key for computing message authentication codes.
356pub struct MacKey {
357    algorithm: MacAlgorithm,
358    key: Vec<u8>,
359    sequence: u32,
360}
361
362impl std::fmt::Debug for MacKey {
363    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
364        f.debug_struct("MacKey")
365            .field("algorithm", &self.algorithm)
366            .field("key", &"<redacted>")
367            .field("sequence", &self.sequence)
368            .finish()
369    }
370}
371
372impl MacKey {
373    /// Creates a new MAC key.
374    pub fn new(algorithm: MacAlgorithm, key_material: &[u8]) -> FynxResult<Self> {
375        if key_material.len() < algorithm.key_size() {
376            return Err(FynxError::Security(format!(
377                "Insufficient key material for MAC: expected {}, got {}",
378                algorithm.key_size(),
379                key_material.len()
380            )));
381        }
382
383        Ok(Self {
384            algorithm,
385            key: key_material[..algorithm.key_size()].to_vec(),
386            sequence: 0,
387        })
388    }
389
390    /// Computes MAC for packet data.
391    ///
392    /// # Arguments
393    ///
394    /// * `packet_data` - The packet data (without MAC)
395    ///
396    /// # Returns
397    ///
398    /// The MAC bytes
399    pub fn compute(&mut self, packet_data: &[u8]) -> Vec<u8> {
400        let mut data = Vec::new();
401        data.extend_from_slice(&self.sequence.to_be_bytes());
402        data.extend_from_slice(packet_data);
403
404        let mac = match self.algorithm {
405            MacAlgorithm::HmacSha256 => {
406                let mut mac =
407                    Hmac::<Sha256>::new_from_slice(&self.key).expect("HMAC key size is valid");
408                mac.update(&data);
409                mac.finalize().into_bytes().to_vec()
410            }
411            MacAlgorithm::HmacSha512 => {
412                let mut mac =
413                    Hmac::<Sha512>::new_from_slice(&self.key).expect("HMAC key size is valid");
414                mac.update(&data);
415                mac.finalize().into_bytes().to_vec()
416            }
417        };
418
419        self.sequence = self.sequence.wrapping_add(1);
420        mac
421    }
422
423    /// Verifies MAC for packet data.
424    ///
425    /// # Arguments
426    ///
427    /// * `packet_data` - The packet data (without MAC)
428    /// * `received_mac` - The received MAC bytes
429    ///
430    /// # Returns
431    ///
432    /// `Ok(())` if MAC is valid, error otherwise
433    pub fn verify(&mut self, packet_data: &[u8], received_mac: &[u8]) -> FynxResult<()> {
434        let computed_mac = self.compute(packet_data);
435
436        if computed_mac.len() != received_mac.len() {
437            return Err(FynxError::Security("MAC length mismatch".to_string()));
438        }
439
440        // Use constant-time comparison
441        use subtle::ConstantTimeEq;
442        if computed_mac.ct_eq(received_mac).into() {
443            Ok(())
444        } else {
445            Err(FynxError::Security("MAC verification failed".to_string()))
446        }
447    }
448
449    /// Returns the algorithm.
450    pub fn algorithm(&self) -> MacAlgorithm {
451        self.algorithm
452    }
453}
454
455impl Drop for MacKey {
456    fn drop(&mut self) {
457        self.key.zeroize();
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    #[test]
466    fn test_cipher_algorithm_properties() {
467        let chacha = CipherAlgorithm::ChaCha20Poly1305;
468        assert_eq!(chacha.name(), "chacha20-poly1305@openssh.com");
469        assert_eq!(chacha.key_size(), 32);
470        assert_eq!(chacha.iv_size(), 12);
471        assert_eq!(chacha.tag_size(), 16);
472        assert!(chacha.is_aead());
473
474        let aes128 = CipherAlgorithm::Aes128Gcm;
475        assert_eq!(aes128.key_size(), 16);
476        assert!(aes128.is_aead());
477
478        let aes256_ctr = CipherAlgorithm::Aes256Ctr;
479        assert_eq!(aes256_ctr.key_size(), 32);
480        assert!(!aes256_ctr.is_aead());
481    }
482
483    #[test]
484    fn test_cipher_from_name() {
485        assert!(matches!(
486            CipherAlgorithm::from_name("chacha20-poly1305@openssh.com"),
487            Some(CipherAlgorithm::ChaCha20Poly1305)
488        ));
489        assert!(matches!(
490            CipherAlgorithm::from_name("aes128-gcm@openssh.com"),
491            Some(CipherAlgorithm::Aes128Gcm)
492        ));
493        assert!(CipherAlgorithm::from_name("invalid").is_none());
494    }
495
496    #[test]
497    fn test_mac_algorithm_properties() {
498        let sha256 = MacAlgorithm::HmacSha256;
499        assert_eq!(sha256.name(), "hmac-sha2-256");
500        assert_eq!(sha256.key_size(), 32);
501        assert_eq!(sha256.mac_size(), 32);
502
503        let sha512 = MacAlgorithm::HmacSha512;
504        assert_eq!(sha512.key_size(), 64);
505        assert_eq!(sha512.mac_size(), 64);
506    }
507
508    #[test]
509    fn test_mac_from_name() {
510        assert!(matches!(
511            MacAlgorithm::from_name("hmac-sha2-256"),
512            Some(MacAlgorithm::HmacSha256)
513        ));
514        assert!(matches!(
515            MacAlgorithm::from_name("hmac-sha2-512"),
516            Some(MacAlgorithm::HmacSha512)
517        ));
518        assert!(MacAlgorithm::from_name("invalid").is_none());
519    }
520
521    #[test]
522    fn test_mac_compute_and_verify() {
523        let key = vec![0u8; 32];
524        let mut mac_key = MacKey::new(MacAlgorithm::HmacSha256, &key).unwrap();
525
526        let data = b"Hello, SSH!";
527        let mac = mac_key.compute(data);
528
529        // Reset sequence for verification
530        mac_key.sequence = 0;
531        assert!(mac_key.verify(data, &mac).is_ok());
532
533        // Wrong MAC should fail
534        let wrong_mac = vec![0u8; 32];
535        mac_key.sequence = 0;
536        assert!(mac_key.verify(data, &wrong_mac).is_err());
537    }
538
539    #[test]
540    fn test_encryption_key_creation() {
541        let key = vec![0u8; 32];
542        let enc_key = EncryptionKey::new(CipherAlgorithm::ChaCha20Poly1305, &key);
543        assert!(enc_key.is_ok());
544
545        let insufficient_key = vec![0u8; 16];
546        let result = EncryptionKey::new(CipherAlgorithm::ChaCha20Poly1305, &insufficient_key);
547        assert!(result.is_err());
548    }
549
550    #[test]
551    fn test_decryption_key_creation() {
552        let key = vec![0u8; 32];
553        let dec_key = DecryptionKey::new(CipherAlgorithm::ChaCha20Poly1305, &key);
554        assert!(dec_key.is_ok());
555    }
556
557    #[test]
558    fn test_chacha20_encrypt_decrypt() {
559        let key = vec![1u8; 32];
560        let mut enc_key = EncryptionKey::new(CipherAlgorithm::ChaCha20Poly1305, &key).unwrap();
561        let mut dec_key = DecryptionKey::new(CipherAlgorithm::ChaCha20Poly1305, &key).unwrap();
562
563        let mut plaintext = b"Hello, SSH!".to_vec();
564        let original = plaintext.clone();
565
566        // Encrypt
567        enc_key.encrypt(&mut plaintext).unwrap();
568        assert_ne!(plaintext, original); // Should be different after encryption
569
570        // Decrypt
571        dec_key.decrypt(&mut plaintext).unwrap();
572        assert_eq!(plaintext, original); // Should match original
573    }
574
575    #[test]
576    fn test_aes128_gcm_encrypt_decrypt() {
577        let key = vec![2u8; 16];
578        let mut enc_key = EncryptionKey::new(CipherAlgorithm::Aes128Gcm, &key).unwrap();
579        let mut dec_key = DecryptionKey::new(CipherAlgorithm::Aes128Gcm, &key).unwrap();
580
581        let mut plaintext = b"Test data".to_vec();
582        let original = plaintext.clone();
583
584        enc_key.encrypt(&mut plaintext).unwrap();
585        dec_key.decrypt(&mut plaintext).unwrap();
586        assert_eq!(plaintext, original);
587    }
588}