File: CryptPkcs7VerifyCommon.c

package info (click to toggle)
edk2 2025.11-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 338,436 kB
  • sloc: ansic: 2,166,377; asm: 270,725; perl: 235,301; python: 149,900; sh: 34,744; cpp: 23,311; makefile: 3,334; pascal: 1,602; xml: 806; lisp: 35; ruby: 16; sed: 6; tcl: 4
file content (1354 lines) | stat: -rw-r--r-- 37,049 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
/** @file
  PKCS#7 SignedData Sign Wrapper and PKCS#7 SignedData Verification Wrapper
  Implementation over mbedtls.

  RFC 8422 - Elliptic Curve Cryptography (ECC) Cipher Suites
  FIPS 186-4 - Digital Signature Standard (DSS)

Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent

**/

#include "CryptPkcs7Internal.h"
#include <mbedtls/pkcs7.h>

/* Profile for backward compatibility. Allows RSA 1024, unlike the default
   profile. */
STATIC mbedtls_x509_crt_profile  gCompatProfile =
{
  /* Hashes from SHA-256 and above. Note that this selection
   * should be aligned with ssl_preset_default_hashes in ssl_tls.c. */

 #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES
  MBEDTLS_X509_ID_FLAG (MBEDTLS_MD_SHA1) |
 #endif
  MBEDTLS_X509_ID_FLAG (MBEDTLS_MD_SHA256) |
  MBEDTLS_X509_ID_FLAG (MBEDTLS_MD_SHA384) |
  MBEDTLS_X509_ID_FLAG (MBEDTLS_MD_SHA512),
  0xFFFFFFF,       /* Any PK alg    */

  /* Curves at or above 128-bit security level. Note that this selection
   * should be aligned with ssl_preset_default_curves in ssl_tls.c. */
  MBEDTLS_X509_ID_FLAG (MBEDTLS_ECP_DP_SECP256R1) |
  MBEDTLS_X509_ID_FLAG (MBEDTLS_ECP_DP_SECP384R1) |
  MBEDTLS_X509_ID_FLAG (MBEDTLS_ECP_DP_SECP521R1) |
  MBEDTLS_X509_ID_FLAG (MBEDTLS_ECP_DP_BP256R1) |
  MBEDTLS_X509_ID_FLAG (MBEDTLS_ECP_DP_BP384R1) |
  MBEDTLS_X509_ID_FLAG (MBEDTLS_ECP_DP_BP512R1) |
  0,
  1024,
};

/**
 Init MbedtlsPkcs7.

  @param[in]  Pkcs7     MbedtlsPkcs7.
**/
STATIC
VOID
MbedTlsPkcs7Init (
  MbedtlsPkcs7  *Pkcs7
  )
{
  ZeroMem (Pkcs7, sizeof (MbedtlsPkcs7));
}

