CryptTs.c 18.7 KB
Newer Older
1
2
3
4
5
6
7
/** @file
  RFC3161 Timestamp Countersignature Verification over OpenSSL.
  The timestamp is generated by a TimeStamping Authority (TSA) and asserts that a
  publisher's signature existed before the specified time. The timestamp extends
  the lifetime of the signature when a signing certificate expires or is later
  revoked.

8
Copyright (c) 2014 - 2017, Intel Corporation. All rights reserved.<BR>
9
SPDX-License-Identifier: BSD-2-Clause-Patent
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

**/

#include "InternalCryptLib.h"

#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pkcs7.h>

//
// OID ASN.1 Value for SPC_RFC3161_OBJID ("1.3.6.1.4.1.311.3.3.1")
//
UINT8 mSpcRFC3161OidValue[] = {
  0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x03, 0x03, 0x01
  };

///
/// The messageImprint field SHOULD contain the hash of the datum to be
/// time-stamped.  The hash is represented as an OCTET STRING.  Its
/// length MUST match the length of the hash value for that algorithm
/// (e.g., 20 bytes for SHA-1 or 16 bytes for MD5).
///
/// MessageImprint ::= SEQUENCE  {
///   hashAlgorithm                AlgorithmIdentifier,
///   hashedMessage                OCTET STRING  }
///
typedef struct {
  X509_ALGOR         *HashAlgorithm;
  ASN1_OCTET_STRING  *HashedMessage;
} TS_MESSAGE_IMPRINT;

//
// ASN.1 Functions for TS_MESSAGE_IMPRINT
//
DECLARE_ASN1_FUNCTIONS (TS_MESSAGE_IMPRINT)
ASN1_SEQUENCE (TS_MESSAGE_IMPRINT) = {
  ASN1_SIMPLE (TS_MESSAGE_IMPRINT, HashAlgorithm, X509_ALGOR),
  ASN1_SIMPLE (TS_MESSAGE_IMPRINT, HashedMessage, ASN1_OCTET_STRING)
} ASN1_SEQUENCE_END (TS_MESSAGE_IMPRINT)
IMPLEMENT_ASN1_FUNCTIONS (TS_MESSAGE_IMPRINT)

///
/// Accuracy represents the time deviation around the UTC time contained
/// in GeneralizedTime of time-stamp token.
///
/// Accuracy ::= SEQUENCE {
///       seconds        INTEGER              OPTIONAL,
///       millis     [0] INTEGER  (1..999)    OPTIONAL,
///       micros     [1] INTEGER  (1..999)    OPTIONAL  }
///
typedef struct {
  ASN1_INTEGER  *Seconds;
  ASN1_INTEGER  *Millis;
  ASN1_INTEGER  *Micros;
} TS_ACCURACY;

//
// ASN.1 Functions for TS_ACCURACY
//
DECLARE_ASN1_FUNCTIONS (TS_ACCURACY)
ASN1_SEQUENCE (TS_ACCURACY) = {
  ASN1_OPT     (TS_ACCURACY, Seconds, ASN1_INTEGER),
  ASN1_IMP_OPT (TS_ACCURACY, Millis,  ASN1_INTEGER, 0),
  ASN1_IMP_OPT (TS_ACCURACY, Micros,  ASN1_INTEGER, 1)
} ASN1_SEQUENCE_END (TS_ACCURACY)
IMPLEMENT_ASN1_FUNCTIONS (TS_ACCURACY)

