This repository has been archived by the owner on Aug 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdsquery.cs
699 lines (597 loc) · 25 KB
/
dsquery.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
690
691
692
693
694
695
696
697
698
699
// Sources:
// - Query AD - https://stackoverflow.com/questions/456523/quick-way-to-retrieve-user-information-active-directory
// - List specific attributes - https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.attributescopequery?view=net-5.0#System_DirectoryServices_DirectorySearcher_AttributeScopeQuery
// - Limit output - https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.sizelimit?view=net-5.0#System_DirectoryServices_DirectorySearcher_SizeLimit
// - Set start node - https://forums.asp.net/t/1592150.aspx?How+to+set+SearchRoot+Path+in+Active+Directory+in+this+scenario
// To Compile:
// C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /t:exe /out:bin\dsquery.exe dsquery.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.IO;
using System.Linq;
using System.Text;
class dsquery
{
// Defines a Table data structure; used to print data in a well-formatted manner
// Source: https://genert.org/blog/csharp-programming/
class Table
{
private List<object> _columns { get; set; }
private List<object[]> _rows { get; set; }
private bool _printDividers;
public Table(string[] columns, bool printDividers = false)
{
if (columns == null || columns.Length == 0)
{
throw new System.ArgumentException("Parameter cannot be null nor empty", "columns");
}
_columns = new List<object>(columns);
_rows = new List<object[]>();
_printDividers = printDividers;
}
private List<int> GetColumnsMaximumStringLengths()
{
List<int> columnsLength = new List<int>();
for (int i = 0; i < _columns.Count; i++)
{
List<object> columnRow = new List<object>();
int max = 0;
columnRow.Add(_columns[i]);
for (int j = 0; j < _rows.Count; j++)
{
columnRow.Add(_rows[j][i]);
}
for (int n = 0; n < columnRow.Count; n++)
{
int len = columnRow[n].ToString().Length;
if (len > max)
{
max = len;
}
}
columnsLength.Add(max);
}
return columnsLength;
}
public void AddRow(object[] values)
{
if (values == null)
{
throw new System.ArgumentException("Parameter cannot be null", "values");
}
if (values.Length != _columns.Count)
{
throw new Exception("The number of values in row does not match columns count.");
}
_rows.Add(values);
}
public override string ToString()
{
StringBuilder tableString = new StringBuilder();
List<int> columnsLength = GetColumnsMaximumStringLengths();
var rowStringFormat = Enumerable
.Range(0, _columns.Count)
.Select(i => "{" + i + ",-" + columnsLength[i] + "} ")
.Aggregate((total, nextValue) => total + nextValue);
if (_printDividers)
{
rowStringFormat = Enumerable
.Range(0, _columns.Count)
.Select(i => " | {" + i + ",-" + columnsLength[i] + "}")
.Aggregate((total, nextValue) => total + nextValue) + " |";
}
string columnHeaders = string.Format(rowStringFormat, _columns.ToArray());
List<string> results = _rows.Select(row => string.Format(rowStringFormat, row)).ToList();
int maximumRowLength = Math.Max(0, _rows.Any() ? _rows.Max(row => string.Format(rowStringFormat, row).Length) : 0);
int maximumLineLength = Math.Max(maximumRowLength, columnHeaders.Length);
string dividerLine = string.Join("", Enumerable.Repeat("-", maximumLineLength - 1));
string divider = string.Format(" {0} ", dividerLine);
if (_printDividers)
{
tableString.AppendLine(divider);
}
tableString.AppendLine(columnHeaders);
foreach (var row in results)
{
if (_printDividers)
{
tableString.AppendLine(divider);
}
tableString.AppendLine(row);
}
if (_printDividers)
{
tableString.AppendLine(divider);
}
return tableString.ToString();
}
public void Print()
{
Console.WriteLine(ToString());
}
}
public static void PrintUsage()
{
Console.WriteLine(@"Query directory services
USAGE:
dsquery * [startNode] -filter <filter_string> [-attr <attributes>] [-limit <number>] [-c | -l | -t] [[-s <server>] | [-d <domain>]] [-u <UserName>] [-p <password>] [-b <buffer_size_in_MB>] [-o <output_file>] [/?]
[startNode] Optional start node (e.g., specific OU; domainroot is NOT supported
at this time)
-filter <filter> Standard dsquery filter string
-attr <attributes> Space-delimited list of attributes; use '*' to return all attributes
If omitted, defaults to '-attr *'
-limit <number> Limits query to <number> records
-c Count only; prints the number of records returned by a search and exits
-l Print in list format
-t Print in table format with ASCII borders around each cell
-s <server> Query the specified server
-d <domain> Query the specified domain
-u <username> Authenticate using the specified username
-p <password> Authenticate using the specified password
-o <output_filepath> Write output to the specified file; will not overwrite an existing file
-b <buffer_size> Write to output file in 'buffer_size' chunks (specified in MB)
/? Prints help");
}
public static void Main(string[] args)
{
SearchResultCollection results = null;
try
{
if (args.Length == 0 || (args.Length > 0 && args[0] == "/?"))
{
PrintUsage();
return;
}
string startNode = "";
string filter = "";
List<string> attrs = new List<string>();
int limit = 0;
bool adspathIncluded = false;
bool countOnly = false;
bool listFormat = false;
bool printDividers = false;
string server = "";
string domain = "";
string username = "";
string password = "";
int buffer = 2 * 1024 * 1024;
string outputFilepath = "";
int argIndex = 1;
// Parse arguments
// Bail if anything but a complex query
if (args[0] != "*")
{
throw new Exception("The specified operation is not supported");
}
// Parse optional start node
if (!args[argIndex].StartsWith("-"))
{
startNode = args[argIndex];
argIndex++;
}
// Parse other arguments
for (int i = argIndex; i < args.Length; i++)
{
string arg = args[i];
switch (arg.ToUpper())
{
case "-FILTER":
case "/FILTER":
i++;
try
{
filter = args[i];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No filter specified");
}
break;
case "-ATTR":
case "/ATTR":
i++;
while (i < args.Length && !args[i].StartsWith("-") && !args[i].StartsWith("/"))
{
if (args[i].ToLower() == "adspath")
{
adspathIncluded = true;
}
attrs.Add(args[i]);
i++;
}
if (attrs.Count == 0)
{
throw new ArgumentException("No attributes specified");
}
// Back up one so any arguments after the attributes can be parsed
if (i < args.Length)
{
i--;
}
break;
case "-LIMIT":
case "/LIMIT":
i++;
try
{
if (!int.TryParse(args[i], out limit))
{
throw new ArgumentException("Invalid limit");
}
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No POST data specified");
}
break;
case "-C":
case "/C":
countOnly = true;
break;
case "-L":
case "/L":
listFormat = true;
break;
case "-T":
case "/T":
printDividers = true;
break;
case "-S":
case "/S":
i++;
try
{
server = args[i];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No server specified");
}
break;
case "-D":
case "/D":
i++;
try
{
domain = args[i];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No domain specified");
}
break;
case "-U":
case "/U":
i++;
try
{
username = args[i];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No username specified");
}
break;
case "-P":
case "/P":
i++;
try
{
password = args[i];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No password specified");
}
break;
case "-B":
case "/B":
i++;
try
{
if (!int.TryParse(args[i], out buffer))
{
throw new ArgumentException("Invalid buffer size");
}
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No buffer specified");
}
buffer = buffer * 1024 * 1024;
break;
case "-O":
case "/O":
i++;
try
{
outputFilepath = args[i];
if (File.Exists(outputFilepath))
{
throw new ArgumentException("Output file already exists");
}
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No output file specified");
}
break;
case "/?":
PrintUsage();
return;
}
}
// Ensure a filter is specified
if (string.IsNullOrEmpty(filter))
{
throw new ArgumentException("No filter specified");
}
// If no 'attr' argument is specified, assume '-attr *'
if (attrs.Count == 0)
{
attrs.Add("*");
}
// Default to list format if '-attr *' is specified
if (attrs.Count > 0 && attrs[0] == "*")
{
listFormat = true;
}
// Prevent accidentally overwriting a file
if (!string.IsNullOrEmpty(outputFilepath) && File.Exists(outputFilepath))
{
throw new Exception(String.Format("Output file ({0}) already exists", outputFilepath));
}
DirectoryEntry rootEntry;
// If a server is specified, use that; if a domain is specified, use that; otherwise, auto-detect the current domain
if (!string.IsNullOrEmpty(server))
{
rootEntry = new DirectoryEntry("LDAP://" + server);
}
else if (!string.IsNullOrEmpty(domain))
{
rootEntry = new DirectoryEntry("LDAP://" + domain);
}
else
{
rootEntry = new DirectoryEntry("LDAP://rootDSE");
rootEntry = new DirectoryEntry("LDAP://" + rootEntry.Properties["defaultNamingContext"].Value);
}
// Optionally specify username and password to use to collect
// Source: https://stackoverflow.com/questions/10742661/c-sharp-accessing-active-directory-with-different-user-credentials
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
rootEntry.Username = username;
rootEntry.Password = password;
}
// Initialize DirectorySearcher based on appropriate target
DirectorySearcher searcher = new DirectorySearcher(rootEntry);
// Set the start node, if applicable
if (!string.IsNullOrEmpty(startNode))
{
if (startNode.ToUpper() == "FORESTROOT")
{
if (!string.IsNullOrEmpty(server))
{
searcher.SearchRoot = new DirectoryEntry("GC://" + server);
}
else if (!string.IsNullOrEmpty(domain))
{
searcher.SearchRoot = new DirectoryEntry("GC://" + domain);
}
else
{
DirectoryEntry tempRootEntry = new DirectoryEntry("LDAP://rootDSE");
string currentdomain = (string)(tempRootEntry.Properties["defaultNamingContext"].Value);
searcher.SearchRoot = new DirectoryEntry("GC://" + currentdomain);
}
}
else
{
searcher.SearchRoot = new DirectoryEntry("LDAP://" + startNode);
}
}
searcher.PageSize = 1000;
searcher.Filter = filter;
// Set the limit, if applicable
if (limit > 0)
{
searcher.SizeLimit = limit;
}
// Set attributes to load
foreach (string attr in attrs)
{
searcher.PropertiesToLoad.Add(attr);
}
// Search
results = searcher.FindAll();
// Print the number of records returned
// Differs from native functionality, but it's convenient
Console.WriteLine("Records Found: {0}\n", results.Count);
if (!countOnly)
{
if (string.IsNullOrEmpty(outputFilepath))
{
// Print results to terminal
PrintResults(results, adspathIncluded, listFormat, printDividers);
}
else
{
// If outputFilepath is specified, redirect standard output from the console to the output file
// Source: https://stackoverflow.com/questions/61074203/c-sharp-performance-comparison-async-vs-non-async-text-file-io-operation-via-r
using (FileStream stream = new FileStream(outputFilepath, FileMode.Create, FileAccess.Write, FileShare.Read, buffer, FileOptions.SequentialScan))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
Console.SetOut(writer);
PrintResults(results, adspathIncluded, listFormat, printDividers);
}
}
// Source: https://docs.microsoft.com/en-us/dotnet/api/system.console.error?view=net-5.0
// Recover the standard output stream so that a completion message can be displayed.
StreamWriter stdout = new StreamWriter(Console.OpenStandardOutput());
stdout.AutoFlush = true;
Console.SetOut(stdout);
}
}
}
catch (Exception e)
{
Console.Error.WriteLine("[-] ERROR: {0}", e.Message.Trim());
}
finally
{
// Dispose of objects used
if (results != null)
{
results.Dispose();
}
Console.WriteLine("\nDONE");
}
}
private static void PrintResults(SearchResultCollection results, bool adspathIncluded, bool listFormat, bool printDividers)
{
if (results.Count > 0)
{
// Get column names from PropertiesToLoad because it is in the user-specified order whereas PropertyNames is not
string[] properties = results.PropertiesLoaded.ToArray();
// ADsPath is automatically included; remove it from the list of properties unless it was explicitly specified
if (!adspathIncluded)
{
properties = results.PropertiesLoaded.Where(e => e != "ADsPath").ToArray();
}
// If '-attr *' was specified, we have to get the property list from PropertyNames; might as well sort them for convenience
if (properties[0] == "*")
{
List<string> props = new List<string>();
foreach (string prop in results[0].Properties.PropertyNames)
{
props.Add(prop);
}
props.Sort();
properties = props.ToArray();
}
// Print results in either list or table format
if (listFormat)
{
PrintResultsListFormat(properties, results);
}
else
{
PrintResultsTableFormat(properties, results, printDividers);
}
}
else
{
Console.WriteLine("No records matched the specified criteria");
}
}
private static void PrintResultsTableFormat(string[] columns, SearchResultCollection results, bool printDividers)
{
// Populate a Table data structure and print it, optionally with delimiters (enhancement)
Table tbl = new Table(columns, printDividers);
List<string> rowData;
string entry;
foreach (SearchResult searchResult in results)
{
rowData = new List<string>();
foreach (string key in columns)
{
entry = "";
// Join multiple entries with a ';'
for (int i = 0; i < searchResult.Properties[key].Count; i++)
{
entry += NormalizeData(key, searchResult.Properties[key][i]).ToString() + ";";
}
// Remove trailiing ';', if applicable
if (entry.Length > 0)
{
entry = entry.Remove(entry.Length - 1);
}
rowData.Add(entry);
}
tbl.AddRow(rowData.ToArray());
}
tbl.Print();
}
private static void PrintResultsListFormat(string[] properties, SearchResultCollection results)
{
// Loop through results and print all retrieved attributes
foreach (SearchResult searchResult in results)
{
foreach (string key in properties)
{
for (int i = 0; i < searchResult.Properties[key].Count; i++)
{
Console.WriteLine("{0}: {1}", key, NormalizeData(key, searchResult.Properties[key][i]));
}
}
// New-line delimit entries
Console.WriteLine("");
}
}
private static string NormalizeData(string key, object data)
{
// Some data is returned as a byte-array; convert known fields to their appropriate string values
if (key.ToLower() == "objectsid")
{
data = ConvertByteToStringSid((byte[])data);
}
else if (key.ToLower() == "objectguid")
{
data = "{" + (new Guid((byte[])data)).ToString().ToUpper() + "}";
}
return data.ToString();
}
// Convert a byte-array representing a Windows SID to an appropriate string representation
// Source: https://stackoverflow.com/questions/47209459/adding-all-users-sids-from-active-directory-in-c-sharp
public static string ConvertByteToStringSid(Byte[] sidBytes)
{
StringBuilder strSid = new StringBuilder();
strSid.Append("S-");
try
{
// Add SID revision.
strSid.Append(sidBytes[0].ToString());
// Next six bytes are SID authority value.
if (sidBytes[6] != 0 || sidBytes[5] != 0)
{
string strAuth = String.Format
("0x{0:2x}{1:2x}{2:2x}{3:2x}{4:2x}{5:2x}",
(Int16)sidBytes[1],
(Int16)sidBytes[2],
(Int16)sidBytes[3],
(Int16)sidBytes[4],
(Int16)sidBytes[5],
(Int16)sidBytes[6]);
strSid.Append("-");
strSid.Append(strAuth);
}
else
{
Int64 iVal = (Int32)(sidBytes[1]) +
(Int32)(sidBytes[2] << 8) +
(Int32)(sidBytes[3] << 16) +
(Int32)(sidBytes[4] << 24);
strSid.Append("-");
strSid.Append(iVal.ToString());
}
// Get sub authority count...
int iSubCount = Convert.ToInt32(sidBytes[7]);
int idxAuth = 0;
for (int i = 0; i < iSubCount; i++)
{
idxAuth = 8 + i * 4;
UInt32 iSubAuth = BitConverter.ToUInt32(sidBytes, idxAuth);
strSid.Append("-");
strSid.Append(iSubAuth.ToString());
}
}
catch (Exception e)
{
Console.Error.WriteLine("[-] ERROR: {0}", e.Message.Trim());
}
return strSid.ToString();
}
}