/**
  Get Pkcs7 Next Content Len.

  @param[in]  Ptr          The start of the buffer.
  @param[in]  End          The end of the buffer.
  @param[out] Len          MbedtlsPkcs7 Content Len.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7GetNextContentLen (
  UINT8  **Ptr,
  UINT8  *End,
  UINTN  *Len
  )
{
  INT32  Ret;

  Ret = mbedtls_asn1_get_tag (Ptr, End, Len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC);
  return Ret;
}

/**
  Get Pkcs7 Version..

  @param[in]  Ptr          The start of the buffer.
  @param[in]  End          The end of the buffer.
  @param[out] Ver          MbedtlsPkcs7 Version.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7GetVersion (
  UINT8  **Ptr,
  UINT8  *End,
  INT32  *Ver
  )
{
  INT32  Ret;

  Ret = mbedtls_asn1_get_int (Ptr, End, Ver);
  return Ret;
}

/**
   ContentInfo ::= SEQUENCE {
        contentType ContentType,
        content
                [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }.

  @param[in]  Ptr            The start of the buffer.
  @param[in]  End          The end of the buffer.
  @param[out] Pkcs7        MbedtlsPkcs7.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
Pkcs7GetContentInfoType (
  UINT8             **Ptr,
  UINT8             *End,
  mbedtls_asn1_buf  *Pkcs7
  )
{
  UINTN  Len;
  int    Ret;

  Len = 0;
  Ret = mbedtls_asn1_get_tag (
          Ptr,
          End,
          &Len,
          MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE
          );

  if (Ret == 0) {
    Ret = mbedtls_asn1_get_tag (Ptr, End, &Len, MBEDTLS_ASN1_OID);
  }

  if (Ret == 0) {
    Pkcs7->tag = MBEDTLS_ASN1_OID;
    Pkcs7->len = Len;
    Pkcs7->p   = *Ptr;
  }

  return Ret;
}

/**
  DigestAlgorithmIdentifier ::= AlgorithmIdentifier.

  @param[in]  Ptr            The start of the buffer.
  @param[in]  End          The end of the buffer.
  @param[out] Alg          MbedtlsPkcs7 AlgorithmIdentifier.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7GetDigestAlgorithm (
  UINT8             **Ptr,
  UINT8             *End,
  mbedtls_x509_buf  *Alg
  )
{
  INT32  Ret;

  Ret = mbedtls_asn1_get_alg_null (Ptr, End, Alg);
  return Ret;
}

/**
  DigestAlgorithmIdentifiers :: SET of DigestAlgorithmIdentifier.

  @param[in]  Ptr            The start of the buffer.
  @param[in]  End          The end of the buffer.
  @param[out] Alg          MbedtlsPkcs7 AlgorithmIdentifier.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7GetDigestAlgorithmSet (
  UINT8             **Ptr,
  UINT8             *End,
  mbedtls_x509_buf  *Alg
  )
{
  UINTN  Len;
  INT32  Ret;

  Len = 0;
  Ret = mbedtls_asn1_get_tag (
          Ptr,
          End,
          &Len,
          MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET
          );

  if (Ret == 0) {
    End = *Ptr + Len;
    // assume only one digest algorithm
    Ret = mbedtls_asn1_get_alg_null (Ptr, End, Alg);
  }

  return Ret;
}

/**
   certificates :: SET OF ExtendedCertificateOrCertificate,
   ExtendedCertificateOrCertificate ::= CHOICE {
        certificate Certificate -- x509,
        extendedCertificate[0] IMPLICIT ExtendedCertificate }.

  @param[in]  Ptr            The start of the buffer.
  @param[in]  Plen         The buffer len.
  @param[out] Certs        mbedtls_x509_crt cert.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7GetCertificates (
  UINT8             **Ptr,
  INTN              Plen,
  mbedtls_x509_crt  *Certs
  )
{
  INT32  Ret;

  Ret = mbedtls_x509_crt_parse (Certs, *Ptr, Plen);
  return Ret;
}

/**
   EncryptedDigest ::= OCTET STRING.

  @param[in]  Ptr            The start of the buffer.
  @param[in]  End          The end of the buffer.
  @param[out] Signature    Signature.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
Pkcs7GetSignature (
  UINT8             **Ptr,
  UINT8             *End,
  mbedtls_asn1_buf  *Signature
  )
{
  INT32  Ret;
  UINTN  Len;

  Len = 0;
  Ret = mbedtls_asn1_get_tag (Ptr, End, &Len, MBEDTLS_ASN1_OCTET_STRING);
  if (Ret == 0) {
    Signature->tag = MBEDTLS_ASN1_OCTET_STRING;
    Signature->len = Len;
    Signature->p   = *Ptr;
  }

  return Ret;
}

/**
   SignerInfo ::= SEQUENCE {
        version Version;
        issuerAndSerialNumber   IssuerAndSerialNumber,
        digestAlgorithm DigestAlgorithmIdentifier,
        authenticatedAttributes
                [0] IMPLICIT Attributes OPTIONAL,
        digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
        encryptedDigest EncryptedDigest,
        unauthenticatedAttributes
                [1] IMPLICIT Attributes OPTIONAL.

  @param[in]  Ptr            The start of the buffer.
  @param[in]  End          The end of the buffer.
  @param[out] SignersSet   MbedtlsPkcs7SignerInfo.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedTlsPkcs7GetSignersInfoSet (
  UINT8                   **Ptr,
  UINT8                   *End,
  MbedtlsPkcs7SignerInfo  *SignersSet
  )
{
  UINT8  *EndSet;
  INT32  Ret;
  UINTN  Len;
  UINT8  *TempP;

  Len = 0;

  Ret = mbedtls_asn1_get_tag (
          Ptr,
          End,
          &Len,
          MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET
          );

  if (Ret == 0) {
    EndSet = *Ptr + Len;

    Ret = mbedtls_asn1_get_tag (
            Ptr,
            EndSet,
            &Len,
            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE
            );
  }

  if (Ret == 0) {
    Ret = mbedtls_asn1_get_int (Ptr, EndSet, &SignersSet->Version);
  }

  if (Ret == 0) {
    Ret = mbedtls_asn1_get_tag (
            Ptr,
            EndSet,
            &Len,
            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE
            );
  }

  if (Ret == 0) {
    SignersSet->IssuerRaw.p = *Ptr;
    Ret                     = mbedtls_asn1_get_tag (
                                Ptr,
                                EndSet,
                                &Len,
                                MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE
                                );
  }

  if (Ret == 0) {
    Ret = mbedtls_x509_get_name (Ptr, *Ptr + Len, &SignersSet->Issuer);
  }

  if (Ret == 0) {
    SignersSet->IssuerRaw.len = *Ptr - SignersSet->IssuerRaw.p;

    Ret = mbedtls_x509_get_serial (Ptr, EndSet, &SignersSet->Serial);
  }

  if (Ret == 0) {
    Ret = MbedTlsPkcs7GetDigestAlgorithm (Ptr, EndSet, &SignersSet->AlgIdentifier);
  }

  // OPTIONAL AuthenticatedAttributes
  if (Ret == 0) {
    TempP = *Ptr;
    if (mbedtls_asn1_get_tag (&TempP, EndSet, &Len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC) == 0) {
      SignersSet->AuthAttr.len = Len + (TempP - *Ptr);
      SignersSet->AuthAttr.p   = *Ptr;
      *Ptr                     = TempP + Len;
    } else {
      SignersSet->AuthAttr.p = NULL;
    }
  }

  if (Ret == 0) {
    Ret = MbedTlsPkcs7GetDigestAlgorithm (Ptr, EndSet, &SignersSet->SigAlgIdentifier);
  }

  if (Ret == 0) {
    Ret = Pkcs7GetSignature (Ptr, End, &SignersSet->Sig);
  }

  if (Ret == 0) {
    SignersSet->Next = NULL;
  }

  return Ret;
}

/**
   SignedData ::= SEQUENCE {
        version Version,
        digestAlgorithms DigestAlgorithmIdentifiers,
        contentInfo ContentInfo,
        certificates
                [0] IMPLICIT ExtendedCertificatesAndCertificates
                    OPTIONAL,
        crls
                [0] IMPLICIT CertificateRevocationLists OPTIONAL,
        signerInfos SignerInfos }.

  @param[in]  Buffer       The start of the buffer.
  @param[in]  BufferLen    The len the buffer.
  @param[out] SignedData   MbedtlsPkcs7SignedData.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
Pkcs7GetSignedData (
  UINT8                   *Buffer,
  INTN                    BufferLen,
  MbedtlsPkcs7SignedData  *SignedData
  )
{
  UINT8             *Ptr;
  UINT8             *End;
  UINTN             Len;
  INT32             Ret;
  UINT8             *CertP;
  UINTN             CertLen;
  UINT8             *OldCertP;
  UINTN             TotalCertLen;
  mbedtls_x509_crt  *MoreCert;
  UINT8             CertNum;
  mbedtls_x509_crt  *LastCert;
  mbedtls_x509_crt  *TempCrt;

  Len      = 0;
  Ptr      = Buffer;
  End      = Buffer + BufferLen;
  MoreCert = NULL;

  Ret = mbedtls_asn1_get_tag (
          &Ptr,
          End,
          &Len,
          MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE
          );

  if (Ret == 0) {
    // version
    Ret = MbedTlsPkcs7GetVersion (&Ptr, End, &SignedData->Version);
  }

  if ((Ret == 0) && (SignedData->Version != 1)) {
    Ret = -1;
  }

  if (Ret == 0) {
    // digest algorithm
    Ret = MbedTlsPkcs7GetDigestAlgorithmSet (
            &Ptr,
            End,
            &SignedData->DigestAlgorithms
            );
  }

  if (Ret == 0) {
    if (
 #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES
        ((SignedData->DigestAlgorithms.len == sizeof (MBEDTLS_OID_DIGEST_ALG_SHA1) - 1) &&
         (CompareMem (
            SignedData->DigestAlgorithms.p,
            MBEDTLS_OID_DIGEST_ALG_SHA1,
            SignedData->DigestAlgorithms.len
            ) == 0)) ||
 #endif
        ((SignedData->DigestAlgorithms.len == sizeof (MBEDTLS_OID_DIGEST_ALG_SHA256) - 1) &&
         (CompareMem (
            SignedData->DigestAlgorithms.p,
            MBEDTLS_OID_DIGEST_ALG_SHA256,
            SignedData->DigestAlgorithms.len
            ) == 0)) ||
        ((SignedData->DigestAlgorithms.len == sizeof (MBEDTLS_OID_DIGEST_ALG_SHA384) - 1) &&
         (CompareMem (
            SignedData->DigestAlgorithms.p,
            MBEDTLS_OID_DIGEST_ALG_SHA384,
            SignedData->DigestAlgorithms.len
            ) == 0)) ||
        ((SignedData->DigestAlgorithms.len == sizeof (MBEDTLS_OID_DIGEST_ALG_SHA512) - 1) &&
         (CompareMem (
            SignedData->DigestAlgorithms.p,
            MBEDTLS_OID_DIGEST_ALG_SHA512,
            SignedData->DigestAlgorithms.len
            ) == 0)))
    {
      Ret = 0;
    } else {
      Ret = -1;
    }
  }

  if (Ret == 0) {
    Ret = Pkcs7GetContentInfoType (&Ptr, End, &SignedData->ContentInfo.Oid);
  }

  if (Ret == 0) {
    // move to next
    Ptr   = Ptr + SignedData->ContentInfo.Oid.len;
    Ret   = MbedTlsPkcs7GetNextContentLen (&Ptr, End, &Len);
    CertP = Ptr + Len;

    // move to actual cert, if there are more [0]
    if (MbedTlsPkcs7GetNextContentLen (&CertP, End, &CertLen) == 0) {
      Len = CertLen;
      Ptr = CertP;
    }
  }

  // certificates: may have many certs
  CertP = Ptr;

  TotalCertLen = 0;

  MoreCert = &SignedData->Certificates;
  CertNum  = 0;

  while (TotalCertLen < Len) {
    OldCertP = CertP;

    Ret = mbedtls_asn1_get_tag (&CertP, End, &CertLen, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
    if (Ret != 0) {
      goto Out;
    }

    // cert total len
    CertLen = CertLen + (CertP - OldCertP);

    // move to next cert
    CertP = OldCertP + CertLen;

    // change TotalCertLen
    TotalCertLen += CertLen;

    mbedtls_x509_crt_init (MoreCert);
    Ret = MbedTlsPkcs7GetCertificates (&OldCertP, CertLen, MoreCert);
    if (Ret != 0) {
      goto Out;
    }

    CertNum++;
    MoreCert->next = mbedtls_calloc (1, sizeof (mbedtls_x509_crt));
    MoreCert       = MoreCert->next;
  }

  if (TotalCertLen != Len) {
    Ret = -1;
    goto Out;
  }

  LastCert = &(SignedData->Certificates);

  while (CertNum--) {
    if (CertNum == 0) {
      LastCert->next = NULL;
      break;
    } else {
      LastCert = LastCert->next;
    }
  }

  // signers info
  if (Ret == 0) {
    Ptr = Ptr + Len;
    Ret = MbedTlsPkcs7GetSignersInfoSet (&Ptr, End, &SignedData->SignerInfos);
  }

Out:
  if (Ret == 0) {
    if (MoreCert != NULL) {
      mbedtls_x509_crt_free (MoreCert);
      MoreCert = NULL;
    }
  } else {
    if (SignedData->Certificates.next != NULL) {
      TempCrt = SignedData->Certificates.next;
      mbedtls_x509_crt_free (TempCrt);
    }
  }

  return Ret;
}

/**
  Parse MbedtlsPkcs7 to Der format.
  @param[in]  Buffer       The start of the buffer.
  @param[in]  BufferLen    The len the buffer.
  @param[out] Pkcs7        MbedtlsPkcs7.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedtlsPkcs7ParseDer (
  CONST UINT8   *Buffer,
  INTN          BufferLen,
  MbedtlsPkcs7  *Pkcs7
  )
{
  UINT8  *Ptr;
  UINT8  *End;
  UINTN  Len;
  INT32  Ret;

  if (Pkcs7 == NULL) {
    return -1;
  }

  Len = 0;
  Ptr = (UINT8 *)Buffer;
  End = Ptr + BufferLen;

  Ret = Pkcs7GetContentInfoType (&Ptr, End, &Pkcs7->ContentTypeOid);
  if (Ret != 0) {
    goto Out;
  }

  if ((CompareMem (Pkcs7->ContentTypeOid.p, MBEDTLS_OID_PKCS7_DATA, Pkcs7->ContentTypeOid.len) == 0) ||
      (CompareMem (Pkcs7->ContentTypeOid.p, MBEDTLS_OID_PKCS7_ENCRYPTED_DATA, Pkcs7->ContentTypeOid.len) == 0) ||
      (CompareMem (Pkcs7->ContentTypeOid.p, MBEDTLS_OID_PKCS7_ENVELOPED_DATA, Pkcs7->ContentTypeOid.len) == 0) ||
      (CompareMem (Pkcs7->ContentTypeOid.p, MBEDTLS_OID_PKCS7_SIGNED_AND_ENVELOPED_DATA, Pkcs7->ContentTypeOid.len) == 0) ||
      (CompareMem (Pkcs7->ContentTypeOid.p, MBEDTLS_OID_PKCS7_DIGESTED_DATA, Pkcs7->ContentTypeOid.len) == 0))
  {
    // Invalid PKCS7 data type;
    Ret = -1;
    goto Out;
  }

  if (CompareMem (Pkcs7->ContentTypeOid.p, MBEDTLS_OID_PKCS7_SIGNED_DATA, Pkcs7->ContentTypeOid.len) != 0) {
    // Invalid PKCS7 data type;
    Ret = -1;
    goto Out;
  }

  // Content type is SignedData
  Ptr = Ptr + Pkcs7->ContentTypeOid.len;

  Ret = MbedTlsPkcs7GetNextContentLen (&Ptr, End, &Len);
  if (Ret != 0) {
    goto Out;
  }

  Ret = Pkcs7GetSignedData (Ptr, Len, &Pkcs7->SignedData);
  if (Ret != 0) {
    goto Out;
  }

Out:
  return Ret;
}

/**
  MbedtlsPkcs7 verify MbedtlsPkcs7SignerInfo.
  @param[in]  SignerInfo   MbedtlsPkcs7 SignerInfo.
  @param[in]  Cert         cert.
  @param[in]  Data         Pointer for data.
  @param[in]  DataLen      The len the buffer.

  @retval 0                Success.
  @retval negative         A negative MBEDTLS_ERR_ASN1_XXX error code on failure.
**/
STATIC
INT32
MbedtlsPkcs7SignedDataVerifySigners (
  MbedtlsPkcs7SignerInfo  *SignerInfo,
  mbedtls_x509_crt        *Cert,
  CONST UINT8             *Data,
  INTN                    DataLen
  )
{
  INT32                    Ret;
  UINT8                    Hash[MBEDTLS_MD_MAX_SIZE];
  mbedtls_pk_context       Pk;
  CONST mbedtls_md_info_t  *MdInfo;
  INTN                     HashLen;
  UINT8                    TempAuthAttr;

  Pk = Cert->pk;
  ZeroMem (Hash, MBEDTLS_MD_MAX_SIZE);

  // all the hash algo
 #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES
  MdInfo  = mbedtls_md_info_from_type (MBEDTLS_MD_SHA1);
  HashLen = mbedtls_md_get_size (MdInfo);
  mbedtls_md (MdInfo, Data, DataLen, Hash);
  if (SignerInfo->AuthAttr.p != NULL) {
    TempAuthAttr              = *(SignerInfo->AuthAttr.p);
    *(SignerInfo->AuthAttr.p) = MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET;
    mbedtls_md (MdInfo, SignerInfo->AuthAttr.p, SignerInfo->AuthAttr.len, Hash);
    // Restore content
    *(SignerInfo->AuthAttr.p) = TempAuthAttr;
  }

  Ret = mbedtls_pk_verify (&Pk, MBEDTLS_MD_SHA1, Hash, HashLen, SignerInfo->Sig.p, SignerInfo->Sig.len);

  if (Ret == 0) {
    return Ret;
  }

 #endif

  MdInfo  = mbedtls_md_info_from_type (MBEDTLS_MD_SHA256);
  HashLen = mbedtls_md_get_size (MdInfo);
  ZeroMem (Hash, MBEDTLS_MD_MAX_SIZE);
  mbedtls_md (MdInfo, Data, DataLen, Hash);
  if (SignerInfo->AuthAttr.p != NULL) {
    TempAuthAttr              = *(SignerInfo->AuthAttr.p);
    *(SignerInfo->AuthAttr.p) = MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET;
    mbedtls_md (MdInfo, SignerInfo->AuthAttr.p, SignerInfo->AuthAttr.len, Hash);
    // Restore content
    *(SignerInfo->AuthAttr.p) = TempAuthAttr;
  }

  Ret = mbedtls_pk_verify (&Pk, MBEDTLS_MD_SHA256, Hash, HashLen, SignerInfo->Sig.p, SignerInfo->Sig.len);
  if (Ret == 0) {
    return Ret;
  }

  MdInfo  = mbedtls_md_info_from_type (MBEDTLS_MD_SHA384);
  HashLen = mbedtls_md_get_size (MdInfo);
  ZeroMem (Hash, MBEDTLS_MD_MAX_SIZE);
  mbedtls_md (MdInfo, Data, DataLen, Hash);
  if (SignerInfo->AuthAttr.p != NULL) {
    TempAuthAttr              = *(SignerInfo->AuthAttr.p);
    *(SignerInfo->AuthAttr.p) = MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET;
    mbedtls_md (MdInfo, SignerInfo->AuthAttr.p, SignerInfo->AuthAttr.len, Hash);
    // Restore content
    *(SignerInfo->AuthAttr.p) = TempAuthAttr;
  }

  Ret = mbedtls_pk_verify (&Pk, MBEDTLS_MD_SHA384, Hash, HashLen, SignerInfo->Sig.p, SignerInfo->Sig.len);
  if (Ret == 0) {
    return Ret;
  }

  MdInfo  = mbedtls_md_info_from_type (MBEDTLS_MD_SHA512);
  HashLen = mbedtls_md_get_size (MdInfo);
  ZeroMem (Hash, MBEDTLS_MD_MAX_SIZE);
  mbedtls_md (MdInfo, Data, DataLen, Hash);
  if (SignerInfo->AuthAttr.p != NULL) {
    TempAuthAttr              = *(SignerInfo->AuthAttr.p);
    *(SignerInfo->AuthAttr.p) = MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET;
    mbedtls_md (MdInfo, SignerInfo->AuthAttr.p, SignerInfo->AuthAttr.len, Hash);
    // Restore content
    *(SignerInfo->AuthAttr.p) = TempAuthAttr;
  }

  Ret = mbedtls_pk_verify (&Pk, MBEDTLS_MD_SHA512, Hash, HashLen, SignerInfo->Sig.p, SignerInfo->Sig.len);
  if (Ret == 0) {
    return Ret;
  }

  return Ret;
}

