-
Notifications
You must be signed in to change notification settings - Fork 2
/
PInvoke.Provider.fs
1741 lines (1476 loc) · 62.6 KB
/
PInvoke.Provider.fs
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
//Licensed to the Apache Software Foundation (ASF) under one
//or more contributor license agreements. See the NOTICE file
//distributed with this work for additional information
//regarding copyright ownership. The ASF licenses this file
//to you under the Apache License, Version 2.0 (the
//"License"); you may not use this file except in compliance
//with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing,
//software distributed under the License is distributed on an
//"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//KIND, either express or implied. See the License for the
//specific language governing permissions and limitations
//under the License.
module Fetters.PInvoke.Provider
open System
open System.Diagnostics
open System.Net
open System.Runtime.InteropServices
open System.Security.Principal
open Fetters.DotNet.Common
open Fetters.DomainTypes
///////
//Enums
///////
//// Arp section ////
type ArpEntryType =
|Other = 1
|Invalid = 2
|Dynamic = 3
|Static = 4
//// KERB Enum ////
[<Struct>]
[<Flags>]
// Unverified
type KERB_CACHE_OPTIONS =
|KERB_RETRIEVE_TICKET_DEFAULT = 0x0UL
|KERB_RETRIEVE_TICKET_DONT_USE_CACHE = 0x1UL
|KERB_RETRIEVE_TICKET_USE_CACHE_ONLY = 0x2UL
|KERB_RETRIEVE_TICKET_USE_CREDHANDLE = 0x4UL
|KERB_RETRIEVE_TICKET_AS_KERB_CRED = 0x8UL
|KERB_RETRIEVE_TICKET_WITH_SEC_CRED = 0x10UL
|KERB_RETRIEVE_TICKET_CACHE_TICKET = 0x20UL
|KERB_RETRIEVE_TICKET_MAX_LIFETIME = 0x40UL
[<Struct>]
type KERB_ENCRYPTION_TYPE =
|reserved0 = 0
|des_cbc_crc = 1
|des_cbc_md4 = 2
|des_cbc_md5 = 3
|reserved1 = 4
|des3_cbc_md5 = 5
|reserved2 = 6
|des3_cbc_sha1 = 7
|dsaWithSHA1_CmsOID = 9
|md5WithRSAEncryption_CmsOID = 10
|sha1WithRSAEncryption_CmsOID = 11
|rc2CBC_EnvOID = 12
|rsaEncryption_EnvOID = 13
|rsaES_OAEP_ENV_OID = 14
|des_ede3_cbc_Env_OID = 15
|des3_cbc_sha1_kd = 16
|aes128_cts_hmac_sha1_96 = 17
|aes256_cts_hmac_sha1_96 = 18
|aes128_cts_hmac_sha256_128 = 19
|aes256_cts_hmac_sha384_192 = 20
|rc4_hmac = 23
|rc4_hmac_exp = 24
|camellia128_cts_cmac = 25
|camellia256_cts_cmac = 26
|subkey_keymaterial = 65
[<Struct>]
type KERB_PROTOCOL_MESSAGE_TYPE =
|KerbDebugRequestMessage = 0u
|KerbQueryTicketCacheMessage = 1u
|KerbChangeMachinePasswordMessage = 2u
|KerbVerifyPacMessage = 3u
|KerbRetrieveTicketMessage = 4u
|KerbUpdateAddressesMessage = 5u
|KerbPurgeTicketCacheMessage = 6u
|KerbChangePasswordMessage = 7u
|KerbRetrieveEncodedTicketMessage = 8u
|KerbDecryptDataMessage = 9u
|KerbAddBindingCacheEntryMessage = 10u
|KerbSetPasswordMessage = 11u
|KerbSetPasswordExMessage = 12u
|KerbVerifyCredentialsMessage = 13u
|KerbQueryTicketCacheExMessage = 14u
|KerbPurgeTicketCacheExMessage = 15u
|KerbRefreshSmartcardCredentialsMessage = 16u
|KerbAddExtraCredentialsMessage = 17u
|KerbQuerySupplementalCredentialsMessage = 18u
|KerbTransferCredentialsMessage = 19u
|KerbQueryTicketCacheEx2Message = 20u
|KerbSubmitTicketMessage = 21u
|KerbAddExtraCredentialsExMessage = 22u
|KerbQueryKdcProxyCacheMessage = 23u
|KerbPurgeKdcProxyCacheMessage = 24u
|KerbQueryTicketCacheEx3Message = 25u
|KerbCleanupMachinePkinitCredsMessage = 26u
|KerbAddBindingCacheEntryExMessage = 27u
|KerbQueryBindingCacheMessage = 28u
|KerbPurgeBindingCacheMessage = 29u
|KerbQueryDomainExtendedPoliciesMessage = 30u
|KerbQueryS4U2ProxyCacheMessage = 31u
[<Struct>]
type SECURITY_LOGON_TYPE =
|UndefinedLogonType
|Interactive
|Network
|Batch
|Service
|Proxy
|Unlock
|NetworkCleartext
|NewCredentials
|RemoteInteractive
|CachedInteractive
|CachedRemoteInteractive
|CachedUnlock
//// RDP Enum Section ////
[<Struct>]
type WTS_CONNECTED_CLASS =
|Active
|Connected
|ConnectQuery
|Shadow
|Disconnected
|Idle
|Listen
|Reset
|Down
|Init
[<Struct>]
type WTS_INFO_CLASS =
|WTSClientAddress = 14
//// TCP dump Section ////
[<Struct>]
type MIB_TCP_STATE =
|CLOSED = 1
|LISTEN = 2
|SYN_SENT = 3
|SYN_RCVD = 4
|ESTAB = 5
|FIN_WAIT1 = 6
|FIN_WAIT2 = 7
|CLOSE_WAIT = 8
|CLOSING = 9
|LAST_ACK = 10
|TIME_WAIT = 11
|DELETE_TCB = 12
[<Struct>]
type SC_SERVICE_TAG_QUERY_TYPE =
|ServiceNameFromTagInformation = 1
|ServiceNamesReferencingModuleInformation = 2
|ServiceNameTagMappingInformation = 3
[<Struct>]
type TCP_TABLE_CLASS =
|TCP_TABLE_BASIC_LISTENER
|TCP_TABLE_BASIC_CONNECTIONS
|TCP_TABLE_BASIC_ALL
|TCP_TABLE_OWNER_PID_LISTENER
|TCP_TABLE_OWNER_PID_CONNECTIONS
|TCP_TABLE_OWNER_PID_ALL
|TCP_TABLE_OWNER_MODULE_LISTENER
|TCP_TABLE_OWNER_MODULE_CONNECTIONS
|TCP_TABLE_OWNER_MODULE_ALL
//// Token Section ////
[<Struct>]
type TOKEN_INFORMATION_CLASS =
|TokenUser = 1u
|TokenGroups = 2u
|TokenPrivileges = 3u
|TokenOwner = 4u
|TokenPrimaryGroup = 5u
|TokenDefaultDacl = 6u
|TokenSource = 7u
|TokenType = 8u
|TokenImpersonationLevel = 9u
|TokenStatistics = 10u
|TokenRestrictedSids = 11u
|TokenSessionId = 12u
|TokenGroupsAndPrivileges = 13u
|TokenSessionReference = 14u
|TokenSandBoxInert = 15u
|TokenAuditPolicy = 16u
|TokenOrigin = 17u
//// UDP Section ////
[<Struct>]
type UDP_TABLE_CLASS =
|UDP_TABLE_BASIC
|UDP_TABLE_OWNER_PID
|UDP_TABLE_OWNER_MODULE
//// Vault section ////
[<Struct>]
type VAULT_ELEMENT_TYPE =
|Undefined = -1
|Boolean = 0
|Short = 1
|UnsignedShort = 2
|Int = 3
|UnsignedInt = 4
|Double = 5
|Guid = 6
|String = 7
|ByteArray = 8
|TimeStamp = 9
|ProtectedArray = 10
|Attribute = 11
|Sid = 12
|Last = 13
[<Struct>]
type VAULT_SCHEMA_ELEMENT_ID =
|Illegal = 0
|Resource = 1
|Identity = 2
|Authenticator = 3
|Tag = 4
|PackageSid = 5
|AppStart = 100
|AppEnd = 10000
//////////////
//Struct types
//////////////
//// Arp Section ////
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type MIB_IPNETROW =
val mutable dwIndex : int32
val mutable dwPhysAddrLen : int32
val mutable mac0 : byte
val mutable mac1 : byte
val mutable mac2 : byte
val mutable mac3 : byte
val mutable mac4 : byte
val mutable mac5 : byte
val mutable mac6 : byte
val mutable mac7 : byte
val mutable dwAddr : int32
val mutable dwType : int32
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type MIB_IPNETTABLE =
val mutable numEntries : int32
val mutable tablePtr : IntPtr
//// LSA Section ////
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type LSA_STRING_IN =
val mutable length : uint16
val mutable maxLength : uint16
val mutable buffer : string
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type LSA_STRING_OUT =
val mutable length : uint16
val mutable maxLength : uint16
val mutable buffer : IntPtr
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type LUID =
val mutable lower: uint32
val mutable upper: int
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type SID_IDENTIFIER_AUTHORITY =
[<MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)>]
val mutable value: char []
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type SID =
val mutable revision : char
val mutable subauthcount : char
val mutable idauthority : SID_IDENTIFIER_AUTHORITY
val mutable subauthority : uint32
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
// Unverfied: Folks list some weird self-reference thing in the signatures
// but the docs say these two pointers only, so this is what I'm
// rolling with.
type SECURITY_HANDLE =
val mutable lower: IntPtr
val mutable upper: IntPtr
//// KERB section ////
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type KERB_CRYPTO_KEY =
val mutable keyType : int32
val mutable length : int32
val mutable value : IntPtr
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type KERB_EXTERNAL_NAME =
val mutable nameType : int16
val mutable nameCount : uint16
val mutable names : LSA_STRING_OUT
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type KERB_EXTERNAL_TICKET =
val mutable ServiceName : IntPtr
val mutable TargetName : IntPtr
val mutable ClientName : IntPtr
val mutable DomainName : LSA_STRING_OUT
val mutable TargetDomainName : LSA_STRING_OUT
val mutable AltTargetDomainName : LSA_STRING_OUT
val mutable SessionKey : KERB_CRYPTO_KEY
val mutable TicketFlags : uint32
val mutable Flags : uint32
val mutable KeyExpirationTime : int64
val mutable StartTime : int64
val mutable EndTime : int64
val mutable RenewUntil : int64
val mutable TimeSkew : int64
val mutable EncodedTicketSize : int32
val mutable EncodedTicket : IntPtr
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type KERB_TICKET_CACHE_INFO =
val mutable serverName : LSA_STRING_OUT
val mutable realmName : LSA_STRING_OUT
val mutable startTime : int64
val mutable endTime : int64
val mutable renewTime : int64
val mutable encryptionType : int32
val mutable ticketFlags : uint32
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type KERB_QUERY_TKT_CACHE_REQUEST =
val mutable messageType : KERB_PROTOCOL_MESSAGE_TYPE
val mutable logonID : LUID
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type KERB_QUERY_TKT_CACHE_RESPONSE =
val mutable messageType : KERB_PROTOCOL_MESSAGE_TYPE
val mutable countOfTickets : int
val mutable startOfTickets : IntPtr // A bodge
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type KERB_RETRIEVE_TKT_REQUEST =
val mutable messageType : KERB_PROTOCOL_MESSAGE_TYPE
val mutable logonID : LUID
val mutable targetName : LSA_STRING_IN
val mutable ticketFlags : uint64
val mutable cacheOptions : KERB_CACHE_OPTIONS
val mutable encryptionType : int64
val mutable credentialsHandle : SECURITY_HANDLE
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type KERB_RETRIEVE_TKT_RESPONSE =
val mutable ticket : KERB_EXTERNAL_TICKET
[<Struct>]
[<StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)>]
type LOCAL_GROUP_MEMBER_INFO2 =
val mutable lgrmi2_sid : IntPtr
val mutable lgrmi2_sidusage : int
val mutable lgrmi2_domainandname : string
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type SECURITY_LOGON_SESSION_DATA =
val mutable size : uint32
val mutable loginID : LUID
val mutable username : LSA_STRING_OUT
val mutable loginDomain : LSA_STRING_OUT
val mutable authenticationPackage : LSA_STRING_OUT
val mutable logonType : SECURITY_LOGON_TYPE
val mutable session : uint32
val mutable pSID : IntPtr
val mutable loginTime : uint64
val mutable logonServer : LSA_STRING_OUT
val mutable dnsDomainName : LSA_STRING_OUT
val mutable upn : LSA_STRING_OUT
type KerberosRequest =
|KERB_QUERY_TKT_CACHE_REQ of KERB_QUERY_TKT_CACHE_REQUEST
|KERB_RETRIEVE_TKT_REQ of KERB_RETRIEVE_TKT_REQUEST
type KerberosResponse =
|KERB_QUERY_TKT_CACHE_RESP of KERB_QUERY_TKT_CACHE_RESPONSE
|KERB_RETRIEVE_TKT_RESP of KERB_RETRIEVE_TKT_RESPONSE
type KerberosTicketStruct =
|KERB_EXTERNAL_TKT of KERB_EXTERNAL_TICKET
|KERB_TKT_CACHE_INFO of KERB_TICKET_CACHE_INFO
//// RDP section ////
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type WTS_SESSION_INFO_1 =
val mutable ExecEnvId : int32
val mutable State : WTS_CONNECTED_CLASS
val mutable SessionID : int32
val mutable pSessionName : string
val mutable pHostName : string
val mutable pUserName : string
val mutable pDomainName : string
val mutable pFarmName : string
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type WTS_CLIENT_ADDRESS =
val mutable addressFamily : uint32
[<MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)>]
val mutable addressRaw : byte[]
//// TCP Query Section ////
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type MIB_TCPROW_OWNER_MODULE =
val State : MIB_TCP_STATE
val LocalAddr : uint32
val LocalPort1 : byte
val LocalPort2 : byte
val LocalPort3 : byte
val LocalPort4 : byte
val RemoteAddr : uint32
val RemotePort1 : byte
val RemotePort2 : byte
val RemotePort3 : byte
val RemotePort4 : byte
val OwningPid : uint32
val CreateTimestamp : uint64
val OwningModuleInfo0 : uint64
val OwningModuleInfo1 : uint64
val OwningModuleInfo2 : uint64
val OwningModuleInfo3 : uint64
val OwningModuleInfo4 : uint64
val OwningModuleInfo5 : uint64
val OwningModuleInfo6 : uint64
val OwningModuleInfo7 : uint64
val OwningModuleInfo8 : uint64
val OwningModuleInfo9 : uint64
val OwningModuleInfo10 : uint64
val OwningModuleInfo11 : uint64
val OwningModuleInfo12 : uint64
val OwningModuleInfo13 : uint64
val OwningModuleInfo14 : uint64
val OwningModuleInfo15 : uint64
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type MIB_TCPTABLE_OWNER_MODULE =
val mutable numEntries : uint32
val mutable table : MIB_TCPROW_OWNER_MODULE
//// Token Section ////
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type LUID_AND_ATTRIBUTES =
val mutable luid : LUID
val mutable attributes : int32
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type TOKEN_PRIVILEGES =
val mutable privilegeCount : uint32
val mutable privilegeArray : IntPtr
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type SID_AND_ATTRIBUTES =
val mutable sid : IntPtr
val mutable attributes : uint32
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type TOKEN_GROUPS =
//Groups is a SID_AND_ATTRIBUTES struct array
val mutable GroupCount : uint32
val mutable Groups : IntPtr
//// UDP Section ////
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type MIB_UDPROW_OWNER_MODULE =
val LocalAddr : uint32
val LocalPort1 : byte
val LocalPort2 : byte
val LocalPort3 : byte
val LocalPort4 : byte
val OwningPid : uint32
val CreateTimestamp : uint64
val SpecificPortBind_Flags : uint32
val OwningModuleInfo0 : uint64
val OwningModuleInfo1 : uint64
val OwningModuleInfo2 : uint64
val OwningModuleInfo3 : uint64
val OwningModuleInfo4 : uint64
val OwningModuleInfo5 : uint64
val OwningModuleInfo6 : uint64
val OwningModuleInfo7 : uint64
val OwningModuleInfo8 : uint64
val OwningModuleInfo9 : uint64
val OwningModuleInfo10 : uint64
val OwningModuleInfo11 : uint64
val OwningModuleInfo12 : uint64
val OwningModuleInfo13 : uint64
val OwningModuleInfo14 : uint64
val OwningModuleInfo15 : uint64
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type MIB_UDPTABLE_OWNER_MODULE =
val numEntries : uint32
val table : MIB_UDPROW_OWNER_MODULE
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type SC_SERVICE_TAG_QUERY =
val mutable processId : uint32
val mutable serviceTag : uint32
val mutable unknown : uint32
val mutable buffer : IntPtr
//// Vault Dump Section ////
[<Struct>]
[<StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)>]
type VAULT_ITEM_WIN8 =
val mutable SchemaId : Guid
val mutable pszCredentialFriendlyName :IntPtr
val mutable pResourceElement : IntPtr
val mutable pIdentityElement : IntPtr
val mutable pAuthenticatorElement : IntPtr
val mutable pPackageSid : IntPtr
val mutable LastModified : uint64
val mutable dwFlags : uint32
val mutable dwPropertiesCount : uint32
val mutable pPropertyElements : IntPtr
[<Struct>]
[<StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)>]
type VAULT_ITEM_WIN7 =
val mutable SchemaId : Guid
val mutable pszCredentialFriendlyName :IntPtr
val mutable pResourceElement : IntPtr
val mutable pIdentityElement : IntPtr
val mutable pAuthenticatorElement : IntPtr
val mutable LastModified : uint64
val mutable dwFlags : uint32
val mutable dwPropertiesCount : uint32
val mutable pPropertyElements : IntPtr
[<Struct>]
[<StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)>]
type VAULT_ITEM_ELEMENT =
val mutable SchemaElementId : VAULT_SCHEMA_ELEMENT_ID
val mutable Type : VAULT_ELEMENT_TYPE
type VaultItem =
|WIN8VAULT of VAULT_ITEM_WIN8
|WIN7VAULT of VAULT_ITEM_WIN7
type VaultElementContent =
|EleGUID of Guid
|EleStr of string
|EleSID of SecurityIdentifier
/////////////////////
//Import Declarations
/////////////////////
//// advapi32 ////
[<DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)>]
extern bool OpenProcessToken(
IntPtr processHandle,
uint32 desiredAccess,
[<Out>] IntPtr& tokenHandle
)
[<DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)>]
extern bool DuplicateToken(
IntPtr existingTokenHandle,
int impersonationLevel,
[<Out>] IntPtr& duplicatTokenHandle
)
[<DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)>]
extern bool GetTokenInformation(
IntPtr TokenHandle,
TOKEN_INFORMATION_CLASS TokenInformationClass,
IntPtr TokenInformation,
[<Out>] int TokenInformationLength,
[<Out>] int32& ReturnLength
)
[<DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)>]
extern bool ConvertSidToStringSid(IntPtr pSID, IntPtr& ptrSid)
[<DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Ansi)>]
extern bool LookupPrivilegeName(
string lpSystemName,
IntPtr lpLuid,
IntPtr lpName,
[<Out>] int32& cchName
)
[<DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)>]
extern bool ImpersonateLoggedOnUser(IntPtr tokenHandle)
[<DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)>]
extern bool RevertToSelf()
[<DllImport("advapi32.dll", SetLastError = true)>]
extern uint32 I_QueryTagInformation(
IntPtr nothing,
SC_SERVICE_TAG_QUERY_TYPE Type,
[<In>] [<Out>] SC_SERVICE_TAG_QUERY& Query
)
//// iphlpapi ////
[<DllImport("iphlpapi.dll", SetLastError = true)>]
extern int FreeMibTable(IntPtr plpNetTable)
[<DllImport("iphlpapi.dll", SetLastError = true)>]
extern uint32 GetExtendedTcpTable(
IntPtr pTcpTable,
uint32& dwOutBufLen,
bool sort,
int ipVersion,
TCP_TABLE_CLASS tblClass,
int reserved
)
[<DllImport("iphlpapi.dll", SetLastError = true)>]
extern uint32 GetExtendedUdpTable(
IntPtr pUdpTable,
uint32& dwOutBufLen,
bool sort,
int ipVersion,
UDP_TABLE_CLASS tblClass,
int reserved
)
[<DllImport("iphlpapi.dll", SetLastError = true)>]
extern int GetIpNetTable(IntPtr pIpNetTable, int& pdwSize, bool bOrder)
//// kernel32 ////
[<DllImport("kernel32.dll")>]
extern bool CloseHandle(IntPtr handle)
//// NetApi32 ////
[<DllImport("Netapi32.dll")>]
extern int NetApiBufferFree(IntPtr bufptr)
[<DllImport("netapi32.dll", CharSet = CharSet.Unicode)>]
extern int NetLocalGroupGetMembers(
string serverName,
string localGroupName,
int level,
[<Out>] IntPtr& bufptr,
int prefmaxlen,
[<Out>] int& entriesRead,
[<Out>] int& totalEntries,
[<Out>] IntPtr resumeHandle
)
//// secur32 ////
[<DllImport("secur32.dll", SetLastError = true)>]
extern int LsaConnectUntrusted([<Out>] IntPtr& lsaHandle)
[<DllImport("secur32.dll", SetLastError = true)>]
extern int LsaRegisterLogonProcess(
LSA_STRING_IN& logonProcessName,
[<Out>] IntPtr& lsaHandle,
[<Out>] uint64& securityMode
)
[<DllImport("secur32.dll", SetLastError = true)>]
extern int LsaDeregisterLogonProcess([<In>] IntPtr lsaHandle)
[<DllImport("secur32.dll", SetLastError = true)>]
extern int LsaLookupAuthenticationPackage(
IntPtr lsaHandle,
LSA_STRING_IN packageName,
[<Out>] int& authenticationPackage
)
[<DllImport("secur32.dll", EntryPoint = "LsaCallAuthenticationPackage", SetLastError = true)>]
extern int LsaCallAuthenticationPackage_CACHE(
IntPtr lsaHandle,
int authenticationPackage,
KERB_QUERY_TKT_CACHE_REQUEST protocolSubmitBuffer,
int submitBufferLength,
[<Out>] IntPtr& protocolReturnBuffer,
[<Out>] int& returnBufferLength,
[<Out>] int protocolStatus
)
[<DllImport("secur32.dll", EntryPoint = "LsaCallAuthenticationPackage", SetLastError = true)>]
extern int LsaCallAuthenticationPackage_RET(
IntPtr lsaHandle,
int authenticationPackage,
KERB_RETRIEVE_TKT_REQUEST protocolSubmitBuffer,
int submitBufferLength,
[<Out>] IntPtr& protocolReturnBuffer,
[<Out>] int& returnBufferLength,
[<Out>] int protocolStatus
)
[<DllImport("secur32.dll", SetLastError = true)>]
extern uint32 LsaFreeReturnBuffer(IntPtr& buffer)
[<DllImport("secur32.dll", SetLastError = true)>]
extern uint32 LsaEnumerateLogonSessions([<Out>] uint64& logonSessionCount, [<Out>] IntPtr& logonSessionList)
[<DllImport("secur32.dll", SetLastError = true)>]
extern uint32 LsaGetLogonSessionData(IntPtr luid, [<Out>] IntPtr& ppLogonSessionData )
//// vaultcli ////
[<DllImport("vaultcli.dll")>]
extern int32 VaultOpenVault(
Guid vaultGuid,
uint32 offset,
[<Out>] IntPtr& vaultHandle
)
[<DllImport("vaultcli.dll")>]
extern int32 VaultCloseVault(IntPtr vaultHandle) //these two need to be integrated into the vault code!
[<DllImport("vaultcli.dll")>]
extern int32 VaultFree(IntPtr vaultHandle) // ^
[<DllImport("vaultcli.dll")>]
extern int32 VaultEnumerateVaults(
int32 offset,
[<Out>] int32& vaultCount,
[<Out>] IntPtr& vaultGuid
)
[<DllImport("vaultcli.dll")>]
extern int32 VaultEnumerateItems(
IntPtr vaultHandle,
int32 chunkSize,
[<Out>] int32& vaultItemCount,
[<Out>] IntPtr& vaultItem
)
[<DllImport("vaultcli.dll", EntryPoint = "VaultGetItem")>]
extern int32 VaultGetItem_WIN8(
IntPtr vaultHandle,
Guid schemaId,
IntPtr pResourceElement,
IntPtr pIdentityElement,
IntPtr pPackageSid,
IntPtr zero,
int32 arg6,
[<Out>] IntPtr& passwordVaultPtr
)
[<DllImport("vaultcli.dll", EntryPoint = "VaultGetItem")>]
extern int32 VaultGetItem_WIN7(
IntPtr vaultHandle,
Guid schemaId,
IntPtr pResourceElement,
IntPtr pIdentityElement,
IntPtr zero,
int32 arg5,
[<Out>] IntPtr& passwordVaultPtr
)
//// wtsapi32 ////
[<DllImport("wtsapi32.dll", SetLastError = true)>]
extern IntPtr WTSOpenServer(string pServerName)
[<DllImport("Wtsapi32.dll", SetLastError = true)>]
extern bool WTSQuerySessionInformation(
IntPtr& hServer,
int sessionId,
WTS_INFO_CLASS wtsClientAddress,
[<Out>] IntPtr& ppBuffer,
[<Out>] int& pBytesReturned
)
[<DllImport("wtsapi32.dll", SetLastError = true)>]
extern int WTSEnumerateSessionsEx(
IntPtr hServer,
int& pLevel,
int Filter,
[<Out>] IntPtr& ppSessionInfo,
[<Out>] int& pCount)
/////////////////////////
//Native Function Helpers
/////////////////////////
//For extracting LSA_STRING_OUT
let marshalLSAStringS (sourceStruct: LSA_STRING_OUT) : string =
match sourceStruct with
| x when not(x.buffer = IntPtr.Zero) && not(x.length = 0us) ->
let unmanagedString = Marshal.PtrToStringAuto(sourceStruct.buffer, (int(sourceStruct.maxLength /2us) - 1))
unmanagedString
|_ -> ""
let marshalLSAString (sourceStruct: LSA_STRING_OUT) : string =
match sourceStruct with
| x when not(x.buffer = IntPtr.Zero) && not(x.length = 0us) ->
let unmanagedString = Marshal.PtrToStringAuto(sourceStruct.buffer, (int(sourceStruct.maxLength /2us) ))
unmanagedString
|_ -> ""
//For extracting strings at an offset from a Ptr. Used in the Vault enum code
let marshalIndirectString offset ptr : string =
let oPtr = IntPtr.Add(ptr, offset)
let strPtr = Marshal.ReadIntPtr(oPtr)
Marshal.PtrToStringAuto(strPtr)
//Useful partial for vault code
let marshalVaultString = marshalIndirectString 16
///////////////////////
//Native function calls
///////////////////////
/////////////////////////
//RDP Session Enumeration
/////////////////////////
let private populateRdpSessionStructs ppSessionBaseAddr count : WTS_SESSION_INFO_1[] =
let mutable ppSBA = ppSessionBaseAddr
[|0..(count - 1)|]
|> Array.map(fun _ ->
let wtsSessionInfo = Marshal.PtrToStructure<WTS_SESSION_INFO_1>(ppSBA)
ppSBA <- IntPtr.Add(ppSBA, Marshal.SizeOf<WTS_SESSION_INFO_1>())
wtsSessionInfo)
let private rdpSessionGetAddress ppBuffer : IPAddress =
// Helper function for extracting IP address strings from the
// WTS_CLIENT_ADDRESS struct
let addr = Marshal.PtrToStructure<WTS_CLIENT_ADDRESS>(ppBuffer)
System.Net.IPAddress(addr.addressRaw.[2..5])
let private rdpSessionReverseLookup sessionID : IPAddress =
//Helper function to do a reverse IP lookup on a given Session ID
let mutable server = WTSOpenServer("localhost")
let mutable ppBuffer = IntPtr.Zero
let mutable pBytesReturned = 0
let revLookup =
WTSQuerySessionInformation(
&server,
sessionID,
WTS_INFO_CLASS.WTSClientAddress,
&ppBuffer,
&pBytesReturned
)
match revLookup with
| true -> rdpSessionGetAddress ppBuffer
| false -> System.Net.IPAddress.None
let enumerateRdpSessions () : FettersPInvokeRecord list =
// Returns a RdpSession record list of local sessions meeting the filter,
// namely that they contain the name "RDP" in the session. We don't want
// non-Rdp sessions in this output.
let server = WTSOpenServer("localhost")
let mutable ppSessionInfo = IntPtr.Zero
let mutable count = 0
let mutable level = 1
let returnValue =
WTSEnumerateSessionsEx(server, &level, 0, &ppSessionInfo, &count)
let allEnumeratedSessions =
match returnValue with
| x when x > 0 -> populateRdpSessionStructs ppSessionInfo count
| _ -> [||]
allEnumeratedSessions
|> Array.filter(fun f -> f.pSessionName.StartsWith("RDP"))
|> Array.map(fun sess ->
{state = sess.State.ToString();
sessionID = sess.SessionID;
sessionName = sess.pSessionName;
hostName = sess.pHostName;
username = sess.pUserName;
remoteAddress = (rdpSessionReverseLookup sess.SessionID)
})
|> Array.toList
|> List.map FettersPInvokeRecord.RdpSession
/////////////////////////
//Local Group Enumeration
/////////////////////////
let private populateGroupMemberStruct bufferPtr entriesRead : LOCAL_GROUP_MEMBER_INFO2 [] =
// Helper function for populating the LOCAL_GROUP_MEMBER structs
// I feel like this should actualy use mutability, because it's not necessarily
// clear that the `memberStructs` thta gets passed back is a copy?
let mutable bPtr = bufferPtr
[|0..(entriesRead - 1)|]
|> Array.map(fun _ ->
let mstruct = Marshal.PtrToStructure<LOCAL_GROUP_MEMBER_INFO2>(bPtr)
bPtr <- IntPtr.Add(bPtr, Marshal.SizeOf<LOCAL_GROUP_MEMBER_INFO2>())
mstruct)
let getLocalGroupMembership groupName : string list =
//Enumerates the members of a local group. Will emit a None on empty
//groups or if there was a non-0 return code.
let mutable bufPtr = IntPtr.Zero
let mutable rHandle = IntPtr.Zero
let mutable entRead = 0
let mutable totEntries = 0
let returnValue =
NetLocalGroupGetMembers("", groupName, 2, &bufPtr, -1, &entRead, &totEntries, rHandle)
//Kinda awkward, but we don't deal with errors at this point.
let members =
match returnValue with
| 0 -> populateGroupMemberStruct bufPtr entRead
| _ -> Array.zeroCreate 0 //(LOCAL_GROUP_MEMBER_INFO2())
NetApiBufferFree(bufPtr) |> ignore
members
|> Array.filter(fun gmember -> not (gmember.lgrmi2_sid = IntPtr.Zero))
|> Array.map(fun gmember -> gmember.lgrmi2_domainandname.Trim())
|> Array.toList
///////////////
//Impersonation
///////////////