Skip to content

service

Custom firewall services, port ranges, and service groups.

APP_SERVICE_TYPE module-attribute #

APP_SERVICE_TYPE = Literal['disable', 'app-id', 'app-category']

CHECK_RESET_RANGE module-attribute #

CHECK_RESET_RANGE = Literal['disable', 'default', 'strict']

ENABLE_DISABLE module-attribute #

ENABLE_DISABLE = Literal['disable', 'enable']

HELPER module-attribute #

HELPER = Literal[
    "disable",
    "auto",
    "ftp",
    "tftp",
    "ras",
    "h323",
    "tns",
    "mms",
    "sip",
    "pptp",
    "rtsp",
    "dns-udp",
    "dns-tcp",
    "pmap",
    "rsh",
    "dcerpc",
    "mgcp",
    "gtp-c",
    "gtp-u",
    "gtp-b",
    "pfcp",
]

PORT_RANGE_TYPE module-attribute #

PORT_RANGE_TYPE = Union[Union[str, PortRange], list[Union[str, PortRange]]]

PROTOCOL module-attribute #

PROTOCOL = Literal[
    "ICMP", "IP", "TCP/UDP/SCTP", "ICMP6", "HTTP", "FTP", "CONNECT", "SOCKS", "ALL", "SOCKS-TCP", "SOCKS-UDP"
]

PortRange #

Bases: BaseModel

Port range class

This dataclass is to hold source_start:source_end and destination_start:destination_end port data. For a single source or destination port, either the start or end endpoint can be supplied. The missing endpoint is normalized to the supplied value.

standardize_port_handling #

standardize_port_handling() -> Self

Ensure start and end are either None or the same if not different

Source code in pyfortinet/fmg_api/firewall/service.py
@model_validator(mode="after")
def standardize_port_handling(self) -> Self:
    """Ensure start and end are either None or the same if not different"""
    try:
        if int(self.source_start) > int(self.source_end):
            raise ValueError("Start port must be equal or less than end port!")
    except TypeError:
        pass
    try:
        if int(self.destination_start) > int(self.destination_end):
            raise ValueError("Start port must be equal or less than end port!")
    except TypeError:
        pass

    self.source_start = self.source_start or self.source_end
    self.source_end = self.source_end or self.source_start
    self.destination_start = self.destination_start or self.destination_end
    self.destination_end = self.destination_end or self.destination_start
    return self

ServiceCategory #

Bases: FMGObject

ServiceCustom #

Bases: FMGObject

Custom service class

Attributes:

Name Type Description
app_category Optional[list[int]]

Application category ID

app_service_type Optional[APP_SERVICE_TYPE]

Application service type

application Optional[list[int]]

Application name ID

category Optional[list[Union[ServiceCategory, str]]]

Service category

check_reset_range Optional[CHECK_RESET_RANGE]

Enable to reset session if service does not match

color Optional[int]

Color of icon on the GUI

comment Optional[str]

Comment

fabric_object Optional[ENABLE_DISABLE]

Security Fabric global object setting

fqdn Optional[str]

Fully Qualified Domain Name (FQDN)

helper Optional[HELPER]

Name of helper

icmpcode Optional[int]

ICMP code

icmptype Optional[int]

ICMP type

iprange Optional[str]

Start and end IP addresses for the range

name Optional[str]

Service name

protocol Optional[PROTOCOL]

Protocol type: TCP/UDP/SCTP/ICMP/ICMP6

protocol_number Optional[int]

IP protocol number

proxy Optional[ENABLE_DISABLE]

Enable to use this service for proxy

sctp_portrange Optional[PORT_RANGE_TYPE]

SCTP port range

session_ttl Optional[str]

Session TTL (Timeout) in seconds

tcp_halfclose_timer Optional[int]

TCP half-close timer, in seconds

tcp_halfopen_timer Optional[int]

TCP half-open timer, in seconds

tcp_portrange Optional[PORT_RANGE_TYPE]

TCP port range

tcp_rst_timer Optional[int]

TCP RST timer, in seconds

tcp_timewait_timer Optional[int]

TCP time-wait timer, in seconds

udp_idle_timer Optional[int]

UDP idle timer, in seconds

