This commit is contained in:
parent 06a5a758a3
commit 58fa7d1ee6
19 changed files with 567 additions and 377 deletions

View file

@ -74,7 +74,8 @@ class UFWRule(BaseModel):
"""
if isinstance(v, int):
if not (1 <= v <= 65535):
raise ValueError(f"Порт должен быть в диапазоне 1-65535, получено: {v}")
raise ValueError(
f"Порт должен быть в диапазоне 1-65535, получено: {v}")
return v
elif isinstance(v, str):
try:
@ -112,8 +113,7 @@ class UFWRule(BaseModel):
to_ip = ipaddress.ip_network(v, strict=False)
if isinstance(from_ip, ipaddress.IPv6Network) != isinstance(
to_ip, ipaddress.IPv6Network
):
to_ip, ipaddress.IPv6Network):
raise ValueError(
"Несовместимые версии IP: нельзя смешивать IPv4 и IPv6 в одном правиле"
)
@ -151,7 +151,8 @@ class UFWRule(BaseModel):
cmd_parts.extend(["to", self.to_ip])
# Добавляем порт и протокол
port_str = str(self.port) # Работает как с числами, так и с диапазонами
port_str = str(
self.port) # Работает как с числами, так и с диапазонами
cmd_parts.extend(["port", port_str])
# Добавляем протокол
@ -195,25 +196,20 @@ class UFWRule(BaseModel):
match = re.match(pattern, line, re.VERBOSE | re.IGNORECASE)
if not match:
raise ValueError(f"Невозможно разобрать строку правила UFW: {line}")
raise ValueError(
f"Невозможно разобрать строку правила UFW: {line}")
groups = match.groupdict()
# Преобразуем протокол в enum
proto_str = groups["protocol"].lower()
protocol = (
Protocol.BOTH
if proto_str == "tcp/udp"
else Protocol.UDP if proto_str == "udp" else Protocol.TCP
)
protocol = (Protocol.BOTH if proto_str == "tcp/udp" else
Protocol.UDP if proto_str == "udp" else Protocol.TCP)
# Преобразуем действие в enum (игнорируем регистр)
action_str = groups["action"].lower()
action = (
Action.ALLOW
if action_str == "allow"
else Action.DENY if action_str == "deny" else Action.REJECT
)
action = (Action.ALLOW if action_str == "allow" else
Action.DENY if action_str == "deny" else Action.REJECT)
# Преобразуем направление в enum
direction_str = groups["direction"].lower()
@ -237,7 +233,8 @@ class UFWRule(BaseModel):
port = int(port)
# Обрабатываем комментарий
comment = groups.get("comment", "").strip() if groups.get("comment") else None
comment = groups.get("comment",
"").strip() if groups.get("comment") else None
return cls(
action=action,
@ -261,7 +258,8 @@ class UFWRulesResponse(BaseModel):
"""
enabled: bool = Field(..., description="Включен ли UFW")
rules: List[UFWRule] = Field(default_factory=list, description="Список правил UFW")
rules: List[UFWRule] = Field(default_factory=list,
description="Список правил UFW")
@property
def total_rules(self) -> int: