-
Notifications
You must be signed in to change notification settings - Fork 4
/
verify.cpp
350 lines (305 loc) · 10.6 KB
/
verify.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
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <Softpub.h>
#include <wincrypt.h>
#include <wintrust.h>
#include <mscat.h>
#include <versionhelpers.h>
#include <vector>
#pragma comment (lib, "wintrust")
#pragma comment (lib, "Crypt32")
struct SignResult
{
std::wstring HashFinalCert;
std::wstring SubjectName;
};
PVOID m_RedirectorOldValue = NULL;
void PrintLastError(const WCHAR* msg)
{
LPWSTR str = NULL;
if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // or MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US) to use English
(LPWSTR)&str,
0,
NULL))
{
while (wchar_t* pFound = wcsstr(str, L"\r\n"))
{
*pFound = L' ';
*(pFound + 1) = L' ';
}
wprintf_s(L"%s: %s\n", msg, str);
LocalFree(str);
}
}
bool ToggleFileSystemRedirector(bool bEnable, LPCWSTR path = NULL)
{
static bool IsNotRedirected;
static bool IsInit;
static BOOL IsWow;
static WCHAR WinSysDir[MAX_PATH] = L"\0";
static size_t cchWinSysDir;
if (!IsInit)
{
IsInit = true;
IsWow64Process(GetCurrentProcess(), &IsWow);
if (ExpandEnvironmentStrings(L"%SystemRoot%", WinSysDir, MAX_PATH))
{
wcscat_s(WinSysDir, MAX_PATH, L"\\system32");
cchWinSysDir = wcsnlen_s(WinSysDir, MAX_PATH);
}
}
if (!IsWow)
{
return false;
}
if (path != NULL)
{
if (_wcsnicmp(path, WinSysDir, cchWinSysDir) != 0)
{
return false;
}
}
if (bEnable)
{
if (IsNotRedirected)
{
IsNotRedirected = false;
return Wow64RevertWow64FsRedirection(m_RedirectorOldValue);
}
}
else {
if (!IsNotRedirected)
{
IsNotRedirected = true;
return Wow64DisableWow64FsRedirection(&m_RedirectorOldValue);
}
}
return false;
}
std::wstring ExtractStringFromCertificate(PCCERT_CONTEXT pCertificate, DWORD dwType, DWORD dwFlags = 0)
{
DWORD size = CertGetNameString(pCertificate, dwType, dwFlags, NULL, NULL, NULL);
if (size)
{
std::vector<wchar_t> buff(size);
CertGetNameString(pCertificate, dwType, dwFlags, NULL, (LPWSTR)&buff[0], size);
std::wstring result(buff.begin(), buff.end());
return result;
}
return L"";
}
void GetSignerInfo(HANDLE hWVTStateData, SignResult& SignResult)
{
CRYPT_PROVIDER_DATA* pProvData = WTHelperProvDataFromStateData(hWVTStateData);
if (pProvData != NULL)
{
int idxSigner = 0;
CRYPT_PROVIDER_SGNR* pCPSigner = WTHelperGetProvSignerFromChain(pProvData, idxSigner, FALSE, 0);
if (pCPSigner != NULL)
{
PCCERT_CONTEXT pCertificate = CertDuplicateCertificateContext(pCPSigner->pasCertChain->pCert);
if (pCertificate != NULL)
{
DWORD size = 0;
CertGetCertificateContextProperty(pCertificate, CERT_HASH_PROP_ID, NULL, &size);
if (size != 0)
{
std::vector<uint8_t> buff(size);
if (CertGetCertificateContextProperty(pCertificate, CERT_HASH_PROP_ID, &buff.front(), &size))
{
WCHAR pszMemberTag[100] = { 0 };
for (DWORD i = 0; i < size; ++i)
{
wsprintfW(&pszMemberTag[i * 2], L"%02X", buff[i]);
}
SignResult.HashFinalCert = pszMemberTag;
}
}
SignResult.SubjectName = ExtractStringFromCertificate(pCertificate, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0);
CertFreeCertificateContext(pCertificate);
}
}
}
}
bool VerifySignature(LPCWSTR lpFileName, SignResult& signResult)
{
BOOL bRet = FALSE, bIsVerified = FALSE;
WINTRUST_DATA wd = { 0 };
WINTRUST_FILE_INFO wfi = { 0 };
WINTRUST_CATALOG_INFO wci = { 0 };
CATALOG_INFO catalogInfo = { 0 };
WCHAR pszMemberTag[260] = { 0 };
HCATINFO hCatInfoContext = NULL;
LONG iResult = 0;
DRIVER_VER_INFO verInfo = { 0 };
WINTRUST_SIGNATURE_SETTINGS signSettings = { 0 };
HCATADMIN hCatAdmin = NULL;
// redirector OFF
ToggleFileSystemRedirector(false, lpFileName);
HANDLE hFile = CreateFileW(lpFileName,
FILE_READ_ATTRIBUTES | FILE_READ_DATA | STANDARD_RIGHTS_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
// redirector ON
ToggleFileSystemRedirector(true, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
PrintLastError(L"Error in CreateFileW");
return FALSE;
}
GUID DriverGuid = DRIVER_ACTION_VERIFY;
GUID VerifyGuid = WINTRUST_ACTION_GENERIC_VERIFY_V2;
if (IsWindows8OrGreater())
{
CryptCATAdminAcquireContext2(&hCatAdmin, &DriverGuid, BCRYPT_SHA256_ALGORITHM, NULL, 0);
if (hCatAdmin != NULL)
{
wprintf_s(L"Used CryptCATAdminAcquireContext2\n");
}
}
if (hCatAdmin == NULL)
{
if (!CryptCATAdminAcquireContext(&hCatAdmin, &DriverGuid, 0))
{
PrintLastError(L"Error in CryptCATAdminAcquireContext");
return FALSE;
}
}
DWORD dwHashSize = 0;
std::vector<uint8_t> fileHash;
if (IsWindows8OrGreater())
{
bRet = CryptCATAdminCalcHashFromFileHandle2(hCatAdmin, hFile, &dwHashSize, NULL, 0);
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
fileHash.resize(dwHashSize);
bRet = CryptCATAdminCalcHashFromFileHandle2(hCatAdmin, hFile, &dwHashSize, &fileHash.front(), 0);
if (bRet)
{
wprintf_s(L"Used CryptCATAdminCalcHashFromFileHandle2\n");
}
}
}
if (!bRet || dwHashSize == 0)
{
bRet = CryptCATAdminCalcHashFromFileHandle(hFile, &dwHashSize, NULL, 0);
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
fileHash.resize(dwHashSize);
bRet = CryptCATAdminCalcHashFromFileHandle(hFile, &dwHashSize, &fileHash.front(), 0);
}
if (!bRet)
{
PrintLastError(L"Error in CryptCATAdminCalcHashFromFileHandle");
goto Finalize;
}
}
for (DWORD i = 0; i < dwHashSize; ++i)
{
wsprintfW(&pszMemberTag[i * 2], L"%02X", fileHash[i]);
}
hCatInfoContext = CryptCATAdminEnumCatalogFromHash(hCatAdmin, &fileHash.front(), dwHashSize, 0, NULL);
if (hCatInfoContext != NULL)
{
catalogInfo.cbStruct = sizeof(CATALOG_INFO);
if (!CryptCATCatalogInfoFromContext(hCatInfoContext, &catalogInfo, 0))
{
CryptCATAdminReleaseCatalogContext(hCatAdmin, hCatInfoContext, 0);
hCatInfoContext = NULL;
}
}
if (IsWindows8OrGreater())
{
wd.cbStruct = sizeof(WINTRUST_DATA);
}
else {
wd.cbStruct = sizeof(WINTRUST_DATA) - sizeof(void*);
}
wd.dwUIChoice = WTD_UI_NONE;
wd.dwStateAction = WTD_STATEACTION_VERIFY;
wd.fdwRevocationChecks = WTD_REVOKE_NONE;
wd.dwProvFlags = IsWindowsVistaOrGreater() ? WTD_CACHE_ONLY_URL_RETRIEVAL : WTD_REVOCATION_CHECK_NONE;
wd.hWVTStateData = NULL;
wd.pwszURLReference = NULL;
if (hCatInfoContext != NULL)
{
verInfo.cbStruct = sizeof(DRIVER_VER_INFO);
wd.pPolicyCallbackData = &verInfo;
wd.dwUnionChoice = WTD_CHOICE_CATALOG;
wd.pCatalog = &wci;
wd.dwUIContext = WTD_UICONTEXT_EXECUTE;
wci.cbStruct = sizeof(WINTRUST_CATALOG_INFO);
wci.pcwszCatalogFilePath = catalogInfo.wszCatalogFile;
wci.pcwszMemberTag = pszMemberTag;
wci.pcwszMemberFilePath = lpFileName;
wci.hMemberFile = hFile;
wci.pbCalculatedFileHash = &fileHash.front();
wci.cbCalculatedFileHash = dwHashSize;
wci.hCatAdmin = hCatAdmin;
wprintf_s(L"Verified by Catalogue.\n");
}
else {
wd.dwUnionChoice = WTD_CHOICE_FILE;
wd.pFile = &wfi;
wfi.cbStruct = sizeof(WINTRUST_FILE_INFO);
wfi.pcwszFilePath = NULL;
wfi.hFile = hFile;
wfi.pgKnownSubject = NULL;
if (IsWindows8OrGreater())
{
signSettings.cbStruct = sizeof(signSettings);
signSettings.pCryptoPolicy = NULL;
signSettings.dwFlags = WSS_GET_SECONDARY_SIG_COUNT;
wd.pSignatureSettings = &signSettings;
}
wprintf_s(L"Verified Internal.\n");
// To check specific signature index (in double-signature file):
//signSettings.dwFlags = WSS_VERIFY_SPECIFIC;
//signSettings.dwIndex = ... 0, 1
}
iResult = WinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &VerifyGuid, &wd);
wprintf_s(L"WinVerifyTrust returned: 0x%X (err: 0x%X)\n", iResult, GetLastError());
bIsVerified = TRUE;
if (iResult == 0 || iResult == CERT_E_UNTRUSTEDROOT || iResult == CERT_E_EXPIRED)
{
GetSignerInfo(wd.hWVTStateData, signResult);
}
Finalize:
if (hCatAdmin && hCatInfoContext)
CryptCATAdminReleaseCatalogContext(hCatAdmin, hCatInfoContext, 0);
if (bIsVerified)
{
wd.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &VerifyGuid, &wd);
}
if (hCatAdmin)
CryptCATAdminReleaseContext(hCatAdmin, 0);
CloseHandle(hFile);
return iResult == 0 || iResult == CERT_E_UNTRUSTEDROOT || iResult == CERT_E_EXPIRED;
}
bool FileExists(LPCWSTR file)
{
DWORD attr = GetFileAttributesW(file);
return attr != INVALID_FILE_ATTRIBUTES && ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0);
}
int main()
{
setlocale(LC_ALL, "Russian");
SignResult signResult;
LPCWSTR file = L"C:\\Windows\\System32\\ntdll.dll";
if (!FileExists(file))
{
wprintf_s(L"File not found: %s\n", file);
return 1;
}
if (VerifySignature(file, signResult))
{
wprintf_s(L"Cert Hash: %s\n", signResult.HashFinalCert.c_str());
wprintf_s(L"Publisher: %s\n", signResult.SubjectName.c_str());
}
else std::cout << "Signatue: Failed!" << std::endl;
}