2 # Open some ports on the firewall. Exit statuses are :
3 # 0 - Nothing needed to be done
4 # 1 - Given ports were opened up
5 # 2 - IPtables is not installed or supported
6 # 3 - No firewall is active
7 # 4 - Could not apply configuration
11 $ENV{'WEBMIN_CONFIG'} = "/etc/webmin";
12 $ENV{'WEBMIN_VAR'} = "/var/webmin";
13 if ($0 =~ /^(.*\/)[^\/]+$/) {
16 require './firewall-lib.pl';
17 if ($module_name ne 'firewall') {
18 print STDERR "Command must be run with full path\n";
23 if ($ARGV[0] eq "--no-apply") {
28 print STDERR "Missing ports to open\n";
32 if ($p !~ /^\d+$/ && $p !~ /^\d+:\d+$/ && $p !~ /^\d+(,\d+)*$/) {
33 print STDERR "Port $p must be number or start:end range\n";
38 # Check IPtables support
39 if (&foreign_installed($module_name, 1) != 2) {
40 print STDERR "IPtables is not available\n";
44 # Check if any rules exist
45 @tables = &get_iptables_save();
47 print STDERR "No IPtables rules exist yet\n";
50 ($filter) = grep { $_->{'name'} eq 'filter' } @tables;
52 print STDERR "No IPtables filter table found\n";
55 elsif (!@{$filter->{'rules'}}) {
56 print STDERR "No IPtables rules found in filter table\n";
60 # Check if any rules are active
61 @livetables = &get_iptables_save("iptables-save 2>/dev/null |");
62 ($livefilter) = grep { $_->{'name'} eq 'filter' } @livetables;
65 PORT: foreach $p (@ARGV) {
66 # For each port, find existing rules
67 print STDERR "Checking for port $p ..\n";
68 foreach $r (@{$filter->{'rules'}}) {
69 if ($r->{'chain'} eq 'INPUT' &&
70 $r->{'j'} && $r->{'j'}->[1] eq 'ACCEPT' &&
71 $r->{'p'} && $r->{'p'}->[0] eq '' &&
72 $r->{'p'}->[1] eq 'tcp') {
73 # Found tcp rule .. check ports
76 if ($r->{'dports'} && $r->{'dports'}->[0] eq '') {
77 push(@rports, split(/,/, $r->{'dports'}->[1]));
78 $rrange = $r->{'dports'}->[1];
80 if ($r->{'dport'} && $r->{'dport'}->[0] eq '') {
81 ($s, $e) = split(":", $r->{'dport'}->[1]);
83 push(@rports, ($s .. $e));
88 $rrange = $r->{'dport'}->[1];
90 if (&indexof($p, @rports) >= 0 ||
92 print STDERR ".. already allowed\n";
98 # Add a rule at the top for this port
99 $r = { 'chain' => 'INPUT',
100 'm' => [ [ "", "tcp" ] ],
101 'p' => [ "", "tcp" ],
102 'j' => [ "", 'ACCEPT' ] };
104 $r->{'dports'} = [ "", $p ];
105 push(@{$r->{'m'}}, [ "", "multiport" ]);
108 $r->{'dport'} = [ "", $p ];
110 unshift(@{$filter->{'rules'}}, $r);
115 # Added some rules .. save them
116 &run_before_command();
117 &lock_file($iptables_save_file);
118 &save_table($filter);
119 &unlock_file($iptables_save_file);
120 &run_after_command();
122 print STDERR "Opened ports ",join(" ", @added),"\n";
126 if (!$no_apply && $livefilter && @{$livefilter->{'rules'}}) {
127 $err = &apply_configuration();
129 print "Failed to apply configuration : $err\n";
133 print "Applied configuration successfully\n";
136 &webmin_log("openports", undef, undef, { 'ports' => \@added });
140 print STDERR "All ports are already open\n";