Skip to content

About

Keep UniFi Policy-Based Routes in sync automatically. Define a service once (ASN, CIDR, domain, or operator URL feed like Zoom/Cloudflare/GitHub/Fastly/AWS/MS365) and it resolves fresh prefixes and pushes them to your UDR/UDM as Traffic Routes — IP-match or Domain-match. 75 presets, DNS churn diagnostic, IPv4+IPv6, REST API. Docker, MIT.

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

UniFi Traffic Routes

Self-hosted controller that keeps UniFi Policy-Based Routes in sync with service definitions built from ASNs, static CIDRs, and domains.

Built for a specific real-world scenario: you have a bonded / SpeedFusion WAN as primary and a local ISP breakout as WAN2, and you want streaming services, Apple iCloud/APNS, banking, and other geo-sensitive traffic to bypass the bonded tunnel — without hand-maintaining prefix lists as providers rotate CDN blocks.

Why this exists

Ubiquiti's official Network Integration API (v10.3+) exposes address groups ("Traffic Matching Lists"), firewall policies, DNS policies, and more — but does not yet expose the Policy-Based Routing endpoint. And in the Policy Table refactor (Network 9.4+), Ubiquiti removed the ability for a Route policy to reference an address group.

Meanwhile, every streaming/finance/auth service you care about publishes its IP footprint via ASNs, RIR records, or DNS. Someone has to be the glue between those upstream data sources and the UDR's routing table.

This tool is that glue: it resolves service definitions to CIDRs on every sync and inlines them directly into UniFi Traffic Routes, using the classic API where the official one doesn't reach.

What it does

  • Define a service once: Netflix = AS2906 + AS40027, Apple = AS714 + AS6185 + 17.0.0.0/8, Chase Bank = chase.com (via DNS). Or install from 72 curated presets across 9 categories.
  • Resolve fresh on every sync: bgpq4 for ASNs, DNS for domains, aggregated into minimal supernets with hole-punching via ipaddress.address_exclude.
  • Push to UDR: creates/updates Policy-Based Routes with the resolved prefixes inlined, targeting the WAN interface you pick.
  • Verify: reads back after every write and diffs against what was sent.
  • Notice drift: if Apple adds new prefixes overnight, the scheduled sync updates both the address group and any Traffic Routes referencing it.