/**
  Find signer cert in MbedtlsPkcs7SignerInfo.

  @param[in]  SignerInfo   MbedtlsPkcs7 SignerInfo.
  @param[in]  Certs        MbedtlsPkcs7 SignerInfo certs.

  @retval cert             Signer Cert.
**/
STATIC
mbedtls_x509_crt *
MbedTlsPkcs7FindSignerCert (
  MbedtlsPkcs7SignerInfo  *SignerInfo,
  mbedtls_x509_crt        *Certs
  )
{
  mbedtls_x509_crt  *Cert;

  Cert = Certs;
  while (Cert != NULL) {
    if ((Cert->serial.p == NULL) || (Cert->issuer_raw.p == NULL)) {
      return NULL;
    }

    if ((Cert->issuer_raw.len == SignerInfo->IssuerRaw.len) &&
        (CompareMem (Cert->issuer_raw.p, SignerInfo->IssuerRaw.p, Cert->issuer_raw.len) == 0) &&
        (Cert->serial.len == SignerInfo->Serial.len) &&
        (CompareMem (Cert->serial.p, SignerInfo->Serial.p, Cert->serial.len) == 0))
    {
      break;
    }

    Cert = Cert->next;
  }

  return Cert;
}

/**
  verify cert.

  @param[in]  Ca    CA cert.
  @param[in]  CaCrl CRL.
  @param[in]  End   Cert which need be verified.

  @retval TRUE      Verify successfully.
  @retval FALSE     Verify failed.
**/
STATIC
BOOLEAN
MbedTlsPkcs7VerifyCert (
  mbedtls_x509_crt  *Ca,
  mbedtls_x509_crl  *CaCrl,
  mbedtls_x509_crt  *End
  )
{
  INT32                     Ret;
  UINT32                    VFlag;
  mbedtls_x509_crt_profile  Profile;

  VFlag = 0;
  CopyMem (&Profile, &gCompatProfile, sizeof (mbedtls_x509_crt_profile));

  Ret = mbedtls_x509_crt_verify_with_profile (End, Ca, CaCrl, &Profile, NULL, &VFlag, NULL, NULL);

  return Ret == 0;
}

