feat(pydantic): Add Port and PortRange

This commit is contained in:
v-lafeychine 2023-06-16 23:26:07 +02:00
parent e55e1cc68c
commit d2d43bb5ed
Signed by: v-lafeychine
GPG key ID: F46CAAD27C7AB0D5
2 changed files with 28 additions and 25 deletions

View file

@ -30,14 +30,14 @@ filter:
- src: mgmt - src: mgmt
protocols: protocols:
tcp: tcp:
dport: "22,240..242" dport: [22, 240..242]
verdict: accept verdict: accept
- src: backbone - src: backbone
protocols: protocols:
ospf: true ospf: true
vrrp: true vrrp: true
tcp: tcp:
dport: 179 dport: [179]
verdict: accept verdict: accept
- protocols: - protocols:
icmp: true icmp: true
@ -50,7 +50,7 @@ filter:
- src: users-internet-allowed - src: users-internet-allowed
protocols: protocols:
tcp: tcp:
dport: 25 dport: [25]
verdict: drop verdict: drop
- src: users-internet-allowed - src: users-internet-allowed
dest: dest:

View file

@ -9,6 +9,8 @@ from pydantic import (
FilePath, FilePath,
IPvAnyAddress, IPvAnyAddress,
IPvAnyNetwork, IPvAnyNetwork,
conint,
parse_obj_as,
validator, validator,
root_validator, root_validator,
) )
@ -19,18 +21,27 @@ class RestrictiveBaseModel(BaseModel, extra=Extra.forbid):
pass pass
def parse_range_string(s): # Ports
parts = s.split(",") Port = conint(ge=0, le=2**16)
values = []
for part in parts:
if ".." in part:
start, end = part.split("..")
values.append(range(int(start), int(end) + 1))
else:
values.append(int(part))
return values class PortRange(str):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
try:
start, end = v.split("..")
except ValueError:
raise ValueError("invalid port range: must be in the form start..end")
start, end = parse_obj_as(Port, start), parse_obj_as(Port, end)
if start > end:
raise ValueError("invalid port range: start must be less than end")
return range(start, end)
# Zones # Zones
@ -73,21 +84,13 @@ class Verdict(str, Enum):
class TcpProtocol(RestrictiveBaseModel): class TcpProtocol(RestrictiveBaseModel):
dport: str | None dport: list[Port | PortRange] | None
sport: str | None sport: list[Port | PortRange] | None
@validator("dport", "sport")
def parse_range(cls, v):
return parse_range_string(v)
class UdpProtocol(RestrictiveBaseModel): class UdpProtocol(RestrictiveBaseModel):
dport: str | None dport: list[Port | PortRange] | None
sport: str | None sport: list[Port | PortRange] | None
@validator("dport", "sport")
def parse_range(cls, v):
return parse_range_string(v)
class Protocols(RestrictiveBaseModel): class Protocols(RestrictiveBaseModel):