forked from Sysinternals/SysmonCommon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventsCommon.cpp
3372 lines (2728 loc) · 95.7 KB
/
eventsCommon.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
/*
SysmonCommon
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//====================================================================
//
// EventsCommon.c
//
// Implements event handling depending of windows versions
//
//====================================================================
#include "stdafx.h"
#include "rules.h"
#include "eventsCommon.h"
#include "printfFormat.h"
#if defined _WIN64 || defined _WIN32
#include <Objbase.h>
#include <WinEvt.h>
#include <VersionHelper.h>
#include "dll.h"
#include "events.h"
extern PFN_EVENT_WRITE PfnEventWrite;
BOOLEAN bPreVista = FALSE;
#elif defined __linux__
#include <pthread.h>
#include "linuxHelpers.h"
#include <sys/time.h>
#include <pwd.h>
#include <syslog.h>
extern "C" {
#include "outputxml.h"
}
extern "C" {
VOID syslogHelper( int priority, const char* fmt, char* msg );
}
// define Linux as being 'pre-Vista' as it helps without event output
BOOLEAN bPreVista = TRUE;
#endif
//
// Command line can be up to 0x7FFE but event log strings have a limit
// of 31839 characters (https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-reporteventa)
//
#define PATH_MAX_SIZE 31839
#define MAX_EVENT_PACKET_SIZE 62000
REGHANDLE g_Event = 0;
HANDLE g_hEventSource = NULL;
BOOLEAN bInitialized = FALSE;
ULONG machineId = 0;
//--------------------------------------------------------------------
//
// Ulong64ToString
//
// Write a Ulong64 as a string.
//
//--------------------------------------------------------------------
BOOLEAN Ulong64ToString(
PTCHAR out,
DWORD size,
ULONG64 value
)
{
if (out == NULL) {
return FALSE;
}
_stprintf_s( out, size, _T( "" PRINTF_ULONG64_FS ), value );
return TRUE;
}
//--------------------------------------------------------------------
//
// LogonIdToString
//
// Write a LogonId as a string.
//
//--------------------------------------------------------------------
BOOLEAN LogonIdToString(
PTCHAR out,
DWORD size,
ULONG64 logonId
)
{
if (out == NULL) {
return FALSE;
}
#if defined _WIN64 || defined _WIN32
_stprintf_s( out, size, _T("0x%I64x"), logonId );
#elif defined __linux__
// On Linux, the low part of the LUID is the Linux logon Id
_stprintf_s( out, size, "%ld", logonId & 0xffff );
#endif
return TRUE;
}
//--------------------------------------------------------------------
//
// GenerateUniqueId
//
// Get a unique GUID for this event on this machine
// Structure:
// - machineID (last part of the machine account SID)
// - Time of the event in seconds
// - TokenId (unique object ID) | type of the object
//
//--------------------------------------------------------------------
GUID GenerateUniqueId(
_In_ PLARGE_INTEGER timestamp,
_In_ ULONGLONG ProcessStartKey,
OBJECT_TYPE type
)
{
GUID result = {0,};
DWORD seconds = 0;
PBYTE pResult = (PBYTE)&result;
#if defined _WIN64 || defined _WIN32
RtlTimeToSecondsSince1970( timestamp, &seconds );
#elif defined __linux__
// timestamp in 100ns intervals since epoch
seconds = LargeTimeToSeconds( timestamp );
#endif
*(DWORD*) pResult = machineId;
pResult += sizeof(DWORD);
*(DWORD*) pResult = seconds;
pResult += sizeof(DWORD);
*(DWORD64*) pResult = ProcessStartKey;
return result;
}
//--------------------------------------------------------------------
//
// ProcessCache class implementation
//
// Static class that caches processes for faster lookup. Does not
// require explicit initialisation. Has locking and unlocking
// functions to guard access to it and the objects returned by it.
//
//--------------------------------------------------------------------
//--------------------------------------------------------------------
//
// ProcessCache::ProcessGet
//
// Fetch a process cache entry.
//
//--------------------------------------------------------------------
PPROCESS_CACHE_INFORMATION ProcessCache::ProcessGet(
_In_ DWORD ProcessId,
_In_ const PLARGE_INTEGER time,
_In_opt_ PVOID ProcessObject
)
{
PPROCESS_CACHE_INFORMATION ret = NULL;
LockCache();
//
// search for process ID in unordered map
//
auto processEntry = _processCache.find( ProcessId );
if( processEntry != _processCache.end() ) {
//
// iterate over list items for this process ID
//
for( auto ¤t : processEntry->second ) {
// #444 If a process object was provided, check for a match against this in addition to the PID
if( (ProcessObject == NULL) ||
(current.data->m_ProcessObject == NULL) ||
(current.data->m_ProcessObject == ProcessObject) ) {
if( time != NULL ) {
//
// If I didn't select the entry or the time of the event was
// before the process was removed
//
if( ret == NULL ) {
//
// Only if time makes sense, else we will select a wrong old entry
// and the latest will be skipped
//
if( (current.removedTime.QuadPart == 0 || // If the current entry is still open
(ULONG64)time->QuadPart < (ULONG64)(current.removedTime.QuadPart + NT_500_MS)) && // Or it has now terminated but terminated after the process creation time
// the half second buffer is because we have seen network events appear marginally later than the process terminate event
(time->QuadPart >= current.data->m_CreateTime.QuadPart) ) { // #444. We validate the end of the time window but not the start..
ret = ¤t;
}
} else if( current.removedTime.QuadPart != 0 && // The process has terminadumpted
(ULONG64)time->QuadPart < (ULONG64)current.removedTime.QuadPart && // The process terminated after our process creation time
time->QuadPart >= current.data->m_CreateTime.QuadPart && // #444 Validate the start of the time window too
(ret->removedTime.QuadPart == 0 || // we are either superseding a candidate that is still open
(ULONG64)ret->removedTime.QuadPart > ( ULONG64 )current.removedTime.QuadPart) ) { // or we are superseding a process with a wider windows than the current candidate
ret = ¤t;
}
} else {
//
// Select the latest available;
//
if( ret == NULL ) {
ret = ¤t;
} else if( (current.removedTime.QuadPart == 0) ||
((ret->removedTime.QuadPart != 0) &&
((ULONG64)ret->removedTime.QuadPart < (ULONG64)current.removedTime.QuadPart)) ) {
ret = ¤t;
}
break;
}
}
}
}
UnlockCache();
return ret;
}
//--------------------------------------------------------------------
//
// ProcessCache::RemoveEntries
//
// Remove all entries from the cache.
//
//--------------------------------------------------------------------
void ProcessCache::RemoveEntries()
{
LockCache();
//
// for every entry in the cache (removing after each iteration)
//
for( auto cacheEntry = _processCache.begin(); cacheEntry != _processCache.end(); cacheEntry = _processCache.erase( cacheEntry ) ) {
//
// iterate over list items for this process ID
//
for( auto ¤t : cacheEntry->second ) {
free( current.data );
}
}
UnlockCache();
}
//--------------------------------------------------------------------
//
// ProcessCache::ProcessRemove
//
// Mark an entry as expired; calls PurgeExpired() to remove entries
// that were marked as expired further back than the grace period.
//
//--------------------------------------------------------------------
void ProcessCache::ProcessRemove(
_In_ DWORD ProcessId,
_In_ GUID* ProcessGuid,
_In_opt_ PLARGE_INTEGER EventTime
)
{
LARGE_INTEGER currentTime;
if( EventTime == NULL ) {
GetSystemTimeAsLargeInteger( ¤tTime );
EventTime = ¤tTime;
}
LockCache();
//
// search for process ID in unordered map
//
auto processEntry = _processCache.find( ProcessId );
if( processEntry != _processCache.end() ) {
//
// iterate over list items for this process ID
//
for( auto ¤t : processEntry->second) {
//
// Mark the entry as removed, but keep it around in case
// we get delayed ETW events that reference it
//
current.removedTime.QuadPart = EventTime->QuadPart;
}
_expiringProcesses.emplace( EventTime->QuadPart, ProcessId );
}
PurgeExpired( EventTime );
UnlockCache();
}
//--------------------------------------------------------------------
//
// ProcessCache::PurgeExpired
//
// Remove expired entries from the cache that are older than the grace
// period.
//
//--------------------------------------------------------------------
void ProcessCache::PurgeExpired( PLARGE_INTEGER EventTime )
{
while( !_expiringProcesses.empty() && Expired( _expiringProcesses.top().time, EventTime->QuadPart ) ) {
CacheEntryToExpire oldest = _expiringProcesses.top();
_expiringProcesses.pop();
auto processes = _processCache.find( oldest.pid );
if( processes != _processCache.end() ) {
for( auto &process : processes->second ) {
free( process.data );
}
_processCache.erase( oldest.pid );
}
}
}
//--------------------------------------------------------------------
//
// ProcessCache::ProcessAdd
//
// Add a process record to the process cache.
//
//--------------------------------------------------------------------
void ProcessCache::ProcessAdd(
_In_ GUID uniqueProcessGUID,
_In_ PSYSMON_EVENT_HEADER event
)
{
PROCESS_CACHE_INFORMATION cacheEntry;
PSYSMON_PROCESS_CREATE data;
SIZE_T dataSize;
data = &event->m_EventBody.m_ProcessCreateEvent;
dataSize = event->m_EventSize - offsetof( SYSMON_EVENT_HEADER, m_EventBody );
cacheEntry.data = static_cast<PSYSMON_PROCESS_CREATE>( malloc( dataSize ) );
if( cacheEntry.data != NULL ) {
LockCache();
memcpy( cacheEntry.data, data, dataSize );
cacheEntry.uniqueProcessGUID = uniqueProcessGUID;
cacheEntry.removedTime.QuadPart = 0;
cacheEntry.dnsQueryCache = {};
ProcessRemove( data->m_ProcessId, &uniqueProcessGUID, NULL );
auto processEntry = _processCache.find( data->m_ProcessId );
if( processEntry == _processCache.end() ) {
_processCache.emplace( data->m_ProcessId, CacheEntries{ cacheEntry } );
} else {
processEntry->second.push_front( cacheEntry );
}
UnlockCache();
}
}
//--------------------------------------------------------------------
//
// ProcessCache::Empty
//
// Reports if the process cache is empty or not.
//
//--------------------------------------------------------------------
bool ProcessCache::Empty()
{
LockCache();
bool ret = _processCache.empty();
UnlockCache();
return ret;
}
#if defined _WIN64 || defined _WIN32
//--------------------------------------------------------------------
//
// ProcessCache::DnsEntryAdd
//
// Adds a DNS entry to a process in the cache.
//
//--------------------------------------------------------------------
bool ProcessCache::DnsEntryAdd( DWORD ProcessId, PDNS_QUERY_DATA DnsEntry )
{
LockCache();
auto processInfo = ProcessGet( ProcessId, NULL, NULL );
if( processInfo != NULL ) {
for( auto &cachedQuery : processInfo->dnsQueryCache) {
if( !_tcsicmp( cachedQuery.QueryName, DnsEntry->QueryName ) &&
!_tcsicmp( cachedQuery.QueryResult, DnsEntry->QueryResult ) &&
!_tcsicmp( cachedQuery.QueryStatus, DnsEntry->QueryStatus ) ) {
UnlockCache();
return false;
}
}
//
// Add to the cache
//
if( processInfo->dnsQueryCache.size() == DNS_CACHE_LIMIT ) {
processInfo->dnsQueryCache.pop_back();
}
// Performing a copy here, just in case.
processInfo->dnsQueryCache.push_front( *DnsEntry );
}
UnlockCache();
return true;
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
extern HANDLE g_hDriver;
#ifdef __cplusplus
}
#endif
//
// Default values
//
TCHAR DefaultString[] = _T("-");
GUID DefaultGuid = {0,};
//--------------------------------------------------------------------
//
// EventDataDescCreateS
//
// Helper function for EventDataDescCreate handling with strings
//
//--------------------------------------------------------------------
VOID EventDataDescCreateS(
_In_ PEVENT_DATA_DESCRIPTOR Data,
_In_ const TCHAR* String
)
{
if( String == NULL ) {
String = _T("NULL");
}
EventDataDescCreate( Data, (PVOID)String, (ULONG)((_tcslen(String) + 1) * sizeof(TCHAR)) );
}
//--------------------------------------------------------------------
//
// GenerateUniquePGUID
//
// Generate a unique GUID for the process
//
//--------------------------------------------------------------------
void GenerateUniquePGUID(
_In_ GUID* pguid,
_In_ PSYSMON_EVENT_HEADER event,
_In_ BOOLEAN Cache
)
{
GUID g;
PSYSMON_PROCESS_CREATE data;
data = &event->m_EventBody.m_ProcessCreateEvent;
g = GenerateUniqueId( &data->m_CreateTime, data->m_ProcessKey, Process );
// Update the cache
if( Cache ) {
ProcessCache::Instance().ProcessAdd( g, event );
}
*pguid = g;
}
//--------------------------------------------------------------------
//
// FetchUniquePGUID
//
// Fetch a unique GUID for the process from the cache
//
//--------------------------------------------------------------------
void FetchUniquePGUID(
_Out_ GUID* pguid,
_In_ ULONG ProcessId,
_In_ BOOLEAN UpdateCache,
_In_ PLARGE_INTEGER time
)
{
PPROCESS_CACHE_INFORMATION cache;
UCHAR buffer[16386];
BOOL result;
PSYSMON_EVENT_HEADER event;
ProcessCache::Instance().LockCache();
cache = ProcessCache::Instance().ProcessGet( ProcessId, time, NULL );
if( cache ) {
*pguid = cache->uniqueProcessGUID;
ProcessCache::Instance().UnlockCache();
} else {
ProcessCache::Instance().UnlockCache();
#if defined _WIN64 || defined _WIN32
DWORD bytesReturned = 1;
UPDATE_CACHE cacheRequest;
cacheRequest.ProcessId = ProcessId;
cacheRequest.UpdateCache = UpdateCache;
result = DeviceIoControl( g_hDriver, IOCTL_SYSMON_PROCESS_CACHE, &cacheRequest, sizeof(cacheRequest),
buffer, sizeof(buffer), &bytesReturned, NULL );
if( result ) {
D_ASSERT(bytesReturned > 0);
event = (PSYSMON_EVENT_HEADER) buffer;
GenerateUniquePGUID( pguid, event, UpdateCache );
} else {
DBG_MODE( _tprintf( _T("PROCESS_CACHE_REQUEST failed with %d\n"), GetLastError() ) );
}
#elif defined __linux__
result = GetProcess( (PSYSMON_EVENT_HEADER) buffer, sizeof(buffer), ProcessId );
if( result ) {
event = (PSYSMON_EVENT_HEADER) buffer;
GenerateUniquePGUID( pguid, event, UpdateCache );
} else {
DBG_MODE( _tprintf( _T("PROCESS_CACHE_REQUEST failed\n") ) );
}
#endif
}
}
//--------------------------------------------------------------------
//
// GenerateUniqueSGUID
//
// Generate a unique GUID for the session
//
//--------------------------------------------------------------------
void GenerateUniqueSGUID(
_In_ GUID* sguid,
_In_ LUID* authenticationId
)
{
GUID g;
LARGE_INTEGER timestamp = {0,};
#if defined _WIN64 || defined _WIN32
NTSTATUS status;
PSECURITY_LOGON_SESSION_DATA sessionData;
status = LsaGetLogonSessionData( authenticationId, &sessionData );
if (NT_SUCCESS(status))
{
timestamp = sessionData->LogonTime;
LsaFreeReturnBuffer( sessionData );
}
#elif defined __linux__
timestamp = GetLogonTime( authenticationId );
#endif
g = GenerateUniqueId( ×tamp, * (PULONGLONG) authenticationId, Session );
*sguid = g;
}
//--------------------------------------------------------------------
//
// RefreshProcessCache
//
// Refresh the process cache from the current process list
//
//--------------------------------------------------------------------
VOID RefreshProcessCache(
VOID
)
{
PDWORD processList = NULL;
GUID tmp;
DWORD i;
// 16384 entries should be large enough for most systems, but still only uses
// 64KB of RAM.
DWORD processSize = 16384 * sizeof( DWORD );
DWORD processUsed = 0;
for( i = 0; i < 5; i++ ) {
processList = (PDWORD)malloc( processSize );
if( processList == NULL ) {
PrintErrorEx( (PTCHAR)_T( __FUNCTION__ ), 0, (PTCHAR)_T( "Out of memory condition" ) );
return;
}
// Check that EnumProcesses succeeds AND that we have all the processes available
// If EnumProcesses fails, for simplicity handle it in the same way as if the buffer
// is too small. The extra memory usage is inconsequential - total memory usage would
// reach 128KB if it fails 5 times in a row.
if( EnumProcesses( processList, processSize, &processUsed ) && processUsed < processSize ) {
break;
}
// If 16K entries is too small, we need to jump a reasonable amount to ensure
// we find a suitable size before the loop expires.
processSize += 4096 * sizeof( DWORD );
free( processList );
processList = NULL;
}
if( processList == NULL ) {
PrintErrorEx( (PTCHAR)_T( __FUNCTION__ ), 0, (PTCHAR)_T( "Failed to udpate the process cache on start" ) );
return;
}
//
// Fetch each process GUID to update the cache
//
for( i = 0; i < (processUsed / sizeof( DWORD )); i++ ) {
FetchUniquePGUID( &tmp, processList[i], TRUE, NULL );
}
free( processList );
}
//--------------------------------------------------------------------
//
// TimestampFormat
//
// Format a timestamp to local time for event reporting
//
//--------------------------------------------------------------------
VOID TimestampFormat(
_Out_ PTCHAR buffer,
_In_ SIZE_T bufferCount,
_In_ PLARGE_INTEGER timestamp
)
{
#if defined _WIN64 || defined _WIN32
SYSTEMTIME timeFields;
FILETIME fileTime;
fileTime.dwLowDateTime = timestamp->LowPart;
fileTime.dwHighDateTime = (DWORD)timestamp->HighPart;
if( FileTimeToSystemTime( &fileTime, &timeFields ) ) {
_stprintf_s( buffer, bufferCount, _T("%04u-%02u-%02u %02u:%02u:%02u.%03u"),
timeFields.wYear, timeFields.wMonth, timeFields.wDay,
timeFields.wHour, timeFields.wMinute, timeFields.wSecond, timeFields.wMilliseconds );
} else {
_stprintf_s( buffer, bufferCount, _T("Incorrect filetime: 0x%I64x"),
timestamp->QuadPart );
}
#elif defined __linux__
// time in 100ns intervals since epoch
struct tm timeFields;
time_t fileTime = 0;
// timestamp in 100ns intervals since epoch
fileTime = LargeTimeToSeconds( timestamp );
if ( gmtime_r(&fileTime, &timeFields) ) {
snprintf( buffer, bufferCount, "%04u-%02u-%02u %02u:%02u:%02u.%03u",
timeFields.tm_year + 1900, timeFields.tm_mon + 1, timeFields.tm_mday,
timeFields.tm_hour, timeFields.tm_min, timeFields.tm_sec,
LargeTimeMilliseconds( timestamp ));
} else {
_stprintf_s( buffer, bufferCount, _T("Incorrect filetime: 0x%" PRIx64),
timestamp->QuadPart );
}
#endif
}
//--------------------------------------------------------------------
//
// ExtGetPtr
//
// Get a pointer to the target extension of the event
//
//--------------------------------------------------------------------
PVOID ExtGetPtr(
_In_ PULONG extensionsSizes,
_In_ PVOID extensions,
_In_ ULONG index,
_Out_ PULONG retSize
)
{
ULONG i, size;
PBYTE ptr = (PBYTE) extensions;
size = extensionsSizes[index];
if( retSize ) {
*retSize = size;
}
if( size == 0 ) {
return NULL;
}
for( i = 0; i < index; i++ ) {
ptr += extensionsSizes[i];
}
return ptr;
}
//--------------------------------------------------------------------
//
// ExtGetEscapeString
//
// Extract a string from an extension
//
//--------------------------------------------------------------------
PTCHAR ExtGetEscapeString(
_In_ PULONG extensionsSizes,
_In_ PVOID extensions,
_In_ ULONG index
)
{
ULONG size, i, escapes = 0;
PVOID ptr;
PTCHAR str, strPtr;
ptr = ExtGetPtr( extensionsSizes, extensions, index, &size );
if( ptr == NULL || size < sizeof( TCHAR ) ) {
return NULL;
}
if( (size % sizeof( TCHAR )) != 0 ) {
size--;
}
// Count % characters
for (i = 0; i < size / sizeof(TCHAR); i++) {
if( ((PTCHAR) ptr)[i] == '%' )
escapes++;
}
str = strPtr = (PTCHAR) malloc( size + (escapes * sizeof( TCHAR )) + sizeof( TCHAR ) );
if( str != NULL ) {
size /= sizeof( TCHAR );
for( i = 0; i < size; i++ ) {
*strPtr = ((PTCHAR) ptr)[i];
strPtr++;
if( ((PTCHAR) ptr)[i] == '%' ) {
*strPtr = '%';
strPtr++;
}
}
*strPtr = 0;
}
return str;
}
//--------------------------------------------------------------------
//
// ExtGetAnsiString
//
// Extract a string from an extension
//
//--------------------------------------------------------------------
PWCHAR ExtGetAnsiString(
_In_ PULONG extensionsSizes,
_In_ PVOID extensions,
_In_ ULONG index,
_In_ PULONG size
)
{
ULONG origSize;
PVOID ptr;
PWCHAR str;
ptr = ExtGetPtr( extensionsSizes, extensions, index, &origSize );
if( ptr == NULL || origSize < sizeof( TCHAR ) ) {
return NULL;
}
#if defined _WIN64 || defined _WIN32
*size = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, (LPCSTR) ptr, origSize, NULL, 0 );
#elif defined __linux__
*size = UTF8toUTF16( NULL, (LPCSTR) ptr, 0 );
#endif
if( *size == 0 ) {
return NULL;
}
*size = *size * sizeof( WCHAR );
str = (PWCHAR)malloc( *size );
if( str != NULL ) {
#if defined _WIN64 || defined _WIN32
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, (LPCSTR)ptr, origSize, str, *size );
#elif defined __linux__
UTF8toUTF16( str, (LPCSTR)ptr, *size );
#endif
}
return str;
}
//--------------------------------------------------------------------
//
// ExtGetString
//
// Extract a string from an extension
//
//--------------------------------------------------------------------
PTCHAR ExtGetString(
_In_ PULONG extensionsSizes,
_In_ PVOID extensions,
_In_ ULONG index
)
{
ULONG size;
PVOID ptr;
PTCHAR str;
ptr = ExtGetPtr( extensionsSizes, extensions, index, &size );
if( ptr == NULL || size < sizeof(TCHAR) ) {
return NULL;
}
if( (size % sizeof(TCHAR)) != 0 ) {
size--;
}
str = (PTCHAR) malloc( size + sizeof(TCHAR) );
if( str != NULL ) {
size /= sizeof(TCHAR);
_tcsncpy( str, (PTCHAR) ptr, size );
str[size] = 0;
}
return str;
}
//--------------------------------------------------------------------
//
// IsNullTerminated
//
// Check if the string is null terminated
//
//--------------------------------------------------------------------
BOOLEAN IsNullTerminated(
_In_ PVOID ptr,
_In_ ULONG size
)
{
if( size == 0 ) {
return FALSE;
}
PTCHAR str = (PTCHAR)ptr;
size /= sizeof(TCHAR);
return ( str[size-1] == 0 );
}
//--------------------------------------------------------------------
//
// DupStringWithoutNullChar
//
// Duplicate a string without null char bound
//
//--------------------------------------------------------------------
PTCHAR DupStringWithoutNullChar(
_In_ PTCHAR input,
_In_ ULONG sizeInByte
)
{
PTCHAR str;
if( input == NULL || sizeInByte < sizeof(TCHAR) ) {
return NULL;
}
if( (sizeInByte % sizeof(TCHAR)) != 0 ) {
sizeInByte--;
}
if( IsNullTerminated( input, sizeInByte ) ) {
return _tcsdup( input );
}
str = (PTCHAR) malloc( sizeInByte + sizeof(TCHAR) );
if( str == NULL ) {
return NULL;
}
ZeroMemory( str, sizeInByte + sizeof(TCHAR) );
_tcsncpy( str, input, sizeInByte / sizeof(TCHAR) );
return str;
}
//--------------------------------------------------------------------
//
// ReplaceAndDup
//
// Replace a part of the string and dup it
//
//--------------------------------------------------------------------
PTCHAR ReplaceAndDup(
_In_ PTCHAR Input,
_In_ ULONG SizeInBytes,
_In_ ULONG Offset,
_In_ ULONG SubCch,
_In_ PTCHAR Replacement
)
{
ULONG newSize, replaceSize, sizeCch;
PTCHAR str, pos;
if( Input == NULL || SizeInBytes < sizeof(TCHAR) ) {
return NULL;
}
sizeCch = SizeInBytes / sizeof(TCHAR);
if( sizeCch <= Offset || sizeCch < (Offset + SubCch) ) {
return NULL;
}
replaceSize = (ULONG)_tcslen( Replacement );
newSize = sizeCch + replaceSize - SubCch;
//
// Need a null char?
//
if( sizeCch < 2 || Input[sizeCch-1] != 0 ) {
newSize++;