Created
September 18, 2025 20:14
-
-
Save fathonix/885826f183ad22e5c899bbf889c3a2a9 to your computer and use it in GitHub Desktop.
Modify OpenWrt firewall zone of an interface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# fwzone.sh - Modify OpenWrt firewall zone of an interface | |
# Licensed under MIT. (c) 2025 Aldo Adirajasa Fathoni | |
action="$1" | |
iface="$2" | |
zone="$3" | |
msg() { | |
echo $@ | |
logger -t fwzone.sh[$$] "$@" | |
} | |
die() { | |
msg "${@}, action=${action} iface=${iface} zone=${zone}" >&2 | |
exit 1 | |
} | |
run_uci() { | |
uci $@ || die "Error running \`uci ${@}'" | |
} | |
getzoneidx() { | |
run_uci show firewall | sed -nr "s/firewall\.@zone\[(-?[0-9]+)\]\.name='${zone}'/\1/p" | |
} | |
getzoneidxbyiface() { | |
run_uci show firewall | sed -nr "s/firewall\.@zone\[(-?[0-9]+)\]\.network=.*'${iface}'.*/\1/p" | |
} | |
check_args() { | |
[ "$(uci get "network.${iface}")" = interface ] || die "Error checking interface" | |
[ -z "$(getzoneidx)" ] && die "Error checking firewall zone" | |
} | |
action_add() { | |
[ -n "$(getzoneidxbyiface)" ] && die "Error interface already in a zone" | |
idx=$(getzoneidx) | |
[ -z "$idx" ] && die "Error zone not found" | |
run_uci add_list "firewall.@zone[${idx}].network=${iface}" | |
run_uci commit firewall | |
/etc/init.d/firewall reload | |
msg "Interface ${iface} added to zone ${zone}" | |
} | |
action_del() { | |
idx=$(getzoneidxbyiface) | |
[ -z "$idx" ] && die "Error interface is not assigned to the zone" | |
zoneifaces=$(run_uci get "firewall.@zone[${idx}].network") | |
run_uci del "firewall.@zone[${idx}].network" | |
for f in $zoneifaces; do | |
[ "$f" = "$iface" ] && continue | |
run_uci add_list "firewall.@zone[${idx}].network=${f}" | |
done | |
run_uci commit firewall | |
/etc/init.d/firewall reload | |
msg "Interface ${iface} deleted from zone ${zone}" | |
} | |
action_help() { | |
echo "Usage: ${0} help|add|del [uci interface] [firewall zone]" | |
} | |
case "$action" in | |
help|--help|-h) | |
action_help | |
;; | |
add|del) | |
check_args | |
action_$action | |
;; | |
*) | |
echo "Invalid command. Run \`${0} help'." >&2 | |
exit 1 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment