-
Notifications
You must be signed in to change notification settings - Fork 17
/
library.cpp
5132 lines (4434 loc) · 136 KB
/
library.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
#define CRYPT_OID_INFO_HAS_EXTRA_FIELDS
#define CMSG_SIGNER_ENCODE_INFO_HAS_CMS_FIELDS
#include <string>
#include <tuple>
#include <algorithm>
#include <map>
#include <sstream>
#include <charconv>
#include <windows.h>
#include <shlobj.h>
#include <wincrypt.h>
#include <wintrust.h>
#include <bcrypt.h>
#include <vector>
#include <variant>
#include <optional>
#pragma comment(lib,"Crypt32.lib")
#pragma comment(lib,"Bcrypt.lib")
#pragma comment(lib,"Ncrypt.lib")
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#include <asn_application.h>
#include <asn_internal.h>
#pragma warning(disable: 4189)
#pragma warning(disable: 4100)
#include "AdES.hpp"
#include "TestTest.h"
#include "SigningCertificateV2.h"
#include "SignaturePolicyIdentifier.h"
#include "CommitmentTypeIndication.h"
#include "CompleteCertificateRefs.h"
#include "CompleteRevocationRefs.h"
#include "SpcIndirectDataContent.h"
#include "SpcIndirectDataContentV2.h"
#include "DigestInfo.h"
#include "SpcPeImageFlags.h"
#include "SpcAttributeTypeAndOptionalValue.h"
#include "SpcPeImageData.h"
#include "SpcSpOpusInfo.h"
#include "SpcPeImageData.h"
//using namespace std;
#include "xml\\xml3all.h"
template <typename T = char, typename T2 = std::vector<T>>
inline bool PutFile(const wchar_t* f, T2& d)
{
HANDLE hX = CreateFile(f, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
if (hX == INVALID_HANDLE_VALUE)
return false;
DWORD A = 0;
WriteFile(hX, d.data(), (DWORD)d.size(), &A, 0);
CloseHandle(hX);
if (A != d.size())
return false;
return true;
}
template <typename T = char>
inline bool LoadFile(const wchar_t* f, std::vector<T>& d)
{
HANDLE hX = CreateFile(f, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
if (hX == INVALID_HANDLE_VALUE)
return false;
LARGE_INTEGER sz = { 0 };
GetFileSizeEx(hX, &sz);
d.resize((size_t)(sz.QuadPart / sizeof(T)));
DWORD A = 0;
ReadFile(hX, d.data(), (DWORD)sz.QuadPart, &A, 0);
CloseHandle(hX);
if (A != sz.QuadPart)
return false;
return true;
}
class OID
{
public:
std::vector<unsigned char>abBinary;
void MakeBase128(unsigned long l, int first) {
if (l > 127) {
MakeBase128(l / 128, 0);
}
l %= 128;
if (first) {
abBinary.push_back((unsigned char)l);
}
else {
abBinary.push_back(0x80 | (unsigned char)l);
}
}
std::string dec(char* d, int nBinary)
{
std::string s;
char fOut[100] = { 0 };
auto pb = d;
int nn = 0;
int ll = 0;
int fOK = 0;
while (nn < nBinary)
{
if (nn == 0)
{
// unsigned char cl = ((*pb & 0xC0) >> 6) & 0x03;
/* switch (cl)
{
}*/
}
else if (nn == 1)
{
if (nBinary - 2 != *pb)
{
return "";
}
}
else if (nn == 2)
{
sprintf_s(fOut, 100, ".%d.%d", *pb / 40, *pb % 40);
s += fOut;
fOK = 1;
ll = 0;
}
else if ((*pb & 0x80) != 0)
{
ll *= 128;
ll += (*pb & 0x7F);
fOK = 0;
}
else
{
ll *= 128;
ll += *pb;
fOK = 1;
sprintf_s(fOut, 100, ".%lu", ll);
s += fOut;
ll = 0;
}
pb++;
nn++;
}
if (!fOK)
{
return "";
}
else
{
return s;
}
}
std::vector<unsigned char> enc(char* oid)
{
bool isRelative = false;
abBinary.clear();
while (true) {
char *p = oid;
unsigned char cl = 0x00;
char *q = NULL;
int nPieces = 1;
int n = 0;
unsigned char b = 0;
unsigned long l = 0;
bool isjoint = false;
// Alternative call: ./oid RELATIVE.2.999
if (_strnicmp(p, "ABSOLUTE.", 9) == 0) {
isRelative = false;
p += 9;
}
else if (_strnicmp(p, "RELATIVE.", 9) == 0) {
isRelative = true;
p += 9;
}
else {
// use the CLI option
// isRelative = false;
}
cl = 0x00; // Class. Always UNIVERSAL (00)
// Tag for Universal Class
if (isRelative) {
cl |= 0x0D;
}
else {
cl |= 0x06;
}
q = p;
nPieces = 1;
while (*p) {
if (*p == '.') {
nPieces++;
}
p++;
}
n = 0;
b = 0;
p = q;
while (n < nPieces) {
q = p;
while (*p) {
if (*p == '.') {
break;
}
p++;
}
l = 0;
if (*p == '.') {
*p = 0;
l = (unsigned long)atoi(q);
q = p + 1;
p = q;
}
else {
l = (unsigned long)atoi(q);
q = p;
}
/* Digit is in l. */
if ((!isRelative) && (n == 0)) {
if (l > 2) {
return {};
}
b = 40 * ((unsigned char)l);
isjoint = l == 2;
}
else if ((!isRelative) && (n == 1)) {
if ((l > 39) && (!isjoint)) {
return {};
}
if (l > 47) {
l += 80;
MakeBase128(l, 1);
}
else {
b += ((unsigned char)l);
abBinary.push_back(b);
}
}
else {
MakeBase128(l, 1);
}
n++;
}
if ((!isRelative) && (n < 2)) {
return {};
}
break;
}
return abBinary;
}
};
class HASH
{
BCRYPT_ALG_HANDLE h;
BCRYPT_HASH_HANDLE ha;
public:
HASH(const wchar_t* alg = BCRYPT_SHA256_ALGORITHM)
{
BCryptOpenAlgorithmProvider(&h, alg, 0, 0);
if (h)
BCryptCreateHash(h, &ha, 0, 0, 0, 0, 0);
}
bool hash(const BYTE* d, DWORD sz)
{
if (!ha)
return false;
auto nt = BCryptHashData(ha, (UCHAR*)d, sz, 0);
return (nt == 0) ? true : false;
}
bool get(std::vector<BYTE>& b)
{
DWORD hl;
ULONG rs;
if (!ha)
return false;
auto nt = BCryptGetProperty(ha, BCRYPT_HASH_LENGTH, (PUCHAR)&hl, sizeof(DWORD), &rs, 0);
if (nt != 0)
return false;
b.resize(hl);
nt = BCryptFinishHash(ha, b.data(), hl, 0);
if (nt != 0)
return false;
return true;
}
~HASH()
{
if (ha)
BCryptDestroyHash(ha);
ha = 0;
if (h)
BCryptCloseAlgorithmProvider(h, 0);
h = 0;
}
};
inline std::vector<char> StripASNTagLength(std::vector<char>& d)
{
std::vector<char> x = d;
// Strip Tag
x.erase(x.begin());
unsigned char d0 = d[0];
if (d0 < 127)
{
x.erase(x.begin());
return x;
}
x.erase(x.begin());
d0 -= 128;
while (d0 > 0)
{
x.erase(x.begin());
d0--;
}
return x;
}
inline void LenPush(unsigned char s, std::vector<char>& x, DWORD sz)
{
x.push_back(s);
if (sz <= 127)
x.push_back((unsigned char)sz);
else
{
if (sz <= 255)
{
x.push_back((unsigned char)0x81);
x.push_back((unsigned char)sz);
}
else
if (sz <= 65535)
{
x.push_back((unsigned char)0x82);
x.push_back(HIBYTE(sz));
x.push_back(LOBYTE(sz));
}
else
{
//*
}
}
}
inline std::vector<char> EncodeCertList(std::vector<PCCERT_CONTEXT>& d)
{
// CertificateValues :: = SEQUENCE OF Certificate
std::vector<char> x;
DWORD sz = 0;
for (auto& dd : d)
{
sz += dd->cbCertEncoded;
}
LenPush(0x30, x, sz);
for (auto& dd : d)
{
std::vector<char> dz(dd->cbCertEncoded);
memcpy(dz.data(), dd->pbCertEncoded, dd->cbCertEncoded);
x.insert(x.end(), dz.begin(), dz.end());
}
return x;
}
inline std::vector<char> EncodeCRLList(std::vector<PCCRL_CONTEXT>& d)
{
/*
TestTest tt = { 0 };
BYTE b1[1];
BYTE b2[1];
INTEGER_t ty1;
INTEGER_t os1;
tt.testdummy1 = &ty1;
tt.testdummy1->size = 1;
tt.testdummy1->buf = b1;
tt.testdummy1->buf[0] = 0x88;
tt.testdummy2 = &ty1;
tt.testdummy2->size = 1;
tt.testdummy2->buf = b2;
tt.testdummy2->buf[0] = 0x77;
// Encode it as DER
std::vector<char> buff3;
auto ec2 = der_encode(&asn_DEF_TestTest,
&tt, [](const void *buffer, size_t size, void *app_key) ->int
{
std::vector<char>* x = (std::vector<char>*)app_key;
auto es = x->size();
x->resize(x->size() + size);
memcpy(x->data() + es, buffer, size);
return 0;
}, (void*)&buff3);
*/
std::vector<char> x;
/*
RevocationValues ::= SEQUENCE {
crlVals [0] SEQUENCE OF CertificateList OPTIONAL,
ocspVals [1] SEQUENCE OF BasicOCSPResponse OPTIONAL,
otherRevVals [2] OtherRevVals OPTIONAL
}
OtherRevVals ::= SEQUENCE {
OtherRevValType OtherRevValType,
OtherRevVals ANY DEFINED BY OtherRevValType
}
OtherRevValType ::= OBJECT IDENTIFIER
*/
DWORD sz = 0;
for (auto& dd : d)
{
sz += dd->cbCrlEncoded;
}
LenPush(0x30, x, sz);
for (auto& dd : d)
{
std::vector<char> dz(dd->cbCrlEncoded);
memcpy(dz.data(), dd->pbCrlEncoded, dd->cbCrlEncoded);
x.insert(x.end(), dz.begin(), dz.end());
}
// x has the seq of CRLs
// We must also put the explicit tag 0xa0 <length>
std::vector<char> x3;
LenPush(0xa0, x3,(DWORD) x.size());
x3.insert(x3.end(), x.begin(), x.end());
std::vector<char> x2;
LenPush(0x30, x2, (DWORD)x3.size());
x2.insert(x2.end(), x3.begin(), x3.end());
return x2;
}
#include <mutex>
#include <queue>
#include <sstream>
#include <map>
#include <thread>
#include <string>
#include <vector>
#include <optional>
#include <variant>
#include <memory>
#include <functional>
namespace PE
{
const std::uint16_t MZ_MAGIC = 0x5A4D;
const std::uint32_t NT_MAGIC = 0x00004550;
const std::uint16_t DIR_SECURITY = 4;
struct BPTR
{
char* p = 0;
size_t sz = 0;
};
struct section {
IMAGE_SECTION_HEADER* sec = 0;
std::uint64_t sectionBase;
BPTR sectionData;
};
#include <ImageHlp.h>
#pragma comment(lib,"imagehlp.lib")
class PE
{
private:
std::vector<char> full;
_IMAGE_DOS_HEADER* dos = 0;
BPTR dos2;
IMAGE_NT_HEADERS32* pnt32 = 0;
IMAGE_NT_HEADERS64* pnt64 = 0;
IMAGE_FILE_HEADER* pfh = 0;
bool Is32 = false;
bool Is64 = false;
char* pnt = 0;
std::vector<section> sections;
// Directories
public:
bool Load(const char* pp, size_t sz)
{
if (!pp || !sz)
return false;
full.reserve(sz * 4);
full.resize(sz);
memcpy(full.data(), pp, sz);
char* p = full.data();
[[maybe_unused]] auto orgp = p;
[[maybe_unused]] auto orgsz = sz;
// DOS header
dos = (_IMAGE_DOS_HEADER*)p;
if (dos->e_magic != MZ_MAGIC)
return false;
// Remaining DOS-related stuff
dos2.sz = dos->e_lfanew - sizeof(_IMAGE_DOS_HEADER);
dos2.p = p + sizeof(_IMAGE_DOS_HEADER);
p += dos->e_lfanew;
sz -= dos->e_lfanew;
// NT header
pnt = p;
pnt32 = (IMAGE_NT_HEADERS32*)p;
pnt64 = (IMAGE_NT_HEADERS64*)p;
if (pnt32->Signature != NT_MAGIC)
return false;
p += 4;
sz -= 4;
pfh = (IMAGE_FILE_HEADER*)p;
p += sizeof(IMAGE_FILE_HEADER);
sz -= sizeof(IMAGE_FILE_HEADER);
if (pfh->Machine == IMAGE_FILE_MACHINE_AMD64)
{
Is64 = true;
Is32 = false;
p += sizeof(IMAGE_OPTIONAL_HEADER64);
sz -= sizeof(IMAGE_OPTIONAL_HEADER64);;
}
else
{
Is64 = false;
Is32 = true;
p += sizeof(IMAGE_OPTIONAL_HEADER);
sz -= sizeof(IMAGE_OPTIONAL_HEADER);
}
// Sections
for (std::uint32_t i = 0; i < pfh->NumberOfSections; i++)
{
section s;
// item
s.sec = (IMAGE_SECTION_HEADER*)p;
p += sizeof(IMAGE_SECTION_HEADER); sz -= sizeof(IMAGE_SECTION_HEADER);
if (Is32)
s.sectionBase = pnt32->OptionalHeader.ImageBase + s.sec->VirtualAddress;
else
s.sectionBase = pnt64->OptionalHeader.ImageBase + s.sec->VirtualAddress;
s.sectionData.sz = s.sec->SizeOfRawData;
s.sectionData.p = orgp + s.sec->PointerToRawData;
sections.push_back(s);
}
return true;
}
bool GetSignature(std::vector<char>& dd)
{
IMAGE_DATA_DIRECTORY expd;
if (Is32)
{
expd = pnt32->OptionalHeader.DataDirectory[DIR_SECURITY];
}
else
{
expd = pnt64->OptionalHeader.DataDirectory[DIR_SECURITY];
}
if (expd.Size == 0)
return false;
dd.resize(expd.Size - 8);
memcpy(dd.data(), full.data() + expd.VirtualAddress + 8, expd.Size - 8);
return true;
}
bool AddSignature(std::vector<char>& dd)
{
std::vector<char> d;
WIN_CERTIFICATE wc = { 0 };
wc.dwLength = dd.size() + 8;
wc.wRevision = WIN_CERT_REVISION_2_0;
wc.wCertificateType = WIN_CERT_TYPE_PKCS_SIGNED_DATA;
d.resize(dd.size() + 8);
memcpy(d.data(), &wc, 8);
memcpy(d.data() + 8, dd.data(), dd.size());
std::wstring TempFile(wchar_t* x, const wchar_t* prf);
wchar_t x[1000] = { 0 };
auto exe = TempFile(x, L"exe");
DeleteFile(x);
PutFile(x, full);
HANDLE hX = CreateFile(x, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
DWORD ddw = 0;
WIN_CERTIFICATE* ws = (WIN_CERTIFICATE*)d.data();
ImageAddCertificate(hX, ws, &ddw);
CloseHandle(hX);
LoadFile(x, full);
DeleteFile(x);
/*
size_t fs = full.size();
if (Is32)
{
pnt32->OptionalHeader.DataDirectory[DIR_SECURITY].Size = d.size();
pnt32->OptionalHeader.DataDirectory[DIR_SECURITY].VirtualAddress = fs;
}
else
{
pnt64->OptionalHeader.DataDirectory[DIR_SECURITY].Size = d.size();
pnt64->OptionalHeader.DataDirectory[DIR_SECURITY].VirtualAddress = fs;
}
full.insert(full.end(), d.begin(), d.end());
*/ return true;
}
bool Save(std::vector<char>& d)
{
d = full;
return true;
}
void GetDataToSign(std::vector<char>& d)
{
if (sections.empty())
return;// duh
//char* a1 = (char*)LoadLibraryEx(L"r:\\test1.exe",0, LOAD_LIBRARY_AS_IMAGE_RESOURCE);
//LOADED_IMAGE* li = ImageLoad("r:\\test1.exe", "");
//ImageUnload(li);
/*HANDLE hY = CreateFile(L"r:\\test1.exe", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
ImageGetDigestStream(hY,
CERT_SECTION_TYPE_ANY
, [](DIGEST_HANDLE refdata,
PBYTE pData,
DWORD dwLength) -> BOOL
{
std::vector<char>* a1 = (std::vector<char>*)refdata;
auto s1 = a1->size();
a1->resize(s1 + dwLength);
memcpy(a1->data() + s1, pData, dwLength);
return true;
}, (DIGEST_HANDLE)& d);
*/
/* d = full;
d.erase(d.begin() + 296, d.begin() + 296 + 8);
d.erase(d.begin() + 216, d.begin() + 216 + 4);
HASH h;
std::vector<BYTE> hh;
h.hash((BYTE*)d.data(), d.size());
h.get(hh);
return;
*/
/*
1. Load the image header into memory.
2. Initialize a hash algorithm context.
3. Hash the image header from its base to immediately before the start of the checksum address, as specified in Optional Header Windows-Specific Fields.
4. Skip over the checksum, which is a 4-byte field.
5. Hash everything from the end of the checksum field to immediately before the start of the Certificate Table entry, as specified in Optional Header Data Directories.
6. Get the Attribute Certificate Table address and size from the Certificate Table entry. For details, see section 5.7 of the PE/COFF specification.
7. Exclude the Certificate Table entry from the calculation and hash everything from the end of the Certificate Table entry to the end of image header, including Section Table (headers).The Certificate Table entry is 8 bytes long, as specified in Optional Header Data Directories.
8. Create a counter called SUM_OF_BYTES_HASHED, which is not part of the signature. Set this counter to the SizeOfHeaders field, as specified in Optional Header Windows-Specific Field.
9. Build a temporary table of pointers to all of the section headers in the image. The NumberOfSections field of COFF File Header indicates how big the table should be. Do not include any section headers in the table whose SizeOfRawData field is zero.
10. Using the PointerToRawData field (offset 20) in the referenced SectionHeader structure as a key, arrange the table's elements in ascending order. In other words, sort the section headers in ascending order according to the disk-file offset of the sections.
11. Walk through the sorted table, load the corresponding section into memory, and hash the entire section. Use the SizeOfRawData field in the SectionHeader structure to determine the amount of data to hash.
12. Add the sections SizeOfRawData value to SUM_OF_BYTES_HASHED.
13. Repeat steps 11 and 12 for all of the sections in the sorted table.
14. Create a value called FILE_SIZE, which is not part of the signature. Set this value to the images file size, acquired from the underlying file system. If FILE_SIZE is greater than SUM_OF_BYTES_HASHED, the file contains extra data that must be added to the hash. This data begins at the SUM_OF_BYTES_HASHED file offset, and its length is:
(File Size) ((Size of AttributeCertificateTable) + SUM_OF_BYTES_HASHED) Note: The size of Attribute Certificate Table is specified in the second ULONG value in the Certificate Table entry (32 bit: offset 132, 64 bit: offset 148) in Optional Header Data Directories.
15. Finalize the hash algorithm context. Note: This procedure uses offset values from the PE/COFF specification, version 8.1 . For authoritative offset values, refer to the most recent version of the PE/COFF specification.
*/
size_t s = 0;
// Sort Sections
std::sort(sections.begin(), sections.end(), [](const section& s1, const section& s2) -> bool
{
if (s1.sec->PointerToRawData < s2.sec->PointerToRawData)
return true;
return false;
});
// Up to where?
size_t BytesUpToLastSection = ((char*)(sections[sections.size() - 1].sec) - full.data()) + sizeof(IMAGE_SECTION_HEADER);
d.resize(BytesUpToLastSection);
memcpy(d.data(), full.data(), BytesUpToLastSection);
// We remove the certificate table entry (8 bytes)
size_t offset = 0;
IMAGE_DATA_DIRECTORY expd;
if (Is32)
{
offset = offsetof(_IMAGE_OPTIONAL_HEADER, DataDirectory[DIR_SECURITY]);
expd = pnt32->OptionalHeader.DataDirectory[DIR_SECURITY];
}
else
{
offset = offsetof(_IMAGE_OPTIONAL_HEADER64, DataDirectory[DIR_SECURITY]);
expd = pnt64->OptionalHeader.DataDirectory[DIR_SECURITY];
}
offset += sizeof(IMAGE_FILE_HEADER) + 4;
offset += pnt - full.data();
d.erase(d.begin() + offset, d.begin() + offset + 8);
// We remove the checksum (4 bytes)
if (Is32)
offset = offsetof(_IMAGE_OPTIONAL_HEADER,CheckSum);
else
offset = offsetof(_IMAGE_OPTIONAL_HEADER64,CheckSum);
offset += sizeof(IMAGE_FILE_HEADER) + 4;
offset += pnt - full.data();
d.erase(d.begin() + offset, d.begin() + offset + 4);
// Counter
size_t SUM_OF_BYTES_HASHED = 0;
if (Is32)
SUM_OF_BYTES_HASHED = pnt32->OptionalHeader.SizeOfHeaders;
else
SUM_OF_BYTES_HASHED = pnt64->OptionalHeader.SizeOfHeaders;
for (auto& ss : sections)
{
if (ss.sectionData.sz == 0)
continue;
s = d.size();
d.resize(d.size() + ss.sectionData.sz);
memcpy(d.data() + s, ss.sectionData.p, ss.sectionData.sz);
SUM_OF_BYTES_HASHED += ss.sec->SizeOfRawData;
}
size_t FILE_SIZE = full.size();
if (FILE_SIZE > SUM_OF_BYTES_HASHED)
{
}
}
};
}
AdES::AdES()
{
}
HRESULT AdES::VerifyB(const char* data, DWORD sz, int sidx, bool Attached, PCCERT_CONTEXT c, bool WasPDF)
{
HRESULT hr = E_FAIL;
bool CTFound = false;
bool MDFound = false;
bool TSFound = false;
bool CHFound = false;
if (!c || !data || !sz)
return E_FAIL;
auto hMsg = CryptMsgOpenToDecode(
MY_ENCODING_TYPE, // Encoding type
Attached ? 0 : CMSG_DETACHED_FLAG, // Flags
0, // Message type (get from message)
0, // Cryptographic provider
NULL, // Recipient information
NULL);
if (hMsg)
{
if (CryptMsgUpdate(
hMsg, // Handle to the message
(BYTE*)data, // Pointer to the encoded BLOB
(DWORD)sz, // Size of the encoded BLOB
TRUE)) // Last call
{
DWORD da = 0;
if (CryptMsgGetParam(hMsg, CMSG_SIGNER_AUTH_ATTR_PARAM, sidx, 0, &da))
{
std::vector<char> ca;
ca.resize(da);
if (CryptMsgGetParam(hMsg, CMSG_SIGNER_AUTH_ATTR_PARAM, sidx, ca.data(), &da))
{
CRYPT_ATTRIBUTES* si = (CRYPT_ATTRIBUTES*)ca.data();
for (DWORD g = 0; g < si->cAttr; g++)
{
CRYPT_ATTRIBUTE& attr = si->rgAttr[g];
if (strcmp(attr.pszObjId, "1.2.840.113549.1.9.3") == 0) // Content Type
{
CTFound = true;
}
if (strcmp(attr.pszObjId, "1.2.840.113549.1.9.4") == 0) // Digest
{
MDFound = true;
}
if (strcmp(attr.pszObjId, "1.2.840.113549.1.9.5") == 0 && attr.cValue == 1) // Timestamp
{
std::vector<char> bu(10000);
DWORD xd = 10000;
if (CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, szOID_RSA_signingTime, attr.rgValue[0].pbData, attr.rgValue[0].cbData, 0, 0, (void*)bu.data(), &xd))
{
TSFound = true;
}
}
if (strcmp(attr.pszObjId, "1.2.840.113549.1.9.16.2.47") == 0 && attr.cValue == 1) // ESSCertificateV2
{
SigningCertificateV2* v = 0;
auto rval = asn_DEF_SigningCertificateV2.ber_decoder(0,
&asn_DEF_SigningCertificateV2,
(void **)&v,
attr.rgValue[0].pbData, attr.rgValue[0].cbData, 0);
if (v)
{
// Check the certificate hash
std::vector<BYTE> dhash;
HASH hash(BCRYPT_SHA256_ALGORITHM);
hash.hash(c->pbCertEncoded, c->cbCertEncoded);
hash.get(dhash);
if (v->certs.list.count == 1 && v->certs.list.array[0]->certHash.size == (int)dhash.size())
{
if (memcmp(v->certs.list.array[0]->certHash.buf, dhash.data(), dhash.size()) == 0)
CHFound = true;
}
asn_DEF_SigningCertificateV2.free_struct(&asn_DEF_SigningCertificateV2, v, 0);
v = 0;
}
}
}
}
}
}
}
if (hMsg)
{
CryptMsgClose(hMsg);
hMsg = 0;
}
if (WasPDF)
TSFound = true;
if (CTFound && MDFound && TSFound && CHFound)
hr = S_OK;
return hr;
}
HRESULT AdES::VerifyU(const char* data, DWORD sz, bool Attached, int TSServerSignIndex)
{
HRESULT hr = E_FAIL;
auto hMsg = CryptMsgOpenToDecode(MY_ENCODING_TYPE,Attached ? 0 : CMSG_DETACHED_FLAG,0,0,0,0);
if (hMsg)
{
if (CryptMsgUpdate(hMsg, (BYTE*)data, (DWORD)sz, TRUE))
{
std::vector<char> ca;
DWORD da = 0;
if (CryptMsgGetParam(hMsg, CMSG_SIGNER_UNAUTH_ATTR_PARAM, TSServerSignIndex, 0, &da))
{
ca.resize(da);
if (CryptMsgGetParam(hMsg, CMSG_SIGNER_UNAUTH_ATTR_PARAM, TSServerSignIndex, ca.data(), &da))
{
}
}
}
}
return hr;
}
HRESULT AdES::VerifyT(const char* data, DWORD sz, PCCERT_CONTEXT* pX, bool Attached, int TSServerSignIndex, FILETIME* ft, PCRYPT_TIMESTAMP_CONTEXT* ptc)
{
HRESULT hr = E_FAIL;
auto hMsg = CryptMsgOpenToDecode(
MY_ENCODING_TYPE, // Encoding type
Attached ? 0 : CMSG_DETACHED_FLAG, // Flags
0, // Message type (get from message)
0, // Cryptographic provider
NULL, // Recipient information
NULL);
if (hMsg)
{
if (CryptMsgUpdate(
hMsg, // Handle to the message
(BYTE*)data, // Pointer to the encoded BLOB
(DWORD)sz, // Size of the encoded BLOB
TRUE)) // Last call
{
std::vector<char> ca;
DWORD da = 0;
if (CryptMsgGetParam(
hMsg, // Handle to the message
CMSG_ENCRYPTED_DIGEST, // Parameter type
TSServerSignIndex, // Index
NULL, // Address for returned information
&da)) // Size of the returned information
{
std::vector<char> EH(da);
if (CryptMsgGetParam(
hMsg, // Handle to the message
CMSG_ENCRYPTED_DIGEST, // Parameter type
TSServerSignIndex, // Index
(BYTE*)EH.data(), // Address for returned information
&da)) // Size of the returned information
{
EH.resize(da);
if (CryptMsgGetParam(hMsg, CMSG_SIGNER_UNAUTH_ATTR_PARAM, TSServerSignIndex, 0, &da))
{
ca.resize(da);
if (CryptMsgGetParam(hMsg, CMSG_SIGNER_UNAUTH_ATTR_PARAM, TSServerSignIndex, ca.data(), &da))
{
CRYPT_ATTRIBUTES* si = (CRYPT_ATTRIBUTES*)ca.data();
if (si->cAttr >= 1)
{
for (DWORD a = 0; a < si->cAttr; a++)
{
if (strcmp(si->rgAttr[a].pszObjId, "1.2.840.113549.1.9.16.2.14") == 0 && si->rgAttr[a].cValue == 1)
{
auto& v = si->rgAttr[a].rgValue[0];
// It is already decoded
PCRYPT_TIMESTAMP_CONTEXT re = 0;
BYTE* b = (BYTE*)v.pbData;
auto sz3 = v.cbData;
auto res = CryptVerifyTimeStampSignature(b, sz3, (BYTE*)EH.data(), (DWORD)EH.size(), 0, &re, pX, 0);
if (!res)
hr = E_FAIL;
else
{
if (ft)
*ft = re->pTimeStamp->ftTime;
if (ptc)
*ptc = re;
else
CryptMemFree(re);
hr = S_OK;
break;
}
}
}
}
}
}
}
}
}
}
if (hMsg)
{
CryptMsgClose(hMsg);
hMsg = 0;
}