Firewall added & some fixes

This commit is contained in:
MoonDev
2026-04-13 12:40:49 +03:00
parent 7eaa9750b0
commit 8c35022483
22 changed files with 1659 additions and 134 deletions

50
main.go
View File

@@ -11,6 +11,7 @@ import (
"alpine-router/config"
"alpine-router/dhcp"
"alpine-router/firewall"
"alpine-router/handlers"
"alpine-router/mihomo"
"alpine-router/nat"
@@ -68,6 +69,9 @@ func main() {
mux.HandleFunc("/api/config.yaml", handlers.HandleConfigYAML)
mux.HandleFunc("/api/firewall", handlers.HandleFirewall)
mux.HandleFunc("/api/firewall/apply", handlers.HandleFirewallApply)
mux.HandleFunc("/api/nat", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
@@ -227,13 +231,51 @@ func applyConfig(cfg *config.AppConfig) {
}
}
if err := nat.ApplyRulesWithBlocked(natCfg, blockedIPs); err != nil {
log.Printf("Warning: apply NAT: %v", err)
// Build LAN interface set: NAT interfaces + all VLAN interfaces + their parents.
seenLAN := map[string]bool{}
var lanIfaces []string
addLAN := func(name string) {
if name != "" && !seenLAN[name] {
lanIfaces = append(lanIfaces, name)
seenLAN[name] = true
}
}
for _, name := range cfg.NAT.Interfaces {
addLAN(name)
}
if names, err := network.GetInterfaces(); err == nil {
for _, name := range names {
if network.IsVLAN(name) {
addLAN(name)
addLAN(network.VLANParent(name))
}
}
}
// Convert config firewall rules.
fwRules := make([]firewall.Rule, len(cfg.Firewall.Rules))
for i, r := range cfg.Firewall.Rules {
fwRules[i] = firewall.Rule{
ID: r.ID, Enabled: r.Enabled, Action: r.Action, Protocol: r.Protocol,
SrcAddr: r.SrcAddr, SrcPort: r.SrcPort, DstAddr: r.DstAddr, DstPort: r.DstPort,
InIface: r.InIface, OutIface: r.OutIface, Comment: r.Comment,
}
}
err := firewall.ApplyAll(
firewall.NATConfig{Interfaces: cfg.NAT.Interfaces},
firewall.Config{Rules: fwRules, VLANIsolation: cfg.Firewall.VLANIsolation},
blockedIPs,
lanIfaces,
)
if err != nil {
log.Printf("Warning: apply firewall/NAT rules: %v", err)
} else {
log.Printf("NAT rules applied (%d interfaces, %d blocked clients)", len(cfg.NAT.Interfaces), len(blockedIPs))
log.Printf("Firewall/NAT applied (%d NAT ifaces, %d fw rules, %d blocked, vlan_isolation=%v)",
len(cfg.NAT.Interfaces), len(fwRules), len(blockedIPs), cfg.Firewall.VLANIsolation)
}
} else {
log.Printf("nftables not installed — NAT unavailable (install with: apk add nftables)")
log.Printf("nftables not installed — NAT/firewall unavailable (install with: apk add nftables)")
}
if dhcp.IsInstalled() {