-
Notifications
You must be signed in to change notification settings - Fork 8
/
netdb.cgi.pl
executable file
·5012 lines (3909 loc) · 151 KB
/
netdb.cgi.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/bin/perl -wT
#################################################################################
# Network Tracking Database CGI Interface
# Author: Jonathan Yantis <[email protected]>
# Copyright (C) 2014 Jonathan Yantis
#########################################################################
#
# netdb.pl takes input from the web and searches the NetDB database. The
# script determines if the input is a mac address, hostname or an IP address.
# By selecting different options, searches on vendor codes, switch reports and
# vlan reports can be created.
#
# Dependencies:
# - Make sure to install under user authenticated location on your webserver,
# relies on usernames for accounting.
# - Most options are configured from the netdb-cgi.conf files installed in /etc
#
# Installing:
# - Install netdb-cgi.conf in /etc and configure the options for your site.
# - Make sure the netdb.conf and netdb-cgi.conf files are readable by www-data
# - Create netdbReport.csv in /var/www/ and make it owned by the webserver user (www-data)
# - Copy or link the depends directory from netdb/extra/depends/ to the root location on
# your web server (eg /var/www/depends).
# - Copy the netdb.cgi.pl file to your cgi-bin directory and rename to netdb.pl
# - Use the netdb-template.html file as the basis for your own website, relies on
# <!-- PAGECONTENT --> and netdb.css primarily
# - Optionally install Jose Pedro Oliveira's wakeonlan script to /usr/bin
# - Edit /opt/netdb/extra/about.html with your own about page info
#
# Debugging/Troubleshooting:
# Script should output all errors to the webpage. Call script with
# http://site/netdb.pl?debug=1 to enable extensive debugging.
#
# Version History:
# v1.0 04/26/2008 - Script ported from hal to the tools site
# v1.1 06/30/2008 - Added extended reporting on super tables (views)
# v1.2 07/08/2008 - Added CSV reporting and transaction logs
# v1.3 08/08/2008 - Added AJAX Table Support
# v1.4 11/06/2008 - Added WoL support
# v2.0 11/16/2008 - Rewrote interface using JQuery UI Tabs. Added
# inline camtrace, inline WoL, and inline Excel
# reports. Reworked look and feel and expanded
# the help documentation.
# v2.1 12/30/2008 - Added extended switchport information to match NetDB's
# v1.3 library. Cleaned up some output issues.
# v2.2 02/04/2009 - Added getVlanSwitchStatus reports to website to get
# all switchports configured with a vlan
# v2.3 02/09/2009 - Fixed loading image to remove absolute positioning and
# alternate template issues. Changed CSS for tables.
# v2.4 02/11/2009 - Added description to switch reports
# v2.5 02/27/2009 - Cleaned up error reporting and error handling, new css code
# v2.6 03/04/2008 - Removed all XML and Spry javascript libraries. Moved to
# jquery tablesort. Changed from checkboxes to drop down box.
# Added new devices report.
# v2.7 03/11/2009 - Upgraded to jquery-1.3.2 and jquery-ui-1.7, cleaned up code
# v2.8 03/31/2009 - Added Access Level Controls and moved all configuration options
# to /etc/netdb-cgi.conf
# v2.9 06/02/2009 - Added mac_format options to netdb-cgi.conf
# v2.10 06/18/2009 - Added user report and NAC registration display table
# v2.11 07/10/2009 - Added full jquery ui library and css to code. Changed error
# reporting to dialog boxes for clarity. Made address text
# box auto selected when page loads.
# v2.12 03/04/2010 - Added VLAN Change Capability
# v2.13 10/15/2010 - Added IPv6 Support
# v2.14 03/25/2011 - Added Unused ports report and cleaned up user error reporting
# v2.15 05/02/2011 - Added custom shutdown support (local to developer)
# v2.16 - Bug fixes for v1.10
# v2.17 10/17/2012 - Added neighbor discovery data and NAC role changes
# v2.18 02/14/2013 - Adding VRF support, inventory and new icons
# v2.19 02/27/2014 - Added description search and shut/no shut functionality
#
#################################################################################
use CGI qw(:standard Vars);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use Net::IP;
use NetDB;
use AppConfig;
use DateTime;
use Time::HiRes qw (gettimeofday);
use English;
use strict;
eval "use WebTemplate;"; # Custom module for template processing, ok if not available
# No nonsense
no warnings 'uninitialized';
#############################################################################
# Primary Configuration File (edit this file with your configuration options)
#############################################################################
my $config_cgi = "/etc/netdb-cgi.conf";
################################################
# Script Variables (DO NOT EDIT BELOW THIS LINE)
################################################
my $wolTimeout =25; #
my ( $scriptName, $ownerInfo, $ownerEmail, $pageTitle, $pageName, $template, $cgibin, $root, );
my ( $aboutFile, $config_file, $useCamtrace, $useStatistics, $mac_format, $desc_length );
my ( $findipuser, $trans_script, $mnc_shut, $mnc_unshut, $mnc_block, $mnc_noblock, $desc_script );
my ( $shut_script, $mnc_portshut, $mnc_portunshut );
# Other Vars
my $netdbCGIVer = '2.19';
my $netdbVer = '1';
my $netdbMinorVer = '13';
# Default Description Length
$desc_length = 30;
# DEVELOPMENT - Change the default config file if executed file is the development path
if ( $0 eq '/usr/lib/cgi-bin/netdb2.pl' || $0 eq '/usr/lib/cgi-bin2/netdb2.pl' ) {
$config_cgi = "/scripts/dev/netdb/netdbdev-cgi.conf";
}
#####################
# Process Config File
#####################
&parseConfig();
# File and Script Dependencies
my $netdbCSVcmd = "/opt/netdb/netdb.pl -c -conf $config_file";
my $wakecmd = "/usr/bin/wakeonlan -i ";
my $docRootTools2 = '/var/www/tools2/'; ## Only used for alternate web templates
my $CSVFile = 'netdbReport.csv';
my $netdbVerFile = '/opt/netdb/data/netdbversion.txt';
# Stats generated from update-statistics.sh
my $netdbTotalStats = '/opt/netdb/data/netdbstats.txt';
my $netdbMonthlyStats = '/opt/netdb/data/netdbmonthlystats.txt';
my $netdbDailyStats = '/opt/netdb/data/netdbdailystats.txt';
# ENV vars
my $docRoot = $ENV{'DOCUMENT_ROOT'};
my $source_address = $ENV{REMOTE_ADDR};
my $envuser = $ENV{REMOTE_USER};
#Clean domain info from username
( $envuser ) = split( /\@/, $envuser );
# Tools Template
if ( $docRoot eq $docRootTools2 ) {
$cgibin = '/cgi-bin2';
$root = '/var/www/tools2';
$template = "/var/www/tools2/output-template.htm";
}
# Dynamic File Locations
my $scriptLocation = "$cgibin/$scriptName";
my $camtraceLoc = "$cgibin/camtrace.pl";
my $dnsLoc = "$cgibin/dns.pl";
my $CSVFileLoc = "$root/$CSVFile";
# Text arrays for preloading tables and text output from queries
my @ntable;
my @netdbText;
# Authorization Variables
my $defaultAuthLevel;
my $userAuthLevel;
my %reportAuthLevel;
my %reportMaxCount;
my %vlanAuth;
my %nacAuth;
# Other Vars
my $DEBUG; # Set to 1 or append ?debug=1 to url
my ( $CSVOption, $verbose, $vendorOption, $switchReport, $vlanReport, $vlanStatusReport, $newMacsReport, $userReport );
my ( $inputType, $wakeLoc, $menuBar, $searchDays, $errmsg, $infomsg, $transactionID, $skipTemplate, $getOptions );
my ( $useNAC, $vlan_script, $unusedPortsReport, $role_file, $role_script, $statseeker, $useInventory, $invReport );
my ( $wifi_http, $descReport, $use_fqdn );
my $starttime = [ Time::HiRes::gettimeofday( ) ];
# Detaint the Path
$ENV{'PATH'} =~ /(.*)/;
$ENV{'PATH'} = $1;
# Autoflush
$OUTPUT_AUTOFLUSH = 1;
# DEVELOPMENT - Change default config file if this is the development copy
if ( $0 eq '/usr/lib/cgi-bin/netdb2.pl' || $0 eq '/usr/lib/cgi-bin2/netdb2.pl' ) {
my $config_cgi = "/scripts/dev/netdb/netdbdev-cgi.conf";
}
#################################################
# Process variables and check for POST state data
#################################################
my %FORM = Vars();
# Search over days
if ( $FORM{"days"} ) {
$searchDays = parseInputVar( "days" );
}
# Enable Debugging, use as a GET variable
if ( $FORM{"debug"} ) {
$DEBUG = 1;
$verbose = 1;
$getOptions = $getOptions . "&debug=1"
}
# Verbose camtrace output
if ( $FORM{"verbose"} ) {
$verbose = 1;
}
# Mac Format Option
if ( $FORM{"macformat"} ) {
$mac_format = parseInputVar( "macformat" );
$mac_format = 'ieee_dash' if $mac_format eq 'dash';
$mac_format = 'ieee_colon' if $mac_format eq 'colon';
$mac_format = 'no_format' if $mac_format eq 'none';
$getOptions = $getOptions . "&macformat=$mac_format"
}
# Parse Select Form for report type
if ( my $option = $FORM{"netdbselect"} ) {
$vendorOption = 1 if $option eq 'vendor';
$vlanReport = 1 if $option eq 'vlan';
$switchReport = 1 if $option eq 'switch';
$vlanStatusReport = 1 if $option eq 'status';
$newMacsReport = 1 if $option eq 'newmacs';
$userReport = 1 if $option eq 'user';
$unusedPortsReport = 1 if $option eq 'unusedports';
$invReport = 1 if $option eq 'invreport';
$descReport = 1 if $option eq 'desc_search';
}
## GET Option processing
# Vendor Code
if ( $FORM{"vendor"} ) {
$vendorOption = 1;
}
# Switch Report
if ( $FORM{"switchreport"} ) {
$switchReport = 1;
}
# Unused Port Report
if ( $FORM{"unusedports"} ) {
$unusedPortsReport = 1;
}
# Inventory Report
if ( $FORM{"invreport"} ) {
$invReport = 1;
}
# VLAN Report
if ( $FORM{"vlan"} ) {
$vlanReport = 1;
}
# User Report
if ( $FORM{"user"} ) {
$userReport = 1;
}
###########################################
# Skip template processing for AJAX Results
###########################################
if ( $FORM{"skiptemplate"} ) {
$skipTemplate = 1;
print header; # Always print a content type header
# Generating CSV report, results returned inline in tab
if ( $transactionID = $FORM{csvreport} ) {
generateReport();
}
# Wake on LAN, results retunred inline in WoL tab
elsif ( $FORM{"wake"} ) {
my $wake = parseInputVar("address");
my $wakeip = parseInputVar("wakeip");
&wakeOnLan( $wake, $wakeip );
}
elsif ( $FORM{"disableclient"} ) {
disableClient();
}
elsif ( $FORM{"vlanchange"} ) {
changeVlan();
}
elsif ( $FORM{"descchange"} ) {
changeDesc();
}
elsif ( $FORM{"shutchange"} ) {
changeStatus();
}
elsif ( $FORM{"findipuser"} ) {
findIPUser();
}
elsif ( $FORM{"bradfordtrans"} ) {
bradfordTransactions();
}
elsif ( $FORM{"rolechange"} ) {
changeRole();
}
else {
sendMain();
}
}
##########################################################
# Normal Script Processing, non-ajax full template support
##########################################################
else {
print header;
##################
# Process Template
##################
open( my $TEMPLATE, '<', "$template") or die "Can't open Template: $template: $!";
while ( my $line = <$TEMPLATE> ) {
# Search for comments used to insert dynamic content in to template
if ( $line =~ /<!--\s\w+\s-->/ ) {
if ( $line =~ /--\sPAGETITLE\s--/ ) {
print "$pageTitle";
}
elsif ( $line =~ /--\sPAGENAME\s--/ ) {
print "$pageName\n";
}
elsif ( $line =~ /--\sSIDELINKS1\s--/ ) {
WebTemplate::printSideLinks( (1, "nst", "Team Links" ) );
}
## Call main routine to populate page content
elsif ( $line =~ /--\sPAGECONTENT\s--/ ) {
if ( $FORM{"vlanchange"} ) {
&changeVlan();
}
else {
sendMain();
}
}
elsif ( $line =~ /--\sYOURIPADDRESS\s--/ ) {
print "<br><strong>IP: $ENV{REMOTE_ADDR} </strong>";
}
##################################################
# Javascript and CSS header code specific to NetDB
##################################################
elsif ( $line =~ /--\sSTYLESHEET\s--/ ) {
print '<!-- Start NetDB Header Code -->' . "\n";
print '<meta http-equiv="Content-Style-Type" content="text/css">' . "\n";
print '<meta http-equiv="Content-Script-Type" content="text/javascript">' . "\n";
print $line;
print '<script type="text/javascript" src="/depends/jquery-1.3.2.min.js"></script>' . "\n";
print '<script type="text/javascript" src="/depends/jquery-ui-1.7.2.custom.min.js"></script>' . "\n";
print '<link rel="stylesheet" href="/depends/jquery-ui-1.7.2.custom.css" type="text/css" media="print, projection, screen">' . "\n";
print '<script type="text/javascript" src="/depends/jquery.tablesorter.js"></script>' . "\n";
print '<script type="text/javascript" src="/depends/jquery.livequery.js"></script>' . "\n";
print '<script type="text/javascript" src="/depends/jquery.bgiframe.min.js"></script>' . "\n";
# Print custom javascript code for NetDB
&printHeaderCode();
print "\n" . '<!-- End NetDB Header Code -->' . "\n";
}
# If unknown comment, just print the line anyway
else {
print "$line\n";
}
}
# Fixup for tools site
elsif($line =~ /2col_leftNav.css/) {
$line =~ s/2col_leftNav.css/\/2col_leftNav.css/g;
print "$line";
}
# If nothing special on line, print it out unchanged
else {
print $line;
}
}
}
#######################################
#**************************************
# Main routine after template handoff
#**************************************
#######################################
sub sendMain {
my $address;
my $switchSearch;
# Parse and detaint input from POST/GET variable
$address = parseInputVar("address");
$switchSearch = $FORM{switch}; # Macs on a switchport
# Set searchDays if unset
$searchDays = 7 if !$searchDays;
# Make sure days is reasonable
if ( $searchDays > 5000 ) {
$searchDays = 5000;
}
# Some links call script with alternate var 'search'
if ( !$address ) {
$address = parseInputVar("search");
}
# Make sure a valid mac, ip or host, pass to special parser
if ( $address && !$switchSearch && !$switchReport && !$vendorOption && !$vlanReport &&
!$vlanStatusReport && !$unusedPortsReport && !$invReport ) {
print "<br>Debug: Calling NetDB Parser on $address\n" if $DEBUG;
($address, $inputType) = parseNetDBAddress($address);
print "<br>Debug: NetDB Parser results $address as $inputType\n" if $DEBUG;
}
# Switchport search, address is a mac
if ( $switchSearch ) {
$inputType = "switch";
}
# Unused Port Report
if ( $unusedPortsReport ) {
$inputType = "unusedports"
}
# Inventory Report
if ( $invReport ) {
$inputType = "invreport";
}
# Vendor Code Search
if ( $vendorOption ) {
$inputType = "vendor";
}
# Switch Report Option
if ( $switchReport ) {
$inputType = "switchreport";
# Strip off any domain name from the switch name unless using fqdn
( $address ) = split( /\./, $address ) if !$use_fqdn;
}
# Switchport Description Search
if ( $descReport ) {
# Loose input searching
$address = parseInputVarLoose("address");
$inputType = "desc_search";
}
# Vlan Report
if ( $vlanReport ) {
$inputType = "vlanreport";
}
# Vlan Status Report
if ( $vlanStatusReport ) {
$inputType = "vlanstatus";
}
# New MAC Address Report
if ( $newMacsReport ) {
$inputType = "newmacs";
$address = "New Devices";
}
# User Report
if ( $userReport ) {
$inputType = "user";
}
# Header
if ( !$skipTemplate ) {
print "<br>Debug: Printing Header\n" if $DEBUG;
printHeader($address);
}
# AJAX Return Block for inline requests
if ( !$skipTemplate ) {
print "<div id=\"ajaxresults\">\n";
}
# Check to see if generating report
if ( $transactionID = $FORM{csvreport} ) {
generateReport();
}
# WoL GET Method support
elsif ( $FORM{wake} ) {
my $wakemac = parseInputVar("address");
my $wakeip = parseInputVar("wakeip");
wakeOnLan( $wakemac, $wakeip );
printFooter( $address );
}
###############################################
# Query NetDB if $address passed all the checks
###############################################
elsif ( $address ) {
# Record a transaction for security purposes
$transactionID = recordTransaction( $address, $inputType );
# Make sure user is authorized to access this type of report
my $success = &checkAuthorization( $address, $inputType );
if ( $success eq "authorized" ) {
# Call NetDB routine to query database
getNetDB( $address, $inputType );
# Print Results if no errors
if ( !$errmsg && !$infomsg ) {
printResults( $address ); # Print NetDB Results
}
}
}
# Print any error or informational messages in dialog boxes
if ( $infomsg || $errmsg ) {
print '<div class="netdbresults" style="display: block;">' . "\n";
printAboutNetDB();
printFooter( $address );
print '</div>' . "\n";
# Informational Message
if ( $infomsg ) {
my ($infotype) = split( /\:/, $infomsg );
$infomsg =~ s/$infotype\:\s//;
print "<font size=\"3\"><div id=\"infodialog\" title=\"$infotype\">";
print "<p>$infomsg</p>\n";
print '</div>';
}
# Error Message
if ($errmsg) {
my ($infotype) = split( /\:/, $errmsg );
$errmsg =~ s/$infotype\:\s//;
print "<font size=\"3\"><div id=\"errordialog\" title=\"$infotype\">";
print "<p>$errmsg</p>\n";
print '</div>';
}
}
# Print about NetDB if no address passed in and no errors encountered
elsif ( !$address ) {
print '<div class="netdbresults" style="display: block;">' . "\n";
printNetDBStats() if $useStatistics;
printAboutNetDB();
printFooter( $address );
print '</div>' . "\n";
}
# Close AJAX Results
print "</div>\n" if !$skipTemplate;
}
#########################################################
# Check to see if user is authorized for this report type
#########################################################
sub checkAuthorization {
my $address = shift;
my $reportType = shift;
print "<br>Access Control: User $envuser has access level $userAuthLevel, attempting to access $reportType report
level $reportAuthLevel{$reportType}" if $DEBUG;
# Check to see if user has high enough access level for report unless report has no access restrictions
if ( $userAuthLevel >= $reportAuthLevel{"$reportType"} || !$reportAuthLevel{"$reportType"} ) {
return "authorized";
}
# If doing a switch report for a specific port (eg switch,Gi4/1) , allow access
elsif ( $reportType eq "switchreport" && $address =~ /\w+\,\w+\d+\// ) {
return "authorized";
}
else {
# Special case when users are searching their own registration data
if ( $userReport && $address eq $envuser ) {
return "authorized";
}
elsif ( $userReport ) {
$errmsg = "<b>No Access</b>: By default, users can only search for their own registrations. If you work in IT, send an email " .
"to <a href=\"mailto:$ownerEmail\">$ownerInfo</a> and request that your username be added to the NetDB Level $reportAuthLevel{$reportType} " .
"Access List. <br><br>(config: $config_cgi)";
}
else {
$errmsg = "<b>No Access to $reportType</b>: You must request permission to access the report type you selected (<b>$reportType</b>). " .
"If you need access, send an email " .
"to <a href=\"mailto:$ownerEmail\">$ownerInfo</a> and request that your username be added to the NetDB Level $reportAuthLevel{$reportType} " .
"Access List. <br><br>(config: $config_cgi)";
print STDERR "Netdb: User $envuser tried to access $reportType and was denied\n";
}
}
return;
}
###########################################
# Generate a CSV Report, inline ajax return
###########################################
sub generateReport {
# Query as unpriviledge user
my $dbh = connectDBro( $config_file );
my $netdb_ref = getTransaction( $dbh, $transactionID );
my @netDB = @$netdb_ref;
my $querytype = $netDB[0]{querytype};
my $queryvalue = $netDB[0]{queryvalue};
#$queryvalue =~ s/*/\%/gi; #flip to sql regex
my $querydays = $netDB[0]{querydays};
my $success;
$searchDays = $querydays;
$netdbCSVcmd = $netdbCSVcmd . " -d $querydays";
if ( $mac_format ) {
$netdbCSVcmd = $netdbCSVcmd . " -mf $mac_format";
}
# Use netdb CLI program to generate report based on type
if ( $querytype eq 'IP' ) {
`$netdbCSVcmd -i $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'switch' ) {
`$netdbCSVcmd -p $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'Hostname' ) {
`$netdbCSVcmd -n $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'vlanreport' ) {
`$netdbCSVcmd -vl $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'vendor' ) {
`$netdbCSVcmd -vc $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'switchreport' ) {
`$netdbCSVcmd -sw $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'desc_search' ) {
`$netdbCSVcmd -ds $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'vlanstatus' ) {
`$netdbCSVcmd -vs $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'user' ) {
`$netdbCSVcmd -u $queryvalue > $CSVFileLoc`;
$success = 1;
}
elsif ( $querytype eq 'unusedports' ) {
`$netdbCSVcmd -up $queryvalue > $CSVFileLoc`;
$success = 1;
}
# Display report link if successful
if ( $success ) {
print "<p><font size=\"+1\"><a class=\"btn\" href =\"/$CSVFile\"><span><span>Download CSV Report</span></span></a></font></p>\n";
print "<br><br> (report id:$transactionID)</p>\n" if $DEBUG;
}
else {
print "<p>Error: Could not generate report for [$transactionID] $queryvalue $querytype</p>";
}
}
##################################################
# Input Handling, check for safe input and detaint
##################################################
sub parseInputVar {
my $inputVar = shift;
my $inputData = $FORM{$inputVar};
my $returnData; ## Used as detainted var
#########################################
# Initially Verify Input Data and Detaint
#########################################
if ( $inputData ) {
# Strip out unwanted hostname (hack)
$inputData =~ s/\.clinlan\.local//;
# Strip out 1q from vlan id if passed in
$inputData =~ s/\(1q\)//;
print "<br>Debug: Input Parser on $inputVar - input:$inputData" if $DEBUG;
# Truncate Input Data to 75 characters
$inputData = substr( $inputData, 0, 75 );
# Strip out escape/unneeded characters for security
$inputData =~ s/(\%)//g; # Strip out wildcards
# Strip out spaces if this is not a vendor search
if ( $vendorOption || $invReport ) {
$inputData =~ s/\s+/ /g;
$inputData = lc( $inputData );
}
else {
$inputData =~ s/\s+//g;
}
# Allowed characters
($returnData) = $inputData =~ m/^([A-Z0-9_.\-\:\s\,\/\*]+)$/ig;
print " output:$returnData\n" if $DEBUG;
if ( $inputData ne $returnData ) {
$errmsg = "<b>Input Error</b>: There is a problem with the data you submitted - <strong>$inputData</strong>";
$returnData = undef;
}
}
return ( $returnData );
}
####################################################################
# Less Strict Input Handling, still check for safe input and detaint
####################################################################
sub parseInputVarLoose {
my $inputVar = shift;
my $inputData = $FORM{$inputVar};
my $returnData; ## Used as detainted var
#########################################
# Initially Verify Input Data and Detaint
#########################################
if ( $inputData ) {
# Strip out unwanted hostname (hack)
$inputData =~ s/\.clinlan\.local//;
print "<br>Debug: Input Parser on $inputVar - input:$inputData" if $DEBUG;
# Truncate Input Data to 400 characters
$inputData = substr( $inputData, 0, 400 );
# Strip out escape/unneeded characters for security
$inputData =~ s/(\%)//g; # Strip out wildcards
# Allowed characters
($returnData) = $inputData =~ m/^([A-Z0-9_.\-\:\s\,\/\[\]\s\*]+)$/ig;
print " output:$returnData\n" if $DEBUG;
if ( $inputData ne $returnData ) {
$errmsg = "<b>Input Error</b>: There is a problem with the data you submitted - <strong>$inputData</strong>";
$returnData = undef;
}
}
return ( $returnData );
}
##################################################
# Once input passes intial parser, find out what
# sort of NetDB query it is.
# Identifies MACs and IPs, everything else is
# considered a hostname.
##################################################
sub parseNetDBAddress {
my $inputAddress = shift;
my $inputType = shift;
my $searchmac;
my $mymac;
my $myip;
if ($inputAddress) {
#IP address
if ( ( $inputAddress =~ /^\d+\.\d+\.\d+\.\d+$/ || $inputAddress =~ /^\d+\.\d+\.\d+\.$/ )
&& $inputAddress !~ /\w\w\w\w\.\w\w\w\w\.\w\w\w\w/ )
{
$inputAddress =~ s/\s+//g; #strip out any spaces
$inputType = "IP";
}
# IPv6 Address
elsif ( $inputAddress =~ /\w\w\w:/ || $inputAddress =~ /::/ ) {
$inputAddress =~ s/\s+//g; #strip out any spaces
$inputType = "IP";
}
# Check MAC Address
elsif ( $inputAddress !~ /^(\d+)(\.\d+){3}$/ && $inputAddress !~ /((musc.edu)|(clinlan.local))/) {
# Convert to lowercase
my $mac = $inputAddress;
$mac =~ tr/[A-F]/[a-f]/;
# Check for short mac format, xx:xx
if ( $mac =~ /^\w\w\:\w\w$/ ) {
$inputAddress = $mac;
$inputType = "ShortMAC";
}
# Mac Wildcard Search (55:55* or *55:55:55 etc)
elsif ( $mac =~ /^\w\w(\:\w\w){1,4}\:?\*$/ || $mac =~ /^\*\:?(\w\w\:){1,4}\w\w$/ ) {
$inputAddress = $mac;
$inputType = "ShortMAC";
}
# Not a short mac, normal mac processing
else {
# Strip out all extra characters
$mac =~ s/(:|\.|\-|(^0x)|)//g;
# Make sure it's a mac address
if ( $mac =~ /^(([a-f]|[0-9]){12})$/ ) {
# Nasty code to put the submitted mac address in to the desired format. I should have made a new
# subroutine instead of this mess, but it works.
my %machash;
$machash{mac} = $mac;
my @tmpmac = (\%machash);
my $tmpref = convertMacFormat( \@tmpmac, $mac_format );
@tmpmac = @$tmpref;
$mac = $tmpmac[0]{mac};
$inputAddress = $mac;
$inputType = "MAC";
}
# Hostname
elsif ( $inputAddress =~ /^\w+/ ) {
$inputAddress =~ s/\s+//g;
$inputType = "Hostname";
}
else {
$errmsg = "<b>Input Error</b>: $inputAddress is not an IP address, hostname or MAC address";
$inputAddress = undef;
}
}
}
# Hostname
elsif ( $inputAddress =~ /^\w+/ ) {
$inputAddress =~ s/\s+//g;
$inputType = "Hostname";
}
else {
$errmsg = "<b>Input Error</b>: $inputAddress is not an IP address, hostname or MAC address";
$inputAddress = undef;
}
}
else {
$inputAddress = undef;
}
return ( ($inputAddress, $inputType) );
}
#####################
# Wake On Lan Support
#####################
sub wakeOnLan {
my $wakemac = shift;
my $wakeip = shift;
my $secondarynet;
my @ipmacpair;
# If not supplied ip mac pair, search for device via hostname
if ( !$wakeip ) {
@ipmacpair = getIPMACs( $wakemac );
}
# Supplied mac and IP, add single entry
else {
push( @ipmacpair, "$wakeip,$wakemac" );
}
# Catch no data and return error
if ( !$ipmacpair[0] ) {
print "<div id=\"errordialog\">Could not find this device on the network, ";
print "could be the wrong hostname or search criteria</div><br>\n";
print "<div class=\"messagebox info\">Could not find this device on the network, ";
print "could be the wrong hostname or search criteria</div><br>\n";
return;
}
foreach my $pair ( @ipmacpair ) {
( $wakeip, $wakemac ) = split( /\,/, $pair );
if ( $envuser ne "wol20" ) {
recordTransaction( $wakemac, "WoL" );
}
$wakemac = getIEEEMac( $wakemac );
my @ip = split(/\./, $wakeip );
# Check for even or odd subnet
if ( $ip[2] % 2 == 0 ) {
$secondarynet = $ip[2] + 1;
}
else {
$secondarynet = $ip[2] - 1;
}
# Create the broadcast subnet addresses
my $broadcast1 = "$ip[0].$ip[1].$ip[2].255";
my $broadcast2 = "$ip[0].$ip[1].$secondarynet.255";
if ( $ip[2] == 44 || $ip[2] == 45 ) {
$broadcast1 = "128.23.47.255";
}
`$wakecmd $broadcast1 $wakemac`;
`$wakecmd $broadcast2 $wakemac`;
print "<br>Sent WoL magic packets to $wakemac on subnets $broadcast1 and $broadcast2\n" if $DEBUG;
# Ping device and wait for it to wake up
my $pingpid = open( my $PING, '-|', "/bin/ping -c $wolTimeout $wakeip") || warn("Couldn't execute ping $wakeip: $!");
my $isAwake;
while ( my $line = <$PING> ) {
if ( $line =~ /bytes from/ ) {
$isAwake = 1;
kill 15, $pingpid;
last;
}
}
close $PING;
print "<br>" if $FORM{"skiptemplate"};
if ( $isAwake ) {
print "<div class=\"messagebox success\">$wakeip is awake and on the network. ";
print "Bookmark <a href=\"$scriptLocation?address=$wakemac&wake=1&wakeip=$wakeip\">this link</a>";
print " to wake up this device in the future.</div><br>\n";
}
else {
print "<div class=\"messagebox info\">$wakeip is not responding to pings (usually the device is slow
to boot or has a local firewall issue).
It still might be awake and on the network. Tried to wakeup $wakemac.";
print " Bookmark <a href=\"$scriptLocation?address=$wakemac&wake=1&wakeip=$wakeip\">this link</a>";
print " to wake up this device in the future.</div><br>\n";
}
print <<SCRIPT;
<script>
\$(function() {
\$(".messagebox").fadeIn(500);
});
</script>
SCRIPT
} # End Foreach
}
###################
# NetDB HTML Header
###################