-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSharpADIDNS.cs
More file actions
3169 lines (2880 loc) · 139 KB
/
Copy pathSharpADIDNS.cs
File metadata and controls
3169 lines (2880 loc) · 139 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
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 RedteamNotes
// SharpADIDNS - A C# CLI tool for reading and modifying AD-Integrated DNS records over LDAP.
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
namespace SharpADIDNS
{
// -----------------------------------------------------------------------
// Exit codes
// -----------------------------------------------------------------------
internal static class ExitCodes
{
public const int Success = 0;
public const int UsageError = 1;
public const int LdapError = 2;
public const int NotFound = 3;
public const int AccessDenied = 4;
}
// -----------------------------------------------------------------------
// Entry point
// -----------------------------------------------------------------------
internal static class Program
{
public const string Version = "0.9.5";
// Unique per process. All structured (JSON) output lines from this
// invocation carry the same correlation_id, so an operator
// collecting receipts from --script / Sliver execute-assembly can
// group them together downstream.
public static readonly string CorrelationId = Guid.NewGuid().ToString("D");
private static int Main(string[] args)
{
try
{
if (args == null || args.Length == 0)
{
Options.PrintUsage();
return ExitCodes.UsageError;
}
Options opt = Options.Parse(args);
// --c2 forces a coherent set of in-memory / unattended defaults.
// Explicit flags on the same command line still apply on top of
// these (e.g. --c2 --format text would still produce text), but
// any non-set default flips to the C2-friendly value.
if (opt.C2)
{
opt.AllowCleartextPassword = true;
opt.Yes = true;
opt.NoColor = true;
opt.Quiet = true;
if (opt.Format == "text") opt.Format = "json";
if (string.IsNullOrEmpty(opt.BackupTo)) opt.BackupTo = "-";
}
Logger.ColorEnabled = opt.NoColor ? false :
opt.Color ? true :
!Console.IsOutputRedirected;
Logger.JsonMode = opt.Format == "json";
if (opt.ShowVersion)
{
Console.WriteLine("SharpADIDNS v" + Version);
return ExitCodes.Success;
}
if (opt.ShowHelp)
{
if (!string.IsNullOrEmpty(opt.Action))
Options.PrintActionUsage(opt.Action);
else
Options.PrintUsage();
return ExitCodes.Success;
}
if (string.IsNullOrWhiteSpace(opt.DomainDn))
{
Logger.Err("--dn is required");
return ExitCodes.UsageError;
}
Credentials.Resolve(opt);
if (Replication.CheckBeforeAction(opt) != ExitCodes.Success)
return ExitCodes.UsageError;
// Script mode: one execute-assembly invocation runs multiple
// actions. Outer flags become defaults; each statement can
// override. Outer must not also specify a top-level action.
if (!string.IsNullOrEmpty(opt.Script))
{
if (!string.IsNullOrEmpty(opt.Action))
{
Logger.Err("--script is incompatible with a top-level action verb");
return ExitCodes.UsageError;
}
return RunScript(opt);
}
return DispatchAction(opt);
}
catch (DirectoryServicesCOMException ex)
{
ErrorReporter.PrintCom(ex);
return ErrorReporter.ToExitCode(ex);
}
catch (ArgumentException ex)
{
Logger.Err("{0}", ex.Message);
return ExitCodes.UsageError;
}
catch (FormatException ex)
{
Logger.Err("Format error: {0}", ex.Message);
return ExitCodes.UsageError;
}
catch (Exception ex)
{
Logger.Err("Error: {0}", ex.Message);
if (ex.InnerException != null)
Logger.Err("Inner: {0}", ex.InnerException.Message);
return ExitCodes.LdapError;
}
}
private static int RequireName(Options opt)
{
if (string.IsNullOrWhiteSpace(opt.Name))
{
Logger.Err("{0} requires --name <label>", opt.Action);
return 1;
}
return 0;
}
private static int DispatchAction(Options opt)
{
if (string.IsNullOrWhiteSpace(opt.Action))
{
Logger.Err("No action specified (expected: enum | query | add | disable | remove | list-zones)");
return ExitCodes.UsageError;
}
bool needsZone = opt.Action != "list-zones";
if (needsZone && string.IsNullOrWhiteSpace(opt.Zone))
{
Logger.Err("--zone is required");
return ExitCodes.UsageError;
}
string zoneDn = needsZone ? LdapOps.BuildZoneDn(opt.Zone, opt.Partition, opt.DomainDn) : null;
Logger.Verbose(opt, "Action: {0}", opt.Action);
if (zoneDn != null)
Logger.Verbose(opt, "Zone DN: {0}", zoneDn);
if (!string.IsNullOrWhiteSpace(opt.Server))
Logger.Verbose(opt, "LDAP DC: {0}", opt.Server);
if (!string.IsNullOrWhiteSpace(opt.Username))
Logger.Verbose(opt, "Bind user: {0}", opt.Username);
Logger.Verbose(opt, "Transport: {0}", opt.Ldaps ? "LDAPS (port 636)" : "LDAP (port 389)");
switch (opt.Action)
{
case "enum":
return Actions.RunEnum(opt, zoneDn);
case "query":
if (RequireName(opt) != 0) return ExitCodes.UsageError;
return Actions.RunQuery(opt, zoneDn);
case "list-zones":
return Actions.RunListZones(opt);
case "add":
if (RequireName(opt) != 0) return ExitCodes.UsageError;
if (string.IsNullOrWhiteSpace(opt.Data) && string.IsNullOrWhiteSpace(opt.RawBase64))
{
Logger.Err("add requires --data <value> or --raw <base64>");
return ExitCodes.UsageError;
}
return Actions.RunAdd(opt, zoneDn);
case "disable":
if (RequireName(opt) != 0) return ExitCodes.UsageError;
return Actions.RunDisable(opt, zoneDn);
case "remove":
if (RequireName(opt) != 0) return ExitCodes.UsageError;
return Actions.RunRemove(opt, zoneDn);
default:
Logger.Err("Unknown action: {0}", opt.Action);
return ExitCodes.UsageError;
}
}
private static int RunScript(Options outerOpt)
{
string[] rawStmts = outerOpt.Script.Split(';');
int total = 0, succeeded = 0, failed = 0;
bool halt = outerOpt.ScriptOnError == "halt";
foreach (string raw in rawStmts)
{
string stmt = raw.Trim();
if (stmt.Length == 0) continue;
total++;
string[] tokens = stmt.Split(
new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
Options stmtOpt = outerOpt.Clone();
ResetActionScopedFields(stmtOpt);
try
{
Options.ApplyArgs(stmtOpt, tokens);
int rc = DispatchAction(stmtOpt);
if (rc == ExitCodes.Success)
{
succeeded++;
}
else
{
failed++;
Logger.Err("Statement {0} failed with exit code {1}: {2}", total, rc, stmt);
if (halt) break;
}
}
catch (DirectoryServicesCOMException ex)
{
failed++;
ErrorReporter.PrintCom(ex);
if (halt) break;
}
catch (System.Runtime.InteropServices.COMException ex)
{
// Catches generic COM faults (e.g. DNS lookup failure
// before LDAP, bad ADS path) that aren't
// DirectoryServicesCOMException -- without this, --continue-on-error
// would abort the script on the first such error.
failed++;
Logger.Err("Statement {0} COM error: {1}", total, ex.Message);
if (halt) break;
}
catch (ArgumentException ex)
{
failed++;
Logger.Err("Statement {0}: {1}", total, ex.Message);
if (halt) break;
}
catch (Exception ex)
{
// Final safety net so unexpected exception types from one
// statement don't sink the whole script in continue mode.
failed++;
Logger.Err("Statement {0} error ({1}): {2}", total, ex.GetType().Name, ex.Message);
if (halt) break;
}
}
if (outerOpt.Format == "json")
{
Console.WriteLine(
"{\"correlation_id\":\"" + Program.CorrelationId + "\"," +
"\"_type\":\"script_summary\",\"total\":" + total +
",\"succeeded\":" + succeeded +
",\"failed\":" + failed +
",\"on_error\":\"" + outerOpt.ScriptOnError + "\"}");
}
else
{
Logger.Ok("Script: {0}/{1} succeeded, {2} failed (on-error: {3})",
succeeded, total, failed, outerOpt.ScriptOnError);
}
return failed == 0 ? ExitCodes.Success : ExitCodes.LdapError;
}
private static void ResetActionScopedFields(Options o)
{
o.Action = null;
o.Name = null;
o.Data = null;
o.RawBase64 = null;
o.Force = false;
o.Append = false;
o.MimicAging = false;
o.SetOwner = null;
o.RecordType = "A";
o.SrvPriority = 0;
o.SrvWeight = 0;
o.SrvPort = -1;
o.MxPref = 10;
o.FilterType = null;
o.FilterName = null;
o.OnlyTombstoned = false;
o.NoTombstoned = false;
o.Script = null;
}
}
// -----------------------------------------------------------------------
// Output helpers (respect --quiet / --verbose; ANSI color when enabled)
// -----------------------------------------------------------------------
internal static class Logger
{
public static bool ColorEnabled = false;
public static bool JsonMode = false;
private const string Reset = "[0m";
private const string FgGreen = "[32m";
private const string FgRed = "[31m";
private const string FgYellow = "[33m";
private const string FgCyan = "[36m";
private const string FgGray = "[90m";
private static string Mark(string ansi, string text)
{
return ColorEnabled ? ansi + text + Reset : text;
}
// In JSON mode, route stdout-leaning lines (Info/Ok/Verbose) to stderr
// so stdout is purely the structured JSON receipt stream.
private static TextWriter Out()
{
return JsonMode ? Console.Error : Console.Out;
}
public static void Info(Options opt, string fmt, params object[] args)
{
if (opt != null && opt.Quiet) return;
Out().WriteLine(Mark(FgCyan, "[*]") + " " + fmt, args);
}
public static void Ok(string fmt, params object[] args)
{
Out().WriteLine(Mark(FgGreen, "[+]") + " " + fmt, args);
}
public static void Verbose(Options opt, string fmt, params object[] args)
{
if (opt == null || !opt.Verbose) return;
Out().WriteLine(Mark(FgGray, "[v]") + " " + fmt, args);
}
public static void Warn(string fmt, params object[] args)
{
Console.Error.WriteLine(Mark(FgYellow, "[!]") + " " + fmt, args);
}
public static void Err(string fmt, params object[] args)
{
Console.Error.WriteLine(Mark(FgRed, "[-]") + " " + fmt, args);
}
}
// -----------------------------------------------------------------------
// LDAP helpers
// -----------------------------------------------------------------------
internal static class LdapOps
{
public static string BuildZoneDn(string zone, string partition, string domainDn)
{
if (partition.Equals("DomainDnsZones", StringComparison.OrdinalIgnoreCase))
return "DC=" + EscapeRdn(zone) + ",CN=MicrosoftDNS,DC=DomainDnsZones," + domainDn;
if (partition.Equals("ForestDnsZones", StringComparison.OrdinalIgnoreCase))
return "DC=" + EscapeRdn(zone) + ",CN=MicrosoftDNS,DC=ForestDnsZones," + domainDn;
if (partition.Equals("System", StringComparison.OrdinalIgnoreCase))
return "DC=" + EscapeRdn(zone) + ",CN=MicrosoftDNS,CN=System," + domainDn;
throw new ArgumentException(
"Unsupported --partition: " + partition +
" (expected DomainDnsZones, ForestDnsZones, or System)");
}
public static string BuildContainerDn(string partition, string domainDn)
{
if (partition.Equals("DomainDnsZones", StringComparison.OrdinalIgnoreCase))
return "CN=MicrosoftDNS,DC=DomainDnsZones," + domainDn;
if (partition.Equals("ForestDnsZones", StringComparison.OrdinalIgnoreCase))
return "CN=MicrosoftDNS,DC=ForestDnsZones," + domainDn;
if (partition.Equals("System", StringComparison.OrdinalIgnoreCase))
return "CN=MicrosoftDNS,CN=System," + domainDn;
throw new ArgumentException(
"Unsupported --partition: " + partition +
" (expected DomainDnsZones, ForestDnsZones, or System)");
}
public static string Path(Options opt, string dn)
{
if (string.IsNullOrWhiteSpace(opt.Server))
return "LDAP://" + dn;
return "LDAP://" + opt.Server + "/" + dn;
}
public static AuthenticationTypes Auth(Options opt)
{
AuthenticationTypes t = AuthenticationTypes.Secure;
if (opt.Ldaps) t |= AuthenticationTypes.SecureSocketsLayer;
if (!string.IsNullOrWhiteSpace(opt.Server)) t |= AuthenticationTypes.ServerBind;
return t;
}
public static DirectoryEntry Open(Options opt, string dn)
{
string path = Path(opt, dn);
if (string.IsNullOrWhiteSpace(opt.Username))
return new DirectoryEntry(path, null, null, Auth(opt));
return new DirectoryEntry(path, opt.Username, opt.Password, Auth(opt));
}
public static bool TryBind(DirectoryEntry entry, out DirectoryServicesCOMException error)
{
try
{
object _ = entry.NativeObject;
error = null;
return true;
}
catch (DirectoryServicesCOMException ex)
{
error = ex;
return false;
}
}
public static string EscapeRdn(string value)
{
// RFC 4514 RDN escapes plus the leading '#' and trailing ' ' cases
// are handled by the directory at write time; we cover the chars
// that show up inside DNS labels people put on the CLI.
return value.Replace("\\", "\\5c")
.Replace(",", "\\2c")
.Replace("+", "\\2b")
.Replace("\"", "\\22")
.Replace("<", "\\3c")
.Replace(">", "\\3e")
.Replace(";", "\\3b")
.Replace("=", "\\3d")
.Replace("#", "\\23");
}
}
// -----------------------------------------------------------------------
// DirectoryServicesCOMException dissection
// -----------------------------------------------------------------------
internal static class ErrorReporter
{
// ADSI HRESULTs (winerror.h / activeds.h)
private const int LDAP_NO_SUCH_OBJECT = unchecked((int)0x80072030);
private const int LDAP_INSUFFICIENT_RIGHTS = unchecked((int)0x80072098);
private const int LDAP_ALREADY_EXISTS = unchecked((int)0x80071392);
private const int LDAP_INVALID_CREDENTIALS = unchecked((int)0x8007052E);
private const int LDAP_SERVER_DOWN = unchecked((int)0x8007203A);
private const int E_ACCESSDENIED = unchecked((int)0x80070005);
public static bool IsNotFound(DirectoryServicesCOMException ex)
{
return ex != null && ex.ErrorCode == LDAP_NO_SUCH_OBJECT;
}
public static bool IsAccessDenied(DirectoryServicesCOMException ex)
{
if (ex == null) return false;
return ex.ErrorCode == LDAP_INSUFFICIENT_RIGHTS
|| ex.ErrorCode == E_ACCESSDENIED
|| ex.ErrorCode == LDAP_INVALID_CREDENTIALS;
}
public static bool IsAlreadyExists(DirectoryServicesCOMException ex)
{
return ex != null && ex.ErrorCode == LDAP_ALREADY_EXISTS;
}
public static int ToExitCode(DirectoryServicesCOMException ex)
{
if (IsNotFound(ex)) return ExitCodes.NotFound;
if (IsAccessDenied(ex)) return ExitCodes.AccessDenied;
return ExitCodes.LdapError;
}
public static void PrintCom(DirectoryServicesCOMException ex)
{
Logger.Err("LDAP error: {0}", ex.Message);
Console.Error.WriteLine("[-] HRESULT: 0x{0:X8}", ex.ErrorCode);
if (ex.ExtendedError != 0)
Console.Error.WriteLine("[-] ExtendedError: 0x{0:X} ({0})", ex.ExtendedError);
if (!string.IsNullOrEmpty(ex.ExtendedErrorMessage))
Console.Error.WriteLine("[-] ExtendedMsg: {0}", ex.ExtendedErrorMessage);
}
}
// -----------------------------------------------------------------------
// dnsRecord blob builders and parser (MS-DNSP DNS_RPC_RECORD)
// -----------------------------------------------------------------------
internal static class DnsRecord
{
public const ushort TypeZero = 0x0000; // tombstone
public const ushort TypeA = 0x0001;
public const ushort TypeNs = 0x0002;
public const ushort TypeCname = 0x0005;
public const ushort TypeSoa = 0x0006;
public const ushort TypePtr = 0x000C;
public const ushort TypeMx = 0x000F;
public const ushort TypeTxt = 0x0010;
public const ushort TypeAaaa = 0x001C;
public const ushort TypeSrv = 0x0021;
public static string TypeName(ushort t)
{
switch (t)
{
case TypeZero: return "TS";
case TypeA: return "A";
case TypeNs: return "NS";
case TypeCname: return "CNAME";
case TypeSoa: return "SOA";
case TypePtr: return "PTR";
case TypeMx: return "MX";
case TypeTxt: return "TXT";
case TypeAaaa: return "AAAA";
case TypeSrv: return "SRV";
default: return "Type" + t;
}
}
public static ushort GetType(byte[] data)
{
if (data == null || data.Length < 4) return 0xFFFF;
return Bin.ReadU16Le(data, 2);
}
public static byte[] BuildA(IPAddress ip, int ttl, uint timestamp = 0)
{
if (ip.AddressFamily != AddressFamily.InterNetwork)
throw new ArgumentException("BuildA requires an IPv4 address");
byte[] data = ip.GetAddressBytes();
return BuildHeader(TypeA, data, ttl, timestamp);
}
public static byte[] BuildAaaa(IPAddress ip, int ttl, uint timestamp = 0)
{
if (ip.AddressFamily != AddressFamily.InterNetworkV6)
throw new ArgumentException("BuildAaaa requires an IPv6 address");
byte[] data = ip.GetAddressBytes();
return BuildHeader(TypeAaaa, data, ttl, timestamp);
}
public static byte[] BuildCname(string target, int ttl, uint timestamp = 0)
{
if (string.IsNullOrWhiteSpace(target))
throw new ArgumentException("CNAME target cannot be empty");
byte[] data = EncodeCountName(target);
return BuildHeader(TypeCname, data, ttl, timestamp);
}
public static byte[] BuildTxt(string text, int ttl, uint timestamp = 0)
{
if (text == null) text = "";
byte[] raw = Encoding.ASCII.GetBytes(text);
if (raw.Length > 255)
throw new ArgumentException(
"TXT data exceeds 255 bytes; use --raw to inject multi-string TXT");
byte[] data = new byte[1 + raw.Length];
data[0] = (byte)raw.Length;
Buffer.BlockCopy(raw, 0, data, 1, raw.Length);
return BuildHeader(TypeTxt, data, ttl, timestamp);
}
public static byte[] BuildPtr(string target, int ttl, uint timestamp = 0)
{
if (string.IsNullOrWhiteSpace(target))
throw new ArgumentException("PTR target cannot be empty");
byte[] data = EncodeCountName(target);
return BuildHeader(TypePtr, data, ttl, timestamp);
}
public static byte[] BuildSrv(ushort priority, ushort weight, ushort port,
string target, int ttl, uint timestamp = 0)
{
if (string.IsNullOrWhiteSpace(target))
throw new ArgumentException("SRV target cannot be empty");
byte[] name = EncodeCountName(target);
byte[] data = new byte[6 + name.Length];
Bin.WriteU16Be(data, 0, priority);
Bin.WriteU16Be(data, 2, weight);
Bin.WriteU16Be(data, 4, port);
Buffer.BlockCopy(name, 0, data, 6, name.Length);
return BuildHeader(TypeSrv, data, ttl, timestamp);
}
public static byte[] BuildMx(ushort preference, string exchange, int ttl, uint timestamp = 0)
{
if (string.IsNullOrWhiteSpace(exchange))
throw new ArgumentException("MX exchange cannot be empty");
byte[] name = EncodeCountName(exchange);
byte[] data = new byte[2 + name.Length];
Bin.WriteU16Be(data, 0, preference);
Buffer.BlockCopy(name, 0, data, 2, name.Length);
return BuildHeader(TypeMx, data, ttl, timestamp);
}
public static uint AgingTimestampNow()
{
// Hours since 1601-01-01 00:00:00 UTC (the AD "aging timestamp" base).
// Matches the value a real DDNS update would write.
DateTime epoch = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);
double hours = (DateTime.UtcNow - epoch).TotalHours;
return (uint)hours;
}
public static byte[] BuildTombstone()
{
// DNS_RPC_RECORD_TS per MS-DNSP: type=0, datalen=8, data = EntombedTime FILETIME LE
long ft = DateTime.UtcNow.ToFileTimeUtc();
byte[] data = BitConverter.GetBytes(ft);
if (!BitConverter.IsLittleEndian) Array.Reverse(data);
return BuildHeader(TypeZero, data, 0);
}
private static byte[] BuildHeader(ushort type, byte[] data, int ttl, uint timestamp = 0)
{
byte[] record = new byte[24 + data.Length];
Bin.WriteU16Le(record, 0, (ushort)data.Length); // DataLength
Bin.WriteU16Le(record, 2, type); // Type
record[4] = 0x05; // Version
record[5] = 0xF0; // Rank = DNS_RANK_ZONE
Bin.WriteU16Le(record, 6, 0); // Flags
Bin.WriteU32Le(record, 8, 1); // Serial
Bin.WriteU32Be(record, 12, (uint)ttl); // TTL (big-endian)
Bin.WriteU32Le(record, 16, 0); // Reserved
Bin.WriteU32Le(record, 20, timestamp); // Timestamp: 0=static, else hours-since-1601
Buffer.BlockCopy(data, 0, record, 24, data.Length);
return record;
}
// DNS_COUNT_NAME per MS-DNSP 2.2.2.2.2 (matches Powermad / krbrelayx)
private static byte[] EncodeCountName(string name)
{
if (name.EndsWith("."))
name = name.Substring(0, name.Length - 1);
string[] labels = name.Split('.');
using (MemoryStream ms = new MemoryStream())
{
foreach (string label in labels)
{
byte[] lbl = Encoding.ASCII.GetBytes(label);
if (lbl.Length == 0)
throw new ArgumentException("Empty DNS label in: " + name);
if (lbl.Length > 63)
throw new ArgumentException("DNS label exceeds 63 bytes: " + label);
ms.WriteByte((byte)lbl.Length);
ms.Write(lbl, 0, lbl.Length);
}
ms.WriteByte(0);
byte[] body = ms.ToArray();
if (body.Length > 255)
throw new ArgumentException("Encoded DNS name exceeds 255 bytes: " + name);
byte[] result = new byte[2 + body.Length];
result[0] = (byte)body.Length; // cchNameLength
result[1] = (byte)labels.Length; // bLabelCount
Buffer.BlockCopy(body, 0, result, 2, body.Length);
return result;
}
}
public static string DecodeCountName(byte[] data, int offset)
{
if (offset + 2 > data.Length) return "<short>";
byte count = data[offset + 1];
int p = offset + 2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++)
{
if (p >= data.Length) break;
byte len = data[p++];
if (len == 0) break;
if (p + len > data.Length) break;
if (sb.Length > 0) sb.Append('.');
sb.Append(Encoding.ASCII.GetString(data, p, len));
p += len;
}
return sb.ToString();
}
public static string DecodeTxt(byte[] data, int offset, int len)
{
StringBuilder sb = new StringBuilder();
int end = offset + len;
int p = offset;
while (p < end)
{
byte s = data[p++];
if (p + s > end) break;
if (sb.Length > 0) sb.Append(" | ");
sb.Append(Encoding.ASCII.GetString(data, p, s));
p += s;
}
return sb.ToString();
}
public static string SummaryLine(byte[] data)
{
if (data == null || data.Length < 24) return "<short>";
ushort type = GetType(data);
ushort dataLength = Bin.ReadU16Le(data, 0);
uint ttl = Bin.ReadU32Be(data, 12);
string val;
switch (type)
{
case TypeA:
val = (data.Length >= 28)
? string.Format("{0}.{1}.{2}.{3}", data[24], data[25], data[26], data[27])
: "<malformed>";
break;
case TypeAaaa:
if (dataLength == 16 && data.Length >= 40)
{
byte[] addr = new byte[16];
Buffer.BlockCopy(data, 24, addr, 0, 16);
val = new IPAddress(addr).ToString();
}
else val = "<malformed>";
break;
case TypeCname:
case TypePtr:
case TypeNs:
val = DecodeCountName(data, 24);
break;
case TypeTxt:
val = "\"" + DecodeTxt(data, 24, dataLength) + "\"";
break;
case TypeSrv:
if (dataLength >= 6 && data.Length >= 30)
{
ushort sPri = Bin.ReadU16Be(data, 24);
ushort sWt = Bin.ReadU16Be(data, 26);
ushort sPort = Bin.ReadU16Be(data, 28);
string sTarget = DecodeCountName(data, 30);
val = sPri + " " + sWt + " " + sPort + " " + sTarget;
}
else val = "<malformed>";
break;
case TypeMx:
if (dataLength >= 2 && data.Length >= 26)
{
ushort pref = Bin.ReadU16Be(data, 24);
string exchange = DecodeCountName(data, 26);
val = pref + " " + exchange;
}
else val = "<malformed>";
break;
case TypeZero:
val = "<tombstone>";
break;
default:
val = "<" + dataLength + " bytes>";
break;
}
return string.Format("{0} (ttl={1})", val, ttl);
}
public static void Decode(byte[] data, string indent)
{
if (data.Length < 24)
{
Console.WriteLine("{0}<record too short: {1} bytes>", indent, data.Length);
return;
}
ushort dataLength = Bin.ReadU16Le(data, 0);
ushort type = Bin.ReadU16Le(data, 2);
byte version = data[4];
byte rank = data[5];
ushort flags = Bin.ReadU16Le(data, 6);
uint serial = Bin.ReadU32Le(data, 8);
uint ttl = Bin.ReadU32Be(data, 12);
uint reserved = Bin.ReadU32Le(data, 16);
uint timestamp = Bin.ReadU32Le(data, 20);
Console.WriteLine("{0}Type: {1} ({2})", indent, TypeName(type), type);
Console.WriteLine("{0}DataLength: {1}", indent, dataLength);
Console.WriteLine("{0}Version: {1}", indent, version);
Console.WriteLine("{0}Rank: 0x{1:X2}", indent, rank);
Console.WriteLine("{0}Flags: 0x{1:X4}", indent, flags);
Console.WriteLine("{0}Serial: {1}", indent, serial);
Console.WriteLine("{0}TTL: {1}", indent, ttl);
Console.WriteLine("{0}Timestamp: {1}{2}", indent, timestamp,
timestamp == 0 ? " (static)" : " (hours since 1601-01-01)");
if (data.Length < 24 + dataLength) return;
switch (type)
{
case TypeA:
if (dataLength == 4 && data.Length >= 28)
Console.WriteLine("{0}A: {1}.{2}.{3}.{4}",
indent, data[24], data[25], data[26], data[27]);
break;
case TypeAaaa:
if (dataLength == 16 && data.Length >= 40)
{
byte[] addr = new byte[16];
Buffer.BlockCopy(data, 24, addr, 0, 16);
Console.WriteLine("{0}AAAA: {1}", indent, new IPAddress(addr));
}
break;
case TypeCname:
Console.WriteLine("{0}CNAME: {1}", indent, DecodeCountName(data, 24));
break;
case TypePtr:
Console.WriteLine("{0}PTR: {1}", indent, DecodeCountName(data, 24));
break;
case TypeNs:
Console.WriteLine("{0}NS: {1}", indent, DecodeCountName(data, 24));
break;
case TypeTxt:
Console.WriteLine("{0}TXT: \"{1}\"", indent, DecodeTxt(data, 24, dataLength));
break;
case TypeSrv:
if (dataLength >= 6 && data.Length >= 30)
{
ushort sPri = Bin.ReadU16Be(data, 24);
ushort sWt = Bin.ReadU16Be(data, 26);
ushort sPort = Bin.ReadU16Be(data, 28);
string sTarget = DecodeCountName(data, 30);
Console.WriteLine("{0}SRV: priority={1} weight={2} port={3} target={4}",
indent, sPri, sWt, sPort, sTarget);
}
break;
case TypeMx:
if (dataLength >= 2 && data.Length >= 26)
{
ushort pref = Bin.ReadU16Be(data, 24);
string exchange = DecodeCountName(data, 26);
Console.WriteLine("{0}MX: preference={1} exchange={2}",
indent, pref, exchange);
}
break;
case TypeZero:
if (dataLength == 8)
{
long ft = (long)Bin.ReadU64Le(data, 24);
try
{
DateTime dt = DateTime.FromFileTimeUtc(ft);
Console.WriteLine("{0}Entombed: {1:u}", indent, dt);
}
catch
{
Console.WriteLine("{0}EntombedRaw: 0x{1:X16}", indent, ft);
}
}
break;
default:
byte[] raw = new byte[dataLength];
Buffer.BlockCopy(data, 24, raw, 0, dataLength);
Console.WriteLine("{0}RawData: {1}", indent, BitConverter.ToString(raw).Replace("-", ""));
break;
}
}
}
// -----------------------------------------------------------------------
// Endian helpers
// -----------------------------------------------------------------------
internal static class Bin
{
public static void WriteU16Le(byte[] b, int o, ushort v)
{
b[o] = (byte)(v & 0xff);
b[o + 1] = (byte)((v >> 8) & 0xff);
}
public static void WriteU16Be(byte[] b, int o, ushort v)
{
b[o] = (byte)((v >> 8) & 0xff);
b[o + 1] = (byte)(v & 0xff);
}
public static void WriteU32Le(byte[] b, int o, uint v)
{
b[o] = (byte)(v & 0xff);
b[o + 1] = (byte)((v >> 8) & 0xff);
b[o + 2] = (byte)((v >> 16) & 0xff);
b[o + 3] = (byte)((v >> 24) & 0xff);
}
public static void WriteU32Be(byte[] b, int o, uint v)
{
b[o] = (byte)((v >> 24) & 0xff);
b[o + 1] = (byte)((v >> 16) & 0xff);
b[o + 2] = (byte)((v >> 8) & 0xff);
b[o + 3] = (byte)(v & 0xff);
}
public static ushort ReadU16Le(byte[] b, int o)
{
return (ushort)(b[o] | (b[o + 1] << 8));
}
public static ushort ReadU16Be(byte[] b, int o)
{
return (ushort)((b[o] << 8) | b[o + 1]);
}
public static uint ReadU32Le(byte[] b, int o)
{
return (uint)(b[o]
| (b[o + 1] << 8)
| (b[o + 2] << 16)
| (b[o + 3] << 24));
}
public static uint ReadU32Be(byte[] b, int o)
{
return (uint)((b[o] << 24)
| (b[o + 1] << 16)
| (b[o + 2] << 8)
| b[o + 3]);
}
public static ulong ReadU64Le(byte[] b, int o)
{
ulong lo = ReadU32Le(b, o);
ulong hi = ReadU32Le(b, o + 4);
return lo | (hi << 32);
}
}
// -----------------------------------------------------------------------
// Action runners
// -----------------------------------------------------------------------
internal static class Actions
{
// ------------- list-zones -------------
public static int RunListZones(Options opt)
{
if (opt.Format != "text" && opt.Format != "json")
throw new ArgumentException("--format must be 'text' or 'json'");
bool jsonMode = opt.Format == "json";
string[] partitions = { "DomainDnsZones", "ForestDnsZones", "System" };
int total = 0;
StringBuilder json = null;
bool firstZone = true;
if (jsonMode)
{
json = new StringBuilder();
json.Append("{");
json.AppendFormat("\"correlation_id\":\"{0}\",", Program.CorrelationId);
json.Append("\"action\":\"list-zones\",");
json.Append("\"zones\":[");
}
foreach (string partition in partitions)
{
string containerDn = LdapOps.BuildContainerDn(partition, opt.DomainDn);
Logger.Verbose(opt, "Searching: {0}", containerDn);
using (DirectoryEntry container = LdapOps.Open(opt, containerDn))
{
DirectoryServicesCOMException err;
if (!LdapOps.TryBind(container, out err))
{
if (ErrorReporter.IsNotFound(err))
{
Logger.Verbose(opt, "Partition not present at this DN: {0}", partition);
continue;
}
Logger.Warn("Could not search partition {0}: {1}", partition, err.Message);
continue;
}
using (DirectorySearcher searcher = new DirectorySearcher(container))
{
searcher.Filter = "(objectClass=dnsZone)";
searcher.SearchScope = SearchScope.OneLevel;
searcher.PageSize = 1000;
searcher.PropertiesToLoad.Add("name");
searcher.PropertiesToLoad.Add("distinguishedName");