Skip to main content
Glama
README.md
# OPNsense API Client

A comprehensive Python client providing **100% coverage of all OPNsense Core APIs**.

**Version:** 0.9.0
**Total Coverage:** 582 SDK endpoints + 102 MCP tools across 22 API modules
**Core API Coverage:** ✅ 100% Complete
**MCP Server:** ✅ Complete firewall automation + OpenVPN client package generator for AI agents

This SDK provides complete programmatic access to all OPNsense core functionality including VPN services, firewall management, network services, security features, traffic shaping, and system administration. Now includes professional OpenVPN client package generator following industry best practices.

## APIs Implemented

### OpenVPN API (40 endpoints) ✅ 100% Complete
Complete OpenVPN management including instances, client overwrites, export, and service control.

**Based on:** https://docs.opnsense.org/development/api/core/openvpn.html

**Controllers:**
- **ClientOverwritesController** (8 endpoints) - Client-specific configuration overrides
- **ExportController** (11 endpoints) - VPN configuration export and templates
- **InstancesController** (11 endpoints) - OpenVPN instance management
- **ServiceController** (10 endpoints) - Service control and session management

### Auth API (21 endpoints) ✅ 100% Complete
User, group, and privilege management.

**Based on:** https://docs.opnsense.org/development/api/core/auth.html

**Controllers:**
- **GroupController** (8 endpoints) - User group management
- **PrivController** (8 endpoints) - Privilege management
- **UserController** (5 endpoints) - User account management

### Firewall API (96 endpoints) ✅ 100% Complete
Complete firewall rule management, NAT, aliases, and organization.

**Based on:** https://docs.opnsense.org/development/api/core/firewall.html

**Controllers:**
- **FilterController** (21 endpoints) - Firewall rule management
- **FilterUtilController** (1 endpoint) - Firewall utilities and statistics
- **AliasController** (18 endpoints) - IP/port alias management
- **AliasUtilController** (7 endpoints) - Runtime alias operations
- **MigrationController** (2 endpoints) - Legacy rule migration
- **DNatController** (8 endpoints) - Port forwarding / Destination NAT
- **SourceNatController** (8 endpoints) - Outbound NAT
- **OneToOneController** (8 endpoints) - 1:1 NAT
- **NptController** (8 endpoints) - IPv6 Network Prefix Translation
- **CategoryController** (7 endpoints) - Rule categories
- **GroupController** (8 endpoints) - Rule groups

### Diagnostics API (91 endpoints) ✅ 100% Complete
Comprehensive system diagnostics, network tools, and monitoring.

**Based on:** https://docs.opnsense.org/development/api/core/diagnostics.html

**Controllers:**
- **FirewallController** (6 endpoints) - Firewall logs and state tables
- **InterfaceController** (7 endpoints) - Interface diagnostics and routing
- **SystemController** (2 endpoints) - System information and resources
- **ActivityController** (1 endpoint) - System activity monitoring
- **NetworkInsightController** (6 endpoints) - Advanced network analytics
- **CpuUsageController** (1 endpoint) - CPU usage statistics
- **DnsController** (2 endpoints) - DNS lookup utilities
- **DnsDiagnosticsController** (4 endpoints) - Advanced DNS queries
- **LvtemplateController** (6 endpoints) - Log view templates
- **NetflowController** (8 endpoints) - Netflow configuration
- **PacketCaptureController** (8 endpoints) - Packet capture management
- **PingController** (1 endpoint) - ICMP ping utility
- **PortprobeController** (1 endpoint) - Port connectivity testing
- **SystemhealthController** (4 endpoints) - System health metrics
- **TracerouteController** (1 endpoint) - Network trace utility
- **TrafficController** (6 endpoints) - Traffic monitoring and graphs

### Interfaces API (82 endpoints) ✅ 100% Complete
Complete network interface management including VLANs, bridges, tunnels, and VIPs.

**Based on:** https://docs.opnsense.org/development/api/core/interfaces.html

**Controllers:**
- **OverviewController** (5 endpoints) - Interface overview and status
- **BridgeSettingsController** (8 endpoints) - Network bridge management
- **VlanSettingsController** (8 endpoints) - VLAN interface management
- **LaggSettingsController** (8 endpoints) - Link aggregation (LACP)
- **LoopbackSettingsController** (8 endpoints) - Loopback interfaces
- **VipSettingsController** (9 endpoints) - Virtual IPs (CARP, Proxy ARP, Alias)
- **VxlanSettingsController** (8 endpoints) - VXLAN tunnels
- **GifSettingsController** (9 endpoints) - GIF tunnels
- **GreSettingsController** (9 endpoints) - GRE tunnels
- **NeighborSettingsController** (8 endpoints) - Static ARP/NDP entries
- **SettingsController** (2 endpoints) - Global interface settings