///
/// The timestamp token info resulting from a successful timestamp request,
/// as defined in RFC 3161.
///
///  TSTInfo ::= SEQUENCE  {
///     version                      INTEGER  { v1(1) },
///     policy                       TSAPolicyId,
///     messageImprint               MessageImprint,
///       -- MUST have the same value as the similar field in
///       -- TimeStampReq
///     serialNumber                 INTEGER,
///       -- Time-Stamping users MUST be ready to accommodate integers
///       -- up to 160 bits.
///     genTime                      GeneralizedTime,
///     accuracy                     Accuracy                 OPTIONAL,
///     ordering                     BOOLEAN             DEFAULT FALSE,
///     nonce                        INTEGER                  OPTIONAL,
///       -- MUST be present if the similar field was present
///       -- in TimeStampReq.  In that case it MUST have the same value.
///     tsa                          [0] GeneralName          OPTIONAL,
///     extensions                   [1] IMPLICIT Extensions   OPTIONAL  }
///
typedef struct {
  ASN1_INTEGER              *Version;
  ASN1_OBJECT               *Policy;
  TS_MESSAGE_IMPRINT        *MessageImprint;
  ASN1_INTEGER              *SerialNumber;
  ASN1_GENERALIZEDTIME      *GenTime;
  TS_ACCURACY               *Accuracy;
  ASN1_BOOLEAN              Ordering;
  ASN1_INTEGER              *Nonce;
  GENERAL_NAME              *Tsa;
  STACK_OF(X509_EXTENSION)  *Extensions;
} TS_TST_INFO;

//
// ASN.1 Functions for TS_TST_INFO
//
DECLARE_ASN1_FUNCTIONS (TS_TST_INFO)
ASN1_SEQUENCE (TS_TST_INFO) = {
  ASN1_SIMPLE (TS_TST_INFO, Version, ASN1_INTEGER),
  ASN1_SIMPLE (TS_TST_INFO, Policy, ASN1_OBJECT),
  ASN1_SIMPLE (TS_TST_INFO, MessageImprint, TS_MESSAGE_IMPRINT),
  ASN1_SIMPLE (TS_TST_INFO, SerialNumber, ASN1_INTEGER),
  ASN1_SIMPLE (TS_TST_INFO, GenTime, ASN1_GENERALIZEDTIME),
  ASN1_OPT    (TS_TST_INFO, Accuracy, TS_ACCURACY),
  ASN1_OPT    (TS_TST_INFO, Ordering, ASN1_FBOOLEAN),
  ASN1_OPT    (TS_TST_INFO, Nonce, ASN1_INTEGER),
  ASN1_EXP_OPT(TS_TST_INFO, Tsa, GENERAL_NAME, 0),
  ASN1_IMP_SEQUENCE_OF_OPT (TS_TST_INFO, Extensions, X509_EXTENSION, 1)
} ASN1_SEQUENCE_END (TS_TST_INFO)
IMPLEMENT_ASN1_FUNCTIONS (TS_TST_INFO)


/**
  Convert ASN.1 GeneralizedTime to EFI Time.

  @param[in]  Asn1Time         Pointer to the ASN.1 GeneralizedTime to be converted.
  @param[out] SigningTime      Return the corresponding EFI Time.

Antoine Coeur's avatar
Antoine Coeur committed
139
  @retval  TRUE   The time conversion succeeds.
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
  @retval  FALSE  Invalid parameters.

**/
BOOLEAN
EFIAPI
ConvertAsn1TimeToEfiTime (
  IN  ASN1_TIME  *Asn1Time,
  OUT EFI_TIME   *EfiTime
  )
{
  CONST CHAR8  *Str;
  UINTN        Index;

  if ((Asn1Time == NULL) || (EfiTime == NULL)) {
    return FALSE;
  }

  Str = (CONST CHAR8*)Asn1Time->data;
158
  SetMem (EfiTime, sizeof (EFI_TIME), 0);
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

  Index = 0;
  if (Asn1Time->type == V_ASN1_UTCTIME) {               /* two digit year */
    EfiTime->Year  = (Str[Index++] - '0') * 10;
    EfiTime->Year += (Str[Index++] - '0');
    if (EfiTime->Year < 70) {
      EfiTime->Year += 100;
    }
  } else if (Asn1Time->type == V_ASN1_GENERALIZEDTIME) { /* four digit year */
    EfiTime->Year  = (Str[Index++] - '0') * 1000;
    EfiTime->Year += (Str[Index++] - '0') * 100;
    EfiTime->Year += (Str[Index++] - '0') * 10;
    EfiTime->Year += (Str[Index++] - '0');
    if ((EfiTime->Year < 1900) || (EfiTime->Year > 9999)) {
      return FALSE;
    }
  }

  EfiTime->Month   = (Str[Index++] - '0') * 10;
  EfiTime->Month  += (Str[Index++] - '0');
  if ((EfiTime->Month < 1) || (EfiTime->Month > 12)) {
    return FALSE;
  }

  EfiTime->Day     = (Str[Index++] - '0') * 10;
  EfiTime->Day    += (Str[Index++] - '0');
  if ((EfiTime->Day < 1) || (EfiTime->Day > 31)) {
    return FALSE;
  }

  EfiTime->Hour    = (Str[Index++] - '0') * 10;
  EfiTime->Hour   += (Str[Index++] - '0');
  if (EfiTime->Hour > 23) {
    return FALSE;
  }

  EfiTime->Minute  = (Str[Index++] - '0') * 10;
  EfiTime->Minute += (Str[Index++] - '0');
  if (EfiTime->Minute > 59) {
    return FALSE;
  }

  EfiTime->Second  = (Str[Index++] - '0') * 10;
  EfiTime->Second += (Str[Index++] - '0');
  if (EfiTime->Second > 59) {
    return FALSE;
  }

  /* Note: we did not adjust the time based on time zone information */

  return TRUE;
}

