Skip to main content

HFortix - Python SDK for Fortinet products (FortiOS, FortiManager, FortiAnalyzer)

Project description

Fortinet Python SDK

Python client library for Fortinet products including FortiOS, FortiManager, and FortiAnalyzer.

๐ŸŽฏ Current Status

  • CMDB API: 79 endpoints across 15 categories (52% coverage) โœ…
    • NEW: Firewall category with 28 endpoints (11 flat + 17 nested)
  • Service API: 21 methods across 3 modules โœ…
  • Log API: 42 methods across 5 modules (100% complete) โœ…
  • Monitor API: Not yet implemented โธ๏ธ

Latest Addition (v0.3.0):

  • โœ… Flat Firewall Endpoints (NEW - 11 endpoints):
    • firewall/DoS-policy, DoS-policy6 (DoS protection)
    • firewall/access-proxy, access-proxy6 (Reverse proxy/WAF)
    • firewall/access-proxy-ssh-client-cert (SSH certificates)
    • firewall/access-proxy-virtual-host (Virtual hosts)
    • firewall/address, address6 (IPv4/IPv6 addresses)
    • firewall/addrgrp, addrgrp6 (IPv4/IPv6 address groups)
    • firewall/address6-template (IPv6 address templates)
  • โœ… Firewall Sub-categories:
    • firewall.ipmacbinding (setting, table)
    • firewall.schedule (group, onetime, recurring)
    • firewall.service (category, custom, group)
    • firewall.shaper (per-ip-shaper, traffic-shaper)
    • firewall.ssh (host-key, local-ca, local-key, setting)
    • firewall.ssl (setting)
    • firewall.wildcard-fqdn (custom, group)

๐ŸŽฏ Features

  • Modular Architecture: Each product module can be used independently or together
  • Flexible Installation: Clone individual modules or the complete package
  • Comprehensive Exception Handling: 387+ FortiOS error codes with detailed descriptions
  • Type-Safe: Proper exception hierarchy and error handling
  • Well-Documented: Extensive API documentation and examples
  • Modern Python: Type hints, async support, PEP 585 compliance

๐Ÿ“ฆ Available Modules

Module Status Description
FortiOS ๐Ÿšง In Development FortiGate firewall management API
FortiManager โธ๏ธ Not Started Centralized management for FortiGate devices
FortiAnalyzer โธ๏ธ Not Started Log analysis and reporting platform

๐Ÿš€ Installation Options

Option 1: Complete Package (All Modules)

git clone https://github.com/hermanwjacobsen/hfortix.git
cd hfortix
pip install -e .

Option 2: FortiOS Only (Standalone)

git clone https://github.com/hermanwjacobsen/hfortix.git
cd hfortix/FortiOS
# Use FortiOS as standalone module

๐Ÿ“– Usage

Import from Complete Package

from fortinet import FortiOS, FortinetError, APIError

# Production with valid SSL certificate
fgt = FortiOS(
    host='fortigate.company.com',
    token='your-api-token',
    verify=True  # Recommended for production
)

# Development/Testing with self-signed certificate
fgt_dev = FortiOS(
    host='192.168.1.99',
    token='your-api-token',
    verify=False  # Only for dev/test environments
)

# Use the API
result = fgt.cmdb.firewall.address.list()

Import as Standalone Module

from FortiOS import FortiOS

# Production environment
fgt = FortiOS(
    host='fortigate.company.com',
    token='your-api-token',
    verify=True
)

# Development environment
fgt_dev = FortiOS(
    host='192.168.1.99',
    token='your-api-token',
    verify=False
)

Exception Handling

from fortinet import (
    FortiOS,
    APIError,
    ResourceNotFoundError,
    DuplicateEntryError
)

try:
    result = fgt.cmdb.firewall.address.create(
        name='test-address',
        subnet='10.0.0.0/24'
    )
except DuplicateEntryError as e:
    print(f"Address already exists: {e}")
except ResourceNotFoundError as e:
    print(f"Resource not found: {e}")
except APIError as e:
    print(f"API Error: {e.message}")
    print(f"HTTP Status: {e.http_status}")
    print(f"Error Code: {e.error_code}")

๐Ÿ—๏ธ Project Structure

fortinet/
โ”œโ”€โ”€ __init__.py              # Main package entry point
โ”œโ”€โ”€ exceptions.py            # Base exceptions for all products
โ”œโ”€โ”€ exceptions_forti.py      # FortiOS-specific error codes
โ”œโ”€โ”€ FortiOS/                 # FortiGate management
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ client.py
โ”‚   โ”œโ”€โ”€ exceptions.py        # Backward compatibility
โ”‚   โ””โ”€โ”€ api/                 # API endpoints
โ”‚       โ””โ”€โ”€ v2/
โ”‚           โ”œโ”€โ”€ cmdb/        # Configuration (firewall, system, etc.)
โ”‚           โ”œโ”€โ”€ monitor/     # Monitoring endpoints
โ”‚           โ”œโ”€โ”€ log/         # Log retrieval
โ”‚           โ””โ”€โ”€ service/     # Services (sniffer, security rating)
โ”œโ”€โ”€ FortiManager/            # Coming soon
โ”‚   โ””โ”€โ”€ __init__.py
โ””โ”€โ”€ FortiAnalyzer/           # Coming soon
    โ””โ”€โ”€ __init__.py

