Skip to main content

fynx_proto/ipsec/crypto/
cipher.rs

1//! Cipher implementations for IKEv2 encryption
2//!
3//! Implements encryption and decryption for SK payload as defined in RFC 7296.
4
5use crate::ipsec::{Error, Result};
6use aes_gcm::{
7    aead::{Aead, KeyInit, Payload},
8    Aes128Gcm, Aes256Gcm, Nonce as AesGcmNonce,
9};
10
11/// Cipher algorithm for SK payload encryption
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum CipherAlgorithm {
14    /// AES-GCM with 128-bit key (AEAD)
15    AesGcm128,
16    /// AES-GCM with 256-bit key (AEAD)
17    AesGcm256,
18    /// ChaCha20-Poly1305 (AEAD)
19    ChaCha20Poly1305,
20}
21
22impl CipherAlgorithm {
23    /// Get key length in bytes
24    pub fn key_len(self) -> usize {
25        match self {
26            CipherAlgorithm::AesGcm128 => 16,
27            CipherAlgorithm::AesGcm256 => 32,
28            CipherAlgorithm::ChaCha20Poly1305 => 32,
29        }
30    }
31
32    /// Get IV/nonce length in bytes
33    pub fn iv_len(self) -> usize {
34        match self {
35            CipherAlgorithm::AesGcm128 | CipherAlgorithm::AesGcm256 => 8, // RFC 4106
36            CipherAlgorithm::ChaCha20Poly1305 => 12,                      // RFC 7539
37        }
38    }
39
40    /// Get authentication tag length in bytes (for AEAD ciphers)
41    pub fn tag_len(self) -> usize {
42        16 // All AEAD ciphers use 16-byte tag
43    }
44
45    /// Check if this is an AEAD cipher
46    pub fn is_aead(self) -> bool {
47        true // All currently supported ciphers are AEAD
48    }
49
50    /// Encrypt data with AEAD cipher
51    ///
52    /// # Arguments
53    ///
54    /// * `key` - Encryption key (SK_e)
55    /// * `iv` - Initialization vector / nonce
56    /// * `plaintext` - Data to encrypt
57    /// * `aad` - Additional authenticated data (IKE header)
58    ///
59    /// # Returns
60    ///
61    /// Returns ciphertext with authentication tag appended
62    pub fn encrypt(self, key: &[u8], iv: &[u8], plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
63        // Validate key length
64        if key.len() != self.key_len() {
65            return Err(Error::InvalidKeyLength {
66                expected: self.key_len(),
67                actual: key.len(),
68            });
69        }
70
71        // Validate IV length
72        if iv.len() != self.iv_len() {
73            return Err(Error::InvalidIvLength {
74                expected: self.iv_len(),
75                actual: iv.len(),
76            });
77        }
78
79        match self {
80            CipherAlgorithm::AesGcm128 => {
81                // AES-GCM uses 8-byte IV + 4-byte fixed field (RFC 4106)
82                // For IKEv2, we use 8-byte explicit IV
83                let cipher = Aes128Gcm::new_from_slice(key)
84                    .map_err(|_| Error::CryptoError("Failed to create AES-GCM cipher".into()))?;
85
86                // Pad IV to 12 bytes (8-byte explicit + 4-byte implicit fixed field set to 0)
87                let mut nonce_bytes = [0u8; 12];
88                nonce_bytes[..8].copy_from_slice(iv);
89                let nonce = AesGcmNonce::from(nonce_bytes);
90
91                let payload = Payload {
92                    msg: plaintext,
93                    aad,
94                };
95
96                cipher
97                    .encrypt(&nonce, payload)
98                    .map_err(|_| Error::CryptoError("AES-GCM encryption failed".into()))
99            }
100            CipherAlgorithm::AesGcm256 => {
101                let cipher = Aes256Gcm::new_from_slice(key)
102                    .map_err(|_| Error::CryptoError("Failed to create AES-GCM cipher".into()))?;
103
104                let mut nonce_bytes = [0u8; 12];
105                nonce_bytes[..8].copy_from_slice(iv);
106                let nonce = AesGcmNonce::from(nonce_bytes);
107
108                let payload = Payload {
109                    msg: plaintext,
110                    aad,
111                };
112
113                cipher
114                    .encrypt(&nonce, payload)
115                    .map_err(|_| Error::CryptoError("AES-GCM encryption failed".into()))
116            }
117            CipherAlgorithm::ChaCha20Poly1305 => {
118                // ChaCha20-Poly1305 uses 12-byte nonce (RFC 7539)
119                let cipher = chacha20poly1305::ChaCha20Poly1305::new_from_slice(key)
120                    .map_err(|_| Error::CryptoError("Failed to create ChaCha20 cipher".into()))?;
121
122                // Convert slice to array reference and create Nonce
123                let nonce_array: &[u8; 12] = iv.try_into().map_err(|_| Error::InvalidIvLength {
124                    expected: 12,
125                    actual: iv.len(),
126                })?;
127                let nonce = chacha20poly1305::Nonce::from(*nonce_array);
128
129                let payload = Payload {
130                    msg: plaintext,
131                    aad,
132                };
133
134                cipher
135                    .encrypt(&nonce, payload)
136                    .map_err(|_| Error::CryptoError("ChaCha20-Poly1305 encryption failed".into()))
137            }
138        }
139    }
140
141    /// Decrypt data with AEAD cipher
142    ///
143    /// # Arguments
144    ///
145    /// * `key` - Encryption key (SK_e)
146    /// * `iv` - Initialization vector / nonce
147    /// * `ciphertext` - Data to decrypt (includes authentication tag)
148    /// * `aad` - Additional authenticated data (IKE header)
149    ///
150    /// # Returns
151    ///
152    /// Returns decrypted plaintext
153    pub fn decrypt(self, key: &[u8], iv: &[u8], ciphertext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
154        // Validate key length
155        if key.len() != self.key_len() {
156            return Err(Error::InvalidKeyLength {
157                expected: self.key_len(),
158                actual: key.len(),
159            });
160        }
161
162        // Validate IV length
163        if iv.len() != self.iv_len() {
164            return Err(Error::InvalidIvLength {
165                expected: self.iv_len(),
166                actual: iv.len(),
167            });
168        }
169
170        // Validate ciphertext includes tag
171        if ciphertext.len() < self.tag_len() {
172            return Err(Error::BufferTooShort {
173                required: self.tag_len(),
174                available: ciphertext.len(),
175            });
176        }
177
178        match self {
179            CipherAlgorithm::AesGcm128 => {
180                let cipher = Aes128Gcm::new_from_slice(key)
181                    .map_err(|_| Error::CryptoError("Failed to create AES-GCM cipher".into()))?;
182
183                let mut nonce_bytes = [0u8; 12];
184                nonce_bytes[..8].copy_from_slice(iv);
185                let nonce = AesGcmNonce::from(nonce_bytes);
186
187                let payload = Payload {
188                    msg: ciphertext,
189                    aad,
190                };
191
192                cipher
193                    .decrypt(&nonce, payload)
194                    .map_err(|_| Error::CryptoError("AES-GCM decryption failed".into()))
195            }
196            CipherAlgorithm::AesGcm256 => {
197                let cipher = Aes256Gcm::new_from_slice(key)
198                    .map_err(|_| Error::CryptoError("Failed to create AES-GCM cipher".into()))?;
199
200                let mut nonce_bytes = [0u8; 12];
201                nonce_bytes[..8].copy_from_slice(iv);
202                let nonce = AesGcmNonce::from(nonce_bytes);
203
204                let payload = Payload {
205                    msg: ciphertext,
206                    aad,
207                };
208
209                cipher
210                    .decrypt(&nonce, payload)
211                    .map_err(|_| Error::CryptoError("AES-GCM decryption failed".into()))
212            }
213            CipherAlgorithm::ChaCha20Poly1305 => {
214                let cipher = chacha20poly1305::ChaCha20Poly1305::new_from_slice(key)
215                    .map_err(|_| Error::CryptoError("Failed to create ChaCha20 cipher".into()))?;
216
217                // Convert slice to array reference and create Nonce
218                let nonce_array: &[u8; 12] = iv.try_into().map_err(|_| Error::InvalidIvLength {
219                    expected: 12,
220                    actual: iv.len(),
221                })?;
222                let nonce = chacha20poly1305::Nonce::from(*nonce_array);
223
224                let payload = Payload {
225                    msg: ciphertext,
226                    aad,
227                };
228
229                cipher
230                    .decrypt(&nonce, payload)
231                    .map_err(|_| Error::CryptoError("ChaCha20-Poly1305 decryption failed".into()))
232            }
233        }
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn test_cipher_key_lengths() {
243        assert_eq!(CipherAlgorithm::AesGcm128.key_len(), 16);
244        assert_eq!(CipherAlgorithm::AesGcm256.key_len(), 32);
245        assert_eq!(CipherAlgorithm::ChaCha20Poly1305.key_len(), 32);
246    }
247
248    #[test]
249    fn test_cipher_iv_lengths() {
250        assert_eq!(CipherAlgorithm::AesGcm128.iv_len(), 8);
251        assert_eq!(CipherAlgorithm::AesGcm256.iv_len(), 8);
252        assert_eq!(CipherAlgorithm::ChaCha20Poly1305.iv_len(), 12);
253    }
254
255    #[test]
256    fn test_cipher_tag_lengths() {
257        assert_eq!(CipherAlgorithm::AesGcm128.tag_len(), 16);
258        assert_eq!(CipherAlgorithm::AesGcm256.tag_len(), 16);
259        assert_eq!(CipherAlgorithm::ChaCha20Poly1305.tag_len(), 16);
260    }
261
262    #[test]
263    fn test_aes_gcm_128_encrypt_decrypt() {
264        let key = vec![0x42; 16]; // 128-bit key
265        let iv = vec![0x01; 8]; // 8-byte IV
266        let plaintext = b"Hello, IKEv2!";
267        let aad = b"IKE header data";
268
269        let ciphertext = CipherAlgorithm::AesGcm128
270            .encrypt(&key, &iv, plaintext, aad)
271            .unwrap();
272
273        // Ciphertext should include 16-byte tag
274        assert!(ciphertext.len() > plaintext.len());
275
276        let decrypted = CipherAlgorithm::AesGcm128
277            .decrypt(&key, &iv, &ciphertext, aad)
278            .unwrap();
279
280        assert_eq!(decrypted, plaintext);
281    }
282
283    #[test]
284    fn test_aes_gcm_256_encrypt_decrypt() {
285        let key = vec![0x42; 32]; // 256-bit key
286        let iv = vec![0x01; 8];
287        let plaintext = b"Test data for AES-GCM-256";
288        let aad = b"Additional authenticated data";
289
290        let ciphertext = CipherAlgorithm::AesGcm256
291            .encrypt(&key, &iv, plaintext, aad)
292            .unwrap();
293
294        let decrypted = CipherAlgorithm::AesGcm256
295            .decrypt(&key, &iv, &ciphertext, aad)
296            .unwrap();
297
298        assert_eq!(decrypted, plaintext);
299    }
300
301    #[test]
302    fn test_chacha20_encrypt_decrypt() {
303        let key = vec![0x42; 32]; // 256-bit key
304        let iv = vec![0x01; 12]; // 12-byte nonce
305        let plaintext = b"ChaCha20-Poly1305 test";
306        let aad = b"AAD for ChaCha20";
307
308        let ciphertext = CipherAlgorithm::ChaCha20Poly1305
309            .encrypt(&key, &iv, plaintext, aad)
310            .unwrap();
311
312        let decrypted = CipherAlgorithm::ChaCha20Poly1305
313            .decrypt(&key, &iv, &ciphertext, aad)
314            .unwrap();
315
316        assert_eq!(decrypted, plaintext);
317    }
318
319    #[test]
320    fn test_invalid_key_length() {
321        let key = vec![0x42; 10]; // Wrong length
322        let iv = vec![0x01; 8];
323        let plaintext = b"test";
324        let aad = b"aad";
325
326        let result = CipherAlgorithm::AesGcm128.encrypt(&key, &iv, plaintext, aad);
327        assert!(result.is_err());
328    }
329
330    #[test]
331    fn test_invalid_iv_length() {
332        let key = vec![0x42; 16];
333        let iv = vec![0x01; 4]; // Wrong length
334        let plaintext = b"test";
335        let aad = b"aad";
336
337        let result = CipherAlgorithm::AesGcm128.encrypt(&key, &iv, plaintext, aad);
338        assert!(result.is_err());
339    }
340
341    #[test]
342    fn test_decrypt_authentication_failure() {
343        let key = vec![0x42; 16];
344        let iv = vec![0x01; 8];
345        let plaintext = b"test";
346        let aad = b"aad";
347
348        let mut ciphertext = CipherAlgorithm::AesGcm128
349            .encrypt(&key, &iv, plaintext, aad)
350            .unwrap();
351
352        // Corrupt the ciphertext
353        ciphertext[0] ^= 0xFF;
354
355        let result = CipherAlgorithm::AesGcm128.decrypt(&key, &iv, &ciphertext, aad);
356        assert!(result.is_err());
357    }
358
359    #[test]
360    fn test_decrypt_wrong_aad() {
361        let key = vec![0x42; 16];
362        let iv = vec![0x01; 8];
363        let plaintext = b"test";
364        let aad = b"correct aad";
365
366        let ciphertext = CipherAlgorithm::AesGcm128
367            .encrypt(&key, &iv, plaintext, aad)
368            .unwrap();
369
370        // Use wrong AAD
371        let wrong_aad = b"wrong aad";
372        let result = CipherAlgorithm::AesGcm128.decrypt(&key, &iv, &ciphertext, wrong_aad);
373        assert!(result.is_err());
374    }
375}