Skip to content
المشاريع

حول

UniFi Gateway emulator for third-party routers

الألعاب والمحاكاة

كيف تُقاس هذه الأرقام

النمو المقاس للنجوم

خلال 24 ساعة
٠
خلال 7 أيام
+١
خلال 15 يومًا
+٥
خلال شهر
+١٠

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

UniFi Gateway Emulator Build & Release

A Python 3 daemon that emulates a Ubiquiti UniFi Gateway (UGW3) to a UniFi Controller. This allows non-Ubiquiti routers (OpenWRT, OPNSense, pfSense, or any Linux/FreeBSD router) to appear in the UniFi Controller UI and report network statistics.

How It Works

The daemon runs alongside your non-Ubiquiti router and periodically sends "inform" packets to your UniFi Controller — the same binary protocol that real UniFi devices use. The controller sees a UGW3 gateway and displays its stats (interfaces, traffic, connected clients, routes, etc.) in the dashboard.

Your UniFi APs, switches, and other devices continue connecting to the controller normally. This project fills the "gateway" slot so the controller has a complete view of your network topology.

┌──────────────────┐     inform (HTTP POST)     ┌───────────────────┐
│  This Daemon     │ ─────────────────────────► │  UniFi Controller │
│  (emulates UGW3) │                            │                   │
└────────┬─────────┘                            │  Sees complete    │
         │ reads stats from                     │  network topology │
┌────────▼─────────┐                            │                   │
│  Your Router     │     UniFi APs/Switches ──► │                   │
│  (OPNSense/etc)  │     also inform normally   └───────────────────┘
└──────────────────┘

Requirements

  • A running UniFi Controller (self-hosted or Cloud Key)
  • Network access from the daemon to the controller's /inform endpoint

Installation

Debian / Ubuntu (apt)

curl -fsSL https://amd989.github.io/unifi-gateway/setup-apt.sh | sudo bash
sudo apt install unifi-gateway

RHEL / Rocky / Fedora (dnf)

curl -fsSL https://amd989.github.io/unifi-gateway/setup-rpm.sh | sudo bash
sudo dnf install unifi-gateway

OpenWRT

The OpenWRT packages ship pure Python source and depend on python3, python3-psutil, and python3-pycryptodome from the OpenWRT feeds — keeping the package tiny for flash-constrained devices.

# Auto-detects apk (25.12+) or opkg (older)
curl -fsSL https://amd989.github.io/unifi-gateway/setup-openwrt.sh | sh

Then install with whichever package manager your version uses:

# OpenWRT 25.12+ (apk)
apk add unifi-gateway

# OpenWRT pre-25.12 (opkg)
opkg install unifi-gateway

FreeBSD / OPNSense / pfSense (pkg)

curl -fsSL https://amd989.github.io/unifi-gateway/setup-pkg.sh | sudo sh
sudo pkg install unifi-gateway

Docker

docker pull ghcr.io/amd989/unifi-gateway:latest
docker compose up -d

See the Docker section below for details.

Standalone Binaries

Pre-built binaries are also available from Releases if you prefer manual installation.

Platform Binary
Linux x86_64 unifi-gateway-linux-amd64
Linux ARM64 unifi-gateway-linux-arm64
Linux ARMv7 unifi-gateway-linux-armhf
FreeBSD x86_64 unifi-gateway-freebsd-amd64

From Source

pip install -r requirements.txt

Quick Start

1. Install dependencies

pip install -r requirements.txt

2. Configure

Copy the sample config and edit it:

cp conf/unifi-gateway.sample.conf conf/unifi-gateway.conf

Edit conf/unifi-gateway.conf:

[gateway]
# Map UniFi logical ports to your real system interfaces
ports = [ { "ifname": "eth0", "name": "WAN", "type": "wan", "realif": "eth0" }, { "ifname": "eth1", "name": "LAN", "type": "lan", "realif": "br-lan" } ]

