-
Notifications
You must be signed in to change notification settings - Fork 0
/
dhcpd.pl
executable file
·1156 lines (961 loc) · 39.5 KB
/
dhcpd.pl
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
#!/usr/local/bin/perl -w
### Rozhuk Ivan, 2011 - 2016
### dhcp perl server
### version 1.0
# required:
# /usr/ports/lang/p5-Switch
# /usr/ports/net/p5-Net-DHCP
# /usr/ports/devel/p5-Test-Benchmark
# /usr/ports/databases/p5-DBI
# /usr/ports/databases/p5-Class-DBI-mysql
# 2014.06: * fix: db_get_routing - send routes only in 121/249 option, do not mix with option 33
# 2016.01: * fix: Windows XP work with option 43
# * fix: opt82 parse on new ugly swithes
use strict;
use utf8;
use warnings;
use threads;
use threads::shared;
use Socket;
use DBI;
use Net::DHCP::Packet;
use Net::DHCP::Constants;
use Benchmark ':hireswallclock';
use POSIX qw(setsid setuid strftime :signal_h);
use Getopt::Long;
use Sys::Syslog;
use Data::Dumper;
use 5.010;
no if $] >= 5.018, warnings => "experimental::smartmatch";
#require 'sys/syscall.ph';
binmode(STDOUT, ':utf8');
# settings, via command line or internal defined
my ($BIND_ADDR, $SERVER_PORT, $CLIENT_PORT, $MIRROR, $DHCP_SERVER_ID, $THREADS_COUNT, $DBDATASOURCE, $DBLOGIN, $DBPASS, $PIDFILE, $DEBUG);
# global variables
my $RUNNING :shared;
my ($ADDR_BCAST, $ADDR_MIRROR, $SOCKET_RCV);
#share($SOCKET_RCV);
&startpoint();
# this keeps the program alive or something after exec'ing perl scripts
END{}
BEGIN{}
{
no warnings; *CORE::GLOBAL::exit = sub {die "fakeexit\nrc=" . shift() . "\n";};
};
eval q{exit};
if ($@) {exit unless $@ =~ /^fakeexit/;};
# generic signal handler to cause daemon to stop
sub signal_handler {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
$RUNNING = 0;
close($SOCKET_RCV);
$_->kill('KILL')->detach() foreach threads->list();
#$_->join foreach threads->list();
}
sub startpoint {
if ($#ARGV == - 1) {
usage();
return;
}
# set default settings values
$BIND_ADDR = '0.0.0.0';
$SERVER_PORT = '67';
$CLIENT_PORT = '68';
$DHCP_SERVER_ID = ''; # REQUIRED real IP for work!!!
$MIRROR = undef;
$DBDATASOURCE = 'mysql:dhcp:127.0.0.1';
$DBLOGIN = 'dhcp';
$DBPASS = 'dhcp';
$THREADS_COUNT = 4;
$PIDFILE = '/var/run/perl-dhcpd.pid';
$DEBUG = 0;
my $DAEMON = undef;
GetOptions(
'b=s' => \$BIND_ADDR,
'sp:i' => \$SERVER_PORT,
'cp:i' => \$CLIENT_PORT,
'id=s' => \$DHCP_SERVER_ID,
'm=s' => \$MIRROR,
't:i' => \$THREADS_COUNT,
'dbs=s' => \$DBDATASOURCE,
'dbl=s' => \$DBLOGIN,
'dbp=s' => \$DBPASS,
'P:s' => \$PIDFILE,
'v:i' => \$DEBUG,
'd' => \$DAEMON,
);
# untainte input
if ($BIND_ADDR =~ /^(.*)$/) {$BIND_ADDR = $1;}
if ($DHCP_SERVER_ID =~ /^(.*)$/) {$DHCP_SERVER_ID = $1;}
if ($PIDFILE =~ /^(.*)$/) {$PIDFILE = $1;}
if (defined($DHCP_SERVER_ID) == 0) {
usage();
}
$SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&signal_handler;
# trap or ignore $SIG{PIPE}
# Daemon behaviour
# ignore any PIPE signal: standard behaviour is to quit process
$SIG{PIPE} = 'IGNORE';
openlog("dhcp-perl", "ndelay,pid", "local0");
logger("BIND_ADDR: $BIND_ADDR, THREADS_COUNT: $THREADS_COUNT, PIDFILE: $PIDFILE");
if (defined($DAEMON)) {
$DEBUG = undef;
daemonize();
}
main();
}
sub usage {
print "Usage: dhcpd [options]\n\n";
print " -b <ip> ip address to bind (def: 0.0.0.0)\n";
print " -sp <port> port bind (def: 67)\n";
print " -cp <port> port to send reply directly to client (def: 68)\n";
print " -id <ip> ip addr DHCP server ID, REQUIRED!, MUST be real IP of server\n";
print " -m <ip> ip address to mirror all packets on 67 port\n";
print " -t <threads> number of thread, recomended: CPU cores * 2, (default 4)\n";
print " -dbs database data source: DriverName:database=database_name;host=hostname;port=port\n";
print " -dbl data base login\n";
print " -dbp data base password\n";
print " -P <path> name of PID-file for spawned process\n";
print " -v <level> print debug info, levels: 1, 2 (def: off)\n";
print " -d daemon mode\n";
exit;
}
# sample logger
sub logger {
syslog('info', $_[0]);
if (defined($DEBUG) == 0) {return;}
print STDOUT strftime "[%d/%b/%Y %H:%M:%S] ", localtime;
print STDOUT $_[0] . "\n";
}
sub daemonize {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; # Make %ENV safer
#setuid(65534) or die "Can't set uid: $!\n"; # nobody
open(STDIN, "+>/dev/null") or die "Can't open STDIN: $!\n";
open(STDOUT, "+>&STDIN") or die "Can't open STDOUT: $!\n";
open(STDERR, "+>&STDIN") or die "Can't open STDERR: $!\n";
defined(my $tm = fork) or die "Can't fork: $!\n";
exit if $tm;
setsid or die "Can't start a new session: $!\n";
umask 0;
logger("Daemon mode");
}
sub main {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
if (defined($BIND_ADDR) == 0) {return;}
# write PID to file
if (defined($PIDFILE)) {
open FILE, "> $PIDFILE" || logger("PID file save error: $!");
print FILE "$$\n";
close FILE;
}
$RUNNING = 1;
# broadcast address
$ADDR_BCAST = sockaddr_in($CLIENT_PORT, INADDR_BROADCAST);# sockaddr_in($CLIENT_PORT, inet_aton('255.255.255.255'))
# set mirror address if defimed
if (defined($MIRROR)) {# traff mirroring
$ADDR_MIRROR = sockaddr_in($SERVER_PORT, inet_aton($MIRROR));
}
# open listening socket
socket($SOCKET_RCV, PF_INET, SOCK_DGRAM, getprotobyname('udp')) || die "Socket creation error: $@\n";
bind($SOCKET_RCV, sockaddr_in($SERVER_PORT, inet_aton($BIND_ADDR))) || die "bind: $!";
# start threads
for my $i (1 .. ($THREADS_COUNT - 1)) {
threads->create({ 'context' => 'void' }, \&request_loop);
}
### Collect the bits and pieces! ...
#$_->join foreach threads->list();
#$_->detach foreach threads->list();
# and handle request with other threads
request_loop();
# delete PID file on exit
if (defined($PIDFILE)) {
unlink($PIDFILE);
}
logger("Main: END!");
closelog();
}
sub request_loop {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
my ($buf, $fromaddr, $dhcpreq); # recv data
my $dbh; # database connect
my ($t0, $t1, $td); # perfomance data
my $tid = threads->tid(); # thread ID
logger("Thread ($tid): START");
# each thread make its own connection to DB
# connect($data_source, $username, $password, \%attr)
# dbi:DriverName:database=database_name;host=hostname;port=port
until($dbh = DBI->connect("DBI:".$DBDATASOURCE, $DBLOGIN, $DBPASS)){
logger("Thread ($tid): Could not connect to database: $DBI::errstr");
logger("Thread ($tid): Sleeping 10 sec to retry");
sleep(10);
}
if (defined($dbh) == 0) {
logger("Could not connect to database: $DBI::errstr");
thread_exit(1);
}
$dbh->{mysql_auto_reconnect} = 1;
if ($tid != 0) {
# disable signals receiving on creted threads and set handler for KILL signal
my $sigset = POSIX::SigSet->new(SIGINT, SIGTERM, SIGHUP); # define the signals to block
my $old_sigset = POSIX::SigSet->new; # where the old sigmask will be kept
unless (defined sigprocmask(SIG_BLOCK, $sigset, $old_sigset)) {die "Could not unblock SIGINT\n";}
$SIG{KILL} = sub {
logger("Thread ($tid): END by sig handler");
$dbh->disconnect;
thread_exit(0);
};
}
while ($RUNNING == 1) {
$buf = undef;
eval {
# catch fatal errors
# receive packet
$fromaddr = recv($SOCKET_RCV, $buf, 16384, 0) || logger("Thread ($tid) recv err: $!");
next if ($!); # continue loop if an error occured
# filter to small packets
next if (length($buf) < 236); # 300
if (defined($DEBUG)) {
$t0 = Benchmark->new;
}
# parce data to dhcp structes
$dhcpreq = Net::DHCP::Packet->new($buf);
# filter bad params in head
next if ($dhcpreq->op() != BOOTREQUEST || $dhcpreq->isDhcp() == 0);
next if ($dhcpreq->htype() != HTYPE_ETHER || $dhcpreq->hlen() != 6);
# bad DHCP message!
next if (defined($dhcpreq->getOptionRaw(DHO_DHCP_MESSAGE_TYPE())) == 0);
# Is message for us?
next if (defined($dhcpreq->getOptionRaw(DHO_DHCP_SERVER_IDENTIFIER())) && $dhcpreq->getOptionValue(DHO_DHCP_SERVER_IDENTIFIER()) ne $DHCP_SERVER_ID);
# RRAS client, ignory them
next if (defined($dhcpreq->getOptionRaw(DHO_USER_CLASS())) && $dhcpreq->getOptionRaw(DHO_USER_CLASS()) eq "RRAS.Microsoft");
# send duplicate of received packet to mirror
if (defined($ADDR_MIRROR)) {
send($SOCKET_RCV, $buf, 0, $ADDR_MIRROR) || logger("send mirr error: $!");
}
# print received packed
if (defined($DEBUG)) {
my ($port, $addr) = unpack_sockaddr_in($fromaddr);
my $ipaddr = inet_ntoa($addr);
# change hw addr format
my $mac = FormatMAC(substr($dhcpreq->chaddr(), 0, (2 * $dhcpreq->hlen())));
logger("Thread $tid: Got a packet src = $ipaddr:$port mac = $mac length = " . length($buf));
if ($DEBUG > 1) {
logger($dhcpreq->toString());
}
}
db_log_detailed($dbh, $dhcpreq);
# handle packet
given ($dhcpreq->getOptionValue(DHO_DHCP_MESSAGE_TYPE())) {
when ($_ == DHCPDISCOVER) {handle_discover($dbh, $fromaddr, $dhcpreq);}#-> DHCPOFFER
when ($_ == DHCPREQUEST) {handle_request($dbh, $fromaddr, $dhcpreq);}#-> DHCPACK/DHCPNAK
when ($_ == DHCPDECLINE) {handle_decline($dbh, $fromaddr, $dhcpreq);}
when ($_ == DHCPRELEASE) {handle_release($dbh, $fromaddr, $dhcpreq);}
when ($_ == DHCPINFORM) {handle_inform($dbh, $fromaddr, $dhcpreq);}#-> DHCPACK
}
if (defined($DEBUG)) {
$t1 = Benchmark->new;
$td = timediff($t1, $t0);
logger("Thread $tid: the code took: " . timestr($td));
}
}; # end of 'eval' blocks
if ($@) {
logger("Thread $tid: Caught error in main loop: $@");
}
}
$dbh->disconnect;
thread_exit(0);
}
sub thread_exit($) {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
my $tid = threads->tid(); # thread ID
logger("Thread ($tid): END code: " . $_[0]);
threads->exit($_[0]) if threads->can('exit');
exit($_[0]);
}
sub send_reply {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $fromaddr = $_[0];
#my $dhcpreq = $_[1];
#my $dhcpresp = $_[2];
my ($dhcpresppkt, $toaddr);
# add last!!!!
if (defined($_[1]->getOptionRaw(DHO_DHCP_AGENT_OPTIONS()))) {
$_[2]->addOptionRaw(DHO_DHCP_AGENT_OPTIONS(), $_[1]->getOptionRaw(DHO_DHCP_AGENT_OPTIONS()));
}
$dhcpresppkt = $_[2]->serialize();
#if (length($dhcpresppkt) < 548) {
# $dhcpresppkt .= "\0" x (548 - length($dhcpresppkt));
#}
if ($_[1]->giaddr() eq '0.0.0.0') {
# client local, not relayed
if ($_[2]->DHO_DHCP_MESSAGE_TYPE() == DHCPNAK) {# allways broadcast DHCPNAK
$toaddr = $ADDR_BCAST;
}
else {
if ($_[1]->ciaddr() eq '0.0.0.0') {
# ALL HERE NON RFC 2131 4.1 COMPLIANT!!!
# perl can not send to hw addr unicaset with ip 0.0.0.0, and we send broadcast
if ($_[1]->flags() == 0 || 1) {
# send unicast XXXXXXXXX - flags ignored!
# here we mast send unicast to hw addr, ip 0.0.0.0
my ($port, $addr) = unpack_sockaddr_in($_[0]);
my $ipaddr = inet_ntoa($addr);
if ($ipaddr eq '0.0.0.0') {
$toaddr = $ADDR_BCAST;
}
else {# giaddr and ciaddr is zero but we know ip addr from received packet
$toaddr = sockaddr_in($CLIENT_PORT, $addr);
}
}
else {
# only this comliant to rfc 2131 4.1
$toaddr = $ADDR_BCAST;
}
}
else {# client have IP addr, send unicast
$toaddr = sockaddr_in($CLIENT_PORT, $_[1]->ciaddrRaw());
}
}
}
else {# send to relay
$toaddr = sockaddr_in($SERVER_PORT, $_[1]->giaddrRaw());
}
send($SOCKET_RCV, $dhcpresppkt, 0, $toaddr) || logger("send error: $!");
if (defined($DEBUG)) {
my ($port, $addr) = unpack_sockaddr_in($toaddr);
my $ipaddr = inet_ntoa($addr);
logger("Sending response to = $ipaddr:$port length = " . length($dhcpresppkt));
if ($DEBUG > 1) {
logger($_[1]->toString());
print STDOUT Dumper($_[2]);
}
}
# send copy of packet to mirror, if specified
if (defined($ADDR_MIRROR)) {
send($SOCKET_RCV, $dhcpresppkt, 0, $ADDR_MIRROR) || logger("send mirr error: $!");
}
}
# Generate responce DHCP packet from request DHCP packet
sub GenDHCPRespPkt {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dhcpreq = $_[0];
my $dhcpresp = Net::DHCP::Packet->new(Op => BOOTREPLY(),
Htype => $_[0]->htype(),
Hlen => $_[0]->hlen(),
# Hops => $_[0]->hops(), # - not copyed in responce
Xid => $_[0]->xid(),
Secs => $_[0]->secs(),
Flags => $_[0]->flags(),
Ciaddr => $_[0]->ciaddr(),
#Yiaddr => '0.0.0.0',
Siaddr => $_[0]->siaddr(),
Giaddr => $_[0]->giaddr(),
Chaddr => $_[0]->chaddr(),
DHO_DHCP_MESSAGE_TYPE() => DHCPACK, # must be owerwritten
DHO_DHCP_SERVER_IDENTIFIER() => $DHCP_SERVER_ID
);
return ($dhcpresp);
}
sub BuffToHEX($) {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
my $buf = shift;
#$buf =~ s/([[:^print:]])/ sprintf q[\x%02X], ord $1 /eg; # printable text
$buf =~ s/(.)/sprintf("%02x", ord($1))/eg;
return ($buf);
}
# convert RelayAgent options to human readable
sub unpackRelayAgent(%) {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
my @SubOptions = @_;
my $buf;
for (my $i = 0; defined($SubOptions[$i]); $i += 2) {
$buf .= "($SubOptions[$i])=" . BuffToHEX($SubOptions[($i + 1)]) . ', ';
}
return ($buf);
}
# get relay agent options from dhcp packet
sub GetRelayAgentOptions($$$$$$) {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dhcpreq = $_[0];
#my $dhcp_opt82_vlan_id = $_[1];
#my $dhcp_opt82_unit_id = $_[2];
#my $dhcp_opt82_port_id = $_[3];
#my $dhcp_opt82_chasis_id = $_[4];
#my $dhcp_opt82_subscriber_id = $_[5];
my @RelayAgent;
# Set return values.
$_[1] = '';
$_[2] = '';
$_[3] = '';
$_[4] = '';
$_[5] = '';
# no options, return
return(0) if (defined($_[0]->getOptionRaw(DHO_DHCP_AGENT_OPTIONS())) == 0);
@RelayAgent = $_[0]->decodeRelayAgent($_[0]->getOptionRaw(DHO_DHCP_AGENT_OPTIONS()));
logger("RelayAgent: " . @RelayAgent);
for (my $i = 0; defined($RelayAgent[$i]); $i += 2) {
given ($RelayAgent[$i]){
when ($_ == 1) {
# Circuit ID
logger("RelayAgent Circuit ID: " . $RelayAgent[($i + 1)]);
next if (length($RelayAgent[($i + 1)]) < 4);
# first bytes must be: 00 04
#$_[1] = unpack('n', substr($RelayAgent[($i + 1)], -4, 2)); # may be 's'
$RelayAgent[($i + 1)] =~ /(\d+)(?=\ )/;
$_[1] = $1;
logger("RelayAgent VLan: " . $_[1]);
#$_[2] = unpack('C', substr($RelayAgent[($i + 1)], -2, 1));
$RelayAgent[($i + 1)] =~ /(\d+)(?=\/\d+:)/;
$_[2] = $1;
logger("RelayAgent Unit: " . $_[2]);
#$_[3] = unpack('C', substr($RelayAgent[($i + 1)], -1, 1));
$RelayAgent[($i + 1)] =~ /(\d+)(?=:)/;
$_[3] = $1;
logger("RelayAgent Port: " . $_[3]);
}
when ($_ == 2) {
# Remote ID
next if (length($RelayAgent[($i + 1)]) < 6);
# first bytes must be: 00 06 or 01 06 or 02 xx
# first digit - format/data type, second - len
$_[4] = FormatMAC(unpack("H*", substr($RelayAgent[($i + 1)], - 6, 6)));
logger("RelayAgent 4: " . $_[4]);
# 02 xx - contain vlan num, undone
}
when ($_ == 6) {
# Subscriber ID
$_[5] = $RelayAgent[($i + 1)];
logger("RelayAgent 5: " . $_[5]);
}
}
}
return (1);
}
# change mac addr format from "abcdefg" to "a:b:c:d:e:f:g"
sub FormatMAC {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
$_[0] =~ /([0-9a-f]{2})?([0-9a-f]{2})?([0-9a-f]{2})?([0-9a-f]{2})?([0-9a-f]{2})?([0-9a-f]{2})/i;
return (lc(join(':', $1, $2, $3, $4, $5, $6)));
}
# http://cpansearch.perl.org/src/SARENNER/Net-IPAddress-1.10/IPAddress.pm
#sub parseIPtoNumber {
#return (unpack("N", pack("C4", split(/\./, $_[0])))); # C4 = CCCC
#}
# mask to bits
# http://milanweb.net/uni/old/scripting.html
sub subnetBits {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
my $m = unpack("N", pack("C4", split(/\./, $_[0]))); # parseIPtoNumber
my $v = pack("L", $m);
my $bcnt = 0;
foreach (0 .. 31) {
if (vec($v, $_, 1) == 1) {
$bcnt++;
}
}
return ($bcnt);
}
# (121) Classless-Static-Route / (249) MSFT - Classless route
# by Rozhuk Ivan 2011
# RFC 3442
# based on:
# http://www.linuxconfig.net/index.php/linux-manual/network/203-transfer-of-static-routes-to-dhcp.html
# http://www.linux.by/wiki/index.php/FAQ_DHCP_routes
# Syntax: mk_classless_routes_bin_mask($net, $mask, $gw)
# example: mk_classless_routes_bin_mask('192.168.1.0', '255.255.255.0', '192.168.0.254')
sub mk_classless_routes_bin_mask {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $net = $_[0];
#my $mask = $_[1];
#my $gw = $_[2];
return (mk_classless_routes_bin_prefixlen($_[0], subnetBits($_[1]), $_[2]));
}
# Syntax: mk_classless_routes_bin_prefixlen($net, $prefixlen, $gw)
# example: mk_classless_routes_bin_prefixlen('192.168.1.0', 24, '192.168.0.254')
sub mk_classless_routes_bin_prefixlen {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $net = $_[0];
#my $prefixlen = $_[1];
#my $gw = $_[2];
my $str;
$str = pack('C', $_[1]);
if ($_[1] > 0) {
my ($s1, $s2, $s3, $s4) = split(/\./, $_[0]);
$str .= pack('C', $s1);
$str .= pack('C', $s2) if ($_[1] > 8);
$str .= pack('C', $s3) if ($_[1] > 16);
$str .= pack('C', $s4) if ($_[1] > 24);
}
$str .= pack('CCCC', split(/\./, $_[2]));
return ($str);
}
sub handle_discover {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $fromaddr = $_[1];
#my $dhcpreq = $_[2];
my ($dhcpresp);
$dhcpresp = GenDHCPRespPkt($_[2]);
$dhcpresp->{options}->{DHO_DHCP_MESSAGE_TYPE()} = pack('C', DHCPOFFER);
if (db_get_requested_data($_[0], $_[2], $dhcpresp, $_[1]) == 1) {
send_reply($_[1], $_[2], $dhcpresp);
db_lease_offered($_[0], $_[2], $dhcpresp);
}
else {# if AUTO_CONFIGURE (116) supported - send disable generate link local addr
if (defined($_[2]->getOptionRaw(DHO_AUTO_CONFIGURE))
&& $_[2]->getOptionValue(DHO_AUTO_CONFIGURE()) != 0) {
$dhcpresp->addOptionValue(DHO_AUTO_CONFIGURE(), 0);
send_reply($_[1], $_[2], $dhcpresp);
}
}
}
sub handle_request {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $fromaddr = $_[1];
#my $dhcpreq = $_[2];
my ($dhcpresp);
$dhcpresp = GenDHCPRespPkt($_[2]);
if (db_get_requested_data($_[0], $_[2], $dhcpresp, $_[1]) == 1) {
if ((defined($_[2]->getOptionRaw(DHO_DHCP_REQUESTED_ADDRESS())) &&
$_[2]->getOptionValue(DHO_DHCP_REQUESTED_ADDRESS()) ne $dhcpresp->yiaddr()) ||
(defined($_[2]->getOptionRaw(DHO_DHCP_REQUESTED_ADDRESS())) == 0
&& $_[2]->ciaddr() ne $dhcpresp->yiaddr())) {
# NAK if requested addr not equal IP addr in DB
$dhcpresp->ciaddr('0.0.0.0');
$dhcpresp->yiaddr('0.0.0.0');
$dhcpresp->{options}->{DHO_DHCP_MESSAGE_TYPE()} = pack('C', DHCPNAK);
db_lease_nak($_[0], $_[2]);
}
else {
$dhcpresp->{options}->{DHO_DHCP_MESSAGE_TYPE()} = pack('C', DHCPACK);
db_lease_success($_[0], $_[2]);
}
send_reply($_[1], $_[2], $dhcpresp);
}
}
sub handle_decline {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $fromaddr = $_[1];
#my $dhcpreq = $_[2];
db_lease_decline($_[0], $_[2]);
}
sub handle_release {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $fromaddr = $_[1];
#my $dhcpreq = $_[2];
db_lease_release($_[0], $_[2]);
}
sub handle_inform {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $fromaddr = $_[1];
#my $dhcpreq = $_[2];
my ($dhcpreqparams, $dhcpresp);
$dhcpresp = GenDHCPRespPkt($_[2]);
$dhcpresp->{options}->{DHO_DHCP_MESSAGE_TYPE()} = pack('C', DHCPACK);
if (db_get_requested_data($_[0], $_[2], $dhcpresp, $_[1]) == 0) {
$dhcpreqparams = $_[2]->getOptionValue(DHO_DHCP_PARAMETER_REQUEST_LIST());
static_data_to_reply($dhcpreqparams, $dhcpresp);
}
send_reply($_[1], $_[2], $dhcpresp);
}
sub static_data_to_reply {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dhcpreqparams = $_[0];
#my $dhcpresp = $_[1];
# do not add params if not requested
return() if (defined($_[0]) == 0);
if (index($_[0], DHO_ROUTER_DISCOVERY()) != - 1) {
$_[1]->addOptionValue(DHO_ROUTER_DISCOVERY(), 0);
}
if (index($_[0], DHO_NTP_SERVERS()) != - 1) {
$_[1]->addOptionValue(DHO_NTP_SERVERS(), '8.8.8.8 8.8.8.8');
}
if (index($_[0], DHO_NETBIOS_NODE_TYPE()) != - 1) {
$_[1]->addOptionValue(DHO_NETBIOS_NODE_TYPE(), 8); # H-Node
}
# Option 43 must be last for Windows XP proper work
# https://support.microsoft.com/en-us/kb/953761
if (index($_[0], DHO_VENDOR_ENCAPSULATED_OPTIONS()) != - 1) {
# 001 - NetBIOS over TCP/IP (NetBT): 00000002 (2) - disabled
# 002 - Release DHCP Lease on Shutdown: 00000001 (1) - enabled
# 255 - END
$_[1]->addOptionRaw(DHO_VENDOR_ENCAPSULATED_OPTIONS(), "\x01\x04\x00\x00\x00\x02\x02\x04\x00\x00\x00\x01\xff");
}
print STDOUT Dumper($_[1]) if ($DEBUG > 2);
}
sub db_get_requested_data {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $dhcpreq = $_[1];
#my $dhcpresp = $_[2];
#my $fromaddr = $_[3];
my ($port, $addr) = unpack_sockaddr_in($_[3]);
my $ipaddr = inet_ntoa($addr);
my (
$mac,
$sth,
$dhcpreqparams,
$result
);
my (
$dhcp_opt82_vlan_id,
$dhcp_opt82_unit_id,
$dhcp_opt82_port_id,
$dhcp_opt82_chasis_id,
$dhcp_opt82_subscriber_id
);
# change hw addr format
$mac = FormatMAC(substr($_[1]->chaddr(), 0, (2 * $_[1]->hlen())));
$dhcpreqparams = $_[1]->getOptionValue(DHO_DHCP_PARAMETER_REQUEST_LIST());
$sth = $_[0]->prepare("SELECT * FROM `clients`, `subnets` WHERE `clients`.`mac` = '$mac' AND `clients`.`subnet_id` = `subnets`.`subnet_id` AND `subnets`.`gateway` = '$ipaddr' LIMIT 1;");
if ($DEBUG > 2) {
logger($_[1]->toString());
print STDOUT Dumper($_[2]);
}
if ($DEBUG > 1) {
logger("Got a packet src = $ipaddr:$port");
logger("SQL: SELECT * FROM `clients`, `subnets` WHERE `clients`.`mac` = '$mac' AND `clients`.`subnet_id` = `subnets`.`subnet_id` AND `subnets`.`gateway` = '$ipaddr' LIMIT 1;");
}
$sth->execute();
if ($sth->rows()) {
$result = $sth->fetchrow_hashref();
$_[2]->yiaddr($result->{ip});
db_data_to_reply($result, $dhcpreqparams, $_[2]);
db_get_routing($_[0], $dhcpreqparams, $result->{subnet_id}, $_[2]);
static_data_to_reply($dhcpreqparams, $_[2]);
$sth->finish();
return (1);
}
if (GetRelayAgentOptions($_[1], $dhcp_opt82_vlan_id, $dhcp_opt82_unit_id, $dhcp_opt82_port_id,
$dhcp_opt82_chasis_id, $dhcp_opt82_subscriber_id)) {
# try work as traditional DHCP: find scope by opt82 info, then give some free addr
if ($dhcp_opt82_chasis_id ne '') {
$sth = $_[0]->prepare(
"SELECT
*
FROM
`subnets`,
`ips`
WHERE
`subnets`.`vlan_id` = '$dhcp_opt82_vlan_id'
AND
`subnets`.`type` = 'guest'
AND
`ips`.`lease_time` = ''
LIMIT 1;
"
);
if ($DEBUG > 1) {
logger("SELECT * FROM `subnets`, `ips` WHERE `subnets`.`vlan_id` = '$dhcp_opt82_vlan_id' AND `subnets`.`type` = 'guest' AND `ips`.`lease_time` = '' LIMIT 1;");
}
$sth->execute();
if ($sth->rows()) {
$result = $sth->fetchrow_hashref();
db_data_to_reply($result, $dhcpreqparams, $_[2]);
db_get_routing($_[0], $dhcpreqparams, $result->{subnet_id}, $_[2]);
static_data_to_reply($dhcpreqparams, $_[2]);
#######################$_[2]->yiaddr($result->{ip});
$sth->finish();
return (1);
}
# subnet_id + dhcp client id = client lease
# From: dhcp_guest_leases
}
}
$sth->finish();
return (0);
}
sub db_data_to_reply {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $result = $_[0];
#my $dhcpreqparams = $_[1];
#my $dhcpresp = $_[2];
# http://www.tcpipguide.com/free/t_DHCPLeaseLifeCycleOverviewAllocationReallocationRe.htm
# DHCPDiscover / DHCPRequest / DHCPOffer
#$_[0]->{dhcp_lease_time} = 180;
if (defined($_[0]->{dhcp_lease_time})) {
$_[2]->addOptionValue(DHO_DHCP_LEASE_TIME(), $_[0]->{dhcp_lease_time});
# function (typically 50%) of the full configured duration (or lease time) for a client's lease
if (defined($_[0]->{dhcp_renewal})) {
$_[2]->addOptionValue(DHO_DHCP_RENEWAL_TIME(), $_[0]->{dhcp_renewal});
#} else {
# $_[2]->addOptionValue(DHO_DHCP_RENEWAL_TIME(), ($_[0]->{dhcp_lease_time}/2));
}
# function (typically 87.5%) of the full configured duration (or lease time) for a client's lease
if (defined($_[0]->{dhcp_rebind_time})) {
$_[2]->addOptionValue(DHO_DHCP_REBINDING_TIME(), $_[0]->{dhcp_rebind_time});
#} else {
# $_[2]->addOptionValue(DHO_DHCP_REBINDING_TIME(), ($_[0]->{dhcp_lease_time}*7/8));
}
}
# do not add params if not requested
return() if (defined($_[1]) == 0);
if (index($_[1], DHO_SUBNET_MASK()) != - 1 && defined($_[0]->{mask})) {
$_[2]->addOptionValue(DHO_SUBNET_MASK(), $_[0]->{mask});
}
if (index($_[1], DHO_ROUTERS()) != - 1 && defined($_[0]->{gateway})) {
$_[2]->addOptionValue(DHO_ROUTERS(), $_[0]->{gateway});
}
if (index($_[1], DHO_DOMAIN_NAME_SERVERS()) != - 1 && defined($_[0]->{dns1})) {
$_[2]->addOptionValue(DHO_DOMAIN_NAME_SERVERS(), "$_[0]->{dns1} $_[0]->{dns2}");
}
if (index($_[1], DHO_HOST_NAME()) != - 1 && defined($_[0]->{hostname})) {
$_[2]->addOptionValue(DHO_HOST_NAME(), $_[0]->{hostname});
}
if (index($_[1], DHO_DOMAIN_NAME()) != - 1 && defined($_[0]->{domain})) {
$_[2]->addOptionValue(DHO_DOMAIN_NAME(), $_[0]->{domain});
}
}
sub db_get_routing {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $dhcpreqparams = $_[1];
#my $subnet_id = $_[2];
#my $dhcpresp = $_[3];
my (
$sth,
$opt33Enbled,
$optClasslessRoutesCode
);
# do not add routes if not requested
return() if (defined($_[1]) == 0);
$opt33Enbled = index($_[1], DHO_STATIC_ROUTES());
if ($opt33Enbled == - 1) {
$opt33Enbled = undef;
}
$optClasslessRoutesCode = index($_[1], 121);
if ($optClasslessRoutesCode == - 1) {
$optClasslessRoutesCode = index($_[1], 249); # MSFT
if ($optClasslessRoutesCode == - 1) {
$optClasslessRoutesCode = undef;
}
else {
$opt33Enbled = undef;
$optClasslessRoutesCode = 249;
}
}
else {
$opt33Enbled = undef;
$optClasslessRoutesCode = 121;
}
if (defined($opt33Enbled) == 0 && defined($optClasslessRoutesCode) == 0) {
# nothink to do, return
return ();
}
$sth = $_[0]->prepare("SELECT `destination`, `mask` `gateway` FROM `subnets_routes` WHERE `subnet_id` = '$_[2]' LIMIT 30;");
logger("SQL: SELECT `destination`, `mask` `gateway` FROM `subnets_routes` WHERE `subnet_id` = '$_[2]' LIMIT 30;") if ($DEBUG > 1);
print STDOUT Dumper($_[3]) if ($DEBUG > 2);
$sth->execute();
if ($sth->rows()) {
my $ref;
my $row;
my $opt33_data = undef; # routes to single hosts
my $opt_classless_routes_data = undef; # routes to nets
$ref = $sth->fetchall_arrayref;
foreach $row (@{$ref}) {
if (defined($opt33Enbled) && @$row[1] eq '255.255.255.255') {
# pack dst
$opt33_data .= pack('CCCC', split(/\./, @$row[0]));
# pack gw
$opt33_data .= pack('CCCC', split(/\./, @$row[2]));
}
if (defined($optClasslessRoutesCode)) {
$opt_classless_routes_data .= mk_classless_routes_bin_mask(@$row[0], @$row[1], @$row[2]);
}
}
if (defined($opt33_data)) {# add option
$_[3]->addOptionRaw(DHO_STATIC_ROUTES(), $opt33_data);
}
if (defined($opt_classless_routes_data)) {# add option
$_[3]->addOptionRaw($optClasslessRoutesCode, $opt_classless_routes_data);
}
}
$sth->finish();
}
sub db_lease_offered {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $dhcpreq = $_[1];
#my $dhcpresp = $_[2];
my ($mac, $sth);
# change hw addr format
$mac = FormatMAC(substr($_[1]->chaddr(), 0, (2 * $_[1]->hlen())));
$sth = $_[0]->prepare("UPDATE `ips` SET `mac` = '$mac', `lease_time` = UNIX_TIMESTAMP()+3600 WHERE `ip` = '".$_[2]->yiaddr()."';");
logger("SQL: UPDATE `ips` SET `mac` = '$mac', `lease_time` = UNIX_TIMESTAMP()+3600 WHERE `ip` = '".$_[2]->yiaddr()."';") if ($DEBUG > 1);
print STDOUT Dumper($_[3]) if ($DEBUG > 2);
$sth->execute();
$sth->finish();
return (0);
}
sub db_lease_nak {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $dhcpreq = $_[1];
my ($mac, $sth);
# change hw addr format
$mac = FormatMAC(substr($_[1]->chaddr(), 0, (2 * $_[1]->hlen())));
$sth = $_[0]->prepare("");
logger("SQL: lease nak") if ($DEBUG > 1);
print STDOUT Dumper($_[1]) if ($DEBUG > 2);
$sth->execute();
$sth->finish();
return (0);
}
sub db_lease_decline {
logger("Function: " . (caller(0))[3]) if ($DEBUG > 1);
#my $dbh = $_[0];
#my $dhcpreq = $_[1];
my ($mac, $sth);
my (
$dhcp_opt82_vlan_id,
$dhcp_opt82_unit_id,
$dhcp_opt82_port_id,
$dhcp_opt82_chasis_id,
$dhcp_opt82_subscriber_id
);
my (
$client_ip,
$gateway_ip,
$client_ident,
$requested_ip,
$hostname,
$dhcp_vendor_class,
$dhcp_user_class
);