Firewall added & some fixes
This commit is contained in:
9
RULES.md
9
RULES.md
@@ -1,8 +1,9 @@
|
||||
1. Все настройки обязательно сохранять в config.yaml и восстанавливать оттуда при первом запуске бинарника.
|
||||
1. Все настройки всех подсистем обязательно сохранять в config.yaml и восстанавливать оттуда при первом запуске бинарника, затрия то, что осталось в конфигах управляемых сервисов.
|
||||
2. Функциональные разделы админки писать отдельными html страницами и добавлять в главное меню.
|
||||
3. Документировать весь новый функционал в docs/
|
||||
|
||||
|
||||
|
||||
Установить пакеты:
|
||||
Зависимости alpine:
|
||||
dnsmasq
|
||||
nftables
|
||||
nftables
|
||||
conntrack-tools
|
||||
|
||||
BIN
alpine-router
BIN
alpine-router
Binary file not shown.
@@ -10,6 +10,7 @@ import (
|
||||
)
|
||||
|
||||
type InterfaceConfig struct {
|
||||
Label string `yaml:"label,omitempty"`
|
||||
Auto bool `yaml:"auto"`
|
||||
Mode string `yaml:"mode"`
|
||||
Address string `yaml:"address,omitempty"`
|
||||
@@ -52,12 +53,32 @@ type MihomoConfig struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
}
|
||||
|
||||
type FirewallRule struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Action string `yaml:"action" json:"action"`
|
||||
Protocol string `yaml:"protocol" json:"protocol"`
|
||||
SrcAddr string `yaml:"src_addr" json:"src_addr"`
|
||||
SrcPort string `yaml:"src_port" json:"src_port"`
|
||||
DstAddr string `yaml:"dst_addr" json:"dst_addr"`
|
||||
DstPort string `yaml:"dst_port" json:"dst_port"`
|
||||
InIface string `yaml:"in_iface" json:"in_iface"`
|
||||
OutIface string `yaml:"out_iface" json:"out_iface"`
|
||||
Comment string `yaml:"comment" json:"comment"`
|
||||
}
|
||||
|
||||
type FirewallConfig struct {
|
||||
Rules []FirewallRule `yaml:"rules" json:"rules"`
|
||||
VLANIsolation bool `yaml:"vlan_isolation" json:"vlan_isolation"`
|
||||
}
|
||||
|
||||
type AppConfig struct {
|
||||
Interfaces map[string]*InterfaceConfig `yaml:"interfaces"`
|
||||
DHCP DHCPConfig `yaml:"dhcp"`
|
||||
NAT NATConfig `yaml:"nat"`
|
||||
KnownDevices []KnownDevice `yaml:"known_devices"`
|
||||
Mihomo MihomoConfig `yaml:"mihomo"`
|
||||
Interfaces map[string]*InterfaceConfig `yaml:"interfaces"`
|
||||
DHCP DHCPConfig `yaml:"dhcp"`
|
||||
NAT NATConfig `yaml:"nat"`
|
||||
Firewall FirewallConfig `yaml:"firewall"`
|
||||
KnownDevices []KnownDevice `yaml:"known_devices"`
|
||||
Mihomo MihomoConfig `yaml:"mihomo"`
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -176,6 +197,9 @@ func EnsureDefaults(cfg *AppConfig) {
|
||||
if cfg.NAT.Interfaces == nil {
|
||||
cfg.NAT.Interfaces = []string{}
|
||||
}
|
||||
if cfg.Firewall.Rules == nil {
|
||||
cfg.Firewall.Rules = []FirewallRule{}
|
||||
}
|
||||
if cfg.KnownDevices == nil {
|
||||
cfg.KnownDevices = []KnownDevice{}
|
||||
}
|
||||
|
||||
201
firewall/firewall.go
Normal file
201
firewall/firewall.go
Normal file
@@ -0,0 +1,201 @@
|
||||
package firewall
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const tableName = "alpine-router"
|
||||
|
||||
// Rule is a single stateless forward-filter rule.
|
||||
type Rule struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Action string `yaml:"action" json:"action"` // accept | drop | reject
|
||||
Protocol string `yaml:"protocol" json:"protocol"` // tcp | udp | icmp | all
|
||||
SrcAddr string `yaml:"src_addr" json:"src_addr"` // CIDR or IP, empty = any
|
||||
SrcPort string `yaml:"src_port" json:"src_port"` // "80" | "80-443", empty = any
|
||||
DstAddr string `yaml:"dst_addr" json:"dst_addr"`
|
||||
DstPort string `yaml:"dst_port" json:"dst_port"`
|
||||
InIface string `yaml:"in_iface" json:"in_iface"` // input interface, empty = any
|
||||
OutIface string `yaml:"out_iface" json:"out_iface"` // output interface, empty = any
|
||||
Comment string `yaml:"comment" json:"comment"`
|
||||
}
|
||||
|
||||
// Config is the top-level firewall config stored in config.yaml.
|
||||
type Config struct {
|
||||
Rules []Rule `yaml:"rules" json:"rules"`
|
||||
VLANIsolation bool `yaml:"vlan_isolation" json:"vlan_isolation"`
|
||||
}
|
||||
|
||||
// NATConfig holds NAT masquerade settings (passed to avoid a direct nat import).
|
||||
type NATConfig struct {
|
||||
Interfaces []string
|
||||
}
|
||||
|
||||
// IsInstalled reports whether the nft binary is available.
|
||||
func IsInstalled() bool {
|
||||
_, err := exec.LookPath("nft")
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// ApplyAll atomically regenerates the complete nftables ruleset:
|
||||
// - NAT masquerade for natCfg.Interfaces
|
||||
// - Blocked client IP drops
|
||||
// - User rules from fwCfg (in order, enabled only)
|
||||
// - LAN isolation (if fwCfg.VLANIsolation): blocks traffic between any two LAN interfaces
|
||||
// (native + tagged VLANs). User rules placed above have priority.
|
||||
// - Default accept from LAN interfaces to WAN
|
||||
//
|
||||
// lanIfaces is the union of NAT interfaces and all VLAN interfaces — every interface
|
||||
// that serves a local subnet. Isolation prevents any two of them from talking directly.
|
||||
func ApplyAll(natCfg NATConfig, fwCfg Config, blockedIPs, lanIfaces []string) error {
|
||||
if err := os.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1"), 0644); err != nil {
|
||||
return fmt.Errorf("enable ip_forward: %w", err)
|
||||
}
|
||||
|
||||
// Remove both old and new table names to ensure clean state.
|
||||
exec.Command("nft", "delete", "table", "ip", "alpine-router-nat").Run()
|
||||
exec.Command("nft", "delete", "table", "ip", tableName).Run()
|
||||
|
||||
var activeRules []Rule
|
||||
for _, r := range fwCfg.Rules {
|
||||
if r.Enabled {
|
||||
activeRules = append(activeRules, r)
|
||||
}
|
||||
}
|
||||
|
||||
hasNAT := len(natCfg.Interfaces) > 0
|
||||
hasBlocked := len(blockedIPs) > 0
|
||||
hasVLANIsolation := fwCfg.VLANIsolation && len(lanIfaces) >= 2
|
||||
|
||||
if !hasNAT && !hasBlocked && !hasVLANIsolation && len(activeRules) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, "table ip %s {\n", tableName)
|
||||
|
||||
// ── Forward chain ────────────────────────────────────────────────────────
|
||||
sb.WriteString(" chain forward {\n")
|
||||
sb.WriteString(" type filter hook forward priority filter; policy drop;\n")
|
||||
sb.WriteString(" ct state established,related accept\n")
|
||||
|
||||
for _, ip := range blockedIPs {
|
||||
fmt.Fprintf(&sb, " ip saddr %s drop\n", ip)
|
||||
fmt.Fprintf(&sb, " ip daddr %s drop\n", ip)
|
||||
}
|
||||
|
||||
for _, rule := range activeRules {
|
||||
line := buildRuleLine(rule)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if rule.Comment != "" {
|
||||
fmt.Fprintf(&sb, " # %s\n", rule.Comment)
|
||||
}
|
||||
fmt.Fprintf(&sb, " %s\n", line)
|
||||
}
|
||||
|
||||
// LAN isolation — drop traffic between any two local (LAN) interfaces.
|
||||
// Placed AFTER user rules so explicit allow rules above still take effect.
|
||||
if hasVLANIsolation {
|
||||
quoted := make([]string, len(lanIfaces))
|
||||
for i, v := range lanIfaces {
|
||||
quoted[i] = fmt.Sprintf("%q", v)
|
||||
}
|
||||
set := "{ " + strings.Join(quoted, ", ") + " }"
|
||||
fmt.Fprintf(&sb, " iifname %s oifname %s drop\n", set, set)
|
||||
}
|
||||
|
||||
// Allow from LAN/VLAN interfaces to WAN (non-VLAN, non-blocked traffic falls through above).
|
||||
for _, iface := range natCfg.Interfaces {
|
||||
fmt.Fprintf(&sb, " iifname %q accept\n", iface)
|
||||
}
|
||||
|
||||
sb.WriteString(" }\n")
|
||||
|
||||
// ── Postrouting (masquerade) ─────────────────────────────────────────────
|
||||
if hasNAT {
|
||||
sb.WriteString(" chain postrouting {\n")
|
||||
sb.WriteString(" type nat hook postrouting priority srcnat; policy accept;\n")
|
||||
for _, iface := range natCfg.Interfaces {
|
||||
fmt.Fprintf(&sb, " iifname %q masquerade\n", iface)
|
||||
}
|
||||
sb.WriteString(" }\n")
|
||||
}
|
||||
|
||||
sb.WriteString("}\n")
|
||||
|
||||
cmd := exec.Command("nft", "-f", "-")
|
||||
cmd.Stdin = strings.NewReader(sb.String())
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("nft apply: %s: %w", strings.TrimSpace(string(out)), err)
|
||||
}
|
||||
|
||||
// Flush connection tracking table so existing sessions are re-evaluated
|
||||
// against the new ruleset. Without this, traffic already tracked as
|
||||
// "established/related" bypasses new drop rules until the session ends.
|
||||
flushConntrack()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// flushConntrack clears the kernel connection tracking table so that all traffic
|
||||
// is re-evaluated against the current nftables ruleset. This is necessary when
|
||||
// adding new drop/reject rules to prevent previously-established sessions from
|
||||
// continuing to bypass the new rules via ct state established,related accept.
|
||||
func flushConntrack() {
|
||||
// Preferred: conntrack utility (part of conntrack-tools package).
|
||||
if err := exec.Command("conntrack", "-F").Run(); err == nil {
|
||||
return
|
||||
}
|
||||
// Fallback: write to /proc (available when nf_conntrack module is loaded).
|
||||
_ = os.WriteFile("/proc/sys/net/netfilter/nf_conntrack_flush", []byte("1"), 0644)
|
||||
}
|
||||
|
||||
// buildRuleLine converts a Rule to a single nftables match+action string.
|
||||
// Returns "" if the rule has no valid action.
|
||||
func buildRuleLine(r Rule) string {
|
||||
if r.Action == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
var parts []string
|
||||
|
||||
if r.InIface != "" {
|
||||
parts = append(parts, fmt.Sprintf("iifname %q", r.InIface))
|
||||
}
|
||||
if r.OutIface != "" {
|
||||
parts = append(parts, fmt.Sprintf("oifname %q", r.OutIface))
|
||||
}
|
||||
if r.SrcAddr != "" {
|
||||
parts = append(parts, "ip saddr "+r.SrcAddr)
|
||||
}
|
||||
if r.DstAddr != "" {
|
||||
parts = append(parts, "ip daddr "+r.DstAddr)
|
||||
}
|
||||
|
||||
proto := strings.ToLower(r.Protocol)
|
||||
switch proto {
|
||||
case "tcp", "udp":
|
||||
if r.SrcPort != "" || r.DstPort != "" {
|
||||
if r.SrcPort != "" {
|
||||
parts = append(parts, proto+" sport "+r.SrcPort)
|
||||
}
|
||||
if r.DstPort != "" {
|
||||
parts = append(parts, proto+" dport "+r.DstPort)
|
||||
}
|
||||
} else {
|
||||
parts = append(parts, "ip protocol "+proto)
|
||||
}
|
||||
case "icmp":
|
||||
parts = append(parts, "ip protocol icmp")
|
||||
}
|
||||
|
||||
parts = append(parts, r.Action)
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
@@ -49,7 +49,9 @@ func HandleInterfaces(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
result := make([]iface, 0, len(names))
|
||||
existingNames := map[string]bool{}
|
||||
for _, name := range names {
|
||||
existingNames[name] = true
|
||||
s, err := network.GetInterfaceStats(name)
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -61,6 +63,25 @@ func HandleInterfaces(w http.ResponseWriter, r *http.Request) {
|
||||
result = append(result, iface{s, hasPending})
|
||||
}
|
||||
|
||||
// Also include pending VLAN configs not yet present in the system.
|
||||
for name, cfg := range network.GetAllPending() {
|
||||
if existingNames[name] || !network.IsVLAN(name) {
|
||||
continue
|
||||
}
|
||||
s := &network.InterfaceStats{
|
||||
Name: name,
|
||||
State: "unknown",
|
||||
Mode: cfg.Mode,
|
||||
IPv6: []string{},
|
||||
}
|
||||
if cfg.Mode == "static" {
|
||||
s.IPv4 = cfg.Address
|
||||
s.IPv4Mask = cfg.Netmask
|
||||
s.Gateway = cfg.Gateway
|
||||
}
|
||||
result = append(result, iface{s, true})
|
||||
}
|
||||
|
||||
ok(w, result)
|
||||
}
|
||||
|
||||
@@ -100,6 +121,13 @@ func HandleInterfaceAction(w http.ResponseWriter, r *http.Request) {
|
||||
err = network.IfDown(name)
|
||||
case "restart":
|
||||
err = network.IfRestart(name)
|
||||
case "delete":
|
||||
if !network.IsVLAN(name) {
|
||||
fail(w, http.StatusBadRequest, "delete is only supported for VLAN interfaces")
|
||||
return
|
||||
}
|
||||
network.ClearPendingConfig(name)
|
||||
err = network.DeleteVLAN(name)
|
||||
default:
|
||||
fail(w, http.StatusBadRequest, "unknown action: "+action)
|
||||
return
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"alpine-router/clients"
|
||||
"alpine-router/config"
|
||||
"alpine-router/dhcp"
|
||||
"alpine-router/nat"
|
||||
)
|
||||
|
||||
func HandleClients(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -88,37 +87,6 @@ func updateClient(mac, hostname string, blocked bool, staticIP string) error {
|
||||
return config.Save(cfg)
|
||||
}
|
||||
|
||||
func applyBlockedFirewall() {
|
||||
if !nat.IsInstalled() {
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Printf("Warning: load config for blocked firewall: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
var blockedIPs []string
|
||||
for _, kd := range cfg.KnownDevices {
|
||||
if kd.Blocked {
|
||||
ip := kd.IP
|
||||
if kd.StaticIP != "" {
|
||||
ip = kd.StaticIP
|
||||
}
|
||||
if ip != "" {
|
||||
blockedIPs = append(blockedIPs, ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
natCfg := &nat.Config{Interfaces: cfg.NAT.Interfaces}
|
||||
if err := nat.ApplyRulesWithBlocked(natCfg, blockedIPs); err != nil {
|
||||
log.Printf("Warning: apply blocked firewall rules: %v", err)
|
||||
} else {
|
||||
log.Printf("Applied firewall rules (%d blocked clients)", len(blockedIPs))
|
||||
}
|
||||
}
|
||||
|
||||
func applyDHCPStaticBindings() {
|
||||
if !dhcp.IsInstalled() {
|
||||
|
||||
100
handlers/firewall.go
Normal file
100
handlers/firewall.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
|
||||
"alpine-router/config"
|
||||
"alpine-router/nat"
|
||||
"alpine-router/network"
|
||||
)
|
||||
|
||||
func HandleFirewall(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
handleFirewallGet(w, r)
|
||||
case http.MethodPost:
|
||||
handleFirewallSave(w, r)
|
||||
default:
|
||||
fail(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func handleFirewallGet(w http.ResponseWriter, r *http.Request) {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Collect interface names for the UI dropdowns.
|
||||
names, _ := network.GetInterfaces()
|
||||
|
||||
ok(w, map[string]interface{}{
|
||||
"installed": nat.IsInstalled(),
|
||||
"rules": cfg.Firewall.Rules,
|
||||
"vlan_isolation": cfg.Firewall.VLANIsolation,
|
||||
"interfaces": names,
|
||||
})
|
||||
}
|
||||
|
||||
func handleFirewallSave(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Rules []config.FirewallRule `json:"rules"`
|
||||
VLANIsolation bool `json:"vlan_isolation"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid json: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Assign IDs to new rules that lack one.
|
||||
for i := range body.Rules {
|
||||
if body.Rules[i].ID == "" {
|
||||
body.Rules[i].ID = fmt.Sprintf("%x", rand.Int63())
|
||||
}
|
||||
}
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "load config: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
cfg.Firewall.Rules = body.Rules
|
||||
cfg.Firewall.VLANIsolation = body.VLANIsolation
|
||||
|
||||
if err := config.Save(cfg); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "save config: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ok(w, map[string]string{"message": "saved"})
|
||||
}
|
||||
|
||||
func HandleFirewallApply(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
fail(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
if !nat.IsInstalled() {
|
||||
fail(w, http.StatusServiceUnavailable, "nftables (nft) не установлен — выполните: apk add nftables")
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "load config: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := applyAllRules(cfg); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "apply: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ok(w, map[string]string{"message": "firewall applied"})
|
||||
}
|
||||
@@ -62,10 +62,10 @@ func HandleNATSave(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := nat.ApplyRules(&cfg); err != nil {
|
||||
if err := applyAllRules(appCfg); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "apply: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ok(w, map[string]string{"message": "nat applied"})
|
||||
}
|
||||
}
|
||||
|
||||
98
handlers/rules.go
Normal file
98
handlers/rules.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"alpine-router/config"
|
||||
"alpine-router/firewall"
|
||||
"alpine-router/nat"
|
||||
"alpine-router/network"
|
||||
)
|
||||
|
||||
// applyAllRules rebuilds the complete nftables ruleset from the current config:
|
||||
// NAT masquerade + user firewall rules + VLAN isolation + blocked clients.
|
||||
func applyAllRules(cfg *config.AppConfig) error {
|
||||
if !nat.IsInstalled() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Collect blocked client IPs.
|
||||
var blockedIPs []string
|
||||
for _, kd := range cfg.KnownDevices {
|
||||
if kd.Blocked {
|
||||
ip := kd.IP
|
||||
if kd.StaticIP != "" {
|
||||
ip = kd.StaticIP
|
||||
}
|
||||
if ip != "" {
|
||||
blockedIPs = append(blockedIPs, ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build the LAN interface set for isolation:
|
||||
// all NAT interfaces + all VLAN interfaces (active + pending).
|
||||
// This ensures native interfaces (eth0) and their VLANs (eth0.100) are all
|
||||
// mutually isolated when VLANIsolation is enabled.
|
||||
seen := map[string]bool{}
|
||||
var lanIfaces []string
|
||||
addLAN := func(name string) {
|
||||
if name != "" && !seen[name] {
|
||||
lanIfaces = append(lanIfaces, name)
|
||||
seen[name] = true
|
||||
}
|
||||
}
|
||||
for _, name := range cfg.NAT.Interfaces {
|
||||
addLAN(name)
|
||||
}
|
||||
names, _ := network.GetInterfaces()
|
||||
for _, name := range names {
|
||||
if network.IsVLAN(name) {
|
||||
addLAN(name)
|
||||
addLAN(network.VLANParent(name)) // include parent (native VLAN) too
|
||||
}
|
||||
}
|
||||
for name := range network.GetAllPending() {
|
||||
if network.IsVLAN(name) {
|
||||
addLAN(name)
|
||||
addLAN(network.VLANParent(name))
|
||||
}
|
||||
}
|
||||
|
||||
// Convert config.FirewallRule → firewall.Rule.
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
return firewall.ApplyAll(
|
||||
firewall.NATConfig{Interfaces: cfg.NAT.Interfaces},
|
||||
firewall.Config{Rules: fwRules, VLANIsolation: cfg.Firewall.VLANIsolation},
|
||||
blockedIPs,
|
||||
lanIfaces,
|
||||
)
|
||||
}
|
||||
|
||||
// applyBlockedFirewall is the async helper called after client updates.
|
||||
func applyBlockedFirewall() {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Printf("Warning: load config for firewall: %v", err)
|
||||
return
|
||||
}
|
||||
if err := applyAllRules(cfg); err != nil {
|
||||
log.Printf("Warning: apply firewall rules: %v", err)
|
||||
}
|
||||
}
|
||||
50
main.go
50
main.go
@@ -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() {
|
||||
|
||||
65
nat/nat.go
65
nat/nat.go
@@ -6,19 +6,13 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const tableName = "alpine-router-nat"
|
||||
|
||||
// Config holds NAT masquerade settings per interface.
|
||||
type Config struct {
|
||||
// Interfaces is the list of LAN interface names for which masquerade is enabled.
|
||||
// Traffic arriving on these interfaces will be NATted to the outgoing WAN interface.
|
||||
Interfaces []string `json:"interfaces"`
|
||||
}
|
||||
|
||||
// configPath returns the path to nat.json next to the running binary.
|
||||
func configPath() string {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
@@ -34,7 +28,6 @@ func IsInstalled() bool {
|
||||
}
|
||||
|
||||
// Load reads the NAT config from disk.
|
||||
// Returns an empty config if the file does not exist yet.
|
||||
func Load() (*Config, error) {
|
||||
data, err := os.ReadFile(configPath())
|
||||
if err != nil {
|
||||
@@ -53,7 +46,7 @@ func Load() (*Config, error) {
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// Save writes the NAT config to the configs/ directory next to the binary.
|
||||
// Save writes the NAT config to the configs/ directory.
|
||||
func Save(cfg *Config) error {
|
||||
p := configPath()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
|
||||
@@ -65,59 +58,3 @@ func Save(cfg *Config) error {
|
||||
}
|
||||
return os.WriteFile(p, data, 0644)
|
||||
}
|
||||
|
||||
// ApplyRules flushes the existing alpine-router NAT table and recreates it
|
||||
// from the provided config. Called on every daemon startup and on config save.
|
||||
//
|
||||
// nftables is used instead of iptables because it applies all rules atomically
|
||||
// in a single kernel call, which is faster and avoids partial-state issues.
|
||||
func ApplyRules(cfg *Config) error {
|
||||
return ApplyRulesWithBlocked(cfg, nil)
|
||||
}
|
||||
|
||||
// ApplyRulesWithBlocked is like ApplyRules but also installs drop rules for
|
||||
// the given list of blocked client IPs.
|
||||
func ApplyRulesWithBlocked(cfg *Config, blockedIPs []string) error {
|
||||
if err := os.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1"), 0644); err != nil {
|
||||
return fmt.Errorf("enable ip_forward: %w", err)
|
||||
}
|
||||
|
||||
exec.Command("nft", "delete", "table", "ip", tableName).Run()
|
||||
|
||||
if len(cfg.Interfaces) == 0 && len(blockedIPs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, "table ip %s {\n", tableName)
|
||||
|
||||
sb.WriteString(" chain forward {\n")
|
||||
sb.WriteString(" type filter hook forward priority filter; policy drop;\n")
|
||||
sb.WriteString(" ct state established,related accept\n")
|
||||
|
||||
for _, ip := range blockedIPs {
|
||||
fmt.Fprintf(&sb, " ip saddr %s drop\n", ip)
|
||||
fmt.Fprintf(&sb, " ip daddr %s drop\n", ip)
|
||||
}
|
||||
|
||||
for _, iface := range cfg.Interfaces {
|
||||
fmt.Fprintf(&sb, " iifname \"%s\" accept\n", iface)
|
||||
}
|
||||
sb.WriteString(" }\n")
|
||||
|
||||
sb.WriteString(" chain postrouting {\n")
|
||||
sb.WriteString(" type nat hook postrouting priority srcnat; policy accept;\n")
|
||||
for _, iface := range cfg.Interfaces {
|
||||
fmt.Fprintf(&sb, " iifname \"%s\" masquerade\n", iface)
|
||||
}
|
||||
sb.WriteString(" }\n")
|
||||
sb.WriteString("}\n")
|
||||
|
||||
cmd := exec.Command("nft", "-f", "-")
|
||||
cmd.Stdin = strings.NewReader(sb.String())
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("nft apply: %s: %w", strings.TrimSpace(string(out)), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -72,6 +72,13 @@ func ApplyPending() map[string]error {
|
||||
ClearPendingConfig(name)
|
||||
continue
|
||||
}
|
||||
// For VLAN interfaces ensure the kernel interface exists before ifup.
|
||||
if IsVLAN(name) {
|
||||
if err := EnsureVLANExists(name); err != nil {
|
||||
errs[name] = err
|
||||
continue
|
||||
}
|
||||
}
|
||||
_ = IfDown(name)
|
||||
if cfg := configs[name]; cfg != nil && cfg.Auto {
|
||||
if err := IfUp(name); err != nil {
|
||||
|
||||
@@ -13,6 +13,7 @@ const ConfigFile = "/etc/network/interfaces"
|
||||
// InterfaceConfig represents one stanza in /etc/network/interfaces.
|
||||
type InterfaceConfig struct {
|
||||
Name string `json:"name"`
|
||||
Label string `json:"label,omitempty"` // display name, stored in config.yaml only
|
||||
Auto bool `json:"auto"`
|
||||
Mode string `json:"mode"` // dhcp, static, loopback, manual
|
||||
Address string `json:"address,omitempty"` // static only
|
||||
@@ -154,12 +155,18 @@ func WriteConfig(configs map[string]*InterfaceConfig) error {
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// loopback first
|
||||
// loopback first, then physical interfaces, then VLANs (sorted within each group)
|
||||
if lo, ok := configs["lo"]; ok {
|
||||
writeStanza(f, lo)
|
||||
}
|
||||
for name, cfg := range configs {
|
||||
if name == "lo" {
|
||||
if name == "lo" || IsVLAN(name) {
|
||||
continue
|
||||
}
|
||||
writeStanza(f, cfg)
|
||||
}
|
||||
for name, cfg := range configs {
|
||||
if !IsVLAN(name) {
|
||||
continue
|
||||
}
|
||||
writeStanza(f, cfg)
|
||||
@@ -188,6 +195,12 @@ func writeStanza(f *os.File, c *InterfaceConfig) {
|
||||
fmt.Fprintf(f, "\tdns-nameservers %s\n", strings.Join(c.DNS, " "))
|
||||
}
|
||||
}
|
||||
// VLAN interfaces need vlan-raw-device unless already in Extra
|
||||
if IsVLAN(c.Name) {
|
||||
if _, ok := c.Extra["vlan-raw-device"]; !ok {
|
||||
fmt.Fprintf(f, "\tvlan-raw-device %s\n", VLANParent(c.Name))
|
||||
}
|
||||
}
|
||||
for k, v := range c.Extra {
|
||||
fmt.Fprintf(f, "\t%s %s\n", k, v)
|
||||
}
|
||||
|
||||
80
network/vlan.go
Normal file
80
network/vlan.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package network
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsVLAN reports whether name is a VLAN interface (e.g. "eth0.100").
|
||||
func IsVLAN(name string) bool {
|
||||
idx := strings.LastIndex(name, ".")
|
||||
if idx <= 0 {
|
||||
return false
|
||||
}
|
||||
suffix := name[idx+1:]
|
||||
if suffix == "" {
|
||||
return false
|
||||
}
|
||||
_, err := strconv.Atoi(suffix)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// VLANParent returns the parent interface (e.g. "eth0.100" → "eth0").
|
||||
func VLANParent(name string) string {
|
||||
idx := strings.LastIndex(name, ".")
|
||||
if idx < 0 {
|
||||
return ""
|
||||
}
|
||||
return name[:idx]
|
||||
}
|
||||
|
||||
// VLANId returns the VLAN ID (e.g. "eth0.100" → 100).
|
||||
func VLANId(name string) int {
|
||||
idx := strings.LastIndex(name, ".")
|
||||
if idx < 0 {
|
||||
return 0
|
||||
}
|
||||
id, _ := strconv.Atoi(name[idx+1:])
|
||||
return id
|
||||
}
|
||||
|
||||
// EnsureVLANExists creates the VLAN interface in the kernel if it doesn't exist.
|
||||
func EnsureVLANExists(name string) error {
|
||||
if _, err := os.Stat("/sys/class/net/" + name); err == nil {
|
||||
return nil
|
||||
}
|
||||
parent := VLANParent(name)
|
||||
id := VLANId(name)
|
||||
if parent == "" || id == 0 {
|
||||
return fmt.Errorf("invalid VLAN name: %s", name)
|
||||
}
|
||||
out, err := exec.Command("ip", "link", "add", "link", parent,
|
||||
"name", name, "type", "vlan", "id", strconv.Itoa(id)).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ip link add %s: %s", name, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteVLAN brings down and removes a VLAN interface and its /etc/network/interfaces stanza.
|
||||
func DeleteVLAN(name string) error {
|
||||
_ = IfDown(name)
|
||||
if _, err := os.Stat("/sys/class/net/" + name); err == nil {
|
||||
out, err2 := exec.Command("ip", "link", "delete", name).CombinedOutput()
|
||||
if err2 != nil {
|
||||
return fmt.Errorf("ip link delete %s: %s", name, strings.TrimSpace(string(out)))
|
||||
}
|
||||
}
|
||||
configs, err := ParseConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, ok := configs[name]; ok {
|
||||
delete(configs, name)
|
||||
return WriteConfig(configs)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
166
public/app.js
166
public/app.js
@@ -5,7 +5,8 @@
|
||||
const state = {
|
||||
interfaces: [], // latest data from /api/interfaces
|
||||
pending: [], // interface names with pending config
|
||||
configModal: null, // name of interface being configured
|
||||
configModal: null, // name of interface being configured (null = new VLAN)
|
||||
configModalParent: null, // parent interface when creating a new VLAN
|
||||
nat: null, // {installed, interfaces} from /api/nat
|
||||
};
|
||||
|
||||
@@ -29,6 +30,19 @@ const get = (path) => api('GET', path);
|
||||
const post = (path, body) => api('POST', path, body);
|
||||
const del = (path) => api('DELETE', path);
|
||||
|
||||
// ── VLAN helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
function isVLAN(name) {
|
||||
return /\.\d+$/.test(name);
|
||||
}
|
||||
function vlanParent(name) {
|
||||
return name.replace(/\.\d+$/, '');
|
||||
}
|
||||
function vlanId(name) {
|
||||
const m = name.match(/\.(\d+)$/);
|
||||
return m ? parseInt(m[1]) : 0;
|
||||
}
|
||||
|
||||
// ── Format helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
function fmtBytes(n) {
|
||||
@@ -56,9 +70,24 @@ function renderAll() {
|
||||
const grid = document.getElementById('ifaceGrid');
|
||||
grid.innerHTML = '';
|
||||
|
||||
state.interfaces.forEach(iface => {
|
||||
grid.appendChild(buildCard(iface));
|
||||
});
|
||||
// Group VLANs by parent
|
||||
const vlansByParent = {};
|
||||
const physicals = [];
|
||||
|
||||
for (const iface of state.interfaces) {
|
||||
if (isVLAN(iface.name)) {
|
||||
const p = vlanParent(iface.name);
|
||||
if (!vlansByParent[p]) vlansByParent[p] = [];
|
||||
vlansByParent[p].push(iface);
|
||||
} else {
|
||||
physicals.push(iface);
|
||||
}
|
||||
}
|
||||
|
||||
for (const iface of physicals) {
|
||||
const vlans = vlansByParent[iface.name] || [];
|
||||
grid.appendChild(buildCard(iface, vlans));
|
||||
}
|
||||
|
||||
document.getElementById('loading').classList.add('hidden');
|
||||
grid.classList.remove('hidden');
|
||||
@@ -66,9 +95,10 @@ function renderAll() {
|
||||
renderPendingBanner();
|
||||
}
|
||||
|
||||
function buildCard(iface) {
|
||||
function buildCard(iface, vlans) {
|
||||
const hasPending = state.pending.includes(iface.name);
|
||||
const sc = stateClass(iface.state);
|
||||
const isLo = iface.name === 'lo' || iface.mode === 'loopback';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'iface-card' + (hasPending ? ' has-pending' : '');
|
||||
@@ -129,11 +159,56 @@ function buildCard(iface) {
|
||||
<button class="btn btn-ghost btn-sm" data-action="restart" data-iface="${iface.name}">RESTART</button>
|
||||
<button class="btn btn-primary btn-sm" data-action="config" data-iface="${iface.name}" style="margin-left:auto">CONFIG</button>
|
||||
</div>
|
||||
|
||||
${!isLo ? buildVLANSection(iface.name, vlans) : ''}
|
||||
`;
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
function buildVLANSection(parentName, vlans) {
|
||||
const rows = vlans.map(v => {
|
||||
const sc = stateClass(v.state);
|
||||
const hasPending = state.pending.includes(v.name);
|
||||
const ip = v.ipv4
|
||||
? v.ipv4 + (v.ipv4_mask ? ' / ' + v.ipv4_mask : '')
|
||||
: '<span class="none">—</span>';
|
||||
return `
|
||||
<div class="vlan-row" data-name="${v.name}">
|
||||
<div class="vlan-row-left">
|
||||
<span class="state-dot ${sc}" style="width:8px;height:8px"></span>
|
||||
<span class="vlan-iface-name">${v.name}</span>
|
||||
<span class="vlan-id-tag">VLAN ${vlanId(v.name)}</span>
|
||||
<span class="mode-badge ${v.mode || 'unknown'}">${modeLabel(v.mode)}</span>
|
||||
${hasPending ? '<span class="pending-badge">несохранено</span>' : ''}
|
||||
</div>
|
||||
<div class="vlan-row-info">${ip}</div>
|
||||
<div class="vlan-row-actions">
|
||||
<button class="btn btn-success btn-xs" data-action="up" data-iface="${v.name}">ON</button>
|
||||
<button class="btn btn-danger btn-xs" data-action="down" data-iface="${v.name}">OFF</button>
|
||||
<button class="btn btn-primary btn-xs" data-action="config" data-iface="${v.name}">CONFIG</button>
|
||||
<button class="btn btn-danger btn-xs" data-action="delete" data-iface="${v.name}" title="Удалить VLAN">✕</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
const empty = vlans.length === 0
|
||||
? `<div class="vlan-empty">Нет тегированных VLAN</div>`
|
||||
: '';
|
||||
|
||||
return `
|
||||
<div class="vlan-section">
|
||||
<div class="vlan-header">
|
||||
<span class="vlan-title">Теговые VLAN</span>
|
||||
<button class="btn btn-ghost btn-xs" data-action="addvlan" data-iface="${parentName}">+ Добавить</button>
|
||||
</div>
|
||||
<div class="vlan-list">
|
||||
${rows}
|
||||
${empty}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderPendingBanner() {
|
||||
const banner = document.getElementById('pendingBanner');
|
||||
const list = document.getElementById('pendingList');
|
||||
@@ -164,6 +239,18 @@ async function loadAll() {
|
||||
// ── Interface actions ─────────────────────────────────────────────────────────
|
||||
|
||||
async function doAction(name, action) {
|
||||
if (action === 'delete') {
|
||||
if (!confirm(`Удалить VLAN ${name}?`)) return;
|
||||
try {
|
||||
await post(`/api/interfaces/${name}/delete`);
|
||||
showToast(`${name}: удалён`, 'success');
|
||||
await loadAll();
|
||||
} catch (e) {
|
||||
showToast(`${name} delete: ${e.message}`, 'error');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = document.querySelector(`[data-action="${action}"][data-iface="${name}"]`);
|
||||
if (btn) { btn.disabled = true; btn.textContent = '...'; }
|
||||
|
||||
@@ -182,8 +269,21 @@ async function doAction(name, action) {
|
||||
|
||||
async function openConfig(name) {
|
||||
state.configModal = name;
|
||||
state.configModalParent = null;
|
||||
document.getElementById('modalTitle').textContent = `Настройка: ${name}`;
|
||||
|
||||
// Show/hide VLAN ID field
|
||||
const vlanSection = document.getElementById('vlanIdSection');
|
||||
const vlanInput = document.getElementById('cfgVLANId');
|
||||
if (isVLAN(name)) {
|
||||
vlanSection.classList.remove('hidden');
|
||||
vlanInput.value = vlanId(name);
|
||||
vlanInput.readOnly = true;
|
||||
} else {
|
||||
vlanSection.classList.add('hidden');
|
||||
vlanInput.readOnly = false;
|
||||
}
|
||||
|
||||
try {
|
||||
const [{ config, pending }, natData] = await Promise.all([
|
||||
get(`/api/config/${name}`),
|
||||
@@ -197,6 +297,26 @@ async function openConfig(name) {
|
||||
}
|
||||
}
|
||||
|
||||
async function openNewVLAN(parentName) {
|
||||
state.configModal = null;
|
||||
state.configModalParent = parentName;
|
||||
document.getElementById('modalTitle').textContent = `Новый VLAN на ${parentName}`;
|
||||
|
||||
const vlanSection = document.getElementById('vlanIdSection');
|
||||
const vlanInput = document.getElementById('cfgVLANId');
|
||||
vlanSection.classList.remove('hidden');
|
||||
vlanInput.readOnly = false;
|
||||
vlanInput.value = '';
|
||||
|
||||
try {
|
||||
const natData = await get('/api/nat').catch(() => null);
|
||||
if (natData) state.nat = natData;
|
||||
} catch (_) {}
|
||||
|
||||
fillForm({ auto: true, mode: 'static' }, false, '');
|
||||
document.getElementById('modal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
function fillForm(cfg, pending, name) {
|
||||
document.getElementById('cfgAuto').checked = !!cfg.auto;
|
||||
document.getElementById('cfgAddress').value = cfg.address || '';
|
||||
@@ -208,9 +328,8 @@ function fillForm(cfg, pending, name) {
|
||||
setMode(mode);
|
||||
|
||||
// Mark pending visually
|
||||
const title = document.getElementById('modalTitle');
|
||||
if (pending) {
|
||||
title.textContent = `Настройка: ${state.configModal} (несохранённые изменения)`;
|
||||
if (pending && name) {
|
||||
document.getElementById('modalTitle').textContent = `Настройка: ${name} (несохранённые изменения)`;
|
||||
}
|
||||
|
||||
// NAT section — show for all non-loopback interfaces
|
||||
@@ -244,11 +363,29 @@ function closeModal() {
|
||||
document.getElementById('modal').classList.add('hidden');
|
||||
document.getElementById('configForm').reset();
|
||||
state.configModal = null;
|
||||
state.configModalParent = null;
|
||||
}
|
||||
|
||||
async function saveConfig() {
|
||||
const name = state.configModal;
|
||||
if (!name) return;
|
||||
let name = state.configModal;
|
||||
|
||||
if (!name) {
|
||||
// New VLAN — build name from parent + VLAN ID
|
||||
const parent = state.configModalParent;
|
||||
const id = parseInt(document.getElementById('cfgVLANId').value);
|
||||
if (!parent) return;
|
||||
if (!id || id < 1 || id > 4094) {
|
||||
showToast('Укажите корректный VLAN ID (1–4094)', 'error');
|
||||
return;
|
||||
}
|
||||
name = `${parent}.${id}`;
|
||||
|
||||
// Check for duplicate
|
||||
if (state.interfaces.find(i => i.name === name)) {
|
||||
showToast(`VLAN ${name} уже существует`, 'error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const mode = currentMode();
|
||||
const cfg = {
|
||||
@@ -262,7 +399,6 @@ async function saveConfig() {
|
||||
extra: {},
|
||||
};
|
||||
|
||||
// Basic validation for static
|
||||
if (mode === 'static' && !cfg.address) {
|
||||
showToast('Укажите IP-адрес', 'error');
|
||||
return;
|
||||
@@ -346,6 +482,8 @@ document.getElementById('ifaceGrid').addEventListener('click', e => {
|
||||
const { action, iface } = btn.dataset;
|
||||
if (action === 'config') {
|
||||
openConfig(iface);
|
||||
} else if (action === 'addvlan') {
|
||||
openNewVLAN(iface);
|
||||
} else {
|
||||
doAction(iface, action);
|
||||
}
|
||||
@@ -378,11 +516,5 @@ setInterval(loadAll, 10000);
|
||||
// ── Init ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
(async () => {
|
||||
// Try to get hostname
|
||||
try {
|
||||
const res = await fetch('/api/interfaces');
|
||||
// hostname from Location header or just skip
|
||||
} catch (_) {}
|
||||
|
||||
await loadAll();
|
||||
})();
|
||||
|
||||
@@ -50,9 +50,17 @@
|
||||
</svg>
|
||||
Клиенты
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link">
|
||||
<a href="/firewall.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
||||
<path d="M9 12l2 2 4-4"/>
|
||||
</svg>
|
||||
Файрвол
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
|
||||
</svg>
|
||||
Прокси
|
||||
</a>
|
||||
|
||||
@@ -50,9 +50,17 @@
|
||||
</svg>
|
||||
Клиенты
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link">
|
||||
<a href="/firewall.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
||||
<path d="M9 12l2 2 4-4"/>
|
||||
</svg>
|
||||
Файрвол
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
|
||||
</svg>
|
||||
Прокси
|
||||
</a>
|
||||
|
||||
234
public/firewall.html
Normal file
234
public/firewall.html
Normal file
@@ -0,0 +1,234 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Файрвол — AlpineRouter</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header>
|
||||
<div class="header-left">
|
||||
<svg class="logo" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M12 2L2 7l10 5 10-5-10-5z"/>
|
||||
<path d="M2 17l10 5 10-5"/>
|
||||
<path d="M2 12l10 5 10-5"/>
|
||||
</svg>
|
||||
<h1>AlpineRouter</h1>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<button class="btn btn-ghost" id="refreshBtn" title="Обновить">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
|
||||
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/>
|
||||
<path d="M3 3v5h5"/>
|
||||
</svg>
|
||||
Обновить
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav class="tab-nav">
|
||||
<a href="/" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<path d="M12 2L2 7l10 5 10-5-10-5z"/>
|
||||
<path d="M2 17l10 5 10-5"/>
|
||||
<path d="M2 12l10 5 10-5"/>
|
||||
</svg>
|
||||
Интерфейсы
|
||||
</a>
|
||||
<a href="/dhcp.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<path d="M5 12h14M12 5l7 7-7 7"/>
|
||||
</svg>
|
||||
DHCP сервер
|
||||
</a>
|
||||
<a href="/clients.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<circle cx="9" cy="7" r="4"/><path d="M3 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2"/>
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75M21 21v-2a4 4 0 0 0-3-3.87"/>
|
||||
</svg>
|
||||
Клиенты
|
||||
</a>
|
||||
<a href="/firewall.html" class="tab-link active">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
||||
<path d="M9 12l2 2 4-4"/>
|
||||
</svg>
|
||||
Файрвол
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
|
||||
</svg>
|
||||
Прокси
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
<main class="fw-main">
|
||||
|
||||
<div id="notInstalledBanner" class="alert alert-error hidden">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18">
|
||||
<circle cx="12" cy="12" r="10"/><path d="M12 8v4m0 4h.01"/>
|
||||
</svg>
|
||||
<div>
|
||||
<strong>nftables не установлен.</strong>
|
||||
Для работы файрвола выполните на роутере:
|
||||
<code>apk add nftables</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Top controls bar -->
|
||||
<div class="fw-toolbar">
|
||||
<div class="fw-toolbar-left">
|
||||
<label class="toggle-label" id="vlanIsolationLabel" title="Запрещает трафик между VLAN-интерфейсами по умолчанию. Явные правила разрешения выше имеют приоритет.">
|
||||
<input type="checkbox" id="vlanIsolation">
|
||||
<span class="toggle-slider"></span>
|
||||
<span>Изоляция VLAN</span>
|
||||
</label>
|
||||
<span class="fw-hint">— теговые VLAN не видят друг друга; NAT — только выход в интернет</span>
|
||||
</div>
|
||||
<div class="fw-toolbar-right">
|
||||
<button class="btn btn-ghost btn-sm" id="addRuleBtn">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M12 5v14M5 12h14"/></svg>
|
||||
Добавить правило
|
||||
</button>
|
||||
<button class="btn btn-primary" id="applyBtn">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M5 12l5 5L20 7"/></svg>
|
||||
Сохранить и применить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Rules table -->
|
||||
<div class="fw-card">
|
||||
<div class="fw-table-wrap">
|
||||
<table class="fw-table" id="rulesTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="col-drag"></th>
|
||||
<th class="col-num">#</th>
|
||||
<th class="col-en">Вкл</th>
|
||||
<th class="col-action">Действие</th>
|
||||
<th class="col-proto">Протокол</th>
|
||||
<th class="col-iface">Вх. интерфейс</th>
|
||||
<th class="col-iface">Вых. интерфейс</th>
|
||||
<th class="col-addr">Источник</th>
|
||||
<th class="col-addr">Назначение</th>
|
||||
<th class="col-comment">Комментарий</th>
|
||||
<th class="col-btns"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="rulesTbody">
|
||||
<tr id="emptyRow">
|
||||
<td colspan="11" class="fw-empty">
|
||||
Правил нет. Нажмите «Добавить правило» для создания.
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="fw-policy-note">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
||||
<circle cx="12" cy="12" r="10"/><path d="M12 8v4m0 4h.01"/>
|
||||
</svg>
|
||||
Политика по умолчанию: <strong>DROP</strong> — весь трафик запрещён, если не разрешён явно выше или через NAT.
|
||||
Трафик established/related всегда разрешается.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
|
||||
<!-- Rule Edit Modal -->
|
||||
<div id="ruleModal" class="modal hidden" role="dialog" aria-modal="true">
|
||||
<div class="modal-backdrop" id="ruleModalBackdrop"></div>
|
||||
<div class="modal-box modal-wide">
|
||||
<div class="modal-header">
|
||||
<h2 id="ruleModalTitle">Добавить правило</h2>
|
||||
<button class="btn-icon" id="closeRuleModal">✕</button>
|
||||
</div>
|
||||
|
||||
<form id="ruleForm" autocomplete="off">
|
||||
|
||||
<div class="form-row">
|
||||
<label for="rComment">Комментарий</label>
|
||||
<input type="text" id="rComment" placeholder="Описание правила (необязательно)">
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>Действие</label>
|
||||
<div class="segmented" id="actionSwitch">
|
||||
<button type="button" class="seg-btn active" data-val="accept">Разрешить</button>
|
||||
<button type="button" class="seg-btn" data-val="drop">Запретить</button>
|
||||
<button type="button" class="seg-btn" data-val="reject">Отклонить</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>Протокол</label>
|
||||
<div class="segmented" id="protoSwitch">
|
||||
<button type="button" class="seg-btn active" data-val="all">Любой</button>
|
||||
<button type="button" class="seg-btn" data-val="tcp">TCP</button>
|
||||
<button type="button" class="seg-btn" data-val="udp">UDP</button>
|
||||
<button type="button" class="seg-btn" data-val="icmp">ICMP</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-grid-2">
|
||||
<div class="form-row">
|
||||
<label for="rInIface">Входящий интерфейс</label>
|
||||
<input type="text" id="rInIface" placeholder="eth0, eth0.100 … (пусто = любой)" list="ifaceList">
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="rOutIface">Исходящий интерфейс</label>
|
||||
<input type="text" id="rOutIface" placeholder="eth1 … (пусто = любой)" list="ifaceList">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-grid-2">
|
||||
<div class="form-row">
|
||||
<label for="rSrcAddr">Источник (адрес/подсеть)</label>
|
||||
<input type="text" id="rSrcAddr" placeholder="192.168.1.0/24 или 10.0.0.5">
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="rDstAddr">Назначение (адрес/подсеть)</label>
|
||||
<input type="text" id="rDstAddr" placeholder="10.0.0.0/24 или 8.8.8.8">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-grid-2" id="portFields">
|
||||
<div class="form-row">
|
||||
<label for="rSrcPort">Порт источника</label>
|
||||
<input type="text" id="rSrcPort" placeholder="80 или 1000-2000">
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="rDstPort">Порт назначения</label>
|
||||
<input type="text" id="rDstPort" placeholder="443 или 8080-8090">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="rEnabled" checked>
|
||||
<span>Правило активно</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-ghost" id="cancelRuleBtn">Отмена</button>
|
||||
<button class="btn btn-primary" id="saveRuleBtn">Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<datalist id="ifaceList"></datalist>
|
||||
|
||||
<div id="toast" class="toast hidden"></div>
|
||||
|
||||
<script src="firewall.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
330
public/firewall.js
Normal file
330
public/firewall.js
Normal file
@@ -0,0 +1,330 @@
|
||||
'use strict';
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const state = {
|
||||
rules: [], // current rule list (order matters)
|
||||
interfaces: [], // available interface names for autocomplete
|
||||
editIdx: -1, // index in state.rules being edited (-1 = new)
|
||||
};
|
||||
|
||||
// ── API helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
async function api(method, path, body) {
|
||||
const res = await fetch(path, {
|
||||
method,
|
||||
headers: body ? { 'Content-Type': 'application/json' } : {},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok || !json.success) throw new Error(json.error || `HTTP ${res.status}`);
|
||||
return json.data;
|
||||
}
|
||||
const get = p => api('GET', p);
|
||||
const post = (p, b) => api('POST', p, b);
|
||||
|
||||
// ── Load ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function loadAll() {
|
||||
try {
|
||||
const data = await get('/api/firewall');
|
||||
state.rules = data.rules || [];
|
||||
state.interfaces = data.interfaces || [];
|
||||
document.getElementById('vlanIsolation').checked = !!data.vlan_isolation;
|
||||
|
||||
const notInstalled = document.getElementById('notInstalledBanner');
|
||||
if (!data.installed) {
|
||||
notInstalled.classList.remove('hidden');
|
||||
} else {
|
||||
notInstalled.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Populate datalist for interface autocomplete.
|
||||
const dl = document.getElementById('ifaceList');
|
||||
dl.innerHTML = state.interfaces.map(n => `<option value="${n}">`).join('');
|
||||
|
||||
renderRules();
|
||||
} catch (e) {
|
||||
showToast('Ошибка загрузки: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const ACTION_LABELS = { accept: 'Разрешить', drop: 'Запретить', reject: 'Отклонить' };
|
||||
const ACTION_CLASS = { accept: 'fw-accept', drop: 'fw-drop', reject: 'fw-reject' };
|
||||
const PROTO_LABELS = { all: 'Любой', tcp: 'TCP', udp: 'UDP', icmp: 'ICMP' };
|
||||
|
||||
function addrPort(addr, port) {
|
||||
if (!addr && !port) return '<span class="none">любой</span>';
|
||||
const a = addr || '<span class="none">*</span>';
|
||||
const p = port ? `:<b>${port}</b>` : '';
|
||||
return a + p;
|
||||
}
|
||||
|
||||
function renderRules() {
|
||||
const tbody = document.getElementById('rulesTbody');
|
||||
const emptyRow = document.getElementById('emptyRow');
|
||||
|
||||
// Remove all rows except the empty placeholder.
|
||||
[...tbody.querySelectorAll('.fw-row')].forEach(r => r.remove());
|
||||
|
||||
if (state.rules.length === 0) {
|
||||
emptyRow.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
emptyRow.classList.add('hidden');
|
||||
|
||||
state.rules.forEach((rule, idx) => {
|
||||
const tr = document.createElement('tr');
|
||||
tr.className = 'fw-row' + (rule.enabled ? '' : ' fw-row-disabled');
|
||||
tr.draggable = true;
|
||||
tr.dataset.ruleId = rule.id || String(idx);
|
||||
|
||||
const inIface = rule.in_iface || '<span class="none">—</span>';
|
||||
const outIface = rule.out_iface || '<span class="none">—</span>';
|
||||
|
||||
tr.innerHTML = `
|
||||
<td class="col-drag"><span class="drag-handle" title="Перетащить">⠿</span></td>
|
||||
<td class="col-num">${idx + 1}</td>
|
||||
<td class="col-en">
|
||||
<label class="mini-toggle" title="${rule.enabled ? 'Отключить' : 'Включить'}">
|
||||
<input type="checkbox" data-idx="${idx}" class="rule-toggle" ${rule.enabled ? 'checked' : ''}>
|
||||
<span class="mini-slider"></span>
|
||||
</label>
|
||||
</td>
|
||||
<td class="col-action"><span class="action-badge ${ACTION_CLASS[rule.action] || 'fw-drop'}">${ACTION_LABELS[rule.action] || rule.action}</span></td>
|
||||
<td class="col-proto">${PROTO_LABELS[rule.protocol] || rule.protocol || 'Любой'}</td>
|
||||
<td class="col-iface">${inIface}</td>
|
||||
<td class="col-iface">${outIface}</td>
|
||||
<td class="col-addr">${addrPort(rule.src_addr, rule.src_port)}</td>
|
||||
<td class="col-addr">${addrPort(rule.dst_addr, rule.dst_port)}</td>
|
||||
<td class="col-comment">${rule.comment ? `<span class="fw-comment">${esc(rule.comment)}</span>` : '<span class="none">—</span>'}</td>
|
||||
<td class="col-btns">
|
||||
<button class="btn btn-ghost btn-xs rule-edit" data-idx="${idx}" title="Редактировать">✎</button>
|
||||
<button class="btn btn-danger btn-xs rule-del" data-idx="${idx}" title="Удалить">✕</button>
|
||||
</td>
|
||||
`;
|
||||
|
||||
addDragHandlers(tr);
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
}
|
||||
|
||||
function esc(s) {
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
// ── Drag-to-reorder ───────────────────────────────────────────────────────────
|
||||
|
||||
let dragSrc = null;
|
||||
|
||||
function addDragHandlers(row) {
|
||||
row.addEventListener('dragstart', e => {
|
||||
dragSrc = row;
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
setTimeout(() => row.classList.add('dragging'), 0);
|
||||
});
|
||||
row.addEventListener('dragend', () => {
|
||||
row.classList.remove('dragging');
|
||||
document.querySelectorAll('.fw-row').forEach(r => r.classList.remove('drag-over'));
|
||||
commitDragOrder();
|
||||
dragSrc = null;
|
||||
});
|
||||
row.addEventListener('dragover', e => {
|
||||
e.preventDefault();
|
||||
if (!dragSrc || dragSrc === row) return;
|
||||
document.querySelectorAll('.fw-row').forEach(r => r.classList.remove('drag-over'));
|
||||
row.classList.add('drag-over');
|
||||
});
|
||||
row.addEventListener('drop', e => {
|
||||
e.preventDefault();
|
||||
if (!dragSrc || dragSrc === row) return;
|
||||
const tbody = row.parentNode;
|
||||
const rows = [...tbody.querySelectorAll('.fw-row')];
|
||||
const si = rows.indexOf(dragSrc);
|
||||
const ti = rows.indexOf(row);
|
||||
if (si < ti) {
|
||||
tbody.insertBefore(dragSrc, row.nextSibling);
|
||||
} else {
|
||||
tbody.insertBefore(dragSrc, row);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function commitDragOrder() {
|
||||
const rows = [...document.querySelectorAll('.fw-row')];
|
||||
const byId = {};
|
||||
state.rules.forEach(r => { byId[r.id] = r; });
|
||||
|
||||
const newRules = [];
|
||||
rows.forEach((row, i) => {
|
||||
const id = row.dataset.ruleId;
|
||||
const r = byId[id] || state.rules[parseInt(id)];
|
||||
if (r) newRules.push(r);
|
||||
});
|
||||
state.rules = newRules;
|
||||
renderRules();
|
||||
}
|
||||
|
||||
// ── Modal ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
function openModal(idx) {
|
||||
state.editIdx = idx;
|
||||
const isNew = idx === -1;
|
||||
document.getElementById('ruleModalTitle').textContent = isNew ? 'Добавить правило' : 'Редактировать правило';
|
||||
|
||||
const rule = isNew ? { enabled: true, action: 'accept', protocol: 'all' } : state.rules[idx];
|
||||
|
||||
document.getElementById('rEnabled').checked = rule.enabled !== false;
|
||||
document.getElementById('rComment').value = rule.comment || '';
|
||||
document.getElementById('rSrcAddr').value = rule.src_addr || '';
|
||||
document.getElementById('rSrcPort').value = rule.src_port || '';
|
||||
document.getElementById('rDstAddr').value = rule.dst_addr || '';
|
||||
document.getElementById('rDstPort').value = rule.dst_port || '';
|
||||
document.getElementById('rInIface').value = rule.in_iface || '';
|
||||
document.getElementById('rOutIface').value = rule.out_iface || '';
|
||||
|
||||
setSegmented('actionSwitch', rule.action || 'accept');
|
||||
setSegmented('protoSwitch', rule.protocol || 'all');
|
||||
updatePortFields(rule.protocol || 'all');
|
||||
|
||||
document.getElementById('ruleModal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
document.getElementById('ruleModal').classList.add('hidden');
|
||||
document.getElementById('ruleForm').reset();
|
||||
}
|
||||
|
||||
function setSegmented(id, val) {
|
||||
document.querySelectorAll(`#${id} .seg-btn`).forEach(b => {
|
||||
b.classList.toggle('active', b.dataset.val === val);
|
||||
});
|
||||
}
|
||||
|
||||
function getSegmented(id) {
|
||||
return document.querySelector(`#${id} .seg-btn.active`)?.dataset.val ?? '';
|
||||
}
|
||||
|
||||
function updatePortFields(proto) {
|
||||
const show = proto === 'tcp' || proto === 'udp';
|
||||
document.getElementById('portFields').classList.toggle('hidden', !show);
|
||||
}
|
||||
|
||||
function saveRule() {
|
||||
const rule = {
|
||||
id: state.editIdx === -1 ? genId() : (state.rules[state.editIdx]?.id || genId()),
|
||||
enabled: document.getElementById('rEnabled').checked,
|
||||
action: getSegmented('actionSwitch'),
|
||||
protocol: getSegmented('protoSwitch'),
|
||||
src_addr: document.getElementById('rSrcAddr').value.trim(),
|
||||
src_port: document.getElementById('rSrcPort').value.trim(),
|
||||
dst_addr: document.getElementById('rDstAddr').value.trim(),
|
||||
dst_port: document.getElementById('rDstPort').value.trim(),
|
||||
in_iface: document.getElementById('rInIface').value.trim(),
|
||||
out_iface: document.getElementById('rOutIface').value.trim(),
|
||||
comment: document.getElementById('rComment').value.trim(),
|
||||
};
|
||||
|
||||
if (!rule.action) { showToast('Выберите действие', 'error'); return; }
|
||||
|
||||
if (state.editIdx === -1) {
|
||||
state.rules.push(rule);
|
||||
} else {
|
||||
state.rules[state.editIdx] = rule;
|
||||
}
|
||||
|
||||
closeModal();
|
||||
renderRules();
|
||||
}
|
||||
|
||||
function genId() {
|
||||
return Math.random().toString(36).slice(2, 10);
|
||||
}
|
||||
|
||||
// ── Save & Apply ──────────────────────────────────────────────────────────────
|
||||
|
||||
async function saveAndApply() {
|
||||
const btn = document.getElementById('applyBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Применяю...';
|
||||
|
||||
try {
|
||||
await post('/api/firewall', {
|
||||
rules: state.rules,
|
||||
vlan_isolation: document.getElementById('vlanIsolation').checked,
|
||||
});
|
||||
await post('/api/firewall/apply');
|
||||
showToast('Правила файрвола применены', 'success');
|
||||
} catch (e) {
|
||||
showToast('Ошибка: ' + e.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Сохранить и применить';
|
||||
}
|
||||
}
|
||||
|
||||
// ── Toast ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
let toastTimer;
|
||||
function showToast(msg, type = 'info') {
|
||||
const t = document.getElementById('toast');
|
||||
t.textContent = msg;
|
||||
t.className = `toast ${type}`;
|
||||
t.classList.remove('hidden');
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => t.classList.add('hidden'), 3500);
|
||||
}
|
||||
|
||||
// ── Event wiring ──────────────────────────────────────────────────────────────
|
||||
|
||||
document.getElementById('refreshBtn').addEventListener('click', loadAll);
|
||||
document.getElementById('applyBtn').addEventListener('click', saveAndApply);
|
||||
document.getElementById('addRuleBtn').addEventListener('click', () => openModal(-1));
|
||||
|
||||
// Table events (delegated)
|
||||
document.getElementById('rulesTbody').addEventListener('click', e => {
|
||||
const editBtn = e.target.closest('.rule-edit');
|
||||
const delBtn = e.target.closest('.rule-del');
|
||||
if (editBtn) { openModal(parseInt(editBtn.dataset.idx)); return; }
|
||||
if (delBtn) {
|
||||
const idx = parseInt(delBtn.dataset.idx);
|
||||
if (confirm(`Удалить правило ${idx + 1}?`)) {
|
||||
state.rules.splice(idx, 1);
|
||||
renderRules();
|
||||
}
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('rulesTbody').addEventListener('change', e => {
|
||||
const toggle = e.target.closest('.rule-toggle');
|
||||
if (toggle) {
|
||||
const idx = parseInt(toggle.dataset.idx);
|
||||
state.rules[idx].enabled = toggle.checked;
|
||||
renderRules();
|
||||
}
|
||||
});
|
||||
|
||||
// Modal
|
||||
document.getElementById('closeRuleModal').addEventListener('click', closeModal);
|
||||
document.getElementById('cancelRuleBtn').addEventListener('click', closeModal);
|
||||
document.getElementById('ruleModalBackdrop').addEventListener('click', closeModal);
|
||||
document.getElementById('saveRuleBtn').addEventListener('click', saveRule);
|
||||
document.getElementById('ruleForm').addEventListener('submit', e => { e.preventDefault(); saveRule(); });
|
||||
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
|
||||
|
||||
// Segmented switchers
|
||||
document.getElementById('actionSwitch').addEventListener('click', e => {
|
||||
const b = e.target.closest('.seg-btn');
|
||||
if (b) setSegmented('actionSwitch', b.dataset.val);
|
||||
});
|
||||
document.getElementById('protoSwitch').addEventListener('click', e => {
|
||||
const b = e.target.closest('.seg-btn');
|
||||
if (b) { setSegmented('protoSwitch', b.dataset.val); updatePortFields(b.dataset.val); }
|
||||
});
|
||||
|
||||
// ── Init ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
loadAll();
|
||||
@@ -62,9 +62,17 @@
|
||||
</svg>
|
||||
Клиенты
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link">
|
||||
<a href="/firewall.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
||||
<path d="M9 12l2 2 4-4"/>
|
||||
</svg>
|
||||
Файрвол
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
|
||||
</svg>
|
||||
Прокси
|
||||
</a>
|
||||
@@ -88,6 +96,16 @@
|
||||
</div>
|
||||
|
||||
<form id="configForm" autocomplete="off">
|
||||
|
||||
<!-- VLAN ID — shown only for VLAN interfaces -->
|
||||
<div id="vlanIdSection" class="hidden">
|
||||
<div class="form-row">
|
||||
<label for="cfgVLANId">VLAN ID <span class="form-hint-inline">(1–4094)</span></label>
|
||||
<input type="number" id="cfgVLANId" min="1" max="4094" placeholder="100">
|
||||
</div>
|
||||
<div class="form-divider"></div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="cfgAuto">
|
||||
|
||||
@@ -44,9 +44,17 @@
|
||||
</svg>
|
||||
Клиенты
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link active">
|
||||
<a href="/firewall.html" class="tab-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
||||
<path d="M9 12l2 2 4-4"/>
|
||||
</svg>
|
||||
Файрвол
|
||||
</a>
|
||||
<a href="/proxy.html" class="tab-link active">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
|
||||
</svg>
|
||||
Прокси
|
||||
</a>
|
||||
|
||||
288
public/style.css
288
public/style.css
@@ -1123,6 +1123,294 @@ select {
|
||||
padding-right: 30px;
|
||||
}
|
||||
|
||||
/* ── VLAN section inside interface card ── */
|
||||
.vlan-section {
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 10px 16px 12px;
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.vlan-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.vlan-title {
|
||||
font-size: .75rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.btn-xs {
|
||||
padding: 3px 9px;
|
||||
font-size: .75rem;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.vlan-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.vlan-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 7px 10px;
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
transition: border-color .2s;
|
||||
}
|
||||
|
||||
.vlan-row:hover { border-color: var(--border-hi); }
|
||||
|
||||
.vlan-row-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.vlan-iface-name {
|
||||
font-size: .85rem;
|
||||
font-weight: 700;
|
||||
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.vlan-id-tag {
|
||||
font-size: .68rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: .06em;
|
||||
text-transform: uppercase;
|
||||
padding: 2px 8px;
|
||||
border-radius: 20px;
|
||||
background: rgba(0, 212, 255, 0.06);
|
||||
border: 1px solid rgba(0, 212, 255, 0.2);
|
||||
color: var(--text-dim);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.vlan-row-info {
|
||||
font-size: .8rem;
|
||||
color: var(--text-dim);
|
||||
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
|
||||
.vlan-row-actions {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.vlan-empty {
|
||||
font-size: .8rem;
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
padding: 8px 0 4px;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* Modal hint inline */
|
||||
.form-hint-inline {
|
||||
font-size: .78rem;
|
||||
color: var(--muted);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
/* ── Firewall page ── */
|
||||
.fw-main {
|
||||
padding: 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.fw-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 14px 20px;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
.fw-toolbar-left { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
|
||||
.fw-toolbar-right { display: flex; align-items: center; gap: 10px; }
|
||||
.fw-hint { font-size: .78rem; color: var(--muted); }
|
||||
|
||||
.fw-card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.fw-table-wrap { overflow-x: auto; }
|
||||
|
||||
.fw-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: .85rem;
|
||||
}
|
||||
.fw-table thead th {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: .72rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: .07em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-dim);
|
||||
border-bottom: 1px solid var(--border);
|
||||
white-space: nowrap;
|
||||
background: rgba(0,0,0,.15);
|
||||
}
|
||||
.fw-table tbody td {
|
||||
padding: 9px 12px;
|
||||
vertical-align: middle;
|
||||
border-bottom: 1px solid rgba(0,200,255,.04);
|
||||
}
|
||||
.fw-table tbody tr:last-child td { border-bottom: none; }
|
||||
|
||||
.fw-row { transition: background .15s; }
|
||||
.fw-row:hover { background: var(--surface-2); }
|
||||
.fw-row.fw-row-disabled { opacity: .45; }
|
||||
.fw-row.dragging { opacity: .4; background: rgba(0,212,255,.05); }
|
||||
.fw-row.drag-over { border-top: 2px solid var(--accent); }
|
||||
|
||||
/* Column widths */
|
||||
.col-drag { width: 28px; }
|
||||
.col-num { width: 32px; color: var(--muted); font-size: .78rem; }
|
||||
.col-en { width: 44px; }
|
||||
.col-action { width: 110px; }
|
||||
.col-proto { width: 80px; }
|
||||
.col-iface { width: 120px; font-family: "JetBrains Mono","Fira Code",monospace; font-size: .8rem; }
|
||||
.col-addr { min-width: 160px; font-family: "JetBrains Mono","Fira Code",monospace; font-size: .8rem; }
|
||||
.col-comment { color: var(--text-dim); font-size: .82rem; }
|
||||
.col-btns { width: 80px; white-space: nowrap; }
|
||||
|
||||
.drag-handle {
|
||||
cursor: grab;
|
||||
color: var(--muted);
|
||||
font-size: 1.1rem;
|
||||
user-select: none;
|
||||
display: inline-block;
|
||||
line-height: 1;
|
||||
padding: 2px 4px;
|
||||
}
|
||||
.drag-handle:active { cursor: grabbing; }
|
||||
|
||||
/* Action badges */
|
||||
.action-badge {
|
||||
display: inline-block;
|
||||
font-size: .7rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .07em;
|
||||
padding: 3px 10px;
|
||||
border-radius: 20px;
|
||||
border: 1px solid;
|
||||
}
|
||||
.fw-accept {
|
||||
border-color: rgba(0, 255, 136, 0.4);
|
||||
color: var(--success);
|
||||
background: rgba(0, 255, 136, 0.08);
|
||||
}
|
||||
.fw-drop {
|
||||
border-color: rgba(255, 51, 102, 0.4);
|
||||
color: var(--danger);
|
||||
background: rgba(255, 51, 102, 0.08);
|
||||
}
|
||||
.fw-reject {
|
||||
border-color: rgba(255, 170, 0, 0.4);
|
||||
color: var(--warning);
|
||||
background: rgba(255, 170, 0, 0.08);
|
||||
}
|
||||
|
||||
/* Empty state */
|
||||
.fw-empty {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: var(--muted);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* Policy note */
|
||||
.fw-policy-note {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 16px;
|
||||
font-size: .78rem;
|
||||
color: var(--muted);
|
||||
border-top: 1px solid var(--border);
|
||||
background: rgba(0,0,0,.1);
|
||||
}
|
||||
.fw-policy-note strong { color: var(--danger); }
|
||||
|
||||
/* Mini toggle (inline in table) */
|
||||
.mini-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mini-toggle input { display: none; }
|
||||
.mini-slider {
|
||||
display: inline-block;
|
||||
width: 30px; height: 16px;
|
||||
background: var(--surface-3);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
position: relative;
|
||||
transition: all .2s;
|
||||
}
|
||||
.mini-slider::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 2px; left: 2px;
|
||||
width: 11px; height: 11px;
|
||||
background: var(--muted);
|
||||
border-radius: 50%;
|
||||
transition: all .2s;
|
||||
}
|
||||
.mini-toggle input:checked + .mini-slider {
|
||||
background: rgba(0,255,136,.2);
|
||||
border-color: rgba(0,255,136,.4);
|
||||
}
|
||||
.mini-toggle input:checked + .mini-slider::after {
|
||||
transform: translateX(14px);
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
/* Comment display */
|
||||
.fw-comment { color: var(--text-dim); }
|
||||
|
||||
/* Wider modal for rule editing */
|
||||
.modal-wide { max-width: 680px; }
|
||||
|
||||
/* Two-column form grid */
|
||||
.form-grid-2 {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0 16px;
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.form-grid-2 { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
/* ── Scanline overlay (subtle futuristic effect) ── */
|
||||
body::after {
|
||||
content: '';
|
||||
|
||||
Reference in New Issue
Block a user