├── test ├── __init__.py ├── context.py ├── test_netfilter_openvpn.py ├── test_netfilter_openvpn_iptables.py └── test_netfilter_openvpn_nftables.py ├── requirements-dev.txt ├── .gitmodules ├── TODO ├── MANIFEST.in ├── wrappers ├── netfilter_openvpn.sh ├── netfilter_openvpn_sync.py └── netfilter_openvpn_async.py ├── requirements.txt ├── sudoers.inc ├── systemd-only-kill-process.conf ├── netfilter_openvpn.conf.sample ├── setup.py ├── .gitignore ├── scripts ├── vpn-fw-find-user.sh └── vpn-netfilter-cleanup-ip.py ├── Makefile ├── README.rst ├── LICENSE └── netfilter_openvpn.py /test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | netaddr==1.3.0 2 | coverage==6.2 3 | mock==5.2.0 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "iamvpnlibrary"] 2 | path = iamvpnlibrary 3 | url = https://github.com/mozilla-it/iamvpnlibrary.git 4 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | - perhaps a better/dedicated rule cleanup script per user instead of calling the async. 2 | - reinstate deferred plugin support when openvpn has support for deferred learn-address plugins 3 | - implement ipv6 4 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include TODO 3 | include requirements.txt 4 | include LICENSE 5 | include netfilter_openvpn.conf.sample 6 | include sudoers.inc 7 | recursive-include wrappers * 8 | recursive-include scripts * 9 | -------------------------------------------------------------------------------- /test/context.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Adjustments to allow the tests to be run against the local module 3 | ''' 4 | import os 5 | import sys 6 | sys.path.insert(0, os.path.abspath('..')) 7 | sys.path.insert(1, 'iamvpnlibrary') 8 | 9 | sys.dont_write_bytecode = True 10 | -------------------------------------------------------------------------------- /wrappers/netfilter_openvpn.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # This is a simple sudo wrapper for the synchronous part of the learn script. 3 | # This avoids us putting a sudo into the VPN config directly. 4 | # 5 | # This is required so that we can escalate to root and do OS-level activities. 6 | SUDO=/usr/bin/sudo 7 | 8 | ${SUDO} /usr/lib/openvpn/plugins/netfilter_openvpn_sync.py "$@" 9 | exit $? 10 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # The install here is more for your testing venv than anything. I mean, really, 'just use the nftables that ships with the system' because you're interacting with the system, right? 2 | nftables @ git+https://git.netfilter.org/nftables@v1.1.3#subdirectory=py 3 | 4 | # Strictly speaking, THIS module does not require python-ldap, but it is needed by the internal library iamvpnlibrary. 5 | #python-ldap==3.4.3 6 | ###################### 7 | # python-ldap dependencies 8 | #pyasn1==0.6.1 9 | #pyasn1_modules==0.4.2 10 | -------------------------------------------------------------------------------- /sudoers.inc: -------------------------------------------------------------------------------- 1 | # 2 | # Preserve the untrusted_ip and untrusted_port variables so that the 3 | # netfilter scripts have access to them for reporting purposes. 4 | # username is passed in as the pathway to 'sudo' within the VPN. 5 | Defaults:openvpn env_keep += "untrusted_ip untrusted_port username" 6 | # 7 | # This is so openvpn can call the main python script with enough permissions 8 | # to call system-binary for OS-level changes. 9 | openvpn ALL=NOPASSWD: /usr/lib/openvpn/plugins/netfilter_openvpn_async.py 10 | # This is for the sync script to do initial quick lockdowns. 11 | openvpn ALL=NOPASSWD: /usr/lib/openvpn/plugins/netfilter_openvpn_sync.py 12 | -------------------------------------------------------------------------------- /systemd-only-kill-process.conf: -------------------------------------------------------------------------------- 1 | [Service] 2 | # 3 | # netfilter_openvpn.sh forks off netfilter_openvpn.py in order to delete 4 | # rules as the process shuts down. systemd.kill(5) in its 5 | # default KillMode=control-group will kill those forks before they have a 6 | # chance to do their work. Rather than un-fork them and potentially create 7 | # runtime issues, we pay the penalty at shutdown time. 8 | # 9 | # There is a slight risk that you could blow out TimeoutStopSec from 10 | # systemd.service(5), but the CentOS default is around 90s. If you exceed 11 | # that, you may leave orphans, but you probably have bigger 12 | # issues on the server at that point. 13 | # 14 | KillMode=process 15 | -------------------------------------------------------------------------------- /netfilter_openvpn.conf.sample: -------------------------------------------------------------------------------- 1 | [openvpn-netfilter] 2 | # This section contains tweakable items that you may / may not need. 3 | # If the defaults from the sample are sufficient, then you can get by 4 | # without any config file for netfilter_openvpn. 5 | # 6 | # Path to executables 7 | ; framework = iptables 8 | ; iptables_executable = /sbin/iptables 9 | ; ipset_executable = /usr/sbin/ipset 10 | ; nftables_table = openvpn_netfilter 11 | 12 | # Script locking, so all work completes atomically with respect to 13 | # other invocations of this script 14 | # What external lock file to use: 15 | ; LOCKPATH = /var/run/openvpn_netfilter.lock 16 | # Number of seconds (integer) per try to lock the file 17 | ; LOCKWAITTIME = 2 18 | # Number of times to try to lock the file 19 | ; LOCKRETRIESMAX = 10 20 | 21 | syslog-events-send = False 22 | syslog-events-facility = local5 23 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Setup script for the library. 3 | This packages the library file that integration scripts will use. 4 | """ 5 | # This Source Code Form is subject to the terms of the Mozilla Public 6 | # License, v. 2.0. If a copy of the MPL was not distributed with this 7 | # file, You can obtain one at http://mozilla.org/MPL/2.0/. 8 | # Copyright (c) 2019 Mozilla Corporation 9 | # Author: gcox@mozilla.com 10 | # derived from original Author: gdestuynder@mozilla.com 11 | 12 | import os 13 | import subprocess 14 | from setuptools import setup 15 | 16 | VERSION = '1.3.0' 17 | 18 | 19 | def git_version(): 20 | """ Return the git revision as a string """ 21 | def _minimal_ext_cmd(cmd): 22 | # construct minimal environment 23 | env = {} 24 | for envvar in ['SYSTEMROOT', 'PATH']: 25 | val = os.environ.get(envvar) 26 | if val is not None: 27 | env[envvar] = val 28 | # LANGUAGE is used on win32 29 | env['LANGUAGE'] = 'C' 30 | env['LANG'] = 'C' 31 | env['LC_ALL'] = 'C' 32 | out = subprocess.Popen(cmd, stdout=subprocess.PIPE, 33 | env=env).communicate()[0] 34 | return out 35 | 36 | try: 37 | out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) 38 | git_revision = out.strip().decode('ascii') 39 | except OSError: 40 | git_revision = 'Unknown' 41 | 42 | return git_revision 43 | 44 | 45 | setup( 46 | name='openvpn-netfilter', 47 | py_modules=['netfilter_openvpn'], 48 | version=VERSION, 49 | author='Greg Cox', 50 | author_email='gcox@mozilla.com', 51 | description=('A library to implement netfilter ' + 52 | 'rules per connected user\n' + 53 | 'This package is built upon commit ' + git_version()), 54 | license='MPL', 55 | keywords="vpn netfilter", 56 | url="https://github.com/mozilla-it/openvpn-netfilter", 57 | long_description=open('README.rst', 'r', encoding='utf-8').read(), 58 | install_requires=['iamvpnlibrary>=0.9.0'], 59 | classifiers=[ 60 | "Development Status :: 5 - Production/Stable", 61 | "Topic :: System :: Logging", 62 | "Topic :: Software Development :: Libraries :: Python Modules", 63 | "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", 64 | ], 65 | ) 66 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Our config file: 2 | netfilter_openvpn.conf 3 | # RPMs that get built 4 | openvpn-netfilter-*.rpm 5 | python-openvpn-netfilter-*.rpm 6 | # The upstream library config files, just in case we're testing locally. 7 | iamvpnlibrary.conf 8 | 9 | # Imported from https://github.com/github/gitignore/raw/master/Python.gitignore 10 | # Byte-compiled / optimized / DLL files 11 | __pycache__/ 12 | *.py[cod] 13 | *$py.class 14 | 15 | # C extensions 16 | *.so 17 | 18 | # Distribution / packaging 19 | .Python 20 | build/ 21 | develop-eggs/ 22 | dist/ 23 | downloads/ 24 | eggs/ 25 | .eggs/ 26 | lib/ 27 | lib64/ 28 | parts/ 29 | sdist/ 30 | var/ 31 | wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .coverage 51 | .coverage.* 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | *.cover 56 | .hypothesis/ 57 | .pytest_cache/ 58 | 59 | # Translations 60 | *.mo 61 | *.pot 62 | 63 | # Django stuff: 64 | *.log 65 | local_settings.py 66 | db.sqlite3 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | .python-version 90 | 91 | # celery beat schedule file 92 | celerybeat-schedule 93 | 94 | # SageMath parsed files 95 | *.sage.py 96 | 97 | # Environments 98 | .env 99 | .venv 100 | env/ 101 | venv/ 102 | ENV/ 103 | env.bak/ 104 | venv.bak/ 105 | 106 | # Spyder project settings 107 | .spyderproject 108 | .spyproject 109 | 110 | # Rope project settings 111 | .ropeproject 112 | 113 | # mkdocs documentation 114 | /site 115 | 116 | # mypy 117 | .mypy_cache/ 118 | .dmypy.json 119 | dmypy.json 120 | 121 | 122 | # Imported from https://github.com/github/gitignore/raw/master/Global/Vim.gitignore 123 | # swap 124 | [._]*.s[a-v][a-z] 125 | [._]*.sw[a-p] 126 | [._]s[a-v][a-z] 127 | [._]sw[a-p] 128 | 129 | # Session 130 | Session.vim 131 | 132 | # Temporary 133 | .netrwhist 134 | *~ 135 | # Auto-generated tag files 136 | tags 137 | 138 | -------------------------------------------------------------------------------- /scripts/vpn-fw-find-user.sh: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env bash 2 | # Version: MPL 1.1/GPL 2.0/LGPL 2.1 3 | # 4 | # The contents of this file are subject to the Mozilla Public License Version 5 | # 1.1 (the "License"); you may not use this file except in compliance with 6 | # the License. You may obtain a copy of the License at 7 | # http://www.mozilla.org/MPL/ 8 | # 9 | # Software distributed under the License is distributed on an "AS IS" basis, 10 | # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 11 | # for the specific language governing rights and limitations under the 12 | # License. 13 | # 14 | # The Original Code is the vpn-fw-find-user.sh for the OpenVPN Netfilter plugin 15 | # 16 | # The Initial Developer of the Original Code is 17 | # Mozilla Corporation 18 | # Portions created by the Initial Developer are Copyright (C) 2012 19 | # the Initial Developer. All Rights Reserved. 20 | # 21 | # Contributor(s): 22 | # jvehent@mozilla.com (ulfr) 23 | # 24 | # Alternatively, the contents of this file may be used under the terms of 25 | # either the GNU General Public License Version 2 or later (the "GPL"), or 26 | # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), 27 | # in which case the provisions of the GPL or the LGPL are applicable instead 28 | # of those above. If you wish to allow use of your version of this file only 29 | # under the terms of either the GPL or the LGPL, and not to allow others to 30 | # use your version of this file under the terms of the MPL, indicate your 31 | # decision by deleting the provisions above and replace them with the notice 32 | # and other provisions required by the GPL or the LGPL. If you do not delete 33 | # the provisions above, a recipient may use your version of this file under 34 | # the terms of any one of the MPL, the GPL or the LGPL. 35 | if [ -z "$1" ]; then 36 | echo "usage: $0 " 37 | echo "search for a vpn user that matches the input, and display all firewall rules" 38 | exit 1 39 | fi 40 | usercn=$1 41 | useriplist=$(iptables -L -v -n | grep "$usercn" | grep match-set | awk '{print $11}') 42 | groupslist=$(iptables -L -v -n | grep "$usercn" | grep match-set | awk '{print $16}' | tr ";" "\\n") 43 | # FIXME grab not by number? 44 | 45 | for userip in $useriplist; do 46 | echo -e "\\n--- $usercn has IP $userip ---" 47 | echo -e "ldap groups:\\n$(for g in $groupslist; do echo "- $g";done)" 48 | echo -e "\\n--- IPTABLES RULES ---" 49 | for chain in INPUT OUTPUT FORWARD; do 50 | iptables -L $chain -v -n | grep -E "Chain $chain|$userip" 51 | done 52 | iptables -L "$userip" -v -n 53 | echo 54 | echo -e "\\n--- IPSET HASH TABLE ---" 55 | ipset -s --list "$userip" 56 | echo -e "--- end of $usercn $userip ---\\n\\n" 57 | done 58 | -------------------------------------------------------------------------------- /scripts/vpn-netfilter-cleanup-ip.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # pylint: disable=invalid-name 3 | # This is a script, not a module 4 | """ 5 | Script to execute the delete_chain function and remove leftover 6 | rule debris as needed. 7 | """ 8 | # Version: MPL 1.1/GPL 2.0/LGPL 2.1 9 | # 10 | # The contents of this file are subject to the Mozilla Public License Version 11 | # 1.1 (the "License"); you may not use this file except in compliance with 12 | # the License. You may obtain a copy of the License at 13 | # http://www.mozilla.org/MPL/ 14 | # 15 | # Software distributed under the License is distributed on an "AS IS" basis, 16 | # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 17 | # for the specific language governing rights and limitations under the 18 | # License. 19 | # 20 | # The Original Code is the vpn-netfilter-clean-ip.sh for OpenVPN Netfilter.py 21 | # 22 | # The Initial Developer of the Original Code is 23 | # Mozilla Corporation 24 | # Portions created by the Initial Developer are Copyright (C) 2012 25 | # the Initial Developer. All Rights Reserved. 26 | # 27 | # Contributor(s): 28 | # gcox@mozilla.com 29 | # 30 | # Alternatively, the contents of this file may be used under the terms of 31 | # either the GNU General Public License Version 2 or later (the "GPL"), or 32 | # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), 33 | # in which case the provisions of the GPL or the LGPL are applicable instead 34 | # of those above. If you wish to allow use of your version of this file only 35 | # under the terms of either the GPL or the LGPL, and not to allow others to 36 | # use your version of this file under the terms of the MPL, indicate your 37 | # decision by deleting the provisions above and replace them with the notice 38 | # and other provisions required by the GPL or the LGPL. If you do not delete 39 | # the provisions above, a recipient may use your version of this file under 40 | # the terms of any one of the MPL, the GPL or the LGPL. 41 | 42 | import sys 43 | import netfilter_openvpn 44 | sys.dont_write_bytecode = True 45 | 46 | 47 | def main(): 48 | """ 49 | A scripting failure can leave behind debris. 50 | This script aims to help clean up after accidents in testing. 51 | Uses the locking mechanism of the library, so should be safe 52 | to use even on a production system. 53 | """ 54 | _usage = ('USAGE: {program} user_ip\n' 55 | 'find the firewall rules for a ' 56 | 'specific VPN IP and delete them all') 57 | if len(sys.argv) < 2: 58 | print(_usage.format(program=sys.argv[0])) 59 | return False 60 | userip = sys.argv[1] 61 | 62 | nf_object = netfilter_openvpn.NetfilterOpenVPN() 63 | nf_object.set_targets(client_ip=userip) 64 | 65 | if not nf_object.acquire_lock(): 66 | # never obtained a lock, get out 67 | return False 68 | 69 | chain_work_status = nf_object.del_chain() 70 | 71 | nf_object.free_lock() 72 | return chain_work_status 73 | 74 | if __name__ == "__main__": 75 | if main(): 76 | sys.exit(0) 77 | else: 78 | sys.exit(1) 79 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | INSTALL := install 2 | DESTDIR := / 3 | PREFIX := /usr 4 | PACKAGE := openvpn-netfilter 5 | VERSION := 1.3.0 6 | .DEFAULT: coverage 7 | .PHONY: coverage coveragereport pep8 pylint pythonrpm rpm pythonrpm3 servicerpm pypi install clean 8 | TEST_FLAGS_FOR_SUITE := -m unittest discover -f 9 | 10 | PLAIN_PYTHON = $(shell which python 2>/dev/null) 11 | PYTHON3 = $(shell which python3 2>/dev/null) 12 | ifneq (, $(PYTHON3)) 13 | PYTHON_BIN = $(PYTHON3) 14 | PY_PACKAGE_PREFIX = python3 15 | RPM_MAKE_TARGET = pythonrpm3 16 | endif 17 | ifneq (, $(PLAIN_PYTHON)) 18 | PYTHON_BIN = $(PLAIN_PYTHON) 19 | PY_PACKAGE_PREFIX = python 20 | RPM_MAKE_TARGET = pythonrpm3 21 | endif 22 | 23 | COVERAGE = $(shell which coverage 2>/dev/null) 24 | 25 | coverage: 26 | $(COVERAGE) run $(TEST_FLAGS_FOR_SUITE) -s test 27 | @rm -rf test/__pycache__ 28 | @rm -f netfilter_openvpn.pyc test/*.pyc 29 | 30 | coveragereport: 31 | $(COVERAGE) report -m netfilter_openvpn.py test/*.py 32 | 33 | pythonrpm: $(RPM_MAKE_TARGET) 34 | 35 | pythonrpm3: 36 | fpm -s python -t rpm --python-bin $(PYTHON_BIN) --python-package-name-prefix $(PY_PACKAGE_PREFIX) --rpm-dist "$$(rpmbuild -E '%{?dist}' | sed -e 's#^\.##')" \ 37 | -d iptables -d ipset \ 38 | -d python3-nftables \ 39 | --iteration 1 setup.py 40 | @rm -rf openvpn_netfilter.egg-info 41 | 42 | # FIXME: summary description git? 43 | servicerpm: 44 | $(MAKE) DESTDIR=./tmp install 45 | fpm -s dir -t rpm --rpm-dist "$$(rpmbuild -E '%{?dist}' | sed -e 's#^\.##')" \ 46 | -d "$(PY_PACKAGE_PREFIX)-$(PACKAGE) >= 1.1.4" -d openvpn \ 47 | -n $(PACKAGE) -v $(VERSION) \ 48 | --url https://github.com/mozilla-it/openvpn-netfilter \ 49 | --iteration 1 \ 50 | -a noarch -C tmp etc usr 51 | rm -rf ./tmp 52 | 53 | rpm: pythonrpm servicerpm 54 | 55 | pep8: 56 | @find ./* `git submodule --quiet foreach 'echo -n "-path ./$$path -prune -o "'` -type f -name '*.py' -exec pep8 --show-source --max-line-length=100 {} \; 57 | 58 | pylint: 59 | @find ./* `git submodule --quiet foreach 'echo -n "-path ./$$path -prune -o "'` -path ./test -prune -o -type f -name '*.py' -exec pylint -r no --rcfile=/dev/null {} \; 60 | @find ./test -type f -name '*.py' -exec pylint -r no --disable=protected-access,locally-disabled --rcfile=/dev/null {} \; 61 | 62 | pypi: 63 | python setup.py sdist check upload --sign 64 | 65 | install: 66 | mkdir -p $(DESTDIR)$(PREFIX)/lib/openvpn/plugins 67 | mkdir -p $(DESTDIR)/etc/systemd/system/openvpn@.service.d 68 | mkdir -p $(DESTDIR)/etc/sudoers.d 69 | mkdir -p $(DESTDIR)$(PREFIX)/bin 70 | $(INSTALL) -m755 wrappers/netfilter_openvpn.sh $(DESTDIR)$(PREFIX)/lib/openvpn/plugins/ 71 | $(INSTALL) -m755 wrappers/netfilter_openvpn_sync.py $(DESTDIR)$(PREFIX)/lib/openvpn/plugins/ 72 | $(INSTALL) -m755 wrappers/netfilter_openvpn_async.py $(DESTDIR)$(PREFIX)/lib/openvpn/plugins/ 73 | $(INSTALL) -m755 scripts/vpn-fw-find-user.sh $(DESTDIR)$(PREFIX)/bin 74 | $(INSTALL) -m755 scripts/vpn-netfilter-cleanup-ip.py $(DESTDIR)$(PREFIX)/bin 75 | $(INSTALL) -m440 sudoers.inc $(DESTDIR)/etc/sudoers.d/openvpn-netfilter 76 | $(INSTALL) -m644 systemd-only-kill-process.conf $(DESTDIR)/etc/systemd/system/openvpn@.service.d/only-kill-process.conf 77 | sed -i "1c#!$(PYTHON_BIN)" $(DESTDIR)$(PREFIX)/lib/openvpn/plugins/*.py $(DESTDIR)$(PREFIX)/bin/*.py 78 | 79 | clean: 80 | rm -f netfilter_openvpn.pyc test/*.pyc 81 | rm -rf __pycache__ 82 | rm -rf dist sdist build 83 | rm -rf openvpn_netfilter.egg-info 84 | rm -rf tmp 85 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | openvpn-netfilter 2 | ================= 3 | 4 | Per-VPN-user network ACLs using Netfilter and OpenVPN. 5 | 6 | Setup 7 | ===== 8 | 9 | There are effectively two packages to this repo. 10 | * python-openvpn-netfilter - a python library that does all of the filtering 11 | * openvpn-netfilter - a series of scripts and configurations to allow integration with openvpn. 12 | 13 | openvpn integration: 14 | .. code:: 15 | 16 | learn-address /usr/lib/openvpn/plugins/netfilter_openvpn.sh 17 | 18 | This shell wrapper makes a sudo call to one of the scripts, ```netfilter_openvpn_sync.py``` 19 | While these scripts are fast, there are calls to IAM systems that may hang, and that would be felt by all VPN users. 20 | To minimize that impact, the synchronous script blocks all connections from the client IP, forks a call to ```netfilter_openvpn_async.py```, and returns control to openvpn. 21 | The forked ```netfilter_openvpn_async.py``` then finishes the rule setup. 22 | 23 | Change the settings in /etc/netfilter_openvpn.conf if needed. 24 | Make sure that the paths of the 'iptables', 'ipset', and 'nft' are correct for your OS. Somewhat-conventional defaults are present without a config. 25 | 26 | Obviously this filtering depends on having proper client routes for the network/IPs you allow, so consider the routes. 27 | 28 | Script logic 29 | ============ 30 | 31 | learn-address is an OpenVPN hook called when the remote client is allocated an IP address by the VPN server side. Given the user and now-allocated client IP, we load the netfilter (iptables/x/nft) rules for that user and apply them to that client IP address. 32 | 33 | If the script fails for any reason, OpenVPN will deny packets to come through. 34 | 35 | When a user successfully connects to OpenVPN, netfilter.py will create a set for firewall rules for this user. 36 | The custom rules are added into a new chain named after the VPN IP of the user. 37 | 38 | .. code:: 39 | 40 | Chain 172.16.248.50 (3 references) 41 | pkts bytes target prot opt in out source destination 42 | 5925 854K ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 ctstate ESTABLISHED /* ulfr at 172.16.248.50 */ 43 | 688 46972 ACCEPT all -- * * 172.16.248.50 0.0.0.0/0 match-set 172.16.248.50 dst /* ulfr groups: vpn_caribou;vpn_pokemon;vpn_ninjas; */ 44 | 24 2016 LOG all -- * * 0.0.0.0/0 0.0.0.0/0 /* ulfr at 172.16.248.50 */ LOG flags 0 level 4 prefix `DROP 172.16.248.50' 45 | 24 2016 DROP all -- * * 0.0.0.0/0 0.0.0.0/0 /* ulfr at 172.16.248.50 */ 46 | 47 | 48 | A jump target is added to INPUT, OUTPUT and FORWARD to send all traffic originating from the VPN IP to the custom chain: 49 | 50 | .. code:: 51 | 52 | Chain INPUT (policy ACCEPT 92762 packets, 15M bytes) 53 | 3320 264K 172.16.248.50 all -- * * 172.16.248.50 0.0.0.0/0 54 | Chain OUTPUT (policy ACCEPT 136K packets, 138M bytes) 55 | 2196 549K 172.16.248.50 all -- * * 0.0.0.0/0 172.16.248.50 56 | Chain FORWARD (policy ACCEPT 126K packets, 127M bytes) 57 | 1120 90205 172.16.248.50 all -- * * 172.16.248.50 0.0.0.0/0 58 | 59 | 60 | You'll notice the comments are there for ease of troubleshooting, you can grep through "iptables -L -n" and find out which user or group has access to what easily. 61 | 62 | To reduce the amount of rules created, when a user ACL only contains a list of destination subnets (no ports), these subnets are added into an IPSet. The IPSet is named after the VPN IP of the user. 63 | 64 | .. code:: 65 | 66 | --- IPSET HASH TABLE --- 67 | Name: 172.16.248.50 68 | Type: hash:net 69 | Header: family inet hashsize 1024 maxelem 65536 70 | Size in memory: 17968 71 | References: 1 72 | Members: 73 | 172.39.72.0/24 74 | 172.31.0.0/16 75 | 172.11.92.150 76 | 42.89.217.202 77 | 78 | Maintenance 79 | =========== 80 | You can list the rules and sets of a particular user with the script named 'vpn-fw-find-user.sh'. 81 | 82 | You can delete all of the rules and sets of a given VPN IP using the script named 'vpn-netfilter-cleanup-ip.py'. 83 | 84 | Updates 85 | ======= 86 | 87 | The async script may be invoked by hand to refresh a user's rules while they are still connected / so they do not have to reconnect to the VPN 88 | 89 | .. code:: 90 | 91 | netfilter_openvpn_async.py update 172.16.248.50 ulfr 92 | -------------------------------------------------------------------------------- /wrappers/netfilter_openvpn_sync.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | This script is invoked by openvpn 'to apply rules upon add/delete 4 | of a VPN client.' 5 | There are quotes there because this file is INTENDED to be called 6 | by openvpn itself, but doesn't actually apply the rules. 7 | 8 | Because we make network calls in most of netfilter_openvpn, querying 9 | subsystems about user access, and because openvpn does not have a 10 | forking model/deferred plugin setup for all of its plugin calls, 11 | this script is synchronous with openvpn and seeks to exit fast, 12 | doing a minimum of work. 13 | 14 | If not, any lag caused by this script would be felt by every user 15 | of the VPN. 16 | 17 | This script puts a safety block in place, then fork/execs a new 18 | call to the heavy-lifting async script. 19 | """ 20 | import os 21 | import sys 22 | import netfilter_openvpn 23 | sys.dont_write_bytecode = True 24 | 25 | 26 | def main(): 27 | """ 28 | The main function, here we pick up variables from interfacing 29 | with openvpn itself. 30 | """ 31 | _usage = 'USAGE: {program} [add|update|delete] address [common_name]' 32 | # 33 | # untrusted_ip comes from openvpn itself and is the public IP of the 34 | # client who is connecting to us is coming from. 35 | # This is used for logging only, and is not present on 'delete'. 36 | #client_public_ip = os.environ.get('untrusted_ip', '127.0.0.1') 37 | # 38 | # untrusted_port comes from openvpn itself and is the port that the 39 | # client who is connecting to us is coming from. 40 | # This is used for logging only, and is not present on 'delete'. 41 | #client_port = os.environ.get('untrusted_port', '0') 42 | 43 | if len(sys.argv) < 3: 44 | print(_usage.format(program=sys.argv[0])) 45 | return False 46 | operation = sys.argv[1] 47 | client_private_ip = sys.argv[2] 48 | # client_private_ip is the IP that the client will be assigned after 49 | # all of this is said and done. 50 | 51 | if operation in ('add', 'update'): 52 | usercn = sys.argv[3] 53 | else: 54 | usercn = None 55 | 56 | # Pass in the username that they typed. We won't trust it without 57 | # more checks, but let's pass it in anyway. 58 | unsafe_username = os.environ.get('username', '') 59 | 60 | # Create the object. Note that there's a "must be root" 61 | # enforcer in the object initializer. 62 | nf_object = netfilter_openvpn.NetfilterOpenVPN() 63 | try: 64 | nf_object.set_targets(username_is=usercn, 65 | username_as=unsafe_username, 66 | client_ip=client_private_ip) 67 | except RuntimeError: 68 | # This is likely "we couldn't connect to LDAP" 69 | return False 70 | 71 | # This script is forked off from the openvpn process, and as such, 72 | # multiple copies of this script may be in flight at any one time. 73 | # They're all going to be "taking a while" to query IAM or get their 74 | # turn to make edits, and those edits are shell calls out to the 75 | # OS-based executables. There's a slim chance that we 76 | # could see someone connect+disconnect, and that would lead to a 77 | # case of script A being in the middle of bringup, and B doing 78 | # takedown. So we put a lock around this section of main (which, 79 | # let's be honest, means 'the whole script is locked') because 80 | # we want each execution (multiple changes to on-box firewalling) 81 | # to run to completion without races with other instances of this. 82 | # 83 | # This is far from perfect. human interference and/or system 84 | # management (puppet, ansible) would not respect our lock. But 85 | # in theory they shouldn't be doing anything to our chains anyway. 86 | # 87 | 88 | if operation == 'add': 89 | nf_object.add_safety_block() 90 | elif operation == 'update': 91 | nf_object.add_safety_block() 92 | elif operation == 'delete': 93 | nf_object.remove_safety_block() 94 | else: 95 | return False 96 | 97 | # The block is in place synchronous with openvpn. At this point, 98 | # the parent is going to do nothing else but fork a child to do 99 | # the heavy lifting. The parent needs to gracefully exit back. 100 | 101 | try: 102 | pid = os.fork() 103 | except OSError: 104 | sys.exit("Could not create a child process") 105 | 106 | if pid: 107 | # This is the parent. 108 | # The parent just needs to bail out. 109 | return True 110 | 111 | # This is the child. 112 | # This should exec away. 113 | # IMPROVEME - hardcoded script. 114 | os.execve('/usr/lib/openvpn/plugins/netfilter_openvpn_async.py', 115 | sys.argv, os.environ) 116 | # We should never get here: 117 | return False 118 | 119 | 120 | if __name__ == "__main__": 121 | if main(): 122 | sys.exit(0) 123 | else: 124 | sys.exit(1) 125 | -------------------------------------------------------------------------------- /wrappers/netfilter_openvpn_async.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | This script is invoked 'by openvpn' to apply rules upon add/delete 4 | of a VPN client. 5 | There are quotes there because this file is INTENDED to be called 6 | not by openvpn itself, but by a helper script. 7 | 8 | Because we make network calls in most of netfilter_openvpn, querying 9 | subsystems about user access, and because openvpn does not have a 10 | forking model/deferred plugin setup for all of its plugin calls, 11 | this script should be called from a forking synchronous script. 12 | 13 | If not, any lag caused by this script would be felt by every user 14 | of the VPN. 15 | """ 16 | import os 17 | import sys 18 | import netfilter_openvpn 19 | sys.dont_write_bytecode = True 20 | 21 | 22 | def main(): 23 | """ 24 | The main function, here we pick up variables from interfacing 25 | with openvpn itself. 26 | """ 27 | _usage = 'USAGE: {program} [add|update|delete] address [common_name]' 28 | # 29 | # untrusted_ip comes from openvpn itself and is the public IP of the 30 | # client who is connecting to us is coming from. 31 | # This is used for logging only, and is not present on 'delete'. 32 | client_public_ip = os.environ.get('untrusted_ip', '127.0.0.1') 33 | # 34 | # untrusted_port comes from openvpn itself and is the port that the 35 | # client who is connecting to us is coming from. 36 | # This is used for logging only, and is not present on 'delete'. 37 | client_port = os.environ.get('untrusted_port', '0') 38 | 39 | if len(sys.argv) < 3: 40 | print(_usage.format(program=sys.argv[0])) 41 | return False 42 | operation = sys.argv[1] 43 | client_private_ip = sys.argv[2] 44 | # client_private_ip is the IP that the client will be assigned after 45 | # all of this is said and done. 46 | 47 | if operation in ('add', 'update'): 48 | usercn = sys.argv[3] 49 | else: 50 | usercn = None 51 | 52 | # Pass in the username that they typed. We won't trust it without 53 | # more checks, but let's pass it in anyway. 54 | unsafe_username = os.environ.get('username', '') 55 | 56 | # Create the object. Note that there's a "must be root" 57 | # enforcer in the object initializer. 58 | nf_object = netfilter_openvpn.NetfilterOpenVPN() 59 | try: 60 | nf_object.set_targets(username_is=usercn, 61 | username_as=unsafe_username, 62 | client_ip=client_private_ip) 63 | except RuntimeError: 64 | # This is likely "we couldn't connect to LDAP" 65 | return False 66 | 67 | # This script is forked off from the openvpn process, and as such, 68 | # multiple copies of this script may be in flight at any one time. 69 | # They're all going to be "taking a while" to query IAM or get their 70 | # turn to make edits, and those edits are shell calls out to the 71 | # OS-based executables. There's a slim chance that we 72 | # could see someone connect+disconnect, and that would lead to a 73 | # case of script A being in the middle of bringup, and B doing 74 | # takedown. So we put a lock around this section of main (which, 75 | # let's be honest, means 'the whole script is locked') because 76 | # we want each execution (multiple changes to on-box firewalling) 77 | # to run to completion without races with other instances of this. 78 | # 79 | # This is far from perfect. human interference and/or system 80 | # management (puppet, ansible) would not respect our lock. But 81 | # in theory they shouldn't be doing anything to our chains anyway. 82 | # 83 | if not nf_object.acquire_lock(): 84 | # never obtained a lock, get out 85 | return False 86 | userstring = nf_object.username_string() 87 | 88 | if operation == 'add': 89 | nf_object.send_event(summary=('SUCCESS: VPN netfilter add upon connection for ' 90 | f'{userstring}'), 91 | details={'success': 'true', 92 | 'sourceipaddress': client_public_ip, 93 | 'sourceport': client_port, 94 | 'vpnip': client_private_ip, 95 | 'username': userstring, 96 | }) 97 | chain_work_status = nf_object.add_chain() 98 | elif operation == 'update': 99 | nf_object.send_event(summary=('SUCCESS: VPN netfilter add upon reconnection for ' 100 | f'{userstring}'), 101 | details={'success': 'true', 102 | 'sourceipaddress': client_public_ip, 103 | 'sourceport': client_port, 104 | 'vpnip': client_private_ip, 105 | 'username': userstring, 106 | }) 107 | chain_work_status = nf_object.update_chain() 108 | elif operation == 'delete': 109 | # There is no username here. 110 | # One could be found from the chain before we delete it if we care. 111 | nf_object.send_event(summary='SUCCESS: VPN netfilter deletes upon disconnect', 112 | details={'success': 'true', 113 | 'vpnip': client_private_ip, 114 | }) 115 | chain_work_status = nf_object.del_chain() 116 | else: 117 | # There is no username here. 118 | nf_object.send_event(summary=('FAIL: VPN netfilter failure due to' 119 | f'unknown operation "{operation}"'), 120 | details={'success': 'false', 121 | 'error': 'true', 122 | }) 123 | chain_work_status = False 124 | 125 | nf_object.free_lock() 126 | return chain_work_status 127 | 128 | 129 | if __name__ == "__main__": 130 | if main(): 131 | sys.exit(0) 132 | else: 133 | sys.exit(1) 134 | -------------------------------------------------------------------------------- /test/test_netfilter_openvpn.py: -------------------------------------------------------------------------------- 1 | ''' 2 | tests that are universal no matter which netfilter is used 3 | ''' 4 | # This Source Code Form is subject to the terms of the Mozilla Public 5 | # License, v. 2.0. If a copy of the MPL was not distributed with this 6 | # file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | # Copyright (c) 2025 Mozilla Corporation 8 | 9 | import unittest 10 | import os 11 | import time 12 | import tempfile 13 | import datetime 14 | import json 15 | import syslog 16 | import configparser 17 | import test.context # pylint: disable=unused-import 18 | import mock 19 | from netaddr import IPNetwork 20 | import iamvpnlibrary 21 | from netfilter_openvpn import NetfilterOpenVPN 22 | 23 | 24 | class TestNetfilterOpenVPN(unittest.TestCase): 25 | ''' 26 | Test the NetfilterOpenVPN class. 27 | ''' 28 | 29 | def setUp(self): 30 | # We create a library that pretends it was done by root. 31 | # If you notice in the module, this exists as a simple early filter and prevents scripts 32 | # from going into cases where root is needed. Since we're mocking here, the worry is 33 | # "well, now you can get into situations where you wouldn't otherwise. 34 | # True, but that's the point. 35 | with mock.patch('os.geteuid', return_value=0): 36 | self.library = NetfilterOpenVPN() 37 | 38 | def test_01_init_no_powers(self): 39 | ''' When we're not root, we should explode. ''' 40 | with mock.patch('os.geteuid', return_value=1000): 41 | with self.assertRaises(Exception): 42 | NetfilterOpenVPN() 43 | 44 | def test_03_ingest_no_config_files(self): 45 | """ With no config files, get an empty ConfigParser """ 46 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', new=[]): 47 | result = self.library._ingest_config_from_file() 48 | self.assertIsInstance(result, configparser.ConfigParser, 49 | 'Did not create a config object') 50 | self.assertEqual(result.sections(), [], 51 | 'Should not have found any configfile sections.') 52 | 53 | def test_04_ingest_no_config_file(self): 54 | """ With all missing config files, get an empty ConfigParser """ 55 | _not_a_real_file = '/tmp/no-such-file.txt' # nosec hardcoded_tmp_directory 56 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 57 | new=[_not_a_real_file]): 58 | result = self.library._ingest_config_from_file() 59 | self.assertIsInstance(result, configparser.ConfigParser, 60 | 'Did not create a config object') 61 | self.assertEqual(result.sections(), [], 62 | 'Should not have found any configfile sections.') 63 | 64 | def test_05_ingest_bad_config_file(self): 65 | """ With a bad config file, get an empty ConfigParser """ 66 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 67 | new=['test/context.py']): 68 | result = self.library._ingest_config_from_file() 69 | self.assertIsInstance(result, configparser.ConfigParser, 70 | 'Did not create a config object') 71 | self.assertEqual(result.sections(), [], 72 | 'Should not have found any configfile sections.') 73 | 74 | def test_06_ingest_config_from_file(self): 75 | """ With an actual config file, get a populated ConfigParser """ 76 | _not_a_real_file = '/tmp/no-such-file.txt' # nosec hardcoded_tmp_directory 77 | test_reading_file = '/tmp/test-reader.txt' # nosec hardcoded_tmp_directory 78 | with open(test_reading_file, 'w', encoding='utf-8') as filepointer: 79 | filepointer.write('[aa]\nbb = cc\n') 80 | filepointer.close() 81 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 82 | new=[_not_a_real_file, test_reading_file]): 83 | result = self.library._ingest_config_from_file() 84 | os.remove(test_reading_file) 85 | self.assertIsInstance(result, configparser.ConfigParser, 86 | 'Did not create a config object') 87 | self.assertEqual(result.sections(), ['aa'], 88 | 'Should have found one configfile section.') 89 | self.assertEqual(result.options('aa'), ['bb'], 90 | 'Should have found one option.') 91 | self.assertEqual(result.get('aa', 'bb'), 'cc', 92 | 'Should have read a correct value.') 93 | 94 | def test_08_set_targets(self): 95 | """ test set_targets """ 96 | self.library.set_targets() 97 | self.assertIsNone(self.library.client_ip, 'without args, client_ip should be none') 98 | self.assertIsNone(self.library.username_is, 'without args, username_is should be none') 99 | self.assertIsNone(self.library.username_as, 'without args, username_as should be none') 100 | self.assertIsNone(self.library.iam_object, 'without args, iam_object should be none') 101 | 102 | self.library.set_targets(username_is='a', username_as=None, client_ip='c') 103 | self.assertEqual(self.library.client_ip, 'c', 'client_ip should receive an arg') 104 | self.assertEqual(self.library.username_is, 'a', 'username_is should receive an arg') 105 | self.assertEqual(self.library.username_as, 'a', 'username_as should receive an arg') 106 | self.assertIsNone(self.library.iam_object, 'without sudoing, iam_object should be none') 107 | 108 | with mock.patch('iamvpnlibrary.IAMVPNLibrary') as mock_iam: 109 | instance = mock_iam.return_value 110 | with mock.patch.object(instance, 'verify_sudo_user', return_value='q'): 111 | self.library.set_targets(username_is='a', username_as='b', client_ip='c') 112 | self.assertEqual(self.library.client_ip, 'c', 'client_ip should receive an arg') 113 | self.assertEqual(self.library.username_is, 'a', 'username_is should receive an arg') 114 | self.assertEqual(self.library.username_as, 'q', 'username_as should calculate an arg') 115 | self.assertIsNotNone(self.library.iam_object, 'iam_object should be set when sudoing') 116 | 117 | def test_09_usernamestr(self): 118 | """ test username_string """ 119 | self.library.username_is = None 120 | self.library.username_as = None 121 | self.assertEqual(self.library.username_string(), '', 122 | "username_string must be '' before any vars are set") 123 | self.library.username_is = 'foo' 124 | self.library.username_as = None 125 | self.assertEqual(self.library.username_string(), 'foo', 126 | 'username_string must be set when IS but not AS') 127 | self.library.username_is = 'bar' 128 | self.library.username_as = 'bar' 129 | self.assertEqual(self.library.username_string(), 'bar', 130 | 'username_string must be right when IS and AS agree') 131 | self.library.username_is = 'baz' 132 | self.library.username_as = 'quux' 133 | self.assertEqual(self.library.username_string(), 'baz-sudoing-as-quux', 134 | 'username_string must list sudo when appropriate') 135 | 136 | def test_10_lock_timeout(self): 137 | ''' test the lock_timeout function ''' 138 | self.library.lockwaittime = 3 139 | with self.library._lock_timeout(): 140 | # Do something that will finish in under 3s: 141 | _dummy = 1 + 1 142 | # If all went right, we fell out of the bottom of _lock_timeout just fine. 143 | 144 | # Speed it up, we ain't got all day. 145 | self.library.lockwaittime = 1 146 | with self.assertRaises(OSError): 147 | with self.library._lock_timeout(): 148 | # Do something that can't finish in under 1s: 149 | time.sleep(3) 150 | # Here we took too long, so, timed out correctly. 151 | 152 | def test_11_acquire_lock_simple(self): 153 | ''' test the acquire_lock function when there's no hiccups ''' 154 | tmpfile = tempfile.NamedTemporaryFile() 155 | self.library.lockpath = tmpfile.name 156 | self.assertIsNone(self.library._lock) 157 | self.assertTrue(self.library.acquire_lock()) 158 | self.assertIsNotNone(self.library._lock) 159 | # Better test: is a file object ^ 160 | self.assertTrue(self.library.free_lock()) 161 | self.assertIsNone(self.library._lock) 162 | 163 | def test_12_acquire_lock_failure(self): 164 | ''' test the acquire_lock function when things go badly ''' 165 | tmpfile = tempfile.NamedTemporaryFile() 166 | self.library.lockpath = tmpfile.name 167 | self.assertIsNone(self.library._lock) 168 | with mock.patch('fcntl.flock', side_effect=IOError), \ 169 | mock.patch.object(self.library, 'send_event') as mock_logger: 170 | self.assertFalse(self.library.acquire_lock()) 171 | # Lock failure triggers an event: 172 | mock_logger.assert_called_once() 173 | 174 | def test_13_log_event_nosend(self): 175 | ''' Test the send_event method failing to send ''' 176 | self.library.event_send = False 177 | with mock.patch('syslog.openlog') as mock_openlog, \ 178 | mock.patch('syslog.syslog') as mock_syslog: 179 | self.library.send_event('some message', {'foo': 5}, 'CRITICAL') 180 | mock_openlog.assert_not_called() 181 | mock_syslog.assert_not_called() 182 | 183 | def test_14_log_event_send(self): 184 | ''' Test the send_event method tries to send ''' 185 | datetime_mock = mock.Mock(wraps=datetime.datetime) 186 | datetime_mock.now.return_value = datetime.datetime(2020, 12, 25, 13, 14, 15, 123456, tzinfo=datetime.timezone.utc) 187 | self.library.event_send = True 188 | self.library.event_facility = syslog.LOG_LOCAL1 189 | with mock.patch('syslog.openlog') as mock_openlog, \ 190 | mock.patch('syslog.syslog') as mock_syslog, \ 191 | mock.patch('datetime.datetime', new=datetime_mock), \ 192 | mock.patch('os.getpid', return_value=12345), \ 193 | mock.patch('socket.getfqdn', return_value='my.host.name'): 194 | self.library.send_event('some message', {'foo': 5}, 'CRITICAL') 195 | mock_openlog.assert_called_once_with(facility=syslog.LOG_LOCAL1) 196 | mock_syslog.assert_called_once() 197 | arg_passed_in = mock_syslog.call_args_list[0][0][0] 198 | json_sent = json.loads(arg_passed_in) 199 | details = json_sent['details'] 200 | self.assertEqual(json_sent['category'], 'authentication') 201 | self.assertEqual(json_sent['processid'], 12345) 202 | self.assertEqual(json_sent['severity'], 'CRITICAL') 203 | self.assertIn('processname', json_sent) 204 | self.assertEqual(json_sent['timestamp'], '2020-12-25T13:14:15.123456+00:00') 205 | self.assertEqual(json_sent['hostname'], 'my.host.name') 206 | self.assertEqual(json_sent['summary'], 'some message') 207 | self.assertEqual(json_sent['source'], 'openvpn') 208 | self.assertEqual(json_sent['tags'], ['vpn', 'netfilter']) 209 | self.assertEqual(details, {'foo': 5}) 210 | 211 | def test_15_chain_name(self): 212 | ''' Make sure we get a chain name based on the client_ip value ''' 213 | self.library.client_ip = '12345' 214 | self.assertEqual(self.library._chain_name(), '12345') 215 | 216 | def test_35_get_acls(self): 217 | ''' Test get_acls_for_user function ''' 218 | self.library.username_is = 'joe' 219 | self.library.username_as = 'moe' 220 | self.library.iam_object = mock.Mock() 221 | 222 | with mock.patch.object(self.library.iam_object, 'get_allowed_vpn_acls', 223 | return_value=[]): 224 | result = self.library.get_acls_for_user() 225 | self.assertEqual(result, [], 'User without IAM ACLs must get []') 226 | 227 | # stanalone ACL, WITH a port, WITH a larger group to absorb it (but can't) 228 | acl1 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.10.10/32'), 229 | portstring='80', description='') 230 | # stanalone ACL, WITH a port, WITH a larger group to absorb it (and it could be) 231 | acl2 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.10.12/32'), 232 | portstring='443', description='') 233 | # stanalone ACL, WITH a port, WITHOUT a larger group to absorb it. 234 | acl3 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.40.10/32'), 235 | portstring='80', description='') 236 | # stanalone ACL, WITHOUT a port, WITH a larger group to absorb it. 237 | acl4 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.20.11/32'), 238 | portstring='', description='') 239 | # stanalone ACL, WITHOUT a port, WITHOUT a larger group to absorb it. 240 | acl5 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.30.50.70/32'), 241 | portstring='', description='') 242 | # CIDR ACL, WITH a port, WITH a larger group to absorb it (but can't) 243 | acl6 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.10.0/27'), 244 | portstring='443', description='') 245 | # CIDR ACL, WITH a port, WITH a larger group to absorb it (and it could be) 246 | acl7 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.30.0/27'), 247 | portstring='443', description='') 248 | # CIDR ACL, WITH a port, WITHOUT a larger group to absorb it. 249 | acl8 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.30.0/24'), 250 | portstring='443', description='') 251 | # CIDR ACL, WITHOUT a port, WITH a larger group to absorb it. 252 | acl9 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.20.0/27'), 253 | portstring='', description='') 254 | # CIDR ACL, WITHOUT a port, WITHOUT a larger group to absorb it. 255 | acl10 = iamvpnlibrary.iamvpnbase.ParsedACL(rule='', address=IPNetwork('10.10.20.0/24'), 256 | portstring='', description='') 257 | 258 | # portstring-focused absorbing: 259 | with mock.patch.object(self.library.iam_object, 'get_allowed_vpn_acls', 260 | return_value=[acl1, acl5, acl6]): 261 | self.assertEqual(self.library.get_acls_for_user(), [acl6, acl1, acl5]) 262 | 263 | # portstring that COULD be absorbed, but we don't. This could be improved, so if 264 | # this test is the status quo, but don't be scared to change it. 265 | with mock.patch.object(self.library.iam_object, 'get_allowed_vpn_acls', 266 | return_value=[acl2, acl6]): 267 | self.assertEqual(self.library.get_acls_for_user(), [acl6, acl2]) 268 | 269 | # portstring that COULD be absorbed, but we don't. This could be improved, so if 270 | # this test is the status quo, but don't be scared to change it. 271 | with mock.patch.object(self.library.iam_object, 'get_allowed_vpn_acls', 272 | return_value=[acl7, acl8]): 273 | self.assertEqual(self.library.get_acls_for_user(), [acl8, acl7]) 274 | 275 | # collapsing of ranges: 276 | with mock.patch.object(self.library.iam_object, 'get_allowed_vpn_acls', 277 | return_value=[acl3, acl4, acl9, acl10]): 278 | self.assertEqual(self.library.get_acls_for_user(), [acl10, acl3]) 279 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /test/test_netfilter_openvpn_iptables.py: -------------------------------------------------------------------------------- 1 | ''' 2 | tests that are specific to iptables 3 | ''' 4 | # This Source Code Form is subject to the terms of the Mozilla Public 5 | # License, v. 2.0. If a copy of the MPL was not distributed with this 6 | # file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | # Copyright (c) 2025 Mozilla Corporation 8 | 9 | import unittest 10 | import os 11 | import syslog 12 | import test.context # pylint: disable=unused-import 13 | import mock 14 | import iamvpnlibrary 15 | from netfilter_openvpn import IptablesFailure, IpsetFailure, NetfilterOpenVPN 16 | 17 | 18 | class TestExceptionsiptables(unittest.TestCase): 19 | """ 20 | These are the tests for the class-defined Exceptions. 21 | """ 22 | 23 | def test_exceptions(self): 24 | """ Verify that the self object was initialized """ 25 | self.assertIsInstance(IptablesFailure(), IptablesFailure, 26 | 'IptablesFailure does not exist') 27 | self.assertIsInstance(IptablesFailure(), Exception, 28 | 'IptablesFailure is not an Exception') 29 | self.assertIsInstance(IpsetFailure(), IpsetFailure, 30 | 'IpsetFailure does not exist') 31 | self.assertIsInstance(IpsetFailure(), Exception, 32 | 'IpsetFailure is not an Exception') 33 | 34 | 35 | class TestNetfilterOpenVPNiptables(unittest.TestCase): 36 | ''' 37 | Test the NetfilterOpenVPN class against iptables. 38 | ''' 39 | 40 | def setUp(self): 41 | # We create a library that pretends it was done by root. 42 | # If you notice in the module, this exists as a simple early filter and prevents scripts 43 | # from going into cases where root is needed. Since we're mocking here, the worry is 44 | # "well, now you can get into situations where you wouldn't otherwise. 45 | # True, but that's the point. 46 | test_reading_file = '/tmp/test-reader.txt' # nosec hardcoded_tmp_directory 47 | with open(test_reading_file, 'w', encoding='utf-8') as filepointer: 48 | filepointer.write('[openvpn-netfilter]\n') 49 | filepointer.write('framework = iptables\n') 50 | filepointer.close() 51 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 52 | new=[test_reading_file]), \ 53 | mock.patch('os.geteuid', return_value=0): 54 | self.library = NetfilterOpenVPN() 55 | 56 | def test_07a_ingest_variables_bad(self): 57 | """ With a poor config file, check we get the right things. """ 58 | test_reading_file = '/tmp/test-reader.txt' # nosec hardcoded_tmp_directory 59 | with open(test_reading_file, 'w', encoding='utf-8') as filepointer: 60 | filepointer.write('[openvpn-netfilter]\n') 61 | filepointer.write('framework = iptables\n') 62 | filepointer.write('syslog-events-facility = blah\n') 63 | filepointer.close() 64 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 65 | new=[test_reading_file]), \ 66 | mock.patch('os.geteuid', return_value=0): 67 | library = NetfilterOpenVPN() 68 | os.remove(test_reading_file) 69 | self.assertEqual(library.nf_framework, 'iptables') 70 | self.assertEqual(library.nft, None) 71 | self.assertEqual(library.iptables_executable, '/sbin/iptables') 72 | self.assertEqual(library.ipset_executable, '/usr/sbin/ipset') 73 | #self.assertEqual(library.nftables_table, 'openvpn_netfilter') 74 | self.assertEqual(library.lockpath, '/var/run/openvpn_netfilter.lock') 75 | self.assertEqual(library.lockwaittime, 2) 76 | self.assertEqual(library.lockretriesmax, 10) 77 | self.assertEqual(library.event_send, False) 78 | self.assertEqual(library.event_facility, syslog.LOG_AUTH) 79 | 80 | def test_07b_ingest_variables_good(self): 81 | """ With an actual config file, check we get the right things. """ 82 | test_reading_file = '/tmp/test-reader.txt' # nosec hardcoded_tmp_directory 83 | with open(test_reading_file, 'w', encoding='utf-8') as filepointer: 84 | filepointer.write('[openvpn-netfilter]\n') 85 | filepointer.write('framework = iptables\n') 86 | filepointer.write('iptables_executable = /foo/bar\n') 87 | filepointer.write('ipset_executable = /foo/baz\n') 88 | filepointer.write('nftables_table = some_tablename\n') 89 | filepointer.write('LOCKPATH = /some/lock\n') 90 | filepointer.write('LOCKWAITTIME = 6\n') 91 | filepointer.write('LOCKRETRIESMAX = 12\n') 92 | filepointer.write('syslog-events-send = True\n') 93 | filepointer.write('syslog-events-facility = local0\n') 94 | filepointer.close() 95 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 96 | new=[test_reading_file]), \ 97 | mock.patch('os.geteuid', return_value=0): 98 | library = NetfilterOpenVPN() 99 | os.remove(test_reading_file) 100 | self.assertEqual(library.nf_framework, 'iptables') 101 | self.assertEqual(library.nft, None) 102 | self.assertEqual(library.iptables_executable, '/foo/bar') 103 | self.assertEqual(library.ipset_executable, '/foo/baz') 104 | #self.assertEqual(library.nftables_table, 'some_tablename') 105 | self.assertEqual(library.lockpath, '/some/lock') 106 | self.assertEqual(library.lockwaittime, 6) 107 | self.assertEqual(library.lockretriesmax, 12) 108 | self.assertEqual(library.event_send, True) 109 | self.assertEqual(library.event_facility, syslog.LOG_LOCAL0) 110 | 111 | def test_16_chain_exists_deeptest(self): 112 | ''' Check for odd cases in teardown ''' 113 | self.library.client_ip = '12345' 114 | with mock.patch.object(self.library, 'chain_exists_iptables', return_value=False), \ 115 | mock.patch.object(self.library, 'chain_exists_iptables', return_value=False): 116 | result = self.library.chain_exists() 117 | self.assertFalse(result) 118 | 119 | with mock.patch.object(self.library, 'chain_exists_iptables', return_value=True), \ 120 | mock.patch.object(self.library, 'chain_exists_ipset', return_value=False): 121 | result = self.library.chain_exists() 122 | self.assertTrue(result) 123 | 124 | with mock.patch.object(self.library, 'chain_exists_iptables', return_value=False), \ 125 | mock.patch.object(self.library, 'chain_exists_ipset', return_value=True): 126 | result = self.library.chain_exists() 127 | self.assertTrue(result) 128 | 129 | def test_16_chain_exists_iptables(self): 130 | ''' Make sure can figure out if an iptables chain exists ''' 131 | self.library.client_ip = '12345' 132 | with mock.patch.object(self.library, 'iptables', return_value='x') as mock_ipt: 133 | result = self.library.chain_exists_iptables() 134 | # Get back whatever the iptables call is: 135 | self.assertEqual(result, 'x') 136 | mock_ipt.assert_called_once_with('-L 12345', False) 137 | 138 | def test_16_chain_exists_ipset(self): 139 | ''' Make sure can figure out if an ipset chain exists ''' 140 | self.library.client_ip = '12345' 141 | with mock.patch.object(self.library, 'ipset', return_value='x') as mock_ips: 142 | result = self.library.chain_exists_ipset() 143 | # Get back whatever the ipset call is: 144 | self.assertEqual(result, 'x') 145 | mock_ips.assert_called_once_with('list 12345', False) 146 | 147 | def test_17_update_chain(self): 148 | ''' Make sure update_chain is THAT simple ''' 149 | with mock.patch.object(self.library, 'del_chain') as mock_d, \ 150 | mock.patch.object(self.library, 'add_chain', return_value='y') as mock_a: 151 | result = self.library.update_chain() 152 | # Get back whatever the add_chain call is: 153 | self.assertEqual(result, 'y') 154 | mock_d.assert_called_once_with() 155 | mock_a.assert_called_once_with() 156 | 157 | def test_18_add_chain(self): 158 | ''' Test add_chain function ''' 159 | self.library.client_ip = '3.4.5.6' 160 | 161 | # First assume horrific failure: 162 | with mock.patch.object(self.library, 'chain_exists', side_effect=[True, True]), \ 163 | mock.patch.object(self.library, 'del_chain') as mock_delchain, \ 164 | mock.patch.object(self.library, 'send_event') as mock_logger: 165 | result = self.library.add_chain() 166 | self.assertFalse(result, 'Unremovable chain must cause add_chain to be False') 167 | mock_delchain.assert_called_once_with() 168 | self.assertEqual(mock_logger.call_count, 2, 'Unremovable chain fails twice') 169 | 170 | # Now, assume simple success: 171 | with mock.patch.object(self.library, 'chain_exists', return_value=False), \ 172 | mock.patch.object(self.library, 'iptables') as mock_ipt, \ 173 | mock.patch.object(self.library, 'get_acls_for_user', 174 | return_value='q') as mock_acls, \ 175 | mock.patch.object(self.library, 'create_user_rules') as mock_crea, \ 176 | mock.patch.object(self.library, 'remove_safety_block') as mock_block: 177 | result = self.library.add_chain() 178 | self.assertTrue(result, 'clean add_chain must be True') 179 | mock_acls.assert_called_once_with() 180 | mock_crea.assert_called_once_with('q') 181 | mock_block.assert_called_once_with() 182 | mock_ipt.assert_any_call('-A OUTPUT -d 3.4.5.6 -j 3.4.5.6', True) 183 | mock_ipt.assert_any_call('-A INPUT -s 3.4.5.6 -j 3.4.5.6', True) 184 | mock_ipt.assert_any_call('-A FORWARD -s 3.4.5.6 -j 3.4.5.6', True) 185 | 186 | # Now, copy all that again but assume that we had to do housekeeping: 187 | with mock.patch.object(self.library, 'chain_exists', side_effect=[True, False]), \ 188 | mock.patch.object(self.library, 'del_chain') as mock_delchain, \ 189 | mock.patch.object(self.library, 'iptables') as mock_ipt, \ 190 | mock.patch.object(self.library, 'get_acls_for_user', 191 | return_value='q') as mock_acls, \ 192 | mock.patch.object(self.library, 'create_user_rules') as mock_crea, \ 193 | mock.patch.object(self.library, 'remove_safety_block') as mock_block, \ 194 | mock.patch.object(self.library, 'send_event') as mock_logger: 195 | result = self.library.add_chain() 196 | self.assertTrue(result, 'add_chain must be True even if it had to clean a chain out') 197 | mock_acls.assert_called_once_with() 198 | mock_crea.assert_called_once_with('q') 199 | mock_block.assert_called_once_with() 200 | mock_delchain.assert_called_once_with() 201 | # Collision cleanout triggers an event: 202 | mock_logger.assert_called_once() 203 | mock_ipt.assert_any_call('-A OUTPUT -d 3.4.5.6 -j 3.4.5.6', True) 204 | mock_ipt.assert_any_call('-A INPUT -s 3.4.5.6 -j 3.4.5.6', True) 205 | mock_ipt.assert_any_call('-A FORWARD -s 3.4.5.6 -j 3.4.5.6', True) 206 | 207 | def test_19_del_chain(self): 208 | ''' Test del_chain function ''' 209 | self.library.client_ip = '2.3.4.5' 210 | 211 | with mock.patch.object(self.library, 'iptables') as mock_ipt, \ 212 | mock.patch.object(self.library, 'ipset') as mock_ips: 213 | result = self.library.del_chain() 214 | # A lot just happened. Time to check that iptables and ipset did the right things. 215 | self.assertTrue(result, "del_chain must return True") 216 | mock_ipt.assert_any_call('-D OUTPUT -d 2.3.4.5 -j 2.3.4.5', False) 217 | mock_ipt.assert_any_call('-D INPUT -s 2.3.4.5 -j 2.3.4.5', False) 218 | mock_ipt.assert_any_call('-D FORWARD -s 2.3.4.5 -j 2.3.4.5', False) 219 | mock_ipt.assert_any_call('-F 2.3.4.5', False) 220 | mock_ipt.assert_any_call('-X 2.3.4.5', False) 221 | mock_ips.assert_any_call('--destroy 2.3.4.5', False) 222 | 223 | def test_21_iptables(self): 224 | ''' Test iptables function ''' 225 | # change the executable for shorter testing, and, in case we screw up our mock, 226 | # it'll have no chance of executing on the host. 227 | self.library.iptables_executable = 'ipt' 228 | 229 | # 0 emulates iptables working correctly 230 | with mock.patch('os.system', return_value=0) as mock_syscall: 231 | result = self.library.iptables('foo1', raiseexception=True) 232 | self.assertTrue(result, 'iptables should return True when a command works') 233 | mock_syscall.assert_called_once_with('ipt foo1') 234 | 235 | with mock.patch('os.system', return_value=0) as mock_syscall: 236 | result = self.library.iptables('foo2', raiseexception=False) 237 | self.assertTrue(result, 'iptables should return True when a command works') 238 | mock_syscall.assert_called_once_with('ipt foo2 >/dev/null 2>&1') 239 | 240 | # -1 emulates the iptables executable being wrong completely: 241 | with mock.patch('os.system', return_value=-1) as mock_syscall: 242 | with self.assertRaises(IptablesFailure): 243 | self.library.iptables('foo3', raiseexception=True) 244 | mock_syscall.assert_called_once_with('ipt foo3') 245 | 246 | with mock.patch('os.system', return_value=-1) as mock_syscall: 247 | with self.assertRaises(IptablesFailure): 248 | self.library.iptables('foo4', raiseexception=False) 249 | mock_syscall.assert_called_once_with('ipt foo4 >/dev/null 2>&1') 250 | 251 | # 256 emulates the iptables executable being confused: 252 | with mock.patch('os.system', return_value=256) as mock_syscall: 253 | with self.assertRaises(IptablesFailure): 254 | self.library.iptables('foo5', raiseexception=True) 255 | mock_syscall.assert_called_once_with('ipt foo5') 256 | 257 | with mock.patch('os.system', return_value=256) as mock_syscall: 258 | result = self.library.iptables('foo6', raiseexception=False) 259 | self.assertFalse(result, 'iptables should return False when a command fails') 260 | mock_syscall.assert_called_once_with('ipt foo6 >/dev/null 2>&1') 261 | 262 | def test_22_ipset(self): 263 | ''' Test ipset function ''' 264 | # change the executable for shorter testing, and, in case we screw up our mock, 265 | # it'll have no chance of executing on the host. 266 | self.library.ipset_executable = 'ips' 267 | 268 | # 0 emulates ipset working correctly 269 | with mock.patch('os.system', return_value=0) as mock_syscall: 270 | result = self.library.ipset('foo1', raiseexception=True) 271 | self.assertTrue(result, 'ipset should return True when a command works') 272 | mock_syscall.assert_called_once_with('ips foo1') 273 | 274 | with mock.patch('os.system', return_value=0) as mock_syscall: 275 | result = self.library.ipset('foo2', raiseexception=False) 276 | self.assertTrue(result, 'ipset should return True when a command works') 277 | mock_syscall.assert_called_once_with('ips foo2 >/dev/null 2>&1') 278 | 279 | # -1 emulates the ipset executable being wrong completely: 280 | with mock.patch('os.system', return_value=-1) as mock_syscall: 281 | with self.assertRaises(IpsetFailure): 282 | self.library.ipset('foo3', raiseexception=True) 283 | mock_syscall.assert_called_once_with('ips foo3') 284 | 285 | with mock.patch('os.system', return_value=-1) as mock_syscall: 286 | with self.assertRaises(IpsetFailure): 287 | self.library.ipset('foo4', raiseexception=False) 288 | mock_syscall.assert_called_once_with('ips foo4 >/dev/null 2>&1') 289 | 290 | # 256 emulates the ipset executable being confused: 291 | with mock.patch('os.system', return_value=256) as mock_syscall: 292 | with self.assertRaises(IpsetFailure): 293 | self.library.ipset('foo5', raiseexception=True) 294 | mock_syscall.assert_called_once_with('ips foo5') 295 | 296 | with mock.patch('os.system', return_value=256) as mock_syscall: 297 | result = self.library.ipset('foo6', raiseexception=False) 298 | self.assertFalse(result, 'ipset should return False when a command fails') 299 | mock_syscall.assert_called_once_with('ips foo6 >/dev/null 2>&1') 300 | 301 | def test_30_build_fw_rule(self): 302 | ''' Test _build_firewall_rule_iptables function ''' 303 | self.library.username_is = 'bob' 304 | 305 | iptables_acl1 = iamvpnlibrary.iamvpnbase.ParsedACL( 306 | rule='', address='5.6.7.8', portstring='80', description='') 307 | with mock.patch.object(self.library, 'iptables') as mock_ipt: 308 | self.library._build_firewall_rule_iptables('chain1', '1.2.3.4', 'tcp', iptables_acl1) 309 | mock_ipt.assert_called_once_with(('-A chain1 -s 1.2.3.4 -d 5.6.7.8 -p tcp ' 310 | '-m multiport --dports 80 -j ACCEPT')) 311 | 312 | iptables_acl2 = iamvpnlibrary.iamvpnbase.ParsedACL( 313 | rule='rule2', address='5.6.7.9', portstring='80', description='I HAZ COMMENT') 314 | with mock.patch.object(self.library, 'iptables') as mock_ipt: 315 | self.library._build_firewall_rule_iptables('chain2', '1.2.3.4', 'tcp', iptables_acl2) 316 | mock_ipt.assert_called_once_with(('-A chain2 -s 1.2.3.4 -d 5.6.7.9 -p tcp -m multiport ' 317 | '--dports 80 -m comment ' 318 | '--comment "bob:rule2 ACL I HAZ COMMENT" ' 319 | '-j ACCEPT')) 320 | 321 | ipset_acl1 = iamvpnlibrary.iamvpnbase.ParsedACL( 322 | rule='', address='5.6.7.10', portstring='', description='') 323 | with mock.patch.object(self.library, 'ipset') as mock_ips: 324 | self.library._build_firewall_rule_iptables('chain3', '1.2.3.4', '', ipset_acl1) 325 | mock_ips.assert_called_once_with('--add chain3 5.6.7.10') 326 | 327 | ipset_acl2 = iamvpnlibrary.iamvpnbase.ParsedACL( 328 | rule='rule4', address='5.6.7.11', portstring='', description='IPSET SET SET') 329 | with mock.patch.object(self.library, 'ipset') as mock_ips: 330 | self.library._build_firewall_rule_iptables('chain4', '1.2.3.4', '', ipset_acl2) 331 | mock_ips.assert_called_once_with('--add chain4 5.6.7.11 comment "bob:rule4 ACL IPSET SET SET"') 332 | 333 | def test_31_create_rules(self): 334 | ''' Test create_user_rules function ''' 335 | self.library.username_is = 'larry' 336 | self.library.client_ip = '2.3.4.5' 337 | 338 | acl1 = iamvpnlibrary.iamvpnbase.ParsedACL( 339 | rule='rule2', address='5.6.7.9', portstring='80', description='I HAZ COMMENT') 340 | acl2 = iamvpnlibrary.iamvpnbase.ParsedACL( 341 | rule='rule4', address='5.6.7.11', portstring='', description='IPSET SET SET') 342 | with mock.patch.object(self.library, 'iptables') as mock_ipt, \ 343 | mock.patch.object(self.library, 'ipset') as mock_ips: 344 | self.library.create_user_rules([acl1, acl2]) 345 | # A lot just happened. Time to check that iptables and ipset did the right things. 346 | # This is written not in the order they were invoked, but in the order you'd read them. 347 | # Make the chains: 348 | mock_ipt.assert_any_call('-N 2.3.4.5') 349 | mock_ips.assert_any_call('--create 2.3.4.5 hash:net comment') 350 | # allow established and ipsets: 351 | mock_ipt.assert_any_call(('-I 2.3.4.5 -m conntrack --ctstate ESTABLISHED -m comment ' 352 | '--comment "larry at 2.3.4.5" -j ACCEPT'), True) 353 | mock_ipt.assert_any_call(('-I 2.3.4.5 -s 2.3.4.5 -m set --match-set 2.3.4.5 dst -m ' 354 | 'comment --comment "larry groups: rule2;rule4" -j ACCEPT'), True) 355 | # And now the rules. Two for a portstring: 356 | mock_ipt.assert_any_call(('-A 2.3.4.5 -s 2.3.4.5 -d 5.6.7.9 -p tcp -m multiport ' 357 | '--dports 80 -m comment --comment ' 358 | '"larry:rule2 ACL I HAZ COMMENT" -j ACCEPT')) 359 | mock_ipt.assert_any_call(('-A 2.3.4.5 -s 2.3.4.5 -d 5.6.7.9 -p udp -m multiport ' 360 | '--dports 80 -m comment --comment ' 361 | '"larry:rule2 ACL I HAZ COMMENT" -j ACCEPT')) 362 | # One item in the ipset: 363 | mock_ips.assert_any_call('--add 2.3.4.5 5.6.7.11 comment "larry:rule4 ACL IPSET SET SET"') 364 | # And the mandatory drops: 365 | mock_ipt.assert_any_call(('-A 2.3.4.5 -m comment --comment "larry at 2.3.4.5" ' 366 | '-j LOG --log-prefix "DROP larry "'), True) 367 | mock_ipt.assert_any_call(('-A 2.3.4.5 -m comment --comment "larry at 2.3.4.5" ' 368 | '-j REJECT --reject-with icmp-admin-prohibited'), True) 369 | 370 | def test_add_safety(self): 371 | ''' Test add_safety_block function ''' 372 | self.library.client_ip = '12345' 373 | 374 | # Assume an add works: 375 | with mock.patch.object(self.library, 'iptables') as mock_ipt: 376 | self.library.add_safety_block() 377 | mock_ipt.assert_called_once_with('-I FORWARD -s 12345 -j DROP') 378 | 379 | # Assume an add fails: 380 | with mock.patch.object(self.library, 'iptables', side_effect=IptablesFailure), \ 381 | self.assertRaises(IptablesFailure): 382 | self.library.add_safety_block() 383 | 384 | def test_del_safety(self): 385 | ''' Test add_safety_block function ''' 386 | self.library.client_ip = '23456' 387 | 388 | # Assume a delete has nothing to do: 389 | with mock.patch.object(self.library, 'iptables', return_value=False) as mock_ipt: 390 | self.library.remove_safety_block() 391 | mock_ipt.assert_called_once_with('-C FORWARD -s 23456 -j DROP', False) 392 | 393 | # Assume a delete works: 394 | with mock.patch.object(self.library, 'iptables', side_effect=[True, True]) as mock_ipt, \ 395 | mock.patch.object(self.library, 'send_event') as mock_logger: 396 | self.library.remove_safety_block() 397 | mock_ipt.assert_any_call('-C FORWARD -s 23456 -j DROP', False) 398 | mock_ipt.assert_any_call('-D FORWARD -s 23456 -j DROP >/dev/null 2>&1', True) 399 | mock_logger.assert_not_called() 400 | 401 | # Assume a delete blows out, SOMEHOW: 402 | with mock.patch.object(self.library, 'iptables', 403 | side_effect=[True, IptablesFailure]) as mock_ipt, \ 404 | mock.patch.object(self.library, 'send_event') as mock_logger: 405 | self.library.remove_safety_block() 406 | mock_ipt.assert_any_call('-C FORWARD -s 23456 -j DROP', False) 407 | mock_ipt.assert_any_call('-D FORWARD -s 23456 -j DROP >/dev/null 2>&1', True) 408 | mock_logger.assert_called_once() 409 | -------------------------------------------------------------------------------- /test/test_netfilter_openvpn_nftables.py: -------------------------------------------------------------------------------- 1 | ''' 2 | tests that are specific to nftables 3 | ''' 4 | # This Source Code Form is subject to the terms of the Mozilla Public 5 | # License, v. 2.0. If a copy of the MPL was not distributed with this 6 | # file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | # Copyright (c) 2025 Mozilla Corporation 8 | 9 | import unittest 10 | import os 11 | import syslog 12 | import test.context # pylint: disable=unused-import 13 | import mock 14 | from netaddr import IPNetwork 15 | import iamvpnlibrary 16 | from netfilter_openvpn import NftablesFailure, NetfilterOpenVPN 17 | 18 | 19 | class TestExceptionsnftables(unittest.TestCase): 20 | """ 21 | These are the tests for the class-defined Exceptions. 22 | """ 23 | 24 | def test_exceptions(self): 25 | """ Verify that the self object was initialized """ 26 | self.assertIsInstance(NftablesFailure(), NftablesFailure, 27 | 'NftablesFailure does not exist') 28 | self.assertIsInstance(NftablesFailure(), Exception, 29 | 'NftablesFailure is not an Exception') 30 | 31 | 32 | class TestNetfilterOpenVPNnftables(unittest.TestCase): 33 | ''' 34 | Test the NetfilterOpenVPN class against nftables. 35 | ''' 36 | 37 | def setUp(self): 38 | # We create a library that pretends it was done by root. 39 | # If you notice in the module, this exists as a simple early filter and prevents scripts 40 | # from going into cases where root is needed. Since we're mocking here, the worry is 41 | # "well, now you can get into situations where you wouldn't otherwise. 42 | # True, but that's the point. 43 | test_reading_file = '/tmp/test-reader.txt' # nosec hardcoded_tmp_directory 44 | with open(test_reading_file, 'w', encoding='utf-8') as filepointer: 45 | filepointer.write('[openvpn-netfilter]\n') 46 | filepointer.write('framework = nftables\n') 47 | filepointer.close() 48 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 49 | new=[test_reading_file]), \ 50 | mock.patch('os.geteuid', return_value=0): 51 | self.library = NetfilterOpenVPN() 52 | 53 | 54 | def test_07a_ingest_variables_bad(self): 55 | """ With a poor config file, check we get the right things. """ 56 | test_reading_file = '/tmp/test-reader.txt' # nosec hardcoded_tmp_directory 57 | with open(test_reading_file, 'w', encoding='utf-8') as filepointer: 58 | filepointer.write('[openvpn-netfilter]\n') 59 | filepointer.write('framework = nftables\n') 60 | filepointer.write('syslog-events-facility = blah\n') 61 | filepointer.close() 62 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 63 | new=[test_reading_file]), \ 64 | mock.patch('os.geteuid', return_value=0): 65 | library = NetfilterOpenVPN() 66 | os.remove(test_reading_file) 67 | self.assertEqual(library.nf_framework, 'nftables') 68 | self.assertNotEqual(library.nft, None) 69 | self.assertEqual(library.nftables_table, 'openvpn_netfilter') 70 | self.assertEqual(library.lockpath, '/var/run/openvpn_netfilter.lock') 71 | self.assertEqual(library.lockwaittime, 2) 72 | self.assertEqual(library.lockretriesmax, 10) 73 | self.assertEqual(library.event_send, False) 74 | self.assertEqual(library.event_facility, syslog.LOG_AUTH) 75 | 76 | 77 | def test_07b_ingest_variables_good(self): 78 | """ With an actual config file, check we get the right things. """ 79 | test_reading_file = '/tmp/test-reader.txt' # nosec hardcoded_tmp_directory 80 | with open(test_reading_file, 'w', encoding='utf-8') as filepointer: 81 | filepointer.write('[openvpn-netfilter]\n') 82 | filepointer.write('framework = nftables\n') 83 | filepointer.write('nftables_table = some_tablename\n') 84 | filepointer.write('LOCKPATH = /some/lock\n') 85 | filepointer.write('LOCKWAITTIME = 6\n') 86 | filepointer.write('LOCKRETRIESMAX = 12\n') 87 | filepointer.write('syslog-events-send = True\n') 88 | filepointer.write('syslog-events-facility = local0\n') 89 | filepointer.close() 90 | with mock.patch.object(NetfilterOpenVPN, 'CONFIG_FILE_LOCATIONS', 91 | new=[test_reading_file]), \ 92 | mock.patch('os.geteuid', return_value=0): 93 | library = NetfilterOpenVPN() 94 | os.remove(test_reading_file) 95 | self.assertEqual(library.nf_framework, 'nftables') 96 | self.assertNotEqual(library.nft, None) 97 | self.assertEqual(library.nftables_table, 'some_tablename') 98 | self.assertEqual(library.lockpath, '/some/lock') 99 | self.assertEqual(library.lockwaittime, 6) 100 | self.assertEqual(library.lockretriesmax, 12) 101 | self.assertEqual(library.event_send, True) 102 | self.assertEqual(library.event_facility, syslog.LOG_LOCAL0) 103 | 104 | 105 | def test_16_chain_exists_deeptest(self): 106 | ''' Check for odd cases in teardown ''' 107 | self.library.client_ip = '12345' 108 | with mock.patch.object(self.library, 'chain_exists_nftables', return_value=False): 109 | result = self.library.chain_exists() 110 | self.assertFalse(result) 111 | 112 | with mock.patch.object(self.library, 'chain_exists_nftables', return_value=True): 113 | result = self.library.chain_exists() 114 | self.assertTrue(result) 115 | 116 | 117 | def test_16_chain_exists_nftables(self): 118 | ''' Make sure can figure out if an nftables chain exists ''' 119 | self.library.client_ip = '12345' 120 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 121 | mock_nft.return_value = (0, 'somejson', '') 122 | result = self.library.chain_exists_nftables() 123 | # Get back whatever the nftables call is: 124 | self.assertEqual(result, True) 125 | mock_nft.assert_called_once_with({'nftables': [ 126 | {'list': {'chain': {'family': 'inet', 127 | 'table': 'openvpn_netfilter', 128 | 'name': self.library.client_ip} 129 | }}]}) 130 | 131 | 132 | def test_16_chain_does_not_exist_nftables(self): 133 | ''' Make sure can figure out if an nftables chain is not here ''' 134 | self.library.client_ip = '12345' 135 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 136 | mock_nft.return_value = (-1, 'somejson', '') 137 | result = self.library.chain_exists_nftables() 138 | # Get back whatever the nftables call is: 139 | self.assertEqual(result, False) 140 | mock_nft.assert_called_once_with({'nftables': [ 141 | {'list': {'chain': {'family': 'inet', 142 | 'table': 'openvpn_netfilter', 143 | 'name': self.library.client_ip} 144 | }}]}) 145 | 146 | 147 | def test_17_update_chain(self): 148 | ''' Make sure update_chain is THAT simple ''' 149 | with mock.patch.object(self.library, 'del_chain') as mock_d, \ 150 | mock.patch.object(self.library, 'add_chain', return_value='y') as mock_a: 151 | result = self.library.update_chain() 152 | # Get back whatever the add_chain call is: 153 | self.assertEqual(result, 'y') 154 | mock_d.assert_called_once_with() 155 | mock_a.assert_called_once_with() 156 | 157 | 158 | def test_18_add_chain(self): 159 | ''' Test add_chain function ''' 160 | self.library.client_ip = '3.4.5.6' 161 | 162 | # First assume horrific failure: 163 | with mock.patch.object(self.library, 'chain_exists', side_effect=[True, True]), \ 164 | mock.patch.object(self.library, 'del_chain') as mock_delchain, \ 165 | mock.patch.object(self.library, 'send_event') as mock_logger: 166 | result = self.library.add_chain() 167 | self.assertFalse(result, 'Unremovable chain must cause add_chain to be False') 168 | mock_delchain.assert_called_once_with() 169 | self.assertEqual(mock_logger.call_count, 2, 'Unremovable chain fails twice') 170 | 171 | # Now, assume simple success: 172 | with mock.patch.object(self.library, 'chain_exists', return_value=False), \ 173 | mock.patch.object(self.library.nft, 'json_cmd') as mock_nft, \ 174 | mock.patch.object(self.library, 'get_acls_for_user', 175 | return_value='q') as mock_acls, \ 176 | mock.patch.object(self.library, 'create_user_rules') as mock_crea, \ 177 | mock.patch.object(self.library, 'remove_safety_block') as mock_block: 178 | mock_nft.return_value = (0, '', '') 179 | result = self.library.add_chain() 180 | self.assertTrue(result, 'clean add_chain must be True') 181 | mock_acls.assert_called_once_with() 182 | mock_crea.assert_called_once_with('q') 183 | mock_block.assert_called_once_with() 184 | mock_nft.assert_called_once_with({'nftables': [ 185 | {'add': {'rule': {'family': 'inet', 186 | 'table': 'openvpn_netfilter', 187 | 'chain': 'FORWARD', 188 | 'expr': [{'match': {'op': '==', 189 | 'left': {'payload': {'protocol': 'ip', 'field': 'saddr'}}, 190 | 'right': '3.4.5.6'}}, 191 | {'jump': {'target': '3.4.5.6'}}]}}}, 192 | {'add': {'rule': {'family': 'inet', 193 | 'table': 'openvpn_netfilter', 194 | 'chain': 'FORWARD', 195 | 'expr': [{'match': {'op': '==', 196 | 'left': {'payload': {'protocol': 'ip', 'field': 'daddr'}}, 197 | 'right': '3.4.5.6'}}, 198 | {'jump': {'target': '3.4.5.6'}}]}}}, 199 | ]}) 200 | 201 | # Now, copy all that again but assume that we had to do housekeeping: 202 | with mock.patch.object(self.library, 'chain_exists', side_effect=[True, False]), \ 203 | mock.patch.object(self.library.nft, 'json_cmd') as mock_nft, \ 204 | mock.patch.object(self.library, 'del_chain') as mock_delchain, \ 205 | mock.patch.object(self.library, 'get_acls_for_user', 206 | return_value='q') as mock_acls, \ 207 | mock.patch.object(self.library, 'create_user_rules') as mock_crea, \ 208 | mock.patch.object(self.library, 'remove_safety_block') as mock_block, \ 209 | mock.patch.object(self.library, 'send_event') as mock_logger: 210 | mock_nft.return_value = (0, '', '') 211 | result = self.library.add_chain() 212 | self.assertTrue(result, 'add_chain must be True even if it had to clean a chain out') 213 | mock_acls.assert_called_once_with() 214 | mock_crea.assert_called_once_with('q') 215 | mock_delchain.assert_called_once_with() 216 | # Collision cleanout triggers an event: 217 | mock_logger.assert_called_once() 218 | # Not deep-checking the nft call; the above test should do that. 219 | mock_nft.assert_called_once() 220 | mock_block.assert_called_once_with() 221 | 222 | # One last time, but fail the add: 223 | with mock.patch.object(self.library, 'chain_exists', return_value=False), \ 224 | mock.patch.object(self.library.nft, 'json_cmd') as mock_nft, \ 225 | mock.patch.object(self.library, 'get_acls_for_user', 226 | return_value='q') as mock_acls, \ 227 | mock.patch.object(self.library, 'create_user_rules') as mock_crea, \ 228 | mock.patch.object(self.library, 'remove_safety_block') as mock_block: 229 | mock_nft.return_value = (-1, '', '') 230 | with self.assertRaises(NftablesFailure, 231 | msg='add_chain with a failure must raise'): 232 | self.library.add_chain() 233 | mock_acls.assert_called_once_with() 234 | mock_crea.assert_called_once_with('q') 235 | # Not deep-checking the nft call; the above test should do that. 236 | mock_nft.assert_called_once() 237 | # notice this non-call: 238 | mock_block.assert_not_called() 239 | # ^ this means a bad flaw can leave 'safety blocks' across IPs. This is 240 | # SUPREMELY unlikely based on the design of the blocks, but this is a callout of 241 | # a weird situation and if you ever stumble over this, look at it closely. 242 | 243 | 244 | def test_19_del_chain(self): 245 | ''' Test del_chain function ''' 246 | self.library.client_ip = '2.3.4.5' 247 | 248 | rule_to_delete_out = { 249 | 'family': 'inet', 250 | 'table': 'openvpn_netfilter', 251 | 'chain': 'FORWARD', 252 | 'handle': 13, 253 | 'expr': [ 254 | { 'match': { 255 | 'op': '==', 256 | 'left': { 'payload': { 'protocol': 'ip', 'field': 'saddr' }}, 257 | 'right': self.library.client_ip} 258 | }, 259 | { 'jump': { 'target': self.library.client_ip } } 260 | ] 261 | } 262 | rule_to_delete_in = { 263 | 'family': 'inet', 264 | 'table': 'openvpn_netfilter', 265 | 'chain': 'FORWARD', 266 | 'handle': 14, 267 | 'expr': [ 268 | { 'match': { 269 | 'op': '==', 270 | 'left': { 'payload': { 'protocol': 'ip', 'field': 'daddr' }}, 271 | 'right': self.library.client_ip} 272 | }, 273 | { 'jump': { 'target': self.library.client_ip } } 274 | ] 275 | } 276 | 277 | # Assume a delete works: 278 | search_obj = {"nftables": [ 279 | # A rule with no expr, to test that we don't blow up there. 280 | {"rule": {"family": "inet"}}, 281 | # A chain, to make sure that doesn't stop us. 282 | {"chain": {}}, 283 | # The rules we want: 284 | {"rule": rule_to_delete_out}, 285 | {"rule": rule_to_delete_in}, 286 | ]} 287 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 288 | # This return is a little odd, saying 'search_obj' a lot for 289 | # the list (correct) and the deletes (kinda wrong) 290 | mock_nft.return_value = (0, search_obj, '') 291 | res = self.library.del_chain() 292 | 293 | self.assertTrue(res, 'del_chain shoule be True on positive-success') 294 | # Four calls, the lookup, 2 rule deletes, and the delete of chain+set: 295 | self.assertEqual(mock_nft.call_count, 4) 296 | mock_nft.assert_any_call({'nftables': [ 297 | {'list': {'chain': { 298 | 'family': 'inet', 299 | 'table': 'openvpn_netfilter', 300 | 'name': 'FORWARD'} 301 | }} 302 | ]}) 303 | mock_nft.assert_any_call({'nftables': [ 304 | {'delete': {'rule': {'family': 'inet', 305 | 'table': 'openvpn_netfilter', 306 | 'chain': 'FORWARD', 307 | 'handle': 13,}}}]}) 308 | mock_nft.assert_any_call({'nftables': [ 309 | {'delete': {'rule': {'family': 'inet', 310 | 'table': 'openvpn_netfilter', 311 | 'chain': 'FORWARD', 312 | 'handle': 14,}}}]}) 313 | mock_nft.assert_any_call({'nftables': [ 314 | {'delete': {'chain': {'family': 'inet', 315 | 'table': 'openvpn_netfilter', 316 | 'name': self.library.client_ip,}}}, 317 | {'delete': {'set': {'family': 'inet', 318 | 'table': 'openvpn_netfilter', 319 | 'type': 'ipv4_addr', 320 | 'name': self.library.client_ip,}}}, 321 | ]}) 322 | 323 | # OK so that was a lot.. that was "what if it all works". 324 | # What if a list lookup fails? 325 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 326 | mock_nft.return_value = (-1, 'somejson', '') 327 | with self.assertRaises(NftablesFailure, 328 | msg='del_chain should raise on a botched lookup'): 329 | self.library.del_chain() 330 | 331 | # IMPROVEME - there are potential failures we've not thought of 332 | # or built tests for, because we've not seen them/thought of them. 333 | 334 | 335 | def test_30_build_fw_rule(self): 336 | ''' Test _build_firewall_rule_nftables function ''' 337 | self.library.username_is = 'bob' 338 | 339 | in_acl1 = iamvpnlibrary.iamvpnbase.ParsedACL( 340 | rule='', address=IPNetwork('5.6.7.8'), portstring='80', description='') 341 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 342 | mock_nft.return_value = (0, '', '') 343 | self.library._build_firewall_rule_nftables('chain1', '1.2.3.4', 'tcp', in_acl1) 344 | mock_nft.assert_called_once_with({'nftables': [ 345 | {'add': {'rule': {'family': 'inet', 346 | 'table': 'openvpn_netfilter', 347 | 'chain': 'chain1', 348 | 'comment': None, 349 | 'expr': [{'match': { 350 | 'op': '==', 351 | 'left': {'payload': { 'protocol': 'ip', 'field': 'saddr'}}, 352 | 'right': '1.2.3.4'}}, 353 | {'match': { 354 | 'op': '==', 355 | 'left': {'payload': { 'protocol': 'ip', 'field': 'daddr'}}, 356 | 'right': '5.6.7.8/32'}}, 357 | {'match': { 358 | 'op': '==', 359 | 'left': {'payload': { 'protocol': 'tcp', 'field': 'dport'}}, 360 | 'right': {'set': [80]}}}, 361 | {'drop': None}]}}}]}) 362 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 363 | mock_nft.return_value = (-1, '', 'someerror') 364 | with self.assertRaises(NftablesFailure, 365 | msg='_build_firewall_rule_nftables raises when a rule add fails'): 366 | self.library._build_firewall_rule_nftables('chain1', '1.2.3.4', 'tcp', in_acl1) 367 | 368 | in_acl2 = iamvpnlibrary.iamvpnbase.ParsedACL( 369 | rule='rule2', address=IPNetwork('5.6.7.9'), portstring='80', description='I HAZ COMMENT') 370 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 371 | mock_nft.return_value = (0, '', '') 372 | self.library._build_firewall_rule_nftables('chain2', '1.2.3.4', 'tcp', in_acl2) 373 | mock_nft.assert_called_once_with({'nftables': [ 374 | {'add': {'rule': {'family': 'inet', 375 | 'table': 'openvpn_netfilter', 376 | 'chain': 'chain2', 377 | 'comment': 'bob:rule2 ACL I HAZ COMMENT', 378 | 'expr': [{'match': { 379 | 'op': '==', 380 | 'left': {'payload': { 'protocol': 'ip', 'field': 'saddr'}}, 381 | 'right': '1.2.3.4'}}, 382 | {'match': { 383 | 'op': '==', 384 | 'left': {'payload': { 'protocol': 'ip', 'field': 'daddr'}}, 385 | 'right': '5.6.7.9/32'}}, 386 | {'match': { 387 | 'op': '==', 388 | 'left': {'payload': { 'protocol': 'tcp', 'field': 'dport'}}, 389 | 'right': {'set': [80]}}}, 390 | {'drop': None}]}}}]}) 391 | 392 | ip_set_acl1 = iamvpnlibrary.iamvpnbase.ParsedACL( 393 | rule='', address=IPNetwork('5.6.7.0/24'), portstring='', description='') 394 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 395 | mock_nft.return_value = (0, '', '') 396 | self.library._build_firewall_rule_nftables('chain3', '1.2.3.4', '', ip_set_acl1) 397 | mock_nft.assert_called_once_with({'nftables': [ 398 | {'add': {'element': {'family': 'inet', 399 | 'table': 'openvpn_netfilter', 400 | 'name': 'chain3', 401 | 'elem': [ { 'prefix': { 402 | 'addr': '5.6.7.0', 403 | 'len': 24 } } 404 | ] 405 | }}}]}) 406 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 407 | mock_nft.return_value = (-1, '', 'someerror') 408 | with self.assertRaises(NftablesFailure, 409 | msg='_build_firewall_rule_nftables raises when a set-element add fails'): 410 | self.library._build_firewall_rule_nftables('chain3', '1.2.3.4', '', ip_set_acl1) 411 | 412 | # comments don't work in nftables sets, so "the output here is the same" 413 | ip_set_acl2 = iamvpnlibrary.iamvpnbase.ParsedACL( 414 | rule='rule4', address=IPNetwork('5.6.7.11'), portstring='', description='IPSET SET SET') 415 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 416 | mock_nft.return_value = (0, '', '') 417 | self.library._build_firewall_rule_nftables('chain4', '1.2.3.4', '', ip_set_acl2) 418 | mock_nft.assert_called_once_with({'nftables': [ 419 | {'add': {'element': {'family': 'inet', 420 | 'table': 'openvpn_netfilter', 421 | 'name': 'chain4', 422 | 'elem': ['5.6.7.11'] }}}]}) 423 | 424 | 425 | def test_31_create_rules(self): 426 | ''' Test create_user_rules function ''' 427 | self.library.username_is = 'larry' 428 | self.library.client_ip = '2.3.4.5' 429 | 430 | acl1 = iamvpnlibrary.iamvpnbase.ParsedACL( 431 | rule='rule2', address=IPNetwork('5.6.7.9'), portstring='80', description='I HAZ COMMENT') 432 | acl2 = iamvpnlibrary.iamvpnbase.ParsedACL( 433 | rule='rule4', address=IPNetwork('5.6.7.11'), portstring='', description='IPSET SET SET') 434 | 435 | # Before we get too far into this, let's do the bad cases. 436 | # What if we can't make a chain/set for this person? 437 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft, \ 438 | mock.patch.object(self.library, '_ensure_nftables_framework') as mock_framework: 439 | mock_nft.return_value = (-1, '', '') 440 | with self.assertRaises(NftablesFailure, 441 | msg='create_user_rules raises when creation fails early'): 442 | self.library.create_user_rules([acl1, acl2]) 443 | 444 | # What if we can make a chain/set for this person but then populating it fails? 445 | # skip going to _build_firewall_rule_nftables.. this failure check is to make sure 446 | # our final rule add is looked at. 447 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft, \ 448 | mock.patch.object(self.library, '_build_firewall_rule_nftables'), \ 449 | mock.patch.object(self.library, '_ensure_nftables_framework') as mock_framework: 450 | mock_nft.side_effect = [(0, '', ''), 451 | (-1, '', '')] 452 | with self.assertRaises(NftablesFailure, 453 | msg='create_user_rules raises when creation fails in the second phase'): 454 | self.library.create_user_rules([acl1, acl2]) 455 | 456 | # and now, the very complicated success route: 457 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft, \ 458 | mock.patch.object(self.library, '_ensure_nftables_framework') as mock_framework: 459 | mock_nft.return_value = (0, '', '') 460 | self.library.create_user_rules([acl1, acl2]) 461 | mock_framework.assert_called_once() 462 | # A lot just happened. Time to check that nftables did the right things. 463 | # This is not necessarily written not in the order they were invoked. 464 | # Make the user chain and user set: 465 | self.assertEqual(mock_nft.call_count, 5) 466 | mock_nft.assert_any_call({'nftables': [ 467 | {'add': { 468 | 'chain': { 469 | 'family': 'inet', 470 | 'table': 'openvpn_netfilter', 471 | 'name': '2.3.4.5' 472 | } 473 | } 474 | }, 475 | {'add': { 476 | 'set': { 477 | 'family': 'inet', 478 | 'table': 'openvpn_netfilter', 479 | 'type': 'ipv4_addr', 480 | 'name': '2.3.4.5', 481 | 'flags': ['interval'] 482 | } 483 | } 484 | } 485 | ]} 486 | ) 487 | # This is a long one. allow established and sets, log-drop anything else: 488 | mock_nft.assert_any_call({'nftables': [ 489 | {'add': { 'rule': { 490 | 'family': 'inet', 491 | 'table': 'openvpn_netfilter', 492 | 'chain': '2.3.4.5', 493 | 'comment': 'larry at 2.3.4.5', 494 | 'expr': [ 495 | {'match': { 496 | 'op': 'in', 497 | 'left': {'ct': {'key': 'state'}}, 498 | 'right': [ 499 | 'established', 500 | 'related', 501 | ]}, 502 | }, 503 | {'accept': None} 504 | ] 505 | } 506 | }}, 507 | {'add': {'rule': { 508 | 'family': 'inet', 509 | 'table': 'openvpn_netfilter', 510 | 'chain': '2.3.4.5', 511 | 'expr': [ 512 | {'match': { 513 | 'op': '==', 514 | 'left': {'payload': {'protocol': 'ip', 'field': 'saddr'}}, 515 | 'right': '2.3.4.5'} 516 | }, 517 | {'match': { 518 | 'op': '==', 519 | 'left': {'payload': {'protocol': 'ip', 'field': 'daddr'}}, 520 | 'right': '@2.3.4.5'} 521 | }, 522 | {'accept': None} 523 | ] 524 | } 525 | }}, 526 | {'add': {'rule': { 527 | 'family': 'inet', 528 | 'table': 'openvpn_netfilter', 529 | 'chain': '2.3.4.5', 530 | 'expr': [ 531 | {'log': { 532 | 'prefix': 'DROP larry '} 533 | } 534 | ] 535 | } 536 | }}, 537 | {'add': {'rule': { 538 | 'family': 'inet', 539 | 'table': 'openvpn_netfilter', 540 | 'chain': '2.3.4.5', 541 | 'expr': [ 542 | {'reject': { 543 | 'type': 'icmp', 544 | 'expr': 'admin-prohibited'} 545 | } 546 | ] 547 | } 548 | }} 549 | ]} 550 | ) 551 | 552 | # And now the rules. Two for a portstring: 553 | for test_proto in ('tcp', 'udp'): 554 | mock_nft.assert_any_call({'nftables': [ 555 | {'add': {'rule': { 556 | 'family': 'inet', 557 | 'table': 'openvpn_netfilter', 558 | 'chain': '2.3.4.5', 559 | 'comment': 'larry:rule2 ACL I HAZ COMMENT', 560 | 'expr': [ 561 | {'match': { 562 | 'op': '==', 563 | 'left': {'payload': {'protocol': 'ip', 'field': 'saddr'}}, 564 | 'right': '2.3.4.5'} 565 | }, 566 | {'match': { 567 | 'op': '==', 568 | 'left': {'payload': {'protocol': 'ip', 'field': 'daddr'}}, 569 | 'right': '5.6.7.9/32'} 570 | }, 571 | {'match': { 572 | 'op': '==', 573 | 'left': {'payload': {'protocol': test_proto, 'field': 'dport'}}, 574 | 'right': {'set': [80]}} 575 | }, 576 | {'drop': None}]} 577 | }} 578 | ]} 579 | ) 580 | 581 | # One item added into the set: 582 | mock_nft.assert_any_call({'nftables': [ 583 | {'add': {'element': { 584 | 'family': 'inet', 585 | 'table': 'openvpn_netfilter', 586 | 'name': '2.3.4.5', 587 | 'elem': [ 588 | '5.6.7.11' 589 | ]} 590 | }} 591 | ]} 592 | ) 593 | 594 | 595 | def test_32_ensure_nftables_framework(self): 596 | ''' Test _ensure_nftables_framework function ''' 597 | 598 | # Assume everything is already there. This is the most common case. 599 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 600 | mock_nft.side_effect = [ 601 | (0, '{"nftables": []}', ''), 602 | (0, '{"nftables": []}', '') 603 | ] 604 | res = self.library._ensure_nftables_framework() 605 | self.assertTrue(res) 606 | # 2 lists, all successful: 607 | self.assertEqual(mock_nft.call_count, 2) 608 | mock_nft.assert_any_call({'nftables': [ 609 | {'list': {'table': { 610 | 'family': 'inet', 611 | 'name': 'openvpn_netfilter'} 612 | }} 613 | ]}) 614 | mock_nft.assert_any_call({'nftables': [ 615 | {'list': {'chain': { 616 | 'family': 'inet', 617 | 'table': 'openvpn_netfilter', 618 | 'name': 'FORWARD', 619 | 'type': 'filter', 620 | 'hook': 'forward', 621 | 'prio': -10, 622 | 'policy': 'drop', } 623 | }} 624 | ]}) 625 | 626 | # Assume nothing is already there. This is the startup case. 627 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 628 | mock_nft.side_effect = [ 629 | (-1, '', 'no table'), 630 | (0, '', ''), 631 | (-1, '', 'no chain'), 632 | (0, '', ''), 633 | ] 634 | res = self.library._ensure_nftables_framework() 635 | self.assertTrue(res) 636 | # list add list add, all expected 637 | self.assertEqual(mock_nft.call_count, 4) 638 | for action in ('list', 'add'): 639 | mock_nft.assert_any_call({'nftables': [ 640 | {action: {'table': { 641 | 'family': 'inet', 642 | 'name': 'openvpn_netfilter'} 643 | }} 644 | ]}) 645 | mock_nft.assert_any_call({'nftables': [ 646 | {action: {'chain': { 647 | 'family': 'inet', 648 | 'table': 'openvpn_netfilter', 649 | 'name': 'FORWARD', 650 | 'type': 'filter', 651 | 'hook': 'forward', 652 | 'prio': -10, 653 | 'policy': 'drop', } 654 | }} 655 | ]}) 656 | 657 | # IMPROVEME: needs bad tests 658 | 659 | 660 | def test_add_safety(self): 661 | ''' Test add_safety_block function ''' 662 | self.library.client_ip = '12345' 663 | 664 | # Assume an add works: 665 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft, \ 666 | mock.patch.object(self.library, '_ensure_nftables_framework'): 667 | mock_nft.return_value = (0, 'somejson', '') 668 | res = self.library.add_safety_block() 669 | mock_nft.assert_called_once_with({'nftables': [ 670 | {'add': {'rule': {'family': 'inet', 671 | 'table': 'openvpn_netfilter', 672 | 'chain': 'FORWARD', 673 | 'expr': [{'match': {'op': '==', 674 | 'left': {'payload': {'protocol': 'ip', 'field': 'saddr'}}, 675 | 'right': '12345'}}, 676 | {'drop': None}]}}}]}) 677 | self.assertTrue(res, 'add_safety_block shoule be true on success') 678 | 679 | ### Assume an add fails: 680 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft, \ 681 | mock.patch.object(self.library, '_ensure_nftables_framework'): 682 | mock_nft.return_value = (-1, 'somejson', '') 683 | with self.assertRaises(NftablesFailure, 684 | msg='add_safety_block should raise on a botched delete'): 685 | self.library.add_safety_block() 686 | 687 | 688 | def test_del_safety(self): 689 | ''' Test add_safety_block function ''' 690 | self.library.client_ip = '23456' 691 | 692 | good_rule_to_delete = { 693 | 'family': 'inet', 694 | 'table': 'openvpn_netfilter', 695 | 'chain': 'FORWARD', 696 | 'handle': 13, 697 | 'expr': [ 698 | { 'match': { 699 | 'op': '==', 700 | 'left': { 'payload': { 'protocol': 'ip', 'field': 'saddr' }}, 701 | 'right': self.library.client_ip} 702 | }, 703 | { 'drop': None } 704 | ] 705 | } 706 | 707 | # Assume a delete works: 708 | search_obj = {"nftables": [ 709 | # A rule with no expr, to test that we don't blow up there. 710 | {"rule": {"family": "inet"}}, 711 | # A chain, to make sure that doesn't stop us. 712 | {"chain": {}}, 713 | # The rule we want: 714 | {"rule": good_rule_to_delete}, 715 | ]} 716 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 717 | mock_nft.return_value = (0, search_obj, '') 718 | res = self.library.remove_safety_block() 719 | 720 | self.assertTrue(res, 'remove_safety_block shoule be True on positive-success') 721 | # Two calls, the lookup and the delete: 722 | mock_nft.assert_any_call({'nftables': [ 723 | {'delete': {'rule': {'family': 'inet', 724 | 'table': 'openvpn_netfilter', 725 | 'chain': 'FORWARD', 726 | 'handle': 13,}}}]}) 727 | # The test that would happen if we could delete normally: 728 | #mock_nft.assert_any_call({'nftables': [ 729 | # {'delete': {'rule': {'family': 'inet', 730 | # 'table': 'openvpn_netfilter', 731 | # 'chain': 'FORWARD', 732 | # 'expr': [{'match': {'op': '==', 733 | # 'left': {'payload': {'protocol': 'ip', 'field': 'saddr'}}, 734 | # 'right': '23456'}}, 735 | # {'drop': None}]}}}]}) 736 | 737 | # Assume a delete finds no rule to delete: 738 | search_obj = {"nftables": [ 739 | {"rule": {"family": "inet"}}, 740 | {"chain": {}}, 741 | ]} 742 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 743 | mock_nft.return_value = (0, search_obj, '') 744 | res = self.library.remove_safety_block() 745 | self.assertTrue(res, 'remove_safety_block shoule be True on no-rule-found') 746 | # One call, the lookup: 747 | mock_nft.assert_called_once() 748 | 749 | # Assume a delete fails: 750 | search_obj = {"nftables": [ 751 | # A rule with no expr, to test that we don't blow up there. 752 | {"rule": {"family": "inet"}}, 753 | # A chain, to make sure that doesn't stop us. 754 | {"chain": {}}, 755 | # The rule we want: 756 | {"rule": good_rule_to_delete}, 757 | ]} 758 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 759 | mock_nft.side_effect = [(0, search_obj, ''), 760 | (-1, '', '')] 761 | with self.assertRaises(NftablesFailure, 762 | msg='delete_safety_block should raise on a botched delete'): 763 | self.library.remove_safety_block() 764 | # Not checking the call; the above test should do that. 765 | 766 | # Assume a list blows out, SOMEHOW: 767 | with mock.patch.object(self.library.nft, 'json_cmd') as mock_nft: 768 | mock_nft.return_value = (-1, '{}', '') 769 | with self.assertRaises(NftablesFailure, 770 | msg='delete_safety_block should raise on a botched lookup'): 771 | self.library.remove_safety_block() 772 | # Not checking the call; the above test should do that. 773 | -------------------------------------------------------------------------------- /netfilter_openvpn.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is a librarification of the commands that should add/delete 3 | netfilter rules for someone connecting to OpenVPN. This applies 4 | iptables and ipset rules, aimed at their client IP, to prevent 5 | a remote user from having full reign over the local environment. 6 | 7 | Determination of WHAT to connect to is not this code's job. 8 | The iamvpnlibrary code provides that information. 9 | """ 10 | # vim: set noexpandtab:ts=4 11 | # Requires: 12 | # python-iamvpnlibrary 13 | # 14 | # Version: MPL 1.1/GPL 2.0/LGPL 2.1 15 | # 16 | # The contents of this file are subject to the Mozilla Public License Version 17 | # 1.1 (the "License"); you may not use this file except in compliance with 18 | # the License. You may obtain a copy of the License at 19 | # http://www.mozilla.org/MPL/ 20 | # 21 | # Software distributed under the License is distributed on an "AS IS" basis, 22 | # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 23 | # for the specific language governing rights and limitations under the 24 | # License. 25 | # 26 | # The Original Code is the netfilter.py for OpenVPN learn-address. 27 | # 28 | # The Initial Developer of the Original Code is 29 | # Mozilla Corporation 30 | # Portions created by the Initial Developer are Copyright (C) 2012 31 | # the Initial Developer. All Rights Reserved. 32 | # 33 | # Contributor(s): 34 | # gdestuynder@mozilla.com (initial author) 35 | # jvehent@mozilla.com (ipset support) 36 | # gcox@mozilla.com (repackaging as class + LDAP extraction) 37 | # 38 | # Alternatively, the contents of this file may be used under the terms of 39 | # either the GNU General Public License Version 2 or later (the "GPL"), or 40 | # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), 41 | # in which case the provisions of the GPL or the LGPL are applicable instead 42 | # of those above. If you wish to allow use of your version of this file only 43 | # under the terms of either the GPL or the LGPL, and not to allow others to 44 | # use your version of this file under the terms of the MPL, indicate your 45 | # decision by deleting the provisions above and replace them with the notice 46 | # and other provisions required by the GPL or the LGPL. If you do not delete 47 | # the provisions above, a recipient may use your version of this file under 48 | # the terms of any one of the MPL, the GPL or the LGPL. 49 | 50 | import os 51 | import sys 52 | import fcntl 53 | import signal 54 | import datetime 55 | import socket 56 | import json 57 | import syslog 58 | import configparser 59 | from contextlib import contextmanager 60 | import nftables 61 | import iamvpnlibrary 62 | sys.dont_write_bytecode = True 63 | 64 | 65 | class IptablesFailure(Exception): 66 | """ 67 | A named Exception to raise upon an iptables failure 68 | """ 69 | 70 | 71 | class IpsetFailure(Exception): 72 | """ 73 | A named Exception to raise upon an ipset failure 74 | """ 75 | 76 | 77 | class NftablesFailure(Exception): 78 | ''' A named Exception to raise upon an nftables failure ''' 79 | 80 | 81 | class NetfilterOpenVPN: # pylint: disable=too-many-instance-attributes 82 | """ 83 | This class exists to make a more testable interface into the 84 | adding and removing of per-user ACL rules. 85 | """ 86 | 87 | CONFIG_FILE_LOCATIONS = ['netfilter_openvpn.conf', 88 | '/usr/local/etc/netfilter_openvpn.conf', 89 | '/etc/netfilter_openvpn.conf'] 90 | 91 | def __init__(self): 92 | """ 93 | ingest the config file, then 94 | establish our variables based on it. 95 | """ 96 | self.configfile = self._ingest_config_from_file() 97 | 98 | try: 99 | self.nf_framework = self.configfile.get( 100 | 'openvpn-netfilter', 'framework') 101 | except (configparser.NoOptionError, configparser.NoSectionError): 102 | self.nf_framework = 'iptables' 103 | 104 | try: 105 | self.iptables_executable = self.configfile.get( 106 | 'openvpn-netfilter', 'iptables_executable') 107 | except (configparser.NoOptionError, configparser.NoSectionError): 108 | self.iptables_executable = '/sbin/iptables' 109 | 110 | try: 111 | self.ipset_executable = self.configfile.get( 112 | 'openvpn-netfilter', 'ipset_executable') 113 | except (configparser.NoOptionError, configparser.NoSectionError): 114 | self.ipset_executable = '/usr/sbin/ipset' 115 | 116 | try: 117 | self.nftables_table = self.configfile.get( 118 | 'openvpn-netfilter', 'nftables_table') 119 | except (configparser.NoOptionError, configparser.NoSectionError): 120 | self.nftables_table = 'openvpn_netfilter' 121 | 122 | try: 123 | self.lockpath = self.configfile.get( 124 | 'openvpn-netfilter', 'LOCKPATH') 125 | except (configparser.NoOptionError, configparser.NoSectionError): 126 | self.lockpath = '/var/run/openvpn_netfilter.lock' 127 | 128 | try: 129 | self.lockwaittime = self.configfile.getint( 130 | 'openvpn-netfilter', 'LOCKWAITTIME') 131 | except (configparser.NoOptionError, configparser.NoSectionError): 132 | self.lockwaittime = 2 # this is in seconds 133 | 134 | try: 135 | self.lockretriesmax = self.configfile.getint( 136 | 'openvpn-netfilter', 'LOCKRETRIESMAX') 137 | except (configparser.NoOptionError, configparser.NoSectionError): 138 | self.lockretriesmax = 10 139 | 140 | try: 141 | self.event_send = self.configfile.getboolean( 142 | 'openvpn-netfilter', 'syslog-events-send') 143 | except (configparser.NoOptionError, configparser.NoSectionError): 144 | self.event_send = False 145 | 146 | try: 147 | _base_facility = self.configfile.get( 148 | 'openvpn-netfilter', 'syslog-events-facility') 149 | except (configparser.NoOptionError, configparser.NoSectionError): 150 | _base_facility = 'auth' 151 | try: 152 | self.event_facility = getattr(syslog, f'LOG_{_base_facility.upper()}') 153 | except AttributeError: 154 | self.event_facility = syslog.LOG_AUTH 155 | 156 | self._lock = None 157 | self.username_is = None 158 | self.username_as = None 159 | self.client_ip = None 160 | self.iam_object = None 161 | if os.geteuid() != 0: 162 | # Since everything in this class will modify iptables/ipset, 163 | # this library pretty much must run as root. 164 | # 165 | # Side note: 166 | # Since it's called from learn-address, that means you need 167 | # to have a sudo allowance for the openvpn user. 168 | raise Exception('You must be root to use this library.') 169 | 170 | if self.nf_framework == 'nftables': 171 | self.nft = nftables.Nftables() 172 | else: 173 | self.nft = None 174 | 175 | 176 | def send_event(self, summary, details, severity='INFO'): 177 | ''' 178 | Send an event to our syslog setting, if set 179 | ''' 180 | if not self.event_send: 181 | return 182 | output_json = { 183 | 'category': 'authentication', 184 | 'processid': os.getpid(), 185 | 'severity': severity, 186 | 'processname': sys.argv[0], 187 | 'timestamp': datetime.datetime.now(datetime.timezone.utc).isoformat(), 188 | 'details': details, 189 | 'hostname': socket.getfqdn(), 190 | 'summary': summary, 191 | 'tags': ['vpn', 'netfilter'], 192 | 'source': 'openvpn', 193 | } 194 | syslog_message = json.dumps(output_json) 195 | syslog.openlog(facility=self.event_facility) 196 | syslog.syslog(syslog_message) 197 | 198 | def _ingest_config_from_file(self): 199 | """ 200 | pull in config variables from a system file 201 | """ 202 | config = configparser.ConfigParser() 203 | for filename in self.__class__.CONFIG_FILE_LOCATIONS: 204 | if os.path.isfile(filename): 205 | try: 206 | config.read(filename) 207 | break 208 | except configparser.Error: 209 | pass 210 | else: 211 | # Normally we demand there be a config, but in this case this 212 | # config is only for overriding otherwise-sane defaults. 213 | # raise IOError('Config file not found') 214 | pass 215 | return config 216 | 217 | def set_targets(self, username_is=None, username_as=None, client_ip=None): 218 | """ 219 | Scope this object's target user/client IP. 220 | We don't do this in __init__ because, in testing, we want to 221 | get our targets from the config file. In production, 222 | it could be in init, but, let's make life easy. 223 | """ 224 | # username_is/username_as can be None in a delete 225 | self.client_ip = client_ip 226 | self.username_is = username_is 227 | self.username_as = username_is 228 | # Yes, '_as' is BY DEFAULT set to '_is', because sudo'ing is a rare case. 229 | # We will override this only after going through a gauntlet: 230 | if username_is and username_as: 231 | # ^ bypass on deletes 232 | self.iam_object = iamvpnlibrary.IAMVPNLibrary() 233 | self.username_as = self.iam_object.verify_sudo_user(username_is, username_as) 234 | 235 | def username_string(self): 236 | """ Provide a human-readable string describing the user situation """ 237 | if not self.username_is: 238 | return '' 239 | if not self.username_as: 240 | return self.username_is 241 | if self.username_is == self.username_as: 242 | return self.username_is 243 | return f'{self.username_is}-sudoing-as-{self.username_as}' 244 | 245 | @contextmanager 246 | def _lock_timeout(self): 247 | """ A function to do timeouts """ 248 | def __timeout_handler(_signum, _frame): 249 | """ Convert SIGALRM to Exception """ 250 | #raise TimeoutError('SIGALRM timeout') 251 | raise OSError('SIGALRM timeout') 252 | 253 | # Save off the original signal handler for alarm, add in an exception-throwing function. 254 | original_handler = signal.signal(signal.SIGALRM, __timeout_handler) 255 | try: 256 | # Set an alarm for a few seconds out... 257 | signal.alarm(self.lockwaittime) 258 | # Then yield the flow here, because we want the flow to continue 259 | # and let things run while that alarm ticks on. 260 | yield 261 | finally: 262 | # If we got here, cancel the alarm... 263 | signal.alarm(0) 264 | # ... and restore any old handler. 265 | signal.signal(signal.SIGALRM, original_handler) 266 | 267 | def acquire_lock(self): 268 | """ 269 | This is a time-bound means of waiting for an exclusive lock. 270 | Reason for doing so is down in the main() section 271 | Returns True if locked, False if not 272 | """ 273 | acquired = False 274 | retries = 0 275 | while not acquired: 276 | with self._lock_timeout(): 277 | try: 278 | # Open our lockfile... 279 | self._lock = open(self.lockpath, 'a+', encoding='utf-8') # pylint: disable=consider-using-with 280 | # ... and try to lock it. 281 | # The encoding doesn't matter, it's just to shut pylint up 282 | fcntl.flock(self._lock, fcntl.LOCK_EX) 283 | except (IOError, OSError): 284 | # We didn't lock this time. Don't react. 285 | # We'll try again. 286 | # Close out the FH we opened but couldn't lock... 287 | self._lock.close() 288 | else: 289 | acquired = True 290 | if retries >= self.lockretriesmax: 291 | # We have given up because we've tried too long. 292 | # reset _lock because we don't have one. 293 | self._lock = None 294 | # Tell the world we failed. 295 | self.send_event(summary=('FAIL: internal netfilter issue ' 296 | f'on lock acquisition of {self.lockpath}'), 297 | details={'error': 'true', 298 | 'success': 'false', 299 | # There is no username here 300 | }) 301 | break 302 | retries += 1 303 | return acquired 304 | 305 | def free_lock(self): 306 | """ 307 | Releases the lock that we held 308 | """ 309 | fcntl.flock(self._lock, fcntl.LOCK_UN) 310 | self._lock.close() 311 | self._lock = None 312 | return True 313 | 314 | def _chain_name(self): 315 | """ 316 | OK, you're looking at this and saying "WTF?" 317 | There is an awful name collision all through this library. 318 | Someone coming from a source IP of X, gets an iptables 319 | chain called X, and that chain jumps out to an ipset 320 | also called X. But that might change someday. 321 | So for right now, this exists so that we can have a 322 | different variable scattered in the code in the right places 323 | to indicate whether this means the IP or the chain name. 324 | """ 325 | return self.client_ip 326 | 327 | def iptables(self, argstr, raiseexception=True): 328 | """ 329 | Load the firewall rule received as argument on the local system, 330 | using the iptables binary 331 | 332 | Return: True on success 333 | Exception on error if raiseexception=True 334 | False on error if raiseexception=False 335 | """ 336 | command = f'{self.iptables_executable} {argstr}' 337 | if not raiseexception: 338 | command = command + ' >/dev/null 2>&1' 339 | # IMPROVEME: replace os.system 340 | status = os.system(command) 341 | if status == -1: 342 | # This would require a test case where we misset iptables 343 | raise IptablesFailure(f'failed to invoke iptables ({command})') 344 | status = os.WEXITSTATUS(status) 345 | if raiseexception and (status != 0): 346 | raise IptablesFailure(f'iptables exited with status {status} ({command})') 347 | if status != 0: 348 | return False 349 | return True 350 | 351 | def ipset(self, argstr, raiseexception=True): 352 | """ 353 | Manages an IP Set using the ipset binary 354 | 355 | Return: True on success, 356 | Exception on error if raiseexception=True 357 | False on error if raiseexception=False 358 | """ 359 | command = f'{self.ipset_executable} {argstr}' 360 | if not raiseexception: 361 | command = command + ' >/dev/null 2>&1' 362 | # IMPROVEME: replace os.system 363 | status = os.system(command) 364 | if status == -1: 365 | # This section covers an OS failure, this is almost 366 | # impossible to simulate. 367 | raise IpsetFailure('failed to invoke ipset ({command})') 368 | status = os.WEXITSTATUS(status) 369 | if raiseexception and (status != 0): 370 | raise IpsetFailure(f'ipset exited with status {status} ({command})') 371 | if status != 0: 372 | return False 373 | return True 374 | 375 | def _build_firewall_rule_iptables(self, name, usersrcip, protocol, acl): 376 | """ 377 | This function will select the best way to insert the rule 378 | in iptables. 379 | If protocol and destination port are defined, create a 380 | simple iptables rule. 381 | If only a destination net is set, insert it into the user's 382 | ipset so as to be less unreadable in iptables. 383 | 384 | This function assumes that an iptable/ipset has been created 385 | for a rule to land into. As such, this is intended to be an 386 | internal-only function. 387 | """ 388 | if self.nf_framework != 'iptables': # pragma: no cover 389 | raise RuntimeError('invalid call into _build_firewall_rule_iptables') 390 | comment = '' 391 | if acl.description: 392 | _commentstring = f'{self.username_is}:{acl.rule} ACL {acl.description}' 393 | if protocol and acl.portstring: 394 | if acl.description: 395 | comment = f'-m comment --comment "{_commentstring}"' 396 | destport = f'-m multiport --dports {acl.portstring}' 397 | protocol = f'-p {protocol}' 398 | rulestr = (f'-A {name} -s {usersrcip} -d {acl.address} ' 399 | f'{protocol} {destport} {comment} -j ACCEPT') 400 | self.iptables(rulestr) 401 | else: 402 | if acl.description: 403 | comment = f' comment "{_commentstring}"' 404 | else: 405 | comment = '' 406 | entry = f'--add {name} {acl.address}{comment}' 407 | self.ipset(entry) 408 | 409 | def _build_firewall_rule_nftables(self, name, usersrcip, protocol, acl): 410 | """ 411 | This function will select the best way to insert the rule 412 | in nftables. 413 | If protocol and destination port are defined, create a 414 | simple rule. 415 | If only a destination net is set, insert it into the user's 416 | chain's set. 417 | 418 | This function assumes that a chain and set haive been created 419 | for a rule to land into. As such, this is intended to be an 420 | internal-only function. 421 | """ 422 | if self.nf_framework != 'nftables': # pragma: no cover 423 | raise RuntimeError('invalid call into _build_firewall_rule_nftables') 424 | if protocol and acl.portstring: 425 | dports = [int(x) for x in acl.portstring.split(',')] 426 | comment = None 427 | if acl.description: 428 | comment = f'{self.username_is}:{acl.rule} ACL {acl.description}' 429 | rule_def = { 430 | 'rule': { 431 | 'family': 'inet', 432 | 'table': self.nftables_table, 433 | 'chain': name, 434 | 'comment': comment, 435 | 'expr': [ 436 | { 'match': { 437 | 'op': '==', 438 | 'left': { 'payload': { 'protocol': 'ip', 'field': 'saddr' }}, 439 | 'right': usersrcip, 440 | }}, 441 | { 'match': { 442 | 'op': '==', 443 | 'left': { 'payload': { 'protocol': 'ip', 'field': 'daddr' }}, 444 | 'right': str(acl.address), 445 | }}, 446 | { 'match': { 447 | 'op': '==', 448 | 'left': { 'payload': { 'protocol': protocol, 'field': 'dport' }}, 449 | 'right': { 'set': dports } 450 | }}, 451 | { 'drop': None } 452 | ], 453 | } 454 | } 455 | add_cmd = { 'nftables': [ { 'add': rule_def } ] } 456 | nft_rc, _output, error = self.nft.json_cmd(add_cmd) 457 | if nft_rc != 0: 458 | # IMPROVEME: this add shouldn't fail, we should log more about it. 459 | raise NftablesFailure(f'rule add failed, ({error})') 460 | else: 461 | # set elements can't have comments in nftables 462 | if len(acl.address) == 1: 463 | # This is a single host. 464 | elem_item = [ str(acl.address.network) ] 465 | else: 466 | # This is a range. 467 | elem_item = [ { 'prefix': { 'addr': str(acl.address.network), 468 | 'len': acl.address.prefixlen } } ] 469 | element_def = { 470 | 'element': { 471 | 'family': 'inet', 472 | 'table': self.nftables_table, 473 | 'name': name, 474 | 'elem': elem_item, 475 | } 476 | } 477 | add_cmd = { 'nftables': [ { 'add': element_def } ] } 478 | nft_rc, _output, error = self.nft.json_cmd(add_cmd) 479 | if nft_rc != 0: 480 | # IMPROVEME: this add shouldn't fail, we should log more about it. 481 | raise NftablesFailure(f'set add failed, ({error})') 482 | 483 | def create_user_rules(self, user_acls): 484 | """ 485 | Given the ACLs for a particular user, create the rules that will 486 | limit their access 487 | Inputs: a list of [ParsedACL, ParsedACL, ...] 488 | Output: None. 489 | Changes: box will have an iptables+ipset for the user's IP. 490 | """ 491 | unique_rules_string = ';'.join(sorted({x.rule for x in user_acls})) 492 | # The semicolon-delimited list of rules is used by the 493 | # vpn-fw-find-user utility script. 494 | chain = self._chain_name() 495 | if self.nf_framework == 'iptables': 496 | # First thing, create empty placeholders: 497 | self.iptables('-N ' + chain) 498 | self.ipset('--create ' + chain + ' hash:net comment') 499 | # Now, iterate over the list, which we sort by address 500 | # This assumes that all of the items in user_acls are 501 | # accepts, and thus order won't matter. 502 | for acl in sorted(user_acls, key=lambda acl: acl.address): 503 | if bool(acl.portstring): 504 | protocols = ['tcp', 'udp'] 505 | else: 506 | protocols = [''] 507 | 508 | for protocol in protocols: 509 | self._build_firewall_rule_iptables(chain, self.client_ip, 510 | protocol, acl) 511 | 512 | _commentstring = f'{self.username_is} groups: {unique_rules_string}' 513 | rules_comment = f'-m comment --comment "{_commentstring[:255]}"' 514 | username_comment = f'-m comment --comment "{self.username_is} at {self.client_ip}"' 515 | 516 | # Insert glue to have the user's ipset high up... 517 | use_ipset_rule = (f'-I {chain} -s {self.client_ip} -m set --match-set {chain} dst ' 518 | f'{rules_comment} -j ACCEPT') 519 | self.iptables(use_ipset_rule, True) 520 | # ... and also "accept any established connections" early on. 521 | # This is actually THE first, since it's an Insert after 522 | # another Insert. In case that matters to you later. 523 | allow_established_rule = (f'-I {chain} -m conntrack --ctstate ESTABLISHED ' 524 | f'{username_comment} -j ACCEPT') 525 | self.iptables(allow_established_rule, True) 526 | log_drops_rule = (f'-A {chain} {username_comment} ' 527 | f'-j LOG --log-prefix "DROP {self.username_is[:23]} "') 528 | # log-prefix needs a space at the end ^ 529 | self.iptables(log_drops_rule, True) 530 | drop_rule = (f'-A {chain} {username_comment} ' 531 | '-j REJECT --reject-with icmp-admin-prohibited') 532 | self.iptables(drop_rule, True) 533 | elif self.nf_framework == 'nftables': 534 | self._ensure_nftables_framework() 535 | base_chain_def = { 536 | 'chain': { 537 | 'family': 'inet', 538 | 'table': self.nftables_table, 539 | 'name': chain, 540 | } 541 | } 542 | base_set_def = { 543 | 'set': { 544 | 'family': 'inet', 545 | 'table': self.nftables_table, 546 | # CAUTION: v4-only here: 547 | 'type': 'ipv4_addr', 548 | 'name': chain, 549 | # flags interval means the set can contain CIDRs 550 | 'flags': [ 'interval' ], 551 | } 552 | } 553 | add_cmd = { 'nftables': [ { 'add': base_chain_def }, { 'add': base_set_def } ] } 554 | nft_rc, _output, error = self.nft.json_cmd(add_cmd) 555 | if nft_rc != 0: 556 | raise NftablesFailure(f'chain creation failed, ({error})') 557 | 558 | # Now, iterate over the list, which we sort by address 559 | # This assumes that all of the items in user_acls are 560 | # accepts, and thus order won't matter. 561 | for acl in sorted(user_acls, key=lambda acl: acl.address): 562 | if bool(acl.portstring): 563 | protocols = ['tcp', 'udp'] 564 | else: 565 | protocols = [''] 566 | 567 | for protocol in protocols: 568 | self._build_firewall_rule_nftables(chain, self.client_ip, 569 | protocol, acl) 570 | 571 | # Now begins the glue. 572 | # 573 | # Note, this chain is entered twice from the forward chain. 574 | # 1 when client_ip is the saddr: this is the obvious case. 575 | # 2 when client_ip is the daddr: this is less obvious. 576 | # 577 | # Why put the user rules all in one chain? Well. 'Housekeeping, sorta'. 578 | # We COULD do separate chains but that's kinda 'complexity for no reason' 579 | # but I could be argued off that. 580 | # 581 | # First rule: "accept any established connections" early on. This is 582 | # primarily helpful for when you have an 'established' connection, so "it was okay 583 | # before, should still be okay" in case 1, but also when DNS replies are headed 584 | # back in, the 'related' kicks in on case 2. 585 | # 586 | # After that is the rule that says this client can go out to where it's allowed to. 587 | # That's useful for case 1 but totally useless for case 2. But it'll get skipped 588 | # over quickly as not-applicable in evaluations, so, we just leave it here. 589 | rule_established_def = { 590 | 'rule': { 591 | 'family': 'inet', 592 | 'table': self.nftables_table, 593 | 'chain': chain, 594 | 'comment': f'{self.username_is} at {self.client_ip}', 595 | 'expr': [ 596 | { 'match': { 597 | 'op': 'in', 598 | 'left': { 'ct': { 599 | 'key': 'state', 600 | }}, 601 | 'right': [ 602 | 'established', 603 | 'related', 604 | ], 605 | }}, 606 | { 'accept': None } 607 | ], 608 | } 609 | } 610 | rule_set_def = { 611 | 'rule': { 612 | 'family': 'inet', 613 | 'table': self.nftables_table, 614 | 'chain': chain, 615 | 'expr': [ 616 | { 'match': { 617 | 'op': '==', 618 | 'left': { 'payload': { 619 | 'protocol': 'ip', 620 | 'field': 'saddr' 621 | }}, 622 | 'right': self.client_ip, 623 | }}, 624 | { 'match': { 625 | 'op': '==', 626 | 'left': { 'payload': { 627 | 'protocol': 'ip', 628 | 'field': 'daddr' 629 | }}, 630 | # 'chain' is also the name of the set: 631 | 'right': f'@{chain}', 632 | }}, 633 | { 'accept': None } 634 | ], 635 | } 636 | } 637 | rule_log_def = { 638 | 'rule': { 639 | 'family': 'inet', 640 | 'table': self.nftables_table, 641 | 'chain': chain, 642 | 'expr': [ 643 | { 'log': { 644 | 'prefix': f'DROP {self.username_is[:23]} ' 645 | }}, 646 | ], 647 | } 648 | } 649 | rule_drop_def = { 650 | 'rule': { 651 | 'family': 'inet', 652 | 'table': self.nftables_table, 653 | 'chain': chain, 654 | 'expr': [ 655 | { 'reject': { 656 | 'type': 'icmp', 657 | 'expr': 'admin-prohibited' 658 | }}, 659 | ], 660 | } 661 | } 662 | add_cmd = { 'nftables': [ { 'add': rule_established_def }, 663 | { 'add': rule_set_def }, 664 | { 'add': rule_log_def }, 665 | { 'add': rule_drop_def } ] } 666 | nft_rc, _output, error = self.nft.json_cmd(add_cmd) 667 | if nft_rc != 0: 668 | raise NftablesFailure(f'failed to add glue rules ({error})') 669 | else: # pragma: no cover 670 | # Should be unreachable: 671 | raise RuntimeError('invalid self.nf_framework') 672 | 673 | def _ensure_nftables_framework(self): 674 | ''' 675 | In iptables, we have a main table and forward chain; 676 | In nftables, we have to make it. This is us laying the foundation. 677 | This is invoked from a couple of places to make sure we're okay. 678 | ''' 679 | if self.nf_framework != 'nftables': # pragma: no cover 680 | raise RuntimeError('invalid call into _ensure_nftables_framework') 681 | table_def = { 682 | 'table': { 683 | 'family': 'inet', 684 | 'name': self.nftables_table, 685 | } 686 | } 687 | list_table_cmd = { 'nftables': [ { 'list': table_def } ] } 688 | nft_rc, _output, _error = self.nft.json_cmd(list_table_cmd) 689 | if nft_rc != 0: 690 | # Couldn't list the table. It's probably not there. 691 | add_table_cmd = { 'nftables': [ { 'add': table_def } ] } 692 | _nft_rc, _output, _error = self.nft.json_cmd(add_table_cmd) 693 | # IMPROVEME: what if this is bad? 694 | chain_def = { 695 | 'chain': { 696 | 'family': 'inet', 697 | 'table': self.nftables_table, 698 | 'name': 'FORWARD', 699 | 'type': 'filter', 700 | 'hook': 'forward', 701 | # Just before 'filter' priority: 702 | 'prio': -10, 703 | 'policy': 'drop', 704 | } 705 | } 706 | list_chain_cmd = { 'nftables': [ { 'list': chain_def } ] } 707 | nft_rc, _output, _error = self.nft.json_cmd(list_chain_cmd) 708 | if nft_rc != 0: 709 | # Couldn't list the chain. It's probably not there. 710 | add_chain_cmd = { 'nftables': [ { 'add': chain_def } ] } 711 | _nft_rc, _output, _error = self.nft.json_cmd(add_chain_cmd) 712 | # IMPROVEME: what if this is bad? 713 | return True 714 | 715 | def get_acls_for_user(self): 716 | """ 717 | Fetch the ACLs that a user is allowed to connect to. 718 | Input: None (uses self.username_as) 719 | Return: [ParsedACL, ParsedACL, ...] 720 | """ 721 | # Get the user's ACLs: 722 | raw_acls = self.iam_object.get_allowed_vpn_acls(self.username_as) 723 | # Now, sort those. We sort low to high based on netmask and network 724 | # This is a little odd to follow. It's basically doing a sort that 725 | # is size largest-to-smallest then, within networks of the same size, 726 | # doing network in numerical order. This makes sure a /16 comes 727 | # before a /24, and all /16's are in readable order. 728 | # We do this so that we look at smaller items last, because small 729 | # ACLs may be subsumed by larger ones that we've already seen. 730 | raw_acls.sort(key=lambda x: (x.address.netmask, x.address.network)) 731 | 732 | acls = [] 733 | _seen_nets = [] 734 | for acl in raw_acls: 735 | 736 | for _prev_acl in _seen_nets: 737 | if acl.address in _prev_acl: 738 | # This ACL's address space is fully contained 739 | # within a rule we've already permitted. 740 | break 741 | else: 742 | # We have not seen this before. 743 | if not acl.portstring: 744 | # When there's a portstring, the rule is always 745 | # port specific. So we don't assume we can do anything 746 | # with it (like, you can get to blah port 80, but that 747 | # has no bearing on getting to blah port 22). But when 748 | # portstring is missing, it refers to the whole IP range. 749 | # We add this address to our list, because it means that 750 | # future users who want to use this network already have 751 | # a rule to handle it. 752 | _seen_nets.append(acl.address) 753 | # and at this point, append the acl to our list of things 754 | # acls to pass upstream 755 | acls.append(acl) 756 | 757 | return acls 758 | 759 | def chain_exists(self): 760 | """ 761 | Test existance of 'a chain' in the vague sense, 762 | as there are cases of botched/partial cleanup 763 | """ 764 | if self.nf_framework == 'iptables': 765 | return self.chain_exists_iptables() or self.chain_exists_ipset() 766 | if self.nf_framework == 'nftables': 767 | return self.chain_exists_nftables() 768 | # Should be unreachable: 769 | raise RuntimeError('invalid self.nf_framework') # pragma: no cover 770 | 771 | def chain_exists_iptables(self): 772 | """ 773 | Test existance of a chain via the iptables binary 774 | """ 775 | chain = self._chain_name() 776 | return self.iptables('-L ' + chain, False) 777 | 778 | def chain_exists_ipset(self): 779 | """ 780 | Test existance of a chain via the ipset binary 781 | """ 782 | chain = self._chain_name() 783 | return self.ipset('list ' + chain, False) 784 | 785 | def chain_exists_nftables(self): 786 | ''' Test existance of a chain via the iptables library ''' 787 | chain = self._chain_name() 788 | chain_def = { 789 | 'chain': { 790 | 'family': 'inet', 791 | 'table': self.nftables_table, 792 | 'name': chain, 793 | } 794 | } 795 | list_cmd = { 'nftables': [ { 'list': chain_def } ] } 796 | nft_rc, _output, _error = self.nft.json_cmd(list_cmd) 797 | if nft_rc == 0: 798 | return True 799 | return False 800 | 801 | def add_safety_block(self): 802 | """ 803 | This function adds an iptables block against the vpn IP. 804 | 805 | caution: overload of the word 'block'. 806 | The script that the VPN calls puts in an iptables forwarding 807 | block upon add/update. This is done because we want the script 808 | that is blocking openvpn to finish FAST, but we don't want any 809 | traffic flowing until the (much-slower-to-generate) IAM rules are 810 | put in place (OR it fails, whichever may be the case) 811 | 812 | That script blocks the incoming IP and forks to do the real work 813 | so that openvpn doesn't block. But we don't know if the operation 814 | will succeed yet, so it doesnt allow traffic just to be safe. 815 | This function drops the blocked traffic. Make sure this func 816 | is THE EXACT OPPOSITE of the delete below 817 | """ 818 | # If this fails, we will raise, because something 819 | # is severely messed up. 820 | if self.nf_framework == 'iptables': 821 | return self.iptables(f'-I FORWARD -s {self.client_ip} -j DROP') 822 | if self.nf_framework == 'nftables': 823 | self._ensure_nftables_framework() 824 | rule_def = { 825 | 'rule': { 826 | 'family': 'inet', 827 | 'table': self.nftables_table, 828 | 'chain': 'FORWARD', 829 | 'expr': [ 830 | { 'match': { 831 | 'op': '==', 832 | 'left': { 'payload': { 833 | 'protocol': 'ip', 834 | 'field': 'saddr' 835 | }}, 836 | 'right': self.client_ip, 837 | }}, 838 | { 'drop': None } 839 | ], 840 | } 841 | } 842 | add_cmd = { 'nftables': [ { 'add': rule_def } ] } 843 | nft_rc, _output, error = self.nft.json_cmd(add_cmd) 844 | if nft_rc == 0: 845 | return True 846 | raise NftablesFailure(f'failed to add safety block ({error})') 847 | # Should be unreachable: 848 | raise RuntimeError('invalid self.nf_framework') # pragma: no cover 849 | 850 | def remove_safety_block(self): 851 | """ 852 | This function removes the iptables block against the vpn IP. 853 | """ 854 | if self.nf_framework == 'iptables': 855 | try: 856 | if self.iptables(f'-C FORWARD -s {self.client_ip} -j DROP', False): 857 | # If there was nothing there, there's nothing to do. 858 | # This function can be called when there is or is not 859 | # a block in place, so, only complain if there was one 860 | # which we could not delete. 861 | self.iptables(f'-D FORWARD -s {self.client_ip} -j DROP >/dev/null 2>&1', True) 862 | return True 863 | except IptablesFailure: 864 | # This is an almost-impossible exception to throw, as it would be 865 | # a 'we saw it but couldn't delete it' situation. 866 | self.send_event(summary=('FAIL: did not delete blocking rule, ' 867 | 'potential security issue'), 868 | details={'error': 'true', 869 | 'success': 'false', 870 | 'vpnip': self.client_ip, 871 | 'username': self.username_is, 872 | }, 873 | severity='CRITICAL',) 874 | return False 875 | if self.nf_framework == 'nftables': 876 | # Someday we'll be able to delete by reference. 877 | #rule_def = { 878 | # 'rule': { 879 | # 'family': 'inet', 880 | # 'table': self.nftables_table, 881 | # 'chain': 'FORWARD', 882 | # 'expr': [ 883 | # { 'match': { 884 | # 'op': '==', 885 | # 'left': { 'payload': { 886 | # 'protocol': 'ip', 887 | # 'field': 'saddr' 888 | # }}, 889 | # 'right': self.client_ip, 890 | # }}, 891 | # { 'drop': None } 892 | # ], 893 | # } 894 | #} 895 | # Til then, we have to look up the rules: 896 | chain_holder_def = { 897 | 'chain': { 898 | 'family': 'inet', 899 | 'table': self.nftables_table, 900 | 'name': 'FORWARD', 901 | } 902 | } 903 | list_cmd = { 'nftables': [ { 'list': chain_holder_def } ] } 904 | nft_rc, output, error = self.nft.json_cmd(list_cmd) 905 | if nft_rc != 0: 906 | # If you don't get any rules back from the FORWARD chain, you 907 | # kinda have to assume everything is busted. I mean, this is not 908 | # a complex search here that should ever fail. So you're into 909 | # edge cases like "out of memory" or "all of the table got deleted 910 | # by a rogue actor. At that point everything is suspect so even 911 | # though we're aborting early and not looking for the user's 912 | # chain+set, we're already so busted it's not tenable. 913 | raise NftablesFailure(f'failed to list safety block ({error})') 914 | expr_def = [ 915 | { 'match': { 916 | 'op': '==', 917 | 'left': { 'payload': { 918 | 'protocol': 'ip', 919 | 'field': 'saddr' 920 | }}, 921 | 'right': self.client_ip, 922 | }}, 923 | { 'drop': None } 924 | ] 925 | delete_def = None 926 | for chain_obj in output['nftables']: 927 | rule = chain_obj.get('rule') 928 | if not rule: 929 | continue 930 | expr = rule.get('expr') 931 | if (not expr) or (expr != expr_def): 932 | # "peephole" optimization breaks coverage tests if we don't put in a dummy 933 | # instruction here, unfixable bug in py: http://bugs.python.org/issue2506 934 | _x = 1 935 | continue 936 | delete_def = { 937 | 'rule': { 938 | 'family': rule['family'], 939 | 'table': rule['table'], 940 | 'chain': rule['chain'], 941 | 'handle': rule['handle'], 942 | } 943 | } 944 | break 945 | else: 946 | # Couldn't find a rule to delete, must not be one? 947 | return True 948 | delete_cmd = { 'nftables': [ { 'delete': delete_def } ] } 949 | nft_rc, _output, error = self.nft.json_cmd(delete_cmd) 950 | if nft_rc != 0: 951 | raise NftablesFailure(f'failed to delete safety block ({error})') 952 | return True 953 | # Should be unreachable: 954 | raise RuntimeError('invalid self.nf_framework') # pragma: no cover 955 | 956 | def add_chain(self): 957 | """ 958 | Create a custom chain for the VPN user, named based around 959 | their source IP. 960 | Load the VPN ACL rules into the custom chain 961 | Jump traffic to the custom chain from the 962 | INPUT, OUTPUT & FORWARD chains 963 | """ 964 | if self.chain_exists(): 965 | # This is a dubious little section of code. 966 | # In reality, you should never get here. It means someone is 967 | # trying to create a user chain, for a chain that already exists. 968 | # 969 | # So, NOW what? 970 | # OBVIOUSLY we need to take extraordinary measures here. 971 | # we don't want new rules in the preexisting chain to come 972 | # along and ruin a legit session. 973 | # But really, we shouldn't be here in the first place. openvpn 974 | # shouldn't be handing out an IP it hasn't reclaimed through 975 | # keepalive. So that we're here means something is wrong, 976 | # probably a blowup in testing. But, speculation: likely we 977 | # have a chain that got brought up on boot. 978 | # 979 | # We can't append to / edit the existing rules. That's right 980 | # out. That leaves us with two awful options: 981 | # 982 | # * leave the rules in place. If, by some slim chance, the 983 | # existing chain belongs to a legit user and this is a hack 984 | # attempt, this would be the right call, as it prevents a hack 985 | # causing a DoS of kicking off a legit user. However, if it 986 | # is a mistake / abandoned rule, it would block a new connection 987 | # every time it were attempted. 988 | # There's an assumption here that anyone in a position to do 989 | # a malicious hack can do SO much worse that I can't care about 990 | # this edge case, and as such, we don't choose this route. 991 | # Instead we... 992 | # 993 | # * kill the rules. If the chain is abandoned, nothing is going 994 | # to ever clean it up except someone finding the bad setup. And 995 | # to date, nobody ever has, which means this is a thin case and 996 | # nobody looks for it. Log that this happened and then wipe it. 997 | self.send_event(summary='FAIL: Collision of adding a VPN ACL', 998 | details={'error': 'true', 999 | 'success': 'false', 1000 | 'vpnip': self.client_ip, 1001 | 'username': self.username_is, 1002 | }, 1003 | severity='WARNING',) 1004 | self.del_chain() 1005 | # having now wiped the chain, check again: 1006 | if self.chain_exists(): 1007 | # It didn't delete. Severe problem. 1008 | # This is almost impossible to test, as it means we 1009 | # tried to delete a chain, but it couldn't be deleted. 1010 | self.send_event(summary='FAIL: Undeletable VPN ACL', 1011 | details={'error': 'true', 1012 | 'success': 'false', 1013 | 'vpnip': self.client_ip, 1014 | 'username': self.username_is, 1015 | }, 1016 | severity='ERROR',) 1017 | return False 1018 | # We cleaned the chain out, proceed with a new add. 1019 | user_acls = self.get_acls_for_user() 1020 | self.create_user_rules(user_acls) 1021 | # At this point, a chain and set for usersrcip are now in place. 1022 | # This function continues on to tie them to the OS: 1023 | 1024 | chain = self._chain_name() 1025 | if self.nf_framework == 'iptables': 1026 | self.iptables(f'-A OUTPUT -d {self.client_ip} -j {chain}', True) 1027 | self.iptables(f'-A INPUT -s {self.client_ip} -j {chain}', True) 1028 | self.iptables(f'-A FORWARD -s {self.client_ip} -j {chain}', True) 1029 | # fallthrough 1030 | elif self.nf_framework == 'nftables': 1031 | rule_out_def = { 1032 | 'rule': { 1033 | 'family': 'inet', 1034 | 'table': self.nftables_table, 1035 | 'chain': 'FORWARD', 1036 | 'expr': [ 1037 | { 'match': { 1038 | 'op': '==', 1039 | 'left': { 'payload': { 1040 | 'protocol': 'ip', 1041 | 'field': 'saddr' 1042 | }}, 1043 | 'right': self.client_ip, 1044 | }}, 1045 | { 'jump': { 'target': chain } } 1046 | ], 1047 | } 1048 | } 1049 | rule_in_def = { 1050 | 'rule': { 1051 | 'family': 'inet', 1052 | 'table': self.nftables_table, 1053 | 'chain': 'FORWARD', 1054 | 'expr': [ 1055 | { 'match': { 1056 | 'op': '==', 1057 | 'left': { 'payload': { 1058 | 'protocol': 'ip', 1059 | 'field': 'daddr' 1060 | }}, 1061 | 'right': self.client_ip, 1062 | }}, 1063 | { 'jump': { 'target': chain } } 1064 | ], 1065 | } 1066 | } 1067 | add_cmd = { 'nftables': [ { 'add': rule_out_def }, { 'add': rule_in_def } ] } 1068 | nft_rc, _output, error = self.nft.json_cmd(add_cmd) 1069 | if nft_rc != 0: 1070 | raise NftablesFailure(f'failed to add chaining rules: ({error})') 1071 | # fallthrough 1072 | else: # pragma: no cover 1073 | # Should be unreachable: 1074 | raise RuntimeError('invalid self.nf_framework') 1075 | self.remove_safety_block() 1076 | return True 1077 | 1078 | def del_chain(self): 1079 | """ 1080 | Delete the custom chain and all associated rules 1081 | 1082 | We have to clean up the linking rules from add_chain 1083 | as well as the user items from create_user_rules 1084 | """ 1085 | chain = self._chain_name() 1086 | if self.nf_framework == 'iptables': 1087 | self.iptables(f'-D OUTPUT -d {self.client_ip} -j {chain}', False) 1088 | self.iptables(f'-D INPUT -s {self.client_ip} -j {chain}', False) 1089 | self.iptables(f'-D FORWARD -s {self.client_ip} -j {chain}', False) 1090 | self.iptables(f'-F {chain}', False) 1091 | self.iptables(f'-X {chain}', False) 1092 | self.ipset(f'--destroy {chain}', False) 1093 | elif self.nf_framework == 'nftables': 1094 | # We can get rid of the user's chain and set by name, 1095 | # But we have to get the FORWARD rules by handle. 1096 | 1097 | # First thing, let's look up and remove the 'FORWARD' rules. 1098 | 1099 | chain_holder_def = { 1100 | 'chain': { 1101 | 'family': 'inet', 1102 | 'table': self.nftables_table, 1103 | 'name': 'FORWARD', 1104 | } 1105 | } 1106 | list_cmd = { 'nftables': [ { 'list': chain_holder_def } ] } 1107 | nft_rc, output, error = self.nft.json_cmd(list_cmd) 1108 | if nft_rc != 0: 1109 | # If you don't get any rules back from the FORWARD chain, you 1110 | # kinda have to assume everything is busted. I mean, this is not 1111 | # a complex search here that should ever fail. So you're into 1112 | # edge cases like "out of memory" or "all of the table got deleted 1113 | # by a rogue actor. At that point everything is suspect so even 1114 | # though we're aborting early and not looking for the user's 1115 | # chain+set, we're already so busted it's not tenable. 1116 | raise NftablesFailure(f'failed to list FORWARD ({error})') 1117 | delete_defs = [] 1118 | 1119 | expr_out_def = [ 1120 | { 'match': { 1121 | 'op': '==', 1122 | 'left': { 'payload': { 1123 | 'protocol': 'ip', 1124 | 'field': 'saddr' 1125 | }}, 1126 | 'right': self.client_ip, 1127 | }}, 1128 | { 'jump': { 'target': chain } } 1129 | ] 1130 | expr_in_def = [ 1131 | { 'match': { 1132 | 'op': '==', 1133 | 'left': { 'payload': { 1134 | 'protocol': 'ip', 1135 | 'field': 'daddr' 1136 | }}, 1137 | 'right': self.client_ip, 1138 | }}, 1139 | { 'jump': { 'target': chain } } 1140 | ] 1141 | for chain_obj in output['nftables']: 1142 | rule = chain_obj.get('rule') 1143 | if not rule: 1144 | continue 1145 | expr = rule.get('expr') 1146 | if (not expr) or (expr not in (expr_out_def, expr_in_def)): 1147 | # "peephole" optimization breaks coverage tests if we don't put in a dummy 1148 | # instruction here, unfixable bug in py: http://bugs.python.org/issue2506 1149 | _x = 1 1150 | continue 1151 | delete_defs.append({ 1152 | 'rule': { 1153 | 'family': rule['family'], 1154 | 'table': rule['table'], 1155 | 'chain': rule['chain'], 1156 | 'handle': rule['handle'], 1157 | } 1158 | }) 1159 | # Here's a fallthrough. We could've matched nothing. That would be unusual, 1160 | # but if there's nothing to delete, then there's nothing to delete. 1161 | for delete_def in delete_defs: 1162 | del_cmd = { 'nftables': [ { 'delete': delete_def } ] } 1163 | _nft_rc, _output, _error = self.nft.json_cmd(del_cmd) 1164 | # IMPROVEME 1165 | 1166 | # After those two rules are gone, we can do the delete of the user's 1167 | # chain and set by name. 1168 | 1169 | base_chain_def = { 1170 | 'chain': { 1171 | 'family': 'inet', 1172 | 'table': self.nftables_table, 1173 | 'name': chain, 1174 | } 1175 | } 1176 | base_set_def = { 1177 | 'set': { 1178 | 'family': 'inet', 1179 | 'table': self.nftables_table, 1180 | # CAUTION: v4-only here: 1181 | 'type': 'ipv4_addr', 1182 | 'name': chain, 1183 | } 1184 | } 1185 | del_cmd = { 'nftables': [ { 'delete': base_chain_def }, 1186 | { 'delete': base_set_def } ] } 1187 | _nft_rc, _output, _error = self.nft.json_cmd(del_cmd) 1188 | # We don't check the output here; these 'just work' 1189 | else: # pragma: no cover 1190 | # Should be unreachable: 1191 | raise RuntimeError('invalid self.nf_framework') 1192 | return True 1193 | 1194 | def update_chain(self): 1195 | """ 1196 | Wrapper function around add and delete 1197 | """ 1198 | self.del_chain() 1199 | return self.add_chain() 1200 | --------------------------------------------------------------------------------