Feature summary

  • Four source types for defining a service:
    • ASNs — resolved via bgpq4 (best for services with clean ASN ownership)
    • Static CIDRs — hand-entered blocks
    • Domains — resolved via DNS A/AAAA lookups
    • URL feeds — CIDR lists published by the service operator itself (Zoom, Cloudflare, GitHub, Fastly, AWS, Microsoft 365, Google Cloud) — the most reliable source when the operator provides one
  • DNS coverage diagnostic — on-demand tool that queries each domain against 4 public resolvers with rotation detection, flags domains with short TTLs or geo-DNS as unreliable for IP-based routing
  • Traffic Routes in two modes:
    • IP mode — resolve group prefixes fresh at push time, inline into route
    • Domain mode — pass domain names, UDR watches DNS live (matches even when IPs rotate; requires clients to use UDR as DNS resolver)
  • Full IPv4 + IPv6 support (per-family address groups + Traffic Routes)
  • CIDR aggregation with exclude hole-punching
  • 75 built-in presets across 10 categories with 9 install bundles
  • Two UniFi auth modes:
    • Official Integration API via X-API-Key (for address groups)
    • Classic API via local admin credentials (for Traffic Routes, since PBR isn't yet in the official API surface)
  • Session caching (20 min TTL) to avoid UniFi's login rate limit
  • Batch sync — "Sync all routes" in one auth session
  • Dry-run preview showing what would change before applying
  • Post-write verification with drift detection
  • Retries with exponential backoff on 408/429/5xx
  • Pending-sync detection — group changes propagate to routes
  • REST API (Bearer token) for external automation
  • Import/export configuration as JSON
  • Healthchecks.io / generic webhook notifications
  • Multi-arch Docker image (amd64 + arm64)
  • SQLite with WAL mode, in-place schema migrations on startup

Quick start

# docker-compose.yml
services:
  unifi-routes-manager:
    image: ghcr.io/timerealm/unifi-routes-manager:latest
    container_name: unifi-routes-manager
    restart: unless-stopped
    ports:
      - "8080:8080"
    environment:
      - TZ=America/Chicago
      # Hardening for production deployments (see Security section)
      # - FORCE_HTTPS=true          # if terminating TLS at a reverse proxy
      # - BEHIND_PROXY=true         # if behind Traefik / nginx / Caddy
    volumes:
      - ./data:/data
docker compose up -d
# Browse http://<host>:8080 → first-run wizard

First-run flow

  1. Create the web-UI admin account (first-run wizard).
  2. Settings → configure your UDR:
    • Host: https://<UDR-IP> (e.g. https://192.168.0.1)
    • Auth mode: pick Local API Key (recommended) or Local admin credentials
    • API Key: paste from your UDR → Settings → Control Plane → Integrations
    • Username/Password: also fill this in — needed for Traffic Routes even if API Key mode is your default (the PBR endpoint isn't in the official API surface)
  3. Click Test UniFi connection — verifies auth and discovers your site UUID
  4. Presets → install the Essential bundle, or pick individual services
  5. Watch the initial sync push address groups to your UDR
  6. Routing → New route → pick group + target WAN → Save & apply
  7. Verify with traceroute <service-domain> — the second hop should be your target WAN's next-hop instead of the default WAN's

Choosing the right source type

Each service can be defined using any combination of the four source types. Pick based on what's cleanest for that service:

Source Best when Example
ASN Service owns its ASN (bgpq4 lookup is definitive) Apple (AS714), Netflix (AS2906)
URL feed Operator publishes an IP list at a stable URL Zoom, Cloudflare, GitHub, Fastly
Static CIDR You know a well-known block 17.0.0.0/8 for Apple
DNS domain Nothing else applies; service uses shared cloud infra Anthropic Claude, ChatGPT

DNS is the least reliable — many services rotate IPs on short TTLs or use geo-DNS. Use the built-in DNS coverage diagnostic (accessible from any group's edit page) to check whether a domain is stable or rotating. If it rotates, prefer a URL feed if one exists, or switch the related Traffic Route to Match by Domain mode which relies on live DNS instead of resolved IPs.

Traffic Route modes

Every Traffic Route matches on one of two axes:

  • IP mode (default) — the tool resolves the group's prefixes fresh at push time and inlines them into the route. Works for every client regardless of DNS setup. Won't catch traffic to IPs that appeared after the last sync.

  • Domain mode — the tool sends the group's domain names to the UDR, which watches DNS queries live and routes matching responses. Handles rotating IPs perfectly. Requires clients to use the UDR as their DNS resolver (which is the default for DHCP-configured devices on most home networks).

You can have both modes for the same service (e.g., an IP-mode route covering the ASN-known IPs, plus a Domain-mode route as backup for anything DNS-only). They're additive.

Requirements

  • UDR/UDM/UCG running Network app version 9.4 or later (10.3+ recommended for X-API-Key auth). Confirmed working on UDR7 with Network 10.4.57.
  • Two WAN interfaces configured — this tool just steers traffic to a chosen WAN; it doesn't set up the WANs themselves.
  • A local admin account on your UDR (not a Ubiquiti SSO account) if you want Traffic Route automation.

Environment variables

Variable Default Purpose
DATA_DIR /data Where SQLite DB and Fernet key are stored
TZ UTC Timezone (affects log timestamps and schedule)
FLASK_SECRET_KEY auto-generated Session-cookie signing key
FORCE_HTTPS false Set true to enforce Secure cookies + strict CSRF
BEHIND_PROXY false Set true to trust X-Forwarded-* headers

Security

Deployment expectations: designed for a trusted internal network. If you expose it to the public internet, at minimum:

  • Set FORCE_HTTPS=true and terminate TLS at a reverse proxy
  • Set BEHIND_PROXY=true so the login rate-limiter sees real client IPs
  • Add another auth layer (Cloudflare Access, Authelia, etc.)
  • Restrict at the network layer (firewall, VPN) where possible

Built-in protections:

  • CSRF tokens on every state-changing form
  • Rate-limiting: 10 failed logins per IP in 5 min → 15 min lockout
  • bcrypt password hashing for the web admin
  • Fernet encryption at rest for UDR credentials and API keys
  • Baseline security headers on every response (X-Frame-Options, CSP, etc.)
  • API tokens stored as SHA-256 hashes
  • Session cookies: HttpOnly, SameSite=Lax, Secure when FORCE_HTTPS=true

Reporting vulnerabilities: see SECURITY.md.

Architecture

                    ┌── bgpq4 (ASN prefixes)
Service groups ─────┼── ipaddress.collapse_addresses (aggregation)
(ASN + CIDR +       ├── DNS (A/AAAA for domains)
 Domain + Feed)     └── HTTP GET + parse (URL feeds)
                              │
                              ▼
                   Resolved CIDR set (v4 + v6)
                              │
                              ▼
              ┌───────────────┴───────────────┐
              │                               │
              ▼                               ▼
     Address Groups                 Traffic Routes
     (optional — for                (the primary
      firewall use)                  deliverable)
     via Integration API             via classic API
     + X-API-Key                     + cookie auth
                                            │
                                    ┌───────┴───────┐
                                    ▼               ▼
                                 IP mode      Domain mode
                              inline CIDRs   pass domains,
                               into route    UDR watches DNS
              │                               │
              └───────────────┬───────────────┘
                              ▼
                         UDR / UDM / UCG

Both endpoints are HTTP APIs on your UDR. Address groups become "Traffic Matching Lists" on the UDR (usable by firewall policies). Traffic Routes become "Policy-Based Routes" that actually steer packets — in either IP-match or Domain-match mode, per route.

For the full mechanics — session caching, retry behavior, aggregation algorithm, feed parsers, DNS analyzer — read the source in app/sync.py, app/feeds.py, app/dns_analyzer.py, and app/unifi.py, all heavily commented.

Building from source

git clone https://github.com/timerealm/unifi-routes-manager.git
cd unifi-routes-manager

# Python backend
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

# Tailwind assets (compiled, not CDN)
npm install
npm run build

# Run
export DATA_DIR=./dev-data
mkdir -p "$DATA_DIR"
flask --app wsgi run --port 8080

Contributing

See CONTRIBUTING.md. New presets, bug reports, and schema discoveries for new firmware versions are especially welcome.

License

MIT — see LICENSE.

Acknowledgments

  • Built with Flask, HTMX, Alpine.js, Tailwind CSS, and bgpq4.
  • Traffic Route schema for Network 10.4.57 discovered via the built-in Schema Discovery mode against a real UDR7 — thanks to Ubiquiti for keeping their newer Network firmware self-documenting via the local Swagger docs at https://<UDR>/unifi-api/network.

About

Keep UniFi Policy-Based Routes in sync automatically. Define a service once (ASN, CIDR, domain, or operator URL feed like Zoom/Cloudflare/GitHub/Fastly/AWS/MS365) and it resolves fresh prefixes and pushes them to your UDR/UDM as Traffic Routes — IP-match or Domain-match. 75 presets, DNS churn diagnostic, IPv4+IPv6, REST API. Docker, MIT.

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages