-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
hndlinfo.c
2466 lines (2104 loc) · 70.6 KB
/
hndlinfo.c
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 (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved.
*
* This file is part of System Informer.
*
* Authors:
*
* wj32 2010-2015
* dmex 2017-2021
*
*/
#include <ph.h>
#include <hndlinfo.h>
#include <json.h>
#include <kphuser.h>
#include <lsasup.h>
#include <devquery.h>
#include <devpkey.h>
#define PH_QUERY_HACK_MAX_THREADS 20
typedef struct _PHP_CALL_WITH_TIMEOUT_THREAD_CONTEXT
{
SLIST_ENTRY ListEntry;
PUSER_THREAD_START_ROUTINE Routine;
PVOID Context;
HANDLE StartEventHandle;
HANDLE CompletedEventHandle;
HANDLE ThreadHandle;
} PHP_CALL_WITH_TIMEOUT_THREAD_CONTEXT, *PPHP_CALL_WITH_TIMEOUT_THREAD_CONTEXT;
typedef enum _PHP_QUERY_OBJECT_WORK
{
NtQueryObjectWork,
NtQuerySecurityObjectWork,
NtSetSecurityObjectWork,
NtQueryFileInformationWork,
KphQueryFileInformationWork
} PHP_QUERY_OBJECT_WORK;
typedef struct _PHP_QUERY_OBJECT_COMMON_CONTEXT
{
PHP_QUERY_OBJECT_WORK Work;
NTSTATUS Status;
union
{
struct
{
HANDLE Handle;
OBJECT_INFORMATION_CLASS ObjectInformationClass;
PVOID ObjectInformation;
ULONG ObjectInformationLength;
PULONG ReturnLength;
} NtQueryObject;
struct
{
HANDLE Handle;
SECURITY_INFORMATION SecurityInformation;
PSECURITY_DESCRIPTOR SecurityDescriptor;
ULONG Length;
PULONG LengthNeeded;
} NtQuerySecurityObject;
struct
{
HANDLE Handle;
SECURITY_INFORMATION SecurityInformation;
PSECURITY_DESCRIPTOR SecurityDescriptor;
} NtSetSecurityObject;
struct
{
HANDLE Handle;
FILE_INFORMATION_CLASS FileInformationClass;
PVOID FileInformation;
ULONG FileInformationLength;
} NtQueryFileInformation;
struct
{
HANDLE ProcessHandle;
HANDLE Handle;
FILE_INFORMATION_CLASS FileInformationClass;
PVOID FileInformation;
ULONG FileInformationLength;
} KphQueryFileInformation;
} u;
} PHP_QUERY_OBJECT_COMMON_CONTEXT, *PPHP_QUERY_OBJECT_COMMON_CONTEXT;
PPHP_CALL_WITH_TIMEOUT_THREAD_CONTEXT PhpAcquireCallWithTimeoutThread(
_In_opt_ PLARGE_INTEGER Timeout
);
VOID PhpReleaseCallWithTimeoutThread(
_Inout_ PPHP_CALL_WITH_TIMEOUT_THREAD_CONTEXT ThreadContext
);
NTSTATUS PhpCallWithTimeout(
_Inout_ PPHP_CALL_WITH_TIMEOUT_THREAD_CONTEXT ThreadContext,
_In_ PUSER_THREAD_START_ROUTINE Routine,
_In_opt_ PVOID Context,
_In_ PLARGE_INTEGER Timeout
);
NTSTATUS PhpCallWithTimeoutThreadStart(
_In_ PVOID Parameter
);
static PPH_STRING PhObjectTypeNames[MAX_OBJECT_TYPE_NUMBER] = { 0 };
static PPH_GET_CLIENT_ID_NAME PhHandleGetClientIdName = PhStdGetClientIdName;
static SLIST_HEADER PhpCallWithTimeoutThreadListHead;
static PH_WAKE_EVENT PhpCallWithTimeoutThreadReleaseEvent = PH_WAKE_EVENT_INIT;
PPH_GET_CLIENT_ID_NAME PhSetHandleClientIdFunction(
_In_ PPH_GET_CLIENT_ID_NAME GetClientIdName
)
{
return _InterlockedExchangePointer(
(PVOID *)&PhHandleGetClientIdName,
GetClientIdName
);
}
NTSTATUS PhpGetObjectBasicInformation(
_In_ HANDLE ProcessHandle,
_In_ HANDLE Handle,
_Out_ POBJECT_BASIC_INFORMATION BasicInformation
)
{
NTSTATUS status;
if (KphLevel() >= KphLevelMed)
{
status = KphQueryInformationObject(
ProcessHandle,
Handle,
KphObjectBasicInformation,
BasicInformation,
sizeof(OBJECT_BASIC_INFORMATION),
NULL
);
if (NT_SUCCESS(status))
{
// The object was referenced in KSystemInformer, so we need to subtract 1 from the
// pointer count.
BasicInformation->PointerCount -= 1;
}
}
else
{
ULONG returnLength;
status = NtQueryObject(
Handle,
ObjectBasicInformation,
BasicInformation,
sizeof(OBJECT_BASIC_INFORMATION),
&returnLength
);
if (NT_SUCCESS(status))
{
// The object was referenced in NtQueryObject and a handle was opened to the object. We
// need to subtract 1 from the pointer count, then subtract 1 from both counts.
BasicInformation->HandleCount -= 1;
BasicInformation->PointerCount -= 2;
}
}
return status;
}
NTSTATUS PhpGetObjectTypeName(
_In_ HANDLE ProcessHandle,
_In_ HANDLE Handle,
_In_ ULONG ObjectTypeNumber,
_Out_ PPH_STRING *TypeName
)
{
NTSTATUS status = STATUS_SUCCESS;
PPH_STRING typeName = NULL;
// Enumerate the available object types and pre-cache the object type name. (dmex)
if (WindowsVersion >= WINDOWS_8_1)
{
static PH_INITONCE initOnce = PH_INITONCE_INIT;
if (PhBeginInitOnce(&initOnce))
{
POBJECT_TYPES_INFORMATION objectTypes;
POBJECT_TYPE_INFORMATION objectType;
if (NT_SUCCESS(PhEnumObjectTypes(&objectTypes)))
{
objectType = PH_FIRST_OBJECT_TYPE(objectTypes);
for (ULONG i = 0; i < objectTypes->NumberOfTypes; i++)
{
PhMoveReference(
&PhObjectTypeNames[objectType->TypeIndex],
PhCreateStringFromUnicodeString(&objectType->TypeName)
);
objectType = PH_NEXT_OBJECT_TYPE(objectType);
}
PhFree(objectTypes);
}
PhEndInitOnce(&initOnce);
}
}
// If the cache contains the object type name, use it. Otherwise, query the type name. (dmex)
if (ObjectTypeNumber != ULONG_MAX && ObjectTypeNumber < MAX_OBJECT_TYPE_NUMBER)
typeName = PhObjectTypeNames[ObjectTypeNumber];
if (typeName)
{
PhReferenceObject(typeName);
}
else
{
POBJECT_TYPE_INFORMATION buffer;
ULONG returnLength = 0;
PPH_STRING oldTypeName;
KPH_LEVEL level;
level = KphLevel();
// Get the needed buffer size.
if (level >= KphLevelMed)
{
status = KphQueryInformationObject(
ProcessHandle,
Handle,
KphObjectTypeInformation,
NULL,
0,
&returnLength
);
}
else
{
status = NtQueryObject(
Handle,
ObjectTypeInformation,
NULL,
0,
&returnLength
);
}
if (returnLength == 0)
return status;
buffer = PhAllocate(returnLength);
if (level >= KphLevelMed)
{
status = KphQueryInformationObject(
ProcessHandle,
Handle,
KphObjectTypeInformation,
buffer,
returnLength,
&returnLength
);
}
else
{
status = NtQueryObject(
Handle,
ObjectTypeInformation,
buffer,
returnLength,
&returnLength
);
}
if (!NT_SUCCESS(status))
{
PhFree(buffer);
return status;
}
// Create a copy of the type name.
typeName = PhCreateStringFromUnicodeString(&buffer->TypeName);
if (ObjectTypeNumber != ULONG_MAX && ObjectTypeNumber < MAX_OBJECT_TYPE_NUMBER)
{
// Try to store the type name in the cache.
oldTypeName = _InterlockedCompareExchangePointer(
&PhObjectTypeNames[ObjectTypeNumber],
typeName,
NULL
);
// Add a reference if we stored the type name successfully.
if (!oldTypeName)
PhReferenceObject(typeName);
}
PhFree(buffer);
}
// At this point typeName should contain a type name with one additional reference.
*TypeName = typeName;
return status;
}
NTSTATUS PhpGetObjectName(
_In_ HANDLE ProcessHandle,
_In_ HANDLE Handle,
_In_ BOOLEAN WithTimeout,
_Out_ PPH_STRING *ObjectName
)
{
NTSTATUS status;
POBJECT_NAME_INFORMATION buffer;
ULONG bufferSize;
ULONG attempts = 8;
bufferSize = sizeof(OBJECT_NAME_INFORMATION) + (MAXIMUM_FILENAME_LENGTH * sizeof(WCHAR));
buffer = PhAllocate(bufferSize);
// A loop is needed because the I/O subsystem likes to give us the wrong return lengths... (wj32)
do
{
if (KphLevel() >= KphLevelMed)
{
status = KphQueryInformationObject(
ProcessHandle,
Handle,
KphObjectNameInformation,
buffer,
bufferSize,
&bufferSize
);
}
else
{
if (WithTimeout)
{
status = PhCallNtQueryObjectWithTimeout(
Handle,
ObjectNameInformation,
buffer,
bufferSize,
&bufferSize
);
}
else
{
status = NtQueryObject(
Handle,
ObjectNameInformation,
buffer,
bufferSize,
&bufferSize
);
}
}
if (status == STATUS_BUFFER_OVERFLOW || status == STATUS_INFO_LENGTH_MISMATCH ||
status == STATUS_BUFFER_TOO_SMALL)
{
PhFree(buffer);
buffer = PhAllocate(bufferSize);
}
else
{
break;
}
} while (--attempts);
if (NT_SUCCESS(status))
{
*ObjectName = PhCreateStringFromUnicodeString(&buffer->Name);
}
PhFree(buffer);
return status;
}
NTSTATUS PhpGetEtwObjectName(
_In_ HANDLE ProcessHandle,
_In_ HANDLE Handle,
_Out_ PPH_STRING *ObjectName
)
{
NTSTATUS status;
ETWREG_BASIC_INFORMATION basicInfo;
status = KphQueryInformationObject(
ProcessHandle,
Handle,
KphObjectEtwRegBasicInformation,
&basicInfo,
sizeof(ETWREG_BASIC_INFORMATION),
NULL
);
if (NT_SUCCESS(status))
{
*ObjectName = PhFormatGuid(&basicInfo.Guid);
}
return status;
}
typedef struct _PH_ETW_TRACEGUID_ENTRY
{
PPH_STRING Name;
PGUID Guid;
} PH_ETW_TRACEGUID_ENTRY, *PPH_ETW_TRACEGUID_ENTRY;
VOID PhInitializeEtwTraceGuidCache(
_Inout_ PPH_ARRAY EtwTraceGuidArrayList
)
{
PPH_BYTES guidListString = NULL;
PPH_STRING guidListFileName;
PVOID jsonObject;
ULONG arrayLength;
if (guidListFileName = PhGetApplicationDirectory())
{
PhMoveReference(&guidListFileName, PhConcatStringRefZ(&guidListFileName->sr, L"etwguids.txt"));
guidListString = PhFileReadAllText(&guidListFileName->sr, TRUE);
PhDereferenceObject(guidListFileName);
}
if (!guidListString)
return;
PhInitializeArray(EtwTraceGuidArrayList, sizeof(PH_ETW_TRACEGUID_ENTRY), 2000);
if (!(jsonObject = PhCreateJsonParserEx(guidListString, FALSE)))
return;
if (!(arrayLength = PhGetJsonArrayLength(jsonObject)))
{
PhFreeJsonObject(jsonObject);
return;
}
for (ULONG i = 0; i < arrayLength; i++)
{
PVOID jsonArrayObject;
PPH_STRING guidString;
PPH_STRING guidName;
GUID guid;
PH_ETW_TRACEGUID_ENTRY result;
if (!(jsonArrayObject = PhGetJsonArrayIndexObject(jsonObject, i)))
continue;
guidString = PhGetJsonValueAsString(jsonArrayObject, "guid");
guidName = PhGetJsonValueAsString(jsonArrayObject, "name");
//guidGroup = PhGetJsonValueAsString(jsonArrayObject, "group");
if (!NT_SUCCESS(PhStringToGuid(&guidString->sr, &guid)))
{
PhDereferenceObject(guidName);
PhDereferenceObject(guidString);
continue;
}
result.Name = guidName;
result.Guid = PhAllocateCopy(&guid, sizeof(GUID));
PhAddItemArray(EtwTraceGuidArrayList, &result);
PhDereferenceObject(guidString);
}
PhFreeJsonObject(jsonObject);
PhDereferenceObject(guidListString);
}
PPH_STRING PhGetEtwTraceGuidName(
_In_ PGUID Guid
)
{
static PH_INITONCE initOnce = PH_INITONCE_INIT;
static PH_ARRAY etwTraceGuidArrayList;
PPH_ETW_TRACEGUID_ENTRY entry;
SIZE_T i;
if (WindowsVersion < WINDOWS_8)
return NULL;
if (PhBeginInitOnce(&initOnce))
{
PhInitializeEtwTraceGuidCache(&etwTraceGuidArrayList);
PhEndInitOnce(&initOnce);
}
for (i = 0; i < etwTraceGuidArrayList.Count; i++)
{
entry = PhItemArray(&etwTraceGuidArrayList, i);
if (IsEqualGUID(entry->Guid, Guid))
{
return PhReferenceObject(entry->Name);
}
}
return NULL;
}
PPH_STRING PhGetEtwPublisherName(
_In_ PGUID Guid
)
{
static PH_STRINGREF publishersKeyName = PH_STRINGREF_INIT(L"Software\\Microsoft\\Windows\\CurrentVersion\\WINEVT\\Publishers\\");
PPH_STRING guidString;
PPH_STRING keyName;
HANDLE keyHandle;
PPH_STRING publisherName = NULL;
guidString = PhFormatGuid(Guid);
// We should perform a lookup on the GUID to get the publisher name. (wj32)
keyName = PhConcatStringRef2(&publishersKeyName, &guidString->sr);
if (NT_SUCCESS(PhOpenKey(
&keyHandle,
KEY_READ,
PH_KEY_LOCAL_MACHINE,
&keyName->sr,
0
)))
{
publisherName = PhQueryRegistryString(keyHandle, NULL);
if (publisherName && publisherName->Length == 0)
{
PhDereferenceObject(publisherName);
publisherName = NULL;
}
NtClose(keyHandle);
}
PhDereferenceObject(keyName);
if (publisherName)
{
PhDereferenceObject(guidString);
return publisherName;
}
else
{
if (publisherName = PhGetEtwTraceGuidName(Guid))
{
PhDereferenceObject(guidString);
return publisherName;
}
return guidString;
}
}
PPH_STRING PhGetPnPDeviceName(
_In_ PPH_STRING ObjectName
)
{
static PH_INITONCE initOnce = PH_INITONCE_INIT;
static HRESULT (WINAPI* DevGetObjects_I)(
_In_ DEV_OBJECT_TYPE ObjectType,
_In_ ULONG QueryFlags,
_In_ ULONG cRequestedProperties,
_In_reads_opt_(cRequestedProperties) const DEVPROPCOMPKEY *pRequestedProperties,
_In_ ULONG cFilterExpressionCount,
_In_reads_opt_(cFilterExpressionCount) const DEVPROP_FILTER_EXPRESSION *pFilter,
_Out_ PULONG pcObjectCount,
_Outptr_result_buffer_maybenull_(*pcObjectCount) const DEV_OBJECT **ppObjects) = NULL;
static HRESULT (WINAPI* DevFreeObjects_I)(
_In_ ULONG cObjectCount,
_In_reads_(cObjectCount) const DEV_OBJECT *pObjects) = NULL;
PPH_STRING objectPnPDeviceName = NULL;
ULONG deviceCount = 0;
PDEV_OBJECT deviceObjects = NULL;
DEVPROPCOMPKEY deviceProperties[2];
DEVPROP_FILTER_EXPRESSION deviceFilter[1];
DEVPROPERTY deviceFilterProperty;
DEVPROPCOMPKEY deviceFilterCompoundProp;
if (PhBeginInitOnce(&initOnce))
{
PVOID cfgmgr32;
if (cfgmgr32 = PhLoadLibrary(L"cfgmgr32.dll"))
{
DevGetObjects_I = PhGetDllBaseProcedureAddress(cfgmgr32, "DevGetObjects", 0);
DevFreeObjects_I = PhGetDllBaseProcedureAddress(cfgmgr32, "DevFreeObjects", 0);
}
PhEndInitOnce(&initOnce);
}
if (!(DevGetObjects_I && DevFreeObjects_I))
return NULL;
memset(deviceProperties, 0, sizeof(deviceProperties));
deviceProperties[0].Key = DEVPKEY_NAME;
deviceProperties[0].Store = DEVPROP_STORE_SYSTEM;
deviceProperties[1].Key = DEVPKEY_Device_BusReportedDeviceDesc;
deviceProperties[1].Store = DEVPROP_STORE_SYSTEM;
memset(&deviceFilterCompoundProp, 0, sizeof(deviceFilterCompoundProp));
deviceFilterCompoundProp.Key = DEVPKEY_Device_PDOName;
deviceFilterCompoundProp.Store = DEVPROP_STORE_SYSTEM;
deviceFilterCompoundProp.LocaleName = NULL;
memset(&deviceFilterProperty, 0, sizeof(deviceFilterProperty));
deviceFilterProperty.CompKey = deviceFilterCompoundProp;
deviceFilterProperty.Type = DEVPROP_TYPE_STRING;
deviceFilterProperty.BufferSize = (ULONG)ObjectName->Length + sizeof(UNICODE_NULL);
deviceFilterProperty.Buffer = ObjectName->Buffer;
memset(deviceFilter, 0, sizeof(deviceFilter));
deviceFilter[0].Operator = DEVPROP_OPERATOR_EQUALS_IGNORE_CASE;
deviceFilter[0].Property = deviceFilterProperty;
if (SUCCEEDED(DevGetObjects_I(
DevObjectTypeDevice,
DevQueryFlagNone,
RTL_NUMBER_OF(deviceProperties),
deviceProperties,
RTL_NUMBER_OF(deviceFilter),
deviceFilter,
&deviceCount,
&deviceObjects
)))
{
// Note: We can get a success with 0 results.
if (deviceCount > 0)
{
DEV_OBJECT device = deviceObjects[0];
PPH_STRING deviceName;
PPH_STRING deviceDesc;
PH_STRINGREF displayName;
PH_STRINGREF displayDesc;
PH_STRINGREF firstPart;
PH_STRINGREF secondPart;
displayName.Length = device.pProperties[0].BufferSize;
displayName.Buffer = device.pProperties[0].Buffer;
displayDesc.Length = device.pProperties[1].BufferSize;
displayDesc.Buffer = device.pProperties[1].Buffer;
if (PhSplitStringRefAtLastChar(&displayName, L';', &firstPart, &secondPart))
deviceName = PhCreateString2(&secondPart);
else
deviceName = PhCreateString2(&displayName);
if (PhSplitStringRefAtLastChar(&displayDesc, L';', &firstPart, &secondPart))
deviceDesc = PhCreateString2(&secondPart);
else
deviceDesc = PhCreateString2(&displayDesc);
if (deviceName->Length >= sizeof(UNICODE_NULL) && deviceName->Buffer[deviceName->Length / sizeof(WCHAR)] == UNICODE_NULL)
deviceName->Length -= sizeof(UNICODE_NULL); // PhTrimToNullTerminatorString(deviceName);
if (deviceDesc->Length >= sizeof(UNICODE_NULL) && deviceDesc->Buffer[deviceDesc->Length / sizeof(WCHAR)] == UNICODE_NULL)
deviceDesc->Length -= sizeof(UNICODE_NULL); // PhTrimToNullTerminatorString(deviceDesc);
if (!PhIsNullOrEmptyString(deviceDesc))
{
PH_FORMAT format[4];
PhInitFormatSR(&format[0], deviceDesc->sr);
PhInitFormatS(&format[1], L" (PDO: ");
PhInitFormatSR(&format[2], ObjectName->sr);
PhInitFormatC(&format[3], ')');
PhSetReference(&objectPnPDeviceName, PhFormat(format, 4, 0x50));
}
else if (!PhIsNullOrEmptyString(deviceName))
{
PH_FORMAT format[4];
PhInitFormatSR(&format[0], deviceName->sr);
PhInitFormatS(&format[1], L" (PDO: ");
PhInitFormatSR(&format[2], ObjectName->sr);
PhInitFormatC(&format[3], ')');
PhSetReference(&objectPnPDeviceName, PhFormat(format, 4, 0x50));
}
if (deviceDesc)
PhDereferenceObject(deviceDesc);
if (deviceName)
PhDereferenceObject(deviceName);
}
DevFreeObjects_I(deviceCount, deviceObjects);
}
return objectPnPDeviceName;
}
PPH_STRING PhFormatNativeKeyName(
_In_ PPH_STRING Name
)
{
static PH_STRINGREF hklmPrefix = PH_STRINGREF_INIT(L"\\Registry\\Machine");
static PH_STRINGREF hkcrPrefix = PH_STRINGREF_INIT(L"\\Registry\\Machine\\Software\\Classes");
static PH_STRINGREF hkuPrefix = PH_STRINGREF_INIT(L"\\Registry\\User");
static PPH_STRING hkcuPrefix;
static PPH_STRING hkcucrPrefix;
static PH_STRINGREF hklmString = PH_STRINGREF_INIT(L"HKLM");
static PH_STRINGREF hkcrString = PH_STRINGREF_INIT(L"HKCR");
static PH_STRINGREF hkuString = PH_STRINGREF_INIT(L"HKU");
static PH_STRINGREF hkcuString = PH_STRINGREF_INIT(L"HKCU");
static PH_STRINGREF hkcucrString = PH_STRINGREF_INIT(L"HKCU\\Software\\Classes");
static PH_INITONCE initOnce = PH_INITONCE_INIT;
PPH_STRING newName;
PH_STRINGREF name;
if (PhBeginInitOnce(&initOnce))
{
PTOKEN_USER tokenUser;
PPH_STRING stringSid = NULL;
if (NT_SUCCESS(PhGetTokenUser(PhGetOwnTokenAttributes().TokenHandle, &tokenUser)))
{
stringSid = PhSidToStringSid(tokenUser->User.Sid);
PhFree(tokenUser);
}
if (stringSid)
{
static PH_STRINGREF registryUserPrefix = PH_STRINGREF_INIT(L"\\Registry\\User\\");
static PH_STRINGREF classesString = PH_STRINGREF_INIT(L"_Classes");
hkcuPrefix = PhConcatStringRef2(®istryUserPrefix, &stringSid->sr);
hkcucrPrefix = PhConcatStringRef2(&hkcuPrefix->sr, &classesString);
PhDereferenceObject(stringSid);
}
else
{
hkcuPrefix = PhCreateString(L"..."); // some random string that won't ever get matched
hkcucrPrefix = PhCreateString(L"...");
}
PhEndInitOnce(&initOnce);
}
name = Name->sr;
if (PhStartsWithStringRef(&name, &hkcrPrefix, TRUE))
{
PhSkipStringRef(&name, hkcrPrefix.Length);
newName = PhConcatStringRef2(&hkcrString, &name);
}
else if (PhStartsWithStringRef(&name, &hklmPrefix, TRUE))
{
PhSkipStringRef(&name, hklmPrefix.Length);
newName = PhConcatStringRef2(&hklmString, &name);
}
else if (PhStartsWithStringRef(&name, &hkcucrPrefix->sr, TRUE))
{
PhSkipStringRef(&name, hkcucrPrefix->Length);
newName = PhConcatStringRef2(&hkcucrString, &name);
}
else if (PhStartsWithStringRef(&name, &hkcuPrefix->sr, TRUE))
{
PhSkipStringRef(&name, hkcuPrefix->Length);
newName = PhConcatStringRef2(&hkcuString, &name);
}
else if (PhStartsWithStringRef(&name, &hkuPrefix, TRUE))
{
PhSkipStringRef(&name, hkuPrefix.Length);
newName = PhConcatStringRef2(&hkuString, &name);
}
else
{
PhSetReference(&newName, Name);
}
return newName;
}
NTSTATUS PhGetSectionFileName(
_In_ HANDLE SectionHandle,
_Out_ PPH_STRING *FileName
)
{
NTSTATUS status;
SIZE_T viewSize;
PVOID viewBase;
viewSize = 1;
viewBase = NULL;
status = NtMapViewOfSection(
SectionHandle,
NtCurrentProcess(),
&viewBase,
0,
0,
NULL,
&viewSize,
ViewUnmap,
0,
PAGE_READONLY
);
if (!NT_SUCCESS(status))
return status;
status = PhGetProcessMappedFileName(NtCurrentProcess(), viewBase, FileName);
NtUnmapViewOfSection(NtCurrentProcess(), viewBase);
return status;
}
_Callback_ PPH_STRING PhStdGetClientIdName(
_In_ PCLIENT_ID ClientId
)
{
return PhStdGetClientIdNameEx(ClientId, NULL);
}
PPH_STRING PhStdGetClientIdNameEx(
_In_ PCLIENT_ID ClientId,
_In_opt_ PPH_STRING ProcessName
)
{
PPH_STRING result;
PPH_STRING processName = NULL;
PPH_STRING threadName = NULL;
PH_STRINGREF processNameRef;
PH_STRINGREF threadNameRef;
HANDLE processHandle;
HANDLE threadHandle;
ULONG isProcessTerminated = FALSE;
BOOLEAN isThreadTerminated = FALSE;
if (ProcessName)
{
// Use the supplied name
processNameRef.Length = ProcessName->Length;
processNameRef.Buffer = ProcessName->Buffer;
}
else
{
if (ClientId->UniqueProcess == SYSTEM_PROCESS_ID)
{
if (processName = PhGetKernelFileName())
{
PhMoveReference(&processName, PhGetBaseName(processName));
processNameRef.Length = processName->Length;
processNameRef.Buffer = processName->Buffer;
}
else
{
PhInitializeStringRef(&processNameRef, L"Unknown process");
}
}
else
{
// Determine the name of the process ourselves (diversenok)
if (NT_SUCCESS(PhGetProcessImageFileNameById(
ClientId->UniqueProcess,
NULL,
&processName
)))
{
processNameRef.Length = processName->Length;
processNameRef.Buffer = processName->Buffer;
}
else
{
PhInitializeStringRef(&processNameRef, L"Unknown process");
}
}
}
// Check if the process is alive, but only if we didn't get its name
if (!ProcessName && NT_SUCCESS(PhOpenProcess(
&processHandle,
SYNCHRONIZE,
ClientId->UniqueProcess
)))
{
LARGE_INTEGER timeout = { 0 };
// Waiting with zero timeout checks for termination
if (NtWaitForSingleObject(processHandle, FALSE, &timeout) == STATUS_WAIT_0)
isProcessTerminated = TRUE;
NtClose(processHandle);
}
PhInitializeStringRef(&threadNameRef, L"unnamed thread");
if (ClientId->UniqueThread)
{
if (NT_SUCCESS(PhOpenThread(
&threadHandle,
THREAD_QUERY_LIMITED_INFORMATION,
ClientId->UniqueThread
)))
{
// Check if the thread is alive
PhGetThreadIsTerminated(
threadHandle,
&isThreadTerminated
);
// Use the name of the thread if available
if (NT_SUCCESS(PhGetThreadName(threadHandle, &threadName)))
{
threadNameRef.Length = threadName->Length;
threadNameRef.Buffer = threadName->Buffer;
}
NtClose(threadHandle);
}
}
// Combine everything
if (ClientId->UniqueThread)
{
PH_FORMAT format[10];
// L"%s%.*s (%lu): %s%.*s (%lu)"
PhInitFormatS(&format[0], isProcessTerminated ? L"Terminated " : L"");
PhInitFormatSR(&format[1], processNameRef);
PhInitFormatS(&format[2], L" (");
PhInitFormatU(&format[3], HandleToUlong(ClientId->UniqueProcess));
PhInitFormatS(&format[4], L"): ");
PhInitFormatS(&format[5], isThreadTerminated ? L"terminated " : L"");
PhInitFormatSR(&format[6], threadNameRef);
PhInitFormatS(&format[7], L" (");
PhInitFormatU(&format[8], HandleToUlong(ClientId->UniqueThread));
PhInitFormatC(&format[9], L')');
result = PhFormat(format, RTL_NUMBER_OF(format), 0x50);
}
else
{
PH_FORMAT format[5];
// L"%s%.*s (%lu)"
PhInitFormatS(&format[0], isProcessTerminated ? L"Terminated " : L"");
PhInitFormatSR(&format[1], processNameRef);
PhInitFormatS(&format[2], L" (");
PhInitFormatU(&format[3], HandleToUlong(ClientId->UniqueProcess));
PhInitFormatC(&format[4], L')');
result = PhFormat(format, RTL_NUMBER_OF(format), 0x50);
}
//result = PhFormatString(
// ClientId->UniqueThread ? L"%s%.*s (%lu): %s%.*s (%lu)" : L"%s%.*s (%lu)",
// isProcessTerminated ? L"Terminated " : L"",
// processNameRef.Length / sizeof(WCHAR),
// processNameRef.Buffer,
// HandleToUlong(ClientId->UniqueProcess),
// isThreadTerminated ? L"terminated " : L"",
// threadNameRef.Length / sizeof(WCHAR),
// threadNameRef.Buffer,
// HandleToUlong(ClientId->UniqueThread)
// );
if (processName)
PhDereferenceObject(processName);
if (threadName)
PhDereferenceObject(threadName);
return result;
}
NTSTATUS PhpGetBestObjectName(
_In_ HANDLE ProcessHandle,
_In_ HANDLE Handle,
_In_ PPH_STRING ObjectName,
_In_ PPH_STRING TypeName,
_Out_ PPH_STRING *BestObjectName