UniFi Network Rules is a custom integration for Home Assistant that integrates with your UniFi Dream Machine/Router to both provide and help you create useful interactions and automations for your Home Lab. The goal of this integration is to simplify policy and rule management for real world use cases. I built this because I wanted to enable things like screen time controls for my kids, game server access controls, and more with the push of a button in Home Assistant. Functionality that can be shared with anyone in your home.
- Switch entities for all rules, including firewall policies (zone-based firewall), traffic/firewall rules (non-zone-based firewall), forwarding rules, traffic routes.
- Service actions for full backup and restore of all rules that are managed by this integration.
- Service actions for batch enabling and disabling rules by pattern matching rule names or IDs.
- Service actions for deleting rules by ID.
Request a feature here.
- A UniFi device running network application 9.0.92 or later.
- A local account with Admin privileges to the network application. Must not be a UniFi Cloud account.
- Home Assistant 2025.2 or later with network access to the UniFi device.
If you don't or can't use HACS, alternatively, copy the custom_components/unifi_network_rules
directory to your config/custom_components
directory.
I recommend installing the Studio Code Server addon to make it easier to copy in the custom component directly in the Home Assistant UI. Settings -> Add-ons -> Studio Code Server -> Install
. Then turn on Show in Sidebar
.
THEN
- Restart Home Assistant.
- In the Home Assistant configuration page, click on "Integrations".
- Click on the "+" button in the bottom right corner.
- Search for "UniFi Network Rule Manager" and select it.
- Enter credentials of a local admin user on your UDM and click on the "Submit" button.
Host: The IP address or hostname of your UniFi Device.
Username: The local admin account on the UDM.
Password: The password for the UDM account.
Site: The UniFi site name to connect to (defaults to "default" if not specified).
Update Interval: The automatic refresh interval in minutes. Can be longer since updates real-time.
Verify SSL: Enable SSL certificate verification (defaults to disabled for self-signed certificates).
Once you have configured the integration, you will be able to see the policies, rules, and routes configured on your UniFi Network as switches in Home Assistant. Add the switch to a custom dashboard or use it in automations just like any other Home Assistant switch.
The integration provides several services focused on managing and automating existing UniFi Network rules:
This is the simplest method:
- Go to Settings → Devices & Services → Helpers
- Add a Button helper (e.g., "Refresh UniFi Rules")
- Create an automation that triggers when the button is pressed
- Use the service in the automation's action
Example automation for refresh:
alias: Backup UniFi Network Rules
description: >-
Dumps all policy, rule, and route JSON state to a file in the ha config
directory
triggers:
- trigger: state
entity_id:
- input_button.backup_unr
conditions: []
actions:
- action: unifi_network_rules.backup_rules
metadata: {}
data:
filename: unr_daily_backup.json
mode: single
First, create a script in your Settings → Automations & Scenes → Scripts:
sequence:
- sequence:
- action: unifi_network_rules.backup_rules
metadata: {}
data:
filename: my_custom_unr_backup.json
alias: Backup my UniFi Rules
description: Custom script that will backup all rules and routes imported from your UDM
Then add a button card to your dashboard that references the script:
show_name: true
show_icon: true
type: button
tap_action:
action: perform-action
perform_action: script.backup_my_unifi_rules
target: {}
name: Backup my Network Rules
icon: mdi:cloud-upload
Manually refresh the state of all network rules. Useful if you've made changes directly in the UniFi interface.
Create a backup of all your firewall policies and traffic routes. The backup will be stored in your Home Assistant config directory.
Restore rules from a previously created backup file. You can selectively restore specific rules by their IDs, names, or rule types.
Enable or disable multiple rules at once by matching their names. This is useful for automating rule management based on conditions or schedules.
Delete an existing zone-based firewall policy by its ID. Only available for UniFi OS 9.0.92+ with zone-based firewall enabled.
alias: Backup UniFi Network Rules
description: >-
Creates a daily backup of all policy, rule, and route JSON state to a file in
the Home Assistant config directory every day at 2:00 AM
triggers:
- trigger: time_pattern
hours: "2"
conditions: []
actions:
- action: unifi_network_rules.backup_rules
metadata: {}
data:
filename: unr_daily_backup.json
mode: single
Fully restore the state of all policies
alias: Restore all policies from last backup
description: Restores the backed-up state of all policies, including zones, devices, objects, etc.
triggers:
- trigger: state
entity_id:
- input_button.restore_unr
conditions: []
actions:
- action: unifi_network_rules.restore_rules
metadata: {}
data:
filename: unr_daily_backup.json
mode: single
Selectively restore rules based on name and type
alias: Restore Kid Downtime Policies
description: Restores the backed-up state of the policies that contain the name `Block Kid`
triggers:
- trigger: state
entity_id:
- input_button.restore_unr
conditions: []
actions:
- action: unifi_network_rules.restore_rules
metadata: {}
data:
filename: unr_daily_backup.json
name_filter: Block Kid
rule_types:
- policy
mode: single
Every night at 11PM, Policies or Rules that contain the name "Block Kid Internet" will enable
and send a notification to Chris's iPhone
alias: Daily Device Downtime
description: Block kid devices at bedtime daily
triggers:
- trigger: time_pattern
hours: "23"
conditions: []
actions:
- action: unifi_network_rules.bulk_update_rules
metadata: {}
data:
state: true
name_filter: Block Kid internet
- action: notify.mobile_app_chrisiphone
metadata: {}
data:
message: Kids Device Downtime Enabled
title: Daily Device Downtime
mode: single
alias: Turn Off Minecraft Server Port after 2 hours
description: >-
We don't want to leave this port open indefinitely, just leave open for a
normal gaming session, then automatically turn off.
triggers:
- trigger: state
entity_id:
- switch.port_forward_minecraft_10_1_1_75_4882
from: "off"
to: "on"
conditions: []
actions:
- delay:
hours: 2
minutes: 0
seconds: 0
milliseconds: 0
- action: switch.turn_off
metadata: {}
data: {}
target:
entity_id: switch.port_forward_minecraft_10_1_1_75_4882
mode: single
This automation uses a helper to toggle port forwarding access to a game server. When enabled, it automatically disables the port forwarding after 2 hours for security.
-
Backup Organization: Use descriptive filenames with timestamps:
filename: "UniFi_rules_{{now().strftime('%Y%m%d_%H%M')}}.json"
-
Selective Restore: When restoring rules, use filters to target specific rules:
action: unifi_network_rules.restore_rules data: filename: "backup.json" name_filter: "Guest" # Only restore guest-related rules rule_types: - policy # Only restore firewall policies
-
Bulk Updates: Use naming conventions in UniFi to make bulk updates easier:
- Name related rules with common prefixes (e.g., "Guest_", "IoT_")
- Use the bulk_update_rules service with name_filter to manage groups of rules
-
Integration with Other Services: Combine with other Home Assistant integrations:
- Use the Folder Watcher integration to monitor backup file changes
- Combine with the Google Drive Backup integration for offsite copies
- Set up notifications when rule states change
The UniFi Network Rules integration supports several types of rules:
-
Firewall Policies (policy): Zone-based firewall rules that control traffic between different security zones (WAN, LAN, Guest, etc.). These form the backbone of your network security.
-
Port Forwarding Rules (port_forward): Allow external traffic to reach specific internal devices and services by forwarding specific ports from your WAN to internal IP addresses.
-
Traffic Routes (route): Control how traffic is routed through your network, typically used for VPN routing or specific network destinations. Each traffic route has two components:
- The main switch that enables/disables the route
- A child "kill switch" that blocks all traffic if the route is down (prevents data leakage if your VPN disconnects)
-
QoS Rules (qos_rule): Quality of Service rules that prioritize certain types of traffic on your network. These rules can ensure critical applications (like video conferencing) get bandwidth priority over less time-sensitive applications.
-
Legacy Rules: For older UniFi OS versions, there are also legacy_firewall and legacy_traffic rule types, which are mapped to "policy" when using the service.
To run the tests, you need to install the dependencies in the requirements.txt
file.
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
Then run the tests:
pytest tests
We've created a Bruno collection to manually test the API requests. These are the same requests that the integration makes. This is a great way to verify your credentials are valid and to verify device connectivity and compatibility.
The integration includes targeted diagnostics and debugging capabilities to help troubleshoot issues while minimizing resource usage.
To enable debug logging for the entire integration, add the following to your configuration.yaml
:
logger:
logs:
custom_components.unifi_network_rules: debug
aiounifi: debug # Also log the underlying UniFi library
For more focused debugging of specific subsystems, you can enable only what you need by editing the constants in custom_components/unifi_network_rules/const.py
:
LOG_WEBSOCKET
: Enable detailed WebSocket connection and message logsLOG_API_CALLS
: Log API requests and responsesLOG_DATA_UPDATES
: Log data refresh and update cyclesLOG_ENTITY_CHANGES
: Log entity addition, removal, and state changes
These targeted flags help reduce log noise when troubleshooting specific issues.
This integration supports Home Assistant's built-in diagnostics. To access:
- Go to Settings → Devices & Services → Integrations
- Find the UniFi Network Rules integration
- Click on Configure → Download Diagnostics
- Share the generated file when reporting issues
The diagnostics provide essential information about your system configuration without exposing sensitive data.
For advanced troubleshooting of connectivity issues, the integration includes a WebSocket health monitor that can help identify connection problems with the UniFi controller.
To temporarily enable API call tracing for a session:
- SSH into your Home Assistant instance
- Enter the
/config/custom_components/unifi_network_rules
directory - Edit the file:
const.py
- Change
LOG_API_CALLS = False
toLOG_API_CALLS = True
- Restart Home Assistant
Remember to revert this change after troubleshooting to prevent excessive logging.
If you are having trouble getting the integration to work, please check the following:
- Ensure the UDM is running the latest version of the network application.
- Ensure the UDM is connected to the same network as your Home Assistant instance.
- Ensure you are using the IP address of the UDM, not the hostname.
- Verify your local account has proper admin privileges.
Run this on a computer connected to the same network as your UDM or directly on your Home Assistant instance to verify connectivity to the UDM and that your credentials are valid.
curl -k -X POST https://[UDM-IP]/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"[USERNAME]","password":"[PASSWORD]"}'
Possible responses:
- 200 OK: Credentials are valid. Returns a JSON object with the user's information.
- 401 Unauthorized: Credentials are invalid.
- 429 Too Many Requests: The user has made too many requests in a short period of time. Wait a few minutes and try again.
You can do this by logging into your UniFi device locally or via https://UniFi.ui.com, navigate to Settings -> Admins & Users, and checking the local user's permissions. It should be Admin or Super Admin for the network application.
If you are having trouble getting the integration to work, please open an Issue using the bug report template. Please enable debug logging and include the full log output in your report. Note that it may contain sensitive network information, so please review it before posting. The logs can be large, so i recommend attaching them as a file.
To get the debug log, navigate Devices and Services -> UniFi Network Rules -> Enable Debug Logging. Then reload the integration and try to reproduce the issue. Finally, disable debug logging and download the log file.
This integration uses the same core library that Home Assistant Unifi integration uses, so there can be version incompatibility issues at time. We may ship with a higher version causing conflicts if you use multiple UniFi integrations. Sometimes restarting Home Assistant can help.
This will not support all the features of the UniFi controller, for that, leverage the core integration. The focus of this integration will be home and home lab use cases to extend and differentiate from the core integration.
Contributions are welcome! Please read our Contributing Guidelines and feel free to submit a PR.