use Digest::SHA;
use PVE::INotify;
use PVE::Exception qw(raise raise_param_exc);
-use PVE::JSONSchema qw(get_standard_option);
+use PVE::JSONSchema qw(register_standard_option get_standard_option);
use PVE::Cluster;
use PVE::ProcFSTools;
-use PVE::Tools;
+use PVE::Tools qw($IPV4RE);
use File::Basename;
use File::Path;
use IO::File;
$have_pve_manager = 1;
};
+PVE::JSONSchema::register_format('IPv4orCIDR', \&pve_verify_ipv4_or_cidr);
+sub pve_verify_ipv4_or_cidr {
+ my ($cidr, $noerr) = @_;
+
+ if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
+ return $cidr if Net::IP->new($cidr);
+ return undef if $noerr;
+ die Net::IP::Error() . "\n";
+ }
+ return undef if $noerr;
+ die "value does not look like a valid IP address or CIDR network\n";
+}
+
+PVE::JSONSchema::register_standard_option('ipset-name', {
+ description => "IP set name.",
+ type => 'string',
+ pattern => '[A-Za-z][A-Za-z0-9\-\_]+',
+ minLength => 2,
+ maxLength => 20,
+});
+
+PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => {
+ description => "Log level.",
+ type => 'string',
+ enum => ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
+ optional => 1,
+});
+
+my $security_group_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
+
+PVE::JSONSchema::register_standard_option('pve-security-group-name', {
+ description => "Security Group name.",
+ type => 'string',
+ pattern => $security_group_pattern,
+ minLength => 2,
+ maxLength => 20,
+});
+
my $feature_ipset_nomatch = 0;
eval {
my (undef, undef, $release) = POSIX::uname();
sub parse_address_list {
my ($str) = @_;
- return if $str !~ m/^(\+)(\S+)$/; # ipset ref
+ return if $str =~ m/^(\+)(\S+)$/; # ipset ref
my $count = 0;
my $iprange = 0;
# helper function for API
+sub copy_opject_with_digest {
+ my ($object) = @_;
+
+ my $sha = Digest::SHA->new('sha1');
+
+ my $res = {};
+ foreach my $k (sort keys %$object) {
+ my $v = $object->{$k};
+ next if !defined($v);
+ $res->{$k} = $v;
+ $sha->add($k, ':', $v, "\n");
+ }
+
+ my $digest = $sha->b64digest;
+
+ $res->{digest} = $digest;
+
+ return wantarray ? ($res, $digest) : $res;
+}
+
+sub copy_list_with_digest {
+ my ($list) = @_;
+
+ my $sha = Digest::SHA->new('sha1');
+
+ my $res = [];
+ foreach my $entry (@$list) {
+ my $data = {};
+ foreach my $k (sort keys %$entry) {
+ my $v = $entry->{$k};
+ next if !defined($v);
+ $data->{$k} = $v;
+ $sha->add($k, ':', $v, "\n");
+ }
+ push @$res, $data;
+ }
+
+ my $digest = $sha->b64digest;
+
+ foreach my $entry (@$res) {
+ $entry->{digest} = $digest;
+ }
+
+ return wantarray ? ($res, $digest) : $res;
+}
+
my $rule_properties = {
pos => {
description => "Update rule at position <pos>.",
minimum => 0,
optional => 1,
},
- digest => {
- type => 'string',
- optional => 1,
- maxLength => 27,
- minLength => 27,
- },
+ digest => get_standard_option('pve-config-digest'),
type => {
type => 'string',
optional => 1,
enum => ['in', 'out', 'group'],
},
action => {
+ description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
type => 'string',
optional => 1,
- enum => ['ACCEPT', 'DROP', 'REJECT'],
+ pattern => $security_group_pattern,
+ maxLength => 20,
+ minLength => 2,
},
macro => {
type => 'string',
},
};
-sub cleanup_fw_rule {
- my ($rule, $digest, $pos) = @_;
-
- my $r = {};
-
- foreach my $k (keys %$rule) {
- next if !$rule_properties->{$k};
- my $v = $rule->{$k};
- next if !defined($v);
- $r->{$k} = $v;
- $r->{digest} = $digest;
- $r->{pos} = $pos;
- }
-
- return $r;
-}
-
sub add_rule_properties {
my ($properties) = @_;
raise_param_exc({ type => "security groups not allowed"})
if !$allow_groups;
raise_param_exc({ action => "invalid characters in security group name"})
- if $rule->{action} !~ m/^[A-Za-z0-9_\-]+$/;
+ if $rule->{action} !~ m/^${security_group_pattern}$/;
} else {
raise_param_exc({ type => "unknown rule type '$type'"});
}
push @cmd, "-m iprange --dst-range $dest";
} else {
- push @cmd, "-s $dest";
+ push @cmd, "-d $dest";
}
}
$action .= " --queue-num $1";
}
}
- $action .= " --queue-bypass";
+ $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
}else{
$action = "ACCEPT";
}
# fixme: allow security groups
my $options = $hostfw_conf->{options};
+ my $cluster_options = $cluster_conf->{options};
my $rules = $hostfw_conf->{rules};
+ my $cluster_rules = $cluster_conf->{rules};
# host inbound firewall
my $chain = "PVEFW-HOST-IN";
# we use RETURN because we need to check also tap rules
my $accept_action = 'RETURN';
- foreach my $rule (@$rules) {
+ # add host rules first, so that cluster wide rules can be overwritten
+ foreach my $rule (@$rules, @$cluster_rules) {
next if $rule->{type} ne 'in';
ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
}
# implement input policy
- my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
+ my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
# host outbound firewall
# we use RETURN because we may want to check other thigs later
$accept_action = 'RETURN';
- foreach my $rule (@$rules) {
+ # add host rules first, so that cluster wide rules can be overwritten
+ foreach my $rule (@$rules, @$cluster_rules) {
next if $rule->{type} ne 'out';
ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
}
# implement output policy
- $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
+ $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
die "wrong number of rule elements\n" if scalar(@data) != 3;
die "groups disabled\n" if !$allow_groups;
- die "invalid characters in group name\n" if $action !~ m/^[A-Za-z0-9_\-]+$/;
+ die "invalid characters in group name\n" if $action !~ m/^${security_group_pattern}$/;
} else {
die "unknown rule type '$type'\n";
}
my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
- if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
+ if ($line =~ m/^(enable|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
$opt = lc($1);
$value = int($2);
} elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
$opt = lc($1);
$value = $2 ? lc($3) : '';
- } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
- $opt = lc($1);
- $value = uc($3);
- } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
+ } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
$opt = lc($1);
$value = int($2);
} else {
if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
$opt = lc($1);
$value = int($2);
+ } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
+ $opt = lc($1);
+ $value = uc($3);
} else {
chomp $line;
die "can't parse option '$line'\n"
my $section;
- my $digest = Digest::SHA->new('sha1');
-
while (defined(my $line = <$fh>)) {
- $digest->add($line);
-
next if $line =~ m/^#/;
next if $line =~ m/^\s*$/;
push @{$res->{$section}}, $rule;
}
- $res->{digest} = $digest->b64digest;
-
return $res;
}
my $section;
- my $digest = Digest::SHA->new('sha1');
-
while (defined(my $line = <$fh>)) {
- $digest->add($line);
-
next if $line =~ m/^#/;
next if $line =~ m/^\s*$/;
push @{$res->{$section}}, $rule;
}
-$res->{digest} = $digest->b64digest;
-
return $res;
}
my $section;
my $group;
- my $res = { rules => [], options => {}, groups => {}, ipset => {} };
-
- my $digest = Digest::SHA->new('sha1');
+ my $res = {
+ rules => [],
+ options => {},
+ groups => {},
+ group_comments => {},
+ ipset => {} ,
+ ipset_comments => {},
+ };
while (defined(my $line = <$fh>)) {
- $digest->add($line);
-
next if $line =~ m/^#/;
next if $line =~ m/^\s*$/;
next;
}
- if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
+ if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
$section = 'groups';
$group = lc($1);
+ my $comment = $2;
+ $res->{$section}->{$group} = [];
+ $res->{group_comments}->{$group} = decode('utf8', $comment)
+ if $comment;
next;
}
next;
}
- if ($line =~ m/^\[ipset\s+(\S+)\]\s*$/i) {
+ if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
$section = 'ipset';
$group = lc($1);
+ my $comment = $2;
+ $res->{$section}->{$group} = [];
+ $res->{ipset_comments}->{$group} = decode('utf8', $comment)
+ if $comment;
next;
}
# we can add single line comments to the end of the rule
my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
- $line =~ m/^(\!)?\s*((?:\d+)\.(?:\d+)\.(?:\d+)\.(?:\d+))(?:\/(\d+))?\s*$/;
+ $line =~ m/^(\!)?\s*(\S+)\s*$/;
my $nomatch = $1;
my $cidr = $2;
- $cidr .= "/$3" if defined($3) && $3 != 32;
-
- if (!Net::IP->new($cidr)) {
- my $err = Net::IP::Error();
- warn "$prefix: $cidr - $err\n";
+ $cidr =~ s|/32$||;
+
+ eval { pve_verify_ipv4_or_cidr($cidr); };
+ if (my $err = $@) {
+ warn "$prefix: $cidr - $err";
next;
}
}
}
- $res->{digest} = $digest->b64digest;
return $res;
}
my $raw = '';
foreach my $rule (@$rules) {
- if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
+ if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
$raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
$raw .= uc($rule->{type});
if ($rule->{macro}) {
$raw .= " " . $rule->{action};
}
$raw .= " " . ($rule->{iface} || '-') if $need_iface;
- $raw .= " " . ($rule->{source} || '-');
- $raw .= " " . ($rule->{dest} || '-');
- $raw .= " " . ($rule->{proto} || '-');
- $raw .= " " . ($rule->{dport} || '-');
- $raw .= " " . ($rule->{sport} || '-');
+
+ if ($rule->{type} ne 'group') {
+ $raw .= " " . ($rule->{source} || '-');
+ $raw .= " " . ($rule->{dest} || '-');
+ $raw .= " " . ($rule->{proto} || '-');
+ $raw .= " " . ($rule->{dport} || '-');
+ $raw .= " " . ($rule->{sport} || '-');
+ }
+
$raw .= " # " . encode('utf8', $rule->{comment})
if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
$raw .= "\n";
} else {
- die "implement me '$rule->{type}'";
+ die "unknown rule type '$rule->{type}'";
}
}
my $raw = '';
+ my $nethash = {};
foreach my $entry (@$options) {
+ $nethash->{$entry->{cidr}} = $entry;
+ }
+
+ foreach my $cidr (sort keys %$nethash) {
+ my $entry = $nethash->{$cidr};
my $line = $entry->{nomatch} ? '!' : '';
$line .= $entry->{cidr};
$line .= " # " . encode('utf8', $entry->{comment})
# same as shorewall smurflog.
my $chain = 'PVEFW-smurflog';
+ $pve_std_chains->{$chain} = [];
push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
push @{$pve_std_chains->{$chain}}, "-j DROP";
# same as shorewall logflags action.
$loglevel = get_option_log_level($options, 'tcp_flags_log_level');
$chain = 'PVEFW-logflags';
+ $pve_std_chains->{$chain} = [];
+
# fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
push @{$pve_std_chains->{$chain}}, "-j DROP";
push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
+ # remove duplicates
+ my $nethash = {};
foreach my $entry (@$options) {
- my $cidr = $entry->{cidr};
+ $nethash->{$entry->{cidr}} = $entry;
+ }
+
+ foreach my $cidr (sort keys %$nethash) {
+ my $entry = $nethash->{$cidr};
+
my $cmd = "add $name $cidr";
if ($entry->{nomatch}) {
if ($feature_ipset_nomatch) {
$raw .= &$format_options($options) if scalar(keys %$options);
foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
- $raw .= "[IPSET $ipset]\n\n";
+ if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
+ my $utf8comment = encode('utf8', $comment);
+ $raw .= "[IPSET $ipset] # $utf8comment\n\n";
+ } else {
+ $raw .= "[IPSET $ipset]\n\n";
+ }
my $options = $cluster_conf->{ipset}->{$ipset};
$raw .= &$format_ipset($options);
$raw .= "\n";
foreach my $group (sort keys %{$cluster_conf->{groups}}) {
my $rules = $cluster_conf->{groups}->{$group};
- $raw .= "[group $group]\n\n";
+ if (my $comment = $cluster_conf->{group_comments}->{$group}) {
+ my $utf8comment = encode('utf8', $comment);
+ $raw .= "[group $group] # $utf8comment\n\n";
+ } else {
+ $raw .= "[group $group]\n\n";
+ }
+
$raw .= &$format_rules($rules, 0);
$raw .= "\n";
}
}
sub compile {
+ my ($cluster_conf, $hostfw_conf) = @_;
+
+ $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
+ $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
+
my $vmdata = read_local_vm_config();
my $vmfw_configs = read_vm_firewall_configs($vmdata);
my $routing_table = read_proc_net_route();
- my $cluster_conf = load_clusterfw_conf();
-
my $ipset_ruleset = {};
generate_ipset_chains($ipset_ruleset, $cluster_conf);
ruleset_create_chain($ruleset, "PVEFW-FORWARD");
- my $hostfw_conf = load_hostfw_conf();
my $hostfw_options = $hostfw_conf->{options} || {};
generate_std_chains($ruleset, $hostfw_options);
ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
- return wantarray ? ($ruleset, $hostfw_conf, $ipset_ruleset) : $ruleset;
+ return ($ruleset, $ipset_ruleset);
}
sub get_ruleset_status {
my $active_chains = ipset_get_chains();
my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
+ # remove stale _swap chains
+ foreach my $chain (keys %$active_chains) {
+ if ($chain =~ m/^PVEFW-\S+_swap$/) {
+ $cmdlist .= "destroy $chain\n";
+ }
+ }
+
foreach my $chain (sort keys %$ruleset) {
my $stat = $statushash->{$chain};
die "internal error" if !$stat;
update_nf_conntrack_max($hostfw_conf);
+ update_nf_conntrack_tcp_timeout_established($hostfw_conf);
+
my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
}
}
+sub update_nf_conntrack_tcp_timeout_established {
+ my ($hostfw_conf) = @_;
+
+ my $options = $hostfw_conf->{options} || {};
+
+ my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
+
+ PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
+}
+
sub remove_pvefw_chains {
my ($chash, $hooks) = iptables_get_chains();
my ($start, $verbose) = @_;
my $code = sub {
+
+ my $cluster_conf = load_clusterfw_conf();
+ my $cluster_options = $cluster_conf->{options};
+
+ my $enable = $cluster_options->{enable};
+
my $status = read_pvefw_status();
- my ($ruleset, $hostfw_conf, $ipset_ruleset) = compile();
+ die "Firewall is disabled - cannot start\n" if !$enable && $start;
+
+ if (!$enable) {
+ PVE::Firewall::remove_pvefw_chains();
+ print "Firewall disabled\n" if $verbose;
+ return;
+ }
+
+ my $hostfw_conf = load_hostfw_conf();
+
+ my ($ruleset, $ipset_ruleset) = compile($cluster_conf, $hostfw_conf);
if ($start || $status eq 'active') {