pevFind / pevLib / fileData.h

  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
//          Copyright Billy O'Neal 2011
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)
//
// fileData.h -- The header for one file record. This class
// contains methods for signature verification, timestamp
// comparison, PE file detection, among other things.
#pragma once
#include <string>
#include <vector>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>
#include <cryptopp/sha.h>
#include "utility.h"

class FileData
{
	//Defines for the individual bits in the bitset containing properties for this filedata object
	enum
	{
		ARCHIVE =				0x00000001,  // Standard Win32 Attributes
		COMPRESSED = 			0x00000002,
		DIRECTORY = 			0x00000004,
		FILE =					0x00000008,
		HIDDEN =				0x00000010,
		READONLY = 				0x00000020,
		SYSTEM = 				0x00000040,
		VOLLABEL = 				0x00000080,
		WRITABLE = 				0x00000100,
		REPARSE = 				0x00000200,
		TEMPORARY = 			0x00000400,
		WIN32ENUMD = 			0x00000800,
		// END Standard Win32 Attributes
		// Signature Attributes
		SIGPRESENT = 			0x00001000,
		SIGVALID = 				0x00002000,
		// Executable Attribtutes
		DLL = 					0x00004000,
		DEBUG = 				0x00008000,
		ISPE = 					0x00010000,
		ISNE = 					0x00020000,
		ISLE = 					0x00040000,
		ISMZ = 					0x00080000,
		//Internal state attributes
		//These are used to check if the more time consuming attributes need to be enumerated.
		PEENUMERATED =			0x00100000,
		PECHKSUM =				0x00200000,
		SIGENUMERATED =			0x00400000,
		CRYPTSVCERROR =			0x00800000,
		VERSIONINFOCHECKED =	0x01000000,
		//Looks like I had to add another executable attribute
		PEPLUS =                0x02000000
	};

	mutable DWORD bits; //Container for the bits in the enum above
	                                  //This is mutable because constant functions
	                                  //use the bitset to cache their responses

	//Filename
	std::wstring fileName;
	
	//PE Information
	mutable FILETIME headerTime;
	mutable DWORD headerSum;
	mutable DWORD calcSum;

	//Version information block
	mutable std::vector<BYTE> versionInformationBlock;
	struct LANGANDCODEPAGE {
		WORD wLanguage;
		WORD wCodePage;
		bool operator==(LANGANDCODEPAGE &rhs)
		{
			return wLanguage == rhs.wLanguage && wCodePage == rhs.wCodePage;
		};
		bool operator<(LANGANDCODEPAGE &rhs)
		{
			if (wLanguage != rhs.wLanguage)
				return wLanguage < rhs.wLanguage;
			return wCodePage < rhs.wCodePage;
		};
	};
	mutable std::vector<LANGANDCODEPAGE> versionTranslations;

	//Hex management 
	std::tr1::shared_ptr<std::vector<std::pair<unsigned int, bool> > > hexStorage;

	//Enumeration functions
	//When the results aren't cached in the bitset bits, these functions calculate
	//the correct values and place them into the bitset.
	void initPortableExecutable() const;
	void sigVerify() const;
	void enumVersionInformationBlock() const;

	//Group set functions
	//These functions set a large number of items according to an external data structure
	void setAttributesAccordingToDWORD(DWORD win32Attribs) const;

	//Internal calculation functions
	void inline appendAttributeCharacter(std::wstring &result, const TCHAR attributeCharacter, const size_t curBit) const;
	std::wstring getVersionInformationString(const std::wstring&) const;
	template <typename hashType> std::wstring getHash() const;

	//PE Checksum functions (from Code Project)
	WORD ChkSum(WORD oldChk, USHORT * ptr, DWORD len) const;
	DWORD GetPEChkSum(LPCTSTR filename) const;

	//SFC Safe Mode Fix functions
	static std::vector<std::wstring> sfcFileStrings;
	enum {
		NOT_CHECKED,
		NO_SFCFILES_DLL,
		ENUMERATED
	} SFCStates;
	static unsigned int sfcState;
	void buildSfcList() const;

	inline void setupWin32Attributes() const;
public:
	//Returns the Win32 handle for the file
	HANDLE getFileHandle(bool readOnly = true) const;
	//Construct a fileData record using a Win32FindData structure and a search path.
	FileData(const WIN32_FIND_DATA &rawData, const std::wstring& root);
	//Construct a fileData record using a raw filename
	FileData(const std::wstring &fileNameBuild);

	//Type extensions
	//Used for comparisons and for getting implicit conversions
	bool operator<(FileData& rhs);
	operator std::wstring () const {return getFileName(); };

	//Accessor methods
	//Return information about the current filedata object

	//Size
	inline unsigned __int64 getSize() const;

	//Filename
	inline const std::wstring & getFileName() const;

	//Access times
	inline const FILETIME getLastAccessTime() const;
	inline const FILETIME getLastModTime() const;
	inline const FILETIME getCreationTime() const;
	inline const FILETIME getPEHeaderTime() const;

	//Attributes
	//VFIND style attribute string
	std::wstring getAttributesString() const;
	//PE Attribute string
	std::wstring getPEAttribsString() const;
	//Basic WIN32 Attributes
	inline bool isArchive() const;
	inline bool isCompressed() const;
	inline bool isDirectory() const;
	inline bool isFile() const;
	inline bool isHidden() const;
	inline bool isReadOnly() const;
	inline bool isSystem() const;
	inline bool isVolumeLabel() const;
	inline bool isWritable() const;
	inline bool isTemporary() const;
	inline bool isReparsePoint() const;
	//PE Data Attributes
	inline bool isPE() const;
	inline bool isNE() const;
	inline bool isLE() const;
	inline bool isMZ() const;
	inline bool isPEPlus() const;
	inline bool isStrongExecutable() const;
	inline bool hasAuthenticodeSignature() const;
	inline bool peHeaderChecksumIsValid() const;
	inline bool isDLL() const;
	inline DWORD getPEHeaderCheckSum() const;
	inline DWORD getPECalculatedCheckSum() const;
	void resetPEHeaderCheckSum();
	inline bool peHeaderTimeIsValid() const;
	//Digital Signature Attributes
	inline bool hasValidDigitalSignature() const;
	//Windows File Protection Attributes
	bool isSfcProtected() const;

	//Hashing functions
	std::wstring MD5() const;
	std::wstring SHA1() const;
	std::wstring SHA224() const;
	std::wstring SHA256() const;
	std::wstring SHA384() const;
	std::wstring SHA512() const;

	// Version information functions
	inline std::wstring GetVerCompany() const;
	inline std::wstring GetVerDescription() const;
	inline std::wstring GetVerVersion() const;
	inline std::wstring GetVerProductName() const;
	inline std::wstring GetVerCopyright() const;
	inline std::wstring GetVerOriginalFileName() const;
	inline std::wstring GetVerTrademark() const;
	inline std::wstring GetVerInternalName() const;
	inline std::wstring GetVerComments() const;
	inline std::wstring GetVerPrivateBuild() const;
	inline std::wstring GetVerSpecialBuild() const;
	
	// Logging function
	void write();
};

