Skip to content

init

Public firewall classes and backwards-compatible explicit type imports.

ADDRESS_GROUP_CATEGORY module-attribute #

ADDRESS_GROUP_CATEGORY = Literal['default', 'ztna-ems-tag', 'ztna-geo-tag']

ADDRESS_GROUP_TYPE module-attribute #

ADDRESS_GROUP_TYPE = Literal['default', 'array', 'folder']

ADDRESS_TYPE module-attribute #

ADDRESS_TYPE = Literal[
    "ipmask",
    "iprange",
    "fqdn",
    "wildcard",
    "geography",
    "url",
    "wildcard-fqdn",
    "nsx",
    "aws",
    "dynamic",
    "interface-subnet",
    "mac",
    "fqdn-group",
]

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']

CLEARPASS_SPT module-attribute #

CLEARPASS_SPT = Literal['unknown', 'healthy', 'quarantine', 'checkup', 'transition', 'infected', 'transient']

DIRTY module-attribute #

DIRTY = Literal['dirty', 'clean']

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",
]

OBJ_TYPE module-attribute #

OBJ_TYPE = Literal['ip', 'mac']

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"
]

SDN_ADDR_TYPE module-attribute #

SDN_ADDR_TYPE = Literal['private', 'public', 'all']

SUB_TYPE module-attribute #

SUB_TYPE = Literal[
    "sdn", "clearpass-spt", "fsso", "ems-tag", "swc-tag", "fortivoice-tag", "fortinac-tag", "fortipolicy-tag"
]

__all__ module-attribute #

__all__ = [
    "Address",
    "AddressGroup",
    "AddressTagging",
    "IPPool",
    "IPPoolDynamicMapping",
    "IPPoolGroup",
    "InternetService",
    "PortRange",
    "ProfileGroup",
    "ProxyAddress",
    "ProxyAddressGroup",
    "ProxyAddressGroupTagging",
    "ProxyAddressHeaderGroup",
    "ProxyAddressTagging",
    "Scope",
    "ServiceCategory",
    "ServiceCustom",
    "ServiceGroup",
    "VIP",
    "VIPDynamicMapping",
]

Address #

Bases: FMGObject

Address class for high-level operations

Attributes:

Name Type Description
name str

object name

allow_routing str

Defines whether the use of this address in the static route configuration is enabled or disabled, with possible values being 'disable' or 'enable'.

associated_interface str | list[str]

object assigned to interface/zone name

subnet str | list[str]

subnet in x.x.x.x/x or [x.x.x.x, y.y.y.y] format

cache_ttl int

Defines the minimal TTL (Time To Live) of individual IP addresses in FQDN cache measured in seconds.

clearpass_spt str

Represents the SPT (System Posture Token) value, indicating system status. Possible values include 'healthy', 'quarantine', 'transition', etc.

color int

color code for the address object icon on the GUI.

comment str

comment for the address object.

country str

IP addresses associated to a specific country.

dirty str

Indicates whether the address is to be deleted; possible values 'dirty' or 'clean'.

end_ip str

The final IP address (inclusive) in the range for the address.

epg_name str

endpoint group name.

fabric_object str

Indicates the Security Fabric global object setting, with possible values being 'disable' or 'enable'.

filter str

Match criteria filter.

fqdn str

Fully Qualified Domain Name address.

fsso_group list[str]

A list of FSSO group(s).

interface str

Name of interface whose IP address is to be used.

list list[AddressList]