udp_portrange Optional[PORT_RANGE_TYPE]

UDP port range

visibility Optional[ENABLE_DISABLE]

Enable/disable visibility on FortiGate GUI

ensure_port_ranges #

ensure_port_ranges(v) -> Optional[list[PortRange]]

Create PortRange object from string to standardize portrange handling

Source code in pyfortinet/fmg_api/firewall/service.py
@field_validator("udp_portrange", "tcp_portrange", "sctp_portrange", mode="plain")
def ensure_port_ranges(cls, v) -> Optional[list[PortRange]]:
    """Create PortRange object from string to standardize portrange handling"""
    if v is None:
        return None
    ranges = []
    if not isinstance(v, list):
        v = [v]
    for rng in v:
        if isinstance(rng, PortRange):
            ranges.append(rng)
            continue
        if not isinstance(rng, str):
            raise ValueError("Port ranges must be strings or PortRange objects")
        # assuming string
        # format: "dst_st-dst_end:src_st-src_end"
        match = re.fullmatch(
            r"^(?P<dst>(?P<destination_start>\d+)(?:-(?P<destination_end>\d+))?)"
            r"(?::(?P<src>(?P<source_start>\d+)(?:-(?P<source_end>\d+))?))?$",
            rng,
        )
        if not match:
            raise ValueError(f"Invalid port range: {rng!r}")
        data = match.groupdict()
        if not data["destination_end"]:
            data["destination_end"] = data["destination_start"]
        if not data["source_end"]:
            data["source_end"] = data["source_start"]
        ranges.append(PortRange(**data))
    return ranges

member_names_only #

member_names_only(categories: list[Union[str, ServiceCategory]]) -> list[str]

Ensure member names are passed to API as it is expected

Source code in pyfortinet/fmg_api/firewall/service.py
@field_serializer("category", when_used="unless-none")
def member_names_only(self, categories: list[Union[str, ServiceCategory]]) -> list[str]:
    """Ensure member names are passed to API as it is expected"""
    serialized = []
    if not categories:
        return []
    for category in categories:
        if isinstance(category, str):
            serialized.append(category)
            continue
        serialized.append(category.name)
    return serialized

portranges_to_string #

portranges_to_string(ranges: list[PortRange]) -> list[str]

Ensure portranges are passed to API as it is expected

input format is string as follows:
[dst_start-]dst_end:[src_start-]src_end

Examples:

513:512-1023 means: dst 500 and source range of 512-1023

Source code in pyfortinet/fmg_api/firewall/service.py
@field_serializer("udp_portrange", "tcp_portrange", "sctp_portrange", when_used="unless-none")
def portranges_to_string(ranges: list[PortRange]) -> list[str]:
    """Ensure portranges are passed to API as it is expected

        input format is string as follows:
        [dst_start-]dst_end:[src_start-]src_end

    Examples:
        513:512-1023 means: dst 500 and source range of 512-1023
    """
    serialized = []
    if not ranges:
        return []
    for rng in ranges:
        src = ""
        dst = ""

        if rng.source_start and rng.source_start == rng.source_end:
            src = rng.source_start
        elif rng.source_end:
            src = f"{rng.source_start}-{rng.source_end}" if rng.source_start else rng.source_end
        if rng.destination_start and rng.destination_start == rng.destination_end:
            dst = rng.destination_start
        elif rng.destination_end:
            dst = f"{rng.destination_start}-{rng.destination_end}" if rng.destination_start else rng.destination_end
        if src:
            serialized.append(f"{dst}:{src}")
        else:
            serialized.append(dst)
    return serialized

ServiceGroup #

Bases: FMGObject

Service group class

Attributes:

member_names_only #

member_names_only(members: list[Union[str, ServiceCustom, ServiceGroup]]) -> list[str]

Ensure member names are passed to API as it is expected

Source code in pyfortinet/fmg_api/firewall/service.py
@field_serializer("member", when_used="unless-none")
def member_names_only(self, members: list[Union[str, ServiceCustom, "ServiceGroup"]]) -> list[str]:
    """Ensure member names are passed to API as it is expected"""
    serialized = []
    for member in members:
        if isinstance(member, str):
            serialized.append(member)
            continue
        serialized.append(member.name)
    return serialized