forked from CyberShadow/dhcptest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dhcptest.d
1379 lines (1246 loc) · 40.2 KB
/
dhcptest.d
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
/**
* A DHCP testing tool.
*
* License:
* Boost Software License 1.0:
* http://www.boost.org/LICENSE_1_0.txt
*
* Authors:
* Vladimir Panteleev <[email protected]>
*/
module dhcptest;
import core.thread;
import std.algorithm;
import std.array;
import std.ascii;
import std.bitmanip;
import std.conv;
import std.datetime;
import std.exception;
import std.format;
import std.getopt;
import std.math : ceil;
import std.random;
import std.range;
import std.socket;
import std.stdio;
import std.string;
import std.traits;
version (Windows)
static if (__VERSION__ >= 2067)
import core.sys.windows.winsock2 : ntohs, htons, ntohl, htonl;
else
import std.c.windows.winsock : ntohs, htons, ntohl, htonl;
else
version (Posix)
import core.sys.posix.netdb : ntohs, htons, ntohl, htonl;
else
static assert(false, "Unsupported platform");
version (linux)
{
import core.sys.linux.sys.socket;
import core.sys.posix.net.if_ : IF_NAMESIZE;
import core.sys.posix.sys.ioctl : ioctl, SIOCGIFINDEX;
enum IFNAMSIZ = IF_NAMESIZE;
extern(C) struct ifreq
{
char[IFNAMSIZ] ifr_name = 0;
union
{
private ubyte[IFNAMSIZ] _zeroinit = 0;
sockaddr ifr_addr;
sockaddr ifr_dstaddr;
sockaddr ifr_broadaddr;
sockaddr ifr_netmask;
sockaddr ifr_hwaddr;
short ifr_flags;
int ifr_ifindex;
int ifr_metric;
int ifr_mtu;
// ifmap ifr_map;
char[IFNAMSIZ] ifr_slave;
char[IFNAMSIZ] ifr_newname;
char* ifr_data;
}
}
extern(C) struct sockaddr_ll
{
ushort sll_family;
ushort sll_protocol;
int sll_ifindex;
ushort sll_hatype;
ubyte sll_pkttype;
ubyte sll_halen;
ubyte[8] sll_addr;
}
struct ether_header
{
ubyte[6] ether_dhost;
ubyte[6] ether_shost;
ushort ether_type;
}
struct iphdr
{
mixin(bitfields!(
ubyte, q{ihl}, 4,
ubyte, q{ver}, 4,
));
ubyte tos;
ushort tot_len;
ushort id;
ushort frag_off;
ubyte ttl;
ubyte protocol;
ushort check;
uint saddr;
uint daddr;
}
struct udphdr
{
ushort uh_sport;
ushort uh_dport;
ushort uh_ulen;
ushort uh_sum;
}
enum ETH_P_IP = 0x0800;
enum IP_DF = 0x4000;
}
/// Header (part up to the option fields) of a DHCP packet, as on wire.
align(1)
struct DHCPHeader
{
align(1):
/// Message op code / message type. 1 = BOOTREQUEST, 2 = BOOTREPLY
ubyte op;
/// Hardware address type, see ARP section in "Assigned Numbers" RFC; e.g., '1' = 10mb ethernet.
ubyte htype;
/// Hardware address length (e.g. '6' for 10mb ethernet).
ubyte hlen;
/// Client sets to zero, optionally used by relay agents when booting via a relay agent.
ubyte hops;
/// Transaction ID, a random number chosen by the client, used by the client and server to associate messages and responses between a client and a server.
uint xid;
/// Filled in by client, seconds elapsed since client began address acquisition or renewal process.
ushort secs;
/// Flags. (Only the BROADCAST flag is defined.)
ushort flags;
/// Client IP address; only filled in if client is in BOUND, RENEW or REBINDING state and can respond to ARP requests.
uint ciaddr;
/// 'your' (client) IP address.
uint yiaddr;
/// IP address of next server to use in bootstrap; returned in DHCPOFFER, DHCPACK by server.
uint siaddr;
/// Relay agent IP address, used in booting via a relay agent.
uint giaddr;
/// Client hardware address.
ubyte[16] chaddr;
/// Optional server host name, null terminated string.
char[64] sname = 0;
/// Boot file name, null terminated string; "generic" name or null in DHCPDISCOVER, fully qualified directory-path name in DHCPOFFER.
char[128] file = 0;
/// Optional parameters field. See the options documents for a list of defined options.
ubyte[0] options;
static assert(DHCPHeader.sizeof == 236);
}
/*
35 01 02
0F 17 68 6F 6D 65 2E 74 68 65 63 79 62 65 72 73 68 61 64 6F 77 2E 6E 65 74
01 04 FF FF FF 00
06 04 C0 A8 00 01
03 04 C0 A8 00 01
05 04 C0 A8 00 01
36 04 C0 A8 00 01
33 04 00 00 8C A0
FF
*/
struct DHCPOption
{
ubyte type;
ubyte[] data;
}
struct DHCPPacket
{
DHCPHeader header;
DHCPOption[] options;
}
enum DHCPOptionType : ubyte
{
dhcpMessageType = 53,
parameterRequestList = 55,
}
enum DHCPMessageType : ubyte
{
discover = 1,
offer,
request,
decline,
ack,
nak,
release,
inform
}
enum NETBIOSNodeType : ubyte
{
bNode = 1,
pNode = 2,
mMode = 4,
hNode = 8
}
enum NETBIOSNodeTypeChars = "BPMH";
/// How option values are displayed and interpreted
enum OptionFormat
{
unknown,
special,
str,
ip,
IP = ip, // for backwards compatibility
hex,
boolean,
u8,
u16,
u32,
i32 = u32, // for backwards compatibility
time,
dhcpMessageType,
dhcpOptionType,
netbiosNodeType,
relayAgent, // RFC 3046
vendorSpecificInformation,
classlessStaticRoute, // RFC 3442
clientIdentifier,
zeroLength,
}
struct DHCPOptionSpec
{
string name;
OptionFormat format;
}
DHCPOptionSpec[ubyte] dhcpOptions;
static this()
{
dhcpOptions =
[
0 : DHCPOptionSpec("Pad Option", OptionFormat.special),
1 : DHCPOptionSpec("Subnet Mask", OptionFormat.ip),
2 : DHCPOptionSpec("Time Offset", OptionFormat.time),
3 : DHCPOptionSpec("Router Option", OptionFormat.ip),
4 : DHCPOptionSpec("Time Server Option", OptionFormat.ip),
5 : DHCPOptionSpec("Name Server Option", OptionFormat.ip),
6 : DHCPOptionSpec("Domain Name Server Option", OptionFormat.ip),
7 : DHCPOptionSpec("Log Server Option", OptionFormat.ip),
8 : DHCPOptionSpec("Cookie Server Option", OptionFormat.ip),
9 : DHCPOptionSpec("LPR Server Option", OptionFormat.ip),
10 : DHCPOptionSpec("Impress Server Option", OptionFormat.ip),
11 : DHCPOptionSpec("Resource Location Server Option", OptionFormat.ip),
12 : DHCPOptionSpec("Host Name Option", OptionFormat.str),
13 : DHCPOptionSpec("Boot File Size Option", OptionFormat.u16),
14 : DHCPOptionSpec("Merit Dump File", OptionFormat.str),
15 : DHCPOptionSpec("Domain Name", OptionFormat.str),
16 : DHCPOptionSpec("Swap Server", OptionFormat.ip),
17 : DHCPOptionSpec("Root Path", OptionFormat.str),
18 : DHCPOptionSpec("Extensions Path", OptionFormat.str),
19 : DHCPOptionSpec("IP Forwarding Enable/Disable Option", OptionFormat.boolean),
20 : DHCPOptionSpec("Non-Local Source Routing Enable/Disable Option", OptionFormat.boolean),
21 : DHCPOptionSpec("Policy Filter Option", OptionFormat.ip),
22 : DHCPOptionSpec("Maximum Datagram Reassembly Size", OptionFormat.u16),
23 : DHCPOptionSpec("Default IP Time-to-live", OptionFormat.u8),
24 : DHCPOptionSpec("Path MTU Aging Timeout Option", OptionFormat.u32),
25 : DHCPOptionSpec("Path MTU Plateau Table Option", OptionFormat.u16),
26 : DHCPOptionSpec("Interface MTU Option", OptionFormat.u16),
27 : DHCPOptionSpec("All Subnets are Local Option", OptionFormat.boolean),
28 : DHCPOptionSpec("Broadcast Address Option", OptionFormat.ip),
29 : DHCPOptionSpec("Perform Mask Discovery Option", OptionFormat.boolean),
30 : DHCPOptionSpec("Mask Supplier Option", OptionFormat.boolean),
31 : DHCPOptionSpec("Perform Router Discovery Option", OptionFormat.boolean),
32 : DHCPOptionSpec("Router Solicitation Address Option", OptionFormat.ip),
33 : DHCPOptionSpec("Static Route Option", OptionFormat.ip),
34 : DHCPOptionSpec("Trailer Encapsulation Option", OptionFormat.boolean),
35 : DHCPOptionSpec("ARP Cache Timeout Option", OptionFormat.u32),
36 : DHCPOptionSpec("Ethernet Encapsulation Option", OptionFormat.boolean),
37 : DHCPOptionSpec("TCP Default TTL Option", OptionFormat.u8),
38 : DHCPOptionSpec("TCP Keepalive Interval Option", OptionFormat.u32),
39 : DHCPOptionSpec("TCP Keepalive Garbage Option", OptionFormat.boolean),
40 : DHCPOptionSpec("Network Information Service Domain Option", OptionFormat.str),
41 : DHCPOptionSpec("Network Information Servers Option", OptionFormat.ip),
42 : DHCPOptionSpec("Network Time Protocol Servers Option", OptionFormat.ip),
43 : DHCPOptionSpec("Vendor Specific Information", OptionFormat.vendorSpecificInformation),
44 : DHCPOptionSpec("NetBIOS over TCP/IP Name Server Option", OptionFormat.ip),
45 : DHCPOptionSpec("NetBIOS over TCP/IP Datagram Distribution Server Option", OptionFormat.ip),
46 : DHCPOptionSpec("NetBIOS over TCP/IP Node Type Option", OptionFormat.netbiosNodeType),
47 : DHCPOptionSpec("NetBIOS over TCP/IP Scope Option", OptionFormat.str),
48 : DHCPOptionSpec("X Window System Font Server Option", OptionFormat.ip),
49 : DHCPOptionSpec("X Window System Display Manager Option", OptionFormat.ip),
50 : DHCPOptionSpec("Requested IP Address", OptionFormat.ip),
51 : DHCPOptionSpec("IP Address Lease Time", OptionFormat.time),
52 : DHCPOptionSpec("Option Overload", OptionFormat.clientIdentifier),
53 : DHCPOptionSpec("DHCP Message Type", OptionFormat.dhcpMessageType),
54 : DHCPOptionSpec("Server Identifier", OptionFormat.ip),
55 : DHCPOptionSpec("Parameter Request List", OptionFormat.dhcpOptionType),
56 : DHCPOptionSpec("Message", OptionFormat.str),
57 : DHCPOptionSpec("Maximum DHCP Message Size", OptionFormat.u16),
58 : DHCPOptionSpec("Renewal (T1) Time Value", OptionFormat.time),
59 : DHCPOptionSpec("Rebinding (T2) Time Value", OptionFormat.time),
60 : DHCPOptionSpec("Vendor class identifier", OptionFormat.str),
61 : DHCPOptionSpec("Client-identifier", OptionFormat.u8),
64 : DHCPOptionSpec("Network Information Service+ Domain Option", OptionFormat.str),
65 : DHCPOptionSpec("Network Information Service+ Servers Option", OptionFormat.ip),
66 : DHCPOptionSpec("TFTP server name", OptionFormat.str),
67 : DHCPOptionSpec("Bootfile name", OptionFormat.str),
68 : DHCPOptionSpec("Mobile IP Home Agent option", OptionFormat.ip),
69 : DHCPOptionSpec("Simple Mail Transport Protocol (SMTP) Server Option", OptionFormat.ip),
70 : DHCPOptionSpec("Post Office Protocol (POP3) Server Option", OptionFormat.ip),
71 : DHCPOptionSpec("Network News Transport Protocol (NNTP) Server Option", OptionFormat.ip),
72 : DHCPOptionSpec("Default World Wide Web (WWW) Server Option", OptionFormat.ip),
73 : DHCPOptionSpec("Default Finger Server Option", OptionFormat.ip),
74 : DHCPOptionSpec("Default Internet Relay Chat (IRC) Server Option", OptionFormat.ip),
75 : DHCPOptionSpec("StreetTalk Server Option", OptionFormat.ip),
76 : DHCPOptionSpec("StreetTalk Directory Assistance (STDA) Server Option", OptionFormat.ip),
80 : DHCPOptionSpec("Rapid Commit", OptionFormat.zeroLength),
82 : DHCPOptionSpec("Relay Agent Information", OptionFormat.relayAgent),
100 : DHCPOptionSpec("PCode", OptionFormat.str),
101 : DHCPOptionSpec("TCode", OptionFormat.str),
108 : DHCPOptionSpec("IPv6-Only Preferred", OptionFormat.u32),
114 : DHCPOptionSpec("DHCP Captive-Portal", OptionFormat.str),
116 : DHCPOptionSpec("Auto Config", OptionFormat.boolean),
118 : DHCPOptionSpec("Subnet Selection", OptionFormat.ip),
121 : DHCPOptionSpec("Classless Static Route Option", OptionFormat.classlessStaticRoute),
249 : DHCPOptionSpec("Microsoft Classless Static Route", OptionFormat.classlessStaticRoute),
252 : DHCPOptionSpec("Web Proxy Auto-Discovery", OptionFormat.str),
255 : DHCPOptionSpec("End Option", OptionFormat.special),
];
}
DHCPPacket parsePacket(ubyte[] data)
{
DHCPPacket result;
enforce(data.length > DHCPHeader.sizeof + 4, "DHCP packet too small");
result.header = *cast(DHCPHeader*)data.ptr;
data = data[DHCPHeader.sizeof..$];
enforce(data[0..4] == [99, 130, 83, 99], "Absent DHCP option magic cookie");
data = data[4..$];
ubyte readByte()
{
enforce(data.length, "Unexpected end of packet");
ubyte b = data[0];
data = data[1..$];
return b;
}
while (true)
{
auto optionType = readByte();
if (optionType==0) // pad option
continue;
if (optionType==255) // end option
break;
auto len = readByte();
DHCPOption option;
option.type = optionType;
foreach (n; 0..len)
option.data ~= readByte();
result.options ~= option;
}
return result;
}
ubyte[] serializePacket(DHCPPacket packet)
{
ubyte[] data;
data ~= cast(ubyte[])((&packet.header)[0..1]);
data ~= [99, 130, 83, 99];
foreach (option; packet.options)
{
data ~= option.type;
data ~= to!ubyte(option.data.length);
data ~= option.data;
}
data ~= 255;
return data;
}
string[] classlessStaticRoute(in ubyte[] bytes)
{
string[] result;
size_t i = 0;
while (i < bytes.length)
{
try
{
ubyte maskBits = bytes[i++];
enforce(maskBits <= 32, "Too many bits in mask length");
ubyte[4] subnet = 0;
ubyte subnetSignificantBytes = (maskBits + 7) / 8;
enforce(i + subnetSignificantBytes <= bytes.length, "Not enough bytes for route subnet");
subnet[0 .. subnetSignificantBytes] = bytes[i .. i + subnetSignificantBytes];
i += subnetSignificantBytes;
ubyte[4] routerIP;
enforce(i + 4 <= bytes.length, "Not enough bytes for router IP");
routerIP[] = bytes[i .. i + 4];
i += 4;
result ~= format!"%(%d.%)/%d -> %(%d.%)"(subnet[], maskBits, routerIP);
}
catch (Exception e)
{
result ~= format!"(Error: %s) %(%02x %)"(e.msg, bytes);
break;
}
}
return result;
}
unittest
{
assert(classlessStaticRoute([0x18, 0xc0, 0xa8, 0x02, 0xc0, 0xa8, 0x01, 0x32]) == ["192.168.2.0/24 -> 192.168.1.50"]);
}
string ip(uint addr) { return "%(%d.%)".format(cast(ubyte[])((&addr)[0..1])); }
string ntime(uint n) { return "%d (%s)".format(n.ntohl, n.ntohl.seconds); }
string maybeAscii(in ubyte[] bytes)
{
string s = "%(%02X %)".format(bytes);
if (bytes.all!(b => (b >= 0x20 && b <= 0x7E) || !b))
s = "%(%s, %) (%s)".format((cast(string)bytes).split("\0"), s);
return s;
}
string formatDHCPOptionType(DHCPOptionType type)
{
return format("%3d (%s)", cast(ubyte)type, dhcpOptions.get(type, DHCPOptionSpec("Unknown")).name);
}
DHCPOptionType parseDHCPOptionType(string type)
{
if (type.isNumeric)
return cast(DHCPOptionType)type.to!ubyte;
foreach (opt, spec; dhcpOptions)
if (!icmp(spec.name, type))
return cast(DHCPOptionType)opt;
throw new Exception("Unknown DHCP option type: " ~ type);
}
// Length-prefixed sub-option list
struct VLList(Type)
{
struct Suboption
{
Type type;
char[] value;
this(Type type, inout(char)[] value) inout { this.type = type; this.value = value; }
this(ref string s)
{
assert(s.length);
if (s[0].isDigit)
{
ubyte typeByte;
enforce(s.formattedRead!"%s"(&typeByte) == 1, "Expected sub-option type");
type = cast(Type)typeByte;
}
else
enforce(s.formattedRead!"%s"(&type) == 1, "Expected sub-option type");
enforce(s.skipOver("="), "Expected = in sub-option");
value = s.parseElement!(char[])();
}
string toString() const
{
return format("%s=%(%s%)",
type.to!string.startsWith("cast(") ? type.to!ubyte.to!string : type.to!string,
value.only);
}
const(ubyte)[] toBytes() const pure
{
const(ubyte)[] result;
if (type != Type.raw)
{
result ~= type.to!ubyte;
result ~= value.representation.length.to!ubyte;
}
result ~= value.representation;
return result;
}
}
Suboption[] suboptions;
this(inout(ubyte)[] bytes) inout
{
inout(Suboption)[] suboptions;
while (bytes.length >= 2)
{
auto len = bytes[1];
if (2 + len > bytes.length)
break;
suboptions ~= inout Suboption(cast(Type)bytes[0], cast(inout(char)[])bytes[2 .. 2 + len]);
bytes = bytes[2 + len .. $];
}
if (bytes.length)
suboptions ~= inout Suboption(Type.raw, cast(inout(char)[]) bytes);
this.suboptions = suboptions;
}
this(/*ref*/ string s)
{
while (s.length)
{
suboptions ~= Suboption(s);
if (s.length)
{
enforce(s.skipOver(","), "',' expected");
while (s.skipOver(" ")) {}
}
}
}
string toString() const
{
return format!"%-(%s, %)"(suboptions);
}
const(ubyte)[] toBytes() const pure
{
return suboptions.map!((ref suboption) => suboption.toBytes).join();
}
}
enum RelayAgentInformationSuboption
{
raw = -1, // Not a real sub-option - used to store slack / unparseable bytes
agentCircuitID = 1,
agentRemoteID = 2,
}
alias RelayAgentInformation = VLList!RelayAgentInformationSuboption;
unittest
{
void test(ubyte[] bytes, string str)
{
auto fromBytes = RelayAgentInformation(bytes);
assert(fromBytes.toBytes() == bytes, [fromBytes.toBytes(), bytes].to!string);
assert(fromBytes.toString() == str, [fromBytes.toString(), str].to!string);
auto fromStr = RelayAgentInformation(str);
assert(fromStr.toBytes() == bytes);
assert(fromStr.toString() == str);
}
test(
[],
``
);
test(
[0x00],
`raw="\0"`
);
test(
[0x01, 0x03, 'f', 'o', 'o'],
`agentCircuitID="foo"`
);
test(
[0x01, 0x03, 'f', 'o', 'o', 0x42],
`agentCircuitID="foo", raw="B"`
);
test(
[0x01, 0x03, 'f', 'o', 'o', 0x02, 0x03, 'b', 'a', 'r'],
`agentCircuitID="foo", agentRemoteID="bar"`
);
test(
[0x03, 0x03, 'f', 'o', 'o'],
`3="foo"`
);
}
enum VendorSpecificInformationSuboption
{
raw = -1, // Not a real sub-option - used to store slack / unparseable bytes
}
alias VendorSpecificInformation = VLList!VendorSpecificInformationSuboption;
__gshared string printOnly;
__gshared bool quiet;
/// Print an option in a human-readable format.
void printOption(File f, in ubyte[] bytes, OptionFormat fmt)
{
try
final switch (fmt)
{
case OptionFormat.special:
assert(false);
case OptionFormat.unknown:
case OptionFormat.hex:
f.writeln(maybeAscii(bytes));
break;
case OptionFormat.str:
f.writeln(cast(string)bytes);
break;
case OptionFormat.ip:
enforce(bytes.length % 4 == 0, "Bad IP bytes length");
f.writefln("%-(%s, %)", map!ip(cast(uint[])bytes));
break;
case OptionFormat.classlessStaticRoute:
f.writefln("%-(%s, %)", classlessStaticRoute(bytes));
break;
case OptionFormat.boolean:
f.writefln("%-(%s, %)", cast(bool[])bytes);
break;
case OptionFormat.u8:
f.writefln("%-(%s, %)", bytes);
break;
case OptionFormat.u16:
enforce(bytes.length % 2 == 0, "Bad u16 bytes length");
f.writefln("%-(%s, %)", (cast(ushort[])bytes).map!ntohs);
break;
case OptionFormat.u32:
enforce(bytes.length % 4 == 0, "Bad u32 bytes length");
f.writefln("%-(%s, %)", (cast(uint[])bytes).map!ntohl);
break;
case OptionFormat.time:
enforce(bytes.length % 4 == 0, "Bad time bytes length");
f.writefln("%-(%s, %)", map!ntime(cast(uint[])bytes));
break;
case OptionFormat.dhcpMessageType:
enforce(bytes.length==1, "Bad dhcpMessageType data length");
f.writeln(cast(DHCPMessageType)bytes[0]);
break;
case OptionFormat.dhcpOptionType:
f.writefln("%-(%s, %)", map!formatDHCPOptionType(cast(DHCPOptionType[])bytes));
break;
case OptionFormat.netbiosNodeType:
enforce(bytes.length==1, "Bad netbiosNodeType data length");
f.writefln("%-(%s, %)", bytes
.map!(b =>
NETBIOSNodeTypeChars
.length
.iota
.filter!(i => (1 << i) & b)
.map!(i => NETBIOSNodeTypeChars[i])
.array
)
);
break;
case OptionFormat.vendorSpecificInformation:
f.writeln((const VendorSpecificInformation(bytes)).toString());
break;
case OptionFormat.relayAgent:
f.writeln((const RelayAgentInformation(bytes)).toString());
break;
case OptionFormat.clientIdentifier:
enforce(bytes.length >= 1, "No type");
f.writefln("type=%d, clientIdentifier=%s", bytes[0], maybeAscii(bytes[1..$]));
break;
case OptionFormat.zeroLength:
enforce(bytes.length==0, "Expected zero length");
f.writeln("present");
break;
}
catch (Exception e)
f.writefln("Decode error (%s). Raw bytes: %s",
e.msg, maybeAscii(bytes));
}
/// Print an option in machine-readable format.
void printRawOption(File f, in ubyte[] bytes, OptionFormat fmt)
{
final switch (fmt)
{
case OptionFormat.special:
assert(false);
case OptionFormat.unknown:
case OptionFormat.hex:
case OptionFormat.relayAgent:
case OptionFormat.vendorSpecificInformation:
case OptionFormat.clientIdentifier:
case OptionFormat.zeroLength:
f.writefln("%-(%02X%)", bytes);
break;
case OptionFormat.str:
f.write(cast(char[])bytes);
f.flush();
break;
case OptionFormat.ip:
case OptionFormat.boolean:
case OptionFormat.u8:
case OptionFormat.u16:
case OptionFormat.u32:
case OptionFormat.dhcpMessageType:
case OptionFormat.dhcpOptionType:
case OptionFormat.netbiosNodeType:
case OptionFormat.classlessStaticRoute:
return printOption(f, bytes, fmt);
case OptionFormat.time:
return printOption(f, bytes, OptionFormat.u32);
}
}
void printPacket(File f, DHCPPacket packet)
{
if (printOnly != "")
{
string numStr = printOnly;
string fmtStr = "";
if (numStr.endsWith("]"))
{
auto numParts = printOnly.findSplit("[");
fmtStr = numParts[2][0..$-1];
numStr = numParts[0];
}
auto opt = parseDHCPOptionType(numStr);
OptionFormat fmt = fmtStr.length ? fmtStr.to!OptionFormat : OptionFormat.unknown;
if (fmt == OptionFormat.unknown)
fmt = dhcpOptions.get(opt, DHCPOptionSpec.init).format;
foreach (option; packet.options)
{
if (option.type == opt)
{
printRawOption(f, option.data, fmt);
return;
}
}
if (!quiet) stderr.writefln("(No option %s in packet)", opt);
return;
}
auto opNames = [1:"BOOTREQUEST",2:"BOOTREPLY"];
f.writefln(" op=%s chaddr=%(%02X:%) hops=%d xid=%08X secs=%d flags=%04X\n ciaddr=%s yiaddr=%s siaddr=%s giaddr=%s sname=%s file=%s",
opNames.get(packet.header.op, text(packet.header.op)),
packet.header.chaddr[0..packet.header.hlen],
packet.header.hops,
ntohl(packet.header.xid),
ntohs(packet.header.secs),
ntohs(packet.header.flags),
ip(packet.header.ciaddr),
ip(packet.header.yiaddr),
ip(packet.header.siaddr),
ip(packet.header.giaddr),
to!string(packet.header.sname.ptr),
to!string(packet.header.file.ptr),
);
f.writefln(" %d options:", packet.options.length);
foreach (option; packet.options)
{
auto type = cast(DHCPOptionType)option.type;
f.writef(" %s: ", formatDHCPOptionType(type));
auto format = dhcpOptions.get(type, DHCPOptionSpec.init).format;
printOption(f, option.data, format);
}
f.flush();
}
enum SERVER_PORT = 67;
enum CLIENT_PORT = 68;
ushort serverPort = SERVER_PORT;
ushort clientPort = CLIENT_PORT;
string[] requestedOptions;
string[] sentOptions;
ushort requestSecs = 0;
uint giaddr;
DHCPPacket generatePacket(ubyte[] mac)
{
DHCPPacket packet;
packet.header.op = 1; // BOOTREQUEST
packet.header.htype = 1;
packet.header.hlen = mac.length.to!ubyte;
packet.header.hops = 0;
packet.header.xid = uniform!uint();
packet.header.secs = requestSecs;
packet.header.flags = htons(0x8000); // Set BROADCAST flag - required to be able to receive a reply to an imaginary hardware address
packet.header.chaddr[0..mac.length] = mac;
packet.header.giaddr = giaddr;
if (requestedOptions.length)
packet.options ~= DHCPOption(DHCPOptionType.parameterRequestList, cast(ubyte[])requestedOptions.map!parseDHCPOptionType.array);
foreach (option; sentOptions)
{
scope(failure) stderr.writeln("Error with parsing option ", option, ":");
auto s = option.findSplit("=");
string numStr = s[0];
string value = s[2];
string fmtStr;
if (numStr.endsWith("]"))
{
auto numParts = numStr.findSplit("[");
fmtStr = numParts[2][0..$-1];
numStr = numParts[0];
}
auto opt = parseDHCPOptionType(numStr);
ubyte[] bytes;
OptionFormat fmt = fmtStr.length ? fmtStr.to!OptionFormat : OptionFormat.unknown;
if (fmt == OptionFormat.unknown)
fmt = dhcpOptions.get(opt, DHCPOptionSpec.init).format;
final switch (fmt)
{
case OptionFormat.special:
throw new Exception(format("Can't specify a value for special option %d.", opt));
case OptionFormat.unknown:
throw new Exception(format("Don't know how to interpret given value for option %d, please specify a format explicitly.", opt));
case OptionFormat.str:
bytes = cast(ubyte[])value;
break;
case OptionFormat.ip:
bytes = value
.replace(" ", ".")
.replace(",", ".")
.splitter(".")
.map!(to!ubyte)
.array();
enforce(bytes.length % 4 == 0, "Malformed IP address");
break;
case OptionFormat.hex:
static ubyte fromHex(string os) { auto s = os; ubyte b = s.parse!ubyte(16); enforce(!s.length, "Invalid hex string: " ~ os); return b; }
bytes = value
.replace(" ", "")
.replace(":", "")
.chunks(2)
.map!(chunk => fromHex(to!string(chunk)))
.array();
break;
case OptionFormat.boolean:
bytes = value
.splitter(",")
.map!strip
.map!(to!bool)
.map!(b => ubyte(b))
.array();
break;
case OptionFormat.u8:
bytes = value
.splitter(",")
.map!strip
.map!(to!ubyte)
.array();
break;
case OptionFormat.u16:
bytes = value
.splitter(",")
.map!strip
.map!(to!ushort)
.map!htons
.map!((ushort i) { ushort[] a = [i]; ubyte[] b = cast(ubyte[])a; return b; })
.join();
break;
case OptionFormat.u32:
case OptionFormat.time:
bytes = value
.splitter(",")
.map!strip
.map!(to!int)
.map!htonl
.map!((int i) { int[] a = [i]; ubyte[] b = cast(ubyte[])a; return b; })
.join();
break;
case OptionFormat.dhcpMessageType:
bytes = value
.splitter(",")
.map!strip
.map!(to!DHCPMessageType)
.map!((ubyte i) => [i])
.join();
break;
case OptionFormat.dhcpOptionType:
bytes = value
.splitter(",")
.map!strip
.map!parseDHCPOptionType
.map!((ubyte i) => [i])
.join();
break;
case OptionFormat.netbiosNodeType:
bytes = value
.splitter(",")
.map!strip
.map!(s => s
.map!(c => NETBIOSNodeTypeChars.indexOf(c))
.map!(i => (1 << i).to!ubyte)
.fold!((a, b) => ubyte(a | b))
)
.array();
break;
case OptionFormat.relayAgent:
bytes = RelayAgentInformation(value).toBytes().dup;
break;
case OptionFormat.vendorSpecificInformation:
bytes = VendorSpecificInformation(value).toBytes().dup;
break;
case OptionFormat.classlessStaticRoute:
case OptionFormat.clientIdentifier:
throw new Exception(format("Sorry, the format %s is unsupported for parsing. Please specify another format explicitly.", fmt));
case OptionFormat.zeroLength:
enforce(value == "present", "Value for empty options must be \"present\"");
break;
}
packet.options ~= DHCPOption(opt, bytes);
}
if (packet.options.all!(option => option.type != DHCPOptionType.dhcpMessageType))
packet.options = DHCPOption(DHCPOptionType.dhcpMessageType, [DHCPMessageType.discover]) ~ packet.options;
return packet;
}
ushort ipChecksum(void[] data)
{
if (data.length % 2)
data.length = data.length + 1;
auto words = cast(ushort[])data;
uint checksum = 0xffff;
foreach (word; words)
{
checksum += ntohs(word);
if (checksum > 0xffff)
checksum -= 0xffff;
}
return htons((~checksum) & 0xFFFF);
}
void sendPacket(Socket socket, Address addr, string targetIP, ubyte[] mac, DHCPPacket packet)
{
if (!quiet)
{
stderr.writefln("Sending packet:");
stderr.printPacket(packet);
}
auto data = serializePacket(packet);
static if (is(typeof(AF_PACKET)))
if (socket.addressFamily != AF_INET)
{
static struct Header
{
align(1):
ether_header ether;
iphdr ip;
udphdr udp;
}
Header header;
header.ether.ether_dhost[] = 0xFF; // broadcast
header.ether.ether_shost[] = mac;
header.ether.ether_type = ETH_P_IP.htons;
static assert(iphdr.sizeof % 4 == 0);
header.ip.ihl = iphdr.sizeof / 4;
header.ip.ver = 4;
header.ip.tot_len = (header.ip.sizeof + header.udp.sizeof + data.length).to!ushort.htons;
static ushort idCounter;
header.ip.id = ++idCounter;
// header.ip.frag_off = IP_DF.htons;
header.ip.ttl = 0x40;
header.ip.protocol = IPPROTO_UDP;
header.ip.saddr = 0x00000000; // 0.0.0.0
inet_pton(AF_INET, targetIP.toStringz, &header.ip.daddr).enforce("Invalid target IP address");
header.ip.check = ipChecksum((&header.ip)[0..1]);
header.udp.uh_sport = clientPort.htons;
header.udp.uh_dport = serverPort.htons;
header.udp.uh_ulen = (header.udp.sizeof + data.length).to!ushort.htons;
static struct UDPChecksumData
{
uint saddr;
uint daddr;
ubyte zeroes = 0x0;
ubyte proto = IPPROTO_UDP;
ushort udp_len;
udphdr udp;
}
UDPChecksumData udpChecksumData;
udpChecksumData.saddr = header.ip.saddr;
udpChecksumData.daddr = header.ip.daddr;