From 542718b956cfb865fa34202b332ee36939878a00 Mon Sep 17 00:00:00 2001 From: Ruben van Staveren Date: Fri, 11 Mar 2022 21:21:40 +0100 Subject: [PATCH] Add exception handler for when pfctl operations fail --- jail2ban/__init__.py | 9 +++++++++ tests/test_flush.py | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/jail2ban/__init__.py b/jail2ban/__init__.py index b56d970..1716123 100644 --- a/jail2ban/__init__.py +++ b/jail2ban/__init__.py @@ -5,6 +5,7 @@ from ipaddress import ip_address import re from jail2ban.pfctl import pfctl_table_op, pfctl_cfg_read, pfctl_cfg_write from jail2ban.auth import get_users +from subprocess import CalledProcessError auth = HTTPBasicAuth() @@ -130,6 +131,14 @@ def create_app(): app.logger.fatal(error) return jsonify({'error': str(error)}), 500 + @app.errorhandler(CalledProcessError) + def subprocess_err(error): + ''' + Show a json parsable error if the value is illegal + ''' + app.logger.fatal(error) + return jsonify({'error': str(error)}), 500 + @auth.error_handler def auth_error(): app.logger.error('Access Denied') diff --git a/tests/test_flush.py b/tests/test_flush.py index ea6219d..dcd45b7 100644 --- a/tests/test_flush.py +++ b/tests/test_flush.py @@ -1,5 +1,6 @@ import base64 from types import SimpleNamespace +from subprocess import CalledProcessError def test_flush(client, mocker): @@ -19,3 +20,19 @@ def test_flush(client, mocker): headers={"Authorization": "Basic " + valid_credentials}) assert response.json['operation'] == 'flush' + + +def test_flush_nonexistent(client, mocker): + + cmd = ['/usr/local/bin/sudo', '/sbin/pfctl', '-a', 'some/anchor', '-t', 'nonexistent', '-T', 'flush'] + + mocker.patch('jail2ban.pfctl.run', + side_effect=CalledProcessError(255, cmd, output=b'', + stderr=b'pfctl: Table does not exist')) + + valid_credentials = base64.b64encode(b"test.example.com:testpassword").decode("utf-8") + name = 'nonexistent' + response = client.get(f"/flush/{name}", + headers={"Authorization": "Basic " + valid_credentials}) + + assert 'error' in response.json