-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathPESignAnalyzer.cpp
1342 lines (1270 loc) · 36.7 KB
/
PESignAnalyzer.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 NOTICE & DESCRIPTION
*
* Source: PESignAnalyzer.cpp
* Author: leeqwind
* E-mail: [email protected]
* Notice: This program can retrieve signature information from PE
* files which signed by a/some certificate(s) on Windows.
* Supporting multi-signed information and certificates chain.
*/
#include <Windows.h>
#include <WinTrust.h>
#include <list>
#include <Mscat.h>
#include <SoftPub.h>
#include <strsafe.h>
#include <WinCrypt.h>
#include <math.h>
#include <map>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
#define MY_ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
#ifndef szOID_RFC3161_counterSign
#define szOID_RFC3161_counterSign "1.3.6.1.4.1.311.3.3.1"
#endif
#ifndef szOID_NESTED_SIGNATURE
#define szOID_NESTED_SIGNATURE "1.3.6.1.4.1.311.2.4.1"
#endif
#pragma comment(lib, "Crypt32.lib")
#pragma comment(lib, "Wintrust.lib")
typedef struct _SIGN_COUNTER_SIGN {
std::string SignerName;
std::string MailAddress;
std::string TimeStamp;
} SIGN_COUNTER_SIGN, *PSIGN_COUNTER_SIGN;
/// Per certificate node.
typedef struct _CERT_NODE_INFO {
std::string SubjectName;
std::string IssuerName;
std::string Version;
std::string Serial;
std::string Thumbprint;
std::string NotBefore;
std::string NotAfter;
std::string SignAlgorithm;
std::wstring CRLpoint;
} CERT_NODE_INFO, *PCERT_NODE_INFO;
/// Per signature node.
typedef struct _SIGN_NODE_INFO {
std::string DigestAlgorithm;
std::string Version;
SIGN_COUNTER_SIGN CounterSign;
std::list<CERT_NODE_INFO> CertChain;
} SIGN_NODE_INFO, *PSIGN_NODE_INFO;
typedef struct _SIGNDATA_HANDLE {
DWORD dwObjSize;
PCMSG_SIGNER_INFO pSignerInfo;
HCERTSTORE hCertStoreHandle;
} SIGNDATA_HANDLE, *PSIGNDATA_HANDLE;
BOOL MyCryptMsgGetParam(
HCRYPTMSG hCryptMsg,
DWORD dwParamType,
DWORD dwIndex,
PVOID *pParam,
DWORD *dwOutSize
) {
BOOL bReturn = FALSE;
DWORD dwSize = 0;
if (!pParam)
{
return FALSE;
}
// Get size
bReturn = CryptMsgGetParam(hCryptMsg, dwParamType, dwIndex, NULL, &dwSize);
if (!bReturn)
{
return FALSE;
}
// Alloc memory via size
*pParam = (PVOID)LocalAlloc(LPTR, dwSize);
if (!*pParam)
{
return FALSE;
}
// Get data to alloced memory
bReturn = CryptMsgGetParam(hCryptMsg, dwParamType, dwIndex, *pParam, &dwSize);
if (!bReturn)
{
return FALSE;
}
if (dwOutSize)
{
*dwOutSize = dwSize;
}
return TRUE;
}
CONST UCHAR SG_ProtoCoded[] = {
0x30, 0x82,
};
CONST UCHAR SG_SignedData[] = {
0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02,
};
#define XCH_WORD_LITEND(num) \
(WORD)(((((WORD)num) & 0xFF00) >> 8) | ((((WORD)num) & 0x00FF) << 8))
#define _8BYTE_ALIGN(offset, base) \
(((offset + base + 7) & 0xFFFFFFF8L) - (base & 0xFFFFFFF8L))
// https://msdn.microsoft.com/zh-cn/library/windows/desktop/aa374890(v=vs.85).aspx
BOOL GetNestedSignerInfo(
CONST PSIGNDATA_HANDLE AuthSignData,
std::list<SIGNDATA_HANDLE> & NestedChain
) {
BOOL bSucceed = FALSE;
BOOL bReturn = FALSE;
HCRYPTMSG hNestedMsg = NULL;
PBYTE pbCurrData = NULL;
PBYTE pbNextData = NULL;
DWORD n = 0x00;
DWORD cbCurrData = 0x00;
if (!AuthSignData->pSignerInfo)
{
return FALSE;
}
__try
{
// Traverse and look for a nested signature.
for (n = 0; n < AuthSignData->pSignerInfo->UnauthAttrs.cAttr; n++)
{
if (!lstrcmpA(AuthSignData->pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId,
szOID_NESTED_SIGNATURE))
{
break;
}
}
// Cannot find a nested signature attribute.
if (n >= AuthSignData->pSignerInfo->UnauthAttrs.cAttr)
{
bSucceed = FALSE;
__leave;
}
pbCurrData = AuthSignData->pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData;
cbCurrData = AuthSignData->pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData;
// Multiple nested signatures just add one attr in UnauthAttrs
// list of the main signature pointing to the first nested si-
// gnature. Every nested signature exists side by side in an 8
// bytes aligned way. According to the size of major signature
// parse the nested signatures one by one.
while (pbCurrData > (BYTE *)AuthSignData->pSignerInfo &&
pbCurrData < (BYTE *)AuthSignData->pSignerInfo + AuthSignData->dwObjSize)
{
SIGNDATA_HANDLE NestedHandle = { 0 };
// NOTE: The size in 30 82 xx doesnt contain its own size.
// HEAD:
// 0000: 30 82 04 df ; SEQUENCE (4df Bytes)
// 0004: 06 09 ; OBJECT_ID(9 Bytes)
// 0006: | 2a 86 48 86 f7 0d 01 07 02
// | ; 1.2.840.113549.1.7.2 PKCS 7 SignedData
if (memcmp(pbCurrData + 0, SG_ProtoCoded, sizeof(SG_ProtoCoded)) ||
memcmp(pbCurrData + 6, SG_SignedData, sizeof(SG_SignedData)))
{
break;
}
if (hNestedMsg) {
CryptMsgClose(hNestedMsg);
hNestedMsg = NULL;
}
hNestedMsg = CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
0,
0,
0,
NULL,
0
);
if (!hNestedMsg) // Fatal Error
{
bSucceed = FALSE;
__leave;
}
// Big Endian -> Little Endian
cbCurrData = XCH_WORD_LITEND(*(WORD *)(pbCurrData + 2)) + 4;
pbNextData = pbCurrData;
pbNextData += _8BYTE_ALIGN(cbCurrData, (ULONG_PTR)pbCurrData);
bReturn = CryptMsgUpdate(hNestedMsg, pbCurrData, cbCurrData, TRUE);
pbCurrData = pbNextData;
if (!bReturn)
{
continue;
}
bReturn = MyCryptMsgGetParam(hNestedMsg, CMSG_SIGNER_INFO_PARAM,
0,
(PVOID *)&NestedHandle.pSignerInfo,
&NestedHandle.dwObjSize
);
if (!bReturn)
{
continue;
}
NestedHandle.hCertStoreHandle = CertOpenStore(CERT_STORE_PROV_MSG,
PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
0,
0,
hNestedMsg
);
bSucceed = TRUE;
NestedChain.push_back(NestedHandle);
}
}
__finally
{
if (hNestedMsg) CryptMsgClose(hNestedMsg);
}
return bSucceed;
}
BOOL GetAuthedAttribute(
PCMSG_SIGNER_INFO pSignerInfo
) {
BOOL bSucceed = FALSE;
DWORD dwObjSize = 0x00;
DWORD n = 0x00;
__try
{
for (n = 0; n < pSignerInfo->AuthAttrs.cAttr; n++)
{
if (!lstrcmpA(pSignerInfo->AuthAttrs.rgAttr[n].pszObjId, szOID_RSA_counterSign))
{
bSucceed = TRUE;
break;
}
}
}
__finally
{
}
return bSucceed;
}
// http://support.microsoft.com/kb/323809
BOOL GetCounterSignerInfo(
PCMSG_SIGNER_INFO pSignerInfo,
PCMSG_SIGNER_INFO *pTargetSigner
) {
BOOL bSucceed = FALSE;
BOOL bReturn = FALSE;
DWORD dwObjSize = 0x00;
DWORD n = 0x00;
if (!pSignerInfo || !pTargetSigner)
{
return FALSE;
}
__try
{
*pTargetSigner = NULL;
for (n = 0; n < pSignerInfo->UnauthAttrs.cAttr; n++)
{
if (!lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId, szOID_RSA_counterSign))
{
break;
}
}
if (n >= pSignerInfo->UnauthAttrs.cAttr)
{
bSucceed = FALSE;
__leave;
}
bReturn = CryptDecodeObject(MY_ENCODING,
PKCS7_SIGNER_INFO,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
0,
NULL,
&dwObjSize
);
if (!bReturn)
{
bSucceed = FALSE;
__leave;
}
*pTargetSigner = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwObjSize);
if (!*pTargetSigner)
{
bSucceed = FALSE;
__leave;
}
bReturn = CryptDecodeObject(MY_ENCODING,
PKCS7_SIGNER_INFO,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
0,
(PVOID)*pTargetSigner,
&dwObjSize
);
if (!bReturn)
{
bSucceed = FALSE;
__leave;
}
bSucceed = TRUE;
}
__finally
{
}
return bSucceed;
}
std::string TimeToString(
FILETIME *pftIn,
SYSTEMTIME *pstIn = NULL
) {
SYSTEMTIME st = { 0 };
CHAR szBuffer[256] = { 0 };
if (!pstIn)
{
if (!pftIn)
{
return std::string("");
}
FileTimeToSystemTime(pftIn, &st);
pstIn = &st;
}
_snprintf_s(szBuffer, 256, "%04d/%02d/%02d %02d:%02d:%02d",
pstIn->wYear,
pstIn->wMonth,
pstIn->wDay,
pstIn->wHour,
pstIn->wMinute,
pstIn->wSecond
);
return std::string(szBuffer);
}
BOOL GetCounterSignerData(
CONST PCMSG_SIGNER_INFO SignerInfo,
SIGN_COUNTER_SIGN & CounterSign
) {
BOOL bReturn = FALSE;
DWORD n = 0x00;
DWORD dwData = 0x00;
FILETIME lft, ft;
SYSTEMTIME st;
// Find szOID_RSA_signingTime OID.
for (n = 0; n < SignerInfo->AuthAttrs.cAttr; n++)
{
if (!lstrcmpA(SignerInfo->AuthAttrs.rgAttr[n].pszObjId, szOID_RSA_signingTime))
{
break;
}
}
if (n >= SignerInfo->AuthAttrs.cAttr)
{
return FALSE;
}
// Decode and get FILETIME structure.
dwData = sizeof(ft);
bReturn = CryptDecodeObject(MY_ENCODING,
szOID_RSA_signingTime,
SignerInfo->AuthAttrs.rgAttr[n].rgValue[0].pbData,
SignerInfo->AuthAttrs.rgAttr[n].rgValue[0].cbData,
0,
(PVOID)&ft,
&dwData
);
if (!bReturn)
{
return FALSE;
}
// Convert.
FileTimeToLocalFileTime(&ft, &lft);
FileTimeToSystemTime(&lft, &st);
CounterSign.TimeStamp = TimeToString(NULL, &st);
return TRUE;
}
BOOL SafeToReadNBytes(
DWORD dwSize,
DWORD dwStart,
DWORD dwRequestSize
) {
return dwSize - dwStart >= dwRequestSize;
}
void ParseDERType(
BYTE bIn,
INT & iType,
INT & iClass
) {
iType = bIn & 0x3F;
iClass = bIn >> 6;
}
DWORD ReadNumberFromNBytes(
PBYTE pbSignature,
DWORD dwStart,
DWORD dwRequestSize
) {
DWORD dwNumber = 0;
for (DWORD i = 0; i < dwRequestSize; i++)
{
dwNumber = dwNumber * 0x100 + pbSignature[dwStart + i];
}
return dwNumber;
}
BOOL ParseDERSize(
PBYTE pbSignature,
DWORD dwSize,
DWORD & dwSizefound,
DWORD & dwBytesParsed
) {
if (pbSignature[0] > 0x80 &&
!SafeToReadNBytes(dwSize, 1, pbSignature[0] - 0x80))
{
return FALSE;
}
if (pbSignature[0] <= 0x80)
{
dwSizefound = pbSignature[0];
dwBytesParsed = 1;
}
else
{
dwSizefound = ReadNumberFromNBytes(pbSignature, 1, pbSignature[0] - 0x80);
dwBytesParsed = 1 + pbSignature[0] - 0x80;
}
return TRUE;
}
BOOL ParseDERFindType(
INT iTypeSearch,
PBYTE pbSignature,
DWORD dwSize,
DWORD & dwPositionFound,
DWORD & dwLengthFound,
DWORD & dwPositionError,
INT & iTypeError
) {
DWORD dwPosition = 0;
DWORD dwSizeFound = 0;
DWORD dwBytesParsed = 0;
INT iType = 0;
INT iClass = 0;
iTypeError = -1;
dwPositionFound = 0;
dwLengthFound = 0;
dwPositionError = 0;
if (NULL == pbSignature)
{
iTypeError = -1;
return FALSE;
}
while (dwSize > dwPosition)
{
if (!SafeToReadNBytes(dwSize, dwPosition, 2))
{
dwPositionError = dwPosition;
iTypeError = -2;
return FALSE;
}
ParseDERType(pbSignature[dwPosition], iType, iClass);
switch (iType)
{
case 0x05: // NULL
dwPosition++;
if (pbSignature[dwPosition] != 0x00)
{
dwPositionError = dwPosition;
iTypeError = -4;
return FALSE;
}
dwPosition++;
break;
case 0x06: // OID
dwPosition++;
if (!SafeToReadNBytes(dwSize - dwPosition, 1, pbSignature[dwPosition]))
{
dwPositionError = dwPosition;
iTypeError = -5;
return FALSE;
}
dwPosition += 1 + pbSignature[dwPosition];
break;
case 0x00: // ?
case 0x01: // boolean
case 0x02: // integer
case 0x03: // bit std::string
case 0x04: // octec std::string
case 0x0A: // enumerated
case 0x0C: // UTF8string
case 0x13: // printable std::string
case 0x14: // T61 std::string
case 0x16: // IA5String
case 0x17: // UTC time
case 0x18: // Generalized time
case 0x1E: // BMPstring
dwPosition++;
if (!ParseDERSize(pbSignature + dwPosition, dwSize - dwPosition,
dwSizeFound,
dwBytesParsed))
{
dwPositionError = dwPosition;
iTypeError = -7;
return FALSE;
}
dwPosition += dwBytesParsed;
if (!SafeToReadNBytes(dwSize - dwPosition, 0, dwSizeFound))
{
dwPositionError = dwPosition;
iTypeError = -8;
return FALSE;
}
if (iTypeSearch == iType)
{
dwPositionFound = dwPosition;
dwLengthFound = dwSizeFound;
return TRUE;
}
dwPosition += dwSizeFound;
break;
case 0x20: // context specific
case 0x21: // context specific
case 0x23: // context specific
case 0x24: // context specific
case 0x30: // sequence
case 0x31: // set
dwPosition++;
if (!ParseDERSize(pbSignature + dwPosition, dwSize - dwPosition,
dwSizeFound,
dwBytesParsed))
{
dwPositionError = dwPosition;
iTypeError = -9;
return FALSE;
}
dwPosition += dwBytesParsed;
break;
case 0x22: // ?
dwPosition += 2;
break;
default:
dwPositionError = dwPosition;
iTypeError = iType;
return FALSE;
}
}
return FALSE;
}
BOOL GetGeneralizedTimeStamp(
PCMSG_SIGNER_INFO pSignerInfo,
std::string & TimeStamp
) {
BOOL bSucceed = FALSE;
BOOL bReturn = FALSE;
DWORD dwPositionFound = 0;
DWORD dwLengthFound = 0;
DWORD dwPositionError = 0;
DWORD n = 0;
INT iTypeError = 0;
SYSTEMTIME sst, lst;
FILETIME fft, lft;
ULONG wYear = 0;
ULONG wMonth = 0;
ULONG wDay = 0;
ULONG wHour = 0;
ULONG wMinute = 0;
ULONG wSecond = 0;
ULONG wMilliseconds = 0;
for (n = 0; n < pSignerInfo->UnauthAttrs.cAttr; n++)
{
if (!lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId, szOID_RFC3161_counterSign))
{
break;
}
}
if (n >= pSignerInfo->UnauthAttrs.cAttr)
{
return FALSE;
}
bReturn = ParseDERFindType(0x04,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
dwPositionFound,
dwLengthFound,
dwPositionError,
iTypeError
);
if (!bReturn)
{
return FALSE;
}
PBYTE pbOctetString = &pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData[dwPositionFound];
bReturn = ParseDERFindType(0x18, pbOctetString, dwLengthFound,
dwPositionFound,
dwLengthFound,
dwPositionError,
iTypeError
);
if (!bReturn)
{
return FALSE;
}
CHAR szBuffer[256];
strncpy_s(szBuffer, (CHAR *)&(pbOctetString[dwPositionFound]), dwLengthFound);
szBuffer[dwLengthFound] = 0;
_snscanf_s(szBuffer, 256, "%04d%02d%02d%02d%02d%02d.%03dZ",
&wYear,
&wMonth,
&wDay,
&wHour,
&wMinute,
&wSecond,
&wMilliseconds
);
sst.wYear = (WORD)wYear;
sst.wMonth = (WORD)wMonth;
sst.wDay = (WORD)wDay;
sst.wHour = (WORD)wHour;
sst.wMinute = (WORD)wMinute;
sst.wSecond = (WORD)wSecond;
sst.wMilliseconds = (WORD)wMilliseconds;
SystemTimeToFileTime(&sst, &fft);
FileTimeToLocalFileTime(&fft, &lft);
FileTimeToSystemTime(&lft, &lst);
TimeStamp = TimeToString(NULL, &lst);
return TRUE;
}
INT IsCharacterToStrip(
INT Character
) {
return 0 == Character || '\t' == Character || '\n' == Character || '\r' == Character;
}
VOID StripString(
std::string & StrArg
) {
StrArg.erase(remove_if(StrArg.begin(), StrArg.end(), IsCharacterToStrip), StrArg.end());
}
BOOL GetStringFromCertContext(
PCCERT_CONTEXT pCertContext,
DWORD Type,
DWORD Flag,
std::string & String
) {
DWORD dwData = 0x00;
LPSTR pszTempName = NULL;
dwData = CertGetNameStringA(pCertContext, Type, Flag, NULL, NULL, 0);
if (!dwData)
{
CertFreeCertificateContext(pCertContext);
return FALSE;
}
pszTempName = (LPSTR)LocalAlloc(LPTR, dwData * sizeof(CHAR));
if (!pszTempName)
{
CertFreeCertificateContext(pCertContext);
return FALSE;
}
dwData = CertGetNameStringA(pCertContext, Type, Flag, NULL, pszTempName, dwData);
if (!dwData)
{
LocalFree(pszTempName);
return FALSE;
}
String = std::string(pszTempName);
StripString(String);
LocalFree(pszTempName);
return TRUE;
}
BOOL CalculateSignVersion(
DWORD dwVersion,
std::string & Version
) {
switch (dwVersion)
{
case CERT_V1:
Version = "V1";
break;
case CERT_V2:
Version = "V2";
break;
case CERT_V3:
Version = "V3";
break;
default:
Version = "Unknown";
break;
}
StripString(Version);
return TRUE;
}
BOOL CalculateDigestAlgorithm(
LPCSTR pszObjId,
std::string & Algorithm
) {
if (!pszObjId)
{
Algorithm = "Unknown";
}
else if (!strcmp(pszObjId, szOID_OIWSEC_sha1))
{
Algorithm = "SHA1";
}
else if (!strcmp(pszObjId, szOID_RSA_MD5))
{
Algorithm = "MD5";
}
else if (!strcmp(pszObjId, szOID_NIST_sha256))
{
Algorithm = "SHA256";
}
else
{
Algorithm = std::string(pszObjId);
}
StripString(Algorithm);
return TRUE;
}
BOOL CalculateCertAlgorithm(
LPCSTR pszObjId,
std::string & Algorithm
) {
if (!pszObjId)
{
Algorithm = "Unknown";
}
else if (0 == strcmp(pszObjId, szOID_RSA_SHA1RSA))
{
Algorithm = "sha1RSA(RSA)";
}
else if (0 == strcmp(pszObjId, szOID_OIWSEC_sha1RSASign))
{
Algorithm = "sha1RSA(OIW)";
}
else if (0 == strcmp(pszObjId, szOID_RSA_MD5RSA))
{
Algorithm = "md5RSA(RSA)";
}
else if (0 == strcmp(pszObjId, szOID_OIWSEC_md5RSA))
{
Algorithm = "md5RSA(OIW)";
}
else if (0 == strcmp(pszObjId, szOID_RSA_MD2RSA))
{
Algorithm = "md2RSA(RSA)";
}
else if (0 == strcmp(pszObjId, szOID_RSA_SHA256RSA))
{
Algorithm = "sha256RSA(RSA)";
}
else
{
Algorithm = pszObjId;
}
StripString(Algorithm);
return TRUE;
}
#define SHA1LEN 20
#define BUFSIZE 2048
#define MD5LEN 16
BOOL CalculateHashOfBytes(
BYTE *pbBinary,
ALG_ID Algid,
DWORD dwBinary,
std::string & Hash
) {
BOOL bReturn = FALSE;
DWORD dwLastError = 0;
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
DWORD cbHash = 0;
BYTE rgbHash[SHA1LEN] = { 0 };
CHAR hexbyte[3] = { 0 };
CONST CHAR rgbDigits[] = "0123456789abcdef";
std::string CalcHash;
bReturn = CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
if (!bReturn)
{
dwLastError = GetLastError();
return FALSE;
}
bReturn = CryptCreateHash(hProv, Algid, 0, 0, &hHash);
if (!bReturn)
{
dwLastError = GetLastError();
CryptReleaseContext(hProv, 0);
return FALSE;
}
bReturn = CryptHashData(hHash, pbBinary, dwBinary, 0);
if (!bReturn)
{
dwLastError = GetLastError();
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return FALSE;
}
if (CALG_SHA1 == Algid)
{
cbHash = SHA1LEN;
}
else if (CALG_MD5 == Algid)
{
cbHash = MD5LEN;
}
else
{
cbHash = 0;
}
hexbyte[2] = '\0';
bReturn = CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0);
if (!bReturn)
{
dwLastError = GetLastError();
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return FALSE;
}
for (DWORD i = 0; i < cbHash; i++)
{
hexbyte[0] = rgbDigits[rgbHash[i] >> 4];
hexbyte[1] = rgbDigits[rgbHash[i] & 0xf];
CalcHash.append(hexbyte);
}
Hash = CalcHash;
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return TRUE;
}
BOOL CalculateCertCRLpoint(
DWORD cExtensions,
CERT_EXTENSION rgExtensions[],
std::wstring & CRLpoint
) {
BOOL bReturn = FALSE;
BYTE btData[512] = { 0 };
WCHAR csProperty[512] = { 0 };
ULONG ulDataLen = 512;
PCRL_DIST_POINTS_INFO pCRLDistPoint = (PCRL_DIST_POINTS_INFO)btData;
PCRL_DIST_POINT_NAME dpn = NULL;
PCERT_EXTENSION pe = NULL;
CRLpoint.clear();
pe = CertFindExtension(szOID_CRL_DIST_POINTS, cExtensions, rgExtensions);
if (!pe)
{
return FALSE;
}
bReturn = CryptDecodeObject(MY_ENCODING, szOID_CRL_DIST_POINTS,
pe->Value.pbData,
pe->Value.cbData,
CRYPT_DECODE_NOCOPY_FLAG,
pCRLDistPoint, &ulDataLen
);
if (!bReturn)
{
return FALSE;
}
for (ULONG idx = 0; idx < pCRLDistPoint->cDistPoint; idx++)
{
dpn = &pCRLDistPoint->rgDistPoint[idx].DistPointName;
for (ULONG ulAltEntry = 0; ulAltEntry < dpn->FullName.cAltEntry; ulAltEntry++)
{
if (wcslen(csProperty) > 0)
{
wcscat_s(csProperty, 512, L";");
}
wcscat_s(csProperty, 512, dpn->FullName.rgAltEntry[ulAltEntry].pwszURL);
}
}
CRLpoint = csProperty;
return TRUE;
}
BOOL CalculateSignSerial(
BYTE *pbData,
DWORD cbData,
std::string & Serial
) {
BOOL bReturn = FALSE;
DWORD dwSize = 0x400;
BYTE abSerial[0x400] = { 0 };
CHAR NameBuff[0x400] = { 0 };
Serial.clear();
for (UINT uiIter = 0; uiIter < cbData && uiIter < 0x400; uiIter++)
{
abSerial[uiIter] = pbData[cbData - 1 - uiIter];
}
bReturn = CryptBinaryToStringA(abSerial, cbData, CRYPT_STRING_HEX, NameBuff, &dwSize);
if (!bReturn)
{
return FALSE;
}
DWORD dwIter1 = 0;
DWORD dwIter2 = 0;
for (dwIter1 = 0; dwIter1 < dwSize; dwIter1++)
{
if (!isspace(NameBuff[dwIter1]))
{
NameBuff[dwIter2++] = NameBuff[dwIter1];
}
}
NameBuff[dwIter2] = '\0';
Serial = std::string(NameBuff);
StripString(Serial);
return TRUE;
}
// Getting Signer Signature Information.
// If return TRUE, it will continue for caller;
// else, jump out the while loop.
BOOL GetSignerSignatureInfo(
CONST HCERTSTORE hSystemStore,
CONST HCERTSTORE hCertStore,
CONST PCCERT_CONTEXT pOrigContext,
PCCERT_CONTEXT & pCurrContext,
SIGN_NODE_INFO & SignNode
) {
BOOL bReturn = FALSE;
PCERT_INFO pCertInfo = pCurrContext->pCertInfo;
LPCSTR szObjId = NULL;
CERT_NODE_INFO CertNode;
// Get certificate algorithm.
szObjId = pCertInfo->SignatureAlgorithm.pszObjId;
bReturn = CalculateCertAlgorithm(szObjId, CertNode.SignAlgorithm);
// Get certificate serial.
bReturn = CalculateSignSerial(pCertInfo->SerialNumber.pbData,
pCertInfo->SerialNumber.cbData,
CertNode.Serial
);
// Get certificate version.
bReturn = CalculateSignVersion(pCertInfo->dwVersion, CertNode.Version);
// Get certficate subject.
bReturn = GetStringFromCertContext(pCurrContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
0,
CertNode.SubjectName
);
// Get certificate issuer.
bReturn = GetStringFromCertContext(pCurrContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
CERT_NAME_ISSUER_FLAG,
CertNode.IssuerName
);
// Get certificate thumbprint.
bReturn = CalculateHashOfBytes(pCurrContext->pbCertEncoded,
CALG_SHA1,
pCurrContext->cbCertEncoded,
CertNode.Thumbprint
);
// Get certificate CRL point.
bReturn = CalculateCertCRLpoint(pCertInfo->cExtension,
pCertInfo->rgExtension,
CertNode.CRLpoint
);
// Get certificate validity.
CertNode.NotBefore = TimeToString(&pCertInfo->NotBefore);
CertNode.NotAfter = TimeToString(&pCertInfo->NotAfter);