//
// Inline implementations
//
inline unsigned __int64 FileData::getSize() const
{
	__int64 result;
	WIN32_FILE_ATTRIBUTE_DATA attributeData;
	if(!GetFileAttributesEx(fileName.c_str(), GetFileExInfoStandard, &attributeData))
		return 0;
	if (attributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		return 0;
	result = attributeData.nFileSizeHigh;
	result = result << 32;
	result |= attributeData.nFileSizeLow;
	return result;
}
inline const std::wstring & FileData::getFileName() const
{
	return fileName;
}
inline const FILETIME FileData::getLastAccessTime() const
{
	WIN32_FILE_ATTRIBUTE_DATA attributeData;
	if(!GetFileAttributesEx(fileName.c_str(), GetFileExInfoStandard, &attributeData))
	{
		FILETIME zero;
		zero.dwLowDateTime = 0;
		zero.dwHighDateTime = 0;
		return zero;
	}
	return attributeData.ftLastAccessTime;
}
inline const FILETIME FileData::getLastModTime() const
{
	WIN32_FILE_ATTRIBUTE_DATA attributeData;
	if(!GetFileAttributesEx(fileName.c_str(), GetFileExInfoStandard, &attributeData))
	{
		FILETIME zero;
		zero.dwLowDateTime = 0;
		zero.dwHighDateTime = 0;
		return zero;
	}
	return attributeData.ftLastWriteTime;
}
inline const FILETIME FileData::getCreationTime() const
{
	WIN32_FILE_ATTRIBUTE_DATA attributeData;
	if(!GetFileAttributesEx(fileName.c_str(), GetFileExInfoStandard, &attributeData))
	{
		FILETIME zero;
		zero.dwLowDateTime = 0;
		zero.dwHighDateTime = 0;
		return zero;
	}
	return attributeData.ftCreationTime;
}
inline const FILETIME FileData::getPEHeaderTime() const
{
	initPortableExecutable();
	if (!(bits & ISPE))
	{
		FILETIME zero;
		ZeroMemory(&zero, sizeof(zero));
		return zero;
	}
	return headerTime;
}

inline bool FileData::isArchive() const
{
	setupWin32Attributes();
	return (bits & ARCHIVE) != 0;
}

inline bool FileData::isCompressed() const
{
	setupWin32Attributes();
	return (bits & COMPRESSED) != 0;
}

inline bool FileData::isDirectory() const
{
	setupWin32Attributes();
	return (bits & DIRECTORY) != 0;
}

inline bool FileData::isFile() const
{
	setupWin32Attributes();
	return (bits & FILE) != 0;
}

inline bool FileData::isHidden() const
{
	setupWin32Attributes();
	return (bits & HIDDEN) != 0;
}

inline bool FileData::isReadOnly() const
{
	setupWin32Attributes();
	return (bits & READONLY) != 0;
}

inline bool FileData::isSystem() const
{
	setupWin32Attributes();
	return (bits & SYSTEM) != 0;
}

inline bool FileData::isVolumeLabel() const
{
	setupWin32Attributes();
	return (bits & VOLLABEL) != 0;
}

inline bool FileData::isWritable() const
{
	setupWin32Attributes();
	return (bits & WRITABLE) != 0;
}

inline bool FileData::isTemporary() const
{
	setupWin32Attributes();
	return (bits & TEMPORARY) != 0;
}

inline bool FileData::isReparsePoint() const
{
	setupWin32Attributes();
	return (bits & REPARSE) != 0;
}

inline bool FileData::isPE() const
{
	initPortableExecutable();
	return (bits & ISPE) != 0;
}

inline bool FileData::isPEPlus() const
{
	initPortableExecutable();
	return (bits & PEPLUS) != 0;
}

inline bool FileData::isNE() const
{
	initPortableExecutable();
	return (bits & ISNE) != 0;
}

inline bool FileData::isLE() const
{
	initPortableExecutable();
	return (bits & ISLE) != 0;
}

inline bool FileData::isMZ() const
{
	initPortableExecutable();
	return (bits & ISMZ) != 0;
}

inline bool FileData::isStrongExecutable() const
{
	return isPE() || isNE() || isLE();
}

inline bool FileData::hasValidDigitalSignature() const
{
	if (!isMZ())
		return false;
	if (!(bits & SIGENUMERATED))
		sigVerify();
	return (bits & SIGVALID) != 0;
}

inline bool FileData::hasAuthenticodeSignature() const
{
	initPortableExecutable();
	return (bits & SIGPRESENT) != 0;
}

inline bool FileData::peHeaderChecksumIsValid() const
{
	initPortableExecutable();
	if (headerSum == 0)
		return true;
	return headerSum == getPECalculatedCheckSum();
}

inline bool FileData::isDLL() const
{
	initPortableExecutable();
	return (bits & DLL) != 0;
}

inline DWORD FileData::getPEHeaderCheckSum() const
{
	initPortableExecutable();
	if (!(bits & ISPE))
		return 0;
	return headerSum;
}

inline DWORD FileData::getPECalculatedCheckSum() const
{
	initPortableExecutable();
	if (!(bits & ISPE))
		return 0;
	if (!(bits & PECHKSUM))
		calcSum = GetPEChkSum(fileName.c_str());
	return calcSum;
}

inline bool FileData::peHeaderTimeIsValid() const
{
	SYSTEMTIME curTimeSys;
	GetLocalTime(&curTimeSys);
	FILETIME curTime;
	SystemTimeToFileTime(&curTimeSys,&curTime);
	//One day padding ... one day in 100 nanosecond intervals is 864000000000
	return getPEHeaderTime() < (getLastModTime() + 864000000000ull) && getPEHeaderTime() < (curTime + 864000000000ull);
}

inline std::wstring FileData::GetVerCompany() const
{
	return getVersionInformationString(L"CompanyName");
}
inline std::wstring FileData::GetVerDescription() const
{
	return getVersionInformationString(L"FileDescription");
}
inline std::wstring FileData::GetVerVersion() const
{
	return getVersionInformationString(L"FileVersion");
}
inline std::wstring FileData::GetVerProductName() const
{
	return getVersionInformationString(L"ProductName");
}
inline std::wstring FileData::GetVerCopyright() const
{
	return getVersionInformationString(L"LegalCopyright");
}
inline std::wstring FileData::GetVerOriginalFileName() const
{
	return getVersionInformationString(L"OriginalFilename");
}
inline std::wstring FileData::GetVerTrademark() const
{
	return getVersionInformationString(L"LegalTrademarks");
}
inline std::wstring FileData::GetVerInternalName() const
{
	return getVersionInformationString(L"InternalName");
}
inline std::wstring FileData::GetVerComments() const
{
	return getVersionInformationString(L"Comments");
}
inline std::wstring FileData::GetVerPrivateBuild() const
{
	return getVersionInformationString(L"PrivateBuild");
}
inline std::wstring FileData::GetVerSpecialBuild() const
{
	return getVersionInformationString(L"SpecialBuild");
}


template <typename hashType> 
std::wstring FileData::getHash() const
{
	static const wchar_t constantHexArray[] = L"0123456789ABCDEF";

	HANDLE file;
	disable64.disableFS();
	file = CreateFile(getFileName().c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,NULL,OPEN_EXISTING,NULL,NULL);
	DWORD error = GetLastError();
	disable64.enableFS();
	if (file == INVALID_HANDLE_VALUE)
	{
		if (error == ERROR_LOCK_VIOLATION)
			return L"!HASH: ERROR_LOCK_VIOLATION !!!!";
		return L"!HASH: COULD NOT OPEN FILE !!!!!";
	}
	hashType hash;
	DWORD bytesRead = 0;
	std::vector<unsigned char> buffer;
	DWORD bytesToAttempt = 1024*1024*1024; //1MB
	buffer.resize(bytesToAttempt);
	while (ReadFile(file,&buffer[0],bytesToAttempt,&bytesRead,NULL))
	{
		if (!bytesRead)
		{
			DWORD error = GetLastError();
			if (error && error != ERROR_HANDLE_EOF)
			{
				CloseHandle(file);
				if (error == ERROR_LOCK_VIOLATION)
					return L"!HASH: ERROR_LOCK_VIOLATION !!!!";
				return L"!HASH: COULD NOT OPEN FILE !!!!!";
			}
			break;
		}
		hash.Update(&buffer[0],bytesRead);
	}
	CloseHandle(file);
	std::vector<unsigned char> rawHash;
	rawHash.resize(hash.DigestSize());
	hash.Final(&rawHash[0]);

	std::wstring result;
	result.resize(hash.DigestSize() * 2);
	DWORD len = hash.DigestSize();
	for (unsigned short int idx = 0; idx < len; idx++)
	{
		result[(len*2-1)-2*idx] = constantHexArray[(rawHash[(len-1)-idx] & 0x0F)];
		result[(len*2-1)-(2*idx+1)] = constantHexArray[(rawHash[(len-1)-idx] & 0xF0) >> 4];
	};
	return result;
}

inline void FileData::setupWin32Attributes() const
{
	if (bits & WIN32ENUMD) return;
	setAttributesAccordingToDWORD(GetFileAttributes(fileName.c_str()));
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.