--- /dev/null
+/*.build
+/*.buildinfo
+/*.changes
+/*.deb
+/*.dsc
+/*.tar*
+/pve-firewall-*/
PACKAGE=pve-firewall
-BUILDDIR ?= ${PACKAGE}-${DEB_VERSION_UPSTREAM}
+BUILDDIR ?= $(PACKAGE)-$(DEB_VERSION)
GITVERSION:=$(shell git rev-parse HEAD)
-DEB=${PACKAGE}_${DEB_VERSION_UPSTREAM_REVISION}_${DEB_BUILD_ARCH}.deb
-DSC=${PACKAGE}_${DEB_VERSION_UPSTREAM_REVISION}.dsc
-DEB2=${PACKAGE}-dbgsym_${DEB_VERSION_UPSTREAM_REVISION}_${DEB_BUILD_ARCH}.deb
+DEB=$(PACKAGE)_$(DEB_VERSION)_$(DEB_HOST_ARCH).deb
+DSC=$(PACKAGE)_$(DEB_VERSION).dsc
+DEB2=$(PACKAGE)-dbgsym_$(DEB_VERSION)_$(DEB_HOST_ARCH).deb
DEBS=$(DEB) $(DEB2)
all: $(DEBS)
dinstall: deb
dpkg -i $(DEBS)
-${BUILDDIR}:
- rm -rf ${BUILDDIR}
- rsync -a src/ debian ${BUILDDIR}
- echo "git clone git://git.proxmox.com/git/pve-firewall.git\\ngit checkout ${GITVERSION}" > ${BUILDDIR}/debian/SOURCE
+$(BUILDDIR):
+ rm -rf $(BUILDDIR)
+ rsync -a src/ debian $(BUILDDIR)
+ echo "git clone git://git.proxmox.com/git/pve-firewall.git\\ngit checkout $(GITVERSION)" > $(BUILDDIR)/debian/SOURCE
.PHONY: deb
deb: $(DEBS)
$(DEB2): $(DEB)
-$(DEB): ${BUILDDIR} check
- cd ${BUILDDIR}; dpkg-buildpackage -b -us -uc
- lintian ${DEBS}
+$(DEB): $(BUILDDIR) check
+ cd $(BUILDDIR); dpkg-buildpackage -b -us -uc
+ lintian $(DEBS)
.PHONY: dsc
-dsc: ${DSC}
-${DSC}: ${BUILDDIR}
- cd ${BUILDDIR}; dpkg-buildpackage -S -us -uc -d
- lintian ${DSC}
+dsc:
+ rm -rf $(DSC) $(BUILDDIR)
+ $(MAKE) $(DSC)
+ lintian $(DSC)
+
+$(DSC): $(BUILDDIR)
+ cd $(BUILDDIR); dpkg-buildpackage -S -us -uc -d
+
+sbuild: $(DSC)
+ sbuild $(DSC)
.PHONY: check
check:
clean:
make -C src clean
make -C test clean
- rm -rf *~ debian/*~ example/*~ *.deb *.changes *.buildinfo ${BUILDDIR} ${PACKAGE}*.tar.gz *.dsc
+ rm -rf *.deb *.dsc *.changes *.build *.buildinfo $(PACKAGE)-[0-9]*/ $(PACKAGE)*.tar*
.PHONY: upload
+upload: UPLOAD_DIST ?= $(DEB_DISTRIBUTION)
upload: $(DEBS)
- tar cf - $(DEBS) | ssh repoman@repo.proxmox.com -- upload --product pve --dist buster --arch ${DEB_BUILD_ARCH}
+ tar cf - $(DEBS) | ssh repoman@repo.proxmox.com -- upload --product pve --dist $(UPLOAD_DIST) --arch $(DEB_HOST_ARCH)
+pve-firewall (5.0.5) bookworm; urgency=medium
+
+ * simulator: adapt to more flexible bridge naming scheme
+
+ -- Proxmox Support Team <support@proxmox.com> Tue, 23 Apr 2024 13:11:43 +0200
+
+pve-firewall (5.0.4) bookworm; urgency=medium
+
+ * fix #5335: stable sorting in cluster.fw
+
+ * add configuration option for new nftables firewall tech-preview
+
+ -- Proxmox Support Team <support@proxmox.com> Fri, 19 Apr 2024 20:04:09 +0200
+
+pve-firewall (5.0.3) bookworm; urgency=medium
+
+ * fix resolution of scoped aliases in ipsets
+
+ -- Proxmox Support Team <support@proxmox.com> Mon, 17 Jul 2023 10:39:28 +0200
+
+pve-firewall (5.0.2) bookworm; urgency=medium
+
+ * fix #4556: api: return scoped IPSets and aliases
+
+ -- Proxmox Support Team <support@proxmox.com> Wed, 21 Jun 2023 19:17:19 +0200
+
+pve-firewall (5.0.1) bookworm; urgency=medium
+
+ * fix #4556: support 'dc/' and 'guest/' prefix for aliases and ipsets
+
+ -- Proxmox Support Team <support@proxmox.com> Wed, 07 Jun 2023 16:06:10 +0200
+
+pve-firewall (5.0.0) bookworm; urgency=medium
+
+ * switch to native versioning scheme
+
+ * build for Proxmox VE 8 / Debian 12 Bookworm
+
+ -- Proxmox Support Team <support@proxmox.com> Mon, 22 May 2023 14:43:58 +0200
+
+pve-firewall (4.3-2) bullseye; urgency=medium
+
+ * fix variables declared in conditional statement
+
+ * fix #4730: add safeguards to prevent ICMP type misuse
+
+ -- Proxmox Support Team <support@proxmox.com> Tue, 16 May 2023 11:17:58 +0200
+
+pve-firewall (4.3-1) bullseye; urgency=medium
+
+ * allow entering IP address with the host bits (those inside the mask) not
+ being all zero non-zero, like 192.168.1.155/24 for example.
+
+ * api: firewall logger: add optional parameters `since` and `until` for
+ time-range filtering
+
+ * fix #4550: host options: add nf_conntrack_helpers to compensate that
+ kernel 6.1 and newer have removed the auto helpers
+
+ -- Proxmox Support Team <support@proxmox.com> Fri, 17 Mar 2023 15:24:56 +0100
+
+pve-firewall (4.2-7) bullseye; urgency=medium
+
+ * fix #4018: add firewall macro for SPICE proxy
+
+ * fix #4204: automatically update each usage of a group to the new ID when
+ it is renamed
+
+ * fix #4268: add 'force' parameter to delete IPSet with members
+
+ -- Proxmox Support Team <support@proxmox.com> Thu, 17 Nov 2022 19:53:04 +0100
+
+pve-firewall (4.2-6) bullseye; urgency=medium
+
+ * config defaults: document that the mac filter defaults to on
+
+ * fix #4175: ignore non-filter ebtables tables
+
+ * fix enabling ebtables if VM firewall config is invalid
+
+ -- Proxmox Support Team <support@proxmox.com> Mon, 29 Aug 2022 09:43:53 +0200
+
+pve-firewall (4.2-5) bullseye; urgency=medium
+
+ * fix #3677 ipset get chains: handle newer ipset output for actual
+ change detection
+
+ -- Proxmox Support Team <support@proxmox.com> Thu, 04 Nov 2021 16:37:13 +0100
+
+pve-firewall (4.2-4) bullseye; urgency=medium
+
+ * re-build to avoid issues stemming from semi-broken systemd-debhelper version
+
+ -- Proxmox Support Team <support@proxmox.com> Tue, 12 Oct 2021 10:39:05 +0200
+
+pve-firewall (4.2-3) bullseye; urgency=medium
+
+ * fix #2721: remove the (nowadays) bogus reject for TCP port 43 from the
+ default drop and reject actions
+
+ -- Proxmox Support Team <support@proxmox.com> Fri, 10 Sep 2021 13:00:07 +0200
+
+pve-firewall (4.2-2) bullseye; urgency=medium
+
+ * re-set relevant sysctls on every apply round
+
+ -- Proxmox Support Team <support@proxmox.com> Mon, 21 Jun 2021 11:31:42 +0200
+
+pve-firewall (4.2-1) bullseye; urgency=medium
+
+ * fix #967: source: dest: limit length
+
+ * re-build for Debian 11 Bullseye based releases (Proxmox VE 7)
+
+ * fix #2358: allow --<opt> in firewall rule config files
+
+ -- Proxmox Support Team <support@proxmox.com> Wed, 12 May 2021 20:32:30 +0200
+
+pve-firewall (4.1-3) pve; urgency=medium
+
+ * fix #2773: ebtables: keep policy of custom chains
+
+ * introduce new icmp-type parameter
+
+ -- Proxmox Support Team <support@proxmox.com> Fri, 18 Sep 2020 16:51:27 +0200
+
pve-firewall (4.1-2) pve; urgency=medium
* revert: rules: verify referenced security group exists
Section: admin
Priority: optional
Maintainer: Proxmox Support Team <support@proxmox.com>
-Build-Depends: debhelper (>= 10),
+Build-Depends: debhelper-compat (= 13),
+ libanyevent-perl,
libglib2.0-dev,
libnetfilter-conntrack-dev,
libnetfilter-log-dev,
- libpve-common-perl,
libpve-access-control,
libpve-cluster-perl,
+ libpve-common-perl (>= 7.3-2),
pve-cluster (>= 6.0-4),
pve-doc-generator (>= 5.3-3),
-Standards-Version: 3.9.8
+Standards-Version: 4.6.2
Package: pve-firewall
Architecture: any
iptables,
libpve-access-control,
libpve-cluster-perl,
- libpve-common-perl,
- lsb-base,
+ libpve-common-perl (>= 7.3-2),
pve-cluster (>= 6.1-6),
${misc:Depends},
${perl:Depends},
+debian/README
debian/SOURCE
debian/example/
-debian/README
TimeoutStopSec=5
Type=forking
+[Install]
+WantedBy=multi-user.target
#export DH_VERBOSE=1
%:
- dh $@ --with systemd
+ dh $@
-override_dh_systemd_enable:
- dh_systemd_enable --name pvefw-logger pvefw-logger.service
- dh_systemd_enable --name pve-firewall pve-firewall.service
-
-override_dh_systemd_start:
- dh_systemd_start --restart-after-upgrade pvefw-logger.service
- # pve-firewall start/try-reload-restart manually in postinst
+override_dh_installsystemd:
+ dh_installsystemd --name pvefw-logger pvefw-logger.service
+ dh_installsystemd --name pve-firewall --no-stop-on-upgrade --no-restart-after-upgrade pve-firewall.service
override_dh_installinit:
DESTDIR=
PREFIX= /usr
-BINDIR=${DESTDIR}/${PREFIX}/bin
-SBINDIR=${DESTDIR}/${PREFIX}/sbin
-MANDIR=${DESTDIR}/${PREFIX}/share/man
-DOCDIR=${DESTDIR}/${PREFIX}/share/doc/pve-firewall
-MAN1DIR=${MANDIR}/man1/
-MAN8DIR=${MANDIR}/man8/
-BASHCOMPLDIR=${DESTDIR}/${PREFIX}/share/bash-completion/completions
-ZSHCOMPLDIR=${DESTDIR}/${PREFIX}/share/zsh/vendor-completions
-
-export NOVIEW=1
-include /usr/share/pve-doc-generator/pve-doc-generator.mk
+BINDIR=$(DESTDIR)/$(PREFIX)/bin
+SBINDIR=$(DESTDIR)/$(PREFIX)/sbin
+MANDIR=$(DESTDIR)/$(PREFIX)/share/man
+DOCDIR=$(DESTDIR)/$(PREFIX)/share/doc/pve-firewall
+MAN1DIR=$(MANDIR)/man1/
+MAN8DIR=$(MANDIR)/man8/
+BASHCOMPLDIR=$(DESTDIR)/$(PREFIX)/share/bash-completion/completions
+ZSHCOMPLDIR=$(DESTDIR)/$(PREFIX)/share/zsh/vendor-completions
+
+-include /usr/share/pve-doc-generator/pve-doc-generator.mk
all: pve-firewall.8 pvefw-logger
perl -I. -T -e "use PVE::Service::pve_firewall; PVE::Service::pve_firewall->generate_zsh_completions();" >$@.tmp
mv $@.tmp $@
-CPPFLAGS:=$(shell dpkg-buildflags --get CPPFLAGS)
CFLAGS:=$(shell dpkg-buildflags --get CFLAGS)
+CFLAGS+=$(shell pkg-config libnetfilter_log libnetfilter_conntrack glib-2.0 --libs --cflags)
LDFLAGS:=$(shell dpkg-buildflags --get LDFLAGS)
pvefw-logger: pvefw-logger.c
- gcc -Wall -Werror pvefw-logger.c -o pvefw-logger -std=gnu99 \
- $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) \
- $(shell pkg-config libnetfilter_log libnetfilter_conntrack glib-2.0 --libs --cflags)
+ gcc -Wall -Werror pvefw-logger.c -o pvefw-logger -std=gnu99 $(CFLAGS) $(LDFLAGS)
.PHONY: install
install: pve-firewall pve-firewall.8 pve-firewall.bash-completion pve-firewall.zsh-completion pvefw-logger
make -C PVE install
- install -d -m 0755 ${SBINDIR}
- install -m 0755 pve-firewall ${SBINDIR}
- install -m 0755 pvefw-logger ${SBINDIR}
- install -d ${MAN8DIR}
- install -m 0644 pve-firewall.8 ${MAN8DIR}
- install -m 0644 -D pve-firewall.bash-completion ${BASHCOMPLDIR}/pve-firewall
- install -m 0644 -D pve-firewall.zsh-completion ${ZSHCOMPLDIR}/_pve-firewall
- install -d -m 0755 ${DESTDIR}/usr/lib/sysctl.d/
- install -m 0644 pve-firewall-sysctl.conf ${DESTDIR}/usr/lib/sysctl.d/pve-firewall.conf
+ install -d -m 0755 $(SBINDIR)
+ install -m 0755 pve-firewall $(SBINDIR)
+ install -m 0755 pvefw-logger $(SBINDIR)
+ install -d $(MAN8DIR)
+ install -m 0644 pve-firewall.8 $(MAN8DIR)
+ install -m 0644 -D pve-firewall.bash-completion $(BASHCOMPLDIR)/pve-firewall
+ install -m 0644 -D pve-firewall.zsh-completion $(ZSHCOMPLDIR)/_pve-firewall
+ install -d -m 0755 $(DESTDIR)/usr/lib/sysctl.d/
+ install -m 0644 pve-firewall-sysctl.conf $(DESTDIR)/usr/lib/sysctl.d/pve-firewall.conf
.PHONY: clean
clean:
make -C PVE clean
- make cleanup-docgen
- rm -rf pvefw-logger
- find . -name '*~' -exec rm {} ';'
+ rm -f *.xml.tmp *.1 *.5 *.8 *{synopsis,opts}.adoc docinfo.xml *~
+ rm -rf pvefw-logger
.PHONY: distclean
ref => {
type => 'string',
},
+ scope => {
+ type => 'string',
+ },
comment => {
type => 'string',
optional => 1,
my $conf = PVE::Firewall::load_clusterfw_conf();
- my $res = [];
-
- if (!$param->{type} || $param->{type} eq 'ipset') {
- foreach my $name (keys %{$conf->{ipset}}) {
- my $data = {
- type => 'ipset',
- name => $name,
- ref => "+$name",
- };
- if (my $comment = $conf->{ipset_comments}->{$name}) {
- $data->{comment} = $comment;
- }
- push @$res, $data;
- }
- }
-
- if (!$param->{type} || $param->{type} eq 'alias') {
- foreach my $name (keys %{$conf->{aliases}}) {
- my $e = $conf->{aliases}->{$name};
- my $data = {
- type => 'alias',
- name => $name,
- ref => $name,
- };
- $data->{comment} = $e->{comment} if $e->{comment};
- push @$res, $data;
- }
- }
-
- return $res;
+ return PVE::Firewall::Helpers::collect_refs($conf, $param->{type}, "dc");
}});
1;
return wantarray ? ($list, $digest) : $list;
};
+my $rename_fw_rules = sub {
+ my ($old, $new, $rules) = @_;
+
+ for my $rule (@{$rules}) {
+ next if ($rule->{type} ne "group" || $rule->{action} ne $old);
+ $rule->{action} = $new;
+ }
+};
+
__PACKAGE__->register_method({
name => 'list_security_groups',
path => '',
code => sub {
my ($param) = @_;
+ my $group = $param->{group};
+ my $rename = $param->{rename};
+ my $comment = $param->{comment};
+
PVE::Firewall::lock_clusterfw_conf(10, sub {
my $cluster_conf = PVE::Firewall::load_clusterfw_conf();
- if ($param->{rename}) {
+ if ($rename) {
my (undef, $digest) = &$get_security_group_list($cluster_conf);
PVE::Tools::assert_if_modified($digest, $param->{digest});
- raise_param_exc({ group => "Security group '$param->{rename}' does not exist" })
- if !$cluster_conf->{groups}->{$param->{rename}};
+ raise_param_exc({ group => "Security group '$rename' does not exist" })
+ if !$cluster_conf->{groups}->{$rename};
# prevent overwriting an existing group
- raise_param_exc({ group => "Security group '$param->{group}' does already exist" })
- if $cluster_conf->{groups}->{$param->{group}} &&
- $param->{group} ne $param->{rename};
-
- my $data = delete $cluster_conf->{groups}->{$param->{rename}};
- $cluster_conf->{groups}->{$param->{group}} = $data;
- if (my $comment = delete $cluster_conf->{group_comments}->{$param->{rename}}) {
- $cluster_conf->{group_comments}->{$param->{group}} = $comment;
+ raise_param_exc({ group => "Security group '$group' does already exist" })
+ if $cluster_conf->{groups}->{$group} &&
+ $group ne $rename;
+
+ if ($rename eq $group) {
+ $cluster_conf->{group_comments}->{$rename} = $comment if defined($comment);
+ PVE::Firewall::save_clusterfw_conf($cluster_conf);
+ return;
}
- $cluster_conf->{group_comments}->{$param->{group}} = $param->{comment} if defined($param->{comment});
+
+ # Create an exact copy of the old security group
+ $cluster_conf->{groups}->{$group} = $cluster_conf->{groups}->{$rename};
+ $cluster_conf->{group_comments}->{$group} = $cluster_conf->{group_comments}->{$rename};
+
+ # Update comment if provided
+ $cluster_conf->{group_comments}->{$group} = $comment if defined($comment);
+
+ # Write the copy to the cluster config, so that if something fails inbetween, the new firewall
+ # rules won't be broken when the new name is referenced
+ PVE::Firewall::save_clusterfw_conf($cluster_conf);
+
+ # Update all the host configs to the new copy
+ my $hosts = PVE::Cluster::get_nodelist();
+ foreach my $host (@$hosts) {
+ PVE::Firewall::lock_hostfw_conf($host, 10, sub {
+ my $host_conf_path = "/etc/pve/nodes/$host/host.fw";
+ my $host_conf = PVE::Firewall::load_hostfw_conf($cluster_conf, $host_conf_path);
+
+ if (defined($host_conf)) {
+ &$rename_fw_rules($rename,
+ $group,
+ $host_conf->{rules});
+ PVE::Firewall::save_hostfw_conf($host_conf, $host_conf_path);
+ }
+ });
+ }
+
+ # Update all the VM configs
+ my $vms = PVE::Cluster::get_vmlist();
+ foreach my $vm (keys %{$vms->{ids}}) {
+ PVE::Firewall::lock_vmfw_conf($vm, 10, sub {
+ my $vm_type = $vms->{ids}->{$vm}->{type} eq "lxc" ? "ct" : "vm";
+ my $vm_conf = PVE::Firewall::load_vmfw_conf($cluster_conf, $vm_type, $vm, "/etc/pve/firewall");
+
+ if (defined($vm_conf)) {
+ &$rename_fw_rules($rename,
+ $group,
+ $vm_conf->{rules});
+ PVE::Firewall::save_vmfw_conf($vm, $vm_conf);
+ }
+ });
+ }
+
+ # And also update the cluster itself
+ &$rename_fw_rules($rename,
+ $group,
+ $cluster_conf->{rules});
+
+ # Now that everything has been updated, the old rule can be deleted
+ delete $cluster_conf->{groups}->{$rename};
+ delete $cluster_conf->{group_comments}->{$rename};
} else {
foreach my $name (keys %{$cluster_conf->{groups}}) {
raise_param_exc({ group => "Security group '$name' already exists" })
- if $name eq $param->{group};
+ if $name eq $group;
}
- $cluster_conf->{groups}->{$param->{group}} = [];
- $cluster_conf->{group_comments}->{$param->{group}} = $param->{comment} if defined($param->{comment});
+ $cluster_conf->{groups}->{$group} = [];
+ $cluster_conf->{group_comments}->{$group} = $comment if defined($comment);
}
PVE::Firewall::save_clusterfw_conf($cluster_conf);
code => sub {
my ($param) = @_;
- PVE::Firewall::lock_hostfw_conf(10, sub {
+ PVE::Firewall::lock_hostfw_conf(undef, 10, sub {
my $cluster_conf = PVE::Firewall::load_clusterfw_conf();
my $hostfw_conf = PVE::Firewall::load_hostfw_conf($cluster_conf);
minimum => 0,
optional => 1,
},
+ since => {
+ type => 'integer',
+ minimum => 0,
+ description => "Display log since this UNIX epoch.",
+ optional => 1,
+ },
+ until => {
+ type => 'integer',
+ minimum => 0,
+ description => "Display log until this UNIX epoch.",
+ optional => 1,
+ },
},
},
returns => {
my $rpcenv = PVE::RPCEnvironment::get();
my $user = $rpcenv->get_user();
my $node = $param->{node};
+ my $filename = "/var/log/pve-firewall.log";
- my ($count, $lines) = PVE::Tools::dump_logfile("/var/log/pve-firewall.log", $param->{start}, $param->{limit});
+ my ($count, $lines) = PVE::Firewall::Helpers::dump_fw_logfile(
+ $filename, $param, undef);
$rpcenv->set_result_attrib('total', $count);
my $properties = $class->additional_parameters();
$properties->{name} = get_standard_option('ipset-name');
+ $properties->{force} = {
+ type => 'boolean',
+ optional => 1,
+ description => 'Delete all members of the IPSet, if there are any.',
+ };
$class->register_method({
name => 'delete_ipset',
my ($cluster_conf, $fw_conf, $ipset) = $class->load_config($param);
die "IPSet '$param->{name}' is not empty\n"
- if scalar(@$ipset);
+ if scalar(@$ipset) && !$param->{force};
$class->save_ipset($param, $fw_conf, undef);
my ($cluster_conf, $fw_conf, $ipset) = $class->load_config($param);
my $cidr = $param->{cidr};
- if ($cidr =~ m/^${PVE::Firewall::ip_alias_pattern}$/) {
+ if ($cidr =~ m@^(dc/|guest/)?(${PVE::Firewall::ip_alias_pattern})$@) {
+ my $scope = $1 // "";
+ my $alias = $2;
# make sure alias exists (if $cidr is an alias)
- PVE::Firewall::resolve_alias($cluster_conf, $fw_conf, $cidr);
+ PVE::Firewall::resolve_alias($cluster_conf, $fw_conf, $alias, $scope);
} else {
+ $cidr = PVE::Firewall::clean_cidr($cidr);
# normalize like config parser, otherwise duplicates might slip through
$cidr = PVE::Firewall::parse_ip_or_cidr($cidr);
}
DESTDIR=
PREFIX=/usr
-PERLDIR=${DESTDIR}/${PREFIX}/share/perl5
+PERLDIR=$(DESTDIR)/$(PREFIX)/share/perl5
LIB_SOURCES= \
Aliases.pm \
.PHONY: install
install:
- install -d -m 0755 ${PERLDIR}/PVE/API2/Firewall
- for i in ${LIB_SOURCES}; do install -D -m 0644 $$i ${PERLDIR}/PVE/API2/Firewall/$$i; done
+ install -d -m 0755 $(PERLDIR)/PVE/API2/Firewall
+ for i in $(LIB_SOURCES); do install -D -m 0644 $$i $(PERLDIR)/PVE/API2/Firewall/$$i; done
.PHONY: clean
sub lock_config {
my ($class, $param, $code) = @_;
- PVE::Firewall::lock_hostfw_conf(10, $code, $param);
+ PVE::Firewall::lock_hostfw_conf(undef, 10, $code, $param);
}
sub load_config {
minimum => 0,
optional => 1,
},
+ since => {
+ type => 'integer',
+ minimum => 0,
+ description => "Display log since this UNIX epoch.",
+ optional => 1,
+ },
+ until => {
+ type => 'integer',
+ minimum => 0,
+ description => "Display log until this UNIX epoch.",
+ optional => 1,
+ },
},
},
returns => {
my $rpcenv = PVE::RPCEnvironment::get();
my $user = $rpcenv->get_user();
- my $vmid = $param->{vmid};
+ my $filename = "/var/log/pve-firewall.log";
+ my $vmid = $param->{'vmid'};
- my ($count, $lines) = PVE::Tools::dump_logfile("/var/log/pve-firewall.log",
- $param->{start}, $param->{limit},
- "^$vmid ");
+ my $callback = sub {
+ my ($line) = @_;
+ my $reg = "^$vmid ";
+ return $line =~ m/$reg/;
+ };
+
+ my ($count, $lines) = PVE::Firewall::Helpers::dump_fw_logfile(
+ $filename, $param, $callback);
$rpcenv->set_result_attrib('total', $count);
name => {
type => 'string',
},
+ ref => {
+ type => 'string',
+ },
+ scope => {
+ type => 'string',
+ },
comment => {
type => 'string',
optional => 1,
my $cluster_conf = PVE::Firewall::load_clusterfw_conf();
my $fw_conf = PVE::Firewall::load_vmfw_conf($cluster_conf, $rule_env, $param->{vmid});
- my $ipsets = {};
- my $aliases = {};
-
- foreach my $conf (($cluster_conf, $fw_conf)) {
- next if !$conf;
- if (!$param->{type} || $param->{type} eq 'ipset') {
- foreach my $name (keys %{$conf->{ipset}}) {
- my $data = {
- type => 'ipset',
- name => $name,
- ref => "+$name",
- };
- if (my $comment = $conf->{ipset_comments}->{$name}) {
- $data->{comment} = $comment;
- }
- $ipsets->{$name} = $data;
- }
- }
-
- if (!$param->{type} || $param->{type} eq 'alias') {
- foreach my $name (keys %{$conf->{aliases}}) {
- my $e = $conf->{aliases}->{$name};
- my $data = {
- type => 'alias',
- name => $name,
- ref => $name,
- };
- $data->{comment} = $e->{comment} if $e->{comment};
- $aliases->{$name} = $data;
- }
- }
- }
-
- my $res = [];
- foreach my $e (values %$ipsets) { push @$res, $e; };
- foreach my $e (values %$aliases) { push @$res, $e; };
+ my $dc_refs = PVE::Firewall::Helpers::collect_refs($cluster_conf, $param->{type}, 'dc');
+ my $vm_refs = PVE::Firewall::Helpers::collect_refs($fw_conf, $param->{type}, 'guest');
- return $res;
+ return [@$dc_refs, @$vm_refs];
}});
}
DESTDIR=
PREFIX=/usr
-PERLDIR=${DESTDIR}/${PREFIX}/share/perl5
+PERLDIR=$(DESTDIR)/$(PREFIX)/share/perl5
all:
.PHONY: install
install:
- install -d -m 0755 ${PERLDIR}/PVE/API2
+ install -d -m 0755 $(PERLDIR)/PVE/API2
make -C Firewall install
.PHONY: clean
use PVE::Tools qw($IPV4RE $IPV6RE);
use PVE::Tools qw(run_command lock_file dir_glob_foreach);
+use PVE::Firewall::Helpers;
+
my $pvefw_conf_dir = "/etc/pve/firewall";
my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
sub pve_verify_ip_or_cidr {
my ($cidr, $noerr) = @_;
- if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
- return $cidr if Net::IP->new($cidr);
+ if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(?:/\d+)?$!) {
+ # Net::IP throws an error if the masked CIDR part isn't zero, e.g., `192.168.1.155/24`
+ # fails but `192.168.1.0/24` succeeds. clean_cidr removes the non zero bits from the CIDR.
+ my $clean_cidr = clean_cidr($cidr);
+ return $cidr if Net::IP->new($clean_cidr);
return undef if $noerr;
+
die Net::IP::Error() . "\n";
}
return undef if $noerr;
sub pve_verify_ip_or_cidr_or_alias {
my ($cidr, $noerr) = @_;
- return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
+ return if $cidr =~ m@^(dc/|guest/)?(?:$ip_alias_pattern)$@;
return pve_verify_ip_or_cidr($cidr, $noerr);
}
+sub clean_cidr {
+ my ($cidr) = @_;
+ my ($ip, $len) = split('/', $cidr);
+ return $cidr if !$len;
+ my $ver = ($ip =~ m!^$IPV4RE$!) ? 4 : 6;
+
+ my $bin_ip = Net::IP::ip_iptobin( Net::IP::ip_expand_address($ip, $ver), $ver);
+ my $bin_mask = Net::IP::ip_get_mask($len, $ver);
+ my $clean_ip = Net::IP::ip_compress_address( Net::IP::ip_bintoip($bin_ip & $bin_mask, $ver), $ver);
+
+ return "${clean_ip}/$len";
+}
+
PVE::JSONSchema::register_standard_option('ipset-name', {
description => "IP set name.",
type => 'string',
{ action => 'PARAM', proto => '41' },
{ action => 'PARAM', proto => 'udp', dport => '5072,8374' },
],
+ 'SPICEproxy' => [
+ "Proxmox VE SPICE display proxy traffic",
+ { action => 'PARAM', proto => 'tcp', dport => '3128' },
+ ],
'Squid' => [
"Squid web proxy traffic",
{ action => 'PARAM', proto => 'tcp', dport => '3128' },
],
};
+my $pve_fw_helpers = {
+ 'amanda' => { proto => 'udp', dport => '10080', 'v4' => 1, 'v6' => 1 },
+ 'ftp' => { proto => 'tcp', dport => '21', 'v4' => 1, 'v6' => 1},
+ 'irc' => { proto => 'tcp', dport => '6667', 'v4' => 1 },
+ 'netbios-ns' => { proto => 'udp', dport => '137', 'v4' => 1 },
+ 'pptp' => { proto => 'tcp', dport => '1723', 'v4' => 1, },
+ 'sane' => { proto => 'tcp', dport => '6566', 'v4' => 1, 'v6' => 1 },
+ 'sip' => { proto => 'udp', dport => '5060', 'v4' => 1, 'v6' => 1 },
+ 'snmp' => { proto => 'udp', dport => '161', 'v4' => 1 },
+ 'tftp' => { proto => 'udp', dport => '69', 'v4' => 1, 'v6' => 1},
+};
+
my $pve_fw_parsed_macros;
my $pve_fw_macro_descr;
my $pve_fw_macro_ipversion = {};
# same as shorewall 'Drop', which is equal to DROP,
# but REJECT/DROP some packages to reduce logging,
# and ACCEPT critical ICMP types
- { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
# we are not interested in BROADCAST/MULTICAST/ANYCAST
{ action => 'PVEFW-DropBroadcast' },
# ACCEPT critical ICMP types
# same as shorewall 'Reject', which is equal to Reject,
# but REJECT/DROP some packages to reduce logging,
# and ACCEPT critical ICMP types
- { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
# we are not interested in BROADCAST/MULTICAST/ANYCAST
{ action => 'PVEFW-DropBroadcast' },
# ACCEPT critical ICMP types
}
};
+my $proto_is_icmp = sub {
+ my $proto = shift;
+ return $proto eq 'icmp' || $proto eq 'icmpv6' || $proto eq 'ipv6-icmp';
+};
+
sub init_firewall_macros {
$pve_fw_parsed_macros = {};
return;
}
- if ($str =~ m/^${ip_alias_pattern}$/) {
+ if ($str =~ m@^(dc/|guest/)?${ip_alias_pattern}$@) {
die "alias name too long\n" if length($str) > $max_alias_name_length;
return;
}
return $ipversion;
}
+# $dport must only be set to 1 if the parsed parameter is dport and the
+# protocol is one of the ICMP variants - ICMP type values used to be stored in
+# the dport parameter.
sub parse_port_name_number_or_range {
my ($str, $dport) = @_;
return (scalar(@elements) > 1);
}
+PVE::JSONSchema::register_format('pve-fw-conntrack-helper', \&pve_fw_verify_conntrack_helper);
+sub pve_fw_verify_conntrack_helper {
+ my ($list) = @_;
+
+ my @helpers = split(/,/, $list);
+ die "extraneous commas in list\n" if $list ne join(',', @helpers);
+ foreach my $helper (@helpers) {
+ die "unknown helper $helper" if !$pve_fw_helpers->{$helper};
+ }
+
+ return $list;
+}
+
PVE::JSONSchema::register_format('pve-fw-sport-spec', \&pve_fw_verify_sport_spec);
sub pve_fw_verify_sport_spec {
my ($portstr) = @_;
default => 0,
optional => 1,
},
+ nf_conntrack_helpers => {
+ type => 'string', format => 'pve-fw-conntrack-helper',
+ description => "Enable conntrack helpers for specific protocols. ".
+ "Supported protocols: amanda, ftp, irc, netbios-ns, pptp, sane, sip, snmp, tftp",
+ default => '',
+ optional => 1,
+ },
protection_synflood => {
description => "Enable synflood protection",
type => 'boolean',
default => 0,
optional => 1
},
+ nftables => {
+ description => "Enable nftables based firewall (tech preview)",
+ type => 'boolean',
+ default => 0,
+ optional => 1,
+ },
};
our $vm_option_properties = {
macfilter => {
description => "Enable/disable MAC address filter.",
type => 'boolean',
- default => 0,
+ default => 1,
optional => 1,
},
dhcp => {
description => "Restrict packet source address. $addr_list_descr",
type => 'string', format => 'pve-fw-addr-spec',
optional => 1,
+ maxLength => 512,
},
dest => {
description => "Restrict packet destination address. $addr_list_descr",
type => 'string', format => 'pve-fw-addr-spec',
optional => 1,
+ maxLength => 512,
},
proto => {
description => "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
optional => 1,
},
'icmp-type' => {
- description => "Specify icmp-type. Only valid if proto equals 'icmp'.",
+ description => "Specify icmp-type. Only valid if proto equals 'icmp' or 'icmpv6'/'ipv6-icmp'.",
type => 'string', format => 'pve-fw-icmp-type-spec',
optional => 1,
},
if (my $value = $rule->{$name}) {
if ($value =~ m/^\+/) {
- if ($value =~ m/^\+(${ipset_name_pattern})$/) {
- &$add_error($name, "no such ipset '$1'")
- if !($cluster_conf->{ipset}->{$1} || ($fw_conf && $fw_conf->{ipset}->{$1}));
+ if ($value =~ m@^\+(guest/|dc/)?(${ipset_name_pattern})$@) {
+ &$add_error($name, "no such ipset '$2'")
+ if !($cluster_conf->{ipset}->{$2} || ($fw_conf && $fw_conf->{ipset}->{$2}));
} else {
&$add_error($name, "invalid ipset name '$value'");
}
- } elsif ($value =~ m/^${ip_alias_pattern}$/){
- my $alias = lc($value);
+ } elsif ($value =~ m@^(guest/|dc/)?(${ip_alias_pattern})$@){
+ my $scope = $1 // "";
+ my $alias = lc($2);
&$add_error($name, "no such alias '$value'")
if !($cluster_conf->{aliases}->{$alias} || ($fw_conf && $fw_conf->{aliases}->{$alias}));
- my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
- $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
+
+ my $e;
+ if ($scope ne 'dc/' && $fw_conf) {
+ $e = $fw_conf->{aliases}->{$alias};
+ }
+ if ($scope ne 'guest/' && !$e && $cluster_conf) {
+ $e = $cluster_conf->{aliases}->{$alias};
+ }
&$set_ip_version($e->{ipversion});
}
}
}
+ my $is_icmp = 0;
if ($rule->{proto}) {
eval { pve_fw_verify_protocol_spec($rule->{proto}); };
&$add_error('proto', $@) if $@;
&$set_ip_version(4) if $rule->{proto} eq 'icmp';
&$set_ip_version(6) if $rule->{proto} eq 'icmpv6';
&$set_ip_version(6) if $rule->{proto} eq 'ipv6-icmp';
+ $is_icmp = $proto_is_icmp->($rule->{proto});
}
if ($rule->{dport}) {
- eval { parse_port_name_number_or_range($rule->{dport}, 1); };
+ eval { parse_port_name_number_or_range($rule->{dport}, $is_icmp); };
&$add_error('dport', $@) if $@;
my $proto = $rule->{proto};
&$add_error('proto', "missing property - 'dport' requires this property")
if !$proto;
&$add_error('dport', "protocol '$proto' does not support ports")
- if !$PROTOCOLS_WITH_PORTS->{$proto} &&
- $proto ne 'icmp' && $proto ne 'icmpv6'; # special cases
+ if !$PROTOCOLS_WITH_PORTS->{$proto} && !$is_icmp; #special cases
}
if (my $icmp_type = $rule ->{'icmp-type'}) {
my $proto = $rule->{proto};
&$add_error('proto', "missing property - 'icmp-type' requires this property")
- if $proto ne 'icmp' && $proto ne 'icmpv6' && $proto ne 'ipv6-icmp';
+ if !$is_icmp;
&$add_error('icmp-type', "'icmp-type' cannot be specified together with 'dport'")
if $rule->{dport};
if ($proto eq 'icmp' && !$icmp_type_names->{$icmp_type}) {
}
# core functions
-my $bridge_firewall_enabled = 0;
sub enable_bridge_firewall {
- return if $bridge_firewall_enabled; # only once
PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
# make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
- $bridge_firewall_enabled = 1;
}
sub iptables_restore_cmdlist {
return if $line =~ m/^\s*$/;
if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
my $chain = $1;
+ # ignore initval from ipset v7.7+, won't set that yet so it'd mess up change detection
+ $line =~ s/\binitval 0x[0-9a-f]+//;
$line =~ s/\s+$//; # delete trailing white space
push @{$chains->{$chain}}, $line;
} else {
my $res = {};
my $chains = {};
+ my $table;
my $parser = sub {
my $line = shift;
return if $line =~ m/^#/;
return if $line =~ m/^\s*$/;
+ if ($line =~ m/^\*(\S+)$/) {
+ $table = $1;
+ return;
+ }
+
+ return if $table ne "filter";
+
if ($line =~ m/^:(\S+)\s(ACCEPT|DROP|RETURN)$/) {
# Make sure we know chains exist even if they're empty.
$chains->{$1} //= [];
my $match;
if ($adr =~ m/^\+/) {
- if ($adr =~ m/^\+(${ipset_name_pattern})$/) {
- my $name = $1;
+ if ($adr =~ m@^\+(guest/|dc/)?(${ipset_name_pattern})$@) {
+ my $scope = $1 // "";
+ my $name = $2;
my $ipset_chain;
- if ($fw_conf && $fw_conf->{ipset}->{$name}) {
+ if ($scope ne 'dc/' && $fw_conf && $fw_conf->{ipset}->{$name}) {
$ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
- } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
+ } elsif ($scope ne 'guest/' && $cluster_conf && $cluster_conf->{ipset}->{$name}) {
$ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
} else {
die "no such ipset '$name'\n";
} else {
die "invalid security group name '$adr'\n";
}
- } elsif ($adr =~ m/^${ip_alias_pattern}$/){
- my $alias = lc($adr);
- my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
- $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
+ } elsif ($adr =~ m@^(dc/|guest/)?(${ip_alias_pattern})$@){
+ my $scope = $1 // "";
+ my $alias = lc($2);
+ my $e;
+ if ($scope ne 'dc/' && $fw_conf) {
+ $e = $fw_conf->{aliases}->{$alias};
+ }
+ if ($scope ne 'guest/' && !$e && $cluster_conf) {
+ $e = $cluster_conf->{aliases}->{$alias};
+ }
die "no such alias '$adr'\n" if !$e;
$match = "-${dir} $e->{cidr}";
} elsif ($adr =~ m/\-/){
if (my $proto = $rule->{proto}) {
push @match, "-p $proto";
+ my $is_icmp = $proto_is_icmp->($proto);
- my $multidport = defined($rule->{dport}) && parse_port_name_number_or_range($rule->{dport}, 1);
+ my $multidport = defined($rule->{dport}) && parse_port_name_number_or_range($rule->{dport}, $is_icmp);
my $multisport = defined($rule->{sport}) && parse_port_name_number_or_range($rule->{sport}, 0);
my $add_dport = sub {
return if !defined($rule->{'icmp-type'}) || $rule->{'icmp-type'} eq '';
die "'icmp-type' can only be set if 'icmp', 'icmpv6' or 'ipv6-icmp' is specified\n"
- if ($proto ne 'icmp') && ($proto ne 'icmpv6') && ($proto ne 'ipv6-icmp');
+ if !$is_icmp;
my $type = $proto eq 'icmp' ? 'icmp-type' : 'icmpv6-type';
push @match, "-m $proto --$type $rule->{'icmp-type'}";
$targetstr = $rule->{target};
} else {
my $action = (defined $rule->{action}) ? $rule->{action} : "";
- my $goto = 1 if $action eq 'PVEFW-SET-ACCEPT-MARK';
- $targetstr = ($goto) ? "-g $action" : "-j $action";
+ $targetstr = $action eq 'PVEFW-SET-ACCEPT-MARK' ? "-g $action" : "-j $action";
}
my @iptcmds;
my $tapchain = "$iface-$direction";
my $ipfilter_name = compute_ipfilter_ipset_name($netid);
- my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
+ my $ipfilter_ipset;
+ $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
if ($options->{enable}) {
last if $rule->{type} eq 'group';
- if ($line =~ s/^-p (\S+)\s*//) {
+ if ($line =~ s/^(?:-p|--?proto) (\S+)\s*//) {
$rule->{proto} = $1;
next;
}
- if ($line =~ s/^-dport (\S+)\s*//) {
+ if ($line =~ s/^--?dport (\S+)\s*//) {
$rule->{dport} = $1;
next;
}
- if ($line =~ s/^-sport (\S+)\s*//) {
+ if ($line =~ s/^--?sport (\S+)\s*//) {
$rule->{sport} = $1;
next;
}
- if ($line =~ s/^-source (\S+)\s*//) {
+ if ($line =~ s/^--?source (\S+)\s*//) {
$rule->{source} = $1;
next;
}
- if ($line =~ s/^-dest (\S+)\s*//) {
+ if ($line =~ s/^--?dest (\S+)\s*//) {
$rule->{dest} = $1;
next;
}
- if ($line =~ s/^-log (emerg|alert|crit|err|warning|notice|info|debug|nolog)\s*//) {
+ if ($line =~ s/^--?log (emerg|alert|crit|err|warning|notice|info|debug|nolog)\s*//) {
$rule->{log} = $1;
next;
}
- if ($line =~ s/^-icmp-type (\S+)\s*//) {
+ if ($line =~ s/^--?icmp-type (\S+)\s*//) {
$rule->{'icmp-type'} = $1;
next;
}
my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
- if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp|log_nf_conntrack|nf_conntrack_allow_invalid|protection_synflood):\s*(0|1)\s*$/i) {
+ if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp|log_nf_conntrack|nf_conntrack_allow_invalid|protection_synflood|nftables):\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/^(nf_conntrack_helpers):\s*(((\S+)[,]?)+)\s*$/i) {
+ $opt = lc($1);
+ $value = lc($2);
+ pve_fw_verify_conntrack_helper($value);
} elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established|nf_conntrack_tcp_timeout_syn_recv|protection_synflood_rate|protection_synflood_burst|protection_limit):\s*(\d+)\s*$/i) {
$opt = lc($1);
$value = int($2);
}
sub resolve_alias {
- my ($clusterfw_conf, $fw_conf, $cidr) = @_;
+ my ($clusterfw_conf, $fw_conf, $cidr, $scope) = @_;
+
+ # When we're on the cluster level, the cluster config only gets
+ # saved into fw_conf, so we need some extra handling here (to
+ # stay consistent)
+ my ($cluster_config, $local_config);
+ if (!$clusterfw_conf) {
+ ($cluster_config, $local_config) = ($fw_conf, undef);
+ } else {
+ ($cluster_config, $local_config) = ($clusterfw_conf, $fw_conf);
+ }
my $alias = lc($cidr);
- my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
- $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
+ my $e;
+ if ($scope ne 'dc/' && $local_config) {
+ $e = $local_config->{aliases}->{$alias};
+ }
+ if ($scope ne 'guest/' && !$e && $cluster_config) {
+ $e = $cluster_config->{aliases}->{$alias};
+ }
die "no such alias '$cidr'\n" if !$e;;
my ($line) = @_;
# we can add single line comments to the end of the line
- my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
+ my $comment = $line =~ s/\s*#\s*(.*?)\s*$// ? decode('utf8', $1) : undef;
if ($line =~ m/^(\S+)\s(\S+)$/) {
my ($name, $cidr) = ($1, $2);
push @{$res->{$section}->{$group}}, $rule;
} elsif ($section eq 'ipset') {
# we can add single line comments to the end of the rule
- my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
+ my $comment = $line =~ s/#\s*(.*?)\s*$// ? decode('utf8', $1) : undef;
$line =~ m/^(\!)?\s*(\S+)\s*$/;
my $nomatch = $1;
}
eval {
- if ($cidr =~ m/^${ip_alias_pattern}$/) {
- resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
+ if ($cidr =~ m@^(dc/|guest/)?(${ip_alias_pattern}$)@) {
+ my $scope = $1 // "";
+ my $alias = $2;
+ resolve_alias($cluster_conf, $res, $alias, $scope); # make sure alias exists
} else {
$cidr = parse_ip_or_cidr($cidr);
}
}
}
} elsif ($d->{type} eq 'lxc') {
- if ($have_lxc) {
- my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
- if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
- $lxc->{$vmid} = $conf;
- }
- }
- }
+ if ($have_lxc) {
+ my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
+ if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
+ $lxc->{$vmid} = $conf;
+ }
+ }
+ }
}
return $vmdata;
};
+# FIXME: move use sites over to moved helper and break older packages, then remove this here
sub lock_vmfw_conf {
- my ($vmid, $timeout, $code, @param) = @_;
-
- die "can't lock VM firewall config for undefined VMID\n"
- if !defined($vmid);
-
- my $res = PVE::Cluster::cfs_lock_firewall("vm-$vmid", $timeout, $code, @param);
- die $@ if $@;
-
- return $res;
+ return PVE::Firewall::Helpers::lock_vmfw_conf(@_);
}
sub load_vmfw_conf {
my $raw = '';
$raw .= "[ALIASES]\n\n";
- foreach my $k (keys %$aliases) {
+ foreach my $k (sort keys %$aliases) {
my $e = $aliases->{$k};
$raw .= "$e->{name} $e->{cidr}";
$raw .= " # " . encode('utf8', $e->{comment})
}
}
+# FIXME: remove with 8.0 and break older qemu-server/pve-container
sub remove_vmfw_conf {
- my ($vmid) = @_;
-
- my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
-
- unlink $vmfw_conffile;
+ return PVE::Firewall::Helpers::remove_vmfw_conf(@_);
}
+# FIXME: remove with 8.0 and break older qemu-server/pve-container
sub clone_vmfw_conf {
- my ($vmid, $newid) = @_;
-
- my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
- my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
-
- lock_vmfw_conf($newid, 10, sub {
- if (-f $clonevm_conffile) {
- unlink $clonevm_conffile;
- }
- if (-f $sourcevm_conffile) {
- my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
- PVE::Tools::file_set_contents($clonevm_conffile, $data);
- }
- });
+ return PVE::Firewall::Helpers::clone_vmfw_conf(@_);
}
sub read_vm_firewall_configs {
next if $entry->{errors}; # skip entries with errors
eval {
my ($cidr, $ver);
- if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
- ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
+ if ($entry->{cidr} =~ m@^(dc/|guest/)?(${ip_alias_pattern})$@) {
+ my $scope = $1 // "";
+ my $alias = $2;
+ ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $alias, $scope);
} else {
($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
}
$hashsize = round_powerof2($hashsize);
}
+ my $bucketsize = 12; # lower than the default of 14, faster but slightly more memory use
+
my $family = $ipversion == "6" ? "inet6" : "inet";
- $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
+ $ipset_ruleset->{$name} = [
+ "create $name hash:net family $family hashsize $hashsize maxelem $hashsize bucketsize $bucketsize"
+ ];
foreach my $cidr (sort keys %$data) {
my $entry = $data->{$cidr};
}
}
-sub lock_hostfw_conf {
- my ($timeout, $code, @param) = @_;
+sub lock_hostfw_conf : prototype($$$@) {
+ my ($node, $timeout, $code, @param) = @_;
+
+ $node = $nodename if !defined($node);
- my $res = PVE::Cluster::cfs_lock_firewall("host-$nodename", $timeout, $code, @param);
+ my $res = PVE::Cluster::cfs_lock_firewall("host-$node", $timeout, $code, @param);
die $@ if $@;
return $res;
}
sub save_hostfw_conf {
- my ($hostfw_conf) = @_;
+ my ($hostfw_conf, $filename) = @_;
+
+ $filename = $hostfw_conf_filename if !defined($filename);
my $raw = '';
}
if ($raw) {
- PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
+ PVE::Tools::file_set_contents($filename, $raw);
} else {
- unlink $hostfw_conf_filename;
+ unlink $filename;
}
}
my $hostfw_options = $hostfw_conf->{options} || {};
my $protection_synflood = $hostfw_options->{protection_synflood} || 0;
+ my $conntrack_helpers = $hostfw_options->{nf_conntrack_helpers} || '';
+
+ ruleset_create_chain($ruleset, "PVEFW-PREROUTING") if $protection_synflood != 0 || $conntrack_helpers ne '';
if($protection_synflood) {
$protection_synflood_expire = $protection_synflood_expire * 1000;
my $protection_synflood_mask = $ipversion == 4 ? 32 : 64;
- ruleset_create_chain($ruleset, "PVEFW-PREROUTING");
ruleset_addrule($ruleset, "PVEFW-PREROUTING", "-p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -m hashlimit --hashlimit-above $protection_synflood_rate/sec --hashlimit-burst $protection_synflood_burst --hashlimit-mode srcip --hashlimit-name syn --hashlimit-htable-size 2097152 --hashlimit-srcmask $protection_synflood_mask --hashlimit-htable-expire $protection_synflood_expire", "-j DROP");
}
+ foreach my $conntrack_helper (split(/,/, $conntrack_helpers)) {
+ my $helper = $pve_fw_helpers->{$conntrack_helper};
+ ruleset_addrule($ruleset, "PVEFW-PREROUTING", "-p $helper->{proto} -m $helper->{proto} --dport $helper->{dport} -j CT", "--helper $conntrack_helper") if $helper && $helper->{"v$ipversion"};
+ }
+
return $ruleset;
}
eval {
my $conf = $vmdata->{qemu}->{$vmid};
my $vmfw_conf = $vmfw_configs->{$vmid};
- return if !$vmfw_conf;
+ return if !$vmfw_conf || !$vmfw_conf->{options}->{enable};
my $ipsets = $vmfw_conf->{ipset};
foreach my $netid (sort keys %$conf) {
ruleset_create_chain($ruleset, $tapchain);
if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
- ruleset_addrule($ruleset, $tapchain, "-s ! $macaddr", '-j DROP');
+ ruleset_addrule($ruleset, $tapchain, "-s ! $macaddr", '-j DROP');
}
if (@$arpfilter){
ebtables_restore_cmdlist(get_ebtables_cmdlist({}));
}
-sub init {
- my $cluster_conf = load_clusterfw_conf();
- my $cluster_options = $cluster_conf->{options};
- my $enable = $cluster_options->{enable};
+sub is_nftables {
+ my ($cluster_conf, $host_conf) = @_;
+
+ if (!-x "/usr/libexec/proxmox/proxmox-firewall") {
+ return 0;
+ }
- return if !$enable;
+ $cluster_conf = load_clusterfw_conf() if !defined($cluster_conf);
+ $host_conf = load_hostfw_conf($cluster_conf) if !defined($host_conf);
+
+ return $host_conf->{options}->{nftables};
+}
+
+sub is_enabled_and_not_nftables {
+ my ($cluster_conf, $host_conf) = @_;
+
+ $cluster_conf = load_clusterfw_conf() if !defined($cluster_conf);
+ $host_conf = load_hostfw_conf($cluster_conf) if !defined($host_conf);
+
+ return $cluster_conf->{options}->{enable} && !is_nftables($cluster_conf, $host_conf);
+}
+
+sub init {
+ return if !is_enabled_and_not_nftables();
# load required modules here
}
my $code = sub {
my $cluster_conf = load_clusterfw_conf();
- my $cluster_options = $cluster_conf->{options};
+ my $hostfw_conf = load_hostfw_conf($cluster_conf);
- if (!$cluster_options->{enable}) {
+ if (!is_enabled_and_not_nftables($cluster_conf, $hostfw_conf)) {
PVE::Firewall::remove_pvefw_chains();
return;
}
- my $hostfw_conf = load_hostfw_conf($cluster_conf);
my ($ruleset, $ipset_ruleset, $rulesetv6, $ebtables_ruleset) = compile($cluster_conf, $hostfw_conf);
--- /dev/null
+package PVE::Firewall::Helpers;
+
+use strict;
+use warnings;
+
+use Date::Parse qw(str2time);
+use Errno qw(ENOENT);
+use File::Basename qw(fileparse);
+use IO::Zlib;
+use PVE::Cluster;
+use PVE::Tools qw(file_get_contents file_set_contents);
+
+use base 'Exporter';
+our @EXPORT_OK = qw(
+lock_vmfw_conf
+remove_vmfw_conf
+clone_vmfw_conf
+collect_refs
+);
+
+my $pvefw_conf_dir = "/etc/pve/firewall";
+
+sub lock_vmfw_conf {
+ my ($vmid, $timeout, $code, @param) = @_;
+
+ die "can't lock VM firewall config for undefined VMID\n"
+ if !defined($vmid);
+
+ my $res = PVE::Cluster::cfs_lock_firewall("vm-$vmid", $timeout, $code, @param);
+ die $@ if $@;
+
+ return $res;
+}
+
+sub remove_vmfw_conf {
+ my ($vmid) = @_;
+
+ my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
+
+ unlink $vmfw_conffile;
+}
+
+sub clone_vmfw_conf {
+ my ($vmid, $newid) = @_;
+
+ my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
+ my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
+
+ lock_vmfw_conf($newid, 10, sub {
+ if (-f $clonevm_conffile) {
+ unlink $clonevm_conffile;
+ }
+ if (-f $sourcevm_conffile) {
+ my $data = file_get_contents($sourcevm_conffile);
+ file_set_contents($clonevm_conffile, $data);
+ }
+ });
+}
+
+sub dump_fw_logfile {
+ my ($filename, $param, $callback) = @_;
+ my ($start, $limit, $since, $until) = $param->@{qw(start limit since until)};
+
+ my $filter = sub {
+ my ($line) = @_;
+
+ if (defined($callback)) {
+ return undef if !$callback->($line);
+ }
+
+ if ($since || $until) {
+ my @words = split / /, $line;
+ my $timestamp = str2time($words[3], $words[4]);
+ return undef if $since && $timestamp < $since;
+ return undef if $until && $timestamp > $until;
+ }
+
+ return $line;
+ };
+
+ if (!defined($since) && !defined($until)) {
+ return PVE::Tools::dump_logfile($filename, $start, $limit, $filter);
+ }
+
+ my %state = (
+ 'count' => 0,
+ 'lines' => [],
+ 'start' => $start,
+ 'limit' => $limit,
+ );
+
+ # Take into consideration also rotated logs
+ my ($basename, $logdir, $type) = fileparse($filename);
+ my $regex = qr/^\Q$basename\E(\.[\d]+(\.gz)?)?$/;
+ my @files = ();
+
+ PVE::Tools::dir_glob_foreach($logdir, $regex, sub {
+ my ($file) = @_;
+ push @files, $file;
+ });
+
+ @files = reverse sort @files;
+
+ my $filecount = 0;
+ for my $filename (@files) {
+ $state{'final'} = $filecount == $#files;
+ $filecount++;
+
+ my $fh;
+ if ($filename =~ /\.gz$/) {
+ $fh = IO::Zlib->new($logdir.$filename, "r");
+ } else {
+ $fh = IO::File->new($logdir.$filename, "r");
+ }
+
+ if (!$fh) {
+ # If file vanished since reading dir entries, ignore
+ next if $!{ENOENT};
+
+ my $lines = $state{'lines'};
+ my $count = ++$state{'count'};
+ push @$lines, ($count, { n => $count, t => "unable to open file - $!"});
+ last;
+ }
+
+ PVE::Tools::dump_logfile_by_filehandle($fh, $filter, \%state);
+
+ close($fh);
+ }
+
+ return ($state{'count'}, $state{'lines'});
+}
+
+sub collect_refs {
+ my ($conf, $type, $scope) = @_;
+
+
+ my $res = [];
+
+ if (!$type || $type eq 'ipset') {
+ foreach my $name (keys %{$conf->{ipset}}) {
+ my $data = {
+ type => 'ipset',
+ name => $name,
+ ref => "+$name",
+ scope => $scope,
+ };
+ if (my $comment = $conf->{ipset_comments}->{$name}) {
+ $data->{comment} = $comment;
+ }
+ push @$res, $data;
+ }
+ }
+
+ if (!$type || $type eq 'alias') {
+ foreach my $name (keys %{$conf->{aliases}}) {
+ my $e = $conf->{aliases}->{$name};
+ my $data = {
+ type => 'alias',
+ name => $name,
+ ref => $name,
+ scope => $scope,
+ };
+ $data->{comment} = $e->{comment} if $e->{comment};
+ push @$res, $data;
+ }
+ }
+
+ return $res;
+}
+
+1;
--- /dev/null
+DESTDIR=
+PREFIX=/usr
+PERLDIR=$(DESTDIR)/$(PREFIX)/share/perl5
+
+SOURCES=Helpers.pm
+
+.PHONY: install
+install: $(SOURCES)
+ install -d -m 0755 $(PERLDIR)/PVE/Firewall
+ for i in $(SOURCES); do install -D -m 0644 $$i $(PERLDIR)/PVE/Firewall/$$i; done
+
+clean:
use File::Basename;
use Net::IP;
+use base 'Exporter';
+our @EXPORT_OK = qw(
+$bridge_name_pattern
+$bridge_interface_pattern
+);
+
# dynamically include PVE::QemuServer and PVE::LXC
# to avoid dependency problems
my $have_qemu_server;
my $NUMBER_RE = qr/0x[0-9a-fA-F]+|\d+/;
+our $bridge_name_pattern = '[a-zA-Z][a-zA-Z0-9]{0,9}';
+our $bridge_interface_pattern = "($bridge_name_pattern)/(\\S+)";
+
sub debug {
my $new_value = shift;
$debug = $new_value if defined($new_value);
$pkg->{physdev_in} = $target->{fwln} || die 'internal error';
$pkg->{physdev_out} = $target->{tapdev} || die 'internal error';
- } elsif ($route_state =~ m/^vmbr\d+$/) {
+ } elsif ($route_state =~ m/^$bridge_name_pattern$/) {
die "missing physdev_in - internal error?" if !$physdev_in;
$pkg->{physdev_in} = $physdev_in;
$from_info->{type} = 'host';
$start_state = 'host';
$pkg->{source} = $host_ip if !defined($pkg->{source});
- } elsif ($from =~ m|^(vmbr\d+)/(\S+)$|) {
- $from_info->{type} = 'bport';
- $from_info->{bridge} = $1;
- $from_info->{iface} = $2;
- $start_state = 'from-bport';
} elsif ($from eq 'outside') {
$from_info->{type} = 'bport';
$from_info->{bridge} = 'vmbr0';
$from_info = extract_vm_info($vmdata, $vmid, $netnum);
$start_state = 'fwbr-out';
$pkg->{mac_source} = $from_info->{macaddr};
+ } elsif ($from =~ m|^$bridge_interface_pattern$|) {
+ $from_info->{type} = 'bport';
+ $from_info->{bridge} = $1;
+ $from_info->{iface} = $2;
+ $start_state = 'from-bport';
} else {
die "unable to parse \"from => '$from'\"\n";
}
$target->{type} = 'host';
$target->{iface} = 'host';
$pkg->{dest} = $host_ip if !defined($pkg->{dest});
- } elsif ($to =~ m|^(vmbr\d+)/(\S+)$|) {
- $target->{type} = 'bport';
- $target->{bridge} = $1;
- $target->{iface} = $2;
} elsif ($to eq 'outside') {
$target->{type} = 'bport';
$target->{bridge} = 'vmbr0';
my $vmid = $1;
$target = extract_vm_info($vmdata, $vmid, 0);
$target->{iface} = $target->{tapdev};
+ } elsif ($to =~ m|^$bridge_interface_pattern$|) {
+ $target->{type} = 'bport';
+ $target->{bridge} = $1;
+ $target->{iface} = $2;
} else {
die "unable to parse \"to => '$to'\"\n";
}
DESTDIR=
PREFIX= /usr
-PERLDIR=${DESTDIR}/${PREFIX}/share/perl5
+PERLDIR=$(DESTDIR)/$(PREFIX)/share/perl5
LIB_SOURCES= \
FirewallSimulator.pm \
.PHONY: install
install:
- install -d -m 0755 ${PERLDIR}/PVE
- for i in ${LIB_SOURCES}; do install -D -m 0644 $$i ${PERLDIR}/PVE/$$i; done
+ install -d -m 0755 $(PERLDIR)/PVE
+ for i in $(LIB_SOURCES); do install -D -m 0644 $$i $(PERLDIR)/PVE/$$i; done
make -C API2 install
make -C Service install
+ make -C Firewall install
.PHONY: clean
clean:
rm -rf *~
make -C API2 clean
make -C Service clean
+ make -C Firewall clean
DESTDIR=
PREFIX=/usr
-PERLDIR=${DESTDIR}/${PREFIX}/share/perl5
+PERLDIR=$(DESTDIR)/$(PREFIX)/share/perl5
SOURCES=pve_firewall.pm
.PHONY: install
-install: ${SOURCES}
- install -d -m 0755 ${PERLDIR}/PVE/Service
- for i in ${SOURCES}; do install -D -m 0644 $$i ${PERLDIR}/PVE/Service/$$i; done
+install: $(SOURCES)
+ install -d -m 0755 $(PERLDIR)/PVE/Service
+ for i in $(SOURCES); do install -D -m 0644 $$i $(PERLDIR)/PVE/Service/$$i; done
clean:
use strict;
use warnings;
-use PVE::SafeSyslog;
-use PVE::Daemon;
-use Time::HiRes qw (gettimeofday);
-use PVE::Tools qw(dir_glob_foreach file_read_firstline);
-use PVE::ProcFSTools;
-use PVE::INotify;
+use Data::Dumper;
+use Time::HiRes qw (gettimeofday usleep);
+
+use PVE::CLIHandler;
use PVE::Cluster qw(cfs_read_file);
use PVE::Corosync;
+use PVE::Daemon;
+use PVE::INotify;
+use PVE::ProcFSTools;
use PVE::RPCEnvironment;
-use PVE::CLIHandler;
+use PVE::SafeSyslog;
+use PVE::Tools qw(dir_glob_foreach file_read_firstline);
+
use PVE::Firewall;
use PVE::FirewallSimulator;
-use Data::Dumper;
+use PVE::FirewallSimulator qw($bridge_interface_pattern);
use base qw(PVE::Daemon);
my $nodename = PVE::INotify::nodename();
sub init {
-
PVE::Cluster::cfs_update();
PVE::Firewall::init();
}
-my $restart_request = 0;
-my $next_update = 0;
-
-my $cycle = 0;
+my ($next_update, $cycle, $restart_request) = (0, 0, 0);
my $updatetime = 10;
my $initial_memory_usage;
sub shutdown {
my ($self) = @_;
- syslog('info' , "server closing");
+ syslog('info' , "server shutting down");
# wait for children
1 while (waitpid(-1, POSIX::WNOHANG()) > 0);
- syslog('info' , "clear firewall rules");
+ syslog('info' , "clear PVE-generated firewall rules");
eval { PVE::Firewall::remove_pvefw_chains(); };
warn $@ if $@;
local $SIG{'__WARN__'} = 'IGNORE'; # do not fill up logs
for (;;) { # forever
-
$next_update = time() + $updatetime;
my ($ccsec, $cusec) = gettimeofday ();
PVE::Cluster::cfs_update();
PVE::Firewall::update();
};
- my $err = $@;
-
- if ($err) {
+ if (my $err = $@) {
syslog('err', "status update error: $err");
}
- my ($ccsec_end, $cusec_end) = gettimeofday ();
+ my ($ccsec_end, $cusec_end) = gettimeofday();
my $cptime = ($ccsec_end-$ccsec) + ($cusec_end - $cusec)/1000000;
syslog('info', sprintf("firewall update time (%.3f seconds)", $cptime))
$initial_memory_usage = $mem->{resident};
} else {
my $diff = $mem->{resident} - $initial_memory_usage;
- if ($diff > 5*1024*1024) {
+ if ($diff > 5 * 1024 * 1024) {
syslog ('info', "restarting server after $cycle cycles to " .
"reduce memory usage (free $mem->{resident} ($diff) bytes)");
$self->restart_daemon();
$daemon->register_start_command("Start the Proxmox VE firewall service.");
$daemon->register_restart_command(1, "Restart the Proxmox VE firewall service.");
-$daemon->register_stop_command("Stop firewall. This removes all Proxmox VE " .
- "related iptable rules. " .
- "The host is unprotected afterwards.");
+$daemon->register_stop_command(
+ "Stop the Proxmox VE firewall service. Note, stopping actively removes all Proxmox VE related"
+ ." iptable rules rendering the host potentially unprotected."
+);
__PACKAGE__->register_method ({
name => 'status',
my $localnet = PVE::Firewall::local_network() || '127.0.0.0/8';
print "network auto detect: $localnet\n";
- if ($cluster_conf->{aliases}->{local_network}) {
- print "using user defined local_network: $cluster_conf->{aliases}->{local_network}->{cidr}\n";
+ if (my $local_network = $cluster_conf->{aliases}->{local_network}) {
+ print "using user defined local_network: $local_network->{cidr}\n";
} else {
print "using detected local_network: $localnet\n";
}
name => 'simulate',
path => 'simulate',
method => 'GET',
- description => "Simulate firewall rules. This does not simulate kernel 'routing' table. Instead, this simply assumes that routing from source zone to destination zone is possible.",
+ description => "Simulate firewall rules. This does not simulates the kernel 'routing' table,"
+ ." but simply assumes that routing from source zone to destination zone is possible.",
parameters => {
additionalProperties => 0,
properties => {
from => {
description => "Source zone.",
type => 'string',
- pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
+ pattern => "(host|outside|vm\\d+|ct\\d+|$bridge_interface_pattern)",
optional => 1,
default => 'outside',
},
to => {
description => "Destination zone.",
type => 'string',
- pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
+ pattern => "(host|outside|vm\\d+|ct\\d+|$bridge_interface_pattern)",
optional => 1,
default => 'host',
},
$test->{action} = 'QUERY';
- my $res = PVE::FirewallSimulator::simulate_firewall($ruleset->{filter}, $ipset_ruleset,
- $host_ip, $vmdata, $test);
+ my $res = PVE::FirewallSimulator::simulate_firewall(
+ $ruleset->{filter}, $ipset_ruleset, $host_ip, $vmdata, $test);
print "ACTION: $res\n";
/*
- Copyright (C) 2014 Proxmox Server Solutions GmbH
+ Copyright (C) 2014 - 2021 Proxmox Server Solutions GmbH
This software is written by Proxmox Server Solutions GmbH <support@proxmox.com>
LOG FORMAT:
-Special care was taken to allow fast parsing (and filer messages for a singl VM).
+Special care was taken to allow fast parsing and filering messages for a single VM.
<VMID> <LOGLEVEL> <CHAIN> <TIME> <TIMEZONE> <MSG>