/**
  verify cert chain.

  @param[in]  Pkcs7 MbedtlsPkcs7.
  @param[in]  Ca    CA cert.
  @param[in]  End   Cert which need be verified.

  @retval TRUE      Verify successfully.
  @retval FALSE     Verify failed.
**/
STATIC
BOOLEAN
MbedTlsPkcs7VerifyCertChain (
  MbedtlsPkcs7      *Pkcs7,
  mbedtls_x509_crt  *Ca,
  mbedtls_x509_crt  *End
  )
{
  mbedtls_x509_crt  *AllCert;
  mbedtls_x509_crt  *InterCert;

  AllCert   = &(Pkcs7->SignedData.Certificates);
  InterCert = NULL;

  while (AllCert != NULL) {
    if ((AllCert->next == End) && (MbedTlsPkcs7VerifyCert (AllCert, NULL, End))) {
      InterCert = AllCert;
      break;
    }

    AllCert = AllCert->next;
  }

  if (InterCert == NULL) {
    return FALSE;
  }

  if (MbedTlsPkcs7VerifyCert (Ca, &(Pkcs7->SignedData.Crls), InterCert)) {
    return TRUE;
  } else {
    return MbedTlsPkcs7VerifyCertChain (Pkcs7, Ca, InterCert);
  }
}

