-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathaes.rs
More file actions
1662 lines (1483 loc) · 53.8 KB
/
Copy pathaes.rs
File metadata and controls
1662 lines (1483 loc) · 53.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*++
Licensed under the Apache-2.0 license.
File Name:
aes.rs
Abstract:
Driver for AES hardware operations.
Notes about how this hardware differs from other hardware:
* Shadowed control registers need to be written twice.
* Registers are in little-endian order rather than big-endian,
so we cannot use our normal Array4xN types.
--*/
use crate::{
kv_access::{KvAccess, KvAccessErr},
CaliptraError, CaliptraResult, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, LEArray4x16,
LEArray4x3, LEArray4x4, LEArray4x8, Trng,
};
use caliptra_api::mailbox::CmAesMode;
#[cfg(feature = "cfi")]
use caliptra_cfi_derive::cfi_impl_fn;
use caliptra_registers::{aes::AesReg, aes_clp::AesClpReg};
use core::cmp::Ordering;
use zerocopy::{transmute, FromBytes, Immutable, IntoBytes, KnownLayout};
type AesKeyBlock = LEArray4x8;
type AesBlock = LEArray4x4;
/// AES-GCM IV block (96 bits)
pub type AesGcmIvBlock = LEArray4x3;
/// AES-GCM authentication tag (128 bits)
pub type AesGcmTag = LEArray4x4;
pub const AES_BLOCK_SIZE_BYTES: usize = 16;
const _: () = assert!(AES_BLOCK_SIZE_BYTES == core::mem::size_of::<AesBlock>());
const _: () = assert!(32 == core::mem::size_of::<AesKeyBlock>());
pub const AES_BLOCK_SIZE_WORDS: usize = AES_BLOCK_SIZE_BYTES / 4;
const AES_MAX_DATA_SIZE: usize = 1024 * 1024;
pub const AES_GCM_CONTEXT_SIZE_BYTES: usize = 100;
pub const AES_CONTEXT_SIZE_BYTES: usize = 128;
/// From the CMAC specification
const R_B: u128 = 0x87;
const ZERO_BLOCK: AesBlock = AesBlock::new([0; AES_BLOCK_SIZE_WORDS]);
/// AES GCM IV
#[derive(Debug, Copy, Clone)]
pub enum AesGcmIv<'a> {
Array(&'a AesGcmIvBlock),
Random,
}
impl<'a> From<&'a LEArray4x3> for AesGcmIv<'a> {
fn from(value: &'a LEArray4x3) -> Self {
Self::Array(value)
}
}
/// AES Key
#[derive(Debug, Copy, Clone)]
pub enum AesKey<'a> {
/// Array - 32 Bytes (256 bits)
Array(&'a AesKeyBlock),
/// Split key parts that are XOR'd together
Split(&'a AesKeyBlock, &'a AesKeyBlock),
/// Read from the key vault
KV(KeyReadArgs),
}
impl AesKey<'_> {
// returns true if the key must be sideloaded
const fn sideload(&self) -> bool {
matches!(self, AesKey::KV(_))
}
}
impl<'a> From<&'a AesKeyBlock> for AesKey<'a> {
/// Converts to this type from the input type.
fn from(value: &'a AesKeyBlock) -> Self {
Self::Array(value)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u32)]
pub enum AesMode {
Ecb = 1 << 0,
Cbc = 1 << 1,
_Cfb = 1 << 2,
_Ofb = 1 << 3,
Ctr = 1 << 4,
Gcm = 1 << 5,
_None = (1 << 6) - 1,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AesKeyLen {
_128 = 1,
_192 = 2,
_256 = 4,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AesOperation {
Encrypt = 1,
Decrypt = 2,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GcmPhase {
Init = 1 << 0,
Restore = 1 << 1,
Aad = 1 << 2,
Text = 1 << 3,
Save = 1 << 4,
Tag = 1 << 5,
}
#[derive(Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)]
pub struct AesGcmContext {
pub key: AesKeyBlock,
pub iv: LEArray4x3,
pub aad_len: u32,
pub ghash_state: AesBlock,
pub buffer_len: u32,
pub buffer: [u8; 16],
pub reserved: [u32; 4],
}
const _: () = assert!(core::mem::size_of::<AesGcmContext>() == AES_GCM_CONTEXT_SIZE_BYTES);
#[derive(Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)]
pub struct AesContext {
pub mode: u32,
pub key: AesKeyBlock,
pub last_ciphertext: AesBlock,
pub last_block_index: u8,
_padding: [u8; 75],
}
impl Default for AesContext {
fn default() -> Self {
Self {
mode: 0,
key: AesKeyBlock::default(),
last_ciphertext: AesBlock::default(),
last_block_index: 0,
_padding: [0; 75],
}
}
}
const _: () = assert!(core::mem::size_of::<AesContext>() == AES_CONTEXT_SIZE_BYTES);
#[inline(never)]
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut acc = 0;
for i in 0..a.len() {
acc |= a[i] ^ b[i];
}
acc == 0
}
/// AES cryptographic engine driver.
pub struct Aes {
aes: AesReg,
aes_clp: AesClpReg,
}
// the value of this mask is not important, but the AES engine must be programmed
// with the key split into two pieces that are XOR'd together.
const MASK: u32 = 0x1234_5678;
/// Wait for the AES engine to be idle.
/// Necessary before writing control registers.
fn wait_for_idle(aes: &caliptra_registers::aes::RegisterBlock<caliptra_ureg::RealMmioMut<'_>>) {
while !aes.status().read().idle() {}
}
#[allow(clippy::too_many_arguments)]
impl Aes {
/// Create a new AES driver.
///
/// Runs the non-GCM KATs (ECB, CBC, CTR, CMAC) at construction time.
/// GCM and CMAC-KDF KATs are run by the central KAT harness.
pub fn new(aes: AesReg, aes_clp: AesClpReg) -> CaliptraResult<Self> {
if cfg!(feature = "rom") {
panic!("Do not use in ROM!");
}
let mut aes = Self { aes, aes_clp };
if cfg!(feature = "runtime") {
aes.run_kats()?;
}
Ok(aes)
}
fn new_gcm(aes: AesReg, aes_clp: AesClpReg) -> Self {
Self { aes, aes_clp }
}
/// Run the non-GCM KATs (ECB, CBC, CTR, CMAC).
pub fn run_kats(&mut self) -> CaliptraResult<()> {
crate::kats::execute_ecb_kat(self)?;
crate::kats::execute_cbc_kat(self)?;
crate::kats::execute_ctr_kat(self)?;
crate::kats::execute_cmac_kat(self)?;
Ok(())
}
/// Seed the AES Trivium stream cipher primitive with fresh entropy.
///
/// After reset, the Trivium primitive is initialized to a netlist constant
/// and produces deterministic output. Firmware must provide a new 288-bit
/// seed after every reset by writing all 9 `entropy_if_seed` registers.
pub fn seed_entropy_if(&mut self, trng: &mut Trng) -> CaliptraResult<()> {
let entropy = trng.generate()?;
self.with_aes(|_aes, aes_clp| {
let seeds = aes_clp.entropy_if_seed();
for i in 0..9 {
seeds.at(i).write(|_| entropy.0[i]);
}
});
Ok(())
}
// Ensures that only one copy of the AES registers are used
// in any given context to ensure exclusive access.
fn with_aes<T>(
&mut self,
f: impl FnOnce(
caliptra_registers::aes::RegisterBlock<caliptra_ureg::RealMmioMut<'_>>,
caliptra_registers::aes_clp::RegisterBlock<caliptra_ureg::RealMmioMut<'_>>,
) -> T,
) -> T {
let aes = self.aes.regs_mut();
let aes_clp = self.aes_clp.regs_mut();
f(aes, aes_clp)
}
pub fn aes_256_gcm_init(
&mut self,
trng: &mut Trng,
key: &AesKeyBlock,
iv: AesGcmIv,
aad: &[u8],
) -> CaliptraResult<AesGcmContext> {
if aad.len() > AES_MAX_DATA_SIZE {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
let iv = self.initialize_aes_gcm(
trng,
iv,
AesKey::Array(key),
aad,
AesOperation::Encrypt, // doesn't matter
)?;
let ghash_state = if aad.is_empty() {
// Edge case where we have not actually done any AES operations,
// so the GHASH state should not be saved.
AesBlock::default()
} else {
self.save()
};
self.zeroize_internal();
Ok(AesGcmContext {
key: *key,
iv,
aad_len: aad.len() as u32,
ghash_state,
buffer_len: 0,
buffer: [0; 16],
reserved: [0; 4],
})
}
/// Restores the AES context, updates with new plaintext,
/// and returns the number of ciphertext bytes written and
/// the new context.
pub fn aes_256_gcm_encrypt_update(
&mut self,
context: &AesGcmContext,
plaintext: &[u8],
ciphertext: &mut [u8],
) -> CaliptraResult<(usize, AesGcmContext)> {
self.aes_256_gcm_update(context, plaintext, ciphertext, AesOperation::Encrypt)
}
/// Restores the AES context, updates with new ciphertext,
/// and returns the number of plaintext bytes written and
/// the new context.
pub fn aes_256_gcm_decrypt_update(
&mut self,
context: &AesGcmContext,
ciphertext: &[u8],
plaintext: &mut [u8],
) -> CaliptraResult<(usize, AesGcmContext)> {
self.aes_256_gcm_update(context, ciphertext, plaintext, AesOperation::Decrypt)
}
fn aes_256_gcm_update(
&mut self,
context: &AesGcmContext,
mut input: &[u8],
mut output: &mut [u8],
op: AesOperation,
) -> CaliptraResult<(usize, AesGcmContext)> {
let left = context.buffer_len as usize % AES_BLOCK_SIZE_BYTES;
if output.len() < input.len() + left {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
let mut len = context.buffer_len as usize;
if left + input.len() < AES_BLOCK_SIZE_BYTES {
// not enough bytes to do a block, so save in the buffer and return
let mut buffer = [0u8; AES_BLOCK_SIZE_BYTES];
buffer[..left].copy_from_slice(&context.buffer[..left]);
buffer[left..left + input.len()].copy_from_slice(input);
len += input.len();
self.zeroize_internal();
return Ok((
0,
AesGcmContext {
key: context.key,
iv: context.iv,
aad_len: context.aad_len,
ghash_state: context.ghash_state,
buffer_len: len as u32,
buffer,
reserved: [0; 4],
},
));
}
self.restore(
AesKey::Array(&context.key),
&context.iv,
context.aad_len,
context.buffer_len,
context.ghash_state,
op,
)?;
// check if we need to process the previous buffer
let mut written = 0;
if left > 0 {
// guaranteed to have at least one block to do
let mut buffer = [0u8; AES_BLOCK_SIZE_BYTES];
buffer[..left].copy_from_slice(&context.buffer[..left]);
let take = AES_BLOCK_SIZE_BYTES - left;
buffer[left..].copy_from_slice(&input[..take]);
input = &input[take..];
len += take;
self.read_write_data_gcm(&buffer, GcmPhase::Text, Some(output))?;
output = &mut output[AES_BLOCK_SIZE_BYTES..];
written += AES_BLOCK_SIZE_BYTES;
}
// Write blocks of input and read blocks of output.
while input.len() >= AES_BLOCK_SIZE_BYTES {
let take = AES_BLOCK_SIZE_BYTES;
// should be impossible but needed to prevent panic
if output.len() < take {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
self.read_write_data_gcm(&input[..take], GcmPhase::Text, Some(output))?;
written += take;
output = &mut output[take..];
input = &input[take..];
len += take;
}
// Save the remaining plaintext in the buffer.
len += input.len();
let mut buffer = [0u8; AES_BLOCK_SIZE_BYTES];
buffer[..input.len()].copy_from_slice(input);
let ghash_state = if context.aad_len == 0 && context.buffer_len == 0 {
// Edge case where we have not actually done any AES operations,
// so the GHASH state should not be saved.
AesBlock::default()
} else {
self.save()
};
self.zeroize_internal();
Ok((
written,
AesGcmContext {
key: context.key,
iv: context.iv,
aad_len: context.aad_len,
ghash_state,
buffer_len: len as u32,
buffer,
reserved: [0; 4],
},
))
}
/// Computes the final ciphertext, and returns the number of ciphertext bytes
/// written and the final 16-byte tag.
pub fn aes_256_gcm_encrypt_final(
&mut self,
context: &AesGcmContext,
plaintext: &[u8],
ciphertext: &mut [u8],
) -> CaliptraResult<(usize, AesGcmTag)> {
self.aes_256_gcm_final(context, plaintext, ciphertext, AesOperation::Encrypt)
}
/// Computes the final plaintext, and returns the number of plaintext bytes
/// written and whether the tags matched.
pub fn aes_256_gcm_decrypt_final(
&mut self,
context: &AesGcmContext,
ciphertext: &[u8],
plaintext: &mut [u8],
tag: &[u8],
) -> CaliptraResult<(usize, bool)> {
if tag.len() > AES_BLOCK_SIZE_BYTES {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_TAG_SIZE)?;
}
let (written, computed_tag) =
self.aes_256_gcm_final(context, ciphertext, plaintext, AesOperation::Decrypt)?;
let computed_tag = computed_tag.as_bytes();
let tag_matches = constant_time_eq(tag, computed_tag);
Ok((written, tag_matches))
}
/// Restores the AES context, updates with new input,
/// and returns the number of output bytes written and the final 16-byte tag.
fn aes_256_gcm_final(
&mut self,
context: &AesGcmContext,
mut input: &[u8],
mut output: &mut [u8],
op: AesOperation,
) -> CaliptraResult<(usize, AesGcmTag)> {
let left = context.buffer_len as usize % AES_BLOCK_SIZE_BYTES;
if output.len() < input.len() + left {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
self.restore(
AesKey::Array(&context.key),
&context.iv,
context.aad_len,
context.buffer_len,
context.ghash_state,
op,
)?;
// check if we need to process the previous buffer
let mut len = context.buffer_len as usize;
let mut written = 0;
let mut new_input = [0u8; AES_BLOCK_SIZE_BYTES];
let mut input = if left > 0 {
if left + input.len() >= AES_BLOCK_SIZE_BYTES {
let mut buffer = [0u8; AES_BLOCK_SIZE_BYTES];
buffer[..left].copy_from_slice(&context.buffer[..left]);
let take = AES_BLOCK_SIZE_BYTES - left;
buffer[left..].copy_from_slice(&input[..take]);
input = &input[take..];
len += take;
self.read_write_data_gcm(&buffer, GcmPhase::Text, Some(output))?;
output = &mut output[AES_BLOCK_SIZE_BYTES..];
written += AES_BLOCK_SIZE_BYTES;
input
} else {
// edge case where the buffer and input are not enough to do a block
len -= left; // correct the length, which is added again later
new_input[..left].copy_from_slice(&context.buffer[..left]);
new_input[left..left + input.len()].copy_from_slice(input);
&new_input[..left + input.len()]
}
} else {
input
};
// Write blocks of plaintext and read blocks of ciphertext out.
while input.len() >= AES_BLOCK_SIZE_BYTES {
let take = AES_BLOCK_SIZE_BYTES;
// should be impossible but needed to prevent panic
if take > output.len() {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
self.read_write_data_gcm(&input[..take], GcmPhase::Text, Some(output))?;
output = &mut output[take..];
input = &input[take..];
len += take;
written += take;
}
// Do the final block
if !input.is_empty() {
self.read_write_data_gcm(input, GcmPhase::Text, Some(output))?;
len += input.len();
written += input.len();
}
// Compute and return the tag
let tag = self.compute_tag(context.aad_len as usize, len)?;
Ok((written, tag))
}
/// Saves and returns the current GHASH state.
fn save(&mut self) -> AesBlock {
self.with_aes(|aes, _| {
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_gcm_shadowed()
.write(|w| w.phase(GcmPhase::Save as u32));
}
wait_for_idle(&aes);
// Read out the GHASH state from the data out registers.
let ghash_state = AesBlock::read_from_reg(aes.data_out());
wait_for_idle(&aes);
ghash_state
})
}
/// Restores the GHASH state.
fn restore(
&mut self,
key: AesKey,
iv: &LEArray4x3,
aad_len: u32,
len: u32,
ghash_state: AesBlock,
op: AesOperation,
) -> CaliptraResult<()> {
// No zerocopy since we can't guarantee that the
// byte array is aligned to 4-byte boundaries.
let iv = [
iv.0[0],
iv.0[1],
iv.0[2],
// hardware quirk: the hardware seems to expect IV[3] to be
// presented as a big-endian int instead of little-endian, like elsewhere.
// The specs expect us to store the whole IV when saving and restoring,
// but this is not necessary if we already know the length and can compute this,
// and account for the different endianness of this register.
(len / (AES_BLOCK_SIZE_BYTES as u32) + 2).swap_bytes(),
];
// sideload the KV key before we program the control register
if key.sideload() {
self.load_key(key)?;
}
self.with_aes(|aes, _| {
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_shadowed().write(|w| {
w.key_len(AesKeyLen::_256 as u32)
.mode(AesMode::Gcm as u32)
.operation(op as u32)
.manual_operation(false)
.sideload(key.sideload())
});
}
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_gcm_shadowed()
.write(|w| w.phase(GcmPhase::Init as u32).num_valid_bytes(16));
}
wait_for_idle(&aes);
});
if !key.sideload() {
self.load_key(key)?;
}
self.with_aes(|aes, _| {
wait_for_idle(&aes);
// Program the initial IV (last 4 bytes will be zero)
for (i, ivi) in iv.into_iter().enumerate().take(3) {
aes.iv().at(i).write(|_| ivi);
}
aes.iv().at(3).write(|_| 0);
wait_for_idle(&aes);
// if we haven't actually written any AAD or input, then
// we can skip the restore operation.
// This avoids some edge cases in the hardware.
if aad_len == 0 && len == 0 {
return Ok(());
}
// Restore the GHASH state to data_in registers, which will load the state into the
// GHASH unit.
for _ in 0..2 {
aes.ctrl_gcm_shadowed()
.write(|w| w.phase(GcmPhase::Restore as u32));
}
wait_for_idle(&aes);
ghash_state.write_to_reg(aes.data_in());
wait_for_idle(&aes);
// Program the IV (last 4 bytes may not be zero, unlike when doing normal init)
for (i, ivi) in iv.into_iter().enumerate() {
aes.iv().at(i).write(|_| ivi);
}
wait_for_idle(&aes);
Ok::<(), CaliptraError>(())
})
}
/// Calculate the AES-256-GCM encrypted ciphertext for the given plaintext.
/// Returns the IV and the tag.
#[cfg_attr(feature = "cfi", cfi_impl_fn)]
pub fn aes_256_gcm_encrypt(
&mut self,
trng: &mut Trng,
iv: AesGcmIv,
key: AesKey,
aad: &[u8],
plaintext: &[u8],
ciphertext: &mut [u8],
tag_size: usize,
) -> CaliptraResult<(AesGcmIvBlock, AesGcmTag)> {
if tag_size > AES_BLOCK_SIZE_BYTES {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_TAG_SIZE)?;
}
if ciphertext.len() < plaintext.len() {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
self.aes_256_gcm_op(
trng,
iv,
key,
aad,
plaintext,
ciphertext,
AesOperation::Encrypt,
)
}
/// Calculate the AES-256-GCM decrypted plaintext for the given ciphertext.
#[cfg_attr(feature = "cfi", cfi_impl_fn)]
pub fn aes_256_gcm_decrypt(
&mut self,
trng: &mut Trng,
iv: &LEArray4x3,
key: AesKey,
aad: &[u8],
ciphertext: &[u8],
plaintext: &mut [u8],
tag: &LEArray4x4,
) -> CaliptraResult<()> {
if plaintext.len() < ciphertext.len() {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
let (_, computed_tag) = self.aes_256_gcm_op(
trng,
iv.into(),
key,
aad,
ciphertext,
plaintext,
AesOperation::Decrypt,
)?;
if !constant_time_eq(tag.as_bytes(), computed_tag.as_bytes()) {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_TAG)?;
}
Ok(())
}
/// Initializes the AES engine for GCM mode and returns the IV used.
#[cfg_attr(feature = "cfi", cfi_impl_fn)]
pub fn initialize_aes_gcm(
&mut self,
trng: &mut Trng,
iv: AesGcmIv,
key: AesKey,
aad: &[u8],
op: AesOperation,
) -> CaliptraResult<AesGcmIvBlock> {
if matches!(op, AesOperation::Decrypt) && matches!(iv, AesGcmIv::Random) {
// should be impossible
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_STATE)?;
}
// No zerocopy since we can't guarantee that the
// byte array is aligned to 4-byte boundaries.
let iv: LEArray4x3 = match iv {
AesGcmIv::Array(iv) => *iv,
AesGcmIv::Random => LEArray4x3::new(trng.generate()?.0[..3].try_into().unwrap()),
};
// sideload the KV key before we program the control register
if key.sideload() {
self.load_key(key)?;
}
self.with_aes(|aes, _| {
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_shadowed().write(|w| {
w.key_len(AesKeyLen::_256 as u32)
.mode(AesMode::Gcm as u32)
.operation(op as u32)
.manual_operation(false)
.sideload(key.sideload())
});
}
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_gcm_shadowed()
.write(|w| w.phase(GcmPhase::Init as u32).num_valid_bytes(16));
}
wait_for_idle(&aes);
});
if !key.sideload() {
self.load_key(key)?;
}
self.with_aes(|aes, _| {
wait_for_idle(&aes);
// Program the IV (last 4 bytes must be 0).
for (i, ivi) in iv.0.into_iter().enumerate() {
aes.iv().at(i).write(|_| ivi);
}
aes.iv().at(3).write(|_| 0);
wait_for_idle(&aes);
Ok::<(), CaliptraError>(())
})?;
// Load the AAD
if !aad.is_empty() {
self.read_write_data_gcm(aad, GcmPhase::Aad, None)?;
}
Ok(iv)
}
fn load_key(&mut self, key: AesKey<'_>) -> CaliptraResult<()> {
self.with_aes(|aes, aes_clp| {
wait_for_idle(&aes);
// Program the key
// No zerocopy since we can't guarantee that the
// byte arrays are aligned to 4-byte boundaries.
match key {
AesKey::Array(&arr) => {
for (i, word) in arr.0.iter().enumerate() {
aes.key_share0().at(i).write(|_| *word ^ MASK);
aes.key_share1().at(i).write(|_| MASK);
}
}
AesKey::Split(&key1, &key2) => {
key1.write_to_reg(aes.key_share0());
key2.write_to_reg(aes.key_share1());
}
AesKey::KV(key) => KvAccess::copy_from_kv(
key,
aes_clp.aes_kv_rd_key_status(),
aes_clp.aes_kv_rd_key_ctrl(),
)
.map_err(|_| CaliptraError::DRIVER_AES_READ_KEY_KV_READ)?,
}
wait_for_idle(&aes);
Ok(())
})
}
/// Initializes the AES engine for CBC or CTR mode
#[cfg_attr(feature = "cfi", cfi_impl_fn)]
fn initialize_aes_cbc_ctr(
&mut self,
iv: &AesBlock,
key: AesKey,
op: AesOperation,
mode: AesMode,
) -> CaliptraResult<()> {
// sideload the KV key before we program the control register
if key.sideload() {
self.load_key(key)?;
}
self.with_aes(|aes, _| {
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_shadowed().write(|w| {
w.key_len(AesKeyLen::_256 as u32)
.mode(mode as u32)
.operation(op as u32)
.manual_operation(false)
.sideload(key.sideload())
});
}
wait_for_idle(&aes);
});
if !key.sideload() {
self.load_key(key)?;
}
// Program the IV
self.with_aes(|aes, _| {
wait_for_idle(&aes);
iv.write_to_reg(aes.iv());
wait_for_idle(&aes);
});
Ok(())
}
#[cfg_attr(feature = "cfi", cfi_impl_fn)]
fn aes_256_gcm_op(
&mut self,
trng: &mut Trng,
iv: AesGcmIv,
key: AesKey,
aad: &[u8],
input: &[u8],
output: &mut [u8],
op: AesOperation,
) -> CaliptraResult<(AesGcmIvBlock, AesGcmTag)> {
if input.len() > AES_MAX_DATA_SIZE || output.len() > AES_MAX_DATA_SIZE {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
if input.len() > output.len() {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
let iv = self.initialize_aes_gcm(trng, iv, key, aad, op)?;
// Write blocks of plaintext and read blocks of ciphertext out.
self.read_write_data_gcm(input, GcmPhase::Text, Some(output))?;
let tag = self.compute_tag(aad.len(), input.len())?;
Ok((iv, tag))
}
pub fn compute_tag(&mut self, aad_len: usize, text_len: usize) -> CaliptraResult<AesGcmTag> {
// Compute the tag
self.with_aes(|aes, _| {
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_gcm_shadowed().write(|w| {
w.phase(GcmPhase::Tag as u32)
.num_valid_bytes(AES_BLOCK_SIZE_BYTES as u32)
});
}
});
// Compute the final block and load it into data_in
let mut tag_input = [0u8; AES_BLOCK_SIZE_BYTES];
// as per NIST SP 800-38D, algorithm 4, step 5, the last block
// is len(A) || len(C), with the lengths in bits
tag_input[0..8].copy_from_slice(&((aad_len * 8) as u64).to_be_bytes());
tag_input[8..16].copy_from_slice(&((text_len * 8) as u64).to_be_bytes());
self.load_data_block(&tag_input, 0)?;
// Read out the tag.
let tag_return = self.read_data_block_u32();
self.zeroize_internal();
Ok(tag_return)
}
fn read_data_block_u32(&mut self) -> AesBlock {
let aes = self.aes.regs_mut();
while !aes.status().read().output_valid() {}
AesBlock::read_from_reg(aes.data_out())
}
fn read_data_block(&mut self, output: &mut [u8], block_num: usize) -> CaliptraResult<()> {
// not possible but needed to prevent panic
if block_num * AES_BLOCK_SIZE_BYTES >= output.len() {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
// read the data out
let buffer = self.read_data_block_u32();
let buffer: [u8; AES_BLOCK_SIZE_BYTES] = transmute!(buffer);
let output = &mut output[block_num * AES_BLOCK_SIZE_BYTES..];
let len = output.len().min(AES_BLOCK_SIZE_BYTES);
let output = &mut output[..len];
output.copy_from_slice(&buffer[..len]);
Ok(())
}
fn load_data_block_u32(&mut self, data: AesBlock) {
let aes = self.aes.regs_mut();
while !aes.status().read().input_ready() {}
data.write_to_reg(aes.data_in());
}
fn load_data_block(&mut self, data: &[u8], block_num: usize) -> CaliptraResult<()> {
// not possible but needed to prevent panic
if block_num * AES_BLOCK_SIZE_BYTES >= data.len() {
Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?;
}
let data = &data[block_num * AES_BLOCK_SIZE_BYTES..];
let data = &data[..AES_BLOCK_SIZE_BYTES.min(data.len())];
let len = data.len();
let mut padded_data = [0u8; AES_BLOCK_SIZE_BYTES];
padded_data[..len].copy_from_slice(data);
self.load_data_block_u32(transmute!(padded_data));
Ok(())
}
pub fn gcm_set_text(&mut self, len: u32) {
// set the mode and valid length
self.with_aes(|aes, _| {
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_gcm_shadowed()
.write(|w| w.phase(GcmPhase::Text as u32).num_valid_bytes(len));
}
wait_for_idle(&aes);
});
}
fn read_write_data_gcm(
&mut self,
input: &[u8],
phase: GcmPhase,
output: Option<&mut [u8]>,
) -> CaliptraResult<()> {
let num_blocks = input.len().div_ceil(AES_BLOCK_SIZE_BYTES);
// length of the last block
let partial_text_len = input.len() % AES_BLOCK_SIZE_BYTES;
let read_output = output.is_some();
let output = output.unwrap_or(&mut []);
for i in 0..num_blocks {
if i == 0 || ((i == num_blocks - 1) && (partial_text_len != 0)) {
let num_bytes = if (i == num_blocks - 1) && partial_text_len != 0 {
partial_text_len
} else {
AES_BLOCK_SIZE_BYTES
};
// set the mode and valid length
self.with_aes(|aes, _| {
wait_for_idle(&aes);
for _ in 0..2 {
aes.ctrl_gcm_shadowed()
.write(|w| w.phase(phase as u32).num_valid_bytes(num_bytes as u32));
}
});
}
self.load_data_block(input, i)?;
if read_output {
self.read_data_block(output, i)?;
}
}
Ok(())
}
#[cfg_attr(feature = "cfi", cfi_impl_fn)]
/// AES ECB Decrypt to KV. Used by OCP LOCK for MEK release.
pub fn aes_256_ecb_decrypt_kv(&mut self, input: &LEArray4x16) -> CaliptraResult<()> {
// Only KV 16 is allowed to be key KV.
let mdk_slot = KeyReadArgs::new(KeyId::KeyId16);
// Only KV 23 is allowed to be destination KV.
let mek_slot = KeyWriteArgs::new(KeyId::KeyId23, KeyUsage::default().set_dma_data_en());
self.aes_256_ecb_decrypt_kv_internal(AesKey::KV(mdk_slot), mek_slot, input)
}
/// AES ECB Decrypt to KV.
///
/// NOTE: Use `aes_256_ecb_decrypt_kv` so API invariants are enforced.
pub fn aes_256_ecb_decrypt_kv_internal(
&mut self,
key: AesKey,
output_kv: KeyWriteArgs,
input: &LEArray4x16,
) -> CaliptraResult<()> {
// Key is always in KV, always load before starting OP.
self.load_key(key)?;