# Your LAN-side IP and MAC (how the controller identifies this device)
lan_ip = 192.168.1.1
lan_mac = aa:bb:cc:dd:ee:ff

The realif values must match your actual system interface names (check with ip link on Linux or ifconfig on FreeBSD).

3. Adopt to controller

python unifi_gateway.py set-adopt -s http://your-controller:8080/inform

The first run sends a discovery inform. Go to the UniFi Controller UI, find the new "USG" device, and click Adopt. Then run set-adopt again to complete the handshake:

python unifi_gateway.py set-adopt -s http://your-controller:8080/inform

4. Run

# Foreground (recommended for initial testing)
python unifi_gateway.py run

# Background daemon (Linux only)
python unifi_gateway.py start

# Stop / restart
python unifi_gateway.py stop
python unifi_gateway.py restart

Platform Setup

OpenWRT

The daemon works with OpenWRT's default dnsmasq DHCP server. Typical interface mapping:

ports = [ { "ifname": "eth0", "name": "WAN", "type": "wan", "realif": "eth0" }, { "ifname": "eth1", "name": "LAN", "type": "lan", "realif": "br-lan" } ]

DHCP leases are auto-detected at /tmp/dhcp.leases.

OPNSense (FreeBSD)

The daemon auto-detects FreeBSD and uses arp -an for the neighbor table, netstat -rn for routing. It supports KEA DHCP (OPNSense's default DHCP server) with auto-detection of the lease file at /var/db/kea/kea-leases4.csv.

Typical interface mapping (check your interfaces with ifconfig):

ports = [ { "ifname": "eth0", "name": "WAN", "type": "wan", "realif": "vmx0" }, { "ifname": "eth1", "name": "LAN", "type": "lan", "realif": "vmx1" } ]
dhcp_lease_file = /var/db/kea/kea-leases4.csv
dhcp_lease_format = kea

Recommended setup using a Python virtual environment:

python3 -m venv /opt/unifi-gateway/venv
/opt/unifi-gateway/venv/bin/pip install -r requirements.txt
/opt/unifi-gateway/venv/bin/python unifi_gateway.py set-adopt -s http://your-controller:8080/inform
/opt/unifi-gateway/venv/bin/python unifi_gateway.py run

pfSense (FreeBSD)

Same as OPNSense but uses ISC dhcpd instead of KEA:

dhcp_lease_file = /var/dhcpd/var/db/dhcpd.leases
dhcp_lease_format = isc

Generic Linux (Debian, Ubuntu, etc.)

Works out of the box. Uses /proc/net/dev for multicast counters, /proc/net/route for default gateway, and /etc/resolv.conf for nameservers.

Docker

Build and run

docker build -t unifi-gateway .
docker run -d --name unifi-gateway --network host \
  -v $(pwd)/conf:/app/conf \
  unifi-gateway

Docker Compose

docker compose up -d

For automatic adoption on first start, set the UNIFI_ADOPT_URL environment variable in docker-compose.yml:

environment:
  - UNIFI_ADOPT_URL=http://your-controller:8080/inform

Note: network_mode: host is required so the daemon can read the host's real network interfaces. This only works on Linux — Docker Desktop on Windows/macOS does not support host networking.

Service Management

Packages automatically install and enable the service. After configuring, just start it:

Platform Start Logs
systemd (Debian/Ubuntu/RHEL) sudo systemctl start unifi-gateway journalctl -u unifi-gateway -f
rc.d (FreeBSD/OPNSense) sudo service unifi_gateway start tail -f /var/log/unifi-gateway.log
procd (OpenWRT) /etc/init.d/unifi-gateway start logread -e unifi-gateway

Updates are handled by your package manager: apt upgrade, dnf upgrade, opkg upgrade, apk upgrade, or pkg upgrade.

Configuration Reference

Environment Variables

Variable Default Description
UNIFI_GW_CONFIG conf/unifi-gateway.conf Path to config file
UNIFI_GW_LOG_LEVEL DEBUG Log level (DEBUG, INFO, WARNING, ERROR)
UNIFI_GW_LOG_FILE (stderr) Log to file instead of stderr
UNIFI_ADOPT_URL (none) Controller inform URL for automatic adoption on start
UNIFI_ADOPT_KEY (none) Auth key for auto-adoption (optional, rarely needed)

Config File (conf/unifi-gateway.conf)

[global]

Key Default Description
pid_file unifi-gateway.pid PID file path for daemon mode
disable_broadcast True Disable UDP multicast discovery

[gateway]

Key Default Description
ports (required) JSON list mapping UniFi ports to real interfaces. Optional per port: mac (overrides detection, e.g. for PPPoE interfaces without a MAC)
lan_ip (required) LAN IP address
lan_mac (required) LAN MAC address
firmware 4.4.18.5052168 Reported firmware version
device UGW3 Device model string
device_display UniFi-Gateway-3 Display name
use_aes_gcm False Use AES-GCM encryption (set by controller)
hostname (auto-detected) Override reported hostname
dhcp_lease_file (auto-detected) Path to DHCP lease file
dhcp_lease_format dnsmasq Lease format: dnsmasq, isc, or kea
ping_target ping.ubnt.com Host for latency measurement
speedtest_file ./speedtest.json Path to speedtest results JSON
platform UNIFI-GW Platform string in discovery broadcasts
extra_inform (none) JSON object merged into every complete inform last (testing/overrides). An invalid value is logged and ignored

[openwrt]: DHCP from the controller (optional, off by default)

On OpenWrt, the daemon can apply the DHCP settings you make in the UniFi controller to /etc/config/dhcp: the pool (start, size, lease time) and IPv4 reservations (fixed IPs) of one subnet. It reads the controller's system_cfg in either format: the USG tree, or the udapi format a UXG (Gateway Lite) receives. Everything else the controller sends (firewall, VLANs, other networks, DHCP options) is ignored.

Key Default Description
dhcp_sync_enabled False Turn the sync on
dhcp_sync_mode apply apply, or dry-run to only log the planned changes
dhcp_sync_network (required) The one subnet that may be changed, e.g. 192.168.0.0/24. It must match OpenWrt's network.lan address
dhcp_sync_max_changes 128 Refuse a run that would change more than this
dhcp_config_path /etc/config/dhcp UCI DHCP file
dhcp_backup_dir /etc/unifi-gateway/backups Copies of the DHCP file before each change (last 10 kept)
dhcp_state_file /etc/unifi-gateway/dhcp-sync-state.json Summary of the last applied run
dhcp_controller_url (none) e.g. https://192.168.1.10:8443 (must be https://). With the credentials file, reservation names come from the controller's client list
dhcp_controller_credentials_file (none) JSON {"username": ..., "password": ...} for a controller account; keep it chmod 600
dhcp_controller_site default Controller site name
dhcp_controller_cert_sha256 (none) SHA-256 fingerprint of the controller's certificate (hex, colons optional). Use this for the usual self-signed certificate
dhcp_controller_ca_file (none) CA bundle to verify the controller's certificate. Without this and without a fingerprint, the system CAs are used

How it stays safe:

  • Ownership: reservations it creates or takes over are marked unifi_managed '1' and unifi_mac. Only those are changed or deleted.
  • Hand-made entries: these are never touched. A reservation from the controller that conflicts with one aborts the run.
  • Rollback: if dnsmasq doesn't accept the result, the previous file is restored.
  • Names: first the controller's local DNS record, then the client's name in the controller, then host-<mac>. An existing reservation keeps its current name.
  • Placeholder: the controller's built-in placeholder lease (00:00:00:00:00:00 → 192.168.1.20) is skipped.
  • Start with a test run: begin with dhcp_sync_mode = dry-run and read the planned changes in the log.

Controller client names (optional). The controller's certificate is always checked before the credentials are sent. A standalone controller usually has a self-signed certificate, so pin it. Get its fingerprint with:

openssl s_client -connect 192.168.1.10:8443 </dev/null 2>/dev/null | openssl x509 -noout -fingerprint -sha256

and set dhcp_controller_cert_sha256 to the value after Fingerprint=. When the controller gets a new certificate, update the fingerprint. Until then the lookup logs a warning and new reservations are named host-<mac>; existing ones keep their names.

The lookup uses the standalone Network application's API (/api/login, /api/s/<site>/...). UniFi OS consoles (UDM, Cloud Key Gen2+, UniFi OS Server) use other paths, so there the lookup fails and names fall back to the DNS records and host-<mac>.

[provisioned]

Populated automatically by the controller after adoption. Do not edit manually.

Emulating a Gateway Lite (UXG) instead of a USG

UniFi Network 10.6 is the last release line that supports the USG (UGW3). With device = UXG the daemon poses as a UniFi Gateway Lite, a supported UniFi OS gateway, and the controller provisions it with the UniFi OS ("udapi") config format instead of the USG one.

[gateway]
device = UXG
device_display = Gateway Lite
# use the version the controller lists as current for UXG, or it shows an Update button
firmware = 6.0.17.36539
# Gateway Lite ports: eth0 = LAN, eth1 = WAN (optional per port: "mac", "port_idx", "media", "speed" in Mb/s)
ports = [ { "ifname": "eth0", "name": "LAN", "type": "lan", "realif": "br-lan" },
          { "ifname": "eth1", "name": "WAN", "type": "wan", "realif": "wan" } ]

For any model that isn't UGW*, the complete inform also carries:

  • port_table: one entry per configured port with port_idx and name = the emulated ifname, plus live counters and rates (rx_bytes-r/tx_bytes-r in bytes/s, rx_rate/tx_rate in bits/s). Without it the controller logs Could not find port information for NetworkConf interface eth1 and sends no interfaces or DHCP config. The WAN entry becomes the controller's WAN stats (throughput, "Down/Up Activity"). Speed is the detected link speed (psutil), or the port's speed; the media follows from it (FE, GE, 2.5GE, 10GE) unless media is set.
  • uptime_stats.WAN: uptime, availability and latency from the ping to ping_target. The controller marks the WAN online when uptime > 0, and takes latency/availability from the first alerting_monitors entry. The UI's "Connection" is Excellent at availability 100 and latency < 50 ms, and Failed when those values are missing.
  • udapi_version.versionDetail: the udapi features the "firmware" supports. The controller only sends config sections listed here (services/dhcpServers, interfaces, vlans, ...).
  • leaseExpiry per ipv4_active_leases entry, and active_dhcp_lease_count on the LAN network_table entry.

The config arrives as setparam → system_cfg, a JSON string {"udapi": {...}, "ubntconf": "..."}. udapi.services.dhcpServers[] holds each network's pool, lease time, DNS, domain, options and staticLeases[{"id": MAC, "addresses": [IP]}]. It's recorded in unhandled_commands.json and contains secrets (tokens, certificates, password hashes). Moving an existing USG to UXG means forgetting the device and adopting it again. Tested against UniFi Network 10.6.109 only, not UniFi OS Server or Network 11.

Speed Test

The controller can trigger speed tests. Install speedtest-cli for this to work:

pip install speedtest-cli

Results are saved to speedtest.json and reported in the next inform cycle.

Architecture

Module Purpose
unifi_gateway.py Entry point, inform loop, controller response handling, adoption
unifi_protocol.py TNBU binary protocol: AES-CBC/GCM encryption, zlib/snappy compression, JSON payload construction
datacollector.py Cross-platform data collection via psutil (Linux + FreeBSD), with platform-specific fallbacks
tools.py Helper functions for building if_table and network_table structures
tlv.py TLV encoding for UDP discovery packets
daemon.py Unix daemon (double-fork, PID file)

License

MIT — see LICENSE.

Acknowledgments

This project builds upon and was inspired by:

Protocol documentation:

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…