/**

  Check the validity of TimeStamp Token Information.

  @param[in]  TstInfo          Pointer to the TS_TST_INFO structure.
  @param[in]  TimestampedData  Pointer to the data to be time-stamped.
  @param[in]  DataSize         Size of timestamped data in bytes.

  @retval  TRUE   The TimeStamp Token Information is valid.
  @retval  FALSE  Invalid TimeStamp Token Information.

**/
BOOLEAN
EFIAPI
CheckTSTInfo (
  IN  CONST TS_TST_INFO  *TstInfo,
  IN  CONST UINT8        *TimestampedData,
  IN  UINTN              DataSize
  )
{
  BOOLEAN             Status;
  TS_MESSAGE_IMPRINT  *Imprint;
  X509_ALGOR          *HashAlgo;
  CONST EVP_MD        *Md;
236
  EVP_MD_CTX          *MdCtx;
237
238
239
240
241
242
243
244
245
  UINTN               MdSize;
  UINT8               *HashedMsg;

  //
  // Initialization
  //
  Status    = FALSE;
  HashAlgo  = NULL;
  HashedMsg = NULL;
246
  MdCtx     = NULL;
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

  //
  // -- Check version number of Timestamp:
  //   The version field (currently v1) describes the version of the time-stamp token.
  //   Conforming time-stamping servers MUST be able to provide version 1 time-stamp tokens.
  //
  if ((ASN1_INTEGER_get (TstInfo->Version)) != 1) {
    return FALSE;
  }

  //
  // -- Check Policies
  //   The policy field MUST indicate the TSA's policy under which the response was produced.
  //
  if (TstInfo->Policy == NULL) {
    /// NOTE: Need to check if the requested and returned policies.
    ///       We have no information about the Requested TSA Policy.
    return FALSE;
  }

  //
  // -- Compute & Check Message Imprint
  //
  Imprint  = TstInfo->MessageImprint;
  HashAlgo = X509_ALGOR_dup (Imprint->HashAlgorithm);

  Md = EVP_get_digestbyobj (HashAlgo->algorithm);
  if (Md == NULL) {
    goto _Exit;
  }

  MdSize = EVP_MD_size (Md);
  HashedMsg = AllocateZeroPool (MdSize);
  if (HashedMsg == NULL) {
    goto _Exit;
  }
283
284
285
286
287
288
289
290
291
  MdCtx = EVP_MD_CTX_new ();
  if (MdCtx == NULL) {
    goto _Exit;
  }
  if ((EVP_DigestInit_ex (MdCtx, Md, NULL) != 1) ||
      (EVP_DigestUpdate (MdCtx, TimestampedData, DataSize) != 1) ||
      (EVP_DigestFinal (MdCtx, HashedMsg, NULL) != 1)) {
    goto _Exit;
  }
292
  if ((MdSize == (UINTN)ASN1_STRING_length (Imprint->HashedMessage)) &&
293
      (CompareMem (HashedMsg, ASN1_STRING_get0_data (Imprint->HashedMessage), MdSize) != 0)) {
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
    goto _Exit;
  }

  //
  // -- Check Nonces
  //
  if (TstInfo->Nonce != NULL) {
    //
    // Nonces is optional, No error if no nonce is returned;
    //
  }

  //
  // -- Check if the TSA name and signer certificate is matched.
  //
  if (TstInfo->Tsa != NULL) {
    //
    //  Ignored the optional Tsa field checking.
    //
  }

  Status = TRUE;

_Exit:
  X509_ALGOR_free (HashAlgo);
319
  EVP_MD_CTX_free (MdCtx);
320
321
322
323
324
325
326
327
  if (HashedMsg != NULL) {
    FreePool (HashedMsg);
  }

  return Status;
}

