blib/lib/Net/ISP/Balance.pm untested

filter: Statementstmt 0.0% 0 / 733 Branchbran 0.0% 0 / 184 Conditioncond 0.0% 0 / 144 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 98 Podpod 0.0% 0 / 93 totaltotal 0.0% 0 / 1252 CC 93 SCAR 27.6
CC
93
Cov
0%
_iptables_add_rule
56.0
_execute_rules_files
56.0
restore_routing_and_firewall
42.0
CRAP 15.9
1 package Net::ISP::Balance;
2  
3 use strict;
4 use Fcntl ':flock';
5 use Carp 'croak','carp';
6 use Data::Dumper;
7  
8 eval 'use Net::Netmask';
9 eval 'use Net::ISP::Balance::ConfigData';
10  
11 our $VERSION = '1.20';
12  
13 =head1 NAME
14  
15 Net::ISP::Balance - Support load balancing across multiple internet service providers
16  
17 =head1 SYNOPSIS
18  
19 use Net::ISP::Balance;
20  
21 # initialize the module with its configuration file
22 my $bal = Net::ISP::Balance->new('/etc/network/balance.conf');
23  
24 $bal->verbose(1); # verbosely print routing and firewall
25 # commands to STDERR before running them.
26 $bal->echo_only(1); # echo commands to STDOUT; don't execute them.
27  
28 # mark the balanced services that are up
29 $bal->up('CABLE','DSL','SATELLITE');
30  
31 # write out routing and firewall commands
32 $bal->set_routes_and_firewall();
33  
34 # write out a forwarding rule
35 $bal->forward(80 => '192.168.10.35'); # forward web requests to this host
36  
37 # write out an arbitrary routing rule
38 $bal->ip_route('add 192.168.100.1 dev eth0 src 198.162.1.14');
39  
40 # write out an arbitrary iptables rule
41 $bal->iptables('-A INCOMING -p tcp --dport 6000 -j REJECT');
42  
43 # get information about all services
44 my @s = $bal->service_names;
45 for my $s (@s) {
46 print $bal->dev($s);
47 print $bal->ip($s);
48 print $bal->gw($s);
49 print $bal->net($s);
50 print $bal->fwmark($s);
51 print $bal->table($s);
52 print $bal->running($s);
53 print $bal->weight($s);
54 }
55  
56 =cut
57  
58 use Carp;
59  
60 =head1 USAGE
61  
62 This library supports load_balance.pl, a script to load-balance a home
63 network across two or more Internet Service Providers (ISP). The
64 load_balance.pl script can be found in the bin subdirectory of this
65 distribution. Installation and configuration instructions can be found
66 at http://lstein.github.io/Net-ISP-Balance/.
67  
68 =head1 CONFIGURATION FILE
69  
70 This module reads a configuration file with the following format:
71  
72 #service device role ping-ip weight
73 CABLE eth0 isp 173.194.43.95 1
74 DSL ppp0 isp 173.194.43.95 1
75 LAN1 eth1 lan
76 LAN2 eth2 lan
77 LAN3 eth3 lan
78  
79  
80 The first column is a service name that is used to bring up or down
81 the needed routes and firewall rules.
82  
83 The second column is the name of the network interface device that
84 connects to that service.
85  
86 The third column is either "isp" or "lan". There may be any number of
87 these. The script will firewall traffic passing through any of the
88 ISPs, and will load balance traffic among them. Traffic can flow
89 freely among any of the interfaces marked as belonging to a LAN.
90  
91 The fourth column is the IP address of a host that can be periodically
92 pinged to test the integrity of each ISP connection. If too many pings
93 failed, the service will be brought down and all traffic routed
94 through the remaining ISP(s). The service will continue to be
95 monitored and will be brought up when it is once again working. Choose
96 a host that is not likely to go offline for reasons unrelated to your
97 network connectivity, such as google.com, or the ISP's web site. If
98 this column is absent, then the host will default to www.google.ca,
99 which is probably not what you want!
100  
101 The fifth column (optional) is a weight to assign to the service, and
102 is only valid for ISP rows. If weights are equal, traffic will be
103 apportioned evenly between the two routes. Increase a weight to favor
104 one ISP over the others. For example, if "CABLE" has a weight of 2 and
105 "DSL" has a weight of 1, then twice as much traffic will flow through
106 the CABLE service. If this column is omitted, then equal weights are
107 assumed.
108  
109 If this package is running on a single Internet-connected host, not a
110 router, then do not include a "lan" line.
111  
112 In addition to the main table, there are several configuration options
113 that follow the format "configuration_name=value":
114  
115 =over 4
116  
117 =item forwarding_group=<space-delimited list of services>
118  
119 The forwarding_group configuration option defines a set of services
120 that the router is allowed to forward packets among. Provide a
121 space-delimited set of service names or one or more of the
122 abbreviations ":isp" and ":lan". ":isp" is an abbreviation for all
123 ISP services, while ":lan" is an abbreviation for all LAN services. So
124 for example, the two configuration lines below will allow forwarding
125 of packets between LAN1, LAN2, LAN3 and both ISPs. LAN4 will be
126 granted access to both ISPs but won't be able to exchange packets with
127 LANs 1 through 3:
128  
129 forwarding_group=LAN1 LAN2 LAN3 :isp
130 forwarding_group=LAN4 :isp
131  
132 If no forwarding_group options are defined, then the router will
133 forward packets among all LANs and ISP interfaces. It is equivalent to
134 this:
135  
136 forwarding_group=:lan :isp
137  
138 =item warn_email=<email address>
139  
140 Warn_email provides an email address to send notification messages to
141 if the status of a link changes (goes down, or comes back up). You
142 must have the "mail" program installed and configured for this to
143 work.
144  
145 =item interval_ms=<integer>
146  
147 Indicates how often to check the ping host for each ISP.
148  
149 =item min_packet_loss=<integer>
150  
151 =item max_packet_loss=<integer>
152  
153 These define the minimum and maximum packet losses required to declare
154 a link up or down.
155  
156 =item min_successive_pkts_rcvd=<integer>
157  
158 =item max_successive_pkts_recvd=<integer>
159  
160 These define the minimum and maximum numbers of
161 successively-transmitted pings that must be returned in order to
162 declare a link up or down.
163  
164 =item long_down_time=<integer>
165  
166 This is a value in seconds after a service that has gone down is
167 considered to have been down for a long time. You may optionally run a
168 series of shell scripts when this has occurred (see below).
169  
170 =back
171  
172 =head1 FREQUENTLY-USED METHODS
173  
174 Here are the class methods for this module that can be called on the
175 class name.
176  
177 =head2 $bal = Net::ISP::Balance->new('/path/to/config_file.conf');
178  
179 Creates a new balancer object.
180  
181 The first optional argument is the balancer configuration file, which
182 defaults to /etc/network/balance.conf on Ubuntu/Debian-derived
183 systems, and /etc/sysconfig/network-scripts/balance.conf on
184 RedHat/CentOS-derived systems. From hereon, we'll refer to the base of
185 the various configuration files as $ETC_NETWORK.
186  
187 =cut
188  
189 sub new {
190 my $class = shift;
191 my ($conf,%options) = @_;
192 $conf ||= $class->default_conf_file;
193 $conf && -r $conf || croak 'Must provide a readable configuration file path';
194 my $self = bless {
195 verbose => 0,
196 echo_only => 0,
197 services => {},
198 rules_directory => $class->default_rules_directory,
199 lsm_conf_file => $class->default_lsm_conf_file,
200 lsm_scripts_dir => $class->default_lsm_scripts_dir,
201 bal_conf_file => $conf,
202 keep_custom_chains => 1,
203 dummy_data => $options{dummy_test_data},
204 dev_lookup_retries => $options{dev_lookup_retries},
205 dev_lookup_retry_delay => $options{dev_lookup_retry_delay},
206 },ref $class || $class;
207  
208 $self->_parse_configuration_file($conf);
209  
210 # Instead of potentially timing out on new(), we collect information on all
211 # interfaces that are currently up. We do this again with the timeout before
212 # actually changing the routing table, when it is critical that all interfaces
213 # be configured.
214 # $self->_collect_interfaces_retry(); # try to collect interfaces over 10 seconds
215 my %ifs;
216 $self->_collect_interfaces(\%ifs);
217 $self->{services} = \%ifs;
218  
219 return $self;
220 }
221  
222 =head2 $bal->set_routes_and_firewall
223  
224 Once the Balance objecty is created, call set_routes_and_firewall() to
225 configure the routing tables and firewall for load balancing. These
226 rules will either be executed on the system, or printed to standard
227 output as a series of shell script commands if echo_only() is set to
228 true.
229  
230 The routing tables and firewall rules are based on the configuration
231 described in $ETC_NETWORK/balance.conf. You may add custom routes and
232 rules by creating files in $ETC_NETWORK/balance/routes and
233 $ETC_NETWORK/balance/firewall. The former contains a series of files
234 or perl scripts that define additional routing rules. The latter
235 contains files or perl scripts that define additional firewall rules.
236  
237 Files located in $ETC_NETWORK/balance/pre-run will be executed AFTER
238 load_balance.pl has cleared the routing table and firewall, but before
239 it has emitted any any route/firewall commands. Files located in
240 in $ETC_NETWORK/balance/post-run will be run after load_balance.pl is
241 finished.
242  
243 Any files you put into these directories will be read in alphabetic
244 order and added to the routes and/or firewall rules emitted by the
245 load balancing script.Contained in this directory are subdirectories named "routes" and
246 "firewall". The former contains a series of files or perl scripts that
247 define additional routing rules. The latter contains files or perl
248 scripts that define additional firewall rules.
249  
250 Note that files ending in ~ or starting with # are treated as autosave files
251 and ignored.
252  
253 A typical routing rules file will look like the example shown
254 below.
255  
256 # file: /etc/network/balance/01.my_routes
257 ip route add 192.168.100.1 dev eth0 src 198.162.1.14
258 ip route add 192.168.1.0/24 dev eth2 src 10.0.0.4
259  
260 Each line will be sent to the shell, and it is intended (but not
261 required) that these be calls to the "ip" command. General shell
262 scripting constructs are not allowed here.
263  
264 A typical firewall rules file will look like the example shown here:
265  
266 # file: /etc/network/firewall/01.my_firewall_rules
267  
268 # accept incoming telnet connections to the router
269 iptable -A INPUT -p tcp --syn --dport telnet -j ACCEPT
270  
271 # masquerade connections to the DSL modem's control interface
272 iptables -t nat -A POSTROUTING -o eth2 -j MASQUERADE
273  
274 You may also insert routing and firewall rules via fragments of Perl
275 code, which is convenient because you don't have to hard-code any
276 network addresses and can make use of a variety of shortcuts. To do
277 this, simply end the file's name with .pl and make it executable.
278  
279 Here's an example that defines a series of port forwarding rules for
280 incoming connections:
281  
282 # file: /etc/network/firewall/02.forwardings.pl
283  
284 $B->forward(80 => '192.168.10.35'); # forward port 80 to internal web server
285 $B->forward(443=> '192.168.10.35'); # forward port 443 to
286 $B->forward(23 => '192.168.10.35:22'); # forward port 23 to ssh on web sever
287  
288 The main thing to know is that on entry to the script the global
289 variable $B will contain an initialized instance of a
290 Net::ISP::Balance object. You may then make method calls on this
291 object to emit firewall and routing rules.
292  
293 A typical routing rules file will look like the example shown
294 below.
295  
296 # file: /etc/network/balance/01.my_routes
297 ip route add 192.168.100.1 dev eth0 src 198.162.1.14
298 ip route add 192.168.1.0/24 dev eth2 src 10.0.0.4
299  
300 Each line will be sent to the shell, and it is intended (but not
301 required) that these be calls to the "ip" command. General shell
302 scripting constructs are not allowed here.
303  
304 A typical firewall rules file will look like the example shown here:
305  
306 # file: /etc/network/firewall/01.my_firewall_rules
307  
308 # accept incoming telnet connections to the router
309 iptable -A INPUT -p tcp --syn --dport telnet -j ACCEPT
310  
311 # masquerade connections to the DSL modem's control interface
312 iptables -t nat -A POSTROUTING -o eth2 -j MASQUERADE
313  
314 You may also insert routing and firewall rules via fragments of Perl
315 code, which is convenient because you don't have to hard-code any
316 network addresses and can make use of a variety of shortcuts. To do
317 this, simply end the file's name with .pl and make it executable.
318  
319 Here's an example that defines a series of port forwarding rules for
320 incoming connections:
321  
322 # file: /etc/network/firewall/02.forwardings.pl
323  
324 $B->forward(80 => '192.168.10.35'); # forward port 80 to internal web server
325 $B->forward(443=> '192.168.10.35'); # forward port 443 to
326 $B->forward(23 => '192.168.10.35:22'); # forward port 23 to ssh on web sever
327  
328 The main thing to know is that on entry to the script the global
329 variable $B will contain an initialized instance of a
330 Net::ISP::Balance object. You may then make method calls on this
331 object to emit firewall and routing rules.
332  
333 =cut
334  
335 sub set_routes_and_firewall {
336 my $self = shift;
337  
338 $self->save_routing_and_firewall();
339  
340 # first disable forwarding and clear the routing and firewall tables
341 $self->enable_forwarding(0);
342 $self->_initialize_routes();
343 $self->_initialize_firewall();
344 $self->pre_run_rules();
345 $self->_collect_interfaces_retry();
346 if ($self->isp_services) {
347 $self->set_routes();
348 $self->set_firewall();
349 $self->enable_forwarding(1);
350 $self->post_run_rules();
351 } else {
352 warn "No ISP services seem to be up. Restoring routing tables and firewall.\n";
353 $self->restore_routing_and_firewall() unless $self->echo_only;
354 return;
355 }
356 }
357  
358 sub save_routing_and_firewall {
359 my $self = shift;
360  
361 $self->{stored_routes} = [];
362 $self->{stored_rules} = '';
363 $self->{stored_firewall} = '';
364  
365 open my $f,"ip route show table all|" or die $!; # binary
366 while (<$f>) {
367 chomp;
368 next if /unreachable/;
369 next if /proto none/;
370 unshift @{$self->{stored_routes}},$_;
371 }
372 close $f;
373  
374 open $f,"ip rule show|" or die $!; # text
375 while (<$f>) {
376 $self->{stored_rules} .= $_;
377 }
378 close $f;
379  
380 open $f,"iptables-save|" or die $!; # text
381 while (<$f>) {
382 $self->{stored_firewall} .= $_;
383 }
384 close $f;
385 }
386  
387 sub restore_routing_and_firewall {
388 my $self = shift;
389  
390 $self->_initialize_routes();
391 if ($self->{stored_routes}) {
392 for (@{$self->{stored_routes}}) {
393 $self->ip_route("add $_");
394 }
395 }
396  
397 if ($self->{stored_rules}) {
398 my @rules = split "\n",$self->{stored_rules};
399 for my $r (@rules) {
400 my ($priority,$rule) = $r =~ /^(\d+):\s*(.+)/;
401 next if $priority == 32766; # these are created by _initialize!
402 next if $priority == 32767;
403 $self->ip_rule('add',$rule,"priority $priority");
404 }
405 }
406  
407 if ($self->{stored_firewall}) {
408 open my $f,"|iptables-restore" or die $!;
409 print $f $self->{stored_firewall};
410 close $f;
411 }
412 }
413  
414 =head2 $verbose = $bal->verbose([boolean]);
415  
416 sub bal_conf_file { my $self = shift; my $d = $self->{bal_conf_file};
417 $self->{bal_conf_file} = shift if @_; $d; } Get/set verbosity of
418 the module. If verbose is true, then firewall and routing rules
419 will be echoed to STDERR before being executed on the system.
420  
421 =cut
422  
423 sub verbose {
424 my $self = shift;
425 my $d = $self->{verbose};
426 $self->{verbose} = shift if @_;
427 $d;
428 }
429  
430 =head2 $echo = $bal->echo_only([boolean]);
431  
432 Get/set the echo_only flag. If this is true (default false), then
433 routing and firewall rules will be printed to STDOUT rathar than being
434 executed.
435  
436 =cut
437  
438 sub echo_only {
439 my $self = shift;
440 my $d = $self->{echo_only};
441 $self->{echo_only} = shift if @_;
442 $d;
443 }
444  
445 =head2 $retries = $bal->dev_lookup_retries([$retries])
446  
447 Get/set the number of times the library will try to look up an interface
448 that is not up or does not have an IP address. Default is 10
449  
450 =cut
451  
452 sub dev_lookup_retries {
453 my $self = shift;
454 my $d = $self->{dev_lookup_retries} || 10;
455 $self->{dev_lookup_retries} = shift if @_;
456 $d;
457 }
458  
459 =head2 $seconds = $bal->dev_lookup_retry_delay([$seconds])
460  
461 Get/set the number of seconds between retries when an interface is not up
462 or is missing an IP address. Default is 1.
463  
464 =cut
465  
466 sub dev_lookup_retry_delay {
467 my $self = shift;
468 my $d = $self->{dev_lookup_retry_delay} || 1;
469 $self->{dev_lookup_retry_delay} = shift if @_;
470 $d;
471 }
472  
473 =head2 $boolean = $bal->keep_custom_chains([boolean]);
474  
475 Get/set the keep_custom_chains flag. If this is true (default), then
476 any custom iptables chains, such as those created by miniunpnpd or
477 fail2ban, will be restored after execution of the firewall rules. If
478 false, then these rules were be flushed.
479  
480 =cut
481  
482 sub keep_custom_chains {
483 my $self = shift;
484 my $d = $self->{keep_custom_chains};
485 $self->{keep_custom_chains} = shift if @_;
486 $d;
487 }
488  
489 =head2 $result_code = $bal->sh(@args)
490  
491 Pass @args to the shell for execution. If echo_only() is set to true,
492 the command will not be executed, but instead be printed to standard
493 output.
494  
495 Example:
496  
497 $bal->sh('ip rule flush');
498  
499 The result code is the same as CORE::system().
500  
501 =cut
502  
503 sub sh {
504 my $self = shift;
505 my @args = @_;
506 my $arg = join ' ',@args;
507 chomp($arg);
508 carp $arg if $self->verbose;
509 if ($self->echo_only) {
510 $arg .= "\n";
511 print $arg;
512 } else {
513 system $arg;
514 }
515 }
516  
517 =head2 $bal->iptables(@args)
518  
519 Invoke sh() to call "iptables @args".
520  
521 Example:
522  
523 $bal->iptables('-A OUTPUT -o eth0 -j DROP');
524  
525 You may pass an array reference to iptables(), in which case iptables
526 is called on each member of the array in turn.
527  
528 Example:
529  
530 $bal->iptables(['-P OUTPUT DROP',
531 '-P INPUT DROP',
532 '-P FORWARD DROP']);
533  
534 Note that the method keeps track of rules; if you try to enter the
535 same iptables rule more than once the redundant ones will be ignored.
536  
537 =cut
538  
539 my %seen_rule;
540  
541 sub iptables {
542 my $self = shift;
543 if (ref $_[0] eq 'ARRAY') {
544 $seen_rule{$_}++ || $self->sh('iptables',$_) foreach @{$_[0]};
545 } else {
546 $seen_rule{"@_"}++ || $self->sh('iptables',@_)
547 }
548 }
549  
550 sub _iptables_add_rule {
551 my $self = shift;
552 my ($operation,$chain,$table,@args) = @_;
553 croak "You must provide a chain name" unless $chain;
554 my $op = $operation eq 'append' ? '-A'
555 :$operation eq 'delete' ? '-D'
556 :$operation eq 'check ' ? '-C'
557 :$operation eq 'insert' ? '-I'
558 :'-A';
559
560 my $command = '';
561 $command .= "-t $table " if $table;
562 $command .= "$op $chain ";
563 $command .= $self->_process_iptable_options(@args);
564 $self->iptables($command);
565 }
566  
567 sub iptables_append {
568 my $self = shift;
569 my ($table,$chain,@args) = @_;
570 $self->_iptables_add_rule('append',$table,$chain,@args);
571 }
572  
573 sub iptables_delete {
574 my $self = shift;
575 my ($table,$chain,@args) = @_;
576 $self->_iptables_add_rule('delete',$table,$chain,@args);
577 }
578  
579 sub iptables_check {
580 my $self = shift;
581 my ($table,$chain,@args) = @_;
582 $self->_iptables_add_rule('check',$table,$chain,@args);
583 }
584  
585 sub iptables_insert {
586 my $self = shift;
587 my ($table,$chain,@args) = @_;
588 $self->_iptables_add_rule('insert',$table,$chain,@args);
589 }
590  
591 =head2 $bal->firewall_rule($chain,$table,@args)
592  
593 Issue an iptables firewall rule.
594  
595 $chain -- The chain to apply the rule to, e.g. "INPUT".
596
597 $table -- The table to apply the rule to, e.g. "nat". Undef defaults to
598 the standard "filter" table.
599  
600 @args -- The other arguments to pass to iptables.
601  
602 Here is a typical example of blocking incoming connections to port 25:
603  
604 $bal->firewall_rule(INPUT=>undef,-p=>'tcp',-dport=>25,-j=>'REJECT');
605  
606 This will issue the following command:
607  
608 iptables -A INPUT -p tcp --dport 25 -j REJECT
609  
610 The default operation is to append the rule to the chain using
611 -A. This can be changed by passing $bal->firewall_op() any of the
612 strings "append", "delete", "insert" or "check". Subsequent calls to
613 firewall_rule() will return commands for the indicated function:
614  
615 $bal->firewall_op('delete');
616 $bal->firewall_rule(INPUT=>undef,-p=>'tcp',-dport=>25,-j=>'REJECT');
617 # gives iptables -A INPUT -p tcp --dport 25 -j REJECT
618  
619 If you want to apply a series of deletes and then revert to the
620 original append behavior, then it is easiest to localize the hash key
621 "firewall_op":
622  
623 {
624 local $bal->{firewall_op} = 'delete';
625 $bal->firewall_rule(INPUT=>undef,-dport=>25,-j=>'ACCEPT');
626 $bal->firewall_rule(INPUT->undef,-dport=>80,-j=>'ACCEPT');
627 }
628
629 $bal->firewall_rule(INPUT=>undef,-dport=>25,-j=>'DROP');
630 $bal->firewall_rule(INPUT=>undef,-dport=>80,-j=>'DROP');
631  
632 =cut
633  
634 sub firewall_rule {
635 my $self = shift;
636 my ($chain,$table,@args) = @_;
637 my $operation = $self->firewall_op();
638 $self->_iptables_add_rule($operation,$chain,$table,@args);
639 }
640  
641 sub firewall_op {
642 my $self = shift;
643 if (@_) {
644 $self->{firewall_op} = shift;
645 return;
646 }
647 my $d = $self->{firewall_op} || 'append';
648 return $d;
649 }
650  
651 =head2 $bal->force_route($service_or_device,@selectors)
652  
653 The force_route() method issues iptables commands that will force
654 certain traffic to travel over a particular ISP service or network
655 device. This is useful, for example, when one of your ISPs acts as
656 your e-mail relay and only accepts connections from the IP address
657 it assigns.
658  
659 $service_or_device is the symbolic name of an ISP service
660 (e.g. "CABLE") or a network device that a service is attached to
661 (e.g. "eth0").
662  
663 @selectors are a series of options that will be passed to
664 iptables to select the routing of packets. For example, to forward all
665 outgoing mail (destined to port 25) to the "CABLE" ISP, you would
666 write:
667  
668 $bal->force_route('CABLE','-p'=>'tcp','--syn','--dport'=>25);
669  
670 @selectors is a series of optional arguments that will be passed to
671 iptables on the command line. They will simply be space-separated, and
672 so the following is equivalent to the previous example:
673  
674 $bal->force_route('CABLE','-p tcp --syn --dport 25');
675  
676 Bare arguments that begin with a leading hyphen and are followed by
677 two or more alphanumeric characters are automatically converted into
678 double-hyphen arguments. This allows you to simplify commands
679 slightly. The following is equivalent to the previous examples:
680  
681 $bal->force_route('CABLE',-p=>'tcp',-syn,-dport=>25);
682  
683 You can delete force_route rules by setting firewall_op() to 'delete':
684  
685 $bal->firewall_op('delete');
686 $bal->force_route('CABLE',-p=>'tcp',-syn,-dport=>25);
687  
688 =cut
689  
690 sub force_route {
691 my $self = shift;
692 my ($service_or_device,@selectors) = @_;
693
694 my $service = $self->_service_or_device($service_or_device)
695 or croak "did not recognize $service_or_device as a service or a device";
696  
697 my $dest = $self->mark_table($service);
698 my $selectors = $self->_process_iptable_options(@selectors);
699 $self->firewall_rule(PREROUTING=>'mangle',$selectors,-j=>$dest);
700 }
701  
702 =head2 $bal->add_route($address => $device, [$masquerade])
703  
704 This method is used to create routing and firewall rules for a network
705 that isn't mentioned in balance.conf. This may be necessary to route
706 to VPNs and/or to the control interfaces of attached modems.
707  
708 The first argument is the network address in CIDR format,
709 e.g. '192.168.2.0/24'. The second is the network interface that the
710 network can be accessed via. The third, optional, argument is a
711 boolean. If true, then firewall rules will be set up to masquerade
712 from the LAN into the attached network.
713  
714 Note that this is pretty limited. If you want to do anything more
715 sophisticated you're better off setting the routes and firewall rules
716 manually.
717  
718 =cut
719  
720 sub add_route {
721 my $self = shift;
722 my ($network,$device,$masquerade) = @_;
723 $network && $device or croak "usage: add_network(\$network,\$device,[\$masquerade])";
724 # add the route to our main table
725 $self->ip_route("add $network dev $device");
726 # add the route to each outgoing table
727 $self->ip_route("add $network dev $device table $_") for map {$self->table($_)} $self->isp_services;
728
729 # create appropriate firewall rules for the network
730 {
731 local $self->{firewall_op} = 'insert';
732 $self->firewall_rule(OUTPUT => undef,
733 -o => $device,
734 -d => $network,
735 -j => 'ACCEPT');
736 $self->firewall_rule(INPUT => undef,
737 -i => $device,
738 -s => $network,
739 -j => 'ACCEPT');
740 $self->firewall_rule(FORWARD => undef,
741 -i => $self->dev($_),
742 -s => $self->net($_),
743 -o => $device,
744 -d => $network,
745 -j => 'ACCEPT') for $self->lan_services;
746 $self->firewall_rule(FORWARD => undef,
747 -i => $device,
748 -s => $network,
749 -o => $self->dev($_),
750 -d => $self->net($_),
751 -j => 'ACCEPT') for $self->lan_services;
752 }
753 if ($masquerade) {
754 $self->firewall_rule(POSTROUTING=>'nat',
755 -d => $network,
756 -o => $device,
757 -j => 'MASQUERADE');
758 }
759 }
760  
761 sub _process_iptable_options {
762 my $self = shift;
763 my @opt = @_;
764 foreach (@opt) {
765 $_ = "-$_" if /^-\w{2,}/; # add an extra hyphen to -arguments
766 $_ =~ quotemeta($_);
767 }
768 return join ' ',@opt;
769 }
770  
771 sub _mark {
772 my $self = shift;
773 my $service = shift;
774 return "MARK-${service}";
775 }
776  
777 =head2 $table_name = $bal->mark_table($service)
778  
779 This returns the iptables table name for connections marked for output
780 on a particular ISP service. The name is simply the word "MARK-"
781 appended to the service name. For example, for a service named "DSL",
782 the corresponding firewall table will be named "MARK-DSL".
783  
784 =cut
785  
786 sub mark_table { shift->_mark(shift) }
787  
788 sub _service_or_device {
789 my $self = shift;
790 my $sod = shift;
791 return $sod if $self->dev($sod);
792 # otherwise try looking for devices
793 my %dev2s = map {$self->dev($_) => $_} $self->service_names;
794 return $dev2s{$sod};
795 }
796  
797 =head2 $bal->forward($incoming_port,$destination_host,@protocols)
798  
799 This method emits appropriate port/host forwarding rules using DNAT
800 address translation. The destination host can be specified using
801 either of these forms:
802  
803 192.168.100.1 # forward to same port as incoming
804 192.168.100.1:8080 # forward to a different port on host
805  
806 Protocols are one or more of 'tcp','udp'. If omitted defaults to tcp.
807  
808 Examples:
809
810 $bal->forward(80 => '192.168.100.1');
811 $bal->forward(80 => '192.168.100.1:8080','tcp');
812  
813 =cut
814  
815 sub forward {
816 my $self = shift;
817 my ($port,$host,@protocols) = @_;
818 @protocols = ('tcp') unless @protocols;
819  
820 my ($dhost,$dport) = split ':',$host;
821 $dhost ||= $host;
822 $dport ||= $port;
823  
824 my @dev = map {$self->dev($_)} $self->isp_services;
825  
826 for my $dev (@dev) {
827 for my $protocol (@protocols) {
828 $self->iptables("-t nat -A PREROUTING -i $dev -p $protocol --dport $port -j DNAT --to-destination $host");
829 for my $lan ($self->lan_services) {
830 my $landev = $self->dev($lan);
831 my $lannet = $self->net($lan);
832 my $lanip = $self->ip($lan);
833 my $syn = $protocol eq 'tcp' ? '--syn' : '';
834 $self->iptables("-A FORWARD -p $protocol -o $landev $syn -d $dhost --dport $dport -j ACCEPT");
835 }
836 }
837 }
838 }
839  
840 =head2 $bal->forward_with_snat($incoming_port,$destination_host,@protocols)
841  
842 This method is the same as forward(), except that it also does source
843 NATing from LAN-based requests to make the request appear to have come
844 from the router. This is used when you expose a server, such as a web
845 server, to the internet, but you also need to access the server from
846 machines on the LAN. Use this if you find that the service is visible
847 from outside the LAN but not inside the LAN.
848  
849 Examples:
850  
851 $bal->forward_with_snat(80 => '192.168.100.1');
852 $bal->forward_with_snat(80 => '192.168.100.1:8080','tcp');
853  
854  
855 =cut
856  
857 sub forward_with_snat {
858 my $self = shift;
859 my ($port,$host,@protocols) = @_;
860  
861 @protocols = ('tcp') unless @protocols;
862  
863 my ($dhost,$dport) = split ':',$host;
864 $dhost ||= $host;
865 $dport ||= $port;
866  
867 for my $protocol (@protocols) {
868 for my $svc ($self->isp_services) {
869 my $external_ip = $self->ip($svc);
870 $self->iptables("-t nat -A PREROUTING -d $external_ip -p $protocol --dport $port -j DNAT --to-destination $host");
871 }
872  
873 for my $lan ($self->lan_services) {
874 my $lannet = $self->net($lan);
875 $self->iptables("-t nat -A POSTROUTING -s $lannet -p $protocol --dport $port -d $host -j MASQUERADE");
876 }
877  
878 $self->iptables("-A FORWARD -p $protocol --dport $port -d $host -j ACCEPT");
879  
880 }
881  
882 }
883  
884 =head2 $bal->ip_route(@args)
885  
886 Shortcut for $bal->sh('ip route',@args);
887  
888 =cut
889  
890 sub ip_route {shift->sh('ip','route',@_)}
891  
892 =head2 $bal->ip_rule(@args)
893  
894 Shortcut for $bal->sh('ip rule',@args);
895  
896 =cut
897  
898 sub ip_rule {shift->sh('ip','rule',@_)}
899  
900 =head2 $verbose = $bal->iptables_verbose([boolean])
901  
902 Makes iptables send an incredible amount of debugging information to
903 syslog.
904  
905 =cut
906  
907 sub iptables_verbose {
908 my $self = shift;
909 my $d = $self->{iptables_verbose};
910 $self->{iptables_verbose} = shift if @_;
911 $d;
912 }
913  
914 =head1 QUERYING THE CONFIGURATION
915  
916 These methods allow you to get information about the Net::ISP::Balance
917 object's configuration, including settings and other characteristics
918 of the various network interfaces.
919  
920 =head2 @names = $bal->service_names
921  
922 Return the list of service names defined in balance.conf.
923  
924 =cut
925  
926 sub service_names {
927 my $self = shift;
928 my $s = $self->services;
929 return sort keys %$s;
930 }
931  
932 =head2 @names = $bal->isp_services
933  
934 Return list of service names that correspond to load-balanced ISPs.
935  
936 =cut
937  
938 sub isp_services {
939 my $self = shift;
940 my @n = $self->service_names;
941 return grep {$self->role($_) eq 'isp'} @n;
942 }
943  
944 =head2 @names = $bal->lan_services
945  
946 Return list of service names that correspond to lans.
947  
948  
949 =cut
950  
951 sub lan_services {
952 my $self = shift;
953 my @n = $self->service_names;
954 return grep {$self->role($_) eq 'lan'} @n;
955 }
956  
957 =head2 $state = $bal->event($service => $new_state)
958  
959 Record a transition between "up" and "down" for a named service. The
960 first argument is the name of the ISP service that has changed,
961 e.g. "CABLE". The second argument is either "up" or "down".
962  
963 The method returns a hashref in which the keys are the ISP service names
964 and the values are one of 'up' or 'down'.
965  
966 The persistent state information is stored in /var/lib/lsm/ under a
967 series of files named <SERVICE_NAME>.state.
968  
969 =cut
970  
971 sub event {
972 my $self = shift;
973  
974 if (@_) {
975 my ($svc,$new_state) = @_;
976 $new_state =~ /^(up|down)$/ or croak "state must be 'up' or down'";
977 $self->dev($svc) or croak "service '$svc' is unknown";
978 my $file = "/var/lib/lsm/${svc}.state";
979 my $mode = -e $file ? '+<' : '>';
980 open my $fh,$mode,$file or croak "Couldn't open $file mode $mode: $!";
981 flock $fh,LOCK_EX;
982 truncate $fh,0;
983 seek($fh,0,0);
984 print $fh $new_state;
985 close $fh;
986 }
987  
988 my %state;
989 for my $svc ($self->isp_services) {
990 my $file = "/var/lib/lsm/${svc}.state";
991 if (open my $fh,'<',$file) {
992 flock $fh,LOCK_SH;
993 my $state = <$fh>;
994 close $fh;
995 $state{$svc}=$state;
996 } else {
997 $state{$svc}='unknown';
998 }
999 }
1000 my @up = grep {$state{$_} eq 'up'} keys %state;
1001 $self->up(@up);
1002 return \%state;
1003 }
1004  
1005 =head2 $bal->run_eventd(@args)
1006  
1007 Runs scripts in response to lsm events. The scripts are stored in
1008 directories named after the events, e.g.:
1009  
1010 /etc/network/lsm/up.d/*
1011 /etc/network/lsm/down.d/*
1012 /etc/network/lsm/long_down.d/*
1013  
1014 Scripts are called with the following arguments:
1015  
1016 0. STATE
1017 1. SERVICE NAME
1018 2. CHECKIP
1019 3. DEVICE
1020 4. WARN_EMAIL
1021 5. REPLIED
1022 6. WAITING
1023 7. TIMEOUT
1024 8. REPLY_LATE
1025 9. CONS_RCVD
1026 10. CONS_WAIT
1027 11. CONS_MISS
1028 12. AVG_RTT
1029 13. SRCIP
1030 14. PREVSTATE
1031 15. TIMESTAMP
1032  
1033 =cut
1034  
1035 sub run_eventd {
1036 my $self = shift;
1037 my @args = @_;
1038 my $state = $args[0];
1039 my $dir = $self->lsm_scripts_dir();
1040 my $dird = "$dir/${state}.d";
1041 my @files = sort glob("$dird/*");
1042 for my $script (sort @files) {
1043 next if $script =~ /^#/;
1044 next if $script =~ /~$/;
1045 next unless -f $script && -x _;
1046 system $script,@args;
1047 }
1048 }
1049  
1050 =head2 @up = $bal->up(@up_services)
1051  
1052 Get or set the list of ISP interfaces that are currently active and
1053 should be used for balancing.
1054  
1055 =cut
1056  
1057 sub up {
1058 my $self = shift;
1059 $self->{up} = \@_ if @_;
1060 unless ($self->{up}) { # initialize with running services
1061 my @svc = grep {$self->running($_)} $self->isp_services;
1062 $self->{up} = \@svc;
1063 }
1064 my @up = @{$self->{up}};
1065 return @up;
1066 }
1067  
1068 =head2 $services = $bal->services
1069  
1070 Return a hash containing the configuration information for each
1071 service. The keys are the service names. Here's an example:
1072  
1073 {
1074 0 HASH(0x91201e8)
1075 'CABLE' => HASH(0x9170500)
1076 'dev' => 'eth0'
1077 'fwmark' => 2
1078 'gw' => '191.3.88.1'
1079 'ip' => '191.3.88.152'
1080 'net' => '191.3.88.128/27'
1081 'ping' => 'www.google.ca'
1082 'role' => 'isp'
1083 'running' => 1
1084 'table' => 2
1085 'DSL' => HASH(0x9113e00)
1086 'dev' => 'ppp0'
1087 'fwmark' => 1
1088 'gw' => '112.211.154.198'
1089 'ip' => '11.120.199.108'
1090 'net' => '112.211.154.198/32'
1091 'ping' => 'www.google.ca'
1092 'role' => 'isp'
1093 'running' => 1
1094 'table' => 1
1095 'LAN' => HASH(0x913ce58)
1096 'dev' => 'eth1'
1097 'fwmark' => undef
1098 'gw' => '192.168.10.1'
1099 'ip' => '192.168.10.1'
1100 'net' => '192.168.10.0/24'
1101 'ping' => ''
1102 'role' => 'lan'
1103 'running' => 1
1104 }
1105  
1106 =cut
1107  
1108 sub services { return shift->{services} }
1109  
1110 =head2 $service = $bal->service('CABLE')
1111  
1112 Return the subhash describing the single named service (see services()
1113 above).
1114  
1115 =cut
1116  
1117 sub service {
1118 shift->{services}{shift()};
1119 }
1120  
1121 =head2 $dev = $bal->dev('CABLE')
1122  
1123 =head2 $ip = $bal->ip('CABLE')
1124  
1125 =head2 $gateway = $bal->gw('CABLE')
1126  
1127 =head2 $network = $bal->net('CABLE')
1128  
1129 =head2 $role = $bal->role('CABLE')
1130  
1131 =head2 $running = $bal->running('CABLE')
1132  
1133 =head2 $mark_number = $bal->fwmark('CABLE')
1134  
1135 =head2 $routing_table_number = $bal->table('CABLE')
1136  
1137 =head2 $ping_dest = $bal->ping('CABLE')
1138  
1139 These methods pull out the named information from the configuration
1140 data. fwmark() returns a small integer that will be used for marking
1141 connections for routing through one of the ISP connections when an
1142 outgoing connection originates on the LAN and is routed through the
1143 router. table() returns a small integer corresponding to a routing
1144 table used to route connections originating on the router itself.
1145  
1146 =cut
1147  
1148 sub dev { shift->_service_field(shift,'dev') }
1149 sub ip { shift->_service_field(shift,'ip') }
1150 sub gw { shift->_service_field(shift,'gw') }
1151 sub net { shift->_service_field(shift,'net') }
1152 sub running { shift->_service_field(shift,'running') }
1153 sub role { shift->_service_field(shift,'role') }
1154 sub fwmark { shift->_service_field(shift,'fwmark') }
1155 sub table { shift->_service_field(shift,'table') }
1156 sub ping { shift->_service_field(shift,'ping') }
1157 sub weight { shift->_service_field(shift,'weight') }
1158  
1159 sub _service_field {
1160 my $self = shift;
1161 my ($service,$field) = @_;
1162 my $s = $self->{services}{$service} or return;
1163 $s->{$field};
1164 }
1165  
1166 sub _save_custom_chains {
1167 my $self = shift;
1168 for my $table ('filter','nat','mangle') {
1169 my @rules = split("\n",`sudo iptables -t $table -S`);
1170 # find custom chains
1171 my $mine = 'MARK-|REJECTPERM|DROPGEN|DROPINVAL|DROPPERM|DROPSPOOF|DROPFLOOD|DEBUG';
1172 my @chains = grep {!/^-N ($mine)/} grep {/^-N (\S+)/} @rules or next;
1173 s/^-N // foreach @chains;
1174 my $chains = join '|',map {quotemeta($_)} @chains;
1175 my @targets = grep {/-(?:j|A|I) (?:$chains)/} @rules;
1176 $self->{_custom_chains}{$table} = [(map {"-N $_"} @chains),@targets];
1177 }
1178 }
1179  
1180 sub _restore_custom_chains {
1181 my $self = shift;
1182 my $custom_chains = $self->{_custom_chains} or return;
1183 for my $table (keys %{$custom_chains}) {
1184 my @rules = @{$custom_chains->{$table}} or next;
1185 $self->iptables([map {"-t $table $_"} @rules]);
1186 }
1187 }
1188  
1189 =head1 FILES AND PATHS
1190  
1191 These are methods that determine where Net::ISP::Balance finds its
1192 configuration files.
1193  
1194 =head2 $path = Net::ISP::Balance->install_etc
1195  
1196 Returns the path to where the network configuration files reside on
1197 this system, e.g. /etc/network. Note that this only knows about
1198 Ubuntu/Debian-style network configuration files in /etc/network, and
1199 RedHat/CentOS network configuration files in
1200 /etc/sysconfig/network-scripts.
1201  
1202 =cut
1203  
1204 sub install_etc {
1205 my $self = shift;
1206 return '/etc/network' if -d '/etc/network';
1207 return '/etc/sysconfig/network-scripts' if -d '/etc/sysconfig/network-scripts';
1208 return '/etc';
1209 }
1210  
1211 =head2 $file = Net::ISP::Balance->default_conf_file
1212  
1213 Returns the path to the default configuration file,
1214 $ETC_NETWORK/balance.conf.
1215  
1216 =cut
1217  
1218 sub default_conf_file {
1219 my $self = shift;
1220 return $self->install_etc.'/balance.conf';
1221 }
1222  
1223 =head2 $dir = Net::ISP::Balance->default_rules_directory
1224  
1225 Returns the path to the directory where the additional router and
1226 firewall rules are stored. On Ubuntu-Debian-derived systems, this is
1227 /etc/network/balance/. On RedHat/CentOS systems, this is
1228 /etc/sysconfig/network-scripts/balance/.
1229  
1230 =cut
1231  
1232 sub default_rules_directory {
1233 my $self = shift;
1234 return $self->install_etc."/balance";
1235 }
1236  
1237 =head2 $file = Net::ISP::Balance->default_lsm_conf_file
1238  
1239 Returns the path to the place where we should store lsm.conf, the file
1240 used to configure the lsm (link status monitor) application.
1241  
1242 On Ubuntu/Debian-derived systems, this will be the file
1243 /etc/network/lsm.conf. On RedHad/CentOS-derived systems, this will be
1244 /etc/sysconfig/network-scripts/lsm.conf.
1245  
1246 =cut
1247  
1248 sub default_lsm_conf_file {
1249 my $self = shift;
1250 return $self->install_etc."/balance/lsm.conf";
1251 }
1252  
1253 =head2 $dir = Net::ISP::Balance->default_lsm_scripts_dir
1254  
1255 Returns the path to the place where lsm stores its helper scripts. On
1256 Ubuntu/Debian-derived systems, this will be the directory
1257 /etc/network/lsm/. On RedHad/CentOS-derived systems, this will be
1258 /etc/sysconfig/network-scripts/lsm/.
1259  
1260 =cut
1261  
1262 sub default_lsm_scripts_dir {
1263 my $self = shift;
1264 return $self->install_etc.'/balance/lsm';
1265 }
1266  
1267 =head2 $file = $bal->bal_conf_file([$new_file])
1268  
1269 Get/set the main configuration file path, balance.conf.
1270  
1271 =cut
1272  
1273 sub bal_conf_file {
1274 my $self = shift;
1275 my $d = $self->{bal_conf_file};
1276 $self->{bal_conf_file} = shift if @_;
1277 $d;
1278 }
1279  
1280 =head2 $dir = $bal->rules_directory([$new_rules_directory])
1281  
1282 Get/set the route and firewall rules directory.
1283  
1284 =cut
1285  
1286 sub rules_directory {
1287 my $self = shift;
1288 my $d = $self->{rules_directory};
1289 $self->{rules_directory} = shift if @_;
1290 $d;
1291 }
1292  
1293 =head2 $file = $bal->lsm_conf_file([$new_conffile])
1294  
1295 Get/set the path to the lsm configuration file.
1296  
1297 =cut
1298  
1299 sub lsm_conf_file {
1300 my $self = shift;
1301 my $d = $self->{lsm_conf_file};
1302 $self->{lsm_conf_file} = shift if @_;
1303 $d;
1304 }
1305  
1306 =head2 $dir = $bal->lsm_scripts_dir([$new_dir])
1307  
1308 Get/set the path to the lsm scripts directory.
1309  
1310 =cut
1311  
1312 sub lsm_scripts_dir {
1313 my $self = shift;
1314 my $d = $self->{lsm_scripts_dir};
1315 $self->{lsm_scripts_dir} = shift if @_;
1316 $d;
1317 }
1318  
1319 =head1 INFREQUENTLY-USED METHODS
1320  
1321 These are methods that are used internally, but may be useful to
1322 applications developers.
1323  
1324 =head2 $lsm_config_text = $bal->lsm_config_file(-warn_email=>'root@localhost')
1325  
1326 This method creates the text used to create the lsm.conf configuration
1327 file. Pass it a series of -name=>value pairs to incorporate into the
1328 file.
1329  
1330 Possible switches and their defaults are:
1331  
1332 -checkip 127.0.0.1
1333 -eventscript /etc/network/load_balance.pl
1334 -long_down_eventscript /etc/network/load_balance.pl
1335 -notifyscript /etc/network/balance/lsm/default_script
1336 -max_packet_loss 15
1337 -max_successive_pkts_lost 7
1338 -min_packet_loss 5
1339 -min_successive_pkts_rcvd 10
1340 -interval_ms 1000
1341 -timeout_ms 1000
1342 -warn_email root
1343 -check_arp 0
1344 -sourceip <autodiscovered>
1345 -device <autodiscovered> -eventscript => $balance_script,
1346 -ttl 0 <use system value>
1347 -status 2 <no assumptions>
1348 -debug 8 <moderate verbosity from scale of 0 to 100>
1349  
1350 =cut
1351  
1352 sub lsm_config_text {
1353 my $self = shift;
1354 my %args = @_;
1355 my $scripts_dir = $self->lsm_scripts_dir;
1356 my $balance_script = $self->install_etc."/load_balance.pl";
1357 my %defaults = (
1358 -checkip => '127.0.0.1',
1359 -debug => 8,
1360 -eventscript => $balance_script,
1361 -long_down_eventscript => $balance_script,
1362 -notifyscript => "$scripts_dir/default_script",
1363 -max_packet_loss => 15,
1364 -max_successive_pkts_lost => 7,
1365 -min_packet_loss => 5,
1366 -min_successive_pkts_rcvd => 10,
1367 -interval_ms => 1000,
1368 -timeout_ms => 1000,
1369 -long_down_time => 120,
1370 -warn_email => 'root',
1371 -check_arp => 0,
1372 -sourceip => undef,
1373 -device => undef,
1374 -ttl => 0,
1375 -status => 2
1376 );
1377 %defaults = (%defaults,%{$self->{lsm_config}},%args); # %args supersedes what's in %defaults
1378  
1379 my $result = "# This file is autogenerated by load_balancer.pl when it first runs.\n";
1380 $result .= "# Do not edit directly. Instead edit /etc/network/balance.conf.\n\n";
1381 $result .= "debug=$defaults{-debug}\n\n";
1382 delete $defaults{-debug};
1383  
1384 $result .= "defaults {\n";
1385 $result .= " name=defaults\n";
1386 for my $option (sort keys %defaults) {
1387 (my $o = $option) =~ s/^-//;
1388 $defaults{$option} = '' unless defined $defaults{$option}; # avoid uninit var warnings
1389 $result .= " $o=$defaults{$option}\n";
1390 }
1391 $result .= "}\n\n";
1392  
1393 for my $svc ($self->isp_services) {
1394 my $device = $self->dev($svc);
1395 my $src_ip = $self->ip($svc);
1396 my $ping = $self->ping($svc);
1397 $result .= "connection {\n";
1398 $result .= " name=$svc\n";
1399 $result .= " device=$device\n";
1400 $result .= " checkip=$ping\n";
1401 $result .= "}\n\n";
1402 }
1403  
1404 return $result;
1405 }
1406  
1407 sub _parse_configuration_file {
1408 my $self = shift;
1409 my $path = shift;
1410 my (%services,%lsm_options,@forwarding_group);
1411 open my $f,$path or die "Could not open $path: $!";
1412  
1413 while (<$f>) {
1414 chomp;
1415 next if /^\s*#/;
1416 if (/^forwarding_group\s*=\s*(.+)$/) { # routing group
1417 my @group = split /\s+/,$1 or next;
1418 push @forwarding_group,\@group;
1419 next;
1420 }
1421 if (/^(\w+)\s*=\s*(.*)$/) { # lsm config
1422 $lsm_options{"-${1}"} = $2;
1423 next;
1424 }
1425 my ($service,$device,$role,$ping_dest,$weight) = split /\s+/;
1426 next unless $service && $device && $role;
1427 croak "load_balance.conf line $.: A service can not be named 'up' or 'down'"
1428 if $service=~/^(up|down)$/;
1429 $services{$service}{dev} = $device;
1430 $services{$service}{role} = $role;
1431 $services{$service}{ping} = $ping_dest || 'www.google.ca';
1432 $services{$service}{weight}= $weight || 1;
1433 }
1434 close $f;
1435 $self->{svc_config} = \%services;
1436 $self->{lsm_config} = \%lsm_options;
1437 $self->{forwarding_groups} = \@forwarding_group;
1438 }
1439  
1440 sub _collect_interfaces_retry {
1441 my $self = shift;
1442 my $retries = $self->dev_lookup_retries;
1443 my $wait = $self->dev_lookup_retry_delay;
1444 my %ifs;
1445 for (1..$retries) {
1446 delete $self->{_interface_info_cache}; # don't want to cache partial results
1447 last if $self->_collect_interfaces(\%ifs);
1448 sleep $wait;
1449 }
1450 $self->{services} = \%ifs;
1451 }
1452  
1453 sub _collect_interfaces {
1454 my $self = shift;
1455 my $interface_info = shift;
1456  
1457 my $s = $self->{svc_config} or return;
1458 my $i = $self->interface_info;
1459  
1460 # print STDERR Dumper($i);
1461  
1462 # map devices to services
1463 my %devs;
1464 for my $svc (keys %$s) {
1465 my $vdev = $s->{$svc}{dev};
1466 $devs{$vdev}=$svc;
1467 }
1468  
1469 my $counter = 0;
1470 my $configured_interfaces = 0;
1471  
1472 for my $vdev (sort keys %devs) {
1473 my $info = $i->{$vdev} or next;
1474 my $dev = $info->{dev};
1475 my $svc = $devs{$vdev};
1476 my $role = $s->{$svc}{role};
1477 $configured_interfaces++;
1478  
1479 # copy into hash passed to us
1480 $interface_info->{$svc} = {
1481 dev => $dev, # otherwise, iptables will croak!!!
1482 running => $info->{running},
1483 gw => $info->{gw},
1484 net => $info->{net},
1485 ip => $info->{ip},
1486 fwmark => $role eq 'isp' ? ++$counter : undef,
1487 table => $role eq 'isp' ? $counter : undef,
1488 role => $role,
1489 ping => $s->{$svc}{ping},
1490 weight => $s->{$svc}{weight},
1491 }
1492 }
1493 return $configured_interfaces >= keys %devs;
1494 }
1495  
1496 =head2 $if_hash = $bal->interface_info
1497  
1498 =head2 $if_hash = Net::ISP::Balance->interface_info
1499  
1500 This method returns a hashref containing information about each of the
1501 network interfaces found on the system (independent of those mentioned
1502 in the configuration file). It may be called as a class method or an
1503 instance method.
1504  
1505 Each key in the hash is the name of a (virtual) interface device. The
1506 values are hashrefs with the following keys:
1507  
1508 key value
1509 --- -----
1510 dev name of the underlying physical device (usually same as vdev)
1511 running boolean, true if interface is running
1512 gw gateway, if present
1513 net subnet in xxx.xxx.xxx.xxx/xx
1514  
1515 =cut
1516  
1517  
1518 sub interface_info {
1519 my $self = shift;
1520 return $self->{_interface_info_cache}
1521 if ref $self && exists $self->{_interface_info_cache};
1522
1523 my %results; # keyed by interface device
1524  
1525 # LOGIC TO DEAL WITH VIRTUAL INTERFACES
1526 # 1. From _ip_addr_show get all the inet XXX.XXX.XXX.XXX lines and calculate
1527 # corresponding network and virtual interface.
1528 # 2. Record mapping of network to virtual interface in a hash (%vif)
1529 # 3. When going through the routes, replace $dev with virtual interface name
1530 # 4. In (keys %devs) loop, create an inner loop for each inet found and replace
1531 # device with correct virtual device.
1532  
1533 # get interfaces with assigned addresses
1534 my $a = $self->_ip_addr_show;
1535 my (undef,@ifs) = split /^\d+: /m,$a;
1536 chomp(@ifs);
1537 my %ifs = map {
1538 my ($dev,$config) = split(/: /,$_,2);
1539 $dev =~ s/\@.+$//; # get rid of bonding master information
1540 ($dev,$config);
1541 } @ifs;
1542  
1543 # find virtual interfaces
1544 my (%vnet,%vif);
1545 for my $dev (keys %ifs) {
1546 my $info = $ifs{$dev};
1547 while ($info =~ /inet (\d+\.\d+\.\d+\.\d+)(?:\/(\d+))?.+?(\S+)$/mg) {
1548 my ($addr,$bits,$vdev) = ($1,$2,$3);
1549 $addr or next;
1550 $bits ||= 32;
1551 my ($peer) = $info =~ /peer\s+(\d+\.\d+\.\d+\.\d+)/;
1552 my $block = Net::Netmask->new2("$addr/$bits");
1553 $vnet{$dev}{"$block"} = $vdev;
1554 $vif{$dev}{$vdev}{block} = $block;
1555 $vif{$dev}{$vdev}{addr} = $addr;
1556 }
1557 }
1558  
1559 # get existing routes
1560 my (%gws,%nets);
1561 my $r = $self->_ip_route_show;
1562 my @routes = split /^(?!\s)/m,$r;
1563 chomp(@routes);
1564 foreach (@routes) {
1565 while (/(\S+)\s+via\s+(\S+)\s+dev\s+(\S+)/g) {
1566 my ($net,$gateway,$dev) = ($1,$2,$3);
1567 ($net) = /^(\S+)/ if $net eq 'nexthop';
1568 my $vdev = $vnet{$dev}{$net} || $dev;
1569 $nets{$vdev} = $net unless $net eq 'default';
1570 $gws{$vdev} = $gateway;
1571 }
1572 }
1573 for my $dev (keys %ifs) {
1574 my $info = $ifs{$dev};
1575 my $running = $info =~ /[<,]UP[,>]/;
1576 my ($peer) = $info =~ /peer\s+(\d+\.\d+\.\d+\.\d+)/;
1577 for my $vdev (keys %{$vif{$dev}}) {
1578 my $addr = $vif{$dev}{$vdev}{addr};
1579 my $block = $vif{$dev}{$vdev}{block};
1580 my $net = $nets{$dev} || ($peer?"$peer/32":undef) || "$block";
1581 my $gw = $gws{$dev} || $peer || $self->_dhcp_gateway($dev) || $block->nth(1);
1582  
1583 # copy into hash passed to us
1584 $results{$vdev} = {
1585 dev => $dev, # otherwise, iptables will croak!!!
1586 running => $running,
1587 gw => $gw,
1588 net => $net,
1589 ip => $addr,
1590 }
1591 }
1592 }
1593  
1594 $self->{_interface_info_cache} = \%results if ref $self;
1595 return \%results;
1596 }
1597  
1598 sub _ip_addr_show {
1599 my $self = shift;
1600 return eval{$self->{dummy_data}{"ip_addr_show"}} || `ip addr show`;
1601 }
1602  
1603 sub _ip_route_show {
1604 my $self = shift;
1605 return eval{$self->{dummy_data}{"ip_route_show"}} || `ip route show all`;
1606 }
1607  
1608 # This subroutine is called for dhcp-assigned IP addresses to try to
1609 # get the gateway. It is used for those unusual cases in which the gateway
1610 # is NOT the first IP address in the net block.
1611 # In versions 1.05 and older, we tried to recover this information on static
1612 # interfaces by reading /etc/network/interfaces as well, but the file location was too
1613 # unpredictable across different Linux distros.
1614 sub _dhcp_gateway {
1615 my $self = shift;
1616 my $dev = shift;
1617 my $fh = $self->_open_dhclient_leases($dev) or return;
1618 my ($gw);
1619 while (<$fh>) {
1620 chomp;
1621 $gw = $1 if /option routers (\S+)[,;]/;
1622 }
1623 return $gw;
1624 }
1625  
1626 sub _open_dhclient_leases {
1627 my $self = shift;
1628 my $device = shift;
1629 if (my $dummy = eval{$self->{dummy_data}{"leases_$device"}}) {
1630 open my $fh,'<',\$dummy or die $!;
1631 return $fh;
1632 }
1633 my $leases = $self->_find_dhclient_leases($device) or return;
1634 open my $fh,$leases or die "Can't open $leases: $!";
1635 return $fh;
1636 }
1637  
1638 sub _find_dhclient_leases {
1639 my $self = shift;
1640 my $device = shift;
1641 my @locations = ('/var/lib/NetworkManager','/var/lib/dhcp','/var/lib/dhclient');
1642 for my $l (@locations) {
1643 my @matches = glob("$l/dhclient*$device.lease*");
1644 next unless @matches;
1645 return $matches[0];
1646 }
1647 return;
1648 }
1649  
1650  
1651  
1652 #################################### here are the routing rules ###################
1653  
1654 =head2 $bal->set_routes()
1655  
1656 This method is called by set_routes_and_firewall() to emit the rules
1657 needed to create the load balancing routing tables.
1658  
1659 =cut
1660  
1661 sub set_routes {
1662 my $self = shift;
1663 $self->routing_rules();
1664 $self->local_routing_rules();
1665 }
1666  
1667 =head2 $bal->set_firewall
1668  
1669 This method is called by set_routes_and_firewall() to emit the rules
1670 needed to create the balancing firewall.
1671  
1672 =cut
1673  
1674 sub set_firewall {
1675 my $self = shift;
1676 if ($self->keep_custom_chains) {
1677 $self->_save_custom_chains;
1678 $self->base_fw_rules();
1679 $self->_restore_custom_chains;
1680 } else {
1681 $self->base_fw_rules();
1682 }
1683  
1684 $self->balancing_fw_rules();
1685 $self->sanity_fw_rules();
1686 $self->nat_fw_rules();
1687 $self->local_fw_rules();
1688 }
1689  
1690  
1691 =head2 $bal->enable_forwarding($boolean)
1692  
1693 =cut
1694  
1695 sub enable_forwarding {
1696 my $self = shift;
1697 my $enable = $_[0] ? 1 : 0;
1698 $self->sh("echo $enable > /proc/sys/net/ipv4/ip_forward");
1699 }
1700 =head2 $bal->routing_rules()
1701  
1702 This method is called by set_routes() to emit the rules
1703 needed to create the routing rules.
1704  
1705 =cut
1706  
1707 sub routing_rules {
1708 my $self = shift;
1709 # main table
1710 $self->ip_route("add ",$self->net($_),'dev',$self->dev($_),'src',$self->ip($_)) foreach $self->service_names;
1711 $self->_create_default_route();
1712 $self->_create_service_routing_tables();
1713 }
1714  
1715 sub _initialize_routes {
1716 my $self = shift;
1717 $self->sh(<<END);
1718 ip route flush all
1719 ip rule flush
1720 ip rule add from all lookup main pref 32766
1721 ip rule add from all lookup default pref 32767
1722 END
1723 ;
1724  
1725 $self->ip_route("flush table ",$self->table($_)) foreach $self->isp_services;
1726 }
1727  
1728 sub _create_default_route {
1729 my $self = shift;
1730 my $D = shift;
1731  
1732 my @up = $self->up;
1733  
1734 # create multipath route
1735 if (@up > 1) { # multipath
1736 print STDERR "# setting multipath default gw\n" if $self->verbose;
1737 # EG
1738 # ip route add default scope global nexthop via 192.168.10.1 dev eth0 weight 1 \
1739 # nexthop via 192.168.11.1 dev eth1 weight 1
1740 my $hops = '';
1741 for my $svc (@up) {
1742 my $gw = $self->gw($svc) or next;
1743 my $dev = $self->dev($svc) or next;
1744 my $weight = $self->weight($svc) or next;
1745 $hops .= "nexthop via $gw dev $dev weight $weight ";
1746 }
1747 die "no valid gateways!" unless $hops;
1748 $self->ip_route("add default scope global $hops");
1749 }
1750  
1751 else {
1752 print STDERR "# setting single default route via $up[0]n" if $self->verbose;
1753 $self->ip_route("add default via",$self->gw($up[0]),'dev',$self->dev($up[0]));
1754 }
1755  
1756 }
1757  
1758 sub _create_service_routing_tables {
1759 my $self = shift;
1760  
1761 for my $svc ($self->isp_services) {
1762 print STDERR "# creating routing table for $svc\n" if $self->verbose;
1763 $self->ip_route('add table',$self->table($svc),'default dev',$self->dev($svc),'via',$self->gw($svc));
1764 for my $s ($self->service_names) {
1765 $self->ip_route('add table',$self->table($svc),$self->net($s),'dev',$self->dev($s),'src',$self->ip($s));
1766 }
1767 $self->ip_rule('add from',$self->ip($svc),'table',$self->table($svc));
1768 $self->ip_rule('add fwmark',$self->fwmark($svc),'table',$self->table($svc));
1769 }
1770 }
1771  
1772 =head2 $bal->local_routing_rules()
1773  
1774 This method is called by set_routes() to process the fules and emit
1775 the commands contained in the customized route files located in
1776 $ETC_DIR/balance/routes.
1777  
1778 =cut
1779  
1780 sub local_routing_rules {
1781 my $self = shift;
1782 my $dir = $self->rules_directory;
1783 my @files = sort glob("$dir/routes/*");
1784 $self->_execute_rules_files(@files);
1785 }
1786  
1787 =head2 $bal->local_fw_rules()
1788  
1789 This method is called by set_firewall() to process the fules and emit
1790 the commands contained in the customized route files located in
1791 $ETC_DIR/balance/firewall.
1792  
1793 =cut
1794  
1795 sub local_fw_rules {
1796 my $self = shift;
1797 my $dir = $self->rules_directory;
1798 my @files = sort glob("$dir/firewall/*");
1799 $self->_execute_rules_files(@files);
1800 }
1801  
1802 =head2 $bal->pre_run_rules()
1803  
1804 This method is called by set_routes_and_firewall() to process the fules and emit
1805 the commands contained in the customized route files located in
1806 $ETC_DIR/balance/pre-run.
1807  
1808 =cut
1809  
1810 sub pre_run_rules {
1811 my $self = shift;
1812 my $dir = $self->rules_directory;
1813 my @files = sort glob("$dir/pre-run/*");
1814 $self->_execute_rules_files(@files);
1815 }
1816  
1817 =head2 $bal->post_run_rules()
1818  
1819 This method is called by set__routes_andfirewall() to process the
1820 fules and emit the commands contained in the customized route files
1821 located in $ETC_DIR/balance/post-run.
1822  
1823 =cut
1824  
1825 sub post_run_rules {
1826 my $self = shift;
1827 my $dir = $self->rules_directory;
1828 my @files = sort glob("$dir/post-run/*");
1829 $self->_execute_rules_files(@files);
1830 }
1831  
1832  
1833 sub _execute_rules_files {
1834 my $self = shift;
1835 my @files = @_;
1836  
1837 for my $f (@files) {
1838 next if $f =~ /~$/; # ignore emacs backup files
1839 next if $f =~ /^#/; # ignore autosave files
1840 print STDERR "# executing contents of $f\n" if $self->verbose;
1841 $self->sh("## Including rules from $f ##\n");
1842 next if $f =~ /(~|\.bak)$/ or $f=~/^#/;
1843  
1844 if ($f =~ /\.pl$/) { # perl script
1845 our $B = $self;
1846 do $f;
1847 warn $@ if $@;
1848 } else {
1849 open my $fh,$f or die "Couldn't open $f: $!";
1850 $self->sh($_) while <$fh>;
1851 close $fh;
1852 }
1853 $self->sh("## Finished $f ##\n");
1854 }
1855 }
1856  
1857 #########################
1858 # firewall rules
1859 #########################
1860  
1861 sub _initialize_firewall {
1862 my $self = shift;
1863 $self->sh(<<END);
1864 iptables -F
1865 iptables -X
1866 iptables -t nat -F
1867 iptables -t nat -X
1868 iptables -t mangle -F
1869 iptables -t mangle -X
1870 END
1871 }
1872  
1873 =head2 $bal->base_fw_rules()
1874  
1875 This method is called by set_firewall() to set up basic firewall
1876 rules, including default rules and reporting.
1877  
1878 =cut
1879  
1880 sub base_fw_rules {
1881 my $self = shift;
1882 $self->sh(<<END);
1883 iptables -P INPUT DROP
1884 iptables -P OUTPUT DROP
1885 iptables -P FORWARD DROP
1886  
1887 iptables -N REJECTPERM
1888 iptables -A REJECTPERM -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "REJECTED: "
1889 iptables -A REJECTPERM -j REJECT --reject-with icmp-net-unreachable
1890  
1891 iptables -N DROPGEN
1892 iptables -A DROPGEN -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "GENERAL: "
1893 iptables -A DROPGEN -j DROP
1894  
1895 iptables -N DROPINVAL
1896 iptables -A DROPINVAL -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "INVALID: "
1897 iptables -A DROPINVAL -j DROP
1898  
1899 iptables -N DROPPERM
1900 iptables -A DROPPERM -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "ACCESS-DENIED: "
1901 iptables -A DROPPERM -j DROP
1902  
1903 iptables -N DROPSPOOF
1904 iptables -A DROPSPOOF -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "DROP-SPOOF: "
1905 iptables -A DROPSPOOF -j DROP
1906  
1907 iptables -N DROPFLOOD
1908 iptables -A DROPFLOOD -m limit --limit 1/minute -j LOG --log-level 4 --log-prefix "DROP-FLOOD: "
1909 iptables -A DROPFLOOD -j DROP
1910  
1911 iptables -N DEBUG
1912 iptables -A DEBUG -j LOG --log-level 3 --log-prefix "DEBUG: "
1913 END
1914 ;
1915 if ($self->iptables_verbose) {
1916 print STDERR " #Setting up debugging logging\n" if $self->verbose;
1917 $self->sh(<<END);
1918 iptables -A INPUT -j LOG --log-prefix "INPUT: "
1919 iptables -A OUTPUT -j LOG --log-prefix "OUTPUT: "
1920 iptables -A FORWARD -j LOG --log-prefix "FORWARD: "
1921 iptables -t nat -A INPUT -j LOG --log-prefix "nat INPUT: "
1922 iptables -t nat -A OUTPUT -j LOG --log-prefix "nat OUTPUT: "
1923 iptables -t nat -A FORWARD -j LOG --log-prefix "nat FORWARD: "
1924 iptables -t nat -A PREROUTING -j LOG --log-prefix "nat PREROUTING: "
1925 iptables -t nat -A POSTROUTING -j LOG --log-prefix "nat POSTROUTING: "
1926 iptables -t mangle -A INPUT -j LOG --log-prefix "mangle INPUT: "
1927 iptables -t mangle -A OUTPUT -j LOG --log-prefix "mangle OUTPUT: "
1928 iptables -t mangle -A FORWARD -j LOG --log-prefix "mangle FORWARD: "
1929 iptables -t mangle -A PREROUTING -j LOG --log-prefix "mangle PRE: "
1930 END
1931 ;
1932 }
1933 }
1934  
1935 =head2 $bal->balancing_fw_rules()
1936  
1937 This method is called by set_firewall() to set up the mangle/fwmark
1938 rules for balancing outgoing connections.
1939  
1940 =cut
1941  
1942 sub balancing_fw_rules {
1943 my $self = shift;
1944  
1945 print STDERR "# balancing FW rules\n" if $self->verbose;
1946  
1947 for my $svc ($self->isp_services) {
1948 my $table = $self->mark_table($svc);
1949 my $mark = $self->fwmark($svc);
1950 next unless defined $mark && defined $table;
1951 $self->sh(<<END);
1952 iptables -t mangle -N $table
1953 iptables -t mangle -A $table -j MARK --set-mark $mark
1954 iptables -t mangle -A $table -j CONNMARK --save-mark
1955 END
1956 }
1957  
1958 my @up = $self->up;
1959  
1960 # packets from LAN
1961 for my $lan ($self->lan_services) {
1962 my $landev = $self->dev($lan);
1963 my $src = $self->net($lan);
1964
1965 if (@up > 1) {
1966 print STDERR "# creating balanced mangling rules\n" if $self->verbose;
1967 my $count = @up;
1968 my $probabilities = $self->_weight_to_probability(\@up);
1969 for my $svc (sort {$probabilities->{$b} <=> $probabilities->{$a}} @up) {
1970 my $table = $self->mark_table($svc);
1971 my $probability = $probabilities->{$svc};
1972 $self->iptables("-t mangle -A PREROUTING -i $landev -s $src -m conntrack --ctstate NEW -m statistic --mode random --probability $probability -j $table");
1973 }
1974 }
1975  
1976 else {
1977 my $svc = $up[0];
1978 print STDERR "# forcing all traffic through $svc\n" if $self->verbose;
1979 my $table = $self->mark_table($svc);
1980 $self->iptables("-t mangle -A PREROUTING -i $landev -s $src -m conntrack --ctstate NEW -j $table");
1981 }
1982  
1983 $self->iptables("-t mangle -A PREROUTING -i $landev -s $src -m conntrack --ctstate ESTABLISHED,RELATED -j CONNMARK --restore-mark");
1984 }
1985  
1986 # inbound packets from WAN
1987 for my $wan ($self->isp_services) {
1988 my $dev = $self->dev($wan);
1989 my $table = $self->mark_table($wan);
1990 my $src = $self->net($wan);
1991 $self->iptables("-t mangle -A PREROUTING -i $dev -m conntrack --ctstate NEW -j $table");
1992 $self->iptables("-t mangle -A PREROUTING -i $dev -m conntrack --ctstate ESTABLISHED,RELATED -j CONNMARK --restore-mark");
1993 }
1994  
1995 }
1996  
1997 sub _weight_to_probability {
1998 my $self = shift;
1999 my $svcs = shift;
2000  
2001 # first turn weights into proportions of the total
2002 my %weights = map {$_ => $self->weight($_)} @$svcs;
2003 my $total = 0;
2004 $total += $_ foreach (values %weights);
2005 my %proportions = map {$_ => $weights{$_}/$total} keys %weights;
2006  
2007 # now turn them into probabilities
2008 my %probabilities;
2009  
2010 my $last = 0;
2011 for (sort {$proportions{$a}<=>$proportions{$b} || $a cmp $b} keys %proportions) {
2012 my $threshold = $proportions{$_}/(1-$last);
2013 $last += $proportions{$_};
2014 $probabilities{$_} = $threshold;
2015 }
2016 return \%probabilities;
2017 }
2018  
2019 =head2 $bal->sanity_fw_rules()
2020  
2021 This is called by set_firewall() to create a sensible series of
2022 firewall rules that seeks to prevent spoofing, flooding, and other
2023 antisocial behavior. It also enables UDP-based network time and domain
2024 name service.
2025  
2026 =cut
2027  
2028 sub sanity_fw_rules {
2029 my $self = shift;
2030  
2031 # if any of the devices are ppp, then we clamp the mss
2032 my @ppp_devices = grep {/ppp\d+/} map {$self->dev($_)} $self->isp_services;
2033 $self->iptables("-t mangle -A POSTROUTING -o $_ -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu")
2034 foreach @ppp_devices;
2035  
2036 # lo is ok
2037 $self->iptables(['-A INPUT -i lo -j ACCEPT',
2038 '-A OUTPUT -o lo -j ACCEPT',
2039 '-A INPUT -d 127.0.0.0/8 -j DROPPERM']);
2040  
2041 # accept continuing foreign traffic
2042 $self->iptables(['-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT',
2043 '-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT',
2044 '-A INPUT -p tcp --tcp-flags SYN,ACK ACK -j ACCEPT',
2045 '-A FORWARD -p tcp --tcp-flags SYN,ACK ACK -j ACCEPT',
2046 '-A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST RST -j ACCEPT'
2047 ]);
2048  
2049 # we allow ICMP echo, but establish flood limits
2050 $self->iptables(['-A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT',
2051 '-A INPUT -p icmp --icmp-type echo-request -j DROPFLOOD']);
2052  
2053 # allowable traffic patterns within the LAN services
2054 for my $lan ($self->lan_services) {
2055 my $dev = $self->dev($lan);
2056 my $net = $self->net($lan);
2057  
2058 # allow unlimited traffic from internal network using legit address
2059 $self->iptables("-A INPUT -i $dev -s $net -j ACCEPT");
2060  
2061 # allow locally-generated output to the LAN on the LANDEV
2062 $self->iptables("-A OUTPUT -o $dev -d $net -j ACCEPT");
2063  
2064 # and allow broadcasts to the lan
2065 $self->iptables("-A OUTPUT -o $dev -d 255.255.255.255/32 -j ACCEPT");
2066  
2067 # any outgoing udp packet is fine with me
2068 $self->iptables("-A OUTPUT -p udp -s $net -j ACCEPT");
2069 }
2070  
2071 # allow appropriate outgoing traffic via the ISPs
2072 # NOTE: we use svc_config here so that we allow outgoing traffic
2073 # on interfaces that might be down
2074 # for my $svc ($self->isp_services) {
2075 # my $ispdev = $self->dev($svc);
2076 # $self->iptables("-A OUTPUT -o $ispdev -j ACCEPT");
2077 # }
2078 for my $svc (keys %{$self->{svc_config}}) {
2079 next unless $self->{svc_config}{$svc}{role} eq 'isp';
2080 my $ispdev = $self->{svc_config}{$svc}{dev};
2081 $self->iptables("-A OUTPUT -o $ispdev -j ACCEPT");
2082 }
2083  
2084 # forwarding rules
2085 $self->_lan_wan_forwarding_rules();
2086 $self->_lan_lan_forwarding_rules();
2087  
2088 # anything else is bizarre and should be dropped
2089 $self->iptables('-A OUTPUT -j DROPSPOOF');
2090 }
2091  
2092 # establish expected traffic patterns between lan(s) and isp interfaces
2093 sub _lan_wan_forwarding_rules {
2094 my $self = shift;
2095  
2096 for my $lan ($self->lan_services) {
2097 my $dev = $self->dev($lan);
2098 my $net = $self->net($lan);
2099  
2100 # lan/wan forwarding
2101 # allow lan/wan forwarding
2102 for my $svc ($self->isp_services) {
2103 my $ispdev = $self->dev($svc);
2104 my $target = $self->_allow_forwarding($lan,$svc) ? 'ACCEPT' : 'REJECTPERM';
2105 $self->iptables("-A FORWARD -i $dev -o $ispdev -s $net -j $target");
2106 }
2107 }
2108 }
2109  
2110 # Allow forwarding between lans
2111 sub _lan_lan_forwarding_rules {
2112 my $self = shift;
2113  
2114 # This generates a very long list of rules if you have multiple lan services, but I think
2115 # it is the most general way to get this right.
2116 my @lans = $self->lan_services;
2117 for (my $i=0;$i<@lans;$i++) {
2118 for (my $j=0;$j<@lans;$j++) {
2119 next if $i == $j;
2120 my $lan1 = $lans[$i];
2121 my $lan2 = $lans[$j];
2122 my $target = $self->_allow_forwarding($lan1,$lan2) ? 'ACCEPT' : 'REJECTPERM';
2123 $self->iptables('-A FORWARD','-i',$self->dev($lan1),'-o',$self->dev($lan2),'-s',$self->net($lan1),'-d',$self->net($lan2),"-j $target");
2124 }
2125 }
2126 }
2127  
2128 sub _allow_forwarding {
2129 my $self = shift;
2130 my ($net_a,$net_b) = @_;
2131 my $forward = $self->_forwarding_groups();
2132 my $key = join ',',sort ($net_a,$net_b);
2133 return $forward->{$key};
2134 }
2135  
2136 # this returns a hashref of service pairs that are allowed to forward packets.
2137 # the keys are service name pairs, in alphabetic order, separated by a comma.
2138 sub _forwarding_groups {
2139 my $self = shift;
2140  
2141 # _forwarding_groups is the processed and normalized version of forwarding_groups
2142 return $self->{_forwarding_groups} if exists $self->{_forwarding_groups};
2143  
2144 my %allowed_pairs;
2145 my $fgs = $self->{forwarding_groups};
2146 unless (@$fgs) {
2147 $fgs = [[':isp',':lan']];
2148 }
2149  
2150 for my $fg (@$fgs) {
2151 my @services = map {
2152 /^:isp$/ ? $self->isp_services
2153 : /^:lan$/ ? $self->lan_services
2154 : $_
2155 } @$fg;
2156  
2157 for (my $i=0;$i<@services-1;$i++) {
2158 for (my $j=$i;$j<@services;$j++) {
2159 my $key = join ',',sort ($services[$i],$services[$j]);
2160 $allowed_pairs{$key}++;
2161 }
2162 }
2163 }
2164 return $self->{_forwarding_groups} = \%allowed_pairs;
2165 }
2166  
2167 =head2 $bal->nat_fw_rules()
2168  
2169 This is called by set_firewall() to set up basic NAT rules for lan traffic over ISP
2170  
2171 =cut
2172  
2173 sub nat_fw_rules {
2174 my $self = shift;
2175 return unless $self->lan_services;
2176 $self->iptables('-t nat -A POSTROUTING -o',$self->dev($_),'-j MASQUERADE')
2177 foreach $self->isp_services;
2178 }
2179  
2180 =head2 $bal->start_lsm()
2181  
2182 Start an lsm process.
2183  
2184 =cut
2185  
2186 sub start_lsm {
2187 my $self = shift;
2188 my $lsm = Net::ISP::Balance::ConfigData->config('lsm_path');
2189 my $lsm_conf = $self->lsm_conf_file;
2190 system "$lsm $lsm_conf /var/run/lsm.pid";
2191 }
2192  
2193 =head2 $bal->signal_lsm($signal)
2194  
2195 Send a signal to a running LSM and return true if successfully
2196 signalled. The signal can be numeric (e.g. 9) or a string ('TERM').
2197  
2198 =cut
2199  
2200 sub signal_lsm {
2201 my $self = shift;
2202 my $signal = shift;
2203 $signal ||= 0;
2204 my $pid;
2205 open my $f,'/var/run/lsm.pid' or return;
2206 chomp($pid = <$f>);
2207 close $f;
2208 return unless $pid =~ /^\d+$/;
2209 return kill($signal=>$pid);
2210 }
2211  
2212  
2213 1;
2214  
2215 =head1 BUGS
2216  
2217 Please report bugs to GitHub: https://github.com/lstein/Net-ISP-Balance.
2218  
2219 =head1 AUTHOR
2220  
2221 Copyright 2014, Lincoln D. Stein (lincoln.stein@gmail.com)
2222  
2223 Senior Principal Investigator,
2224 Ontario Institute for Cancer Research
2225  
2226 =head1 LICENSE
2227  
2228 This package is distributed under the terms of the Perl Artistic
2229 License 2.0. See http://www.perlfoundation.org/artistic_license_2_0.
2230  
2231 =cut
2232  
2233 __END__