Skip to content

Commit

Permalink
FIREWALL: Allow to block hosts by IP address
Browse files Browse the repository at this point in the history
When blocking a host, its hostname is resolved using the `dig`
command. If an IP address is provided, `dig` returns nothing.
Check whether it is an IP address before launching `dig`.

No matter whether the correct family is requested, do not call
`dig` when an IP address is provided, in case the caller has
already blocked the DNS host.
  • Loading branch information
aplopez committed Oct 24, 2024
1 parent 74df4af commit 656416d
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions pytest_mh/utils/firewall.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from abc import abstractmethod
from random import randrange
from typing import Any, Literal, TypeAlias
from ipaddress import IPv4Address, IPv6Address

from .. import MultihostHost, MultihostRole, MultihostUtility
from ..conn import ProcessLogLevel
Expand Down Expand Up @@ -605,9 +606,26 @@ def __add_host(
self.firewall.add_rich_rule(f"family=ipv6 destination address={ip} {action}")

def __resolve_hostname(self, hostname: str, type: Literal["A", "AAAA"]) -> list[str]:
result = self.firewall.host.conn.exec(["dig", "+short", "-t", type, hostname], log_level=ProcessLogLevel.Error)

return result.stdout_lines
try:
ipv4 = IPv4Address(hostname)
if type == "A":
return [hostname]
except ValueError:
ipv4 = None

try:
ipv6 = IPv6Address(hostname)
if type == "AAAA":
return [hostname]
except ValueError:
ipv6 = None

if ipv4 is not None or ipv6 is not None:
# In this case we were given an IP address but of the wrong family. We must not consider it a hostname.
return []
else:
result = self.firewall.host.conn.exec(["dig", "+short", "-t", type, hostname], log_level=ProcessLogLevel.Error)
return result.stdout_lines


class WindowsFirewall(Firewall):
Expand Down

0 comments on commit 656416d

Please sign in to comment.