mirror of
https://github.com/home-assistant/core.git
synced 2026-01-14 03:27:32 +01:00
Compare commits
1 Commits
sensor_gro
...
edenhaus-r
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3d918cc09 |
@@ -1 +0,0 @@
|
||||
"""The fail2ban component."""
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"domain": "fail2ban",
|
||||
"name": "Fail2Ban",
|
||||
"codeowners": [],
|
||||
"documentation": "https://www.home-assistant.io/integrations/fail2ban",
|
||||
"iot_class": "local_polling",
|
||||
"quality_scale": "legacy"
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
"""Support for displaying IPs banned by fail2ban."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
|
||||
SensorEntity,
|
||||
)
|
||||
from homeassistant.const import CONF_FILE_PATH, CONF_NAME
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_JAILS = "jails"
|
||||
|
||||
DEFAULT_NAME = "fail2ban"
|
||||
DEFAULT_LOG = "/var/log/fail2ban.log"
|
||||
|
||||
STATE_CURRENT_BANS = "current_bans"
|
||||
STATE_ALL_BANS = "total_bans"
|
||||
SCAN_INTERVAL = timedelta(seconds=120)
|
||||
|
||||
PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
|
||||
{
|
||||
vol.Required(CONF_JAILS): vol.All(cv.ensure_list, vol.Length(min=1)),
|
||||
vol.Optional(CONF_FILE_PATH): cv.isfile,
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_platform(
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
discovery_info: DiscoveryInfoType | None = None,
|
||||
) -> None:
|
||||
"""Set up the fail2ban sensor."""
|
||||
name = config[CONF_NAME]
|
||||
jails = config[CONF_JAILS]
|
||||
log_file = config.get(CONF_FILE_PATH, DEFAULT_LOG)
|
||||
|
||||
log_parser = BanLogParser(log_file)
|
||||
|
||||
async_add_entities((BanSensor(name, jail, log_parser) for jail in jails), True)
|
||||
|
||||
|
||||
class BanSensor(SensorEntity):
|
||||
"""Implementation of a fail2ban sensor."""
|
||||
|
||||
def __init__(self, name, jail, log_parser):
|
||||
"""Initialize the sensor."""
|
||||
self._name = f"{name} {jail}"
|
||||
self.jail = jail
|
||||
self.ban_dict = {STATE_CURRENT_BANS: [], STATE_ALL_BANS: []}
|
||||
self.last_ban = None
|
||||
self.log_parser = log_parser
|
||||
self.log_parser.ip_regex[self.jail] = re.compile(
|
||||
rf"\[{re.escape(self.jail)}\]\s*(Ban|Unban) (.*)"
|
||||
)
|
||||
_LOGGER.debug("Setting up jail %s", self.jail)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self):
|
||||
"""Return the state attributes of the fail2ban sensor."""
|
||||
return self.ban_dict
|
||||
|
||||
@property
|
||||
def native_value(self):
|
||||
"""Return the most recently banned IP Address."""
|
||||
return self.last_ban
|
||||
|
||||
def update(self) -> None:
|
||||
"""Update the list of banned ips."""
|
||||
self.log_parser.read_log(self.jail)
|
||||
|
||||
if self.log_parser.data:
|
||||
for entry in self.log_parser.data:
|
||||
_LOGGER.debug(entry)
|
||||
current_ip = entry[1]
|
||||
if entry[0] == "Ban":
|
||||
if current_ip not in self.ban_dict[STATE_CURRENT_BANS]:
|
||||
self.ban_dict[STATE_CURRENT_BANS].append(current_ip)
|
||||
if current_ip not in self.ban_dict[STATE_ALL_BANS]:
|
||||
self.ban_dict[STATE_ALL_BANS].append(current_ip)
|
||||
if len(self.ban_dict[STATE_ALL_BANS]) > 10:
|
||||
self.ban_dict[STATE_ALL_BANS].pop(0)
|
||||
|
||||
elif (
|
||||
entry[0] == "Unban"
|
||||
and current_ip in self.ban_dict[STATE_CURRENT_BANS]
|
||||
):
|
||||
self.ban_dict[STATE_CURRENT_BANS].remove(current_ip)
|
||||
|
||||
if self.ban_dict[STATE_CURRENT_BANS]:
|
||||
self.last_ban = self.ban_dict[STATE_CURRENT_BANS][-1]
|
||||
else:
|
||||
self.last_ban = "None"
|
||||
|
||||
|
||||
class BanLogParser:
|
||||
"""Class to parse fail2ban logs."""
|
||||
|
||||
def __init__(self, log_file):
|
||||
"""Initialize the parser."""
|
||||
self.log_file = log_file
|
||||
self.data = []
|
||||
self.ip_regex = {}
|
||||
|
||||
def read_log(self, jail):
|
||||
"""Read the fail2ban log and find entries for jail."""
|
||||
self.data = []
|
||||
try:
|
||||
with open(self.log_file, encoding="utf-8") as file_data:
|
||||
self.data = self.ip_regex[jail].findall(file_data.read())
|
||||
|
||||
except (IndexError, FileNotFoundError, IsADirectoryError, UnboundLocalError):
|
||||
_LOGGER.warning("File not present: %s", os.path.basename(self.log_file))
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for the fail2ban component."""
|
||||
@@ -1,206 +0,0 @@
|
||||
"""The tests for local file sensor platform."""
|
||||
|
||||
from unittest.mock import Mock, mock_open, patch
|
||||
|
||||
from homeassistant.components.fail2ban.sensor import (
|
||||
STATE_ALL_BANS,
|
||||
STATE_CURRENT_BANS,
|
||||
BanLogParser,
|
||||
BanSensor,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import assert_setup_component
|
||||
|
||||
|
||||
def fake_log(log_key):
|
||||
"""Return a fake fail2ban log."""
|
||||
fake_log_dict = {
|
||||
"single_ban": (
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 111.111.111.111"
|
||||
),
|
||||
"ipv6_ban": (
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 2607:f0d0:1002:51::4"
|
||||
),
|
||||
"multi_ban": (
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 111.111.111.111\n"
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 222.222.222.222"
|
||||
),
|
||||
"multi_jail": (
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 111.111.111.111\n"
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_two] Ban 222.222.222.222"
|
||||
),
|
||||
"unban_all": (
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 111.111.111.111\n"
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Unban 111.111.111.111\n"
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 222.222.222.222\n"
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Unban 222.222.222.222"
|
||||
),
|
||||
"unban_one": (
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 111.111.111.111\n"
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Ban 222.222.222.222\n"
|
||||
"2017-01-01 12:23:35 fail2ban.actions [111]: "
|
||||
"NOTICE [jail_one] Unban 111.111.111.111"
|
||||
),
|
||||
}
|
||||
return fake_log_dict[log_key]
|
||||
|
||||
|
||||
@patch("os.path.isfile", Mock(return_value=True))
|
||||
async def test_setup(hass: HomeAssistant) -> None:
|
||||
"""Test that sensor can be setup."""
|
||||
config = {"sensor": {"platform": "fail2ban", "jails": ["jail_one"]}}
|
||||
mock_fh = mock_open()
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
assert await async_setup_component(hass, "sensor", config)
|
||||
await hass.async_block_till_done()
|
||||
assert_setup_component(1, "sensor")
|
||||
|
||||
|
||||
@patch("os.path.isfile", Mock(return_value=True))
|
||||
async def test_multi_jails(hass: HomeAssistant) -> None:
|
||||
"""Test that multiple jails can be set up as sensors.."""
|
||||
config = {"sensor": {"platform": "fail2ban", "jails": ["jail_one", "jail_two"]}}
|
||||
mock_fh = mock_open()
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
assert await async_setup_component(hass, "sensor", config)
|
||||
await hass.async_block_till_done()
|
||||
assert_setup_component(2, "sensor")
|
||||
|
||||
|
||||
async def test_single_ban(hass: HomeAssistant) -> None:
|
||||
"""Test that log is parsed correctly for single ban."""
|
||||
log_parser = BanLogParser("/test/fail2ban.log")
|
||||
sensor = BanSensor("fail2ban", "jail_one", log_parser)
|
||||
sensor.hass = hass
|
||||
assert sensor.name == "fail2ban jail_one"
|
||||
mock_fh = mock_open(read_data=fake_log("single_ban"))
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
sensor.update()
|
||||
|
||||
assert sensor.state == "111.111.111.111"
|
||||
assert sensor.extra_state_attributes[STATE_CURRENT_BANS] == ["111.111.111.111"]
|
||||
assert sensor.extra_state_attributes[STATE_ALL_BANS] == ["111.111.111.111"]
|
||||
|
||||
|
||||
async def test_ipv6_ban(hass: HomeAssistant) -> None:
|
||||
"""Test that log is parsed correctly for IPV6 bans."""
|
||||
log_parser = BanLogParser("/test/fail2ban.log")
|
||||
sensor = BanSensor("fail2ban", "jail_one", log_parser)
|
||||
sensor.hass = hass
|
||||
assert sensor.name == "fail2ban jail_one"
|
||||
mock_fh = mock_open(read_data=fake_log("ipv6_ban"))
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
sensor.update()
|
||||
|
||||
assert sensor.state == "2607:f0d0:1002:51::4"
|
||||
assert sensor.extra_state_attributes[STATE_CURRENT_BANS] == ["2607:f0d0:1002:51::4"]
|
||||
assert sensor.extra_state_attributes[STATE_ALL_BANS] == ["2607:f0d0:1002:51::4"]
|
||||
|
||||
|
||||
async def test_multiple_ban(hass: HomeAssistant) -> None:
|
||||
"""Test that log is parsed correctly for multiple ban."""
|
||||
log_parser = BanLogParser("/test/fail2ban.log")
|
||||
sensor = BanSensor("fail2ban", "jail_one", log_parser)
|
||||
sensor.hass = hass
|
||||
assert sensor.name == "fail2ban jail_one"
|
||||
mock_fh = mock_open(read_data=fake_log("multi_ban"))
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
sensor.update()
|
||||
|
||||
assert sensor.state == "222.222.222.222"
|
||||
assert sensor.extra_state_attributes[STATE_CURRENT_BANS] == [
|
||||
"111.111.111.111",
|
||||
"222.222.222.222",
|
||||
]
|
||||
assert sensor.extra_state_attributes[STATE_ALL_BANS] == [
|
||||
"111.111.111.111",
|
||||
"222.222.222.222",
|
||||
]
|
||||
|
||||
|
||||
async def test_unban_all(hass: HomeAssistant) -> None:
|
||||
"""Test that log is parsed correctly when unbanning."""
|
||||
log_parser = BanLogParser("/test/fail2ban.log")
|
||||
sensor = BanSensor("fail2ban", "jail_one", log_parser)
|
||||
sensor.hass = hass
|
||||
assert sensor.name == "fail2ban jail_one"
|
||||
mock_fh = mock_open(read_data=fake_log("unban_all"))
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
sensor.update()
|
||||
|
||||
assert sensor.state == "None"
|
||||
assert sensor.extra_state_attributes[STATE_CURRENT_BANS] == []
|
||||
assert sensor.extra_state_attributes[STATE_ALL_BANS] == [
|
||||
"111.111.111.111",
|
||||
"222.222.222.222",
|
||||
]
|
||||
|
||||
|
||||
async def test_unban_one(hass: HomeAssistant) -> None:
|
||||
"""Test that log is parsed correctly when unbanning one ip."""
|
||||
log_parser = BanLogParser("/test/fail2ban.log")
|
||||
sensor = BanSensor("fail2ban", "jail_one", log_parser)
|
||||
sensor.hass = hass
|
||||
assert sensor.name == "fail2ban jail_one"
|
||||
mock_fh = mock_open(read_data=fake_log("unban_one"))
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
sensor.update()
|
||||
|
||||
assert sensor.state == "222.222.222.222"
|
||||
assert sensor.extra_state_attributes[STATE_CURRENT_BANS] == ["222.222.222.222"]
|
||||
assert sensor.extra_state_attributes[STATE_ALL_BANS] == [
|
||||
"111.111.111.111",
|
||||
"222.222.222.222",
|
||||
]
|
||||
|
||||
|
||||
async def test_multi_jail(hass: HomeAssistant) -> None:
|
||||
"""Test that log is parsed correctly when using multiple jails."""
|
||||
log_parser = BanLogParser("/test/fail2ban.log")
|
||||
sensor1 = BanSensor("fail2ban", "jail_one", log_parser)
|
||||
sensor2 = BanSensor("fail2ban", "jail_two", log_parser)
|
||||
sensor1.hass = hass
|
||||
sensor2.hass = hass
|
||||
assert sensor1.name == "fail2ban jail_one"
|
||||
assert sensor2.name == "fail2ban jail_two"
|
||||
mock_fh = mock_open(read_data=fake_log("multi_jail"))
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
sensor1.update()
|
||||
sensor2.update()
|
||||
|
||||
assert sensor1.state == "111.111.111.111"
|
||||
assert sensor1.extra_state_attributes[STATE_CURRENT_BANS] == ["111.111.111.111"]
|
||||
assert sensor1.extra_state_attributes[STATE_ALL_BANS] == ["111.111.111.111"]
|
||||
assert sensor2.state == "222.222.222.222"
|
||||
assert sensor2.extra_state_attributes[STATE_CURRENT_BANS] == ["222.222.222.222"]
|
||||
assert sensor2.extra_state_attributes[STATE_ALL_BANS] == ["222.222.222.222"]
|
||||
|
||||
|
||||
async def test_ban_active_after_update(hass: HomeAssistant) -> None:
|
||||
"""Test that ban persists after subsequent update."""
|
||||
log_parser = BanLogParser("/test/fail2ban.log")
|
||||
sensor = BanSensor("fail2ban", "jail_one", log_parser)
|
||||
sensor.hass = hass
|
||||
assert sensor.name == "fail2ban jail_one"
|
||||
mock_fh = mock_open(read_data=fake_log("single_ban"))
|
||||
with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True):
|
||||
sensor.update()
|
||||
assert sensor.state == "111.111.111.111"
|
||||
sensor.update()
|
||||
assert sensor.state == "111.111.111.111"
|
||||
assert sensor.extra_state_attributes[STATE_CURRENT_BANS] == ["111.111.111.111"]
|
||||
assert sensor.extra_state_attributes[STATE_ALL_BANS] == ["111.111.111.111"]
|
||||
Reference in New Issue
Block a user