๐Ÿ” Module Discovery

Check which modules are available:

from fortinet import get_available_modules

modules = get_available_modules()
print(modules)
# {'FortiOS': True, 'FortiManager': False, 'FortiAnalyzer': False}

๐ŸŽ“ Examples

FortiOS - Firewall Address Management

from fortinet import FortiOS

fgt = FortiOS(host='192.168.1.99', token='your-token')

# List addresses
addresses = fgt.cmdb.firewall.address.list()

# Create address
result = fgt.cmdb.firewall.address.create(
    name='web-server',
    subnet='10.0.1.100/32',
    comment='Production web server'
)

# Update address
result = fgt.cmdb.firewall.address.update(
    name='web-server',
    comment='Updated comment'
)

# Delete address
result = fgt.cmdb.firewall.address.delete(name='web-server')

FortiOS - DoS Protection (NEW!)

# Create IPv4 DoS policy with simplified API
result = fgt.cmdb.firewall.dos_policy.create(
    policyid=1,
    name='protect-web-servers',
    interface='port3',              # Simple string format
    srcaddr=['all'],                # Simple list format
    dstaddr=['web-servers'],
    service=['HTTP', 'HTTPS'],
    status='enable',
    comments='Protect web farm from DoS attacks'
)

# API automatically converts to FortiGate format:
# interface='port3' โ†’ {'q_origin_key': 'port3'}
# service=['HTTP'] โ†’ [{'name': 'HTTP'}]

# Custom anomaly detection thresholds
result = fgt.cmdb.firewall.dos_policy.create(
    policyid=2,
    name='strict-dos-policy',
    interface='wan1',
    srcaddr=['all'],
    dstaddr=['all'],
    service=['ALL'],
    anomaly=[
        {'name': 'tcp_syn_flood', 'threshold': 500, 'action': 'block'},
        {'name': 'udp_flood', 'threshold': 1000, 'action': 'block'}
    ]
)

FortiOS - Reverse Proxy/WAF (NEW!)

# Create access proxy (requires VIP with type='access-proxy')
result = fgt.cmdb.firewall.access_proxy.create(
    name='web-proxy',
    vip='web-vip',                    # VIP must be type='access-proxy'
    auth_portal='enable',
    log_blocked_traffic='enable',
    http_supported_max_version='2.0',
    svr_pool_multiplex='enable'
)

# Create virtual host with simplified API
result = fgt.cmdb.firewall.access_proxy_virtual_host.create(
    name='api-vhost',
    host='*.api.example.com',
    host_type='wildcard',
    ssl_certificate='Fortinet_Factory'  # String auto-converts to list
)

# API automatically converts:
# ssl_certificate='cert' โ†’ [{'name': 'cert'}]

FortiOS - Address & Address Group Management (NEW!)

# Create IPv4 address (subnet)
result = fgt.cmdb.firewall.address.create(
    name='internal-net',
    type='ipmask',
    subnet='192.168.1.0/24',
    comment='Internal network'
)

# Create IPv4 address (IP range)
result = fgt.cmdb.firewall.address.create(
    name='dhcp-range',
    type='iprange',
    start_ip='192.168.1.100',
    end_ip='192.168.1.200'
)

# Create IPv4 address (FQDN)
result = fgt.cmdb.firewall.address.create(
    name='google-dns',
    type='fqdn',
    fqdn='dns.google.com'
)

# Create IPv6 address
result = fgt.cmdb.firewall.address6.create(
    name='ipv6-internal',
    type='ipprefix',
    ip6='2001:db8::/32',
    comment='IPv6 internal network'
)

# Create address group with simplified API
result = fgt.cmdb.firewall.addrgrp.create(
    name='internal-networks',
    member=['subnet1', 'subnet2', 'subnet3'],  # Simple string list!
    comment='All internal networks'
)

# API automatically converts:
# member=['addr1', 'addr2'] โ†’ [{'name': 'addr1'}, {'name': 'addr2'}]

# Create IPv6 address group
result = fgt.cmdb.firewall.addrgrp6.create(
    name='ipv6-internal-networks',
    member=['ipv6-subnet1', 'ipv6-subnet2'],
    comment='All internal IPv6 networks'
)

# Create IPv6 address template
result = fgt.cmdb.firewall.address6_template.create(
    name='ipv6-subnet-template',
    ip6='2001:db8::/32',
    subnet_segment_count=2,
    comment='IPv6 subnet template'
)

FortiOS - Schedule Management