### IPSec VPN Module (21 endpoints) ✅ 100% Complete
Complete IPSec VPN tunnel management including Phase 1/2 configuration, connections, and leases.

**Based on:** https://docs.opnsense.org/development/api/core/ipsec.html

**Controllers:**
- **ConnectionsController** (8 endpoints) - IPSec connection management
- **LeasesController** (3 endpoints) - Address lease tracking
- **SessionsController** (2 endpoints) - Active session management
- **TunnelController** (8 endpoints) - Phase 1 and Phase 2 tunnel configuration

### WireGuard VPN Module (20 endpoints) ✅ 100% Complete
Modern WireGuard VPN server and client/peer management.

**Based on:** https://docs.opnsense.org/development/api/plugins/wireguard.html

**Controllers:**
- **ClientController** (8 endpoints) - WireGuard client/peer management
- **ServerController** (8 endpoints) - WireGuard server/interface management
- **ServiceController** (4 endpoints) - Service control

### Unbound DNS Module (50 endpoints) ✅ 100% Complete
Complete DNS resolver with host/domain overrides, forwarding, DNSSEC, and DNS over TLS.

**Based on:** https://docs.opnsense.org/development/api/core/unbound.html

**Controllers:**
- **ServiceController** (10 endpoints) - DNS resolver service and cache management
- **SettingsController** (8 endpoints) - Resolver configuration and ACLs
- **OverrideController** (8 endpoints) - DNS host overrides
- **DomainController** (8 endpoints) - DNS domain overrides
- **ForwardController** (8 endpoints) - DNS forwarding configuration
- **DotController** (8 endpoints) - DNS over TLS management

### Kea DHCP Module (34 endpoints) ✅ 100% Complete
Modern Kea DHCP server for both IPv4 and IPv6 with subnet and reservation management.

**Based on:** https://docs.opnsense.org/development/api/plugins/kea.html

**Controllers:**
- **Dhcpv4Controller** (12 endpoints) - IPv4 DHCP server configuration
- **Dhcpv6Controller** (12 endpoints) - IPv6 DHCP server configuration
- **LeasesController** (6 endpoints) - DHCP lease management (v4 and v6)
- **ServiceController** (4 endpoints) - Service management

### Routing Module (13 endpoints) ✅ 100% Complete
Static route and gateway management.

**Based on:** https://docs.opnsense.org/development/api/core/routes.html

**Controllers:**
- **RoutesController** (5 endpoints) - Static route management
- **SettingsController** (8 endpoints) - Gateway and routing configuration

### IDS/IPS (Suricata) Module (15 endpoints) ✅ 100% Complete
Intrusion detection and prevention system configuration.

**Based on:** https://docs.opnsense.org/development/api/core/ids.html

**Controllers:**
- **SettingsController** (8 endpoints) - User-defined IDS rules
- **ServiceController** (7 endpoints) - IDS service and signature updates

### Traffic Shaper Module (25 endpoints) ✅ 100% Complete
Quality of Service (QoS) traffic shaping with pipes, queues, and rules.

**Based on:** https://docs.opnsense.org/development/api/core/trafficshaper.html

**Controllers:**
- **PipeController** (6 endpoints) - Traffic shaper pipe management
- **QueueController** (6 endpoints) - Queue management
- **RuleController** (6 endpoints) - Traffic shaping rules
- **SettingsController** (3 endpoints) - Global configuration

### Captive Portal Module (8 endpoints) ✅ 100% Complete
Guest network authentication and access control.

**Based on:** https://docs.opnsense.org/development/api/core/captiveportal.html

**Controllers:**
- **AccessController** (3 endpoints) - User authentication
- **ServiceController** (5 endpoints) - Session management

### System Service Modules ✅ 100% Complete

**NTPD (Network Time Protocol) - 3 endpoints**
- ServiceController: reconfigure, restart, status

**Syslog (System Logging) - 3 endpoints**
- SettingsController: get, set, reconfigure

**Monit (Service Monitoring) - 5 endpoints**
- SettingsController: get, set
- ServiceController: reconfigure, restart, status

**RADVD (IPv6 Router Advertisement) - 5 endpoints**
- SettingsController: get, set
- ServiceController: reconfigure, restart, status

**DHCP Relay - 3 endpoints**
- SettingsController: get, set, reconfigure

**DNSMasq (DNS Forwarder) - 6 endpoints**
- SettingsController: get, set
- ServiceController: reconfigure, restart, status

**Cron (Task Scheduler) - 4 endpoints**
- SettingsController: get, set
- ServiceController: reconfigure, restart