/**
  MbedTlsPkcs7 Verify SignedData.

  @param[in]  Pkcs7        MbedtlsPkcs7.
  @param[in]  TrustCert    CA cert.
  @param[in]  Data         Pointer for data.
  @param[in]  DataLen      The len the buffer.

  @retval TRUE      Verify successfully.
  @retval FALSE     Verify failed.
**/
STATIC
BOOLEAN
MbedTlsPkcs7SignedDataVerify (
  MbedtlsPkcs7      *Pkcs7,
  mbedtls_x509_crt  *TrustCert,
  CONST UINT8       *Data,
  INTN              DataLen
  )
{
  MbedtlsPkcs7SignerInfo  *SignerInfo;
  mbedtls_x509_crt        *Cert;
  mbedtls_x509_crt        *AllCert;
  BOOLEAN                 Result;

  SignerInfo = &(Pkcs7->SignedData.SignerInfos);
  Result     = TRUE;

  //
  // Traverse signers and verify each signers
  //
  while (SignerInfo != NULL) {
    Result = FALSE;
    // 1. Find signers cert
    Cert = MbedTlsPkcs7FindSignerCert (SignerInfo, &(Pkcs7->SignedData.Certificates));
    if (Cert != NULL) {
      // 2. Check signer cert is trusted by trustCert
      if (MbedTlsPkcs7VerifyCert (TrustCert, &(Pkcs7->SignedData.Crls), Cert)) {
        // root cert verify pass
        Result = TRUE;
      } else {
        if (MbedTlsPkcs7VerifyCertChain (Pkcs7, TrustCert, Cert)) {
          Result = TRUE;
        } else {
          Result = FALSE;
        }
      }

      if (Result == TRUE) {
        // 3. Check signed data
        AllCert = &(Pkcs7->SignedData.Certificates);
        while (AllCert != NULL) {
          if (MbedtlsPkcs7SignedDataVerifySigners (SignerInfo, AllCert, Data, DataLen) == 0) {
            return TRUE;
          }

          AllCert = AllCert->next;
        }

        Result = FALSE;
      }
    }

    // move to next
    SignerInfo = SignerInfo->Next;
  }

  return Result;
}

