-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnetdisco.pm
2241 lines (1647 loc) · 59 KB
/
netdisco.pm
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
# $Id$
=head1 NAME
netdisco.pm - Utility functions used for back and front ends
=head1 DESCRIPTION
This module provides utility functions for use with netdisco in both
the front and backend. Front-end specific features are limited to the
mason (.html) files, and the back-end specific features are limited to
netdisco.
=head1 AUTHOR
Max Baker
=head1 SYNOPSIS
=cut
package netdisco;
use strict;
use Carp;
use Exporter;
use Socket;
use DBI;
use Digest::MD5;
use vars qw/%DBH $DB %CONFIG %GRAPH %GRAPH_SPEED $SENDMAIL $SQLCARP %PORT_CONTROL_REASONS $VERSION/;
@netdisco::ISA = qw/Exporter/;
@netdisco::EXPORT_OK = qw/insert_or_update getip hostname sql_do sql_begin sql_commit sql_rollback sql_disconnect has_layer
sql_hash sql_column sql_columns sql_rows sql_query add_node add_arp add_nbt dbh sql_match
all config updateconfig sort_ip sort_port sql_scalar root_device log
make_graph is_mac user_add user_del mail is_secure in_subnet in_subnets
active_subnets dump_subnet in_device get_community
url_secure is_private cidr mask_to_bits bits_to_mask dbh_quote sql_vacuum
tryuse homepath user_ldap_verify ldap_search/;
%netdisco::EXPORT_TAGS = (all => \@netdisco::EXPORT_OK);
=head1 GLOBALS
=over
=item %netdisco::DBH
Holds Database Handles, key is db name as set in config file.
=cut
=item %netdisco::DB
Index of current Database Handle. Default C<'Pg'>;
=cut
$DB = 'Pg';
=item %netdisco::CONFIG
Holds config info from C<netdisco.conf>
=cut
=item %netdisco::GRAPH
Holds vertex information for C<make_graph()>
=cut
=item $netdisco::SENDMAIL
Full path to sendmail executable
=cut
$SENDMAIL = '/usr/sbin/sendmail';
=item $netdisco::SQLCARP - Carps SQL!
This will C<carp()> the SQL sent off to the server for Debugging.
If running under mason, the output of C<carp()> goes to the Apache
Error Log. From the shell it goes to STDERR.
Note that if you set this on a MASON page, the value will remain
cached across most of the current httpd proccesses. Make sure you set it
back to 0 via mason when you're done, unless you like watching Apache's
error_log grow.
=cut
$SQLCARP=0;
=item %PORT_CONTROL_REASONS
Reason why a port would be shutdown. These get fed into C<port_control_log>
=cut
%PORT_CONTROL_REASONS = (
'address' => ['Address Allocation Abuse',
'A system which does not obtain and/or use its address in a legitimate
fashion. This includes machines that self-assign IP addresses and those
that modify their MAC address.'],
'dos' => ['Denial Of Serivce',
'Any kind of data flow, mailicious or otherwise, which is involved
in a service-affecting disruption. This includes activities such
as ICMP and UDP floods, SYN attacks, and other service disruptive
flows. A system involved in a DoS attack is usually compromised.'],
'bandwidth' => ['Excessive BandWidth',
'A user has sent/received data in excess of campus acceptable use standards.'],
'compromised' => ['System Compromised',
'The system has been compromised and poses a high risk to campus
resources. If other behavior is observed, such as involvement in a DoS attack, that reason code should be used in place of this one.'],
'copyright' => ['Copyright Violation',
"Following the takedown provision of the DMCA to limit the organization's copyright liability."],
'exploit' => ['Remote Exploit Possible',
'A remotely exploitable vulnerability posing high risk exists on the system.'],
'noserv' => ['Not in service',
'Port is not in service. The port may not be phsyically connected to a jack, or it may be that no one is paying for service on the associated jack.'],
'polling' => ['Excessive Polling of DNS/DHCP/SNMP',
'Distinct from DoS attacks, excessive polling is often due to
misconfigured systems or malfunctioning protocol stacks. An example of
this would be sustained, repetitive polling of the DHCP server for an
address.'],
'other' => ['Other', 'Does not fit in any other catagory. Make a <i>very</i> detailed <TT>Log</TT> entry.']
);
=item $VERSION - Sync'ed with Netdisco releases
=cut
$VERSION = '1.3.3';
=back
=head1 Exportable Functions
=head2 General Functions
=over
=item add_arp(mac,ip)
Manipulates entries in 'node_ip' table.
Expires old entries for given IP address.
Adds new entry or time stamps matching one.
=cut
sub add_arp {
my ($mac,$ip) = @_;
my $dbh = &dbh;
# Set the active flag to false to archive all other instances
# of this IP address
sql_do(qq/UPDATE node_ip SET active = 'f' WHERE ip='$ip' AND active/);
# Add this entry to node table.
my %hash = ('mac' => $mac, 'ip' => $ip);
insert_or_update('node_ip', \%hash,
{ 'time_last' => scalar(localtime), 'active' => 1, %hash });
}
=item add_node(mac,ip,port,vlan)
Manipulates entries in C<node> table.
Expires old entries matching given arguments.
Adds a new entry or time stamps matching old entry.
=cut
sub add_node {
my ($mac,$ip,$port,$vlan) = @_;
my $dbh = &dbh;
my $oui = substr($mac,0,8);
# Set the active flag to false to archive all other instances
# of this mac address on this VLAN
my $other = sql_do(qq/UPDATE node SET active = 'f'
WHERE mac = '$mac' AND vlan = '$vlan' AND active
AND NOT (switch = '$ip' AND port = '$port')
/);
# Add this entry to node table.
my %hash = ('switch' => $ip, 'mac' => $mac, 'port' => $port, 'vlan' => $vlan);
my %set = ('time_last' => 'now', 'active' => 1, 'oui' => $oui);
# if there was another node, set time_recent too.
# NOTE: $other might be "0E0", so be careful how you test it.
if ($other != 0) {
$set{time_recent} = 'now';
}
insert_or_update('node', \%hash, { %set, %hash });
}
=item add_nbt(ip,mac,nbname,domain,server,nbuser)
Manipulates entries in 'node_nbt' table.
Expires old entries for given MAC address.
Adds new entry or time stamps matching one.
=cut
sub add_nbt {
my ($ip,$mac,$nbname,$domain,$server,$nbuser) = @_;
my $dbh = &dbh;
# Set the active flag to false to archive all other instances
# of this MAC address
#sql_do(sprintf("UPDATE node_nbt SET active = 'f' WHERE mac=%s",
# $dbh->quote($mac)));
# Add this entry to node_nbt table.
insert_or_update('node_nbt', { 'mac' => $mac },
{ 'mac' => $mac, 'ip' => $ip, 'time_last' => scalar(localtime),
'active' => 1, 'domain' => $domain, 'server' => $server,
'nbname'=>$nbname, 'nbuser'=>$nbuser,
});
}
=item bits_to_mask(bits)
Takes a CIDR style network mask in number of bits (/24) and returns the older style
bitmask.
=cut
sub bits_to_mask {
my $bits = shift;
return join(".",unpack("C4",pack("N", 2**32 - (2 ** (32-$bits)))));
}
=item get_community(type,host,ip)
Get Community depending on type (ro,rw).
If C<get_community> is defined, then get the try to get the community from
shell-command. If C<get_community> is undefined or nothing
is returned from the command use C<community> or
C<community_rw>.
The command specified in C<get_community> must return in stdout a string like
community=<list of readonly-communities>
setCommunity=<list of write-communities>
Returns Community-List as Array reference
Options:
type => 'ro'|'rw' for the type of community
host => name of the device
ip => device ip-address
=cut
sub get_community($$;$) {
my $type = lc(shift);
my $host = shift;
my $ip = shift || $host;
my $cmd = $CONFIG{get_community};
my $rcom = $CONFIG{community};
my $rwcom = $CONFIG{community_rw};
if (defined $cmd && length($cmd)) {
my @com;
# replace variables
$cmd =~ s/\%HOST\%?/$host/egi;
$cmd =~ s/\%IP\%?/$ip/egi;
my $return = `$cmd`;
my @lines = split (/\n/,$return);
foreach (@lines) {
if (/^community\s*=\s*(.*)\s*$/i) {
if (length($1)) {
@com = split(/\s*,\s*/,$1);
$rcom = \@com;
} else {
$rcom = undef;
}
} elsif (/^setCommunity\s*=\s*(.*)\s*$/i) {
if (length($1)) {
@com = split(/\s*,\s*/,$1);
$rwcom = \@com;
} else {
$rwcom = undef;
}
}
}
}
return ($type eq 'rw' ? $rwcom : $rcom);
}
=item config()
Reads the config file and fills the C<%CONFIG> hash.
=cut
sub config {
my $file = shift;
my %args = @_;
# all default to 0
my @booleans = qw/compresslogs ignore_private_nets reverse_sysname daemon_bg
port_info secure_server graph_clusters graph_splines portctl_uplinks
portctl_nophones portctl_vlans macsuck_all_vlans macsuck_no_unnamed
macsuck_bleed bulkwalk_off vlanctl apache_auth nonincreasing
store_modules vacuum store_wireless_client reverse_lookup_ipv6/;
# these will make array refs of their comma separated lists
my @array_refs = qw/community community_rw mibdirs bulkwalk_no
macsuck_no arpnip_no discover_no ignore_interfaces
macsuck_only arpnip_only discover_only
snmpforce_v1 snmpforce_v2 snmpforce_v3 db_tables
v3_users v3_users_rw
ldap_server /;
# these will make a reference to a hash:
# keys :comma separated list entries value : number > 0
my @hash_refs = qw/portcontrol admin web_console_vendors
web_console_models macsuck_no_vlan
ldap_opts ldap_tls_opts
/;
# Multiple arrays
my @array_refs_mult = qw/node_map/;
# Reference to a hash; each line is an entry in the hash,
# with format key:value
my @hash_refs_mult = qw/v3_user/;
# Add custom types from caller outside netdisco
foreach my $type (qw(booleans array_refs hash_refs array_refs_mult hash_refs_mult)) {
eval "push(\@$type, \@{\$args{config}{\$type}});";
}
open(CONF, "<$file") or die "Can't open Config File $file. $!\n";
my @configs=(<CONF>);
close(CONF);
# Clear out config values where can build up
foreach my $a (sort @array_refs_mult) {
$CONFIG{$a} = [];
}
foreach my $a (@hash_refs_mult) {
$CONFIG{$a} = {};
}
while(my $config = shift @configs){
chomp $config;
# Check for wrap (\ at end of line)
my $cur_line = $config;
while ($cur_line =~ /\\\s*$/){
# Remove tailing \
$config =~ s/\\\s*$//;
# Grab next line
my $next_line = shift(@configs);
chomp($next_line);
# Check for trailing \ on newline
if ($next_line =~ /\\\s*$/) {
# If comments in line too, add the \ back in
if ($next_line =~ s/(?<!\\)#.*//){
$next_line .= '\\';
}
# Otherwise just remove the comments
} else {
$next_line =~ s/(?<!\\)#.*//;
}
# Handle escaped pound signs
$next_line =~ s/\\#/#/g;
# Trim out leading whitespace
$next_line =~ s/^\s*/ /;
# concat next line to current.
$config .= $next_line;
# could have lots of \'d lines in a row
$cur_line = $next_line;
}
# Take out Comments - Handle escaped pound signs
$config =~ s/(?<!\\)#.*//;
$config =~ s/\\#/#/g;
# Trim leading and trailing white space
$config =~ s/^\s*//;
$config =~ s/\s*$//;
# Ignore Blank Lines
next unless (length $config);
# Fill the %CONFIG hash
my $var = undef; my $value = undef;
if ($config =~ /^([a-zA-Z_\-0-9]+)\s*=\s*(.*)$/) {
$var = $1; $value = $2;
}
unless(defined $var and defined $value){
print STDERR "Bad Config Line : $config\n";
next;
}
# Config Variable Expansion ($home will become $CONFIG{home})
# ignores \$expression
while ($value =~ m/(?<!\\)\$([a-zA-Z_-]+)/g){
my $configvar = $1; my $configval = $CONFIG{$configvar};
$value =~ s/(?<!\\)\$$configvar/$configval/g if defined $configval;
}
# change \$ to $
$value =~ s/\\\$/\$/g;
# Hacks
# Booleans
if (grep /^\Q$var\E$/,@booleans) {
if ( $value =~ /^(1|t|y|yes|true|si|oui)$/i ) {
$value = 1;
} else {
$value = 0;
}
}
# Comma separated lists -> array ref
if (grep /^\Q$var\E$/,@array_refs) {
my @com = split(/\s*(?<!\\),\s*/,$value);
foreach (@com){
$_ =~ s!\\,!,!g;
}
$value = \@com;
}
# Multiple array refs
if (grep /^\Q$var\E$/,@array_refs_mult) {
my $oldvalue = $CONFIG{$var};
push (@$oldvalue, $value);
$value = $oldvalue;
}
# Multiple hash refs
if (grep /^\Q$var\E$/,@hash_refs_mult) {
my ($key, $val) = split(/\s*:\s*/, $value, 2);
$value = $CONFIG{$var};
$value->{$key} = $val;
}
# Comma separated lists that map to defined hash keys.
if (grep /^\Q$var\E$/,@hash_refs) {
my %seen;
foreach my $key (split(/\s*(?<!\\),\s*/,$value)){
$key =~ s/^\s+//;
$key =~ s/\s+$//;
$key =~ s!\\,!,!g;
$seen{$key}++;
}
$value = \%seen;
}
# Database Hash values
if ($var =~ /^db_([a-zA-z]+)_opts$/){
my %opts;
foreach my $pair (split(/\s*(?<!\\),\s*/,$value)) {
$pair =~ s!\\,!,!g;
my ($hash_key,$hash_value) = split(/\s*=>\s*/,$pair);
$opts{$hash_key}=$hash_value;
}
$value = \%opts;
}
$CONFIG{$var}=$value;
}
$CONFIG{'@file'} = $file;
$CONFIG{'@mtime'} = -M $file;
*::CONFIG = \%CONFIG;
return \%CONFIG;
}
=item updateconfig()
Checks the modification time of the configuration file and
re-reads it if needed. (Note: for now, defaults are not
reset - i.e., if there was an item in the config file before,
and it is missing when we reread it, it keeps its old value
and doesn't get set to the default.)
Uses eval to run config, so that we can keep running with the old
config if there's a problem with the config file.
=cut
sub updateconfig {
my $needupdate = 0;
if (defined($CONFIG{'@file'}) && defined($CONFIG{'@mtime'})) {
if (-M $CONFIG{'@file'} < $CONFIG{'@mtime'}) {
$needupdate = 1;
}
}
if ($needupdate) {
eval { config($CONFIG{'@file'}); };
if ($@) {
carp($@);
}
}
$needupdate;
}
=item has_layer(bit string,layer)
Takes ascii encoded string of eight bits, and checks for the specific
layer being true. Most significant bit first.
has_layer(00000100,3) = true
=cut
sub has_layer {
my ($layers,$check_for) = @_;
return substr($layers,8-$check_for, 1);
}
=item hostname(ip)
Returns the DNS server entry for the given ip or hostname.
=cut
sub hostname {
my $ip = shift;
my @host = ();
if ($ip =~ /^[0-9a-f:]+$/ && $CONFIG{'reverse_lookup_ipv6'}) {
my $cando_v6lookup = tryuse('Socket6', die => 0);
# IPv6 address passed
if ($cando_v6lookup->[0]) {
@host = gethostbyaddr(inet_pton(AF_INET6, $ip), AF_INET6);
}
} else {
# Assume IPv4 address was passed
@host = gethostbyaddr(inet_aton($ip), AF_INET);
}
return $host[0];
}
=item getip(host)
Returns the IP Address of a given IP or hostname. If the
given argument appears to be in dotted octet notation, it
does no DNS hits and just returns it.
It also just returns an IP address with a subnet mask.
Subnet masks are not permitted on host names.
=cut
sub getip {
my $hostname = shift;
my $ip;
if ($hostname =~ /^\d+\.\d+\.\d+\.\d+(?:\/\d+)?$/) {
$ip = $hostname;
} else {
my $testhost = inet_aton($hostname) || inet_aton($hostname . ($CONFIG{domain} || ''));
return undef unless (defined $testhost and length $testhost);
$ip = inet_ntoa($testhost);
}
return $ip;
}
=item in_device(device,to_match)
First argument can either be:
1. plain text IP or hostname
2. A row from the device table as returned from sql_hash
Second argument is an array ref as returned from config, eg. C<bulkwalk_no>.
=cut
sub in_device {
my $device = shift;
my $to_match = shift;
return 0 unless defined $to_match;
return 0 unless defined $device;
my ($ip,$terms);
# First Argument:
# Passed a sql_hash from the device table
if (ref($device) eq 'HASH'){
$ip = $device->{ip};
$terms = $device;
# Passed as simple hostname/IP
} else {
$ip = getip($device);
$terms = {};
}
# Second Argument:
foreach my $term (@$to_match){
$term =~ s/^\s*//;
$term =~ s/\s*$//;
# Check for device types
if ($term =~ /(.*)\s*:\s*(.*)/){
my $attrib = lc($1); my $match = $2;
return 1 if $terms->{$attrib} && $terms->{$attrib} =~ /^$match$/;
# Blanket wildcard
} elsif ($term eq '*') {
return 1;
# Consider this a subnet / host
} else {
#print "checking $term against $ip\n";
return 1 if in_subnet(getip($term),$ip);
}
}
return 0;
}
=item in_subnet(subnet,ip)
Returns Boolean. Checks to see if IP address is in subnet. Subnet
is defined as single IP address, or CIDR block. Partial CIDR format
(192.168/16) is NOT supported.
in_subnet('192.168.0.0/24','192.168.0.3') = 1;
in_subnet('192.168.0.3','192.168.0.3') = 1;
=cut
sub in_subnet{
my ($subnet,$ip) = @_;
unless (defined $subnet and defined $ip){
return undef;
}
# No / just see if they're equal
if ($subnet !~ m!/!) {
return ($subnet eq $ip) ? 1 : 0;
}
# Parse Subnet
my ($root,$bits);
if ($subnet =~ /^([\d\.]+)\/(\d+)$/){
$root = $1; $bits = $2;
} else { return undef; }
my $root_bin = unpack("N",pack("C4",split(/\./,$root)));
my $mask = 2**32 - (2 ** (32 - $bits));
# Parse IP
my $ip_bin = unpack("N",pack("C4",split(/\./,$ip)));
# Root matches and Mask Matches
return ( ($ip_bin & $mask) == $root_bin
and ($ip_bin & ~ $mask)
) ? 1 : 0;
}
=item in_subnets(ip,config_directive)
Returns Boolean. Checks a given IP address against all the IPs and subnet
blocks listed for a config file directive.
print in_subnets('192.168.0.1','macsuck_no');
=cut
sub in_subnets {
my ($ip,$config) = @_;
return 0 unless defined $CONFIG{$config};
return 0 unless defined $ip;
foreach my $net (keys %{$CONFIG{$config}}) {
return 1 if in_subnet($net,$ip);
}
return 0;
}
=item active_subnets()
Returns array ref containing all rows from the subnets table that
have a node or device in them.
=cut
sub active_subnets {
my $subnets = sql_rows('subnets',['net'],undef,undef,'order by net');
my $active = [];
foreach my $row (@$subnets) {
my $net = $row->{net};
my $found = 0;
$found ||= sql_scalar('node_ip',['1 as yup'],{'ip' => \\"<< '$net'"});
$found ||= sql_scalar('device',['1 as yup'],{'ip' => \\"<< '$net'"});
$found ||= sql_scalar('device_ip',['1 as yup'],{'alias' => \\"<< '$net'"});
push(@$active, $net) if $found;
}
return $active;
}
=item dump_subnet(cidr style subnet)
Serves you all the possible IP addresses in a subnet.
Returns reference to hash. Keys are IP addresses
in dotted decimal that are in the subnet.
Gateway and Broadcast (.0 .255) addresses are not included.
$hash_ref = dump_subnet('192.168.0.0/24');
scalar keys %$hash_ref == 254;
Also accepted :
dump_subnet('14.0/16');
dump_subnet('4/24');
=cut
sub dump_subnet {
my $subnet = shift;
# Parse Subnet
my ($root,$bits);
if ($subnet =~ /^([\d\.]+)\/(\d+)$/){
$root = $1; $bits = $2;
} else { return;}
# parse partial subnets
my @roots = split(/\./,$root);
for (my $i=0; scalar(@roots) < 4; $i++){
push (@roots,0);
}
my $root_bin = unpack("N",pack("C4",@roots));
my $mask = 2**32 - (2 ** (32 - $bits));
my $addrs = {};
for (my $ip_bin=$root_bin+1;$ip_bin < 2**32; $ip_bin++){
last unless (($ip_bin & $mask) == $root_bin and ($ip_bin & ~ $mask));
my $ip = inet_ntoa(pack('N', $ip_bin));
next if $ip =~ m/\.(255|0)$/;
$addrs->{$ip}++;
}
return $addrs;
}
=item is_mac(mac)
Returns Boolean. Checks if argument appears to be a mac address.
Checks for types :
08002b:010203
08002b-010203
0800.2b01.0203
08-00-2b-01-02-03
08:00:2b:01:02:03
=cut
sub is_mac{
my $mac = shift;
return 0 if !defined $mac;
my $hex = "[0-9a-fA-F]";
#'08002b:010203', '08002b-010203'
return 1 if ($mac =~ /^${hex}{6}[:-]{1}${hex}{6}$/);
#'0800.2b01.0203'
return 1 if ($mac =~ /^${hex}{4}\.${hex}{4}\.${hex}{4}$/);
#'0800-2b01-0203' c/o http://sites.google.com/site/jrbinks/code/netdisco/mac-patches
return 1 if ($mac =~ /^${hex}{4}-${hex}{4}-${hex}{4}$/);
# '08-00-2b-01-02-03','08:00:2b:01:02:03'
return 1 if ($mac =~ /^${hex}{2}-${hex}{2}-${hex}{2}-${hex}{2}-${hex}{2}-${hex}{2}$/);
return 1 if ($mac =~ /^${hex}{2}:${hex}{2}:${hex}{2}:${hex}{2}:${hex}{2}:${hex}{2}$/);
return 0;
}
=item log(class,text)
Inserts an entry in the C<log> table.
log('error',"this is an error");
=cut
sub log {
my ($class,$entry,$file) = @_;
insert_or_update('log',undef,{'class' => $class, 'entry' => $entry, 'logfile' => $file});
}
=item mail(to,subject,body)
Sends an E-Mail as Netdisco
=cut
sub mail {
my ($to,$subject,$body) = @_;
my $domain = $CONFIG{domain} || 'localhost';
$domain =~ s/^\.//;
open (SENDMAIL, "| $SENDMAIL -t") or die "Can't open sendmail at $SENDMAIL.\n";
print SENDMAIL "To: $to\n";
print SENDMAIL "From: Netdisco <netdisco\@$domain>\n";
print SENDMAIL "Subject: $subject\n\n";
print SENDMAIL $body;
close (SENDMAIL) or die "Can't send letter. $!\n";
}
=item is_private(ip)
Returns true if a given IP address is in the RFC1918 private
address range.
=cut
sub is_private {
my ($ip) = @_;
my $ignore = 0;
# Class A Private
$ignore++ if $ip =~ /^10\./;
# Class B Private
$ignore++ if $ip =~ /^172\.(\d+)\./ && ($1 >= 16 && $1 <= 31);
# Class C private
$ignore++ if $ip =~ /^192\.168\./;
return $ignore;
}
=item cidr(ip, mask)
Takes an IP address and netmask and returns the CIDR format
subnet.
=cut
sub cidr {
my ($ip, $mask) = @_;
my $bits = mask_to_bits($mask);
return undef if (!defined($ip) || !defined($mask));
my $nip = unpack("N", pack("C*", split(/\./, $ip)));
my $nmask = unpack("N", pack("C*", split(/\./, $mask)));
my $netaddr = join(".", unpack("C*", pack("N", $nip & $nmask)));
return "$netaddr/$bits";
}
=item mask_to_bits(mask)
Takes a netmask and returns the CIDR integer number of bits.
mask_to_bits('255.255.0.0') = 16
=cut
sub mask_to_bits{
my $mask = shift;
my $sum = undef;
for my $oct (split(/\./,$mask)){
return undef if ($oct > 255 or $oct < 0 );
for my $bits (split(//,unpack("B*",pack("C",$oct)))) {
$sum += $bits;
}
}
return $sum;
}
=item is_secure
To be run under mason only.
Returns true if the server want's to be secure and is, or true if the server doesn't want to be secure.
Returns false if the server is not secure but wants to be.
=cut
sub is_secure {
my $secure = $CONFIG{secure_server};
return 1 unless defined $secure;
return 1 if $secure !~ /^(1|y|t)/i;
# secure_server is set.
my $ar = $::r || $HTML::Mason::Commands::r;
unless (defined $ar and $ar->can('subprocess_env')){
carp "netdisco::is_secure() - Can't find Apache \$r\n";
return;
}
if (defined $ar->subprocess_env('https') and $ar->subprocess_env('https') eq 'on') {
return 1;
}
return 0;
}
=item url_secure(url)
=cut
sub url_secure {
my $path = shift;
return unless defined $path;
my $ar = $::r || $HTML::Mason::Commands::r;
unless (defined $ar and $ar->can('hostname')){
carp "netdisco::url_secure() - Can't find Apache \$r\n";
return;
}
my $webpath = $CONFIG{webpath};
my $server = $ar->hostname;
# Check for the easy case
if ($path =~ m!^http(s)?://!){
$path =~ s!^http://!https://!;
return $path;
}
# Check for single file
elsif ($path !~ m!^$webpath!){
$path =~ s!^/+!!;
$path = "https://${server}${webpath}/$path";
}
# Check for full path
elsif ($path =~ m!^$webpath!){
$path = "https://${server}${path}";
}
return $path;
}
=item sort_ip()
Used by C<sort {}> calls to sort by IP octet.
If passed two hashes, will sort on the key C<ip> or C<remote_ip>.
=cut
sub sort_ip {
my $aval = shift || $::a || $HTML::Mason::Commands::a || $a;
my $bval = shift || $::b || $HTML::Mason::Commands::b || $b;
$aval = $aval->{ip} || $aval->{remote_ip} if ref($aval) eq 'HASH';
$bval = $bval->{ip} || $bval->{remote_ip} if ref($bval) eq 'HASH';
my ($a1,$a2,$a3,$a4) = split(/\./,$aval);
my ($b1,$b2,$b3,$b4) = split(/\./,$bval);
return 1 if ($a1 > $b1);
return -1 if ($a1 < $b1);
return 1 if ($a2 > $b2);
return -1 if ($a2 < $b2);
return 1 if ($a3 > $b3);
return -1 if ($a3 < $b3);
return 1 if ($a4 > $b4);
return -1 if ($a4 < $b4);
return 0;
}
=item sort_port()
Used by C<sort()> - Sort port names with the following formatting types :
A5
5
FastEthernet0/1