-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgettokeninformation.cpp
1883 lines (1507 loc) · 55.3 KB
/
gettokeninformation.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
// A simple program to dump token information as consumable JSON.
//
// (C) 2021 CubicleSoft. All Rights Reserved.
#define UNICODE
#define _UNICODE
#define _CRT_SECURE_NO_WARNINGS
#ifdef _MBCS
#undef _MBCS
#endif
#define _CRT_NONSTDC_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <windows.h>
#include <tlhelp32.h>
#include <winternl.h>
#define _NTDEF_
#include <ntsecapi.h>
#include <wincred.h>
#include <objbase.h>
#include <sddl.h>
#include <tchar.h>
#include "utf8/utf8_util.h"
#include "utf8/utf8_file_dir.h"
#include "utf8/utf8_mixed_var.h"
#include "json/json_serializer.h"
#include "templates/static_wc_mixed_var.h"
#include "templates/shared_lib.h"
const char *GxTokenClasses[] = {
NULL, "TokenUser", "TokenGroups", "TokenPrivileges", "TokenOwner", "TokenPrimaryGroup",
"TokenDefaultDacl", "TokenSource", "TokenType", "TokenImpersonationLevel", "TokenStatistics",
"TokenRestrictedSids", "TokenSessionId", "TokenGroupsAndPrivileges", "TokenSessionReference", "TokenSandBoxInert",
"TokenAuditPolicy", "TokenOrigin", "TokenElevationType", "TokenLinkedToken", "TokenElevation",
"TokenHasRestrictions", "TokenAccessInformation", "TokenVirtualizationAllowed", "TokenVirtualizationEnabled", "TokenIntegrityLevel",
"TokenUIAccess", "TokenMandatoryPolicy", "TokenLogonSid", "TokenIsAppContainer", "TokenCapabilities",
"TokenAppContainerSid", "TokenAppContainerNumber", "TokenUserClaimAttributes", "TokenDeviceClaimAttributes", "TokenRestrictedUserClaimAttributes",
"TokenRestrictedDeviceClaimAttributes", "TokenDeviceGroups", "TokenRestrictedDeviceGroups", "TokenSecurityAttributes", "TokenIsRestricted",
"TokenProcessTrustLevel", "TokenPrivateNameSpace", "TokenSingletonAttributes", "TokenBnoIsolation", "TokenChildProcessFlags",
"TokenIsLessPrivilegedAppContainer", "TokenIsSandboxed", "TokenOriginatingProcessTrustLevel"
};
const size_t GxNumTokenClasses = sizeof(GxTokenClasses) / sizeof(char *);
#ifdef SUBSYSTEM_WINDOWS
// If the caller is a console application and is waiting for this application to complete, then attach to the console.
void InitVerboseMode(void)
{
if (::AttachConsole(ATTACH_PARENT_PROCESS))
{
if (::GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE)
{
freopen("CONOUT$", "w", stdout);
setvbuf(stdout, NULL, _IONBF, 0);
}
if (::GetStdHandle(STD_ERROR_HANDLE) != INVALID_HANDLE_VALUE)
{
freopen("CONOUT$", "w", stderr);
setvbuf(stderr, NULL, _IONBF, 0);
}
}
}
#endif
void DumpSyntax(TCHAR *currfile)
{
#ifdef SUBSYSTEM_WINDOWS
InitVerboseMode();
#endif
_tprintf(_T("(C) 2021 CubicleSoft. All Rights Reserved.\n\n"));
_tprintf(_T("Syntax: %s [options]\n\n"), currfile);
_tprintf(_T("Options:\n"));
_tprintf(_T("\t/v\n\
\tVerbose mode.\n\
\n\
\t/login\n\
\tUse a Windows credentials dialog to create and retrieve a token.\n\
\tIncompatible with '/pid', '/tid', '/usetoken', and '/createtoken'.\n\
\n\
\t/pid=ProcessID\n\
\tThe process ID to retrieve token information from.\n\
\tIncompatible with '/login', '/tid', '/usetoken', and '/createtoken'.\n\
\n\
\t/tid=ThreadID\n\
\tThe thread ID to retrieve token information from.\n\
\tIncompatible with '/login', '/pid', '/usetoken', and '/createtoken'.\n\
\n\
\t/usetoken=PIDorSIDsAndPrivileges\n\
\tUses the primary token of the specified process ID,\n\
\tor a process matching specific comma-separated user/group SIDs\n\
\tand/or a process with specific privileges.\n\
\tRequires SeDebugPrivilege.\n\
\tIncompatible with '/login', '/pid', '/tid', and '/createtoken'.\n\
\n\
\t/createtokenwild=ProcessID\n\
\tThe primary token of the specified process ID is used\n\
\twith '/createtoken' for wildcard parameters.\n\
\n\
\t/createtoken=Parameters\n\
\tCreates a primary token from scratch.\n\
\tRequires SeDebugPrivilege.\n\
\tIncompatible with '/login', '/pid', '/tid', and '/usetoken'.\n\
\tUses an undocumented Windows kernel API.\n\
\tThe 'Parameters' are semicolon separated:\n\
\t\tUserSID;\n\
\t\tGroupSID:Attr,GroupSID:Attr,...;\n\
\t\tPrivilege:Attr,Privilege:Attr,...;\n\
\t\tOwnerSID;\n\
\t\tPrimaryGroupSID;\n\
\t\tDefaultDACL;\n\
\t\tSourceInHex:SourceLUID\n\
\n\
\t/raw\n\
\tInclude retrieved hex encoded raw data.\n\
\n\
\t/file=OutputFile\n\
\tFile to write the JSON output to instead of stdout.\n\
\n\
\t/c=TokenInfoClass\n\
\tA token information class to retrieve.\n\
\tMultiple /c options can be specified.\n\
\tEach 'TokenInfoClass' can be one of:\n"));
size_t x;
for (x = 1; x < GxNumTokenClasses; x++)
{
printf("\t\t%s\n", GxTokenClasses[x]);
}
printf("\n");
#ifdef SUBSYSTEM_WINDOWS
_tprintf(_T("\t/attach\n"));
_tprintf(_T("\tAttempt to attach to a parent console if it exists.\n\n"));
#endif
}
bool SetThreadProcessPrivilege(LPCWSTR PrivilegeName, bool Enable)
{
HANDLE Token;
TOKEN_PRIVILEGES TokenPrivs;
LUID TempLuid;
bool Result;
if (!::LookupPrivilegeValueW(NULL, PrivilegeName, &TempLuid)) return false;
if (!::OpenThreadToken(::GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &Token))
{
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Token)) return false;
}
TokenPrivs.PrivilegeCount = 1;
TokenPrivs.Privileges[0].Luid = TempLuid;
TokenPrivs.Privileges[0].Attributes = (Enable ? SE_PRIVILEGE_ENABLED : 0);
Result = (::AdjustTokenPrivileges(Token, FALSE, &TokenPrivs, 0, NULL, NULL) && ::GetLastError() == ERROR_SUCCESS);
::CloseHandle(Token);
return Result;
}
void DumpOutput(CubicleSoft::UTF8::File &OutputFile, CubicleSoft::JSON::Serializer &OutputJSON)
{
size_t y;
if (OutputFile.IsOpen()) OutputFile.Write((std::uint8_t *)OutputJSON.GetBuffer(), OutputJSON.GetCurrPos(), y);
else printf("%s", OutputJSON.GetBuffer());
OutputJSON.ResetPos();
}
struct SidInfo {
PSID MxSid;
TCHAR MxDomainName[1024];
TCHAR MxAccountName[1024];
SID_NAME_USE MxSidType;
};
bool DumpSid(CubicleSoft::UTF8::File &OutputFile, CubicleSoft::JSON::Serializer &OutputJSON, const char *key, PSID sid, bool closeobj = true, bool wrapsplit = true)
{
LPTSTR tempstrsid = NULL;
CubicleSoft::UTF8::UTF8MixedVar<char[8192]> TempVar;
SidInfo TempSidInfo;
DWORD acctbuffersize, domainbuffersize;
if (!::ConvertSidToStringSid(sid, &tempstrsid)) return false;
if (wrapsplit) OutputJSON.SetValSplitter(",\n");
OutputJSON.StartObject(key);
OutputJSON.SetValSplitter(", ");
// Basic information.
TempVar.SetUTF8(tempstrsid);
OutputJSON.AppendStr("sid", TempVar.GetStr());
::LocalFree(tempstrsid);
OutputJSON.SetValSplitter(", ");
acctbuffersize = sizeof(TempSidInfo.MxAccountName) / sizeof(TCHAR);
domainbuffersize = sizeof(TempSidInfo.MxDomainName) / sizeof(TCHAR);
if (::LookupAccountSid(NULL, sid, TempSidInfo.MxAccountName, &acctbuffersize, TempSidInfo.MxDomainName, &domainbuffersize, &TempSidInfo.MxSidType))
{
TempVar.SetUTF8(TempSidInfo.MxDomainName);
OutputJSON.AppendStr("domain", TempVar.GetStr());
TempVar.SetUTF8(TempSidInfo.MxAccountName);
OutputJSON.AppendStr("account", TempVar.GetStr());
OutputJSON.AppendUInt("type", TempSidInfo.MxSidType);
}
if (closeobj)
{
DumpOutput(OutputFile, OutputJSON);
OutputJSON.EndObject();
}
return true;
}
void DumpSidAndAttributes(CubicleSoft::UTF8::File &OutputFile, CubicleSoft::JSON::Serializer &OutputJSON, const char *key, SID_AND_ATTRIBUTES &sidattrs, bool wrapsplit = true)
{
if (!DumpSid(OutputFile, OutputJSON, key, sidattrs.Sid, false, wrapsplit)) return;
OutputJSON.AppendUInt("attrs", sidattrs.Attributes);
DumpOutput(OutputFile, OutputJSON);
OutputJSON.EndObject();
}
void DumpLuid(CubicleSoft::JSON::Serializer &OutputJSON, const char *key, LUID &luid)
{
OutputJSON.AppendUInt(key, ((std::uint64_t)(DWORD)luid.HighPart << 32) | (std::uint64_t)luid.LowPart);
}
void DumpLuidAndAttributes(CubicleSoft::UTF8::File &OutputFile, CubicleSoft::JSON::Serializer &OutputJSON, const char *key, LUID_AND_ATTRIBUTES &luidattrs, bool closeobj = true)
{
OutputJSON.SetValSplitter(",\n");
OutputJSON.StartObject(key);
OutputJSON.SetValSplitter(", ");
DumpLuid(OutputJSON, "luid", luidattrs.Luid);
OutputJSON.AppendUInt("attrs", luidattrs.Attributes);
if (closeobj)
{
DumpOutput(OutputFile, OutputJSON);
OutputJSON.EndObject();
}
}
void DumpPrivilege(CubicleSoft::UTF8::File &OutputFile, CubicleSoft::JSON::Serializer &OutputJSON, LUID_AND_ATTRIBUTES &luidattrs)
{
char buffer[256];
DWORD buffersize = sizeof(buffer);
DumpLuidAndAttributes(OutputFile, OutputJSON, NULL, luidattrs, false);
if (::LookupPrivilegeNameA(NULL, &luidattrs.Luid, (LPSTR)buffer, &buffersize)) OutputJSON.AppendStr("name", buffer);
DumpOutput(OutputFile, OutputJSON);
OutputJSON.EndObject();
}
void DumpHexData(CubicleSoft::UTF8::File &OutputFile, CubicleSoft::JSON::Serializer &OutputJSON, const char *key, const std::uint8_t *buffer, size_t buffersize)
{
std::uint8_t val, val2;
char tempbuffer[1024];
size_t x, x2 = 0, y2 = sizeof(tempbuffer);
OutputJSON.StartStr(key);
for (x = 0; x < buffersize; x++)
{
val = buffer[x];
val2 = val / 16;
tempbuffer[x2++] = (char)(val2 > 9 ? val2 - 10 + 'A' : val2 + '0');
val2 = val % 16;
tempbuffer[x2++] = (char)(val2 > 9 ? val2 - 10 + 'A' : val2 + '0');
if (x2 >= y2)
{
if (!OutputJSON.AppendStr(tempbuffer, x2))
{
DumpOutput(OutputFile, OutputJSON);
OutputJSON.AppendStr(tempbuffer, x2);
}
x2 = 0;
}
}
DumpOutput(OutputFile, OutputJSON);
if (x2) OutputJSON.AppendStr(tempbuffer, x2);
OutputJSON.EndStr();
}
void DumpWinError(CubicleSoft::JSON::Serializer &OutputJSON, DWORD winerror)
{
LPTSTR errmsg = NULL;
CubicleSoft::UTF8::UTF8MixedVar<char[8192]> TempVar;
::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, winerror, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
if (errmsg == NULL) OutputJSON.AppendStr("winerror", "Unknown Windows error message.");
else
{
TempVar.SetUTF8(errmsg);
OutputJSON.AppendStr("winerror", TempVar.GetStr());
::LocalFree(errmsg);
}
}
void DumpTokenInformation(CubicleSoft::UTF8::File &OutputFile, CubicleSoft::JSON::Serializer &OutputJSON, bool classesused, bool *classes, bool rawdata, HANDLE tokenhandle, size_t Depth)
{
size_t x, x2;
LPVOID infobuffer = NULL;
DWORD infobuffersize = 0, infobuffersize2;
BOOL result, dumprawdata;
DWORD winerror;
// Retrieve all the juicy details about the token.
for (x = 1; x < GxNumTokenClasses; x++)
{
if (!classesused || classes[x])
{
if (Depth > 1) OutputJSON.SetValSplitter(",\n\n\t");
else OutputJSON.SetValSplitter(",\n\n");
OutputJSON.StartObject(GxTokenClasses[x]);
OutputJSON.SetValSplitter(", ");
// Resize until the buffer is big enough.
while (!(result = ::GetTokenInformation(tokenhandle, (TOKEN_INFORMATION_CLASS)x, infobuffer, infobuffersize, &infobuffersize2)) && (winerror = ::GetLastError()) == ERROR_INSUFFICIENT_BUFFER)
{
if (infobuffer != NULL) ::LocalFree(infobuffer);
infobuffer = (LPVOID)::LocalAlloc(LMEM_FIXED, infobuffersize2);
if (infobuffer != NULL) infobuffersize = infobuffersize2;
else
{
infobuffersize = 0;
winerror = ::GetLastError();
break;
}
}
// Retry with an exact size. TokenLinkedToken, for example, returns ERROR_BAD_LENGTH.
if (!result && winerror == ERROR_BAD_LENGTH && infobuffersize2 > 0)
{
result = ::GetTokenInformation(tokenhandle, (TOKEN_INFORMATION_CLASS)x, infobuffer, infobuffersize2, &infobuffersize2);
if (!result) winerror = ::GetLastError();
}
if (!result)
{
OutputJSON.AppendBool("success", false);
OutputJSON.AppendStr("error", "Unable to get token information.");
OutputJSON.AppendStr("errorcode", "get_token_information_failed");
DumpWinError(OutputJSON, winerror);
OutputJSON.AppendUInt("winerrorcode", winerror);
}
else if (infobuffer == NULL)
{
OutputJSON.AppendBool("success", false);
OutputJSON.AppendStr("error", "Unable to allocate sufficient space for token information.");
OutputJSON.AppendStr("errorcode", "local_alloc_failed");
DumpWinError(OutputJSON, winerror);
OutputJSON.AppendUInt("winerrorcode", winerror);
}
else
{
OutputJSON.AppendBool("success", true);
dumprawdata = rawdata;
switch (x)
{
case TokenUser:
{
DumpSidAndAttributes(OutputFile, OutputJSON, "info", ((PTOKEN_USER)infobuffer)->User, false);
break;
}
case TokenGroups:
case TokenRestrictedSids:
case TokenLogonSid:
case TokenCapabilities:
case TokenDeviceGroups:
case TokenRestrictedDeviceGroups:
{
OutputJSON.StartArray("info");
for (x2 = 0; x2 < ((PTOKEN_GROUPS)infobuffer)->GroupCount; x2++)
{
DumpSidAndAttributes(OutputFile, OutputJSON, NULL, ((PTOKEN_GROUPS)infobuffer)->Groups[x2]);
}
OutputJSON.EndArray();
break;
}
case TokenPrivileges:
{
OutputJSON.StartArray("info");
for (x2 = 0; x2 < ((PTOKEN_PRIVILEGES)infobuffer)->PrivilegeCount; x2++)
{
DumpPrivilege(OutputFile, OutputJSON, ((PTOKEN_PRIVILEGES)infobuffer)->Privileges[x2]);
}
OutputJSON.EndArray();
break;
}
case TokenOwner:
{
DumpSid(OutputFile, OutputJSON, "info", ((PTOKEN_OWNER)infobuffer)->Owner);
break;
}
case TokenPrimaryGroup:
{
DumpSid(OutputFile, OutputJSON, "info", ((PTOKEN_PRIMARY_GROUP)infobuffer)->PrimaryGroup);
break;
}
case TokenDefaultDacl:
{
SECURITY_DESCRIPTOR sd;
LPTSTR tempsddl;
if (::InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) && ::SetSecurityDescriptorDacl(&sd, TRUE, ((PTOKEN_DEFAULT_DACL)infobuffer)->DefaultDacl, TRUE) && ::ConvertSecurityDescriptorToStringSecurityDescriptor(&sd, SDDL_REVISION_1, DACL_SECURITY_INFORMATION, &tempsddl, NULL))
{
CubicleSoft::UTF8::UTF8MixedVar<char[8192]> TempVar;
TempVar.SetUTF8(tempsddl);
OutputJSON.AppendStr("info", TempVar.GetStr());
::LocalFree(tempsddl);
}
else
{
dumprawdata = true;
}
break;
}
case TokenSource:
{
OutputJSON.StartObject("info");
DumpHexData(OutputFile, OutputJSON, "name", (std::uint8_t *)(((PTOKEN_SOURCE)infobuffer)->SourceName), TOKEN_SOURCE_LENGTH);
DumpLuid(OutputJSON, "id", ((PTOKEN_SOURCE)infobuffer)->SourceIdentifier);
OutputJSON.EndObject();
break;
}
case TokenStatistics:
{
OutputJSON.StartObject("info");
DumpLuid(OutputJSON, "token_id", ((PTOKEN_STATISTICS)infobuffer)->TokenId);
DumpLuid(OutputJSON, "auth_id", ((PTOKEN_STATISTICS)infobuffer)->AuthenticationId);
OutputJSON.AppendUInt("expires", ((PTOKEN_STATISTICS)infobuffer)->ExpirationTime.QuadPart);
OutputJSON.AppendUInt("token_type", ((PTOKEN_STATISTICS)infobuffer)->TokenType);
OutputJSON.AppendUInt("impersonation_level", ((PTOKEN_STATISTICS)infobuffer)->ImpersonationLevel);
OutputJSON.AppendUInt("dynamic_charged", ((PTOKEN_STATISTICS)infobuffer)->DynamicCharged);
OutputJSON.AppendUInt("dynamic_avail", ((PTOKEN_STATISTICS)infobuffer)->DynamicAvailable);
OutputJSON.AppendUInt("num_groups", ((PTOKEN_STATISTICS)infobuffer)->GroupCount);
OutputJSON.AppendUInt("num_privileges", ((PTOKEN_STATISTICS)infobuffer)->PrivilegeCount);
DumpLuid(OutputJSON, "modified_id", ((PTOKEN_STATISTICS)infobuffer)->ModifiedId);
OutputJSON.EndObject();
break;
}
case TokenGroupsAndPrivileges:
{
OutputJSON.StartObject("info");
OutputJSON.StartArray("sids");
for (x2 = 0; x2 < ((PTOKEN_GROUPS_AND_PRIVILEGES)infobuffer)->SidCount; x2++)
{
DumpSidAndAttributes(OutputFile, OutputJSON, NULL, ((PTOKEN_GROUPS_AND_PRIVILEGES)infobuffer)->Sids[x2]);
}
OutputJSON.EndArray();
OutputJSON.StartArray("restricted_sids");
for (x2 = 0; x2 < ((PTOKEN_GROUPS_AND_PRIVILEGES)infobuffer)->RestrictedSidCount; x2++)
{
DumpSidAndAttributes(OutputFile, OutputJSON, NULL, ((PTOKEN_GROUPS_AND_PRIVILEGES)infobuffer)->RestrictedSids[x2]);
}
OutputJSON.EndArray();
OutputJSON.StartArray("privileges");
for (x2 = 0; x2 < ((PTOKEN_GROUPS_AND_PRIVILEGES)infobuffer)->PrivilegeCount; x2++)
{
DumpPrivilege(OutputFile, OutputJSON, ((PTOKEN_GROUPS_AND_PRIVILEGES)infobuffer)->Privileges[x2]);
}
OutputJSON.EndArray();
DumpLuid(OutputJSON, "auth_id", ((PTOKEN_GROUPS_AND_PRIVILEGES)infobuffer)->AuthenticationId);
OutputJSON.EndObject();
break;
}
case TokenOrigin:
{
DumpLuid(OutputJSON, "info", ((PTOKEN_ORIGIN)infobuffer)->OriginatingLogonSession);
break;
}
case TokenLinkedToken:
{
OutputJSON.StartObject("info");
if (Depth >= 2) OutputJSON.AppendBool("success", false);
else
{
OutputJSON.AppendBool("success", true);
DumpTokenInformation(OutputFile, OutputJSON, classesused, classes, rawdata, ((PTOKEN_LINKED_TOKEN)infobuffer)->LinkedToken, Depth + 1);
}
::CloseHandle(((PTOKEN_LINKED_TOKEN)infobuffer)->LinkedToken);
OutputJSON.EndObject();
break;
}
case TokenAccessInformation:
{
OutputJSON.StartObject("info");
OutputJSON.StartArray("sids");
for (x2 = 0; x2 < ((PTOKEN_ACCESS_INFORMATION)infobuffer)->SidHash->SidCount; x2++)
{
DumpSidAndAttributes(OutputFile, OutputJSON, NULL, ((PTOKEN_ACCESS_INFORMATION)infobuffer)->SidHash->SidAttr[x2]);
}
OutputJSON.EndArray();
OutputJSON.StartArray("restricted_sids");
for (x2 = 0; x2 < ((PTOKEN_ACCESS_INFORMATION)infobuffer)->RestrictedSidHash->SidCount; x2++)
{
DumpSidAndAttributes(OutputFile, OutputJSON, NULL, ((PTOKEN_ACCESS_INFORMATION)infobuffer)->RestrictedSidHash->SidAttr[x2]);
}
OutputJSON.EndArray();
OutputJSON.StartArray("privileges");
for (x2 = 0; x2 < ((PTOKEN_ACCESS_INFORMATION)infobuffer)->Privileges->PrivilegeCount; x2++)
{
DumpPrivilege(OutputFile, OutputJSON, ((PTOKEN_ACCESS_INFORMATION)infobuffer)->Privileges->Privileges[x2]);
}
OutputJSON.EndArray();
DumpLuid(OutputJSON, "auth_id", ((PTOKEN_ACCESS_INFORMATION)infobuffer)->AuthenticationId);
OutputJSON.AppendUInt("token_type", ((PTOKEN_ACCESS_INFORMATION)infobuffer)->TokenType);
OutputJSON.AppendUInt("impersonation_level", ((PTOKEN_ACCESS_INFORMATION)infobuffer)->ImpersonationLevel);
OutputJSON.AppendUInt("mandatory_policy", ((PTOKEN_ACCESS_INFORMATION)infobuffer)->MandatoryPolicy.Policy);
OutputJSON.AppendUInt("flags", ((PTOKEN_ACCESS_INFORMATION)infobuffer)->Flags);
OutputJSON.AppendUInt("app_container_num", ((PTOKEN_ACCESS_INFORMATION)infobuffer)->AppContainerNumber);
DumpSid(OutputFile, OutputJSON, "package_sid", ((PTOKEN_ACCESS_INFORMATION)infobuffer)->PackageSid);
OutputJSON.StartArray("capabilities");
for (x2 = 0; x2 < ((PTOKEN_ACCESS_INFORMATION)infobuffer)->CapabilitiesHash->SidCount; x2++)
{
DumpSidAndAttributes(OutputFile, OutputJSON, NULL, ((PTOKEN_ACCESS_INFORMATION)infobuffer)->CapabilitiesHash->SidAttr[x2]);
}
OutputJSON.EndArray();
DumpSid(OutputFile, OutputJSON, "trust_level_sid", ((PTOKEN_ACCESS_INFORMATION)infobuffer)->TrustLevelSid);
// Not sure how to handle the "opaque" SecurityAttributes member.
OutputJSON.EndObject();
break;
}
case TokenIntegrityLevel:
{
DumpSidAndAttributes(OutputFile, OutputJSON, "info", ((PTOKEN_MANDATORY_LABEL)infobuffer)->Label, false);
break;
}
case TokenAppContainerSid:
{
DumpSid(OutputFile, OutputJSON, "info", ((PTOKEN_APPCONTAINER_INFORMATION)infobuffer)->TokenAppContainer, true, false);
break;
}
// DWORD cases.
case TokenType:
case TokenImpersonationLevel:
case TokenSessionId:
case TokenSandBoxInert:
case TokenElevationType:
case TokenElevation: // Described as a structure but only contains a DWORD.
case TokenHasRestrictions: // Oddly this is returned as one byte of data rather than a DWORD size (possible bug in GetTokenInformation()?).
case TokenVirtualizationAllowed:
case TokenVirtualizationEnabled:
case TokenUIAccess:
case TokenMandatoryPolicy: // Described as a structure but only contains a DWORD.
case TokenIsAppContainer:
case TokenAppContainerNumber:
{
OutputJSON.AppendUInt("info", *((DWORD *)infobuffer));
break;
}
// Dump everything else as-is.
default:
{
dumprawdata = true;
break;
}
}
if (dumprawdata) DumpHexData(OutputFile, OutputJSON, "data", (std::uint8_t *)infobuffer, infobuffersize2);
}
DumpOutput(OutputFile, OutputJSON);
OutputJSON.EndObject();
}
}
if (infobuffer != NULL) ::LocalFree(infobuffer);
}
// This is a little bit of a hacky workaround since the code is ultimately intended to be used within createprocess.
const char *GxErrorStr = NULL, *GxErrorCode = NULL;
DWORD GxWinError = 0;
void DumpErrorMsg(const char *errorstr, const char *errorcode, DWORD winerror)
{
GxErrorStr = errorstr;
GxErrorCode = errorcode;
GxWinError = winerror;
}
void DumpWideErrorMsg(const WCHAR *errorstr, const char *errorcode, DWORD winerror)
{
char *errorstr2;
BOOL useddefaultchar = FALSE;
int retval = ::WideCharToMultiByte(CP_ACP, 0, errorstr, -1, NULL, 0, NULL, &useddefaultchar);
if (!retval)
{
DumpErrorMsg("Unable to convert error message to multibyte.", "wide_char_to_multibyte_failed", ::GetLastError());
return;
}
DWORD tempsize = (DWORD)retval;
errorstr2 = (char *)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, tempsize);
if (errorstr2 == NULL)
{
DumpErrorMsg("Error message buffer allocation failed.", "heap_alloc_failed", ::GetLastError());
return;
}
useddefaultchar = FALSE;
retval = ::WideCharToMultiByte(CP_ACP, 0, errorstr, -1, errorstr2, tempsize, NULL, &useddefaultchar);
if (!retval)
{
DumpErrorMsg("Unable to convert error message to multibyte.", "wide_char_to_multibyte_failed", ::GetLastError());
::HeapFree(::GetProcessHeap(), 0, errorstr2);
return;
}
size_t y = strlen(errorstr2);
while (y && (errorstr2[y - 1] == '\r' || errorstr2[y - 1] == '\n')) errorstr2[--y] = '\0';
// Display the error message.
DumpErrorMsg(errorstr2, errorcode, winerror);
// Intentionally leaking the error message string.
// ::HeapFree(::GetProcessHeap(), 0, errorstr2);
}
inline void FreeTokenInformation(LPVOID tinfo)
{
if (tinfo != NULL) ::HeapFree(::GetProcessHeap(), 0, tinfo);
}
LPVOID AllocateAndGetTokenInformation(HANDLE token, TOKEN_INFORMATION_CLASS infoclass, DWORD sizehint)
{
LPVOID tinfo;
DWORD tinfosize = sizehint;
bool success;
tinfo = (LPVOID)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, tinfosize);
if (tinfo == NULL) tinfosize = 0;
// Resize until the buffer is big enough.
while (!(success = ::GetTokenInformation(token, infoclass, tinfo, tinfosize, &tinfosize)) && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (tinfo != NULL) FreeTokenInformation(tinfo);
tinfo = (LPVOID)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, tinfosize);
if (tinfo == NULL)
{
tinfosize = 0;
break;
}
}
return tinfo;
}
// Get/Duplicate the primary token of the specified process ID as a primary or impersonation token.
// duptype is ignored if accessmode does not specify TOKEN_DUPLICATE.
HANDLE GetTokenFromPID(DWORD pid, TOKEN_TYPE duptype, DWORD accessmode = TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY)
{
HANDLE tempproc;
HANDLE tokenhandle, tokenhandle2;
// Enable SeDebugPrivilege.
SetThreadProcessPrivilege(L"SeDebugPrivilege", true);
// Open a handle to the process.
tempproc = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if (tempproc == NULL) tempproc = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (tempproc == NULL)
{
DumpErrorMsg("Unable to open a handle to the specified process.", "open_process_failed", ::GetLastError());
return INVALID_HANDLE_VALUE;
}
if (!::OpenProcessToken(tempproc, accessmode, &tokenhandle) && (!(accessmode & TOKEN_QUERY_SOURCE) || !::OpenProcessToken(tempproc, accessmode & ~TOKEN_QUERY_SOURCE, &tokenhandle)))
{
DumpErrorMsg("Unable to open a handle to the specified process token.", "open_process_token_failed", ::GetLastError());
::CloseHandle(tempproc);
return INVALID_HANDLE_VALUE;
}
::CloseHandle(tempproc);
if (!(accessmode & TOKEN_DUPLICATE)) tokenhandle2 = tokenhandle;
else
{
SECURITY_ATTRIBUTES secattr = {0};
secattr.nLength = sizeof(secattr);
secattr.bInheritHandle = FALSE;
secattr.lpSecurityDescriptor = NULL;
if (!::DuplicateTokenEx(tokenhandle, MAXIMUM_ALLOWED, &secattr, SecurityImpersonation, duptype, &tokenhandle2))
{
DumpErrorMsg("Unable to duplicate the specified process token.", "duplicate_token_ex_failed", ::GetLastError());
::CloseHandle(tokenhandle);
return INVALID_HANDLE_VALUE;
}
::CloseHandle(tokenhandle);
}
return tokenhandle2;
}
void GetNumSIDsAndLUIDs(LPWSTR tokenopts, size_t &numsids, size_t &numluids)
{
size_t x = 0;
numsids = 0;
numluids = 0;
while (tokenopts[x] && tokenopts[x] != L';')
{
for (; tokenopts[x] && tokenopts[x] != L';' && tokenopts[x] != L'S'; x++);
if (tokenopts[x] == L'S')
{
if (tokenopts[x + 1] == L'-') numsids++;
else if (tokenopts[x + 1] == L'e') numluids++;
}
for (; tokenopts[x] && tokenopts[x] != L';' && tokenopts[x] != L','; x++);
if (tokenopts[x] == L',') x++;
}
}
bool GetNextTokenOptsSID(LPWSTR tokenopts, size_t &x, PSID &sidbuffer)
{
size_t x2;
WCHAR tempchr;
for (x2 = x; tokenopts[x2] && tokenopts[x2] != L';' && tokenopts[x2] != L':' && tokenopts[x2] != L','; x2++);
tempchr = tokenopts[x2];
tokenopts[x2] = L'\0';
bool result = ::ConvertStringSidToSidW(tokenopts + x, &sidbuffer);
if (!result)
{
DWORD winerror = ::GetLastError();
CubicleSoft::StaticWCMixedVar<WCHAR[8192]> TempVar;
TempVar.SetFormattedStr(L"The specified SID '%ls' in the token options is invalid.", tokenopts + x);
DumpWideErrorMsg(TempVar.GetStr(), "invalid_sid", winerror);
}
tokenopts[x2] = tempchr;
x = x2;
return result;
}
bool GetNextTokenOptsLUID(LPWSTR tokenopts, size_t &x, LUID &luidbuffer)
{
size_t x2;
WCHAR tempchr;
for (x2 = x; tokenopts[x2] && tokenopts[x2] != L';' && tokenopts[x2] != L':' && tokenopts[x2] != L','; x2++);
tempchr = tokenopts[x2];
tokenopts[x2] = L'\0';
bool result = ::LookupPrivilegeValueW(NULL, tokenopts + x, &luidbuffer);
if (!result)
{
DWORD winerror = ::GetLastError();
CubicleSoft::StaticWCMixedVar<WCHAR[8192]> TempVar;
TempVar.SetFormattedStr(L"The specified privilege '%ls' in the token options is invalid.", tokenopts + x);
DumpWideErrorMsg(TempVar.GetStr(), "invalid_privilege", winerror);
}
tokenopts[x2] = tempchr;
x = x2;
return result;
}
DWORD GetNextTokenOptsAttrs(LPWSTR tokenopts, size_t &x)
{
size_t x2;
WCHAR tempchr;
if (tokenopts[x] != L':') return 0;
x++;
for (x2 = x; tokenopts[x2] && tokenopts[x2] != L';' && tokenopts[x2] != L','; x2++);
tempchr = tokenopts[x2];
tokenopts[x2] = L'\0';
DWORD result = (DWORD)_wtoi(tokenopts + x);
tokenopts[x2] = tempchr;
x = x2;
return result;
}
// Attempts to locate an existing token that matches the input option string.
// duptype is ignored if accessmode does not specify TOKEN_DUPLICATE.
// Example: FindExistingTokenFromOpts(L"S-1-16-16384,SeDebugPrivilege,SeAssignPrimaryTokenPrivilege", true)
HANDLE FindExistingTokenFromOpts(LPWSTR tokenopts, TOKEN_TYPE duptype, DWORD accessmode = TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY)
{
if (tokenopts[0] != L'S') return GetTokenFromPID(_wtoi(tokenopts), duptype, accessmode);
// Split and convert the options into SIDs and privilege LUIDs.
CubicleSoft::StaticWCMixedVar<WCHAR[8192]> TempVar;
size_t x, x2, numsids, numluids;
PSID *sids = NULL;
LUID *luids = NULL;
TempVar.SetStr(tokenopts);
WCHAR *tokenopts2 = TempVar.GetStr();
GetNumSIDsAndLUIDs(tokenopts2, numsids, numluids);
if (numsids) sids = (PSID *)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, numsids * sizeof(PSID));
if (numluids) luids = (LUID *)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, numluids * sizeof(LUID));
bool valid = true;
x = 0;
numsids = 0;
numluids = 0;
while (tokenopts2[x])
{
for (; tokenopts2[x] && tokenopts2[x] != L'S'; x++);
if (tokenopts2[x] == L'S')
{
if (tokenopts2[x + 1] == L'-')
{
valid = GetNextTokenOptsSID(tokenopts2, x, sids[numsids]);
if (!valid) break;
numsids++;
}
else if (tokenopts2[x + 1] == L'e')
{
valid = GetNextTokenOptsLUID(tokenopts2, x, luids[numluids]);
if (!valid) break;
numluids++;
}
}
for (; tokenopts2[x] && tokenopts2[x] != L','; x++);
if (tokenopts2[x] == L',') x++;
}
// Find a process that has matching SIDs and LUIDs.
HANDLE result = INVALID_HANDLE_VALUE;
if (valid)
{
// Enable SeDebugPrivilege.
SetThreadProcessPrivilege(L"SeDebugPrivilege", true);
// Get the list of currently running processes.
HANDLE snaphandle, tempproc, proctoken, duptoken;
PTOKEN_USER user = NULL;
PTOKEN_GROUPS groups = NULL;
PTOKEN_PRIVILEGES privs = NULL;
BOOL result2;
snaphandle = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snaphandle == INVALID_HANDLE_VALUE) DumpErrorMsg("Unable to retrieve the list of running processes.", "create_toolhelp32_snapshot_failed", ::GetLastError());
else
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (::Process32First(snaphandle, &pe32))
{
do
{
// Open a handle to the process.
tempproc = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID);
if (tempproc == NULL) tempproc = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe32.th32ProcessID);
if (tempproc != NULL)
{
result2 = ::OpenProcessToken(tempproc, accessmode, &proctoken);
if (result2 == NULL && (accessmode & TOKEN_QUERY_SOURCE)) result2 = ::OpenProcessToken(tempproc, accessmode & ~TOKEN_QUERY_SOURCE, &proctoken);
// DWORD pid = ::GetProcessId(tempproc);
::CloseHandle(tempproc);
if (result2)
{
// Load token user, groups, and privileges.
user = (PTOKEN_USER)AllocateAndGetTokenInformation(proctoken, TokenUser, 4096);
groups = (PTOKEN_GROUPS)AllocateAndGetTokenInformation(proctoken, TokenGroups, 4096);
privs = (PTOKEN_PRIVILEGES)AllocateAndGetTokenInformation(proctoken, TokenPrivileges, 4096);