/**
  Check input P7Data is a wrapped ContentInfo structure or not. If not construct
  a new structure to wrap P7Data.

  Caution: This function may receive untrusted input.
  UEFI Authenticated Variable is external input, so this function will do basic
  check for PKCS#7 data structure.

  @param[in]  P7Data       Pointer to the PKCS#7 message to verify.
  @param[in]  P7Length     Length of the PKCS#7 message in bytes.
  @param[out] WrapFlag     If TRUE P7Data is a ContentInfo structure, otherwise
                           return FALSE.
  @param[out] WrapData     If return status of this function is TRUE:
                           1) when WrapFlag is TRUE, pointer to P7Data.
                           2) when WrapFlag is FALSE, pointer to a new ContentInfo
                           structure. It's caller's responsibility to free this
                           buffer.
  @param[out] WrapDataSize Length of ContentInfo structure in bytes.

  @retval     TRUE         The operation is finished successfully.
  @retval     FALSE        The operation is failed due to lack of resources.

**/
BOOLEAN
WrapPkcs7Data (
  IN CONST UINT8  *P7Data,
  IN UINTN        P7Length,
  OUT BOOLEAN     *WrapFlag,
  OUT UINT8       **WrapData,
  OUT UINTN       *WrapDataSize
  )
{
  BOOLEAN  Wrapped;
  UINT8    *SignedData;

  //
  // Check whether input P7Data is a wrapped ContentInfo structure or not.
  //
  Wrapped = FALSE;
  if ((P7Data[4] == MBEDTLS_ASN1_OID) && (P7Data[5] == sizeof (MBEDTLS_OID_PKCS7_SIGNED_DATA) - 1)) {
    if (CompareMem (P7Data + 6, MBEDTLS_OID_PKCS7_SIGNED_DATA, sizeof (MBEDTLS_OID_PKCS7_SIGNED_DATA) - 1) == 0) {
      if ((P7Data[15] == (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC)) && (P7Data[16] == 0x82)) {
        Wrapped = TRUE;
      }
    }
  }

  if (Wrapped) {
    *WrapData     = (UINT8 *)P7Data;
    *WrapDataSize = P7Length;
  } else {
    //
    // Wrap PKCS#7 signeddata to a ContentInfo structure - add a header in 19 bytes.
    //
    *WrapDataSize = P7Length + 19;
    *WrapData     = AllocateZeroPool (*WrapDataSize);
    if (*WrapData == NULL) {
      *WrapFlag = Wrapped;
      return FALSE;
    }

    SignedData = *WrapData;

    //
    // Part1: 0x30, 0x82.
    //
    SignedData[0] = MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE;
    SignedData[1] = 0x82;

    //
    // Part2: Length1 = P7Length + 19 - 4, in big endian.
    //
    SignedData[2] = (UINT8)(((UINT16)(*WrapDataSize - 4)) >> 8);
    SignedData[3] = (UINT8)(((UINT16)(*WrapDataSize - 4)) & 0xff);

    //
    // Part3: 0x06, 0x09.
    //
    SignedData[4] = MBEDTLS_ASN1_OID;
    SignedData[5] = sizeof (MBEDTLS_OID_PKCS7_SIGNED_DATA) - 1;

    //
    // Part4: OID value -- 0x2A 0x86 0x48 0x86 0xF7 0x0D 0x01 0x07 0x02.
    //
    CopyMem (SignedData + 6, MBEDTLS_OID_PKCS7_SIGNED_DATA, sizeof (MBEDTLS_OID_PKCS7_SIGNED_DATA) - 1);

    //
    // Part5: 0xA0, 0x82.
    //
    SignedData[15] = MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC;
    SignedData[16] = 0x82;

    //
    // Part6: Length2 = P7Length, in big endian.
    //
    SignedData[17] = (UINT8)(((UINT16)P7Length) >> 8);
    SignedData[18] = (UINT8)(((UINT16)P7Length) & 0xff);

    //
    // Part7: P7Data.
    //
    CopyMem (SignedData + 19, P7Data, P7Length);
  }

  *WrapFlag = Wrapped;
  return TRUE;
}