**Firmware (Update Management) - 3 endpoints**
- InfoController: status, check, info

**Trust (Certificate Management) - 25 endpoints** ✅ Complete
- **CertController** (10 endpoints): search, get, upload, raw_dump, user_list, generate_file, ca_info, ca_list, add, set, del_cert
- **CaController** (9 endpoints): raw_dump, ca_list, ca_info, generate_file, search, get, add, set, del_ca
- **CrlController** (6 endpoints): get, raw_dump, search, set, del_crl, get_ocsp_info_data
- **SettingsController** (3 endpoints): get, set, reconfigure

**Host Discovery (Network Scanning) - 2 endpoints**
- ServiceController: scan, status

## Installation

### From Source

```bash
git clone https://github.com/benashby/opnsense-sdk.git
cd opnsense-sdk
pip install -e .
```

For development (linting, build tooling), install the extras:

```bash
pip install -e ".[dev]"
```

The MCP server has its own optional extra:

```bash
pip install -e ".[mcp]"
```

## Version

**Current Version**: 0.11.0

See [CHANGELOG.md](CHANGELOG.md) for release history.

## Quick Examples

### Check Firewall Rules
```python
from opnsense_client import FirewallAPI

firewall = FirewallAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)
rules = firewall.filter.search_rule({'searchPhrase': 'OpenVPN'})
print(rules)
```

### Get Public IP Address
```python
from opnsense_client import InterfacesAPI

ifaces = InterfacesAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)
info = ifaces.overview.interfaces_info()

# Find WAN interface
for iface in info.get('interfaces', []):
    if iface.get('identifier') == 'wan':
        print(f"Public IP: {iface.get('ipaddr')}")
```

### View Firewall Logs
```python
from opnsense_client import DiagnosticsAPI

diag = DiagnosticsAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)
logs = diag.firewall.log({'limit': 50})

for entry in logs.get('rows', []):
    if entry.get('action') == 'block':
        print(f"Blocked: {entry.get('src')} -> {entry.get('dst')}")
```

### Check Active Firewall States
```python
from opnsense_client import DiagnosticsAPI

diag = DiagnosticsAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)
states = diag.firewall.query_states()
print(f"Active connections: {len(states.get('rows', []))}")
```

### OpenVPN Management
```python
from opnsense_client import OpenVPNAPI

vpn = OpenVPNAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)
sessions = vpn.service.search_sessions()
print(f"Active VPN sessions: {sessions}")
```

### Generate OpenVPN Client Package
```python
from opnsense_client import OpenVPNAPI, TrustAPI, InterfacesAPI
from opnsense_client.ovpn_packager import OVPNPackager

# Initialize APIs
openvpn = OpenVPNAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)
trust = TrustAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)
interfaces = InterfacesAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)

# List available server addresses
ifaces = interfaces.overview.get_interface()
for iface in ifaces.get('rows', []):
    if iface.get('addr4'):
        ip = iface.get('addr4').split('/')[0]
        print(f"{iface.get('identifier')}: {ip}")

# Generate complete client package
packager = OVPNPackager(openvpn, trust)
zip_path = packager.create_client_package(
    instance_uuid="abc-123-def",          # OpenVPN instance UUID
    cert_uuid="456-xyz",                  # Client certificate UUID
    server_address="203.0.113.5",         # Choose appropriate IP from above
    client_name="john-laptop"
)

print(f"Client package created: {zip_path}")
# Returns: /tmp/opnsense-vpn-john-laptop-20260130-143022.zip
#
# Package contains:
# - client.ovpn (configuration file)
# - ca.crt (CA certificate)
# - client.crt (client certificate)
# - client.key (client private key)
# - ta.key (TLS auth key, if configured)
# - README.txt (connection instructions for all platforms)
```

### Port Forwarding (DNAT)
```python
from opnsense_client import FirewallAPI

fw = FirewallAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)

# Forward external HTTPS to internal web server
rule_data = {
    "rule": {
        "enabled": "1",
        "interface": "wan",
        "protocol": "tcp",
        "destination_port": "443",
        "target": "192.168.1.10",  # Internal web server
        "description": "Web server HTTPS"
    }
}

result = fw.dnat.add_rule(rule_data)
print(f"Created port forward: {result['uuid']}")

# Apply changes
fw.filter.apply()
```

### Outbound NAT (SNAT)
```python
from opnsense_client import FirewallAPI

fw = FirewallAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)

# Route DMZ network through secondary WAN
rule_data = {
    "rule": {
        "enabled": "1",
        "interface": "wan2",
        "source": "10.0.0.0/24",  # DMZ network
        "destination": "any",
        "description": "DMZ via WAN2"
    }
}

result = fw.source_nat.add_rule(rule_data)
print(f"Created outbound NAT: {result['uuid']}")

# Apply changes
fw.filter.apply()
```

