1use aead::AeadInOut;
24use aes_gcm::aead::consts::U12;
25use aes_gcm::aes::{Aes128, Aes256};
26use aes_gcm::KeyInit as AesKeyInit;
27use aes_gcm::{AesGcm, Nonce, Tag};
28use cipher::block::BlockCipherEncrypt;
29use cmac::Cmac;
30use kuznyechik::Kuznyechik;
31
32type Aes128Gcm12 = AesGcm<Aes128, U12, U12>;
34type Aes256Gcm12 = AesGcm<Aes256, U12, U12>;
36#[allow(dead_code)]
38type KuznyechikCmac = Cmac<Kuznyechik>;
39
40pub mod security_control {
42 pub const AUTHENTICATION: u8 = 0x10;
44 pub const ENCRYPTION: u8 = 0x20;
46 pub const KEY_SET_BROADCAST: u8 = 0x40;
48 pub const COMPRESSION: u8 = 0x80;
50 pub const AUTHENTICATED_ENCRYPTION: u8 = AUTHENTICATION | ENCRYPTION;
52}
53
54pub const GOST_SUITE_ID: u8 = 0x0D;
56
57pub fn is_gost_suite(sc: u8) -> bool {
59 (sc & 0x0F) == GOST_SUITE_ID
60}
61
62pub mod glo {
64 pub const INITIATE_REQUEST: u8 = 0x21;
66 pub const INITIATE_RESPONSE: u8 = 0x28;
68 pub const GET_REQUEST: u8 = 0xC8;
70 pub const SET_REQUEST: u8 = 0xC9;
72 pub const ACTION_REQUEST: u8 = 0xCB;
74 pub const GET_RESPONSE: u8 = 0xCC;
76 pub const SET_RESPONSE: u8 = 0xCD;
78 pub const ACTION_RESPONSE: u8 = 0xCF;
80}
81
82pub mod ded {
84 pub const GET_REQUEST: u8 = 0xD0;
86 pub const SET_REQUEST: u8 = 0xD1;
88 pub const ACTION_REQUEST: u8 = 0xD3;
90 pub const GET_RESPONSE: u8 = 0xD4;
92 pub const SET_RESPONSE: u8 = 0xD5;
94 pub const ACTION_RESPONSE: u8 = 0xD7;
96}
97
98#[derive(Debug, PartialEq, Eq)]
100pub enum CipherError {
101 InvalidSystemTitle,
103 InvalidKey,
105 Truncated,
107 AuthenticationFailed,
109 CryptoError,
111 ReplayDetected,
114 InvocationCounterExhausted,
117}
118
119impl std::fmt::Display for CipherError {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 write!(f, "{self:?}")
122 }
123}
124
125impl std::error::Error for CipherError {}
126
127#[derive(Debug, Clone)]
129pub struct SecurityContext {
130 pub security_control: u8,
132 pub encryption_key: Vec<u8>,
134 pub authentication_key: Vec<u8>,
136 pub system_title: Vec<u8>,
138 pub invocation_counter: u32,
140 last_peer_ic: u32,
143 ic_valid: bool,
146}
147
148impl Drop for SecurityContext {
149 fn drop(&mut self) {
152 use zeroize::Zeroize;
153 self.encryption_key.zeroize();
154 self.authentication_key.zeroize();
155 }
156}
157
158impl SecurityContext {
159 pub fn for_suite(
164 policy: crate::security::SecurityPolicy,
165 suite: crate::security::SecuritySuite,
166 encryption_key: Vec<u8>,
167 authentication_key: Vec<u8>,
168 system_title: Vec<u8>,
169 invocation_counter: u32,
170 ) -> Result<SecurityContext, CipherError> {
171 if encryption_key.len() != suite.aes_key_len() {
172 return Err(CipherError::InvalidKey);
173 }
174 Ok(SecurityContext {
175 security_control: policy.security_control_byte(suite),
176 encryption_key,
177 authentication_key,
178 system_title,
179 invocation_counter,
180 last_peer_ic: 0,
181 ic_valid: false,
182 })
183 }
184
185 fn check_replay(&self, ic: u32) -> Result<(), CipherError> {
190 if self.ic_valid && ic <= self.last_peer_ic {
191 return Err(CipherError::ReplayDetected);
192 }
193 Ok(())
194 }
195
196 fn accept_peer_ic(&mut self, ic: u32) {
199 self.last_peer_ic = ic;
200 self.ic_valid = true;
201 }
202
203 fn check_send_ic(&self) -> Result<(), CipherError> {
207 if self.invocation_counter == u32::MAX {
208 return Err(CipherError::InvocationCounterExhausted);
209 }
210 Ok(())
211 }
212
213 pub fn key_rotation_needed(&self) -> bool {
218 self.invocation_counter >= u32::MAX - 1000
219 }
220
221 fn authentication(&self) -> bool {
222 self.security_control & security_control::AUTHENTICATION != 0
223 }
224
225 fn encryption(&self) -> bool {
226 self.security_control & security_control::ENCRYPTION != 0
227 }
228
229 fn iv(&self) -> Result<[u8; 12], CipherError> {
230 if self.system_title.len() != 8 {
231 return Err(CipherError::InvalidSystemTitle);
232 }
233 let mut iv = [0u8; 12];
234 iv[..8].copy_from_slice(&self.system_title);
235 iv[8..].copy_from_slice(&self.invocation_counter.to_be_bytes());
236 Ok(iv)
237 }
238}
239
240pub fn protect(ctx: &SecurityContext, ciphered_tag: u8, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
243 ctx.check_send_ic()?;
244 let iv = ctx.iv()?;
245 let sc = ctx.security_control;
246
247 let mut protected = Vec::new();
248 match (ctx.authentication(), ctx.encryption()) {
249 (true, true) => {
250 let aad = [&[sc][..], &ctx.authentication_key].concat();
252 let mut buf = plaintext.to_vec();
253 let tag = gcm_encrypt_in_place(&ctx.encryption_key, &iv, &aad, &mut buf)?;
254 protected.extend_from_slice(&buf);
255 protected.extend_from_slice(&tag);
256 }
257 (true, false) => {
258 let aad = [&[sc][..], &ctx.authentication_key, plaintext].concat();
260 let mut empty = Vec::new();
261 let tag = gcm_encrypt_in_place(&ctx.encryption_key, &iv, &aad, &mut empty)?;
262 protected.extend_from_slice(plaintext);
263 protected.extend_from_slice(&tag);
264 }
265 (false, true) => {
266 let mut buf = plaintext.to_vec();
268 gcm_encrypt_in_place(&ctx.encryption_key, &iv, &[], &mut buf)?;
269 protected.extend_from_slice(&buf);
270 }
271 (false, false) => protected.extend_from_slice(plaintext),
272 }
273
274 let mut body = Vec::with_capacity(5 + protected.len());
276 body.push(sc);
277 body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
278 body.extend_from_slice(&protected);
279
280 let mut apdu = vec![ciphered_tag];
281 push_length(body.len(), &mut apdu);
282 apdu.extend_from_slice(&body);
283 Ok(apdu)
284}
285
286pub fn unprotect(ctx: &mut SecurityContext, apdu: &[u8]) -> Result<(u8, Vec<u8>), CipherError> {
295 let ciphered_tag = *apdu.first().ok_or(CipherError::Truncated)?;
296 let (len, header) = read_length(&apdu[1..]).ok_or(CipherError::Truncated)?;
297 let body = apdu.get(1 + header..1 + header + len).ok_or(CipherError::Truncated)?;
298 if body.len() < 5 {
299 return Err(CipherError::Truncated);
300 }
301 let sc = body[0];
302 let ic = u32::from_be_bytes([body[1], body[2], body[3], body[4]]);
303 ctx.check_replay(ic)?;
304 ctx.security_control = sc;
305 ctx.invocation_counter = ic;
306 let protected = &body[5..];
307 let iv = ctx.iv()?;
308
309 let plaintext = match (ctx.authentication(), ctx.encryption()) {
310 (true, true) => {
311 if protected.len() < 12 {
312 return Err(CipherError::Truncated);
313 }
314 let (ct, tag) = protected.split_at(protected.len() - 12);
315 let aad = [&[sc][..], &ctx.authentication_key].concat();
316 gcm_decrypt(&ctx.encryption_key, &iv, &aad, ct, tag)?
317 }
318 (true, false) => {
319 if protected.len() < 12 {
320 return Err(CipherError::Truncated);
321 }
322 let (plain, tag) = protected.split_at(protected.len() - 12);
323 let aad = [&[sc][..], &ctx.authentication_key, plain].concat();
324 let mut empty = Vec::new();
326 let expected = gcm_encrypt_in_place(&ctx.encryption_key, &iv, &aad, &mut empty)?;
327 if expected.as_slice() != tag {
328 return Err(CipherError::AuthenticationFailed);
329 }
330 plain.to_vec()
331 }
332 (false, true) => {
333 let mut buf = protected.to_vec();
334 gcm_decrypt_no_tag(&ctx.encryption_key, &iv, &mut buf)?;
335 buf
336 }
337 (false, false) => protected.to_vec(),
338 };
339 ctx.accept_peer_ic(ic);
340 Ok((ciphered_tag, plaintext))
341}
342
343pub fn gost_protect(ctx: &SecurityContext, ciphered_tag: u8, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
355 ctx.check_send_ic()?;
356 if ctx.encryption_key.len() != 32 {
357 return Err(CipherError::InvalidKey);
358 }
359 let sc = ctx.security_control;
360 let iv = ctx.iv()?;
361 let nonce = build_gost_nonce(&iv);
362
363 match (ctx.authentication(), ctx.encryption()) {
364 (true, true) => {
365 let ciphertext = gost_ctr_encrypt(&ctx.encryption_key, &nonce, plaintext)?;
367 let aad = [[sc].as_ref(), &ctx.authentication_key, &ciphertext].concat();
368 let tag = gost_cmac_tag(&ctx.encryption_key, &aad)?;
369 let mut body = Vec::with_capacity(5 + ciphertext.len() + 16);
370 body.push(sc);
371 body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
372 body.extend_from_slice(&ciphertext);
373 body.extend_from_slice(&tag);
374 let mut apdu = vec![ciphered_tag];
375 push_length(body.len(), &mut apdu);
376 apdu.extend_from_slice(&body);
377 Ok(apdu)
378 }
379 (true, false) => {
380 let aad = [[sc].as_ref(), &ctx.authentication_key, plaintext].concat();
382 let tag = gost_cmac_tag(&ctx.encryption_key, &aad)?;
383 let mut body = Vec::with_capacity(5 + plaintext.len() + 16);
384 body.push(sc);
385 body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
386 body.extend_from_slice(plaintext);
387 body.extend_from_slice(&tag);
388 let mut apdu = vec![ciphered_tag];
389 push_length(body.len(), &mut apdu);
390 apdu.extend_from_slice(&body);
391 Ok(apdu)
392 }
393 (false, true) => {
394 let ciphertext = gost_ctr_encrypt(&ctx.encryption_key, &nonce, plaintext)?;
396 let mut body = Vec::with_capacity(5 + ciphertext.len());
397 body.push(sc);
398 body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
399 body.extend_from_slice(&ciphertext);
400 let mut apdu = vec![ciphered_tag];
401 push_length(body.len(), &mut apdu);
402 apdu.extend_from_slice(&body);
403 Ok(apdu)
404 }
405 (false, false) => {
406 let mut body = Vec::with_capacity(5 + plaintext.len());
407 body.push(sc);
408 body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
409 body.extend_from_slice(plaintext);
410 let mut apdu = vec![ciphered_tag];
411 push_length(body.len(), &mut apdu);
412 apdu.extend_from_slice(&body);
413 Ok(apdu)
414 }
415 }
416}
417
418pub fn gost_unprotect(ctx: &mut SecurityContext, apdu: &[u8]) -> Result<(u8, Vec<u8>), CipherError> {
422 let ciphered_tag = *apdu.first().ok_or(CipherError::Truncated)?;
423 let (len, header) = read_length(&apdu[1..]).ok_or(CipherError::Truncated)?;
424 let body = apdu.get(1 + header..1 + header + len).ok_or(CipherError::Truncated)?;
425 if body.len() < 5 {
426 return Err(CipherError::Truncated);
427 }
428 let sc = body[0];
429 let ic = u32::from_be_bytes([body[1], body[2], body[3], body[4]]);
430 ctx.check_replay(ic)?;
431 ctx.security_control = sc;
432 ctx.invocation_counter = ic;
433 let protected = &body[5..];
434 let iv = ctx.iv()?;
435 let nonce = build_gost_nonce(&iv);
436
437 let plaintext = match (ctx.authentication(), ctx.encryption()) {
438 (true, true) => {
439 if protected.len() < 16 {
440 return Err(CipherError::Truncated);
441 }
442 let (ct, tag) = protected.split_at(protected.len() - 16);
443 let aad = [[sc].as_ref(), &ctx.authentication_key, ct].concat();
444 let expected_tag = gost_cmac_tag(&ctx.encryption_key, &aad)?;
445 if tag != expected_tag.as_slice() {
446 return Err(CipherError::AuthenticationFailed);
447 }
448 gost_ctr_decrypt(&ctx.encryption_key, &nonce, ct)?
449 }
450 (true, false) => {
451 if protected.len() < 16 {
452 return Err(CipherError::Truncated);
453 }
454 let (plain, tag) = protected.split_at(protected.len() - 16);
455 let aad = [[sc].as_ref(), &ctx.authentication_key, plain].concat();
456 let expected_tag = gost_cmac_tag(&ctx.encryption_key, &aad)?;
457 if tag != expected_tag.as_slice() {
458 return Err(CipherError::AuthenticationFailed);
459 }
460 plain.to_vec()
461 }
462 (false, true) => gost_ctr_decrypt(&ctx.encryption_key, &nonce, protected)?,
463 (false, false) => protected.to_vec(),
464 };
465 ctx.accept_peer_ic(ic);
466 Ok((ciphered_tag, plaintext))
467}
468
469fn gost_ctr_encrypt(key: &[u8], nonce: &[u8; 16], plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
471 use cipher::BlockCipherEncrypt;
472 let cipher = Kuznyechik::new_from_slice(key).map_err(|_| CipherError::InvalidKey)?;
473 let mut ciphertext = plaintext.to_vec();
474 let mut counter = *nonce;
475
476 for chunk in ciphertext.chunks_mut(16) {
477 let mut keystream = cipher::Array::from(counter);
479 cipher.encrypt_block(&mut keystream);
480 let ks: [u8; 16] = keystream.into();
481 for (i, byte) in chunk.iter_mut().enumerate() {
483 *byte ^= ks[i];
484 }
485 increment_counter(&mut counter);
487 }
488 Ok(ciphertext)
489}
490
491fn gost_ctr_decrypt(key: &[u8], nonce: &[u8; 16], ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
493 gost_ctr_encrypt(key, nonce, ciphertext)
495}
496
497fn gost_cmac_tag(key: &[u8], data: &[u8]) -> Result<Vec<u8>, CipherError> {
500 if key.len() != 32 {
501 return Err(CipherError::InvalidKey);
502 }
503
504 let cipher = Kuznyechik::new_from_slice(key).map_err(|_| CipherError::InvalidKey)?;
505
506 let mut l = cipher::Array::from([0u8; 16]);
508 cipher.encrypt_block(&mut l);
509 let l_bytes: [u8; 16] = l.into();
510
511 let k1 = ghash_subkey(&l_bytes);
512 let k2 = ghash_subkey(&k1);
513
514 let mut state = [0u8; 16];
516 let chunks: Vec<&[u8]> = data.chunks(16).collect();
517 let last_block = data.chunks(16).last();
518
519 if data.is_empty() || last_block.is_some_and(|b| b.len() == 16) {
520 for chunk in &chunks {
522 xor_blocks(&mut state, chunk);
523 let mut block = cipher::Array::from(state);
524 cipher.encrypt_block(&mut block);
525 state = block.into();
526 }
527 if !data.is_empty() && last_block.is_some_and(|b| b.len() == 16) {
528 xor_blocks(&mut state, &k1);
530 let mut block = cipher::Array::from(state);
531 cipher.encrypt_block(&mut block);
532 state = block.into();
533 }
534 } else {
535 let mut padded = [0u8; 16];
537 padded[..chunks.last().unwrap().len()].copy_from_slice(chunks.last().unwrap());
538 padded[chunks.last().unwrap().len()] = 0x80; for chunk in &chunks[..chunks.len() - 1] {
541 xor_blocks(&mut state, chunk);
542 let mut block = cipher::Array::from(state);
543 cipher.encrypt_block(&mut block);
544 state = block.into();
545 }
546 xor_blocks(&mut state, &padded);
548 xor_blocks(&mut state, &k2);
549 let mut block = cipher::Array::from(state);
550 cipher.encrypt_block(&mut block);
551 state = block.into();
552 }
553
554 Ok(state.to_vec())
555}
556
557fn ghash_subkey(l: &[u8; 16]) -> [u8; 16] {
559 let mut result = [0u8; 16];
560 let carry = l[0] & 0x80 != 0;
561 for i in 0..16 {
562 result[i] = (l[i] << 1) | if i + 1 < 16 { l[i + 1] >> 7 } else { 0 };
563 }
564 if carry {
565 result[15] ^= 0x87; }
567 result
568}
569
570fn xor_blocks(a: &mut [u8; 16], b: &[u8]) {
572 for i in 0..16.min(b.len()) {
573 a[i] ^= b[i];
574 }
575}
576
577fn build_gost_nonce(iv: &[u8; 12]) -> [u8; 16] {
581 let mut nonce = [0u8; 16];
582 nonce[..12].copy_from_slice(iv);
583 nonce
584}
585
586fn increment_counter(counter: &mut [u8; 16]) {
588 for i in (0..16).rev() {
589 counter[i] = counter[i].wrapping_add(1);
590 if counter[i] != 0 {
591 break;
592 }
593 }
594}
595
596pub fn gost_gmac_tag(key: &[u8], iv: &[u8; 12], aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
609 if key.len() != 32 {
610 return Err(CipherError::InvalidKey);
611 }
612
613 let cipher = Kuznyechik::new_from_slice(key).map_err(|_| CipherError::InvalidKey)?;
614
615 let mut h = cipher::Array::from([0u8; 16]);
617 cipher.encrypt_block(&mut h);
618 let _h_bytes: [u8; 16] = h.into();
619
620 let mut state = [0u8; 16];
622
623 for chunk in aad.chunks(16) {
625 let mut block = [0u8; 16];
626 block[..chunk.len()].copy_from_slice(chunk);
627 if chunk.len() < 16 {
628 block[chunk.len()] = 0x80; }
630 xor_blocks(&mut state, &block);
631 let mut block_arr = cipher::Array::from(state);
632 cipher.encrypt_block(&mut block_arr);
633 state = block_arr.into();
634 }
635
636 for chunk in plaintext.chunks(16) {
638 let mut block = [0u8; 16];
639 block[..chunk.len()].copy_from_slice(chunk);
640 if chunk.len() < 16 {
641 block[chunk.len()] = 0x80; }
643 xor_blocks(&mut state, &block);
644 let mut block_arr = cipher::Array::from(state);
645 cipher.encrypt_block(&mut block_arr);
646 state = block_arr.into();
647 }
648
649 let aad_bit_len = (aad.len() as u64) * 8;
651 let ct_bit_len = (plaintext.len() as u64) * 8;
652 let mut len_block = [0u8; 16];
653 len_block[0..8].copy_from_slice(&aad_bit_len.to_be_bytes());
654 len_block[8..16].copy_from_slice(&ct_bit_len.to_be_bytes());
655 xor_blocks(&mut state, &len_block);
656 let mut block_arr = cipher::Array::from(state);
657 cipher.encrypt_block(&mut block_arr);
658 state = block_arr.into();
659
660 let mut enc_block = cipher::Array::from(build_gmac_counter(iv));
663 cipher.encrypt_block(&mut enc_block);
664 let enc_bytes: [u8; 16] = enc_block.into();
665 xor_blocks(&mut state, &enc_bytes);
666
667 Ok(state.to_vec())
668}
669
670fn build_gmac_counter(iv: &[u8; 12]) -> [u8; 16] {
673 let mut counter = [0u8; 16];
674 counter[..12].copy_from_slice(iv);
675 counter[15] = 0x01; counter
677}
678
679pub fn gost_gmac_encrypt(key: &[u8], iv: &[u8; 12], plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
681 let cipher = Kuznyechik::new_from_slice(key).map_err(|_| CipherError::InvalidKey)?;
683 let mut ciphertext = plaintext.to_vec();
684 let mut counter = build_gmac_counter(iv);
685
686 for chunk in ciphertext.chunks_mut(16) {
687 let mut keystream = cipher::Array::from(counter);
688 cipher.encrypt_block(&mut keystream);
689 let ks: [u8; 16] = keystream.into();
690 for (i, byte) in chunk.iter_mut().enumerate() {
691 *byte ^= ks[i];
692 }
693 increment_counter(&mut counter);
694 }
695 Ok(ciphertext)
696}
697
698pub fn gost_gmac_decrypt(key: &[u8], iv: &[u8; 12], ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
700 gost_gmac_encrypt(key, iv, ciphertext)
702}
703
704pub fn gost_gmac_protect(ctx: &SecurityContext, ciphered_tag: u8, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
706 ctx.check_send_ic()?;
707 if ctx.encryption_key.len() != 32 {
708 return Err(CipherError::InvalidKey);
709 }
710 let sc = ctx.security_control;
711 let iv = ctx.iv()?;
712
713 let mut protected = Vec::new();
714 match (ctx.authentication(), ctx.encryption()) {
715 (true, true) => {
716 let ciphertext = gost_gmac_encrypt(&ctx.encryption_key, &iv, plaintext)?;
718 let aad = [[sc].as_ref(), &ctx.authentication_key].concat();
719 let tag = gost_gmac_tag(&ctx.encryption_key, &iv, &aad, &ciphertext)?;
720 protected.extend_from_slice(&ciphertext);
721 protected.extend_from_slice(&tag);
722 }
723 (true, false) => {
724 let aad = [[sc].as_ref(), &ctx.authentication_key].concat();
726 let tag = gost_gmac_tag(&ctx.encryption_key, &iv, &aad, plaintext)?;
727 protected.extend_from_slice(plaintext);
728 protected.extend_from_slice(&tag);
729 }
730 (false, true) => {
731 let ciphertext = gost_gmac_encrypt(&ctx.encryption_key, &iv, plaintext)?;
733 protected.extend_from_slice(&ciphertext);
734 }
735 (false, false) => protected.extend_from_slice(plaintext),
736 }
737
738 let mut body = Vec::with_capacity(5 + protected.len());
739 body.push(sc);
740 body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
741 body.extend_from_slice(&protected);
742
743 let mut apdu = vec![ciphered_tag];
744 push_length(body.len(), &mut apdu);
745 apdu.extend_from_slice(&body);
746 Ok(apdu)
747}
748
749pub fn gost_gmac_unprotect(ctx: &mut SecurityContext, apdu: &[u8]) -> Result<(u8, Vec<u8>), CipherError> {
753 let ciphered_tag = *apdu.first().ok_or(CipherError::Truncated)?;
754 let (len, header) = read_length(&apdu[1..]).ok_or(CipherError::Truncated)?;
755 let body = apdu.get(1 + header..1 + header + len).ok_or(CipherError::Truncated)?;
756 if body.len() < 5 {
757 return Err(CipherError::Truncated);
758 }
759 let sc = body[0];
760 let ic = u32::from_be_bytes([body[1], body[2], body[3], body[4]]);
761 ctx.check_replay(ic)?;
762 ctx.security_control = sc;
763 ctx.invocation_counter = ic;
764 let protected = &body[5..];
765 let iv = ctx.iv()?;
766
767 let plaintext = match (ctx.authentication(), ctx.encryption()) {
768 (true, true) => {
769 if protected.len() < 16 {
770 return Err(CipherError::Truncated);
771 }
772 let (ct, tag) = protected.split_at(protected.len() - 16);
773 let aad = [[sc].as_ref(), &ctx.authentication_key].concat();
774 let expected_tag = gost_gmac_tag(&ctx.encryption_key, &iv, &aad, ct)?;
775 if tag != expected_tag.as_slice() {
776 return Err(CipherError::AuthenticationFailed);
777 }
778 gost_gmac_decrypt(&ctx.encryption_key, &iv, ct)?
779 }
780 (true, false) => {
781 if protected.len() < 16 {
782 return Err(CipherError::Truncated);
783 }
784 let (plain, tag) = protected.split_at(protected.len() - 16);
785 let aad = [[sc].as_ref(), &ctx.authentication_key].concat();
786 let expected_tag = gost_gmac_tag(&ctx.encryption_key, &iv, &aad, plain)?;
787 if tag != expected_tag.as_slice() {
788 return Err(CipherError::AuthenticationFailed);
789 }
790 plain.to_vec()
791 }
792 (false, true) => gost_gmac_decrypt(&ctx.encryption_key, &iv, protected)?,
793 (false, false) => protected.to_vec(),
794 };
795 ctx.accept_peer_ic(ic);
796 Ok((ciphered_tag, plaintext))
797}
798
799fn gcm_encrypt_in_place(key: &[u8], iv: &[u8; 12], aad: &[u8], buf: &mut [u8]) -> Result<[u8; 12], CipherError> {
801 let nonce = Nonce::<U12>::from(*iv);
802 let tag = match key.len() {
803 16 => Aes128Gcm12::new_from_slice(key)
804 .map_err(|_| CipherError::InvalidKey)?
805 .encrypt_inout_detached(&nonce, aad, buf.into())
806 .map_err(|_| CipherError::CryptoError)?,
807 32 => Aes256Gcm12::new_from_slice(key)
808 .map_err(|_| CipherError::InvalidKey)?
809 .encrypt_inout_detached(&nonce, aad, buf.into())
810 .map_err(|_| CipherError::CryptoError)?,
811 _ => return Err(CipherError::InvalidKey),
812 };
813 let mut out = [0u8; 12];
814 out.copy_from_slice(&tag);
815 Ok(out)
816}
817
818fn gcm_decrypt(key: &[u8], iv: &[u8; 12], aad: &[u8], ct: &[u8], tag: &[u8]) -> Result<Vec<u8>, CipherError> {
820 let nonce = Nonce::<U12>::from(*iv);
821 let tag = Tag::<U12>::try_from(tag).map_err(|_| CipherError::InvalidKey)?;
822 let mut buf = ct.to_vec();
823 match key.len() {
824 16 => Aes128Gcm12::new_from_slice(key)
825 .map_err(|_| CipherError::InvalidKey)?
826 .decrypt_inout_detached(&nonce, aad, buf.as_mut_slice().into(), &tag)
827 .map_err(|_| CipherError::AuthenticationFailed)?,
828 32 => Aes256Gcm12::new_from_slice(key)
829 .map_err(|_| CipherError::InvalidKey)?
830 .decrypt_inout_detached(&nonce, aad, buf.as_mut_slice().into(), &tag)
831 .map_err(|_| CipherError::AuthenticationFailed)?,
832 _ => return Err(CipherError::InvalidKey),
833 }
834 Ok(buf)
835}
836
837fn gcm_decrypt_no_tag(key: &[u8], iv: &[u8; 12], buf: &mut [u8]) -> Result<(), CipherError> {
841 let nonce = Nonce::<U12>::from(*iv);
844 match key.len() {
845 16 => {
846 Aes128Gcm12::new_from_slice(key)
847 .map_err(|_| CipherError::InvalidKey)?
848 .encrypt_inout_detached(&nonce, &[], buf.into())
849 .map_err(|_| CipherError::CryptoError)?;
850 }
851 32 => {
852 Aes256Gcm12::new_from_slice(key)
853 .map_err(|_| CipherError::InvalidKey)?
854 .encrypt_inout_detached(&nonce, &[], buf.into())
855 .map_err(|_| CipherError::CryptoError)?;
856 }
857 _ => return Err(CipherError::InvalidKey),
858 }
859 Ok(())
860}
861
862#[allow(clippy::cast_possible_truncation)] fn push_length(length: usize, out: &mut Vec<u8>) {
865 if length < 128 {
866 out.push(length as u8);
867 } else {
868 let bytes = (length as u64).to_be_bytes();
869 let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
870 let n = 8 - first;
871 out.push(0x80 | n as u8);
872 out.extend_from_slice(&bytes[first..]);
873 }
874}
875
876fn read_length(bytes: &[u8]) -> Option<(usize, usize)> {
877 let first = *bytes.first()?;
878 if first < 128 {
879 Some((first as usize, 1))
880 } else {
881 let n = (first & 0x7F) as usize;
882 let slice = bytes.get(1..1 + n)?;
883 let mut len = 0usize;
884 for &b in slice {
885 len = (len << 8) | b as usize;
886 }
887 Some((len, 1 + n))
888 }
889}
890
891#[cfg(test)]
892mod tests {
893 use super::*;
894
895 fn hex(s: &[u8]) -> Vec<u8> {
896 fn nib(c: u8) -> u8 {
897 match c {
898 b'0'..=b'9' => c - b'0',
899 b'A'..=b'F' => c - b'A' + 10,
900 b'a'..=b'f' => c - b'a' + 10,
901 _ => panic!("bad hex"),
902 }
903 }
904 s.chunks(2).map(|p| (nib(p[0]) << 4) | nib(p[1])).collect()
905 }
906
907 fn ctx() -> SecurityContext {
908 SecurityContext {
909 security_control: security_control::AUTHENTICATED_ENCRYPTION,
910 encryption_key: hex(b"000102030405060708090A0B0C0D0E0F"),
911 authentication_key: hex(b"D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF"),
912 system_title: hex(b"4D4D4D0000BC614E"),
913 invocation_counter: 0x01234567,
914 last_peer_ic: 0,
915 ic_valid: false,
916 }
917 }
918
919 #[test]
920 fn protect_matches_blue_book_e5_vector() {
921 let plaintext = hex(b"0800065F1F0400007C1F04000007");
923 let apdu = protect(&ctx(), glo::INITIATE_RESPONSE, &plaintext).unwrap();
924 let expected = hex(b"281F30012345678912\
92514A0845E475714383F65BC19745CA235906525E4F3E1C893");
926 assert_eq!(apdu, expected);
927 }
928
929 #[test]
930 fn protect_then_unprotect_round_trips() {
931 let plaintext = hex(b"0800065F1F0400007C1F04000007");
932 let apdu = protect(&ctx(), glo::GET_RESPONSE, &plaintext).unwrap();
933 let (tag, recovered) = unprotect(&mut ctx(), &apdu).unwrap();
934 assert_eq!(tag, glo::GET_RESPONSE);
935 assert_eq!(recovered, plaintext);
936 }
937
938 #[test]
939 fn unprotect_detects_tampering() {
940 let plaintext = hex(b"0800065F1F0400007C1F04000007");
941 let mut apdu = protect(&ctx(), glo::GET_RESPONSE, &plaintext).unwrap();
942 let n = apdu.len();
943 apdu[n - 1] ^= 0x01; assert_eq!(unprotect(&mut ctx(), &apdu), Err(CipherError::AuthenticationFailed));
945 }
946
947 #[test]
948 fn unprotect_rejects_replayed_or_reordered_ic() {
949 let mut tx = ctx();
950 let mut rx = ctx();
951 let plaintext = hex(b"C001C100080000010000FF0200");
952
953 tx.invocation_counter = 5;
955 let apdu = protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
956 let (_, recovered) = unprotect(&mut rx, &apdu).unwrap();
957 assert_eq!(recovered, plaintext);
958 assert_eq!(rx.last_peer_ic, 5);
959
960 assert_eq!(unprotect(&mut rx, &apdu), Err(CipherError::ReplayDetected));
962
963 tx.invocation_counter = 3;
966 let older = protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
967 assert_eq!(unprotect(&mut rx, &older), Err(CipherError::ReplayDetected));
968 assert_eq!(rx.last_peer_ic, 5);
970
971 tx.invocation_counter = 6;
973 let next = protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
974 assert!(unprotect(&mut rx, &next).is_ok());
975 assert_eq!(rx.last_peer_ic, 6);
976 }
977
978 #[test]
979 fn protect_rejects_exhausted_invocation_counter() {
980 let mut tx = ctx();
981 tx.invocation_counter = u32::MAX;
982 assert_eq!(protect(&tx, glo::GET_REQUEST, b"x"), Err(CipherError::InvocationCounterExhausted));
983 }
984
985 #[test]
986 fn key_rotation_needed_flags_approaching_overflow() {
987 let mut c = ctx();
988 c.invocation_counter = 0;
989 assert!(!c.key_rotation_needed());
990 c.invocation_counter = u32::MAX - 1000;
991 assert!(c.key_rotation_needed());
992 c.invocation_counter = u32::MAX;
993 assert!(c.key_rotation_needed());
994 }
995
996 #[test]
997 fn for_suite_validates_key_length_and_builds_sc() {
998 use crate::security::{SecurityPolicy, SecuritySuite};
999 assert_eq!(
1001 SecurityContext::for_suite(
1002 SecurityPolicy::AuthenticationEncryption,
1003 SecuritySuite::Suite2,
1004 vec![0u8; 16],
1005 vec![0u8; 16],
1006 vec![0u8; 8],
1007 0,
1008 )
1009 .unwrap_err(),
1010 CipherError::InvalidKey
1011 );
1012 let ctx = SecurityContext::for_suite(
1014 SecurityPolicy::AuthenticationEncryption,
1015 SecuritySuite::Suite0,
1016 vec![0u8; 16],
1017 vec![0u8; 16],
1018 vec![0u8; 8],
1019 0,
1020 )
1021 .unwrap();
1022 assert_eq!(ctx.security_control, 0x30);
1023 let ctx2 = SecurityContext::for_suite(
1025 SecurityPolicy::Encryption,
1026 SecuritySuite::Suite2,
1027 vec![0u8; 32],
1028 vec![0u8; 32],
1029 vec![0u8; 8],
1030 0,
1031 )
1032 .unwrap();
1033 assert_eq!(ctx2.security_control, 0x22);
1034 }
1035
1036 #[test]
1037 fn authentication_only_round_trips() {
1038 let mut c = ctx();
1039 c.security_control = security_control::AUTHENTICATION;
1040 let plaintext = hex(b"C001C100080000010000FF0200");
1041 let apdu = protect(&c, glo::GET_REQUEST, &plaintext).unwrap();
1042 assert_eq!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1044 let (_, recovered) = unprotect(&mut c, &apdu).unwrap();
1045 assert_eq!(recovered, plaintext);
1046 }
1047
1048 fn gost_ctx() -> SecurityContext {
1053 SecurityContext {
1054 security_control: security_control::AUTHENTICATED_ENCRYPTION | GOST_SUITE_ID,
1055 encryption_key: hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677"),
1056 authentication_key: hex(b"bddc7e4ac4e164e40785d8c147b4a883bddc7e4ac4e164e40785d8c147b4a883"),
1057 system_title: hex(b"4D4D4D0000BC614E"),
1058 invocation_counter: 0x01234567,
1059 last_peer_ic: 0,
1060 ic_valid: false,
1061 }
1062 }
1063
1064 #[test]
1065 fn gost_protect_unprotect_round_trip() {
1066 let plaintext = hex(b"C001C100080000010000FF0200");
1067 let apdu = gost_protect(&gost_ctx(), glo::GET_REQUEST, &plaintext).unwrap();
1068 let (tag, recovered) = gost_unprotect(&mut gost_ctx(), &apdu).unwrap();
1069 assert_eq!(tag, glo::GET_REQUEST);
1070 assert_eq!(recovered, plaintext);
1071 }
1072
1073 #[test]
1074 fn gost_unprotect_rejects_replayed_ic() {
1075 let mut tx = gost_ctx();
1076 let mut rx = gost_ctx();
1077 let plaintext = hex(b"C001C100080000010000FF0200");
1078
1079 tx.invocation_counter = 5;
1080 let apdu = gost_protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
1081 assert!(gost_unprotect(&mut rx, &apdu).is_ok());
1082 assert_eq!(gost_unprotect(&mut rx, &apdu), Err(CipherError::ReplayDetected));
1083 }
1084
1085 #[test]
1086 fn gost_protect_unprotect_with_auth_only() {
1087 let mut c = gost_ctx();
1088 c.security_control = security_control::AUTHENTICATION | GOST_SUITE_ID;
1089 let plaintext = hex(b"0800065F1F0400007C1F04000007");
1090 let apdu = gost_protect(&c, glo::GET_RESPONSE, &plaintext).unwrap();
1091 assert_eq!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1093 let (_, recovered) = gost_unprotect(&mut c, &apdu).unwrap();
1094 assert_eq!(recovered, plaintext);
1095 }
1096
1097 #[test]
1098 fn gost_protect_unprotect_encryption_only() {
1099 let mut c = gost_ctx();
1100 c.security_control = security_control::ENCRYPTION | GOST_SUITE_ID;
1101 let plaintext = hex(b"C001C100080000010000FF0200");
1102 let apdu = gost_protect(&c, glo::SET_REQUEST, &plaintext).unwrap();
1103 assert_ne!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1105 let (_, recovered) = gost_unprotect(&mut c, &apdu).unwrap();
1106 assert_eq!(recovered, plaintext);
1107 }
1108
1109 #[test]
1110 fn gost_detects_tampering() {
1111 let plaintext = hex(b"0800065F1F0400007C1F04000007");
1112 let mut apdu = gost_protect(&gost_ctx(), glo::GET_RESPONSE, &plaintext).unwrap();
1113 let n = apdu.len();
1114 apdu[n - 1] ^= 0x01; assert_eq!(gost_unprotect(&mut gost_ctx(), &apdu), Err(CipherError::AuthenticationFailed));
1116 }
1117
1118 #[test]
1119 fn gost_wrong_key_fails() {
1120 let mut c = gost_ctx();
1121 c.encryption_key = hex(b"0000000000000000000000000000000000000000000000000000000000000000");
1122 let plaintext = hex(b"C001C100");
1123 let apdu = gost_protect(&c, glo::GET_REQUEST, &plaintext).unwrap();
1124 assert_eq!(gost_unprotect(&mut gost_ctx(), &apdu), Err(CipherError::AuthenticationFailed));
1126 }
1127
1128 #[test]
1129 fn is_gost_suite_detection() {
1130 assert!(is_gost_suite(GOST_SUITE_ID));
1131 assert!(is_gost_suite(0x30 | GOST_SUITE_ID));
1132 assert!(!is_gost_suite(0x30)); assert!(!is_gost_suite(0x31)); }
1135
1136 #[test]
1137 fn gost_counter_increment() {
1138 let mut counter = [0xFFu8; 16];
1139 increment_counter(&mut counter);
1140 assert_eq!(
1141 counter,
1142 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1143 );
1144 }
1145
1146 #[test]
1147 fn gost_cmac_produces_16_octet_tag() {
1148 let key = hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677");
1149 let data = hex(b"0102030405");
1150 let tag = gost_cmac_tag(&key, &data).unwrap();
1151 assert_eq!(tag.len(), 16);
1152 }
1153
1154 fn gost_gmac_ctx() -> SecurityContext {
1159 SecurityContext {
1160 security_control: security_control::AUTHENTICATED_ENCRYPTION | GOST_SUITE_ID,
1161 encryption_key: hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677"),
1162 authentication_key: hex(b"bddc7e4ac4e164e40785d8c147b4a883bddc7e4ac4e164e40785d8c147b4a883"),
1163 system_title: hex(b"4D4D4D0000BC614E"),
1164 invocation_counter: 0x01234567,
1165 last_peer_ic: 0,
1166 ic_valid: false,
1167 }
1168 }
1169
1170 #[test]
1171 fn gost_gmac_protect_unprotect_round_trip() {
1172 let plaintext = hex(b"C001C100080000010000FF0200");
1173 let apdu = gost_gmac_protect(&gost_gmac_ctx(), glo::GET_REQUEST, &plaintext).unwrap();
1174 let (tag, recovered) = gost_gmac_unprotect(&mut gost_gmac_ctx(), &apdu).unwrap();
1175 assert_eq!(tag, glo::GET_REQUEST);
1176 assert_eq!(recovered, plaintext);
1177 }
1178
1179 #[test]
1180 fn gost_gmac_unprotect_rejects_replayed_ic() {
1181 let mut tx = gost_gmac_ctx();
1182 let mut rx = gost_gmac_ctx();
1183 let plaintext = hex(b"C001C100080000010000FF0200");
1184
1185 tx.invocation_counter = 5;
1186 let apdu = gost_gmac_protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
1187 assert!(gost_gmac_unprotect(&mut rx, &apdu).is_ok());
1188 assert_eq!(gost_gmac_unprotect(&mut rx, &apdu), Err(CipherError::ReplayDetected));
1189 }
1190
1191 #[test]
1192 fn gost_gmac_protect_unprotect_with_auth_only() {
1193 let mut c = gost_gmac_ctx();
1194 c.security_control = security_control::AUTHENTICATION | GOST_SUITE_ID;
1195 let plaintext = hex(b"0800065F1F0400007C1F04000007");
1196 let apdu = gost_gmac_protect(&c, glo::GET_RESPONSE, &plaintext).unwrap();
1197 assert_eq!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1199 let (_, recovered) = gost_gmac_unprotect(&mut c, &apdu).unwrap();
1200 assert_eq!(recovered, plaintext);
1201 }
1202
1203 #[test]
1204 fn gost_gmac_protect_unprotect_encryption_only() {
1205 let mut c = gost_gmac_ctx();
1206 c.security_control = security_control::ENCRYPTION | GOST_SUITE_ID;
1207 let plaintext = hex(b"C001C100080000010000FF0200");
1208 let apdu = gost_gmac_protect(&c, glo::SET_REQUEST, &plaintext).unwrap();
1209 assert_ne!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1211 let (_, recovered) = gost_gmac_unprotect(&mut c, &apdu).unwrap();
1212 assert_eq!(recovered, plaintext);
1213 }
1214
1215 #[test]
1216 fn gost_gmac_detects_tampering() {
1217 let plaintext = hex(b"0800065F1F0400007C1F04000007");
1218 let mut apdu = gost_gmac_protect(&gost_gmac_ctx(), glo::GET_RESPONSE, &plaintext).unwrap();
1219 let n = apdu.len();
1220 apdu[n - 1] ^= 0x01; assert_eq!(gost_gmac_unprotect(&mut gost_gmac_ctx(), &apdu), Err(CipherError::AuthenticationFailed));
1222 }
1223
1224 #[test]
1225 fn gost_gmac_wrong_key_fails() {
1226 let mut c = gost_gmac_ctx();
1227 c.encryption_key = hex(b"0000000000000000000000000000000000000000000000000000000000000000");
1228 let plaintext = hex(b"C001C100");
1229 let apdu = gost_gmac_protect(&c, glo::GET_REQUEST, &plaintext).unwrap();
1230 assert_eq!(gost_gmac_unprotect(&mut gost_gmac_ctx(), &apdu), Err(CipherError::AuthenticationFailed));
1232 }
1233
1234 #[test]
1235 fn gost_gmac_tag_produces_16_octet_tag() {
1236 let key = hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677");
1237 let iv = hex(b"4D4D4D0000BC614E01234567");
1238 let aad = hex(b"01");
1239 let data = hex(b"0102030405060708");
1240 let tag = gost_gmac_tag(&key, &iv.try_into().unwrap(), &aad, &data).unwrap();
1241 assert_eq!(tag.len(), 16);
1242 }
1243
1244 #[test]
1245 fn gost_gmac_encrypt_decrypt_round_trip() {
1246 let key = hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677");
1247 let iv_bytes = hex(b"4D4D4D0000BC614E01234567");
1248 let iv: [u8; 12] = iv_bytes.try_into().unwrap();
1249 let plaintext = hex(b"C001C100080000010000FF0200");
1250 let ciphertext = gost_gmac_encrypt(&key, &iv, &plaintext).unwrap();
1251 assert_ne!(ciphertext, plaintext);
1252 let recovered = gost_gmac_decrypt(&key, &iv, &ciphertext).unwrap();
1253 assert_eq!(recovered, plaintext);
1254 }
1255}