/**
  Verifies the validity of a PKCS#7 signed data as described in "PKCS #7:
  Cryptographic Message Syntax Standard". The input signed data could be wrapped
  in a ContentInfo structure.

  If P7Data, TrustedCert or InData is NULL, then return FALSE.
  If P7Length, CertLength or DataLength overflow, then return FALSE.
  If this interface is not supported, then return FALSE.

  @param[in]  P7Data       Pointer to the PKCS#7 message to verify.
  @param[in]  P7Length     Length of the PKCS#7 message in bytes.
  @param[in]  TrustedCert  Pointer to a trusted/root certificate encoded in DER, which
                           is used for certificate chain verification.
  @param[in]  CertLength   Length of the trusted certificate in bytes.
  @param[in]  InData       Pointer to the content to be verified.
  @param[in]  DataLength   Length of InData in bytes.

  @retval  TRUE  The specified PKCS#7 signed data is valid.
  @retval  FALSE Invalid PKCS#7 signed data.
  @retval  FALSE This interface is not supported.

**/
BOOLEAN
EFIAPI
Pkcs7Verify (
  IN CONST UINT8  *P7Data,
  IN UINTN        P7Length,
  IN CONST UINT8  *TrustedCert,
  IN UINTN        CertLength,
  IN CONST UINT8  *InData,
  IN UINTN        DataLength
  )
{
  BOOLEAN           Status;
  UINT8             *WrapData;
  UINTN             WrapDataSize;
  BOOLEAN           Wrapped;
  MbedtlsPkcs7      Pkcs7;
  INT32             Ret;
  mbedtls_x509_crt  Crt;
  mbedtls_x509_crt  *TempCrt;

  //
  // Check input parameters.
  //
  if ((P7Data == NULL) || (TrustedCert == NULL) || (InData == NULL) ||
      (P7Length > INT_MAX) || (CertLength > INT_MAX) || (DataLength > INT_MAX))
  {
    return FALSE;
  }

  Status = WrapPkcs7Data (P7Data, P7Length, &Wrapped, &WrapData, &WrapDataSize);

  if (!Status) {
    return FALSE;
  }

  Status = FALSE;
  MbedTlsPkcs7Init (&Pkcs7);
  mbedtls_x509_crt_init (&Crt);

  Ret = MbedtlsPkcs7ParseDer (WrapData, (INT32)WrapDataSize, &Pkcs7);
  if (Ret != 0) {
    goto Cleanup;
  }

  Ret = mbedtls_x509_crt_parse_der (&Crt, TrustedCert, CertLength);
  if (Ret != 0) {
    goto Cleanup;
  }

  Status = MbedTlsPkcs7SignedDataVerify (&Pkcs7, &Crt, InData, (INT32)DataLength);

Cleanup:
  if (&Crt != NULL) {
    mbedtls_x509_crt_free (&Crt);
  }

  if (Pkcs7.SignedData.Certificates.next != NULL) {
    TempCrt = Pkcs7.SignedData.Certificates.next;
    mbedtls_x509_crt_free (TempCrt);
  }

  return Status;
}

/**
  Wrap function to use free() to free allocated memory for certificates.

  @param[in]  Certs        Pointer to the certificates to be freed.

**/
VOID
EFIAPI
Pkcs7FreeSigners (
  IN UINT8  *Certs
  )
{
  if (Certs == NULL) {
    return;
  }

  FreePool (Certs);
}

/**
  Get the signer's certificates from PKCS#7 signed data as described in "PKCS #7:
  Cryptographic Message Syntax Standard". The input signed data could be wrapped
  in a ContentInfo structure.

  If P7Data, CertStack, StackLength, TrustedCert or CertLength is NULL, then
  return FALSE. If P7Length overflow, then return FALSE.

  Caution: This function may receive untrusted input.
  UEFI Authenticated Variable is external input, so this function will do basic
  check for PKCS#7 data structure.

  @param[in]  P7Data       Pointer to the PKCS#7 message to verify.
  @param[in]  P7Length     Length of the PKCS#7 message in bytes.
  @param[out] CertStack    Pointer to Signer's certificates retrieved from P7Data.
                           It's caller's responsibility to free the buffer with
                           Pkcs7FreeSigners().
                           This data structure is EFI_CERT_STACK type.
  @param[out] StackLength  Length of signer's certificates in bytes.
  @param[out] TrustedCert  Pointer to a trusted certificate from Signer's certificates.
                           It's caller's responsibility to free the buffer with
                           Pkcs7FreeSigners().
  @param[out] CertLength   Length of the trusted certificate in bytes.

  @retval  TRUE            The operation is finished successfully.
  @retval  FALSE           Error occurs during the operation.

**/
BOOLEAN
EFIAPI
Pkcs7GetSigners (
  IN CONST UINT8  *P7Data,
  IN UINTN        P7Length,
  OUT UINT8       **CertStack,
  OUT UINTN       *StackLength,
  OUT UINT8       **TrustedCert,
  OUT UINTN       *CertLength
  )
{
  MbedtlsPkcs7SignerInfo  *SignerInfo;
  mbedtls_x509_crt        *Cert;
  MbedtlsPkcs7            Pkcs7;
  BOOLEAN                 Status;
  UINT8                   *WrapData;
  UINTN                   WrapDataSize;
  BOOLEAN                 Wrapped;
  mbedtls_x509_crt        *TempCrt;

  UINTN  CertSize;
  UINT8  Index;
  UINT8  *CertBuf;
  UINT8  *OldBuf;
  UINTN  BufferSize;
  UINTN  OldSize;

  if ((P7Data == NULL) || (CertStack == NULL) || (StackLength == NULL) ||
      (TrustedCert == NULL) || (CertLength == NULL) || (P7Length > INT_MAX))
  {
    return FALSE;
  }

  Status = WrapPkcs7Data (P7Data, P7Length, &Wrapped, &WrapData, &WrapDataSize);

  if (!Status) {
    return FALSE;
  }

  Status  = FALSE;
  CertBuf = NULL;
  OldBuf  = NULL;
  Cert    = NULL;

  MbedTlsPkcs7Init (&Pkcs7);
  if (MbedtlsPkcs7ParseDer (WrapData, (INT32)WrapDataSize, &Pkcs7) != 0) {
    goto _Exit;
  }

  SignerInfo = &(Pkcs7.SignedData.SignerInfos);

  //
  // Traverse each signers
  //
  // Convert CertStack to buffer in following format:
  // UINT8  CertNumber;
  // UINT32 Cert1Length;
  // UINT8  Cert1[];
  // UINT32 Cert2Length;
  // UINT8  Cert2[];
  // ...
  // UINT32 CertnLength;
  // UINT8  Certn[];
  //
  BufferSize = sizeof (UINT8);
  OldSize    = BufferSize;
  Index      = 0;

  while (SignerInfo != NULL) {
    // Find signers cert
    Cert = MbedTlsPkcs7FindSignerCert (SignerInfo, &(Pkcs7.SignedData.Certificates));
    if (Cert == NULL) {
      goto _Exit;
    }

    CertSize   = Cert->raw.len;
    OldSize    = BufferSize;
    OldBuf     = CertBuf;
    BufferSize = OldSize + CertSize + sizeof (UINT32);

    CertBuf = AllocateZeroPool (BufferSize);
    if (CertBuf == NULL) {
      goto _Exit;
    }

    if (OldBuf != NULL) {
      CopyMem (CertBuf, OldBuf, OldSize);
      FreePool (OldBuf);
      OldBuf = NULL;
    }

    WriteUnaligned32 ((UINT32 *)(CertBuf + OldSize), (UINT32)CertSize);
    CopyMem (CertBuf + OldSize + sizeof (UINT32), Cert->raw.p, CertSize);

    Index++;

    // move to next
    SignerInfo = SignerInfo->Next;
  }

  if (CertBuf != NULL) {
    //
    // Update CertNumber.
    //
    CertBuf[0] = Index;

    *CertLength  = BufferSize - OldSize - sizeof (UINT32);
    *TrustedCert = AllocateZeroPool (*CertLength);
    if (*TrustedCert == NULL) {
      goto _Exit;
    }

    CopyMem (*TrustedCert, CertBuf + OldSize + sizeof (UINT32), *CertLength);
    *CertStack   = CertBuf;
    *StackLength = BufferSize;
    Status       = TRUE;
  }

_Exit:
  //
  // Release Resources
  //
  if (!Status && (CertBuf != NULL)) {
    FreePool (CertBuf);
    *CertStack = NULL;
  }

  if (Status) {
    if (Pkcs7.SignedData.Certificates.next != NULL) {
      TempCrt = Pkcs7.SignedData.Certificates.next;
      mbedtls_x509_crt_free (TempCrt);
    }
  }

  if (OldBuf != NULL) {
    FreePool (OldBuf);
  }

  return Status;
}

/**
  Retrieves all embedded certificates from PKCS#7 signed data as described in "PKCS #7:
  Cryptographic Message Syntax Standard", and outputs two certificate lists chained and
  unchained to the signer's certificates.
  The input signed data could be wrapped in a ContentInfo structure.

  @param[in]  P7Data            Pointer to the PKCS#7 message.
  @param[in]  P7Length          Length of the PKCS#7 message in bytes.
  @param[out] SignerChainCerts  Pointer to the certificates list chained to signer's
                                certificate. It's caller's responsibility to free the buffer
                                with Pkcs7FreeSigners().
                                This data structure is EFI_CERT_STACK type.
  @param[out] ChainLength       Length of the chained certificates list buffer in bytes.
  @param[out] UnchainCerts      Pointer to the unchained certificates lists. It's caller's
                                responsibility to free the buffer with Pkcs7FreeSigners().
                                This data structure is EFI_CERT_STACK type.
  @param[out] UnchainLength     Length of the unchained certificates list buffer in bytes.

  @retval  TRUE         The operation is finished successfully.
  @retval  FALSE        Error occurs during the operation.

**/
BOOLEAN
EFIAPI
Pkcs7GetCertificatesList (
  IN CONST UINT8  *P7Data,
  IN UINTN        P7Length,
  OUT UINT8       **SignerChainCerts,
  OUT UINTN       *ChainLength,
  OUT UINT8       **UnchainCerts,
  OUT UINTN       *UnchainLength
  )
{
  ASSERT (FALSE);
  return FALSE;
}