-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
util.c
5383 lines (4578 loc) · 144 KB
/
util.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
/*
* Process Hacker -
* general support functions
*
* Copyright (C) 2009-2016 wj32
* Copyright (C) 2017 dmex
*
* This file is part of Process Hacker.
*
* Process Hacker is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Process Hacker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Process Hacker. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ph.h>
#include <commctrl.h>
#include <commdlg.h>
#include <shellapi.h>
#define CINTERFACE
#define COBJMACROS
#include <shlobj.h>
#undef CINTERFACE
#undef COBJMACROS
#include <winsta.h>
#include <apiimport.h>
#include <lsasup.h>
#include <mapimg.h>
#include <settings.h>
#include "md5.h"
#include "sha.h"
#include "sha256.h"
typedef BOOLEAN (NTAPI *_WinStationQueryInformationW)(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG LogonId,
_In_ WINSTATIONINFOCLASS WinStationInformationClass,
_Out_writes_bytes_(WinStationInformationLength) PVOID WinStationInformation,
_In_ ULONG WinStationInformationLength,
_Out_ PULONG ReturnLength
);
typedef BOOL (WINAPI *_CreateEnvironmentBlock)(
_Out_ LPVOID *lpEnvironment,
_In_opt_ HANDLE hToken,
_In_ BOOL bInherit
);
typedef BOOL (WINAPI *_DestroyEnvironmentBlock)(
_In_ LPVOID lpEnvironment
);
DECLSPEC_SELECTANY WCHAR *PhSizeUnitNames[7] = { L"B", L"kB", L"MB", L"GB", L"TB", L"PB", L"EB" };
DECLSPEC_SELECTANY ULONG PhMaxSizeUnit = MAXULONG32;
/**
* Ensures a rectangle is positioned within the specified bounds.
*
* \param Rectangle The rectangle to be adjusted.
* \param Bounds The bounds.
*
* \remarks If the rectangle is too large to fit inside the bounds, it is positioned at the top-left
* of the bounds.
*/
VOID PhAdjustRectangleToBounds(
_Inout_ PPH_RECTANGLE Rectangle,
_In_ PPH_RECTANGLE Bounds
)
{
if (Rectangle->Left + Rectangle->Width > Bounds->Left + Bounds->Width)
Rectangle->Left = Bounds->Left + Bounds->Width - Rectangle->Width;
if (Rectangle->Top + Rectangle->Height > Bounds->Top + Bounds->Height)
Rectangle->Top = Bounds->Top + Bounds->Height - Rectangle->Height;
if (Rectangle->Left < Bounds->Left)
Rectangle->Left = Bounds->Left;
if (Rectangle->Top < Bounds->Top)
Rectangle->Top = Bounds->Top;
}
/**
* Positions a rectangle in the center of the specified bounds.
*
* \param Rectangle The rectangle to be adjusted.
* \param Bounds The bounds.
*/
VOID PhCenterRectangle(
_Inout_ PPH_RECTANGLE Rectangle,
_In_ PPH_RECTANGLE Bounds
)
{
Rectangle->Left = Bounds->Left + (Bounds->Width - Rectangle->Width) / 2;
Rectangle->Top = Bounds->Top + (Bounds->Height - Rectangle->Height) / 2;
}
/**
* Ensures a rectangle is positioned within the working area of the specified window's monitor.
*
* \param hWnd A handle to a window. If NULL, the monitor closest to \a Rectangle is used.
* \param Rectangle The rectangle to be adjusted.
*/
VOID PhAdjustRectangleToWorkingArea(
_In_opt_ HWND hWnd,
_Inout_ PPH_RECTANGLE Rectangle
)
{
HMONITOR monitor;
MONITORINFO monitorInfo = { sizeof(monitorInfo) };
if (hWnd)
{
monitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
}
else
{
RECT rect;
rect = PhRectangleToRect(*Rectangle);
monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);
}
if (GetMonitorInfo(monitor, &monitorInfo))
{
PH_RECTANGLE bounds;
bounds = PhRectToRectangle(monitorInfo.rcWork);
PhAdjustRectangleToBounds(Rectangle, &bounds);
}
}
/**
* Centers a window.
*
* \param WindowHandle The window to center.
* \param ParentWindowHandle If specified, the window will be positioned at the center of this
* window. Otherwise, the window will be positioned at the center of the monitor.
*/
VOID PhCenterWindow(
_In_ HWND WindowHandle,
_In_opt_ HWND ParentWindowHandle
)
{
if (ParentWindowHandle)
{
RECT rect, parentRect;
PH_RECTANGLE rectangle, parentRectangle;
GetWindowRect(WindowHandle, &rect);
GetWindowRect(ParentWindowHandle, &parentRect);
rectangle = PhRectToRectangle(rect);
parentRectangle = PhRectToRectangle(parentRect);
PhCenterRectangle(&rectangle, &parentRectangle);
PhAdjustRectangleToWorkingArea(WindowHandle, &rectangle);
MoveWindow(WindowHandle, rectangle.Left, rectangle.Top,
rectangle.Width, rectangle.Height, FALSE);
}
else
{
MONITORINFO monitorInfo = { sizeof(monitorInfo) };
if (GetMonitorInfo(
MonitorFromWindow(WindowHandle, MONITOR_DEFAULTTONEAREST),
&monitorInfo
))
{
RECT rect;
PH_RECTANGLE rectangle;
PH_RECTANGLE bounds;
GetWindowRect(WindowHandle, &rect);
rectangle = PhRectToRectangle(rect);
bounds = PhRectToRectangle(monitorInfo.rcWork);
PhCenterRectangle(&rectangle, &bounds);
MoveWindow(WindowHandle, rectangle.Left, rectangle.Top,
rectangle.Width, rectangle.Height, FALSE);
}
}
}
/**
* References an array of objects.
*
* \param Objects An array of objects.
* \param NumberOfObjects The number of elements in \a Objects.
*/
VOID PhReferenceObjects(
_In_reads_(NumberOfObjects) PVOID *Objects,
_In_ ULONG NumberOfObjects
)
{
ULONG i;
for (i = 0; i < NumberOfObjects; i++)
PhReferenceObject(Objects[i]);
}
/**
* Dereferences an array of objects.
*
* \param Objects An array of objects.
* \param NumberOfObjects The number of elements in \a Objects.
*/
VOID PhDereferenceObjects(
_In_reads_(NumberOfObjects) PVOID *Objects,
_In_ ULONG NumberOfObjects
)
{
ULONG i;
for (i = 0; i < NumberOfObjects; i++)
PhDereferenceObject(Objects[i]);
}
/**
* Gets a string stored in a DLL's message table.
*
* \param DllHandle The base address of the DLL.
* \param MessageTableId The identifier of the message table.
* \param MessageLanguageId The language ID of the message.
* \param MessageId The identifier of the message.
*
* \return A pointer to a string containing the message. You must free the string using
* PhDereferenceObject() when you no longer need it.
*/
PPH_STRING PhGetMessage(
_In_ PVOID DllHandle,
_In_ ULONG MessageTableId,
_In_ ULONG MessageLanguageId,
_In_ ULONG MessageId
)
{
NTSTATUS status;
PMESSAGE_RESOURCE_ENTRY messageEntry;
status = RtlFindMessage(
DllHandle,
MessageTableId,
MessageLanguageId,
MessageId,
&messageEntry
);
// Try using the system LANGID.
if (!NT_SUCCESS(status))
{
status = RtlFindMessage(
DllHandle,
MessageTableId,
GetSystemDefaultLangID(),
MessageId,
&messageEntry
);
}
// Try using U.S. English.
if (!NT_SUCCESS(status))
{
status = RtlFindMessage(
DllHandle,
MessageTableId,
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
MessageId,
&messageEntry
);
}
if (!NT_SUCCESS(status))
return NULL;
// dmex: We don't support parsing insert sequences.
if (messageEntry->Text[0] == '%')
return NULL;
if (messageEntry->Flags & MESSAGE_RESOURCE_UNICODE)
{
return PhCreateStringEx((PWCHAR)messageEntry->Text, messageEntry->Length);
}
else
{
return PhConvertMultiByteToUtf16Ex((PCHAR)messageEntry->Text, messageEntry->Length);
}
}
/**
* Gets a message describing a NT status value.
*
* \param Status The NT status value.
*/
PPH_STRING PhGetNtMessage(
_In_ NTSTATUS Status
)
{
PPH_STRING message;
if (!NT_NTWIN32(Status))
message = PhGetMessage(PhGetDllHandle(L"ntdll.dll"), 0xb, GetUserDefaultLangID(), (ULONG)Status);
else
message = PhGetWin32Message(WIN32_FROM_NTSTATUS(Status));
if (PhIsNullOrEmptyString(message))
return message;
PhTrimToNullTerminatorString(message);
// Remove any trailing newline.
if (message->Length >= 2 * sizeof(WCHAR) &&
message->Buffer[message->Length / sizeof(WCHAR) - 2] == '\r' &&
message->Buffer[message->Length / sizeof(WCHAR) - 1] == '\n')
{
PhMoveReference(&message, PhCreateStringEx(message->Buffer, message->Length - 2 * sizeof(WCHAR)));
}
// Fix those messages which are formatted like:
// {Asdf}\r\nAsdf asdf asdf...
if (message->Buffer[0] == '{')
{
PH_STRINGREF titlePart;
PH_STRINGREF remainingPart;
if (PhSplitStringRefAtChar(&message->sr, '\n', &titlePart, &remainingPart))
PhMoveReference(&message, PhCreateString2(&remainingPart));
}
return message;
}
/**
* Gets a message describing a Win32 error code.
*
* \param Result The Win32 error code.
*/
PPH_STRING PhGetWin32Message(
_In_ ULONG Result
)
{
PPH_STRING message;
message = PhGetMessage(PhGetDllHandle(L"kernel32.dll"), 0xb, GetUserDefaultLangID(), Result);
if (message)
PhTrimToNullTerminatorString(message);
// Remove any trailing newline.
if (message && message->Length >= 2 * sizeof(WCHAR) &&
message->Buffer[message->Length / sizeof(WCHAR) - 2] == '\r' &&
message->Buffer[message->Length / sizeof(WCHAR) - 1] == '\n')
{
PhMoveReference(&message, PhCreateStringEx(message->Buffer, message->Length - 2 * sizeof(WCHAR)));
}
return message;
}
/**
* Displays a message box.
*
* \param hWnd The owner window of the message box.
* \param Type The type of message box to display.
* \param Format A format string.
*
* \return The user's response.
*/
INT PhShowMessage(
_In_ HWND hWnd,
_In_ ULONG Type,
_In_ PWSTR Format,
...
)
{
INT result;
va_list argptr;
PPH_STRING message;
va_start(argptr, Format);
message = PhFormatString_V(Format, argptr);
va_end(argptr);
if (!message)
return -1;
result = MessageBox(hWnd, message->Buffer, PhApplicationName, Type);
PhDereferenceObject(message);
return result;
}
INT PhShowMessage2(
_In_ HWND hWnd,
_In_ ULONG Buttons,
_In_opt_ PWSTR Icon,
_In_opt_ PWSTR Title,
_In_ PWSTR Format,
...
)
{
INT result;
va_list argptr;
PPH_STRING message;
TASKDIALOGCONFIG config = { sizeof(config) };
va_start(argptr, Format);
message = PhFormatString_V(Format, argptr);
va_end(argptr);
if (!message)
return -1;
config.hwndParent = hWnd;
config.hInstance = PhInstanceHandle;
config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | (IsWindowVisible(hWnd) ? TDF_POSITION_RELATIVE_TO_WINDOW : 0);
config.dwCommonButtons = Buttons;
config.pszWindowTitle = PhApplicationName;
config.pszMainIcon = Icon;
config.pszMainInstruction = Title;
config.pszContent = message->Buffer;
if (TaskDialogIndirect(
&config,
&result,
NULL,
NULL
) == S_OK)
{
PhDereferenceObject(message);
return result;
}
else
{
PhDereferenceObject(message);
return -1;
}
}
PPH_STRING PhGetStatusMessage(
_In_ NTSTATUS Status,
_In_opt_ ULONG Win32Result
)
{
if (!Win32Result)
{
// In some cases we want the simple Win32 messages.
if (
Status == STATUS_ACCESS_DENIED ||
Status == STATUS_ACCESS_VIOLATION
)
{
Win32Result = RtlNtStatusToDosError(Status);
}
// Process NTSTATUS values with the NT-Win32 facility.
else if (NT_NTWIN32(Status))
{
Win32Result = WIN32_FROM_NTSTATUS(Status);
}
}
if (!Win32Result)
return PhGetNtMessage(Status);
else
return PhGetWin32Message(Win32Result);
}
/**
* Displays an error message for a NTSTATUS value or Win32 error code.
*
* \param hWnd The owner window of the message box.
* \param Message A message describing the operation that failed.
* \param Status A NTSTATUS value, or 0 if there is none.
* \param Win32Result A Win32 error code, or 0 if there is none.
*/
VOID PhShowStatus(
_In_ HWND hWnd,
_In_opt_ PWSTR Message,
_In_ NTSTATUS Status,
_In_opt_ ULONG Win32Result
)
{
PPH_STRING statusMessage;
statusMessage = PhGetStatusMessage(Status, Win32Result);
if (!statusMessage)
{
if (Message)
{
PhShowError(hWnd, L"%s.", Message);
}
else
{
PhShowError(hWnd, L"Unable to perform the operation.");
}
return;
}
if (Message)
{
PhShowError2(hWnd, Message, statusMessage->Buffer);
}
else
{
PhShowError(hWnd, L"%s", statusMessage->Buffer);
}
PhDereferenceObject(statusMessage);
}
/**
* Displays an error message for a NTSTATUS value or Win32 error code, and allows the user to cancel
* the current operation.
*
* \param hWnd The owner window of the message box.
* \param Message A message describing the operation that failed.
* \param Status A NTSTATUS value, or 0 if there is none.
* \param Win32Result A Win32 error code, or 0 if there is none.
*
* \return TRUE if the user wishes to continue with the current operation, otherwise FALSE.
*/
BOOLEAN PhShowContinueStatus(
_In_ HWND hWnd,
_In_opt_ PWSTR Message,
_In_ NTSTATUS Status,
_In_opt_ ULONG Win32Result
)
{
PPH_STRING statusMessage;
INT result;
statusMessage = PhGetStatusMessage(Status, Win32Result);
if (!statusMessage)
{
if (Message)
{
result = PhShowMessage(hWnd, MB_ICONERROR | MB_OKCANCEL, L"%s.", Message);
}
else
{
result = PhShowMessage(hWnd, MB_ICONERROR | MB_OKCANCEL, L"Unable to perform the operation.");
}
return result == IDOK;
}
if (Message)
{
result = PhShowError2(hWnd, Message, statusMessage->Buffer);
}
else
{
result = PhShowMessage(hWnd, MB_ICONERROR | MB_OKCANCEL, L"%s", statusMessage->Buffer);
}
PhDereferenceObject(statusMessage);
return result == IDOK;
}
/**
* Displays a confirmation message.
*
* \param hWnd The owner window of the message box.
* \param Verb A verb describing the operation, e.g. "terminate".
* \param Object The object of the operation, e.g. "the process".
* \param Message A message describing the operation.
* \param Warning TRUE to display the confirmation message as a warning, otherwise FALSE.
*
* \return TRUE if the user wishes to continue, otherwise FALSE.
*/
BOOLEAN PhShowConfirmMessage(
_In_ HWND hWnd,
_In_ PWSTR Verb,
_In_ PWSTR Object,
_In_opt_ PWSTR Message,
_In_ BOOLEAN Warning
)
{
PPH_STRING verb;
PPH_STRING verbCaps;
PPH_STRING action;
TASKDIALOGCONFIG config = { sizeof(config) };
TASKDIALOG_BUTTON buttons[2];
INT button;
// Make sure the verb is all lowercase.
verb = PhaLowerString(PhaCreateString(Verb));
// "terminate" -> "Terminate"
verbCaps = PhaDuplicateString(verb);
if (verbCaps->Length > 0) verbCaps->Buffer[0] = towupper(verbCaps->Buffer[0]);
// "terminate", "the process" -> "terminate the process"
action = PhaConcatStrings(3, verb->Buffer, L" ", Object);
config.hwndParent = hWnd;
config.hInstance = PhInstanceHandle;
config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | (IsWindowVisible(hWnd) ? TDF_POSITION_RELATIVE_TO_WINDOW : 0);
config.pszWindowTitle = PhApplicationName;
config.pszMainIcon = Warning ? TD_WARNING_ICON : NULL;
config.pszMainInstruction = PhaConcatStrings(3, L"Do you want to ", action->Buffer, L"?")->Buffer;
if (Message)
config.pszContent = PhaConcatStrings2(Message, L" Are you sure you want to continue?")->Buffer;
buttons[0].nButtonID = IDYES;
buttons[0].pszButtonText = verbCaps->Buffer;
buttons[1].nButtonID = IDNO;
buttons[1].pszButtonText = L"Cancel";
config.cButtons = 2;
config.pButtons = buttons;
config.nDefaultButton = IDYES;
if (TaskDialogIndirect(
&config,
&button,
NULL,
NULL
) == S_OK)
{
return button == IDYES;
}
else
{
return FALSE;
}
}
/**
* Finds an integer in an array of string-integer pairs.
*
* \param KeyValuePairs The array.
* \param SizeOfKeyValuePairs The size of the array, in bytes.
* \param String The string to search for.
* \param Integer A variable which receives the found integer.
*
* \return TRUE if the string was found, otherwise FALSE.
*
* \remarks The search is case-sensitive.
*/
BOOLEAN PhFindIntegerSiKeyValuePairs(
_In_ PPH_KEY_VALUE_PAIR KeyValuePairs,
_In_ ULONG SizeOfKeyValuePairs,
_In_ PWSTR String,
_Out_ PULONG Integer
)
{
ULONG i;
for (i = 0; i < SizeOfKeyValuePairs / sizeof(PH_KEY_VALUE_PAIR); i++)
{
if (PhEqualStringZ(KeyValuePairs[i].Key, String, TRUE))
{
*Integer = PtrToUlong(KeyValuePairs[i].Value);
return TRUE;
}
}
return FALSE;
}
/**
* Finds a string in an array of string-integer pairs.
*
* \param KeyValuePairs The array.
* \param SizeOfKeyValuePairs The size of the array, in bytes.
* \param Integer The integer to search for.
* \param String A variable which receives the found string.
*
* \return TRUE if the integer was found, otherwise FALSE.
*/
BOOLEAN PhFindStringSiKeyValuePairs(
_In_ PPH_KEY_VALUE_PAIR KeyValuePairs,
_In_ ULONG SizeOfKeyValuePairs,
_In_ ULONG Integer,
_Out_ PWSTR *String
)
{
ULONG i;
for (i = 0; i < SizeOfKeyValuePairs / sizeof(PH_KEY_VALUE_PAIR); i++)
{
if (PtrToUlong(KeyValuePairs[i].Value) == Integer)
{
*String = (PWSTR)KeyValuePairs[i].Key;
return TRUE;
}
}
return FALSE;
}
/**
* Creates a random (type 4) UUID.
*
* \param Guid The destination UUID.
*/
VOID PhGenerateGuid(
_Out_ PGUID Guid
)
{
static ULONG seed = 0;
// The top/sign bit is always unusable for RtlRandomEx (the result is always unsigned), so we'll
// take the bottom 24 bits. We need 128 bits in total, so we'll call the function 6 times.
ULONG random[6];
ULONG i;
for (i = 0; i < 6; i++)
random[i] = RtlRandomEx(&seed);
// random[0] is usable
*(PUSHORT)&Guid->Data1 = (USHORT)random[0];
// top byte from random[0] is usable
*((PUSHORT)&Guid->Data1 + 1) = (USHORT)((random[0] >> 16) | (random[1] & 0xff));
// top 2 bytes from random[1] are usable
Guid->Data2 = (SHORT)(random[1] >> 8);
// random[2] is usable
Guid->Data3 = (SHORT)random[2];
// top byte from random[2] is usable
*(PUSHORT)&Guid->Data4[0] = (USHORT)((random[2] >> 16) | (random[3] & 0xff));
// top 2 bytes from random[3] are usable
*(PUSHORT)&Guid->Data4[2] = (USHORT)(random[3] >> 8);
// random[4] is usable
*(PUSHORT)&Guid->Data4[4] = (USHORT)random[4];
// top byte from random[4] is usable
*(PUSHORT)&Guid->Data4[6] = (USHORT)((random[4] >> 16) | (random[5] & 0xff));
((PGUID_EX)Guid)->s2.Version = GUID_VERSION_RANDOM;
((PGUID_EX)Guid)->s2.Variant &= ~GUID_VARIANT_STANDARD_MASK;
((PGUID_EX)Guid)->s2.Variant |= GUID_VARIANT_STANDARD;
}
FORCEINLINE VOID PhpReverseGuid(
_Inout_ PGUID Guid
)
{
Guid->Data1 = _byteswap_ulong(Guid->Data1);
Guid->Data2 = _byteswap_ushort(Guid->Data2);
Guid->Data3 = _byteswap_ushort(Guid->Data3);
}
/**
* Creates a name-based (type 3 or 5) UUID.
*
* \param Guid The destination UUID.
* \param Namespace The UUID of the namespace.
* \param Name The input name.
* \param NameLength The length of the input name, not including the null terminator if present.
* \param Version The type of UUID.
* \li \c GUID_VERSION_MD5 Creates a type 3, MD5-based UUID.
* \li \c GUID_VERSION_SHA1 Creates a type 5, SHA1-based UUID.
*/
VOID PhGenerateGuidFromName(
_Out_ PGUID Guid,
_In_ PGUID Namespace,
_In_ PCHAR Name,
_In_ ULONG NameLength,
_In_ UCHAR Version
)
{
PGUID_EX guid;
PUCHAR data;
ULONG dataLength;
GUID ns;
UCHAR hash[20];
// Convert the namespace to big endian.
ns = *Namespace;
PhpReverseGuid(&ns);
// Compute the hash of the namespace concatenated with the name.
dataLength = 16 + NameLength;
data = PhAllocate(dataLength);
memcpy(data, &ns, 16);
memcpy(&data[16], Name, NameLength);
if (Version == GUID_VERSION_MD5)
{
MD5_CTX context;
MD5Init(&context);
MD5Update(&context, data, dataLength);
MD5Final(&context);
memcpy(hash, context.digest, 16);
}
else
{
A_SHA_CTX context;
A_SHAInit(&context);
A_SHAUpdate(&context, data, dataLength);
A_SHAFinal(&context, hash);
Version = GUID_VERSION_SHA1;
}
PhFree(data);
guid = (PGUID_EX)Guid;
memcpy(guid->Data, hash, 16);
PhpReverseGuid(&guid->Guid);
guid->s2.Version = Version;
guid->s2.Variant &= ~GUID_VARIANT_STANDARD_MASK;
guid->s2.Variant |= GUID_VARIANT_STANDARD;
}
/**
* Fills a buffer with random uppercase alphabetical characters.
*
* \param Buffer The buffer to fill with random characters, plus a null terminator.
* \param Count The number of characters available in the buffer, including space for the null
* terminator.
*/
VOID PhGenerateRandomAlphaString(
_Out_writes_z_(Count) PWSTR Buffer,
_In_ ULONG Count
)
{
static ULONG seed = 0;
ULONG i;
if (Count == 0)
return;
for (i = 0; i < Count - 1; i++)
{
Buffer[i] = 'A' + (RtlRandomEx(&seed) % 26);
}
Buffer[Count - 1] = 0;
}
/**
* Modifies a string to ensure it is within the specified length.
*
* \param String The input string.
* \param DesiredCount The desired number of characters in the new string. If necessary, parts of
* the string are replaced with an ellipsis to indicate characters have been omitted.
*
* \return The new string.
*/
PPH_STRING PhEllipsisString(
_In_ PPH_STRING String,
_In_ ULONG DesiredCount
)
{
if (
(ULONG)String->Length / 2 <= DesiredCount ||
DesiredCount < 3
)
{
return PhReferenceObject(String);
}
else
{
PPH_STRING string;
string = PhCreateStringEx(NULL, DesiredCount * 2);
memcpy(string->Buffer, String->Buffer, (DesiredCount - 3) * 2);
memcpy(&string->Buffer[DesiredCount - 3], L"...", 6);
return string;
}
}
/**
* Modifies a string to ensure it is within the specified length, parsing the string as a path.
*
* \param String The input string.
* \param DesiredCount The desired number of characters in the new string. If necessary, parts of
* the string are replaced with an ellipsis to indicate characters have been omitted.
*
* \return The new string.
*/
PPH_STRING PhEllipsisStringPath(
_In_ PPH_STRING String,
_In_ ULONG DesiredCount
)
{
ULONG_PTR secondPartIndex;
secondPartIndex = PhFindLastCharInString(String, 0, L'\\');
if (secondPartIndex == -1)
secondPartIndex = PhFindLastCharInString(String, 0, L'/');
if (secondPartIndex == -1)
return PhEllipsisString(String, DesiredCount);
if (
String->Length / 2 <= DesiredCount ||
DesiredCount < 3
)
{
return PhReferenceObject(String);
}
else
{
PPH_STRING string;
ULONG_PTR firstPartCopyLength;
ULONG_PTR secondPartCopyLength;
string = PhCreateStringEx(NULL, DesiredCount * 2);
secondPartCopyLength = String->Length / 2 - secondPartIndex;
// Check if we have enough space for the entire second part of the string.
if (secondPartCopyLength + 3 <= DesiredCount)
{
// Yes, copy part of the first part and the entire second part.
firstPartCopyLength = DesiredCount - secondPartCopyLength - 3;
}
else
{
// No, copy part of both, from the beginning of the first part and the end of the second
// part.
firstPartCopyLength = (DesiredCount - 3) / 2;
secondPartCopyLength = DesiredCount - 3 - firstPartCopyLength;
secondPartIndex = String->Length / 2 - secondPartCopyLength;
}
memcpy(
string->Buffer,
String->Buffer,
firstPartCopyLength * 2
);
memcpy(
&string->Buffer[firstPartCopyLength],
L"...",
6
);
memcpy(
&string->Buffer[firstPartCopyLength + 3],
&String->Buffer[secondPartIndex],
secondPartCopyLength * 2
);
return string;
}
}
FORCEINLINE BOOLEAN PhpMatchWildcards(
_In_ PWSTR Pattern,
_In_ PWSTR String,
_In_ BOOLEAN IgnoreCase
)
{
PWCHAR s, p;
BOOLEAN star = FALSE;
// Code is from http://xoomer.virgilio.it/acantato/dev/wildcard/wildmatch.html
LoopStart:
for (s = String, p = Pattern; *s; s++, p++)
{
switch (*p)
{
case '?':
break;
case '*':
star = TRUE;
String = s;
Pattern = p;
do
{
Pattern++;
} while (*Pattern == '*');
if (!*Pattern) return TRUE;
goto LoopStart;
default:
if (!IgnoreCase)
{
if (*s != *p)
goto StarCheck;
}
else
{
if (towupper(*s) != towupper(*p))
goto StarCheck;
}
break;
}
}