# Create recurring schedule
result = fgt.cmdb.firewall.schedule.recurring.create(
    name='business-hours',
    day=['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
    start='08:00',
    end='18:00'
)

# Create one-time schedule
from datetime import datetime, timedelta
tomorrow = datetime.now() + timedelta(days=1)
start = f"09:00 {tomorrow.strftime('%Y/%m/%d')}"
end = f"17:00 {tomorrow.strftime('%Y/%m/%d')}"

result = fgt.cmdb.firewall.schedule.onetime.create(
    name='maintenance-window',
    start=start,
    end=end,
    color=5
)

Exception Hierarchy

Exception
โ””โ”€โ”€ FortinetError (base)
    โ”œโ”€โ”€ AuthenticationError
    โ”œโ”€โ”€ AuthorizationError
    โ””โ”€โ”€ APIError
        โ”œโ”€โ”€ ResourceNotFoundError (404)
        โ”œโ”€โ”€ BadRequestError (400)
        โ”œโ”€โ”€ MethodNotAllowedError (405)
        โ”œโ”€โ”€ RateLimitError (429)
        โ”œโ”€โ”€ ServerError (500)
        โ”œโ”€โ”€ DuplicateEntryError (-5, -15, -100)
        โ”œโ”€โ”€ EntryInUseError (-23, -94, -95)
        โ”œโ”€โ”€ InvalidValueError (-651, -1, -50)
        โ””โ”€โ”€ PermissionDeniedError (-14, -37)

๐Ÿงช Testing

Each module includes comprehensive tests:

# Run FortiOS tests (requires FortiGate access)
cd FortiOS/Tests
python3 test_exceptions.py
python3 cmdb/firewall/address.py

๐Ÿ“ Version

Current version: 0.1.0

from fortinet import get_version
print(get_version())  # '0.1.0'

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests
  5. Submit a pull request

๐Ÿ“„ License

[Your License Here]

๐Ÿ”— Links

๐Ÿ’ก Tips

  • Use API Tokens: Only token-based authentication is supported for FortiOS REST API
  • Error Handling: Always catch specific exceptions for better error handling
  • Verify SSL: Set verify=True in production (requires valid certificates)
  • Rate Limiting: Be aware of API rate limits (HTTP 429 errors)

โš™๏ธ Configuration

Environment Variables

export FGT_HOST="192.168.1.99"
export FGT_TOKEN="your-api-token"
export FGT_VERIFY_SSL="false"

Using .env File

from dotenv import load_dotenv
import os

load_dotenv()

fgt = FortiOS(
    host=os.getenv('FGT_HOST'),
    token=os.getenv('FGT_TOKEN'),
    verify=os.getenv('FGT_VERIFY_SSL', 'false').lower() == 'true'
)

๐ŸŽฏ Roadmap

  • [๐Ÿšง] FortiOS API implementation (In Development)
    • Exception handling system (387 error codes)
    • Base client architecture
    • [๐Ÿ”ท] CMDB endpoints (Beta - partial coverage)
      • Firewall (address, policy, service, etc.)
      • System (interface, admin, global, etc.)
      • Router (static, policy, etc.)
      • VPN (IPsec, SSL, etc.)
    • [๐Ÿ”ท] Service endpoints (Beta)
      • Sniffer, Security Rating, etc.
    • [๐Ÿ”ท] Log endpoints (Beta)
      • Traffic, Event, Virus, etc.
    • Monitor endpoints (Not Started)
    • Complete API coverage
  • Modular package architecture
  • FortiManager module (Not Started)
  • FortiAnalyzer module (Not Started)
  • PyPI package publication
  • Async support
  • CLI tool

๐Ÿ‘ค Author

Herman W. Jacobsen


Built with โค๏ธ for the Fortinet community

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hfortix-0.3.0.tar.gz (121.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

hfortix-0.3.0-py3-none-any.whl (222.1 kB view details)

Uploaded Python 3

File details

Details for the file hfortix-0.3.0.tar.gz.

File metadata

  • Download URL: hfortix-0.3.0.tar.gz
  • Upload date:
  • Size: 121.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for hfortix-0.3.0.tar.gz
Algorithm Hash digest
SHA256 9878221cdffde49e3cc3a2fb5ba94ddafd2f9bed28a75bafa1cc54a8f7b50bb8
MD5 7d69219cfb7187c6ef367da21746b487
BLAKE2b-256 5048bff2e3f06eb85ab7c78f765fe8e048a86c80fcbe4b309f4268374c91af02

See more details on using hashes here.

File details

Details for the file hfortix-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: hfortix-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 222.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for hfortix-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 42a7cb88e086b7039f70ecfc1d3ccb833bc23add00f1b59bfc16cb67c376cebb
MD5 6b6b1d1ce28640a86c85b2a57c6de87c
BLAKE2b-256 5a52000462018f111def6a3ff8f475e6879ac6545882725e2901064bed02a9d1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page