List (TODO: figure out, docs don't help)

macaddr list[str]

Multiple MAC address ranges.

node_ip_only str

Defines whether only the collection of node addresses in Kubernetes is enabled or disabled. Possible values are 'disable' or 'enable'.

obj_id str

Object ID for NSX.

obj_tag str

Tag of dynamic address object.

obj_type str

type of the object (IP, MAC)

organization str

Organization domain name (Syntax: organization/domain).

policy_group str

policy group name.

sdn str

SDN.

sdn_addr_type str

Type of addresses to collect.

sdn_tag str

SDN tag.

start_ip str

First IP address (inclusive) in the range for the address.

sub_type str

Indicates the sub-type of address. Possible values include 'sdn', 'clearpass-spt', 'fsso', etc.

subnet_name str

Subnet name.

tag_detection_level str

Tag detection level of dynamic address object.

tag_type str

Tag type of dynamic address object.

tagging list[AddressTagging]

tagging details for this address.

tenant str

tenant related to this address.

type str

Indicates the type of address. Possible values include 'ipmask', 'iprange', 'fqdn', etc.

uuid str

Contains the Universally Unique Identifier (UUID; automatically assigned but can be manually reset).

wildcard str

This is the IP address and wildcard netmask.

wildcard_fqdn str

Contains a Fully Qualified Domain Name with wildcard characters.

global_object int

global object related to this address.

mapping__scope list[dict, Scope]

the mapping scope for this address.

standardize_assoc_iface #

standardize_assoc_iface(v)

validator: FMG sends a list with a single element, replace with single element

Source code in pyfortinet/fmg_api/firewall/address.py
@field_validator("associated_interface")
def standardize_assoc_iface(cls, v):
    """validator: FMG sends a list with a single element, replace with single element"""
    if isinstance(v, list):
        return first(v, None)
    else:
        return v

standardize_subnet #

standardize_subnet(v)

validator: x.x.x.x/y.y.y.y -> x.x.x.x/y

API use this list form: ["1.2.3.4", "255.255.255.0"] Human use this form: "1.2.3.4/24"

Source code in pyfortinet/fmg_api/firewall/address.py
@field_validator("subnet")
def standardize_subnet(cls, v):
    """validator: x.x.x.x/y.y.y.y -> x.x.x.x/y

    API use this list form: ["1.2.3.4", "255.255.255.0"]
    Human use this form: "1.2.3.4/24"
    """
    if isinstance(v, list):
        return IPv4Interface("/".join(v)).compressed
    else:
        return IPv4Interface(v).compressed

validate_wildcard #

validate_wildcard(v) -> str

Ensure wildcard address definition is correct (x.x.x.x y.y.y.y)

Source code in pyfortinet/fmg_api/firewall/address.py
@field_validator("wildcard", mode="before")
def validate_wildcard(cls, v) -> str:
    """Ensure wildcard address definition is correct (x.x.x.x y.y.y.y)"""
    if isinstance(v, list):
        return " ".join(IPv4Address(part).compressed for part in v)
    else:  # string
        return " ".join(IPv4Address(part).compressed for part in v.split())

AddressGroup #

Bases: FMGObject

member_names_only #

member_names_only(members: list[Union[str, Address, AddressGroup]]) -> list[str]

Ensure member names are passed to API as it is expected

Source code in pyfortinet/fmg_api/firewall/address.py
@field_serializer("member", "exclude_member", when_used="unless-none")
def member_names_only(self, members: builtins.list[Union[str, Address, "AddressGroup"]]) -> builtins.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

AddressTagging #

Bases: BaseModel

IPPool #

Bases: FMGObject

Fields for pm.config.firewall.ippool; omitted values are not written.

IPPoolDynamicMapping #

Bases: BaseModel

Fields for pm.config.firewall.ippool.dynamic_mapping; omitted values are not written.

IPPoolGroup #

Bases: FMGObject

Fields for pm.config.firewall.ippool_grp; omitted values are not written.

InternetService #

Bases: FMGObject

Fields for pm.config.firewall.internet-service; omitted values are not written.

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

ProfileGroup #

Bases: FMGObject

Service group class

Attributes:

Name Type Description
application_list Optional[str]

Name of an existing Application list.

av_profile Optional[str]

Name of an existing Antivirus profile.

dlp_profile Optional[str]

Name of an existing DLP profile.

dnsfilter_profile Optional[str]

Name of an existing DNS filter profile.

emailfilter_profile Optional[str]

Name of an existing email filter profile.

file_filter_profile Optional[str]

Name of an existing file_filter profile.

icap_profile Optional[str]

Name of an existing ICAP profile.

ips_sensor Optional[str]

Name of an existing IPS sensor.

ips_voip_filter Optional[str]

Name of an existing VoIP (ips) profile.

name Optional[str]

Profile group name.

profile_protocol_options Optional[str]

Name of an existing Protocol options profile.

sctp_filter_profile Optional[str]

Name of an existing SCTP filter profile.

ssh_filter_profile Optional[str]

Name of an existing SSH filter profile.

ssl_ssh_profile Optional[str]

Name of an existing SSL SSH profile.

videofilter_profile Optional[str]

Name of an existing VideoFilter profile.

voip_profile Optional[str]

Name of an existing VoIP (voipd) profile.

waf_profile Optional[str]

Name of an existing Web application firewall profile.

webfilter_profile Optional[str]

Name of an existing Web filter profile.

ProxyAddress #

Bases: FMGObject

Fields for pm.config.firewall.proxy-address; omitted values are not written.

ProxyAddressGroup #

Bases: FMGObject

Fields for pm.config.firewall.proxy-addrgrp; omitted values are not written.

ProxyAddressGroupTagging #

Bases: BaseModel

Fields for pm.config.firewall.proxy-addrgrp.tagging; omitted values are not written.

ProxyAddressHeaderGroup #

Bases: BaseModel

Fields for pm.config.firewall.proxy-address.header-group; omitted values are not written.

ProxyAddressTagging #

Bases: BaseModel

Fields for pm.config.firewall.proxy-address.tagging; omitted values are not written.

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

VIP #

Bases: FMGObject

Fields for pm.config.firewall.vip; omitted values are not written.

VIPDynamicMapping #

Bases: BaseModel

Fields for pm.config.firewall.vip.dynamic_mapping; omitted values are not written.