-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathencryption-zynqmp.cpp
executable file
·1301 lines (1154 loc) · 44.7 KB
/
encryption-zynqmp.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-zynqmp.h"
#include "bootimage.h"
#include "encryptutils.h"
#include "options.h"
#include "encryptutils.h"
#include "fileutils.h"
#include <openssl/rand.h>
#include "obfskutil.h"
/*
------------------------------------------------------------------------------------------------
********************************************************************** F U N C T I O N S ***
------------------------------------------------------------------------------------------------
*/
/******************************************************************************/
ZynqMpEncryptionContext::ZynqMpEncryptionContext()
: isBootloader(false)
, aesSeedexits(false)
, partNum(0)
{
encryptionAlgorithm = new AesGcmEncryptionContext();
};
/******************************************************************************/
ZynqMpEncryptionContext::ZynqMpEncryptionContext(const EncryptionContext* other)
: isBootloader(false)
, aesSeedexits(false)
, partNum(0)
{
aesFilename = other->aesFilename;
encryptionAlgorithm = new AesGcmEncryptionContext();
}
/******************************************************************************/
ZynqMpEncryptionContext::~ZynqMpEncryptionContext()
{
if (encryptionAlgorithm)
{
delete encryptionAlgorithm;
}
if (aesKey)
{
delete aesKey;
}
if (aesIv)
{
delete aesIv;
}
if (aesSeed)
{
delete aesSeed;
}
if (outBufKDF)
{
delete outBufKDF;
}
if (fixedInputData)
{
delete fixedInputData;
}
};
/******************************************************************************/
void ZynqMpEncryptionContext::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 ZynqMpEncryptionContext::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 ZynqMpEncryptionContext::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 ZynqMpEncryptionContext::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 ");
}
if (options.bifOptions->GetAesOptKeyFlag())
{
const uint32_t* tmpOptKey = GetAesOptKey();
if (tmpOptKey != NULL)
{
memcpy_be(aesOptKey, tmpOptKey, AES_GCM_KEY_SZ);
}
else
{
LOG_ERROR("Encryption Error !!!\n Operational Key 'Key Opt' 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 ZynqMpEncryptionContext::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 << " ";
if (x == 0 && GetIv() != NULL) {
for (y = 0; y < WORDS_PER_IV; ++y)
{
keyFile << std::uppercase << std::hex << std::setfill('0') << std::setw(8) << aesIv[y];
}
}
else {
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";
}
if (useOptionalKey == true)
{
keyFile << "Key Opt ";
if (GetAesOptKey() != NULL) {
for (y = 0; y < WORDS_PER_AES_KEY; ++y)
{
keyFile << std::uppercase << std::hex << std::setfill('0') << std::setw(8) << aesOptKey[y];
}
}
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";
}
}
/******************************************************************************/
void ZynqMpEncryptionContext::ReadEncryptionKeyFile(const std::string& inputFileName)
{
LOG_TRACE("Reading the AES key file");
int aesKeyNum = 0;
int aesIvNum = 0;
// Get the encryption key file name
std::ifstream keyFile(inputFileName.c_str());
aesKeyVec.clear();
aesIvVec.clear();
if (!keyFile)
{
LOG_ERROR("Failure reading AES key file - %s", inputFileName.c_str());
}
while (keyFile)
{
std::string word;
keyFile >> word;
// If file vacant
if (word == "")
{
return;
}
char c = ' ';
// First Word is "Key"
if (word == "Key")
{
keyFile >> word;
// Second Word is "Opt"
if (word == "Opt")
{
word = "";
while ((keyFile >> c) && isalnum(c))
{
word.push_back(c);
}
if (word == "pick")
{
GenerateAesOptKey();
}
else
{
SetAesOptKeyString(word);
}
}
// Second Word is "0"
else if (word != "" && isalnum(word[0]))
{
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);
}
// Third Word is "pick" - then generate AES key, otherwise set the key specified
if (word == "pick")
{
GenerateAesKey();
}
else
{
if (aesKeyVec.size() == 0)
{
SetAesKeyString(word);
}
aesKeyVec.push_back(word);
}
}
// Second Word other than "0", "StartCBC" or "HMAC" - throw error
else
{
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());
}
}
// If first word is not "Key" but "Device"
else if (word == "Device")
{
word = "";
keyFile >> word;
/*while( (keyFile >> c) && (isalnum(c) || c=='-' || c=='_') )
{
word.push_back(c);
}*/
c = word[word.size() - 1];
word.erase(word.size() - 1);
deviceName = word;
}
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 (word == "pick")
{
GenerateIv();
}
else
{
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;
}
// If first word is neither "Key" nor "Device"
else
{
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());
}
// Semicolons expected at end of every line
if (c != ';')
{
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 ZynqMpEncryptionContext::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 ZynqMpEncryptionContext::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 ZynqMpEncryptionContext::GetNextKey(uint8_t * keyNext, int ptr)
{
PackNextEncryptionKey(keyNext, ptr);
}
/******************************************************************************/
void ZynqMpEncryptionContext::GetNextIv(uint8_t * keyNext, int ptr)
{
PackNextIv(keyNext, ptr);
}
/******************************************************************************/
void ZynqMpEncryptionContext::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* ZynqMpEncryptionContext::GetAesSeed(void)
{
return (uint32_t *)aesSeed;
}
/******************************************************************************/
const uint32_t * ZynqMpEncryptionContext::GetAesKey(void)
{
return (uint32_t *)aesKey;
}
/******************************************************************************/
const uint32_t* ZynqMpEncryptionContext::GetAesOptKey(void)
{
return (uint32_t *)aesOptKey;
}
/******************************************************************************/
void ZynqMpEncryptionContext::SetAesOptKey(const uint8_t* key)
{
aesOptKey = new uint32_t[WORDS_PER_AES_KEY];
for (uint32_t index = 0; index < WORDS_PER_AES_KEY; index++)
{
aesOptKey[index] = ReadBigEndian32(key);
key += sizeof(uint32_t);
}
}
/******************************************************************************/
void ZynqMpEncryptionContext::SetAesOptKeyString(const std::string& key)
{
uint8_t hexData[256];
if (key.size() != (WORDS_PER_AES_KEY * 8))
{
LOG_DEBUG(DEBUG_STAMP, "AES key size - %d", key.size());
LOG_ERROR("An AES key must be 256 bits long - %s", key.c_str());
}
PackHex(key, hexData);
SetAesOptKey(hexData);
}
/******************************************************************************/
void ZynqMpEncryptionContext::GenerateAesOptKey(void)
{
uint32_t keysize = WORDS_PER_AES_KEY * sizeof(uint32_t);
uint8_t newKeyData[BYTES_PER_AES_KEY];
// Get temp data to encrypt as the newKey.
RAND_bytes(newKeyData, keysize);
// Set the new key.
SetAesOptKey(newKeyData);
// For logging purpose
LOG_INFO("AES Key generated successfully");
}
/******************************************************************************/
void ZynqMpEncryptionContext::SetIv(const uint8_t* iv)
{
aesIv = new uint32_t[WORDS_PER_IV];
// Copy the key
for (uint32_t index = 0; index < WORDS_PER_IV; index++)
{
aesIv[index] = ReadBigEndian32(iv);
iv += sizeof(uint32_t);
}
}
/******************************************************************************/
void ZynqMpEncryptionContext::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 ZynqMpEncryptionContext::GenerateIv(void)
{
// Get temp data to encrypt as the newCBC.
uint8_t newIVData[BYTES_PER_IV];
RAND_bytes(newIVData, BYTES_PER_IV);
SetIv(newIVData);
// For logging purpose
LOG_INFO("AES IV generated successfully");
}
/******************************************************************************/
const uint32_t* ZynqMpEncryptionContext::GetIv(void)
{
return (uint32_t *)aesIv;
}
/******************************************************************************/
void ZynqMpEncryptionContext::GenerateRemainingKeys(Options& options, std::string aesFilename)
{
uint32_t blocks, x;
bool useOptionalKey = false;
if (GetAesOptKey() == NULL)
{
useOptionalKey = options.bifOptions->GetAesOptKeyFlag();
}
if (GetAesKey() == NULL && !aesSeedexits)
{
LOG_ERROR("Encryption Error !!!\n Key 0 does not exist in the AES key file ");
}
if (options.bifOptions->GetAesOptKeyFlag())
{
if (GetAesOptKey() == NULL && !aesSeedexits)
{
LOG_ERROR("Encryption Error !!!\n Operational Key 'Key Opt' does not exist in the AES key file ");
}
}
if (GetIv() == NULL && !aesSeedexits)
{
LOG_ERROR("IV 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 (GetAesKey() == NULL && aesSeedexits)
{
blocks = options.bifOptions->GetEncryptionBlocksList().size() + 1 + useOptionalKey;
LOG_TRACE("Keys for encryption will be generated based on the seed");
}
else
{
blocks = options.bifOptions->GetEncryptionBlocksList().size() + useOptionalKey;
if (aesSeedexits)
{
LOG_TRACE("Keys for encryption will be generated based on the seed");
}
else
{
LOG_TRACE("Keys for encryption will be generated based on Key 0");
}
}
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);
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);
aesIvVec.push_back(ConvertKeyIvToString(aesIvNext, AES_GCM_IV_SZ).c_str());
if (GetIv() == NULL)
{
SetIv(aesIvNext);
}
}
if (useOptionalKey == true)
{
if (GetAesOptKey() == NULL)
{
SetAesOptKey(aesKeyNext);
}
}
}
/******************************************************************************/
void ZynqMpEncryptionContext::ChunkifyAndEncrypt(Options& options, const uint8_t *inBuf, uint32_t inLen, 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 *aesOptKey = 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, aesOptKey, aesIv);
GetNextKey(aesKeyNext, 1);
GetNextIv(aesIVNext, 1);
if (partNum > 0) {
uint8_t *x = new uint8_t[AES_GCM_IV_SZ];
memset(x, 0, AES_GCM_IV_SZ);
*(x + AES_GCM_IV_SZ - 1) = partNum;
*(aesIv + AES_GCM_IV_SZ - 1) = *(aesIv + AES_GCM_IV_SZ - 1) + *(x + AES_GCM_IV_SZ - 1);
delete[] x;
}
// Extract the first block size
uint32_t nextBlkSize = (blockList.empty()) ? inLen : blockList[0];
nextBlkSize = (nextBlkSize > inLen) ? inLen : nextBlkSize + 0;
uint8_t secureHdr_in[AES_GCM_KEY_SZ + AES_GCM_IV_SZ + NUM_BYTES_PER_WORD];
uint32_t charZero = 0;
if (options.bifOptions->GetAesOptKeyFlag())
{
//Write the optional key from .nky file
memcpy(secureHdr_in, aesOptKey, AES_GCM_KEY_SZ);
if (isBootloader == false)
{
/* If optional key is enabled, then aesKey (boot key) needs to be used only encrypt the secure header
Next block is encrypted using Opt Key.
For all partitions, other than bootloader, don't use aesKey (bootkey), always use optional key
Reason: The main idea to use optional key is to minimize the time of bootkey usage during booting process */
memcpy(aesKey, aesOptKey, AES_GCM_KEY_SZ);
memset(secureHdr_in, 0, AES_GCM_KEY_SZ);
memcpy(secureHdr_in, aesKeyNext, AES_GCM_KEY_SZ);
}
}
else
{
/*Security Vulnerability : Reusing same AES / IV Key Pair*/
//Write Dummy key
memset(secureHdr_in, charZero, AES_GCM_KEY_SZ);
//Write Next key
if (isBootloader == false)
{
memcpy(secureHdr_in, aesKeyNext, AES_GCM_KEY_SZ);
}
}
// Block 0 IV(random generated), and the Block0 word size
memcpy(secureHdr_in + AES_GCM_KEY_SZ, aesIVNext, AES_GCM_IV_SZ);
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;
encryptionAlgorithm->AesGcm256Encrypt(secureHdr_in, SECURE_HDR_SZ, aesKey, aesIv, NULL, 0, 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
encryptionAlgorithm->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";
}
}
uint32_t bytesWritten = 0;
uint32_t inPtr = 0;
uint32_t blkPtr = 1;
//Take the next random generated IV for encryption
/* Secure Header and Block 0 will be using the same IV, to have equal number of Keys
and IVs from Key File. */
/*Security Vulnerability : Reusing same AES / IV Key Pair*/
memcpy(aesIv, aesIVNext, AES_GCM_IV_SZ);
if (options.bifOptions->GetAesOptKeyFlag())
{
if (isBootloader == false)
{
memcpy(aesKey, aesKeyNext, AES_GCM_KEY_SZ);
}
else
{
memcpy(aesKey, aesOptKey, AES_GCM_KEY_SZ);
}
}
else
{
if (isBootloader == false)
{
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(random for next key from keyfile) 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 of partition number %d", blkPtr, currBlkSize, partNum);
encryptionAlgorithm->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;
*/
encryptionAlgorithm->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
{
//VERBOSE_OUT << std::dec << " Encrypted block " << currBlk++ << " was failed in decryption and tag matching\n";
}
}
//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;