/**
Gary Lin's avatar
Gary Lin committed
328
  Verifies the validity of a TimeStamp Token as described in RFC 3161 ("Internet
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
  X.509 Public Key Infrastructure Time-Stamp Protocol (TSP)").

  If TSToken is NULL, then return FALSE.
  If TimestampedData is NULL, then return FALSE.

  @param[in]  TSToken          Pointer to the RFC3161 TimeStamp Token, which is generated
                               by a TSA and located in the software publisher's SignerInfo
                               structure.
  @param[in]  TokenSize        Size of the TimeStamp Token in bytes.
  @param[in]  TsaCert          Pointer to a trusted/root TSA certificate encoded in DER.
  @param[in]  CertSize         Size of the trusted TSA certificate in bytes.
  @param[in]  TimestampedData  Pointer to the data to be time-stamped.
  @param[in]  DataSize         Size of timestamped data in bytes.
  @param[out] SigningTime      Return the time of timestamp generation time if the timestamp
                               signature is valid.

  @retval  TRUE   The specified timestamp token is valid.
  @retval  FALSE  Invalid timestamp token.

**/
BOOLEAN
EFIAPI
TimestampTokenVerify (
  IN  CONST UINT8  *TSToken,
  IN  UINTN        TokenSize,
  IN  CONST UINT8  *TsaCert,
  IN  UINTN        CertSize,
  IN  CONST UINT8  *TimestampedData,
  IN  UINTN        DataSize,
  OUT EFI_TIME     *SigningTime
  )
{
  BOOLEAN      Status;
  CONST UINT8  *TokenTemp;
  PKCS7        *Pkcs7;
  X509         *Cert;
365
  CONST UINT8  *CertTemp;
366
367
368
369
  X509_STORE   *CertStore;
  BIO          *OutBio;
  UINT8        *TstData;
  UINTN        TstSize;
370
  CONST UINT8  *TstTemp;
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
  TS_TST_INFO  *TstInfo;

  Status = FALSE;

  //
  // Check input parameters
  //
  if ((TSToken == NULL) || (TsaCert == NULL) || (TimestampedData == NULL) ||
      (TokenSize > INT_MAX) || (CertSize > INT_MAX) || (DataSize > INT_MAX)) {
    return FALSE;
  }

  //
  // Initializations
  //
  if (SigningTime != NULL) {
    SetMem (SigningTime, sizeof (EFI_TIME), 0);
  }
  Pkcs7     = NULL;
  Cert      = NULL;
  CertStore = NULL;
  OutBio    = NULL;
  TstData   = NULL;
  TstInfo   = NULL;

  //
  // TimeStamp Token should contain one valid DER-encoded ASN.1 PKCS#7 structure.
  //
  TokenTemp = TSToken;
  Pkcs7     = d2i_PKCS7 (NULL, (const unsigned char **) &TokenTemp, (int) TokenSize);
  if (Pkcs7 == NULL) {
    goto _Exit;
  }

  //
  // The timestamp signature (TSA's response) will be one PKCS#7 signed data.
  //
  if (!PKCS7_type_is_signed (Pkcs7)) {
    goto _Exit;
  }

  //
  // Read the trusted TSA certificate (DER-encoded), and Construct X509 Certificate.
  //
415
416
  CertTemp = TsaCert;
  Cert = d2i_X509 (NULL, &CertTemp, (long) CertSize);
417
418
419
420
421
422
423
424
425
426
427
428
429
  if (Cert == NULL) {
    goto _Exit;
  }

  //
  // Setup X509 Store for trusted certificate.
  //
  CertStore = X509_STORE_new ();
  if ((CertStore == NULL) || !(X509_STORE_add_cert (CertStore, Cert))) {
    goto _Exit;
  }

  //
430
  // Allow partial certificate chains, terminated by a non-self-signed but
431
  // still trusted intermediate certificate. Also disable time checks.
432
  //
433
434
  X509_STORE_set_flags (CertStore,
                        X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_NO_CHECK_TIME);
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

  X509_STORE_set_purpose (CertStore, X509_PURPOSE_ANY);

  //
  // Verifies the PKCS#7 signedData structure, and output the signed contents.
  //
  OutBio = BIO_new (BIO_s_mem ());
  if (OutBio == NULL) {
    goto _Exit;
  }
  if (!PKCS7_verify (Pkcs7, NULL, CertStore, NULL, OutBio, PKCS7_BINARY)) {
    goto _Exit;
  }

  //
  // Read the signed contents detached in timestamp signature.
  //
  TstData = AllocateZeroPool (2048);
  if (TstData == NULL) {
    goto _Exit;
  }
  TstSize = BIO_read (OutBio, (void *) TstData, 2048);

  //
  // Construct TS_TST_INFO structure from the signed contents.
  //
  TstTemp = TstData;
462
463
  TstInfo = d2i_TS_TST_INFO (NULL, (const unsigned char **) &TstTemp,
              (int)TstSize);
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
  if (TstInfo == NULL) {
    goto _Exit;
  }

  //
  // Check TS_TST_INFO structure.
  //
  Status = CheckTSTInfo (TstInfo, TimestampedData, DataSize);
  if (!Status) {
    goto _Exit;
  }

  //
  // Retrieve the signing time from TS_TST_INFO structure.
  //
  if (SigningTime != NULL) {
    SetMem (SigningTime, sizeof (EFI_TIME), 0);
    Status = ConvertAsn1TimeToEfiTime (TstInfo->GenTime, SigningTime);
  }

_Exit:
  //
  // Release Resources
  //
  PKCS7_free (Pkcs7);
  X509_free (Cert);
  X509_STORE_free (CertStore);
  BIO_free (OutBio);
  TS_TST_INFO_free (TstInfo);

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

  return Status;
}

/**
Gary Lin's avatar
Gary Lin committed
502
  Verifies the validity of a RFC3161 Timestamp CounterSignature embedded in PE/COFF Authenticode
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
  signature.

  If AuthData is NULL, then return FALSE.

  @param[in]  AuthData     Pointer to the Authenticode Signature retrieved from signed
                           PE/COFF image to be verified.
  @param[in]  DataSize     Size of the Authenticode Signature in bytes.
  @param[in]  TsaCert      Pointer to a trusted/root TSA certificate encoded in DER, which
                           is used for TSA certificate chain verification.
  @param[in]  CertSize     Size of the trusted certificate in bytes.
  @param[out] SigningTime  Return the time of timestamp generation time if the timestamp
                           signature is valid.

  @retval  TRUE   The specified Authenticode includes a valid RFC3161 Timestamp CounterSignature.
  @retval  FALSE  No valid RFC3161 Timestamp CounterSignature in the specified Authenticode data.

**/
BOOLEAN
EFIAPI
ImageTimestampVerify (
  IN  CONST UINT8  *AuthData,
  IN  UINTN        DataSize,
  IN  CONST UINT8  *TsaCert,
  IN  UINTN        CertSize,
  OUT EFI_TIME     *SigningTime
  )
{
  BOOLEAN                      Status;
  PKCS7                        *Pkcs7;
532
  CONST UINT8                  *Temp;
533
534
535
536
537
  STACK_OF(PKCS7_SIGNER_INFO)  *SignerInfos;
  PKCS7_SIGNER_INFO            *SignInfo;
  UINTN                        Index;
  STACK_OF(X509_ATTRIBUTE)     *Sk;
  X509_ATTRIBUTE               *Xa;
538
  ASN1_OBJECT                  *XaObj;
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
  ASN1_TYPE                    *Asn1Type;
  ASN1_OCTET_STRING            *EncDigest;
  UINT8                        *TSToken;
  UINTN                        TokenSize;

  //
  // Input Parameters Checking.
  //
  if ((AuthData == NULL) || (TsaCert == NULL)) {
    return FALSE;
  }

  if ((DataSize > INT_MAX) || (CertSize > INT_MAX)) {
    return FALSE;
  }

  //
  // Register & Initialize necessary digest algorithms for PKCS#7 Handling.
  //
  if ((EVP_add_digest (EVP_md5 ()) == 0) || (EVP_add_digest (EVP_sha1 ()) == 0) ||
      (EVP_add_digest (EVP_sha256 ()) == 0) || (EVP_add_digest_alias (SN_sha1WithRSAEncryption, SN_sha1WithRSA)) == 0) {
    return FALSE;
  }

  //
  // Initialization.
  //
  Status    = FALSE;
  Pkcs7     = NULL;
  SignInfo  = NULL;

  //
  // Decode ASN.1-encoded Authenticode data into PKCS7 structure.
  //
573
574
  Temp  = AuthData;
  Pkcs7 = d2i_PKCS7 (NULL, (const unsigned char **) &Temp, (int) DataSize);
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
  if (Pkcs7 == NULL) {
    goto _Exit;
  }

  //
  // Check if there is one and only one signer.
  //
  SignerInfos = PKCS7_get_signer_info (Pkcs7);
  if (!SignerInfos || (sk_PKCS7_SIGNER_INFO_num (SignerInfos) != 1)) {
    goto _Exit;
  }

  //
  // Locate the TimeStamp CounterSignature.
  //
  SignInfo = sk_PKCS7_SIGNER_INFO_value (SignerInfos, 0);
  if (SignInfo == NULL) {
    goto _Exit;
  }

  //
  // Locate Message Digest which will be the data to be time-stamped.
  //
  EncDigest = SignInfo->enc_digest;
  if (EncDigest == NULL) {
    goto _Exit;
  }

  //
  // The RFC3161 timestamp counterSignature is contained in unauthenticatedAttributes field
  // of SignerInfo.
  //
  Sk = SignInfo->unauth_attr;
  if (Sk == NULL) {             // No timestamp counterSignature.
    goto _Exit;
  }

  Asn1Type = NULL;
  for (Index = 0; Index < (UINTN) sk_X509_ATTRIBUTE_num (Sk); Index++) {
    //
    // Search valid RFC3161 timestamp counterSignature based on OBJID.
    //
    Xa = sk_X509_ATTRIBUTE_value (Sk, (int)Index);
618
    if (Xa == NULL) {
619
620
      continue;
    }
621
622
623
624
    XaObj = X509_ATTRIBUTE_get0_object(Xa);
    if (XaObj == NULL) {
      continue;
    }
625
626
    if ((OBJ_length(XaObj) != sizeof (mSpcRFC3161OidValue)) ||
        (CompareMem (OBJ_get0_data(XaObj), mSpcRFC3161OidValue, sizeof (mSpcRFC3161OidValue)) != 0)) {
627
628
629
      continue;
    }
    Asn1Type = X509_ATTRIBUTE_get0_type(Xa, 0);
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
  }

  if (Asn1Type == NULL) {
    Status = FALSE;
    goto _Exit;
  }
  TSToken   = Asn1Type->value.octet_string->data;
  TokenSize = Asn1Type->value.octet_string->length;

  //
  // TimeStamp counterSignature (Token) verification.
  //
  Status = TimestampTokenVerify (
             TSToken,
             TokenSize,
             TsaCert,
             CertSize,
             EncDigest->data,
             EncDigest->length,
             SigningTime
             );

_Exit:
  //
  // Release Resources
  //
  PKCS7_free (Pkcs7);

  return Status;
}