Debian Codegraph @

perllib/qosient/radhcp.pm

raw
1 package qosient::radhcp;
2
3 # Gargoyle Client Software. Tools to read, analyze and manage Argus data.
4 # Copyright (c) 2017-2018 QoSient, LLC
5 # All Rights Reserved
6 #
7 # THE ACCOMPANYING PROGRAM IS PROPRIETARY SOFTWARE OF QoSIENT, LLC,
8 # AND CANNOT BE USED, DISTRIBUTED, COPIED OR MODIFIED WITHOUT
9 # EXPRESS PERMISSION OF QoSIENT, LLC.
10 #
11 # QOSIENT, LLC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
12 # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13 # AND FITNESS, IN NO EVENT SHALL QOSIENT, LLC BE LIABLE FOR ANY
14 # SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
16 # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
17 # ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
18 # THIS SOFTWARE.
19 #
20 # This library contains routines for accessing the DHCP SQL tables.
21
22 use POSIX qw(strftime floor ceil);
23 use Time::Local;
24 use qosient::util;
25 use DBI qw(:sql_types);
26 use Carp;
27 use strict;
28 use warnings;
29 use Try::Tiny;
30 use IO::Socket::INET;
31 use JSON;
32
33 use strict;
34 use Exporter;
35 use vars qw($VERSION @ISA @EXPORT);
36 $VERSION = "1.00";
37 @ISA = qw(Exporter);
38 @EXPORT = qw(dhcp_gethostbyaddr
39 dhcp_gethostbyaddr_from_table
40 dhcp_gethostbyname
41 dhcp_gethostbyname_from_table
42 dhcp_getleasebyaddr_from_table
43 dhcp_getleasebyaddr
44 dhcp_getleasebyname_from_table
45 dhcp_getleasebyname
46 dhcp_insert_fqdn
47 dhcp_opendb
48 dhcp_closedb
49 dhcp_opensocket
50 dhcp_closesocket);
51
52 my $debug = 0;
53 my $time = q{}; # "yesterday" according to parsetime()
54 my @time;
55 my $dbase = q{dhcpFlows};
56 my $dbase_matrix = q{dhcpMatrix};
57 my $table_summary = q{dhcp_summary_%Y_%m_%d};
58 my $table_detail = q{dhcp_detail_%Y_%m_%d};
59 my $table_matrix = q{matrix_%Y_%m_%d};
60 my $table_ethers = q{dhcp_ethers_%Y_%m_%d};
61 my $dsn;
62 my $dbuser = 'root';
63 my $password = q{};
64 my %attr = ( PrintError => $debug, RaiseError => 0 );
65 my $errcount = 0;
66
67 # regular expressions to ensure user-provided address have only
68 # valid characters. Since we are using these in SQL expressions
69 # where positional parameters cannot be explicitly bound (no question
70 # mark substitution) any values added to this hash that allow parens
71 # or semicolons must be checked very carefully. So far, nothing
72 # of that sort here.
73 my %addr_valid_characters = (
74 '4' => q{^[0-9./]+$}, # IPv4
75 '6' => q{^[0-9a-fA-F:/]+$}, # IPv6
76 'h' => q{^[0-9a-fA-F:]+$}, # hardware address (oui48)
77 'n' => q{^[0-9a-zA-Z_._\-]+}, # name
78 );
79
80 my %addr_search_field = (
81 '4' => q{clientaddr},
82 '6' => q{clientaddr},
83 'h' => q{clientmac},
84 'n' => q{requested_hostname}, # although q{hostname} should
85 # also be checked. Maybe
86 # qw(hostname requested_hostname)
87 );
88
89 my %addr_socket_search_field = (
90 '4' => q{addr},
91 '6' => undef,
92 'h' => q{chaddr},
93 'n' => undef,
94 );
95
96 my $canonicalize_oui48 = sub {
97 my ($str) = @_;
98 my @bytes = split(/:/, $str);
99
100 if (scalar(@bytes) != 6) {
101 return;
102 }
103
104 my @num = map { hex($_) } @bytes;
105 return sprintf('%02x:%02x:%02x:%02x:%02x:%02x', @num);
106 };
107
108 my %addr_canon_func = (
109 'h' => $canonicalize_oui48,
110 );
111
112 sub dhcp_opensocket {
113 my $socket = IO::Socket::INET->new(
114 PeerHost => 'localhost',
115 PeerPort => '9999',
116 Proto => 'tcp',
117 Timeout => 1,
118 );
119
120 if ( !$socket ) {
121 return;
122 }
123
124 $socket->timeout(5);
125
126 my $start = "START: \n";
127 my $bytes = $socket->send($start);
128
129 if ( $bytes != length($start) ) {
130 carp "could not send start command";
131 $socket->close();
132 return;
133 }
134
135 return $socket;
136 }
137
138 sub dhcp_closesocket {
139 my ($socket) = @_;
140
141 my $done = "DONE: \n";
142 my $bytes = $socket->send($done);
143
144 if ( $bytes != length($done) ) {
145 carp "could not send done command";
146 }
147
148 $socket->close();
149 }
150
151 # The control channel code in the clients is a little broken when
152 # the callback that generates the response needs to report an error.
153 # The data from the control channel may end with "FAIL\nOK\n".
154 # _response_complete can always check for a string ending in "OK\n"
155 # to figure out if the response is finished, but will also have to
156 # check for a preceding "FAIL\n" to know if the response is valid.
157 my $_response_complete = sub {
158 my ($str) = @_;
159 my $last3 = substr $str, -3; # OK
160
161 if ( not ( $last3 eq "OK\n" ) ) {
162 return;
163 }
164
165 return 1;
166 };
167
168 # $str must be a completed response (ends in OK)
169 my $_response_success = sub {
170 my ($str) = @_;
171 my $prev5 = substr $str, -8, 5; # FAIL (maybe);
172
173 if ( $prev5 eq "FAIL\n" ) {
174 return;
175 }
176
177 return 1;
178 };
179
180 my $MAX_SOCKET_READ = 4096;
181 my $MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
182
183 my $_read_response = sub {
184 my ($socket) = @_;
185 my $resp = q{};
186 my $tmpstr;
187 my $tmpbytes;
188 my $bytes = 0;
189
190 do {
191 $tmpbytes = $socket->sysread( $tmpstr, $MAX_SOCKET_READ );
192 if ( $tmpbytes && $tmpstr && $tmpbytes > 0 ) {
193 $resp .= $tmpstr;
194 $bytes += $tmpbytes;
195 }
196 } while ( defined($tmpbytes)
197 && !$_response_complete->($resp)
198 && $bytes < $MAX_RESPONSE_BYTES );
199
200 if ( $bytes == 0 ) {
201 return;
202 }
203
204 if ( !$_response_success->($resp) ) {
205 return;
206 }
207
208 $resp = substr $resp, 0, -3; # remove "OK\n"
209 return $resp;
210 };
211
212 my $dhcp_getleasebyaddr_from_socket = sub {
213 my $socket = shift(@_);
214 my $when = shift(@_);
215 my $summary = shift(@_);
216 my $addrtype = shift(@_);
217 my $paramcount = @_;
218 my @results;
219
220 if ( $paramcount < 1 ) {
221 return;
222 }
223
224 chomp $when;
225 my $json = JSON->new->allow_nonref;
226
227 # To make these queries match the behavior of the database queries,
228 # search for an entire day if nothing but the date was supplied.
229 if ( $when =~ /^[1-9][0-9][0-9][0-9]\/[0-9][0-9]\/[0-9][0-9]$/ ) {
230 $when .= '+1d';
231 }
232
233 my $addrfield = $addr_socket_search_field{$addrtype};
234 if ( !$addrfield ) {
235 return;
236 }
237
238 foreach my $addr (@_) {
239 my $query = "SEARCH: when=$when,$addrfield=$addr";
240
241 if ( defined($summary) && $summary != 0 ) {
242 $query .= ',pullup';
243 }
244 $query .= "\n";
245
246 my $bytes = $socket->send($query);
247
248 if ( $bytes != length($query) ) {
249 carp "could not send entire SEARCH string?";
250 return;
251 }
252
253 # _read_search_response needs to strip "OK" from the end
254 # and return undef on any error
255 my $resp = $_read_response->($socket);
256 if ( !$resp ) {
257 carp "did not receive response to SEARCH";
258 return;
259 }
260
261 my $resp_href = $json->decode($resp);
262 if ( !$resp_href ) {
263 carp "received invalid JSON in response to SEARCH";
264 return;
265 }
266
267 foreach my $idx ( keys %$resp_href ) {
268
269 # assemble an array of hash references, assuming that JSON
270 # builds nested hashes
271 push @results, $resp_href->{$idx};
272 }
273 }
274
275 if ( !@results ) {
276 return;
277 }
278
279 return \@results;
280 };
281
282 sub dhcp_opendb {
283 @time = parsetime(q{});
284 $dsn = "DBI:mysql:$dbase";
285 my $dbh = DBI->connect( $dsn, $dbuser, $password, \%attr );
286 return $dbh; # undefined on error
287 }
288
289 sub dhcp_closedb {
290 my ($dbh) = @_;
291
292 $dbh->disconnect();
293 return 0;
294 }
295
296 # Build an array of hash references from SQL query results.
297 # Return a reference to the array.
298 my $_result_list = sub {
299 my $sth = shift(@_);
300 my @arr;
301 my $done = 0;
302 while ( $done == 0 ) {
303 my $href = $sth->fetchrow_hashref;
304 if ( !defined $href ) {
305 $done = 1;
306 next;
307 }
308 push @arr, $href;
309 }
310 return \@arr;
311 };
312
313 # dhcp_gethostbyaddr_from_table
314 # args: <database-handle> <table> <addr> [<addr> [<addr> ...] ...]
315 # returns reference to array of hash references
316 sub dhcp_gethostbyaddr_from_table {
317 my $dbh = shift(@_);
318 my $table = shift(@_);
319 my $addrs = join( q{','}, @_ );
320
321 if ( !( $table =~ /[0-9a-zA-Z_]+/ ) ) {
322 my $sub_name = ( caller(0) )[3];
323 carp "$sub_name: table name contains invalid characters";
324 return;
325 }
326
327 for my $tmpaddr (@_) {
328 if ( length($tmpaddr) > 0 ) {
329 if ( !( $tmpaddr =~ /$addr_valid_characters{'4'}/ ) ) {
330 my $sub_name = ( caller(0) )[3];
331 carp "$sub_name: address contains invalid characters";
332 return;
333 }
334 }
335 }
336
337 my $query =
338 "SELECT clientaddr, hostname, requested_hostname, domainname FROM $table WHERE";
339
340 if ( length($addrs) > 0 ) {
341 $query .= " clientaddr IN ('$addrs') AND"
342 }
343
344 $query .= ' ( requested_hostname <> "" OR hostname <> "" )'
345 . ' GROUP BY clientaddr, hostname, requested_hostname, domainname';
346 my $sth = $dbh->prepare($query);
347
348 if ( !defined $sth ) {
349 my $sub_name = ( caller(0) )[3];
350 carp "$sub_name: unable to prepare SQL statement";
351 return;
352 }
353
354 my $res = $sth->execute;
355
356 if ( !defined $res ) {
357 return;
358 }
359
360 my $aryref = $_result_list->($sth);
361
362 $sth->finish;
363 return $aryref;
364 }
365
366 # args: <database-handle> <when> <addr> [<addr> [<addr> ...] ...]
367 # returns reference to array of hash references
368 sub dhcp_gethostbyaddr {
369 my $dbh = shift(@_);
370 my $when = shift(@_);
371 my $paramcount = @_;
372
373 if ( $paramcount < 1 ) {
374
375 # no addresses or insufficient args
376 return;
377 }
378
379 my @whenary = parsetime($when);
380 my $table = strftime $table_summary, @whenary;
381
382 return dhcp_gethostbyaddr_from_table( $dbh, "$dbase.$table", @_ );
383 }
384
385 # args: <database-handle> <table> [<name> [<name> [<name> ...] ...]]
386 # returns reference to array of hash references.
387 # If no name specified, returns all names in table. Leases without a hostname
388 # are ignored.
389 sub dhcp_gethostbyname_from_table {
390 my $dbh = shift(@_);
391 my $table = shift(@_);
392 my $names = join( q{','}, @_ );
393
394 if ( !( $table =~ /[0-9a-zA-Z_]+/ ) ) {
395 my $sub_name = ( caller(0) )[3];
396 carp "$sub_name: table name contains invalid characters";
397 return;
398 }
399
400 for my $tmpname (@_) {
401 if ( length($tmpname) > 0 ) {
402 if ( !( $tmpname =~ /$addr_valid_characters{'n'}/ ) ) {
403 my $sub_name = ( caller(0) )[3];
404 carp "$sub_name: hostname contains invalid characters";
405 return;
406 }
407 }
408 }
409
410 my $query =
411 'SELECT clientaddr, hostname, requested_hostname, domainname '
412 . "FROM $table";
413
414 if ( length($names) > 0 ) {
415 $query .= " WHERE requested_hostname IN ('$names')"
416 . " OR hostname IN ('$names')";
417 }
418 else {
419 $query .= ' WHERE requested_hostname <> "" OR hostname <> ""';
420 }
421 $query .= ' GROUP BY clientaddr, hostname, requested_hostname, domainname';
422 my $sth = $dbh->prepare($query);
423
424 if ( !defined $sth ) {
425 my $sub_name = ( caller(0) )[3];
426 carp "$sub_name: unable to prepare SQL statement";
427 return;
428 }
429
430 my $res = $sth->execute;
431
432 if ( !defined $res ) {
433 return;
434 }
435
436 my $aryref = $_result_list->($sth);
437
438 $sth->finish;
439 return $aryref;
440 }
441
442 # args: <database-handle> <when> <name> [<name> [<name> ...] ...]
443 # returns reference to array of hash references
444 sub dhcp_gethostbyname {
445 my $dbh = shift(@_);
446 my $when = shift(@_);
447 my $paramcount = @_;
448
449 my @whenary = parsetime($when);
450 my $table = strftime $table_summary, @whenary;
451
452 return dhcp_gethostbyname_from_table( $dbh, "$dbase.$table", @_ );
453 }
454
455 # args: <database-handle> <table> <addr-type> <addr> [<addr> ...]
456 # <addr-type> := "4"|"6"|"h"
457 # ipv4, ipv6 or hardware (ethernet oui48 for most cases)
458 # returns reference to array of hash references. Each hash contain
459 # the entire row from the specified table (detail or summary).
460 my $_dhcp_getlease_from_table = sub {
461 my $dbh = shift(@_);
462 my $table = shift(@_);
463 my $addrtype = shift(@_);
464 my $addrs = join( q{','}, @_ );
465
466 if ( !defined $addrtype ) {
467 my $sub_name = ( caller(0) )[3];
468 carp "$sub_name: need an address type";
469 return;
470 }
471
472 if ( !( $addrtype =~ /[46hn]/ ) ) {
473 my $sub_name = ( caller(0) )[3];
474 carp qq{$sub_name: address type must be one of "4", "6" or "h".};
475 return;
476 }
477
478 if ( !( $table =~ /[0-9a-zA-Z_]+/ ) ) {
479 my $sub_name = ( caller(0) )[3];
480 carp "$sub_name: table name contains invalid characters";
481 return;
482 }
483
484 my $pattern = $addr_valid_characters{$addrtype};
485
486 for my $tmpaddr (@_) {
487 if ( length($tmpaddr) > 0 ) {
488 if ( !( $tmpaddr =~ /$pattern/ ) ) {
489 my $sub_name = ( caller(0) )[3];
490 carp "$sub_name: address contains invalid characters";
491 return;
492 }
493 }
494 }
495
496 my $addrfield = $addr_search_field{$addrtype};
497
498 # SELECT * FROM $table WHERE $addrfield IN (...)
499 # ORDER BY clientmac, clientaddr, stime ;
500 my $query = qq{SELECT * FROM $table};
501
502 if ( length($addrs) > 0 ) {
503 $query .= qq{ WHERE $addrfield IN ('$addrs')};
504 }
505
506 $query .= q{ ORDER BY clientmac, clientaddr, stime};
507 my $sth = $dbh->prepare($query);
508
509 if ( !defined $sth ) {
510 my $sub_name = ( caller(0) )[3];
511 carp "$sub_name: unable to prepare SQL statement";
512 return;
513 }
514
515 my $res = $sth->execute;
516
517 if ( !defined $res ) {
518 return;
519 }
520
521 my $aryref = $_result_list->($sth);
522
523 $sth->finish;
524 return $aryref;
525 };
526
527 sub dhcp_getleasebyaddr_from_table {
528 return $_dhcp_getlease_from_table->(@_);
529 }
530
531 # args: <database-handle> <when> <addr-type> <addr> [<addr> [<addr> ...] ...]
532 # returns reference to array of hash references
533 sub dhcp_getleasebyaddr {
534 my $dbh = shift(@_);
535 my $when = shift(@_);
536 my $addrtype = shift(@_);
537 my $paramcount = @_;
538 my $func = $addr_canon_func{$addrtype};
539 my @addrs;
540
541 if ( $func ) {
542 # canonicalize the address strings
543 @addrs = map { $func->($_) } @_;
544 } else {
545 @addrs = @_;
546 }
547
548 my @whenary = parsetime($when);
549 my $whensec = timelocal(@whenary);
550 my $now = timelocal( localtime() );
551 my $seconds_in_day = 86400;
552 if ( $whensec > $now || ( $now - $whensec ) <= $seconds_in_day ) {
553 my $socket = dhcp_opensocket;
554 if ( defined($socket) ) {
555 my $rv = $dhcp_getleasebyaddr_from_socket->( $socket, $when, 1, $addrtype, @addrs );
556
557 dhcp_closesocket($socket);
558 return $rv;
559 }
560 }
561
562 my $table = strftime $table_summary, @whenary;
563 return $_dhcp_getlease_from_table->( $dbh, "$dbase.$table", $addrtype, @addrs );
564 }
565
566 # args: <database-handle> <table> <name> [<name> [<name> ...] ...]
567 # returns reference to array of hash references. Each hash contain
568 # the entire row from the specified table (detail or summary).
569 sub dhcp_getleasebyname_from_table {
570 my ( $dbh, $table ) = @_;
571 shift(@_);
572 shift(@_);
573 return $_dhcp_getlease_from_table->( $dbh, $table, 'n', @_ );
574 }
575
576 # args: <database-handle> <when> <name> [<name> [<name> ...] ...]
577 # returns reference to array of hash references
578 sub dhcp_getleasebyname {
579 my $dbh = shift(@_);
580 my $when = shift(@_);
581 my $paramcount = @_;
582
583 my @whenary = parsetime($when);
584 my $table = strftime $table_summary, @whenary;
585
586 return $_dhcp_getlease_from_table->( $dbh, "$dbase.$table", 'n', @_ );
587 }
588
589 sub dhcp_lease_expand_one {
590 my ( $dbh, $href, $now ) = @_;
591
592 if ( !defined $href ) {
593 return;
594 }
595
596 # take a lease summarization as generated by dhcp_getleasebyaddr*
597 # or dhcp_getleasebyname* and use the detail SQL tables to find
598 # the leases that contributed to the summary.
599
600 # summary lease start and last times
601 my $seconds_in_day = 86400;
602 my $date_range_stime = POSIX::floor( $href->{'stime'} );
603 my $date_range_ltime = POSIX::ceil( $href->{'ltime'} );
604
605 if ( $date_range_ltime > ( $now + $seconds_in_day ) ) {
606 # DHCP Precognition is not a supported feature
607 $date_range_ltime = $now + $seconds_in_day;
608 }
609
610 if ( $date_range_stime > $date_range_ltime ) {
611 # something went wrong
612 return;
613 }
614
615 my $duration = $date_range_ltime - $date_range_stime;
616 my $seconds = $date_range_stime;
617 my $results_aref;
618
619 # Step through the range of lease times one 24-hour period at a
620 # time and format the year-month-day table name for each.
621 # Search those tables for matching clients and times.
622 while ( $duration > 0 ) {
623 my $table = strftime $table_detail, localtime($seconds);
624 my $query = qq{SELECT * FROM $table WHERE }
625 . q{(clientmac=? AND clientaddr=? AND stime>=? AND ltime<?)};
626 my $sth = $dbh->prepare($query);
627
628 if ( !defined $sth ) {
629 print STDERR "Unable to prepare $query";
630 return;
631 }
632
633 $sth->bind_param( 1, $href->{'clientmac'} );
634 $sth->bind_param( 2, $href->{'clientaddr'} );
635 $sth->bind_param( 3, $href->{'stime'}, { TYPE => SQL_DOUBLE } );
636 $sth->bind_param( 4, $href->{'ltime'}, { TYPE => SQL_DOUBLE } );
637
638 my $res = $sth->execute;
639
640 if ( !defined $res ) {
641 goto ADVANCE;
642 }
643
644 my $tmp = $_result_list->($sth);
645
646 # keep appending to the array reference returned from the
647 # first call to execute()
648 if ( defined $results_aref ) {
649 push $results_aref, @$tmp;
650 }
651 else {
652 $results_aref = $tmp;
653 }
654
655 ADVANCE:
656 $duration -= $seconds_in_day;
657 $seconds += $seconds_in_day;
658 $sth->finish;
659 }
660
661 return $results_aref;
662 }
663
664 # Return an array (reference) of array references. Each array
665 # reference points to an array of hash references. Each hash
666 # reference points to a lease record.
667 #
668 # for example, two leases might expand to a structure like this:
669 # \[ \[ \% \% ] \[ \% ] ]
670 #
671 # where the outer array contains two inner arrays and where each
672 # inner array contains references to hashes with the detailed lease
673 # data. If there are no search results, return a reference to an
674 # empty list.
675
676 sub dhcp_lease_expand {
677 my ( $dbh, $aref ) = @_;
678 my @reslist = ();
679 my @time = localtime();
680 my $now = timegm(@time);
681
682 for my $href (@$aref) {
683 my $aref = dhcp_lease_expand_one( $dbh, $href, $now );
684
685 if ( !defined $aref ) {
686 next;
687 }
688
689 push @reslist, $aref;
690 }
691 return \@reslist;
692 }
693
694 # dhcp_insert_fqdn takes an array reference as returned by dhcp_gethostby* and
695 # adds an fqdn entry to each hash if enough information is present.
696 sub dhcp_insert_fqdn {
697 my ($aref) = @_;
698
699 for my $href (@$aref) {
700 my $have_domainname = 0;
701 my $domainname = $href->{'domainname'};
702 my $hostname;
703
704 if ( defined $href->{'hostname'} && length( $href->{'hostname'} ) > 0 )
705 {
706 $hostname = $href->{'hostname'};
707 }
708 else {
709 if ( defined $href->{'requested_hostname'}
710 && length( $href->{'requested_hostname'} ) > 0 )
711 {
712 $hostname = $href->{'requested_hostname'};
713 }
714 }
715
716 if ( !defined $hostname ) {
717 $href->{'fqdn'} = "";
718 next;
719 }
720
721 # If the hostname (requested or otherwise) has a period in it,
722 # most likely it is something like .local or .home and was put
723 # there by a residential router, cablemodem, etc. In this case
724 # assume that there is no effect on DNS and that the hostname we
725 # already have is as "fully qualified" as it is going to get.
726 if ( $hostname =~ /\./ ) {
727 $href->{'fqdn'} = $hostname;
728 next;
729 }
730
731 if ( defined $href->{'domainname'}
732 && length( $href->{'domainname'} ) > 0 )
733 {
734 $hostname .= ".$domainname";
735 }
736
737 $href->{'fqdn'} = $hostname;
738 }
739 return;
740 }
741
742 1;