### 1:1 NAT for Dedicated Public IP
```python
from opnsense_client import FirewallAPI

fw = FirewallAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)

# Map public IP to internal server
rule_data = {
    "rule": {
        "enabled": "1",
        "interface": "wan",
        "external": "203.0.113.50",  # Public IP
        "source": "192.168.1.100",   # Internal server
        "destination": "any",
        "description": "Dedicated IP for web server"
    }
}

result = fw.one_to_one.add_rule(rule_data)
print(f"Created 1:1 NAT: {result['uuid']}")

# Apply changes
fw.filter.apply()
```

### Firewall Configuration Backup
```python
from opnsense_client import FirewallAPI
import json

fw = FirewallAPI('https://opnsense.local', 'key', 'secret', verify_ssl=False)

# Backup all aliases
alias_backup = fw.alias.export()
with open('alias_backup.json', 'w') as f:
    json.dump(alias_backup, f, indent=2)

# Backup filter rules
filter_backup = fw.filter.download_rules()
with open('filter_backup.json', 'w') as f:
    json.dump(filter_backup, f, indent=2)

print("Configuration backed up successfully")

# To restore later:
# with open('alias_backup.json') as f:
#     fw.alias.import_data(json.load(f))
# fw.alias.reconfigure()
```

## Available Controllers (OpenVPN)

1. **ClientOverwritesController** - Manage client-specific overwrites
2. **ExportController** - Export VPN configurations
3. **InstancesController** - Manage OpenVPN instances
4. **ServiceController** - Control OpenVPN service

### Endpoints

#### ClientOverwritesController
- `POST /api/openvpn/client_overwrites/add` - Add client overwrite
- `POST /api/openvpn/client_overwrites/del/{uuid}` - Delete client overwrite
- `GET /api/openvpn/client_overwrites/get/{uuid}` - Get client overwrite
- `GET|POST /api/openvpn/client_overwrites/search` - Search client overwrites
- `POST /api/openvpn/client_overwrites/set/{uuid}` - Update client overwrite
- `POST /api/openvpn/client_overwrites/toggle/{uuid}` - Toggle client overwrite

#### ExportController
- `GET /api/openvpn/export/accounts/{vpnid}` - Get accounts
- `POST /api/openvpn/export/download/{vpnid}/{certref}` - Download config
- `GET /api/openvpn/export/providers` - Get providers
- `POST /api/openvpn/export/store_presets/{vpnid}` - Store presets
- `GET /api/openvpn/export/templates` - Get templates
- `POST /api/openvpn/export/validate_presets/{vpnid}` - Validate presets

#### InstancesController
- `POST /api/openvpn/instances/add` - Add instance
- `POST /api/openvpn/instances/add_static_key` - Add static key
- `POST /api/openvpn/instances/del/{uuid}` - Delete instance
- `GET /api/openvpn/instances/gen_key/{type}` - Generate key
- `POST /api/openvpn/instances/set/{uuid}` - Update instance
- `POST /api/openvpn/instances/toggle/{uuid}` - Toggle instance

#### ServiceController
- `POST /api/openvpn/service/kill_session` - Kill session
- `POST /api/openvpn/service/reconfigure` - Reconfigure service
- `POST /api/openvpn/service/restart_service/{id}` - Restart service
- `GET /api/openvpn/service/search_routes` - Search routes
- `GET /api/openvpn/service/search_sessions` - Search sessions

## Setup

1. Install dependencies:
```bash
pip install -r requirements.txt
```

2. Configure your OPNsense credentials in `.env`:
```bash
cp .env.example .env
# Edit .env with your credentials
```

3. Run the example:
```bash
python examples/basic_usage.py
```

## Verify OpenVPN Firewall Configuration

Use the included verification script to check your OpenVPN firewall setup:

```bash
export OPNSENSE_HOST='https://your-opnsense.local'
export OPNSENSE_API_KEY='your-api-key'
export OPNSENSE_API_SECRET='your-api-secret'
export OPENVPN_PORT='1194'  # Optional, defaults to 1194
python examples/verify_openvpn_firewall.py
```

This script will:
- ✓ Search for firewall rules matching your OpenVPN port
- ✓ Display your WAN public IP address
- ✓ Check firewall logs for blocked traffic
- ✓ Show active OpenVPN connections
- ✓ Display routing table with OpenVPN routes

## Authentication

OPNsense API uses API key + secret authentication. You need to:
1. Create an API key in OPNsense: System → Access → Users → Edit → API Keys
2. Set the API key and secret in your `.env` file or environment variables