-
Notifications
You must be signed in to change notification settings - Fork 65
/
Program.cs
690 lines (629 loc) · 26.5 KB
/
Program.cs
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
using System;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Net.NetworkInformation;
using CommandLine;
using CommandLine.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using SOAPHound.ADWS;
using SOAPHound.Enums;
using SOAPHound.Processors;
using System.Linq;
namespace SOAPHound
{
public class Program
{
public string Server = null;
public int Port = 9389;
public NetworkCredential Credential = null;
public Boolean dnsdump = false;
public Boolean certdump = false;
public Boolean bhdump = false;
public Boolean deep = false;
public string c1 = "abcdefghijklmnopqrstuvwxyz0123456789";
public string c2 = "abcdefghijklmnopqrstuvwxyz0123456789";
public Boolean autosplit = false;
public int threshold = 0;
public Boolean showStats = false;
public Boolean buildcacheonly = false;
public Boolean outputitems = false;
public Boolean nolaps = false;
public string[] properties = null;
public string ldapfilter = null;
public string ldapbase = null;
public string domainName = null;
public string cacheFileName = null;
public string outputDirectory = null;
public static void Main(string[] args)
{
Program program = new Program();
program.ParseCommandLineArgs(args);
}
private string GetCurrentDomain()
{
return IPGlobalProperties.GetIPGlobalProperties().DomainName;
}
private void EnableLogFile(string logfile)
{
Trace.AutoFlush = true;
TextWriterTraceListener listener = new TextWriterTraceListener(logfile);
Trace.Listeners.Add(listener);
}
void ParseCommandLineArgs(string[] args)
{
Trace.WriteLine("Before parsing arguments");
var parser = new Parser(with =>
{
with.CaseInsensitiveEnumValues = true;
with.CaseSensitive = false;
with.HelpWriter = null;
with.AutoVersion = false;
});
var parserResult = parser.ParseArguments<Options>(args);
parserResult
.WithParsed<Options>(options => RunOptions(options))
.WithNotParsed(errs => DisplayHelp(parserResult, errs));
}
void DisplayHelp<T>(ParserResult<T> result, IEnumerable<Error> errs)
{
var helpText = HelpText.AutoBuild(result, h =>
{
h.AdditionalNewLineAfterOption = false;
h.Heading = "SOAPHound";
h.Copyright = "Copyright (c) 2024 FalconForce";
h.AutoVersion = false;
h.MaximumDisplayWidth = 300;
return HelpText.DefaultParsingErrorsHandler(result, h);
}, e => e);
Console.WriteLine(helpText);
}
public void DisplayErrorMessage(string text)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(text);
Console.ResetColor();
}
private void RunOptions(Options options)
{
string user = null;
string userdomain = null;
string password = null;
if (!string.IsNullOrEmpty(options.LogFile))
{
EnableLogFile(options.LogFile);
}
if (!(options.BuildCache || options.ShowStats || options.DNSDump || options.CertDump || options.BHDump))
{
DisplayErrorMessage("No valid mode has been selected. Please execute --help to select a valid mode.");
return;
}
if (options.DNSDump || options.CertDump || options.BHDump)
{
if (String.IsNullOrEmpty(options.OutputDirectory))
{
DisplayErrorMessage("Output directory is required. Use --outputdirectory");
return;
}
else
{
outputDirectory = options.OutputDirectory.TrimEnd('\\') + "\\";
}
}
if (!(options.ShowStats))
{
if (options.User != null)
{
if (options.User.Contains("\\"))
{
int pos = options.User.IndexOf('\\');
userdomain = options.User.Substring(0, pos);
user = options.User.Substring(pos + 1);
}
else
{
user = options.User;
if (!user.Contains("@"))
{
DisplayErrorMessage("User must be in the format domain\\user or user@domain");
}
}
}
Server = options.DC;
password = options.Password;
if (String.IsNullOrEmpty(Server))
{
Server = GetCurrentDomain();
if (String.IsNullOrEmpty(Server))
{
DisplayErrorMessage("Domain controller is missing, use --dc.");
return;
}
}
if (user != null)
{
if (password == null)
DisplayErrorMessage("Password is missing, use --password.");
if (String.IsNullOrEmpty(userdomain))
{
Credential = new NetworkCredential(user, password);
}
else
{
Credential = new NetworkCredential(user, password, userdomain);
}
}
}
if (options.DNSDump)
{
dnsdump = true;
};
if (options.ShowStats)
{
if (String.IsNullOrEmpty(options.CacheFileName))
{
DisplayErrorMessage("Cache file name is missing, use --cachefilename.");
return;
}
autosplit = true;
showStats = true;
cacheFileName = options.CacheFileName;
}
if (options.BuildCache)
{
if (String.IsNullOrEmpty(options.CacheFileName))
{
DisplayErrorMessage("Cache file name is missing, use --cachefilename.");
return;
}
buildcacheonly = true;
cacheFileName = options.CacheFileName;
}
if (options.CertDump)
{
if (String.IsNullOrEmpty(options.CacheFileName))
{
DisplayErrorMessage("Cache file name is missing, use --cachefilename.");
return;
}
certdump = true;
cacheFileName = options.CacheFileName;
}
if (options.BHDump)
{
if (String.IsNullOrEmpty(options.CacheFileName))
{
DisplayErrorMessage("Cache file name is missing, use --cachefilename.");
return;
}
if (options.AutoSplit)
{
if (options.Threshold == 0)
{
DisplayErrorMessage("AutoSplit threshold is missing, use --threshold.");
return;
}
}
bhdump = true;
cacheFileName = options.CacheFileName;
autosplit = options.AutoSplit;
threshold = options.Threshold;
nolaps = options.NoLAPS;
}
domainName = options.Domain;
domainName = string.IsNullOrEmpty(domainName) ? GetCurrentDomain() : domainName;
if (string.IsNullOrEmpty(domainName))
{
DisplayErrorMessage("Domain is missing and could not be determined automatically, use --domain.");
return;
}
Run(Server, Port, Credential);
return;
}
public void Run(string Server, int Port, NetworkCredential Credential)
{
ADWSUtils.Server = Server;
ADWSUtils.Port = Port;
ADWSUtils.Credential = Credential;
ADWSUtils.nolaps = nolaps;
if (!string.IsNullOrEmpty(outputDirectory))
{
System.IO.Directory.CreateDirectory(outputDirectory);
}
if (!string.IsNullOrEmpty(cacheFileName))
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(cacheFileName));
}
if (dnsdump)
{
DNSDump();
}
if (buildcacheonly)
{
GenerateCache();
}
if (certdump)
{
CertificateDump();
}
if (bhdump || autosplit)
{
ADDump();
}
}
private void DNSDump()
{
List<ADObject> dnsobjects = ADWSUtils.GetObjects("dns");
string outputFileName = outputDirectory + "DNS.txt";
foreach (ADObject dnsobject in dnsobjects)
{
File.AppendAllText(outputFileName, "\r\n" + dnsobject.Name);
hDNSRecord.ReadandOutputDNSObject(dnsobject.DnsRecord, outputFileName);
}
Console.WriteLine("-------------");
Console.WriteLine("Output file generated in " + outputDirectory);
dnsdump = false;
}
private void CertificateDump()
{
//Loading cache
if (!File.Exists(cacheFileName))
{
Console.WriteLine("File: " + cacheFileName + " does not exist. Generate cache before executing this command.");
return;
}
else
{
try
{
Console.WriteLine("Loading cache from disk");
Cache.Deserialize(cacheFileName);
Console.WriteLine("Loaded cache with stats: " + Cache.GetCacheStats());
}
catch (Exception e)
{
Console.WriteLine($"Error loading cache: {e}");
throw;
}
}
//Generate cache of PKI objects
List<ADObject> cachedpkiobjects = ADWSUtils.GetObjects("pkicache");
foreach (ADObject cachedpkiobject in cachedpkiobjects)
{
if (cachedpkiobject.CertificateTemplates != null)
{
string caname = cachedpkiobject.Name.ToUpper();
foreach (string template in cachedpkiobject.CertificateTemplates)
{
PKICache.AddTemplateCA(template, caname);
}
}
}
List<ADObject> adobjects = ADWSUtils.GetObjects("pkidata");
OutputCA outputCA = new OutputCA();
OutputCATemplate outputCATemplate = new OutputCATemplate();
CAProcessor _ca = new CAProcessor();
foreach (ADObject adobject in adobjects)
{
if (adobject.Class == "pkienrollmentservice")
{
CA caNode = _ca.parseCA(adobject, domainName);
outputCA.data.Add(caNode);
}
if (adobject.Class == "pkicertificatetemplate")
{
CATemplate caTemplate = _ca.parseCATemplate(adobject, domainName);
outputCATemplate.data.Add(caTemplate);
}
}
outputCA.meta.count = outputCA.data.Count();
outputCATemplate.meta.count = outputCATemplate.data.Count();
var jsonString = JsonConvert.SerializeObject(outputCA);
File.WriteAllText(outputDirectory + "CA.json", jsonString);
//Console.WriteLine(jsonString);
jsonString = JsonConvert.SerializeObject(outputCATemplate);
File.WriteAllText(outputDirectory + "CATemplate.json", jsonString);
Console.WriteLine("-------------");
Console.WriteLine("Output files generated in " + outputDirectory);
certdump = false;
}
private void ADDump()
{
//Loading cache
if (!File.Exists(cacheFileName))
{
Console.WriteLine("File: " + cacheFileName + " does not exist. Generate cache before executing this command.");
return;
}
else
{
try
{
Console.WriteLine("Loading cache from disk");
Cache.Deserialize(cacheFileName);
Console.WriteLine("Loaded cache with stats: " + Cache.GetCacheStats());
}
catch (Exception e)
{
Console.WriteLine($"Error loading cache: {e}");
throw;
}
}
if (autosplit)
{
AutoSplit();
}
else
{
List<ADObject> adobjects = new List<ADObject>();
adobjects = ADWSUtils.GetObjects("ad");
CreateOutput(adobjects, "full");
adobjects.Clear();
}
}
private void GenerateCache()
{
if (string.IsNullOrEmpty(cacheFileName))
{
Console.WriteLine("Cache file name has not been defined.");
}
else
{
//Generate cache of all objects (SID,Type,CN)
List<ADObject> cachedobjects = ADWSUtils.GetObjects("cache");
foreach (ADObject cachedobject in cachedobjects)
{
//parsing Computers,Users,Groups (ObjectSid != null)
if (cachedobject.ObjectSid != null)
{
string objectSid = cachedobject.ObjectSid.ToString();
//parsing WellKnownPrincipals
if (objectSid.StartsWith("S-1") && WellKnownPrincipal.GetWellKnownPrincipal(objectSid, out var commonPrincipal))
{
Cache.AddConvertedValue(cachedobject.DistinguishedName, objectSid);
Cache.AddType(objectSid, commonPrincipal.ObjectType);
}
else
{
Cache.AddConvertedValue(cachedobject.DistinguishedName, objectSid);
Cache.AddType(objectSid, ADWSUtils.ClasstoLabel(cachedobject.Class));
}
}
//parsing Domains,Containers,GPOs,OUs
else if (ADWSUtils.ClasstoLabel(cachedobject.Class) != Label.Base)
{
Cache.AddConvertedValue(cachedobject.DistinguishedName, cachedobject.ObjectGUID.ToString());
Cache.AddType(cachedobject.ObjectGUID.ToString(), ADWSUtils.ClasstoLabel(cachedobject.Class));
}
}
Cache.Serialize(cacheFileName);
}
}
private void AutoSplit()
{
char firstChar;
string dictKey = null;
var dict = new Dictionary<string, int>();
foreach (var key in Cache.ValueToIdCache.Keys)
{
if (key.StartsWith("CN="))
{
firstChar = key.ToString().ToLower()[3];
if (!"abcdefghijklmnopqrstuvwxyz0123456789".Contains(firstChar))
{
dictKey = "nonchars";
}
else
{
dictKey = firstChar.ToString();
}
}
if (dictKey != null)
{
if (dict.ContainsKey(dictKey))
{
dict[dictKey]++;
}
else
{
dict[dictKey] = 1;
}
}
}
var sortedDict = new SortedDictionary<string, int>(dict);
if (showStats)
{
foreach (var kvp in sortedDict)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("Finished");
return;
}
//Gathering Domains data
List<ADObject> domobjects = new List<ADObject>();
domobjects = ADWSUtils.GetObjects("domains");
CreateOutput(domobjects, "dom");
domobjects.Clear();
// Gathering non alphanumeric data
if (sortedDict.ContainsKey("nonchars"))
{
List<ADObject> adobjects = new List<ADObject>();
//ParseNonCharsADObjects();
adobjects = ADWSUtils.GetObjects("nonchars");
CreateOutput(adobjects, "nonchars");
adobjects.Clear();
sortedDict.Remove("nonchars");
}
sortedDict.Remove("nonchars");
// Gathering autosplit data
foreach (var item in sortedDict)
{
if (item.Value < threshold)
{
Console.WriteLine("Gathering full letter: " + item.Key);
deep = false;
ParseAutosplitObjects(item.Key, c2);
}
else
{
Console.WriteLine("Gathering split letter: " + item.Key);
deep = true;
ParseAutosplitObjects(item.Key, c2);
}
}
}
private void ParseAutosplitObjects(string str1, string str2)
{
foreach (char c1 in str1)
{
if (deep)
{
//Gather 2nd depth level
foreach (char c2 in str2)
{
List<ADObject> objects = ADWSUtils.GetObjects("(cn=" + c1 + c2 + "*)");
CreateOutput(objects, c1.ToString() + c2.ToString());
objects.Clear();
}
//Gather non alphanumeric in 2nd depth level
List<ADObject> adobjects = ADWSUtils.GetObjects("(&(cn=" + c1 + "*)(!(cn=" + c1 + "a*))(!(cn=" + c1 + "b*))(!(cn=" + c1 + "c*))(!(cn=" + c1 + "d*))(!(cn=" + c1 + "e*))(!(cn=" + c1 + "f*))(!(cn=" + c1 + "g*))(!(cn=" + c1 + "h*))(!(cn=" + c1 + "i*))(!(cn=" + c1 + "j*))(!(cn=" + c1 + "k*))(!(cn=" + c1 + "l*))(!(cn=" + c1 + "m*))(!(cn=" + c1 + "n*))(!(cn=" + c1 + "o*))(!(cn=" + c1 + "p*))(!(cn=" + c1 + "q*))(!(cn=" + c1 + "r*))(!(cn=" + c1 + "s*))(!(cn=" + c1 + "t*))(!(cn=" + c1 + "u*))(!(cn=" + c1 + "v*))(!(cn=" + c1 + "w*))(!(cn=" + c1 + "x*))(!(cn=" + c1 + "y*))(!(cn=" + c1 + "z*))(!(cn=" + c1 + "0*))(!(cn=" + c1 + "1*))(!(cn=" + c1 + "2*))(!(cn=" + c1 + "3*))(!(cn=" + c1 + "4*))(!(cn=" + c1 + "5*))(!(cn=" + c1 + "6*))(!(cn=" + c1 + "7*))(!(cn=" + c1 + "8*))(!(cn=" + c1 + "9*)))");
CreateOutput(adobjects, c1.ToString() + "_nonchars_");
adobjects.Clear();
}
else
{
//Gather full letter
List<ADObject> adobjects = ADWSUtils.GetObjects("(cn=" + c1 + "*)");
CreateOutput(adobjects, c1.ToString());
adobjects.Clear();
}
}
}
public void CreateOutput(List<ADObject> adobjects, string header)
{
OutputComputers outputComputers = new OutputComputers();
OutputUsers outputUsers = new OutputUsers();
OutputGroups outputGroups = new OutputGroups();
OutputDomains outputDomains = new OutputDomains();
OutputGPOs outputGPOs = new OutputGPOs();
OutputOUs outputOUs = new OutputOUs();
OutputContainers outputContainers = new OutputContainers();
foreach (ADObject adobject in adobjects)
{
try
{
if (adobject.Class == "computer")
{
ComputerProcessor _comp = new ComputerProcessor();
ComputerNode computerNode = _comp.parseComputerObject(adobject, domainName);
outputComputers.data.Add(computerNode);
}
else if (adobject.Class == "user")
{
UserProcessor _usr = new UserProcessor();
UserNode userNode = _usr.parseUserObject(adobject, domainName);
outputUsers.data.Add(userNode);
}
else if (adobject.Class == "group")
{
GroupProcessor _grp = new GroupProcessor();
GroupNode groupNode = _grp.parseGroupObject(adobject, domainName);
outputGroups.data.Add(groupNode);
}
else if (adobject.Class == "domaindns" || adobject.Class == "domain")
{
DomainProcessor _dom = new DomainProcessor(Server, Port, Credential);
DomainNode domainNode = _dom.parseDomainObject(adobject);
outputDomains.data.Add(domainNode);
}
else if (adobject.Class == "grouppolicycontainer")
{
GPOProcessor _gpo = new GPOProcessor();
GPONode gpoNode = _gpo.parseGPOObject(adobject, domainName);
outputGPOs.data.Add(gpoNode);
}
else if (adobject.Class == "organizationalunit")
{
OUProcessor _ou = new OUProcessor();
OUNode ouNode = _ou.parseOUObject(adobject, domainName);
outputOUs.data.Add(ouNode);
}
else if (adobject.Class == "container" || adobject.Class == "rpccontainer" || adobject.Class == "msimaging-psps" || adobject.Class == "msExchConfigurationContainer") //todo: add more custom container classes
{
//filter out domainupdates and user/machine system policies
string dn = adobject.DistinguishedName.ToUpper();
if (dn.Contains("CN=DOMAINUPDATES,CN=SYSTEM"))
continue;
if (dn.Contains("CN=POLICIES,CN=SYSTEM") && (dn.StartsWith("CN=USER") || dn.StartsWith("CN=MACHINE")))
continue;
ContainerProcessor _cp = new ContainerProcessor();
ContainerNode containerNode = _cp.parseContainerObject(adobject, domainName);
outputContainers.data.Add(containerNode);
}
else
{
//Trace.WriteLine("we have an unprocessed " + adobject.Class + " object:" + adobject.Name);
}
}
catch (Exception e)
{
DisplayErrorMessage("Exception " + e.ToString() + "\nError parsing object with ObjectGUID :" + adobject.ObjectGUID.ToString());
}
}
outputUsers.meta.count = outputUsers.data.Count();
if (outputUsers.meta.count > 0)
{
var jsonString = JsonConvert.SerializeObject(outputUsers);
File.WriteAllText(outputDirectory + header + "_outputUsers.json", jsonString);
//Console.WriteLine(jsonString);
}
outputComputers.meta.count = outputComputers.data.Count();
if (outputComputers.meta.count > 0)
{
var jsonString = JsonConvert.SerializeObject(outputComputers);
File.WriteAllText(outputDirectory + header + "_outputComputers.json", jsonString);
//Console.WriteLine(jsonString);
}
outputGroups.meta.count = outputGroups.data.Count();
if (outputGroups.meta.count > 0)
{
var jsonString = JsonConvert.SerializeObject(outputGroups);
File.WriteAllText(outputDirectory + header + "_outputGroups.json", jsonString);
//Console.WriteLine(jsonString);
}
outputDomains.meta.count = outputDomains.data.Count();
if (outputDomains.meta.count > 0)
{
var jsonString = JsonConvert.SerializeObject(outputDomains);
File.WriteAllText(outputDirectory + header + "_outputDomains.json", jsonString);
//Console.WriteLine(jsonString);
}
outputGPOs.meta.count = outputGPOs.data.Count();
if (outputGPOs.meta.count > 0)
{
var jsonString = JsonConvert.SerializeObject(outputGPOs);
File.WriteAllText(outputDirectory + header + "_outputGPOs.json", jsonString);
//Console.WriteLine(jsonString);
}
outputOUs.meta.count = outputOUs.data.Count();
if (outputOUs.meta.count > 0)
{
var jsonString = JsonConvert.SerializeObject(outputOUs);
File.WriteAllText(outputDirectory + header + "_outputOUs.json", jsonString);
//Console.WriteLine(jsonString);
}
outputContainers.meta.count = outputContainers.data.Count();
if (outputContainers.meta.count > 0)
{
var jsonString = JsonConvert.SerializeObject(outputContainers);
File.WriteAllText(outputDirectory + header + "_outputContainers.json", jsonString);
//Console.WriteLine(jsonString);
}
Console.WriteLine("-------------");
Console.WriteLine("Output files with prefix \"" + header + "\" generated in " + outputDirectory);
Console.WriteLine("-------------");
}
}
}