-
Notifications
You must be signed in to change notification settings - Fork 1
/
Invoke-PrivescCheck.ps1
6270 lines (4776 loc) · 244 KB
/
Invoke-PrivescCheck.ps1
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
<#
This scripts is an extended and updated version of PowerUp. I tried to filter out as many false
positives as I could and I also added some extra checks based on well known privilege escalation
cheat sheets (see links below).
Author: @itm4n
Credit: @harmj0y @mattifestation
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
Links:
https://github.com/itm4n
https://github.com/HarmJ0y/PowerUp
https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/
https://book.hacktricks.xyz/windows/windows-local-privilege-escalation
#>
#Requires -Version 2
# ----------------------------------------------------------------
# Win32 stuff
# ----------------------------------------------------------------
#region Win32
<#
https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1
https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/
#>
$CSharpSource = @'
private const Int32 ANYSIZE_ARRAY = 1;
[System.FlagsAttribute]
public enum ServiceAccessFlags : uint
{
QueryConfig = 1,
ChangeConfig = 2,
QueryStatus = 4,
EnumerateDependents = 8,
Start = 16,
Stop = 32,
PauseContinue = 64,
Interrogate = 128,
UserDefinedControl = 256,
Delete = 65536,
ReadControl = 131072,
WriteDac = 262144,
WriteOwner = 524288,
Synchronize = 1048576,
AccessSystemSecurity = 16777216,
GenericAll = 268435456,
GenericExecute = 536870912,
GenericWrite = 1073741824,
GenericRead = 2147483648
}
[StructLayout(LayoutKind.Sequential)]
public struct LUID {
public UInt32 LowPart;
public Int32 HighPart;
}
[StructLayout(LayoutKind.Sequential)]
public struct SID_AND_ATTRIBUTES {
public IntPtr Sid;
public int Attributes;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct LUID_AND_ATTRIBUTES {
public LUID Luid;
public UInt32 Attributes;
}
public struct TOKEN_USER {
public SID_AND_ATTRIBUTES User;
}
public struct TOKEN_PRIVILEGES {
public int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=ANYSIZE_ARRAY)]
public LUID_AND_ATTRIBUTES [] Privileges;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPROW_OWNER_PID
{
public uint state;
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint remoteAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] remotePort;
public uint owningPid;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPROW_OWNER_PID
{
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint owningPid;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCP6ROW_OWNER_PID
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] localAddr;
public uint localScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] remoteAddr;
public uint remoteScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] remotePort;
public uint state;
public uint owningPid;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDP6ROW_OWNER_PID
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] localAddr;
public uint localScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint owningPid;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPTABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_TCPROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPTABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_UDPROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCP6TABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_TCP6ROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDP6TABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_UDP6ROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct FILETIME
{
public uint dwLowDateTime;
public uint dwHighDateTime;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct CREDENTIAL
{
public uint Flags;
public uint Type;
public string TargetName;
public string Comment;
public FILETIME LastWritten;
public uint CredentialBlobSize;
public IntPtr CredentialBlob;
public uint Persist;
public uint AttributeCount;
public IntPtr Attributes;
public string TargetAlias;
public string UserName;
}
[StructLayout(LayoutKind.Sequential)]
public struct UNICODE_STRING
{
public ushort Length;
public ushort MaximumLength;
public IntPtr Buffer;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct VAULT_ITEM_7
{
public Guid SchemaId;
public string FriendlyName;
public IntPtr Resource;
public IntPtr Identity;
public IntPtr Authenticator;
public UInt64 LastWritten;
public UInt32 Flags;
public UInt32 PropertiesCount;
public IntPtr Properties;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct VAULT_ITEM_8
{
public Guid SchemaId;
public string FriendlyName;
public IntPtr Resource;
public IntPtr Identity;
public IntPtr Authenticator;
public IntPtr PackageSid;
public UInt64 LastWritten;
public UInt32 Flags;
public UInt32 PropertiesCount;
public IntPtr Properties;
}
[StructLayout(LayoutKind.Sequential)]
public struct VAULT_ITEM_DATA_HEADER
{
public UInt32 SchemaElementId;
public UInt32 Unknown1;
public UInt32 Type;
public UInt32 Unknown2;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WLAN_INTERFACE_INFO
{
public Guid InterfaceGuid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string strInterfaceDescription;
public uint isState; // WLAN_INTERFACE_STATE
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WLAN_PROFILE_INFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string strProfileName;
public uint dwFlags;
}
[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool QueryServiceObjectSecurity(IntPtr serviceHandle, System.Security.AccessControl.SecurityInfos secInfo, byte[] lpSecDesrBuf, uint bufSize, out uint bufSizeNeeded);
[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseServiceHandle(IntPtr hSCObject);
[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetTokenInformation(IntPtr TokenHandle, UInt32 TokenInformationClass, IntPtr TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool LookupAccountSid(string lpSystemName, IntPtr Sid, System.Text.StringBuilder lpName, ref uint cchName, System.Text.StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out int peUse);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool LookupPrivilegeName(string lpSystemName, IntPtr lpLuid, System.Text.StringBuilder lpName, ref int cchName );
[DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CredEnumerate(IntPtr Filter, UInt32 Flags, out UInt32 Count, out IntPtr Credentials);
[DllImport("advapi32.dll")]
public static extern void CredFree(IntPtr Buffer);
[DllImport("advapi32.dll", SetLastError=false)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsTextUnicode(IntPtr buf, UInt32 len, ref UInt32 opt);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
public static extern UInt64 GetTickCount64();
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern uint GetFirmwareEnvironmentVariable(string lpName, string lpGuid, IntPtr pBuffer, uint nSize);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool GetFirmwareType(ref uint FirmwareType);
[DllImport("iphlpapi.dll", SetLastError=true)]
public static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int pdwSize, bool bOrder, int ulAf, uint TableClass, uint Reserved);
[DllImport("iphlpapi.dll", SetLastError=true)]
public static extern uint GetExtendedUdpTable(IntPtr pUdpTable, ref int pdwSize, bool bOrder, int ulAf, uint TableClass, uint Reserved);
[DllImport("vaultcli.dll", SetLastError=false)]
public static extern uint VaultEnumerateVaults(uint dwFlags, out int VaultsCount, out IntPtr ppVaultGuids);
[DllImport("vaultcli.dll", SetLastError=false)]
public static extern uint VaultOpenVault(IntPtr pVaultId, uint dwFlags, out IntPtr pVaultHandle);
[DllImport("vaultcli.dll", SetLastError=false)]
public static extern uint VaultEnumerateItems(IntPtr pVaultHandle, uint dwFlags, out int ItemsCount, out IntPtr ppItems);
[DllImport("vaultcli.dll", SetLastError=false, EntryPoint="VaultGetItem")]
public static extern uint VaultGetItem7(IntPtr pVaultHandle, ref Guid guidSchemaId, IntPtr pResource, IntPtr pIdentity, IntPtr pUnknown, uint iUnknown, out IntPtr pItem);
[DllImport("vaultcli.dll", SetLastError=false, EntryPoint="VaultGetItem")]
public static extern uint VaultGetItem8(IntPtr pVaultHandle, ref Guid guidSchemaId, IntPtr pResource, IntPtr pIdentity, IntPtr pPackageSid, IntPtr pUnknown, uint iUnknown, out IntPtr pItem);
[DllImport("vaultcli.dll", SetLastError=false)]
public static extern uint VaultFree(IntPtr pVaultItem);
[DllImport("vaultcli.dll", SetLastError=false)]
public static extern uint VaultCloseVault(ref IntPtr pVaultHandle);
[DllImport("Wlanapi.dll")]
public static extern uint WlanOpenHandle(uint dwClientVersion, IntPtr pReserved, out uint pdwNegotiatedVersion, out IntPtr hClientHandle);
[DllImport("Wlanapi.dll")]
public static extern uint WlanCloseHandle(IntPtr hClientHandle, IntPtr pReserved);
[DllImport("Wlanapi.dll")]
public static extern uint WlanEnumInterfaces(IntPtr hClientHandle, IntPtr pReserved, ref IntPtr ppInterfaceList);
[DllImport("Wlanapi.dll")]
public static extern void WlanFreeMemory(IntPtr pMemory);
[DllImport("Wlanapi.dll")]
public static extern uint WlanGetProfileList(IntPtr hClientHandle, [MarshalAs(UnmanagedType.LPStruct)]Guid interfaceGuid, IntPtr pReserved, out IntPtr ppProfileList);
[DllImport("Wlanapi.dll")]
public static extern uint WlanGetProfile(IntPtr clientHandle, [MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [MarshalAs(UnmanagedType.LPWStr)] string profileName, IntPtr pReserved, [MarshalAs(UnmanagedType.LPWStr)] out string profileXml, ref uint flags, out uint pdwGrantedAccess);
'@
try {
# Is the Type already defined?
[PrivescCheck.Win32] | Out-Null
} catch {
# If not, create it by compiling the C# code in memory
$CompilerParameters = New-Object -TypeName System.CodeDom.Compiler.CompilerParameters
$CompilerParameters.GenerateInMemory = $True
$CompilerParameters.GenerateExecutable = $False
#$Compiler = New-Object -TypeName Microsoft.CSharp.CSharpCodeProvider
#$Compiler.CompileAssemblyFromSource($CompilerParameters, $CSharpSource)
Add-Type -MemberDefinition $CSharpSource -Name 'Win32' -Namespace 'PrivescCheck' -Language CSharp -CompilerParameters $CompilerParameters
}
#endregion Win32
# ----------------------------------------------------------------
# Helpers
# ----------------------------------------------------------------
#region Helpers
$global:IgnoredPrograms = @("Common Files", "Internet Explorer", "ModifiableWindowsApps", "PackageManagement", "Windows Defender", "Windows Defender Advanced Threat Protection", "Windows Mail", "Windows Media Player", "Windows Multimedia Platform", "Windows NT", "Windows Photo Viewer", "Windows Portable Devices", "Windows Security", "WindowsPowerShell", "Microsoft.NET", "Windows Portable Devices", "dotnet", "MSBuild", "Intel", "Reference Assemblies")
function Convert-DateToString {
<#
.SYNOPSIS
Helper - Converts a DateTime object to a string representation
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
The output string is a simplified version of the ISO format: YYYY-MM-DD hh:mm:ss.
.PARAMETER Date
A System.DateTime object
.EXAMPLE
PS C:\> $Date = Get-Date; Convert-DateToString -Date $Date
2020-01-16 - 10:26:11
#>
[CmdletBinding()] param(
[System.DateTime]
$Date
)
$OutString = ""
$OutString += $Date.ToString('yyyy-MM-dd - HH:mm:ss')
#$OutString += " ($($Date.ToString('o')))" # ISO format
$OutString
}
function Convert-ServiceTypeToString {
<#
.SYNOPSIS
Helper - Converts a service type (integer) to its actual name
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
Services have a type which is saved as an integer in the registry. This function will retrieve
the "name" of the type based on this integer value.
.PARAMETER ServiceType
A service type as an integer
.EXAMPLE
PS C:\> Convert-ServiceTypeToString -ServiceType 16
Win32OwnProcess
#>
[CmdletBinding()] param(
[int]
$ServiceType
)
$ServiceTypeEnum = @{
"KernelDriver" = "1";
"FileSystemDriver" = "2";
"Adapter" = "4";
"RecognizerDriver" = "8";
"Win32OwnProcess" = "16";
"Win32ShareProcess" = "32";
"InteractiveProcess" = "256";
}
$ServiceTypeEnum.GetEnumerator() | ForEach-Object {
if ( $_.value -band $ServiceType )
{
$_.name
}
}
}
function Convert-ServiceStartModeToString {
<#
.SYNOPSIS
Helper - Convert a Start mode (integer) to its actual name
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
Services have a Start mode (e.g.: Automatic), which is saved as an integer in the registry.
This function will retrieve the "name" of the Start mode based on this integer value.
.PARAMETER StartMode
A Start mode as an integer
.EXAMPLE
PS C:\> Convert-ServiceStartModeToString -StartMode 2
Automatic
#>
[CmdletBinding()] param(
[int]
$StartMode
)
$StartModeEnum = @{
"Boot" = "0";
"System" = "1";
"Automatic" = "2";
"Manual" = "3";
"Disabled" = "4";
}
$StartModeEnum.GetEnumerator() | ForEach-Object {
if ( $_.Value -eq $StartMode )
{
$_.Name
}
}
}
function Test-IsKnownService {
[CmdletBinding()] param(
[object]$Service
)
if ($Service) {
$ImagePath = $Service.ImagePath
$SeparationCharacterSets = @('"', "'", ' ', "`"'", '" ', "' ", "`"' ")
ForEach($SeparationCharacterSet in $SeparationCharacterSets) {
$CandidatePaths = $ImagePath.Split($SeparationCharacterSet) | Where-Object {$_ -and ($_.trim() -ne '')}
ForEach($CandidatePath in $CandidatePaths) {
$TempPath = $([System.Environment]::ExpandEnvironmentVariables($CandidatePath))
$TempPathResolved = Resolve-Path -Path $TempPath -ErrorAction SilentlyContinue -ErrorVariable ErrorResolvePath
if (-not $ErrorResolvePath) {
$File = Get-Item -Path $TempPathResolved -ErrorAction SilentlyContinue -ErrorVariable ErrorGetItem
if (-not $ErrorGetItem) {
if ($File.VersionInfo.LegalCopyright -Like "*Microsoft Corporation*") {
return $True
} else {
return $False
}
}
}
}
}
}
return $False
}
function Get-UserPrivileges {
<#
.SYNOPSIS
Helper - Enumerates the privileges of the current user
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
Enumerates the privileges of the current user using the Windows API. First, it gets a handle
to the current access token using OpenProcessToken. Then it calls GetTokenInformation to list
all the privileges that it contains along with their state (enabled/disabled). For each result
a custom object is returned, indicating the name of the privilege and its state.
.EXAMPLE
PS C:\> Get-UserPrivileges
Name State Description
---- ------ -----------
SeShutdownPrivilege Disabled Shut down the system
SeChangeNotifyPrivilege Enabled Bypass traverse checking
SeUndockPrivilege Disabled Remove computer from docking station
SeIncreaseWorkingSetPrivilege Disabled Increase a process working set
SeTimeZonePrivilege Disabled Change the time zone
.LINK
https://docs.microsoft.com/en-us/windows/win32/secauthz/privilege-constants
#>
[CmdletBinding()] param()
function Get-PrivilegeDescription {
[CmdletBinding()] param(
[string]
$Name
)
$PrivilegeDescriptions = @{
"SeAssignPrimaryTokenPrivilege" = "Replace a process-level token";
"SeAuditPrivilege" = "Generate security audits";
"SeBackupPrivilege" = "Back up files and directories";
"SeChangeNotifyPrivilege" = "Bypass traverse checking";
"SeCreateGlobalPrivilege" = "Create global objects";
"SeCreatePagefilePrivilege" = "Create a pagefile";
"SeCreatePermanentPrivilege" = "Create permanent shared objects";
"SeCreateSymbolicLinkPrivilege" = "Create symbolic links";
"SeCreateTokenPrivilege" = "Create a token object";
"SeDebugPrivilege" = "Debug programs";
"SeDelegateSessionUserImpersonatePrivilege" = "Impersonate other users";
"SeEnableDelegationPrivilege" = "Enable computer and user accounts to be trusted for delegation";
"SeImpersonatePrivilege" = "Impersonate a client after authentication";
"SeIncreaseBasePriorityPrivilege" = "Increase scheduling priority";
"SeIncreaseQuotaPrivilege" = "Adjust memory quotas for a process";
"SeIncreaseWorkingSetPrivilege" = "Increase a process working set";
"SeLoadDriverPrivilege" = "Load and unload device drivers";
"SeLockMemoryPrivilege" = "Lock pages in memory";
"SeMachineAccountPrivilege" = "Add workstations to domain";
"SeManageVolumePrivilege" = "Manage the files on a volume";
"SeProfileSingleProcessPrivilege" = "Profile single process";
"SeRelabelPrivilege" = "Modify an object label";
"SeRemoteShutdownPrivilege" = "Force shutdown from a remote system";
"SeRestorePrivilege" = "Restore files and directories";
"SeSecurityPrivilege" = "Manage auditing and security log";
"SeShutdownPrivilege" = "Shut down the system";
"SeSyncAgentPrivilege" = "Synchronize directory service data";
"SeSystemEnvironmentPrivilege" = "Modify firmware environment values";
"SeSystemProfilePrivilege" = "Profile system performance";
"SeSystemtimePrivilege" = "Change the system time";
"SeTakeOwnershipPrivilege" = "Take ownership of files or other objects";
"SeTcbPrivilege" = "Act as part of the operating system";
"SeTimeZonePrivilege" = "Change the time zone";
"SeTrustedCredManAccessPrivilege" = "Access Credential Manager as a trusted caller";
"SeUndockPrivilege" = "Remove computer from docking station";
"SeUnsolicitedInputPrivilege" = "N/A";
}
$PrivilegeDescriptions[$Name]
}
# Get a handle to a process the current user owns
$ProcessHandle = [PrivescCheck.Win32]::GetCurrentProcess()
Write-Verbose "Current process handle: $ProcessHandle"
# Get a handle to the token corresponding to this process
$TOKEN_QUERY= 0x0008
[IntPtr]$TokenHandle = [IntPtr]::Zero
$Success = [PrivescCheck.Win32]::OpenProcessToken($ProcessHandle, $TOKEN_QUERY, [ref]$TokenHandle);
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
Write-Verbose "OpenProcessToken() OK - Token handle: $TokenHandle"
# TOKEN_INFORMATION_CLASS - 3 = TokenPrivileges
$TokenPrivilegesPtrSize = 0
$Success = [PrivescCheck.Win32]::GetTokenInformation($TokenHandle, 3, 0, $Null, [ref]$TokenPrivilegesPtrSize)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if (-not ($TokenPrivilegesPtrSize -eq 0)) {
Write-Verbose "GetTokenInformation() OK - TokenPrivilegesPtrSize = $TokenPrivilegesPtrSize"
[IntPtr]$TokenPrivilegesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivilegesPtrSize)
$Success = [PrivescCheck.Win32]::GetTokenInformation($TokenHandle, 3, $TokenPrivilegesPtr, $TokenPrivilegesPtrSize, [ref]$TokenPrivilegesPtrSize)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
# Convert the unmanaged memory at offset $TokenPrivilegesPtr to a TOKEN_PRIVILEGES managed type
$TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivilegesPtr, [type] [PrivescCheck.Win32+TOKEN_PRIVILEGES])
#$Offset = [System.IntPtr]::Add($TokenPrivilegesPtr, 4)
# Properly Incrementing an IntPtr
# https://docs.microsoft.com/en-us/archive/blogs/jaredpar/properly-incrementing-an-intptr
$Offset = [IntPtr] ($TokenPrivilegesPtr.ToInt64() + 4)
Write-Verbose "GetTokenInformation() OK - Privilege count: $($TokenPrivileges.PrivilegeCount)"
For ($i = 0; $i -lt $TokenPrivileges.PrivilegeCount; $i++) {
# Cast the unmanaged memory at offset
$LuidAndAttributes = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Offset, [type] [PrivescCheck.Win32+LUID_AND_ATTRIBUTES])
# Copy LUID to unmanaged memory
$LuidSize = [System.Runtime.InteropServices.Marshal]::SizeOf($LuidAndAttributes.Luid)
[IntPtr]$LuidPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($LuidSize)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($LuidAndAttributes.Luid, $LuidPtr, $True)
# public static extern bool LookupPrivilegeName(string lpSystemName, IntPtr lpLuid, System.Text.StringBuilder lpName, ref int cchName );
[int]$Length = 0
$Success = [PrivescCheck.Win32]::LookupPrivilegeName($Null, $LuidPtr, $Null, [ref]$Length)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if (-not ($Length -eq 0)) {
Write-Verbose "LookupPrivilegeName() OK - Length = $Length"
$Name = New-Object -TypeName System.Text.StringBuilder
$Name.EnsureCapacity($Length + 1) |Out-Null
$Success = [PrivescCheck.Win32]::LookupPrivilegeName($Null, $LuidPtr, $Name, [ref]$Length)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
$PrivilegeName = $Name.ToString()
# SE_PRIVILEGE_ENABLED = 0x00000002
$PrivilegeEnabled = ($LuidAndAttributes.Attributes -band 2) -eq 2
Write-Verbose "LookupPrivilegeName() OK - Name: $PrivilegeName - Enabled: $PrivilegeEnabled"
$PrivilegeObject = New-Object -TypeName PSObject
$PrivilegeObject | Add-Member -MemberType "NoteProperty" -Name "Name" -Value $PrivilegeName
$PrivilegeObject | Add-Member -MemberType "NoteProperty" -Name "State" -Value $(if ($PrivilegeEnabled) { "Enabled" } else { "Disabled" })
$PrivilegeObject | Add-Member -MemberType "NoteProperty" -Name "Description" -Value $(Get-PrivilegeDescription -Name $PrivilegeName)
$PrivilegeObject
} else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
} else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
# Cleanup - Free unmanaged memory
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($LuidPtr)
# Update the offset to point to the next LUID_AND_ATTRIBUTES structure in the unmanaged buffer
#$Offset = [System.IntPtr]::Add($Offset, [System.Runtime.InteropServices.Marshal]::SizeOf($LuidAndAttributes))
# Properly Incrementing an IntPtr
# https://docs.microsoft.com/en-us/archive/blogs/jaredpar/properly-incrementing-an-intptr
$Offset = [IntPtr] ($Offset.ToInt64() + [System.Runtime.InteropServices.Marshal]::SizeOf($LuidAndAttributes))
}
} else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
# Cleanup - Free unmanaged memory
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenPrivilegesPtr)
} else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
# Cleanup - Close Token handle
$Success = [PrivescCheck.Win32]::CloseHandle($TokenHandle)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
Write-Verbose "Token handle closed"
} else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
} else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
}
function Get-UserFromProcess() {
<#
.SYNOPSIS
Helper - Gets the user associated to a given process
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
First it gets a handle to the process identified by the given PID. Then, it uses this handle to
access the process token. GetTokenInformation() is then used to query the SID of the user.
Finally the SID is converted to a domain name, user name and SID type. All this information is
returned in a custom PS object.
.PARAMETER ProcessId
The PID of the target process
.EXAMPLE
PS C:\> Get-UserFromProcess -ProcessId 6972
Domain Username Type
------ -------- ----
DESKTOP-FEOHNOM lab-user User
#>
[CmdletBinding()] param(
[Parameter(Mandatory=$true)]
[int]
$ProcessId
)
function Get-SidTypeName {
param(
$SidType
)
$SidTypeEnum = @{
"User" = "1";
"Group" = "2";
"Domain" = "3";
"Alias" = "4";
"WellKnownGroup" = "5";
"DeletedAccount" = "6";
"Invalid" = "7";
"Unknown" = "8";
"Computer" = "9";
"Label" = "10";
"LogonSession" = "11";
}
$SidTypeEnum.GetEnumerator() | ForEach-Object {
if ( $_.value -eq $SidType )
{
$_.name
}
}
}
# PROCESS_QUERY_INFORMATION = 0x0400
$AccessFlags = 0x0400
$ProcessHandle = [PrivescCheck.Win32]::OpenProcess($AccessFlags, $False, $ProcessId)
#$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if (-not ($Null -eq $ProcessHandle)) {
Write-Verbose "OpenProcess() OK - Handle: $ProcessHandle"
$TOKEN_QUERY= 0x0008
[IntPtr]$TokenHandle = [IntPtr]::Zero
$Success = [PrivescCheck.Win32]::OpenProcessToken($ProcessHandle, $TOKEN_QUERY, [ref]$TokenHandle);
#$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
Write-Verbose "OpenProcessToken() OK - Handle: $ProcessHandle"
# TOKEN_INFORMATION_CLASS - 1 = TokenUser
$TokenUserPtrSize = 0
$Success = [PrivescCheck.Win32]::GetTokenInformation($TokenHandle, 1, 0, $Null, [ref]$TokenUserPtrSize)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if (($TokenUserPtrSize -gt 0) -and ($LastError -eq 122)) {
Write-Verbose "GetTokenInformation() OK - Size: $TokenUserPtrSize"
[IntPtr]$TokenUserPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenUserPtrSize)
$Success = [PrivescCheck.Win32]::GetTokenInformation($TokenHandle, 1, $TokenUserPtr, $TokenUserPtrSize, [ref]$TokenUserPtrSize)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
Write-Verbose "GetTokenInformation() OK"
# Cast unmanaged memory to managed TOKEN_USER struct
$TokenUser = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenUserPtr, [type] [PrivescCheck.Win32+TOKEN_USER])
$SidType = 0
$UserNameSize = 256
$UserName = New-Object -TypeName System.Text.StringBuilder
$UserName.EnsureCapacity(256) | Out-Null
$UserDomainSize = 256
$UserDomain = New-Object -TypeName System.Text.StringBuilder
$UserDomain.EnsureCapacity(256) | Out-Null
$Success = [PrivescCheck.Win32]::LookupAccountSid($Null, $TokenUser.User.Sid, $UserName, [ref]$UserNameSize, $UserDomain, [ref]$UserDomainSize, [ref]$SidType)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
$UserObject = New-Object -TypeName PSObject
$UserObject | Add-Member -MemberType "NoteProperty" -Name "Domain" -Value $UserDomain.ToString()
$UserObject | Add-Member -MemberType "NoteProperty" -Name "Username" -Value $UserName.ToString()
$UserObject | Add-Member -MemberType "NoteProperty" -Name "DisplayName" -Value "$($UserDomain.ToString())\$($UserName.ToString())"
$UserObject | Add-Member -MemberType "NoteProperty" -Name "Type" -Value $(Get-SidTypeName $SidType)
$UserObject
} else {
Write-Verbose "LookupAccountSid() failed."
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
} else {
Write-Verbose "GetTokenInformation() failed."
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
# Cleanup - Free unmanaged memory
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenUserPtr)
}
# Cleanup - Close token handle
$Success = [PrivescCheck.Win32]::CloseHandle($TokenHandle)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
Write-Verbose "Token handle closed"
} else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
} else {
Write-Verbose "Can't open token for process with PID $ProcessId"
}
# Cleanup - Close process handle
$Success = [PrivescCheck.Win32]::CloseHandle($ProcessHandle)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Success) {
Write-Verbose "Process handle closed"
} else {
Write-Verbose ([ComponentModel.Win32Exception] $LastError)
}
} else {
Write-Verbose "Can't open process with PID $ProcessId"
}
}
function Get-NetworkEndpoints {
<#
.SYNOPSIS
Helper - Gets a list of listening ports (TCP/UDP)
Author: @itm4n
License: BSD 3-Clause
.DESCRIPTION
It uses the 'GetExtendedTcpTable' and 'GetExtendedUdpTable' functions of the Windows API to
list the TCP/UDP endpoints on the local machine. It handles both IPv4 and IPv6. For each
entry in the table, a custom PS object is returned, indicating the IP version (IPv4/IPv6),
the protocol (TCP/UDP), the local address (e.g.: "0.0.0.0:445"), the state, the PID of the
associated process and the name of the process. The name of the process is retrieved through
a call to "Get-Process -PID <PID>".
.EXAMPLE
PS C:\> Get-NetworkEndpoints | ft
IP Proto LocalAddress LocalPort Endpoint State PID Name
-- ----- ------------ --------- -------- ----- --- ----
IPv4 TCP 0.0.0.0 135 0.0.0.0:135 LISTENING 1216 svchost
IPv4 TCP 0.0.0.0 445 0.0.0.0:445 LISTENING 4 System
IPv4 TCP 0.0.0.0 5040 0.0.0.0:5040 LISTENING 8580 svchost
IPv4 TCP 0.0.0.0 49664 0.0.0.0:49664 LISTENING 984 lsass
IPv4 TCP 0.0.0.0 49665 0.0.0.0:49665 LISTENING 892 wininit
IPv4 TCP 0.0.0.0 49666 0.0.0.0:49666 LISTENING 1852 svchost
IPv4 TCP 0.0.0.0 49667 0.0.0.0:49667 LISTENING 1860 svchost
IPv4 TCP 0.0.0.0 49668 0.0.0.0:49668 LISTENING 2972 svchost
IPv4 TCP 0.0.0.0 49669 0.0.0.0:49669 LISTENING 4480 spoolsv
IPv4 TCP 0.0.0.0 49670 0.0.0.0:49670 LISTENING 964 services
.EXAMPLE
PS C:\> Get-NetworkEndpoints -UDP -IPv6 | ft
IP Proto LocalAddress LocalPort Endpoint State PID Name
-- ----- ------------ --------- -------- ----- --- ----
IPv6 UDP :: 500 [::]:500 N/A 5000 svchost
IPv6 UDP :: 3702 [::]:3702 N/A 4128 dasHost
IPv6 UDP :: 3702 [::]:3702 N/A 4128 dasHost
IPv6 UDP :: 4500 [::]:4500 N/A 5000 svchost
IPv6 UDP :: 62212 [::]:62212 N/A 4128 dasHost
IPv6 UDP ::1 1900 [::1]:1900 N/A 5860 svchost
IPv6 UDP ::1 63168 [::1]:63168 N/A 5860 svchost
#>
[CmdletBinding()] param(
[switch]
$IPv6 = $False, # IPv4 by default
[switch]
$UDP = $False # TCP by default
)
$AF_INET6 = 23
$AF_INET = 2
if ($IPv6) {
$IpVersion = $AF_INET6
} else {
$IpVersion = $AF_INET
}
if ($UDP) {
$UDP_TABLE_OWNER_PID = 1
[int]$BufSize = 0
$Result = [PrivescCheck.Win32]::GetExtendedUdpTable([IntPtr]::Zero, [ref]$BufSize, $True, $IpVersion, $UDP_TABLE_OWNER_PID, 0)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
} else {
$TCP_TABLE_OWNER_PID_LISTENER = 3
[int]$BufSize = 0
$Result = [PrivescCheck.Win32]::GetExtendedTcpTable([IntPtr]::Zero, [ref]$BufSize, $True, $IpVersion, $TCP_TABLE_OWNER_PID_LISTENER, 0)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
}
if ($Result -eq 122) {
Write-Verbose "GetExtendedProtoTable() OK - Size: $BufSize"
[IntPtr]$TablePtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BufSize)
if ($UDP) {
$Result = [PrivescCheck.Win32]::GetExtendedUdpTable($TablePtr, [ref]$BufSize, $True, $IpVersion, $UDP_TABLE_OWNER_PID, 0)
$LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
} else {