-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathencryption-versal.cpp
executable file
·1475 lines (1297 loc) · 54.4 KB
/
encryption-versal.cpp
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
/******************************************************************************
* Copyright 2015-2022 Xilinx, Inc.
* Copyright 2022-2023 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/*
-------------------------------------------------------------------------------
*********************************************** H E A D E R F I L E S ***
-------------------------------------------------------------------------------
*/
#include "encryption-versal.h"
#include "bootimage.h"
#include "encryptutils.h"
#include "options.h"
#include "imageheadertable-versal.h"
#include "partitionheadertable-versal.h"
#include <openssl/rand.h>
/*
-------------------------------------------------------------------------------
***************************************************** F U N C T I O N S ***
-------------------------------------------------------------------------------
*/
/******************************************************************************/
VersalEncryptionContext::VersalEncryptionContext()
: isBootloader(false)
, aesSeedexits(false)
, isPmcData(false)
{
encryptionAlgorithm = new AesGcmEncryptionContext();
};
/******************************************************************************/
VersalEncryptionContext::VersalEncryptionContext(const EncryptionContext* other)
: isBootloader(false)
, aesSeedexits(false)
, isPmcData(false)
{
aesFilename = other->aesFilename;
encryptionAlgorithm = new AesGcmEncryptionContext();
}
/******************************************************************************/
VersalEncryptionContext::~VersalEncryptionContext()
{
if (encryptionAlgorithm != NULL)
{
delete[] encryptionAlgorithm;
}
}
/******************************************************************************/
void VersalEncryptionContext::SetAesKey(const uint8_t* key)
{
aesKey = new uint32_t[WORDS_PER_AES_KEY];
for (uint32_t index = 0; index < WORDS_PER_AES_KEY; index++)
{
aesKey[index] = ReadBigEndian32(key);
key += sizeof(uint32_t);
}
}
/******************************************************************************/
void VersalEncryptionContext::SetAesSeedString(const std::string& key)
{
uint8_t hexData[256];
if (key.size() != (WORDS_PER_AES_KEY * 8))
{
LOG_DEBUG(DEBUG_STAMP, "Seed size - %d", key.size());
LOG_ERROR("An AES Seed must be 256 bits long - %s", key.c_str());
}
PackHex(key, hexData);
SetAesSeed(hexData);
}
/******************************************************************************/
void VersalEncryptionContext::GenerateAesKey(void)
{
uint32_t keysize = WORDS_PER_AES_KEY * sizeof(uint32_t);
uint8_t newKey[BYTES_PER_AES_KEY];
RAND_bytes(newKey, keysize);
SetAesKey(newKey);
LOG_INFO("AES Key generated successfully");
}
/******************************************************************************/
void VersalEncryptionContext::GetEncryptionKeys(Options& options, uint8_t* aesKey,
uint8_t* aesOptKey, uint8_t* aesIV)
{
const uint32_t* tmpKey = GetAesKey();
if (tmpKey != NULL)
{
memcpy_be(aesKey, tmpKey, AES_GCM_KEY_SZ);
}
else
{
LOG_ERROR("Encryption Error !!!\n Key 0 does not exist in the AES key file ");
}
const uint32_t* tmpIv = GetIv();
if (tmpIv != NULL)
{
memcpy_be(aesIV, tmpIv, AES_GCM_IV_SZ);
}
else
{
LOG_ERROR("IV does not exist in the AES key file ");
}
}
/******************************************************************************/
void VersalEncryptionContext::WriteEncryptionKeyFile(const std::string & baseFileName,
bool useOptionalKey, uint32_t blocks)
{
uint32_t x, y, index;
/* Setup the file for writing */
std::string ext = StringUtils::GetExtension(baseFileName);
std::string filename;
if (ext == "")
{
filename = baseFileName + ".nky";
}
else
{
filename = baseFileName;
}
std::ofstream keyFile(filename.c_str());
if (!keyFile)
{
LOG_ERROR("Failure writing AES key file", filename.c_str());
}
/* Write device name */
if (deviceName != "")
{
keyFile << "Device " << deviceName << ";\n";
keyFile << "\n";
}
/* Ko can then be used for key/iv pairs */
for (x = 0; x<blocks; x++)
{
keyFile << "Key " << std::dec << x;
keyFile << " ";
if (x == 0 && GetAesKey() != NULL)
{
for (index = 0; index < WORDS_PER_AES_KEY; ++index)
{
keyFile << std::uppercase << std::hex << std::setfill('0') << std::setw(8) << aesKey[index];
}
}
else
{
for (y = 0; y < WORDS_PER_AES_KEY; y++)
{
keyFile << std::uppercase << std::hex << std::setfill('0') << std::setw(8) << outBufKDF[11 * x + y];
}
}
keyFile << ";\n";
keyFile << "IV " << std::dec << x;
keyFile << " ";
for (y = WORDS_PER_AES_KEY; y < WORDS_PER_AES_KEY + WORDS_PER_IV; y++)
{
keyFile << std::uppercase << std::hex << std::setfill('0') << std::setw(8) << outBufKDF[11 * x + y];
}
keyFile << ";\n";
keyFile << "\n";
}
}
/******************************************************************************/
void VersalEncryptionContext::ReadEncryptionKeyFile(const std::string& inputFileName)
{
LOG_TRACE("Reading the AES key file");
std::ifstream keyFile(inputFileName.c_str());
aesKeyVec.clear();
aesIvVec.clear();
int aesKeyNum = 0;
int aesIvNum = 0;
if (!keyFile)
{
LOG_ERROR("Failure reading AES key file - %s", inputFileName.c_str());
}
while (keyFile)
{
std::string word;
keyFile >> word;
if (word == "")
{
return;
}
char c = ' ';
if (word == "Device")
{
word = "";
keyFile >> word;
c = word[word.size() - 1];
word.erase(word.size() - 1);
deviceName = word;
}
else if (word == "Key")
{
keyFile >> word;
if (word == "Opt")
{
LOG_ERROR("The key word 'Key Opt' is not supported in VERSAL architecture");
}
if (word != "" && isalnum(word[0]))
{
/* Second Word is "0" or "1" or "2" ...*/
int index = std::stoi(word);
if (aesKeyNum != index)
{
LOG_DEBUG(DEBUG_STAMP, "Key order incorrect.");
LOG_ERROR("Error parsing AES key file - %s.", inputFileName.c_str());
}
aesKeyNum++;
word = "";
while ((keyFile >> c) && isalnum(c))
{
word.push_back(c);
}
if (aesKeyVec.size() == 0)
{
SetAesKeyString(word);
}
aesKeyVec.push_back(word);
}
else
{
/* Second Word other than "0", - throw error */
LOG_DEBUG(DEBUG_STAMP, "Unknown key type - '%s' in %s", word.c_str(), inputFileName.c_str());
LOG_ERROR("Error parsing AES key file - %s", inputFileName.c_str());
}
}
else if (word == "IV")
{
keyFile >> word;
if (word != "")
{
if (word.size() == ((BYTES_PER_IV * 2) + 1))
{
c = word[word.size() - 1];
word.erase(word.size() - 1);
SetIvString(word);
}
else
{
int index = std::stoi(word);
if (aesIvNum != index)
{
LOG_DEBUG(DEBUG_STAMP, "Iv order incorrect.");
LOG_ERROR("Error parsing AES key file - %s.", inputFileName.c_str());
}
aesIvNum++;
word = "";
while ((keyFile >> c) && isalnum(c))
{
word.push_back(c);
}
if (aesIvVec.size() == 0)
{
SetIvString(word);
}
}
}
aesIvVec.push_back(word);
}
else if (word == "Seed")
{
word = "";
while ((keyFile >> c) && isalnum(c))
{
word.push_back(c);
}
SetAesSeedString(word);
aesSeedexits = true;
}
else if (word == "Label")
{
LOG_ERROR("The input 'Label' is deprecated.\n\t Please construct a FixedInputData of 60 Bytes instead and provide the same in the nky file.This will be used along with Seed in KDF.");
}
else if (word == "Context")
{
LOG_ERROR("The input 'Context' is deprecated.\n\t Please construct a FixedInputData of 60 Bytes instead and provide the same in the nky file.This will be used along with Seed in KDF.");
}
else if (word == "FixedInputData")
{
word = "";
while ((keyFile >> c) && isalnum(c))
{
word.push_back(c);
}
SetAesFixedInputDataString(word);
fixedInputDataExits = true;
}
else
{
/* If the word is neither of the above */
LOG_DEBUG(DEBUG_STAMP, "'Key' or 'Device' identifier expected, '%s' found instead", word.c_str());
LOG_ERROR("Error parsing AES key file - %s", inputFileName.c_str());
}
if (c != ';')
{
/* Semicolons expected at end of every line */
while ((keyFile >> c) && isspace(c))
{
word.push_back(c);
}
}
if (c != ';')
{
LOG_DEBUG(DEBUG_STAMP, "Terminating ';' expected. Last word read was '%s'", word.c_str());
LOG_ERROR("Error parsing AES key file - %s", inputFileName.c_str());
}
if (deviceName == "")
{
LOG_DEBUG(DEBUG_STAMP, "Partname 'Device' missing in the key file - %s", inputFileName.c_str());
LOG_ERROR("Error parsing AES key file - %s", inputFileName.c_str());
}
if ((aesKeyVec.size() > 1 || aesIvVec.size() > 1) && aesSeedexits)
{
LOG_ERROR("Seed is not expected with multiple keys/Iv.");
}
if (fixedInputDataExits && !aesSeedexits)
{
LOG_ERROR("Seed must be specified along with FixedInputData.");
}
}
}
/******************************************************************************/
void VersalEncryptionContext::PackNextEncryptionKey(uint8_t* aesKeyNext, int aeskeyPtr)
{
uint8_t hexData[AES_GCM_KEY_SZ];
uint8_t* hexDataPtr = hexData;
if (aesKeyVec[aeskeyPtr].length() != (WORDS_PER_AES_KEY * 8))
{
LOG_DEBUG(DEBUG_STAMP, "AES key %d size - %d", aeskeyPtr, aesKeyVec[aeskeyPtr].length());
LOG_ERROR("An AES key must be 256 bits long - %s", aesKeyVec[aeskeyPtr].c_str());
}
if (aesKeyVec[aeskeyPtr].length() & 1)
{
LOG_DEBUG(DEBUG_STAMP, "Hex String - %s - does not have even no. of hex digits", aesKeyVec[aeskeyPtr].c_str());
LOG_ERROR("Error parsing encryption key");
}
for (uint32_t i = 0; i<aesKeyVec[aeskeyPtr].length(); i += 2)
{
std::string byte = aesKeyVec[aeskeyPtr].substr(i, 2);
if (!isxdigit(byte[0]) || !isxdigit(byte[1]))
{
LOG_DEBUG(DEBUG_STAMP, "Hex String - %s - is has a non hex digit", aesKeyVec[aeskeyPtr].c_str());
LOG_ERROR("Error parsing encryption key");
}
*hexDataPtr++ = (uint8_t)strtoul(byte.c_str(), NULL, 16);
}
hexDataPtr = hexData;
memcpy(aesKeyNext, hexDataPtr, AES_GCM_KEY_SZ);
}
/******************************************************************************/
void VersalEncryptionContext::PackNextIv(uint8_t* aesIVNext, int aesIvPtr)
{
uint8_t hexData[AES_GCM_IV_SZ];
uint8_t* hexDataPtr = hexData;
if (aesIvVec[aesIvPtr].length() != (BYTES_PER_IV * 2))
{
LOG_DEBUG(DEBUG_STAMP, "IV[%d] Size = %d", aesIvPtr, aesIvVec[aesIvPtr].length());
LOG_ERROR("Encryption Error !!!\n An IV key must be 12 bytes long");
}
if (aesIvVec[aesIvPtr].length() & 1)
{
LOG_DEBUG(DEBUG_STAMP, "Hex String - %s - does not have even no. of hex digits", aesIvVec[aesIvPtr].c_str());
LOG_ERROR("Error parsing encryption key");
}
for (uint32_t i = 0; i<aesIvVec[aesIvPtr].length(); i += 2)
{
std::string byte = aesIvVec[aesIvPtr].substr(i, 2);
if (!isxdigit(byte[0]) || !isxdigit(byte[1]))
{
LOG_DEBUG(DEBUG_STAMP, "Hex String - %s - is has a non hex digit", aesIvVec[aesIvPtr].c_str());
LOG_ERROR("Error parsing encryption key");
}
*hexDataPtr++ = (uint8_t)strtoul(byte.c_str(), NULL, 16);
}
hexDataPtr = hexData;
memcpy(aesIVNext, hexDataPtr, BYTES_PER_IV);
}
/******************************************************************************/
void VersalEncryptionContext::GetNextKey(uint8_t * keyNext, int ptr)
{
PackNextEncryptionKey(keyNext, ptr);
}
/******************************************************************************/
void VersalEncryptionContext::GetNextIv(uint8_t * keyNext, int ptr)
{
PackNextIv(keyNext, ptr);
}
/******************************************************************************/
void VersalEncryptionContext::SetAesSeed(const uint8_t* key)
{
aesSeed = new uint32_t[WORDS_PER_AES_KEY];
for (uint32_t index = 0; index < WORDS_PER_AES_KEY; index++)
{
aesSeed[index] = ReadBigEndian32(key);
key += sizeof(uint32_t);
}
}
/******************************************************************************/
const uint32_t* VersalEncryptionContext::GetAesSeed(void)
{
return (uint32_t *)aesSeed;
}
/******************************************************************************/
const uint32_t* VersalEncryptionContext::GetAesKey(void)
{
return (uint32_t *)aesKey;
}
/******************************************************************************/
void VersalEncryptionContext::SetIv(const uint8_t* iv)
{
aesIv = new uint32_t[WORDS_PER_IV];
for (uint32_t index = 0; index < WORDS_PER_IV; index++)
{
aesIv[index] = ReadBigEndian32(iv);
iv += sizeof(uint32_t);
}
}
/******************************************************************************/
void VersalEncryptionContext::SetIvString(const std::string& IV)
{
uint8_t hexData[256];
if (IV.size() != (BYTES_PER_IV * 2))
{
LOG_DEBUG(DEBUG_STAMP, "IV = %s, IV Size = %d", IV.c_str(), IV.size());
LOG_ERROR("Encryption Error !!!\n An IV key must be 12 bytes long");
}
PackHex(IV, hexData);
SetIv(hexData);
}
/******************************************************************************/
void VersalEncryptionContext::GenerateIv(void)
{
uint8_t newIVData[BYTES_PER_IV];
RAND_bytes(newIVData, BYTES_PER_IV);
SetIv(newIVData);
LOG_INFO("AES IV generated successfully");
}
/******************************************************************************/
const uint32_t* VersalEncryptionContext::GetIv(void)
{
return (uint32_t *)aesIv;
}
/******************************************************************************/
void VersalEncryptionContext::GenerateRemainingKeys(Options& options)
{
uint32_t blocks, x = 0;
if (GetAesKey() == NULL && !aesSeedexits)
{
LOG_ERROR("Encryption Error !!!\n Key 0 does not exist in the AES key file ");
}
if (GetIv() == NULL && !aesSeedexits)
{
LOG_ERROR("IV 0 does not exist in the AES key file ");
}
if (aesKeyVec.size() != aesIvVec.size())
{
//LOG_ERROR("Encryption Error !!!\n Number of Keys in the AES key file are not equal to the number of IVs. ");
}
/* If only seed exists in the given in nky file => No key0/iv0 mentioned. +1 to generate key0/IV0 for SH */
if ((aesKeyVec.size() == 0 || aesIvVec.size() == 0))
{
blocks = options.bifOptions->GetEncryptionBlocksList().size() + 1;
}
else
{
blocks = options.bifOptions->GetEncryptionBlocksList().size();
}
if (GetAesSeed() == NULL)
{
aesSeed = new uint32_t[WORDS_PER_AES_KEY];
memset(aesSeed, 0, WORDS_PER_AES_KEY);
GenerateAesSeed();
}
if (GetFixedInputData() == NULL)
{
fixedInputData = new uint32_t[WORDS_PER_FID];
memset(fixedInputData, 0, WORDS_PER_FID);
GenerateAesFixedInputData();
}
uint32_t outBufBytes = blocks * (AES_GCM_KEY_SZ + AES_GCM_IV_SZ);
outBufKDF = new uint32_t[outBufBytes];
SetKdfLogFile(options.GetEncryptionDumpFlag());
uint32_t ret = kdf->CounterModeKDF(aesSeed, fixedInputData, fixedInputDataByteLength, outBufKDF, outBufBytes);
if (ret != 0)
{
LOG_ERROR("Error generating encryption keys from Counter Mode KDF.");
}
uint8_t aesKeyNext[AES_GCM_KEY_SZ];
uint8_t aesIvNext[AES_GCM_IV_SZ];
for (x = 0; x < blocks; x++)
{
memcpy(aesKeyNext, &outBufKDF[(x * 11)], AES_GCM_KEY_SZ);
if (aesKeyVec.size() < (options.bifOptions->GetEncryptionBlocksList().size() + 1))
{
aesKeyVec.push_back(ConvertKeyIvToString(aesKeyNext, AES_GCM_KEY_SZ).c_str());
}
if (GetAesKey() == NULL)
{
SetAesKey(aesKeyNext);
}
memcpy(aesIvNext, &outBufKDF[(x * 11) + WORDS_PER_AES_KEY], AES_GCM_IV_SZ);
if (aesIvVec.size() < (options.bifOptions->GetEncryptionBlocksList().size() + 1))
{
aesIvVec.push_back(ConvertKeyIvToString(aesIvNext, AES_GCM_IV_SZ).c_str());
}
if (GetIv() == NULL)
{
SetIv(aesIvNext);
}
}
}
/******************************************************************************/
void VersalEncryptionContext::ChunkifyAndEncrypt(Options& options, const uint8_t *inBuf, uint32_t inLen,
uint8_t *aad, uint32_t aad_len, uint8_t* outBuf, uint32_t& outLen)
{
std::vector<uint32_t> blockList = options.bifOptions->GetEncryptionBlocksList();
uint8_t *aesIv = new uint8_t[AES_GCM_IV_SZ];
uint8_t *aesKey = new uint8_t[AES_GCM_KEY_SZ];
uint8_t *aesIVNext = new uint8_t[AES_GCM_IV_SZ];
uint8_t *aesKeyNext = new uint8_t[AES_GCM_KEY_SZ];
GetEncryptionKeys(options, aesKey, NULL, aesIv);
GetNextKey(aesKeyNext, 1);
GetNextIv(aesIVNext, 1);
uint8_t secureHdr_in[AES_GCM_KEY_SZ + AES_GCM_IV_SZ + NUM_BYTES_PER_WORD];
/* Extract the first block size */
uint32_t nextBlkSize = (blockList.empty()) ? inLen : blockList[0];
nextBlkSize = (nextBlkSize > inLen) ? inLen : nextBlkSize + 0;
/* Copy Key,IV used for encrypting next block to Secure Header*/
memcpy(secureHdr_in, aesKeyNext, AES_GCM_KEY_SZ);
memcpy(secureHdr_in + AES_GCM_KEY_SZ, aesIVNext, AES_GCM_IV_SZ);
/* Copy the word Size of Block 0 to Secure Header*/
WriteLittleEndian32(secureHdr_in + AES_GCM_KEY_SZ + AES_GCM_IV_SZ, nextBlkSize / NUM_BYTES_PER_WORD);
int ct_len;
uint8_t gcm_tag[AES_GCM_TAG_SZ];
/* Encrypt the Secure Header with device key and starting IV */
LOG_TRACE("Encrypting the Secure Header");
uint8_t* ptr = outBuf;
AesGcm256Encrypt(secureHdr_in, SECURE_HDR_SZ, aesKey, aesIv, aad, aad_len, ptr, ct_len, gcm_tag);
/* Attach the AES-GCM generated Hash Tag to end of the block */
memcpy(outBuf + ct_len, gcm_tag, AES_GCM_TAG_SZ);
uint32_t outPtr = ct_len + AES_GCM_TAG_SZ;
uint8_t secureHdr_out[1024];
int pt_len;
uint32_t length = 0;
if (options.GetEncryptionDumpFlag())
{
uint32_t i = 0;
VERBOSE_OUT << std::endl << " Secure Header";
VERBOSE_OUT << std::endl << " AES Key : ";
for (i = 0; i<AES_GCM_KEY_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(aesKey[i]);
VERBOSE_OUT << std::endl << " AES IV : ";
for (i = 0; i<AES_GCM_IV_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(aesIv[i]);
VERBOSE_OUT << std::endl << " Length : ";
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << SECURE_HDR_SZ;
VERBOSE_OUT << std::endl << " Next Key, IV and length stored in Secure Header: ";
VERBOSE_OUT << std::endl << " Next Key : ";
for (i = 0; i<AES_GCM_KEY_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(secureHdr_in[i]);
VERBOSE_OUT << std::endl << " Next IV : ";
for (i = 0; i<AES_GCM_IV_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(secureHdr_in[i + AES_GCM_KEY_SZ]);
VERBOSE_OUT << std::endl << " Length : ";
length = ReadLittleEndian32(secureHdr_in + AES_GCM_KEY_SZ + AES_GCM_IV_SZ);
VERBOSE_OUT << std::hex << length * 4;
/*
VERBOSE_OUT << std::endl << " GCM Tag : ";
for (i = 0; i<AES_GCM_TAG_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(gcm_tag[i]);
VERBOSE_OUT << std::endl;
*/
//AES-GCM Decryption for verification purpose
AesGcm256Decrypt(secureHdr_out, pt_len, aesKey, aesIv, NULL, 0, outBuf, SECURE_HDR_SZ, gcm_tag);
int ret = memcmp(secureHdr_in, secureHdr_out, SECURE_HDR_SZ);
if (ret == 0)
{
//VERBOSE_OUT << " Encrypted secure header was successfully decrypted and tag matched\n";
}
else
{
//LOG_ERROR("Decrypted Secure Header tag mis-matched");
}
}
uint32_t bytesWritten = 0;
uint32_t inPtr = 0;
uint32_t blkPtr = 1;
/* Take the next generated Key and IV for encrypting next block */
memcpy(aesIv, aesIVNext, AES_GCM_IV_SZ);
memcpy(aesKey, aesKeyNext, AES_GCM_KEY_SZ);
while (bytesWritten < inLen)
{
//Update the block size for current block and extract the next block size
uint32_t currBlkSize = nextBlkSize;
bytesWritten += currBlkSize;
nextBlkSize = (blockList.size() > blkPtr) ? blockList[blkPtr] : inLen - bytesWritten;
nextBlkSize = ((nextBlkSize + bytesWritten) > inLen) ? (inLen - bytesWritten) : (nextBlkSize + 0);
/* Get next key and IV - store in current block - use for next block */
if (nextBlkSize == 0)
{
memset(aesKeyNext, 0, AES_GCM_KEY_SZ);
memset(aesIVNext, 0, AES_GCM_IV_SZ);
}
else
{
GetNextKey(aesKeyNext, blkPtr + 1);
GetNextIv(aesIVNext, blkPtr + 1);
}
uint8_t *gcm_pt = new uint8_t[currBlkSize + AES_GCM_KEY_SZ + AES_GCM_IV_SZ + NUM_BYTES_PER_WORD];
/* Prepare the buffer for encryption - Actual block data + Next Block Key + Next Block IV + Next Block Word Size */
memcpy(gcm_pt, inBuf + inPtr, currBlkSize);
inPtr += currBlkSize;
memcpy(gcm_pt + currBlkSize, aesKeyNext, AES_GCM_KEY_SZ);
memcpy(gcm_pt + currBlkSize + AES_GCM_KEY_SZ, aesIVNext, AES_GCM_IV_SZ);
WriteLittleEndian32(gcm_pt + currBlkSize + AES_GCM_KEY_SZ + AES_GCM_IV_SZ, nextBlkSize / NUM_BYTES_PER_WORD);
//Encrypt the consolidated block
LOG_TRACE("Encrypting the block %d of size 0x%x", blkPtr, currBlkSize);
AesGcm256Encrypt(gcm_pt, currBlkSize + SECURE_HDR_SZ, aesKey, aesIv, NULL, 0, outBuf + outPtr, ct_len, gcm_tag);
memcpy(outBuf + outPtr + ct_len, gcm_tag, AES_GCM_TAG_SZ);
uint8_t* inBuf_out = new uint8_t[ct_len + AES_GCM_TAG_SZ];
if (options.GetEncryptionDumpFlag())
{
uint32_t i = 0;
/*VERBOSE_OUT << std::endl << std::dec << "Unencrypted Bootimage Data - block-" << currBlk << " Length-" << (currBlkSize+SECURE_HDR_SZ) << std::endl;
int size = currBlkSize+SECURE_HDR_SZ;
for(i=0; i<(currBlkSize+SECURE_HDR_SZ); i++)
VERBOSE_OUT << "0x" << std::setfill('0') << std::setw(2) << std::hex << uint32_t(gcm_pt[i]) << " ";
VERBOSE_OUT << std::endl;
*/
VERBOSE_OUT << std::endl << " Block " << blkPtr - 1;
VERBOSE_OUT << std::endl << " AES Key : ";
for (i = 0; i<AES_GCM_KEY_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(aesKey[i]);
VERBOSE_OUT << std::endl << " AES IV : ";
for (i = 0; i<AES_GCM_IV_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(aesIv[i]);
VERBOSE_OUT << std::endl << " Length : ";
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << currBlkSize;
VERBOSE_OUT << std::endl << " Next Key, IV and length stored in Block " << blkPtr - 1;
VERBOSE_OUT << std::endl << " Next Key : ";
for (i = 0; i<AES_GCM_KEY_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(gcm_pt[i + currBlkSize]);
VERBOSE_OUT << std::endl << " Next IV : ";
for (i = 0; i<AES_GCM_IV_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(gcm_pt[i + currBlkSize + AES_GCM_KEY_SZ]);
VERBOSE_OUT << std::endl << " Length : ";
length = ReadLittleEndian32(gcm_pt + currBlkSize + AES_GCM_KEY_SZ + AES_GCM_IV_SZ);
VERBOSE_OUT << std::hex << length * 4;
/*
VERBOSE_OUT << std::endl << " GCM Tag : ";
for (i = 0; i<AES_GCM_TAG_SZ; i++)
VERBOSE_OUT << std::setfill('0') << std::setw(2) << std::hex << uint32_t(gcm_tag[i]);
VERBOSE_OUT << std::endl;
*/
AesGcm256Decrypt(inBuf_out, pt_len, aesKey, aesIv, NULL, 0, outBuf + outPtr, ct_len, gcm_tag);
int ret = memcmp(gcm_pt, inBuf_out, pt_len);
if (ret == 0)
{
//VERBOSE_OUT << std::dec << " Encrypted block " << currBlk++ << " was successfully decrypted and tag matched\n";
}
else
{
//LOG_ERROR("Decrypted block %d tag mis-matched", currBlk++);
}
}
//Update the current key & IV
outPtr += ct_len + AES_GCM_TAG_SZ;
memcpy(aesIv, aesIVNext, AES_GCM_IV_SZ);
memcpy(aesKey, aesKeyNext, AES_GCM_KEY_SZ);
delete[] gcm_pt;
delete[] inBuf_out;
blkPtr++;
}
outLen = outPtr;
delete[] aesIv;
delete[] aesKey;
delete[] aesIVNext;
delete[] aesKeyNext;
}
/******************************************************************************/
void VersalEncryptionContext::WarnforDPACMImpactonBootTime(bool dpacmKeyRollingEnable, bool dpacmMaskEnable)
{
static bool dpaKeyrollingWarningGiven = false;
static bool dpaMaskingWarningGiven = false;
if (!dpaKeyrollingWarningGiven)
{
if (dpacmKeyRollingEnable)
{
LOG_WARNING("DPA key rolling countermeasure is enabled.\n\t Boot time will be impacted, Refer to boot time estimator spreadsheet for calculations.");
dpaKeyrollingWarningGiven = true;
}
}
if (!dpaMaskingWarningGiven)
{
if (dpacmMaskEnable)
{
LOG_WARNING("DPA masking countermeasure enabled.\n\t Boot time will be impacted, Refer to boot time estimator spreadsheet for calculations.");
dpaMaskingWarningGiven = true;
}
}
}
/******************************************************************************/
void VersalEncryptionContext::Process(BootImage& bi, PartitionHeader* partHdr)
{
Options& options = bi.options;
LOG_INFO("Encrypting the partition - %s", partHdr->partition->section->Name.c_str());
std::vector<uint32_t> encrBlocks = partHdr->imageHeader->GetEncrBlocksList();
uint32_t defEncrBlocks = partHdr->imageHeader->GetDefaultEncrBlockSize();
Binary::Length_t lastBlock = 0;
uint32_t totalencrBlocks = 0;
WarnforDPACMImpactonBootTime(encrBlocks.size() != 0, partHdr->imageHeader->GetDpacm() == DpaCM::DpaCMEnable);
/* Default key rolling to make a chunk size of 32KB - Valid for any partition other than bootloader */
if (!partHdr->IsBootloader())
{
totalencrBlocks = encrBlocks.size();
defEncrBlocks = 0;
uint32_t overhead = (totalencrBlocks) * (SECURE_HDR_SZ + AES_GCM_TAG_SZ);
/* Due to encryption over head, the actual default size on which the partition needs to be Key rolled is always less than 64KB.
So first calculate the default key roll data size by substracting the overhead. */
/* Then calculate the number of such blocks possible on a given partition. */
/* Note that the last block will always be based on the partition length.*/
std::vector<uint32_t> secureChunkEncrBlocks;
uint32_t actualSecureChunkSize = bi.GetSecureChunkSize(partHdr->IsBootloader()) - overhead;
if (partHdr->imageHeader->GetAuthenticationType() == Authentication::None && !partHdr->imageHeader->GetDelayAuthFlag())
{
actualSecureChunkSize += SHA3_LENGTH_BYTES;
}
uint32_t totalKeyRollencrBlocks = GetTotalEncryptionBlocks(partHdr->partition->section->Length, secureChunkEncrBlocks, actualSecureChunkSize, &lastBlock);
secureChunkEncrBlocks.clear();
for (uint32_t itr = 0; itr < totalKeyRollencrBlocks; itr++)
{
if ((itr == totalKeyRollencrBlocks - 1) && (lastBlock != 0))
{
secureChunkEncrBlocks.push_back(lastBlock);
lastBlock = 0;
}
else
{
secureChunkEncrBlocks.push_back(actualSecureChunkSize);
}
}
/* Now chunk each default key roll data size, based on user encryption blocks.
Note that the last block will always be based on the partition length.*/
options.bifOptions->GetEncryptionBlocksList().clear();
for (uint32_t itr1 = 0; itr1 < totalKeyRollencrBlocks; itr1++)
{
if ((itr1 == totalKeyRollencrBlocks - 1) && (secureChunkEncrBlocks[itr1] != actualSecureChunkSize))
{
Binary::Length_t encrBlocksSize = 0;
for (uint32_t itr = 0; itr < encrBlocks.size(); itr++)
{
encrBlocksSize += encrBlocks[itr];
if (secureChunkEncrBlocks[itr1] > encrBlocksSize)
{
options.bifOptions->InsertEncryptionBlock(encrBlocks[itr]);
}
else
{
options.bifOptions->InsertEncryptionBlock(secureChunkEncrBlocks[itr1] - (encrBlocksSize - encrBlocks[itr]));
break;
}
}
}
else
{
for (uint32_t itr = 0; itr < encrBlocks.size(); itr++)
{
options.bifOptions->InsertEncryptionBlock(encrBlocks[itr]);
}
}
}
totalencrBlocks = options.bifOptions->GetEncryptionBlocksList().size();
}
else
{
totalencrBlocks = GetTotalEncryptionBlocks(partHdr->partition->section->Length, encrBlocks, defEncrBlocks, &lastBlock);
options.bifOptions->GetEncryptionBlocksList().clear();
for (uint32_t itr = 0; itr < totalencrBlocks; itr++)
{
if (itr < encrBlocks.size())
{
options.bifOptions->InsertEncryptionBlock(encrBlocks[itr]);
}
else if (defEncrBlocks != 0)
{
options.bifOptions->InsertEncryptionBlock(defEncrBlocks);
}
else if ((itr == totalencrBlocks - 1) && (lastBlock != 0))
{
options.bifOptions->InsertEncryptionBlock(lastBlock);
}
}
}
LOG_TRACE("Total no. of Key/IV pairs needed to encrypt - %d", totalencrBlocks + 1);
/* Get the key file */
SetAesFileName(partHdr->partitionAesKeyFile);
LOG_INFO("Key file - %s", aesFilename.c_str());
if (partHdr->generateAesKeyFile)
{
std::ifstream keyFile(aesFilename);
bool fileExists = keyFile.good();
if (!fileExists)
{
if (bi.aesKeyandKeySrc.size() != 0)
{
for (uint32_t i = 0; i < bi.aesKeyandKeySrc.size(); i++)
{
if (partHdr->imageHeader->GetEncryptionKeySrc() == bi.aesKeyandKeySrc[i].first)
{
aesKey = new uint32_t[AES_GCM_KEY_SZ / 4];
memcpy(aesKey, bi.aesKeyandKeySrc[i].second, AES_GCM_KEY_SZ);
break;
}
}
}
GenerateEncryptionKeyFile(aesFilename, options);
}
else
{
LOG_ERROR("Key Generation Error !!!\n File - %s already exists.", aesFilename.c_str());
}
}
bi.InsertEncryptionKeyFile(aesFilename);
CheckForSameAesKeyFiles(bi.GetEncryptionKeyFileVec());
ReadEncryptionKeyFile(aesFilename);
std::pair<KeySource::Type, uint32_t*> asesKeyandKeySrcPair (partHdr->imageHeader->GetEncryptionKeySrc(), aesKey);
bi.aesKeyandKeySrc.push_back(asesKeyandKeySrcPair);
bi.bifOptions->CheckForBadKeyandKeySrcPair(bi.aesKeyandKeySrc, aesFilename);
options.SetDevicePartName(deviceName);
CheckForExtraKeyIVPairs(totalencrBlocks, partHdr->partition->section->Name);
if (!aesSeedexits && aesKeyVec.size() != 1)
{
if (totalencrBlocks + 1 > aesKeyVec.size())
{
LOG_ERROR("AES Key file has less keys than the number of blocks to be encrypted in %s.", partHdr->partition->section->Name.c_str());
}
if (totalencrBlocks + 1 > aesIvVec.size())
{
LOG_ERROR("AES Key file has less IVs than the number of blocks to be encrypted in %s.", partHdr->partition->section->Name.c_str());
}
}
else
{
if (bi.aesKeyandKeySrc.size() != 0)
{
for (uint32_t i = 0; i < bi.aesKeyandKeySrc.size(); i++)
{
if (partHdr->imageHeader->GetEncryptionKeySrc() == bi.aesKeyandKeySrc[i].first)
{
if (aesKey == NULL)
{
aesKey = new uint32_t[AES_GCM_KEY_SZ / 4];
memcpy(aesKey, bi.aesKeyandKeySrc[i].second, AES_GCM_KEY_SZ);
}
if (aesKeyVec.size() == 0)
{
aesKeyVec.push_back(ConvertKeyIvToString((uint8_t *)aesKey, AES_GCM_KEY_SZ).c_str());
}
break;
}
}
}
GenerateRemainingKeys(options);
}
CheckForRepeatedKeyIVPairs(bi.GetEncryptionKeyFileVec(), false);
if (bi.aesKeyandKeySrc.size() != 0)
{
for (uint32_t i = 0; i < bi.aesKeyandKeySrc.size(); i++)
{
if (partHdr->imageHeader->GetEncryptionKeySrc() == bi.aesKeyandKeySrc[i].first)
{
if (aesKey != NULL)
{
memcpy(aesKey, bi.aesKeyandKeySrc[i].second, AES_GCM_KEY_SZ);
}
break;
}
}
}
// For copying SCR HDR IV into Boot Header
const uint32_t* tmpIv = GetIv();
if (tmpIv != NULL)