Skip to content

Commit

Permalink
refactor: 重构防火墙
Browse files Browse the repository at this point in the history
  • Loading branch information
devhaozi committed Oct 17, 2024
1 parent 905e206 commit e9cbc8e
Show file tree
Hide file tree
Showing 19 changed files with 1,399 additions and 373 deletions.
2 changes: 1 addition & 1 deletion internal/data/safe.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func (r *safeRepo) UpdateSSH(port uint, status bool) error {
}

func (r *safeRepo) GetPingStatus() (bool, error) {
out, err := shell.Execf(`firewall-cmd --list-all`)
out, err := shell.Execf(`firewall-cmd --list-rich-rules`)
if err != nil {
return true, errors.New(out)
}
Expand Down
15 changes: 15 additions & 0 deletions internal/http/request/firewall.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,18 @@ type FirewallRule struct {
Strategy string `json:"strategy" validate:"required,oneof=accept drop reject"`
Direction string `json:"direction"`
}

type FirewallIPRule struct {
Family string `json:"family" validate:"required,oneof=ipv4 ipv6"`
Protocol string `json:"protocol" validate:"min=1,oneof=tcp udp tcp/udp"`
Address string `json:"address"`
Strategy string `json:"strategy" validate:"required,oneof=accept drop reject"`
Direction string `json:"direction"`
}

type FirewallForward struct {
Protocol string `json:"protocol" validate:"min=1,oneof=tcp udp tcp/udp"`
Port uint `json:"port" validate:"required,gte=1,lte=65535"`
TargetIP string `json:"target_ip" validate:"required"`
TargetPort uint `json:"target_port" validate:"required,gte=1,lte=65535"`
}
6 changes: 6 additions & 0 deletions internal/route/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,12 @@ func Http(r chi.Router) {
r.Get("/rule", firewall.GetRules)
r.Post("/rule", firewall.CreateRule)
r.Delete("/rule", firewall.DeleteRule)
r.Get("/ipRule", firewall.GetIPRules)
r.Post("/ipRule", firewall.CreateIPRule)
r.Delete("/ipRule", firewall.DeleteIPRule)
r.Get("/forward", firewall.GetForwards)
r.Post("/forward", firewall.CreateForward)
r.Delete("/forward", firewall.DeleteForward)
})

r.Route("/ssh", func(r chi.Router) {
Expand Down
2 changes: 1 addition & 1 deletion internal/service/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"github.com/TheTNB/panel/pkg/ntp"
"path/filepath"
"time"

Expand All @@ -21,6 +20,7 @@ import (
"github.com/TheTNB/panel/internal/http/request"
"github.com/TheTNB/panel/pkg/api"
"github.com/TheTNB/panel/pkg/io"
"github.com/TheTNB/panel/pkg/ntp"
"github.com/TheTNB/panel/pkg/str"
"github.com/TheTNB/panel/pkg/systemctl"
"github.com/TheTNB/panel/pkg/tools"
Expand Down
148 changes: 147 additions & 1 deletion internal/service/firewall.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package service

import (
"net/http"
"slices"

"github.com/go-rat/chix"

"github.com/TheTNB/panel/internal/http/request"
"github.com/TheTNB/panel/pkg/firewall"
"github.com/TheTNB/panel/pkg/os"
"github.com/TheTNB/panel/pkg/systemctl"
)

Expand Down Expand Up @@ -64,7 +66,38 @@ func (s *FirewallService) GetRules(w http.ResponseWriter, r *http.Request) {
return
}

paged, total := Paginate(r, rules)
var filledRules []map[string]any
for rule := range slices.Values(rules) {
// 去除IP规则
if rule.PortStart == 1 && rule.PortEnd == 65535 {
continue
}
isUse := false
for port := rule.PortStart; port <= rule.PortEnd; port++ {
if rule.Protocol == firewall.ProtocolTCP {
isUse = os.TCPPortInUse(port)
} else if rule.Protocol == firewall.ProtocolUDP {
isUse = os.UDPPortInUse(port)
} else {
isUse = os.TCPPortInUse(port) || os.UDPPortInUse(port)
}
if isUse {
break
}
}
filledRules = append(filledRules, map[string]any{
"family": rule.Family,
"port_start": rule.PortStart,
"port_end": rule.PortEnd,
"protocol": rule.Protocol,
"address": rule.Address,
"strategy": rule.Strategy,
"direction": rule.Direction,
"in_use": isUse,
})
}

paged, total := Paginate(r, filledRules)

Success(w, chix.M{
"total": total,
Expand Down Expand Up @@ -105,3 +138,116 @@ func (s *FirewallService) DeleteRule(w http.ResponseWriter, r *http.Request) {

Success(w, nil)
}

func (s *FirewallService) GetIPRules(w http.ResponseWriter, r *http.Request) {
rules, err := s.firewall.ListRule()
if err != nil {
Error(w, http.StatusInternalServerError, "%v", err)
return
}

var filledRules []map[string]any
for rule := range slices.Values(rules) {
// 保留IP规则
if rule.PortStart != 1 || rule.PortEnd != 65535 || rule.Address == "" {
continue
}
filledRules = append(filledRules, map[string]any{
"family": rule.Family,
"protocol": rule.Protocol,
"address": rule.Address,
"strategy": rule.Strategy,
"direction": rule.Direction,
})
}

paged, total := Paginate(r, filledRules)

Success(w, chix.M{
"total": total,
"items": paged,
})
}

func (s *FirewallService) CreateIPRule(w http.ResponseWriter, r *http.Request) {
req, err := Bind[request.FirewallIPRule](r)
if err != nil {
Error(w, http.StatusUnprocessableEntity, "%v", err)
return
}

if err = s.firewall.RichRules(firewall.FireInfo{
Family: req.Family, Address: req.Address, Protocol: firewall.Protocol(req.Protocol), Strategy: firewall.Strategy(req.Strategy), Direction: firewall.Direction(req.Direction),
}, firewall.OperationAdd); err != nil {
Error(w, http.StatusInternalServerError, "%v", err)
return
}

Success(w, nil)
}

func (s *FirewallService) DeleteIPRule(w http.ResponseWriter, r *http.Request) {
req, err := Bind[request.FirewallIPRule](r)
if err != nil {
Error(w, http.StatusUnprocessableEntity, "%v", err)
return
}

if err = s.firewall.RichRules(firewall.FireInfo{
Family: req.Family, Address: req.Address, Protocol: firewall.Protocol(req.Protocol), Strategy: firewall.Strategy(req.Strategy), Direction: firewall.Direction(req.Direction),
}, firewall.OperationRemove); err != nil {
Error(w, http.StatusInternalServerError, "%v", err)
return
}

Success(w, nil)
}

func (s *FirewallService) GetForwards(w http.ResponseWriter, r *http.Request) {
forwards, err := s.firewall.ListForward()
if err != nil {
Error(w, http.StatusInternalServerError, "%v", err)
return
}

paged, total := Paginate(r, forwards)

Success(w, chix.M{
"total": total,
"items": paged,
})
}

func (s *FirewallService) CreateForward(w http.ResponseWriter, r *http.Request) {
req, err := Bind[request.FirewallForward](r)
if err != nil {
Error(w, http.StatusUnprocessableEntity, "%v", err)
return
}

if err = s.firewall.Forward(firewall.Forward{
Protocol: firewall.Protocol(req.Protocol), Port: req.Port, TargetIP: req.TargetIP, TargetPort: req.TargetPort,
}, firewall.OperationAdd); err != nil {
Error(w, http.StatusInternalServerError, "%v", err)
return
}

Success(w, nil)
}

func (s *FirewallService) DeleteForward(w http.ResponseWriter, r *http.Request) {
req, err := Bind[request.FirewallForward](r)
if err != nil {
Error(w, http.StatusUnprocessableEntity, "%v", err)
return
}

if err = s.firewall.Forward(firewall.Forward{
Protocol: firewall.Protocol(req.Protocol), Port: req.Port, TargetIP: req.TargetIP, TargetPort: req.TargetPort,
}, firewall.OperationRemove); err != nil {
Error(w, http.StatusInternalServerError, "%v", err)
return
}

Success(w, nil)
}
17 changes: 8 additions & 9 deletions pkg/firewall/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,15 @@ type FireInfo struct {
}

type FireForwardInfo struct {
Address string `json:"address"` // 源地址
Port uint `json:"port"` // 1-65535
Protocol Protocol `json:"protocol"` // tcp udp tcp/udp
TargetIP string `json:"targetIP"` // 目标地址
TargetPort string `json:"targetPort"` // 1-65535
Port uint `json:"port"` // 1-65535
Protocol Protocol `json:"protocol"` // tcp udp tcp/udp
TargetIP string `json:"target_ip"` // 目标地址
TargetPort uint `json:"target_port"` // 1-65535
}

type Forward struct {
Protocol Protocol `json:"protocol"` // tcp udp tcp/udp
Port uint `json:"port"` // 1-65535
TargetIP string `json:"targetIP"` // 目标地址
TargetPort uint `json:"targetPort"` // 1-65535
Protocol Protocol `json:"protocol"` // tcp udp tcp/udp
Port uint `json:"port"` // 1-65535
TargetIP string `json:"target_ip"` // 目标地址
TargetPort uint `json:"target_port"` // 1-65535
}
68 changes: 48 additions & 20 deletions pkg/firewall/firewall.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package firewall
import (
"errors"
"fmt"
"net"
"regexp"
"slices"
"strings"
Expand All @@ -22,7 +23,7 @@ type Firewall struct {
func NewFirewall() *Firewall {
firewall := &Firewall{
forwardListRegex: regexp.MustCompile(`^port=(\d{1,5}):proto=(.+?):toport=(\d{1,5}):toaddr=(.*)$`),
richRuleRegex: regexp.MustCompile(`^rule family="([^"]+)"(?: .*?(source|destination) address="([^"]+)")?(?: .*?port port="([^"]+)")?(?: .*?protocol="([^"]+)")?.*?(accept|drop|reject)$`),
richRuleRegex: regexp.MustCompile(`^rule family="([^"]+)"(?: .*?(source|destination) address="([^"]+)")?(?: .*?port port="([^"]+)")?(?: .*?protocol(?: value)?="([^"]+)")?.*?(accept|drop|reject)$`),
}

return firewall
Expand Down Expand Up @@ -107,7 +108,7 @@ func (r *Firewall) ListForward() ([]FireForwardInfo, error) {
Port: cast.ToUint(match[1]),
Protocol: Protocol(match[2]),
TargetIP: match[4],
TargetPort: match[3],
TargetPort: cast.ToUint(match[3]),
})
}
}
Expand Down Expand Up @@ -182,10 +183,18 @@ func (r *Firewall) RichRules(rule FireInfo, operation Operation) error {
ruleBuilder.WriteString(fmt.Sprintf(`port port="%d-%d" `, rule.PortStart, rule.PortEnd))
}
if operation == OperationRemove && protocol != "" && rule.Protocol != "tcp/udp" { // 删除操作,可以不指定协议
ruleBuilder.WriteString(fmt.Sprintf(`protocol="%s" `, protocol))
ruleBuilder.WriteString(`protocol`)
if rule.PortStart == 0 && rule.PortEnd == 0 { // IP 规则下,必须添加 value
ruleBuilder.WriteString(` value`)
}
ruleBuilder.WriteString(fmt.Sprintf(`="%s" `, protocol))
}
if operation == OperationAdd && protocol != "" {
ruleBuilder.WriteString(fmt.Sprintf(`protocol="%s" `, protocol))
ruleBuilder.WriteString(`protocol`)
if rule.PortStart == 0 && rule.PortEnd == 0 { // IP 规则下,必须添加 value
ruleBuilder.WriteString(` value`)
}
ruleBuilder.WriteString(fmt.Sprintf(`="%s" `, protocol))
}

ruleBuilder.WriteString(string(rule.Strategy))
Expand All @@ -199,26 +208,29 @@ func (r *Firewall) RichRules(rule FireInfo, operation Operation) error {
return err
}

func (r *Firewall) PortForward(info Forward, operation Operation) error {
func (r *Firewall) Forward(rule Forward, operation Operation) error {
if err := r.enableForward(); err != nil {
return err
}

var ruleStr strings.Builder
ruleStr.WriteString(fmt.Sprintf("firewall-cmd --zone=public --%s-forward-port=port=%d:proto=%s:", operation, info.Port, info.Protocol))
if info.TargetIP != "" && info.TargetIP != "127.0.0.1" && info.TargetIP != "localhost" {
ruleStr.WriteString(fmt.Sprintf("toaddr=%s:toport=%d", info.TargetIP, info.TargetPort))
} else {
ruleStr.WriteString(fmt.Sprintf("toport=%d", info.TargetPort))
}
ruleStr.WriteString(" --permanent")
protocols := strings.Split(string(rule.Protocol), "/")
for protocol := range slices.Values(protocols) {
var ruleBuilder strings.Builder
ruleBuilder.WriteString(fmt.Sprintf("firewall-cmd --zone=public --%s-forward-port=port=%d:proto=%s:", operation, rule.Port, protocol))
if rule.TargetIP != "" && !r.isLocalAddress(rule.TargetIP) {
ruleBuilder.WriteString(fmt.Sprintf("toport=%d:toaddr=%s", rule.TargetPort, rule.TargetIP))
} else {
ruleBuilder.WriteString(fmt.Sprintf("toport=%d", rule.TargetPort))
}
ruleBuilder.WriteString(" --permanent")

_, err := shell.Execf(ruleStr.String()) // nolint: govet
if err != nil {
return fmt.Errorf("%s port forward failed, err: %v", operation, err)
_, err := shell.Execf(ruleBuilder.String()) // nolint: govet
if err != nil {
return fmt.Errorf("%s port forward failed, err: %v", operation, err)
}
}

_, err = shell.Execf("firewall-cmd --reload")
_, err := shell.Execf("firewall-cmd --reload")
return err
}

Expand Down Expand Up @@ -270,15 +282,31 @@ func (r *Firewall) enableForward() error {
if out == "no" {
out, err = shell.Execf("firewall-cmd --zone=public --add-masquerade --permanent")
if err != nil {
return fmt.Errorf("%s: %s", err, out)
return fmt.Errorf("%v: %s", err, out)
}

_, err = shell.Execf("firewall-cmd --reload")
return err
}

return fmt.Errorf("%v: %s", err, out)
}

return nil
}

func (r *Firewall) isLocalAddress(ip string) bool {
parsed := net.ParseIP(ip)
if parsed == nil {
return false
}
if parsed.IsLoopback() {
return true
}
if parsed.IsUnspecified() {
return true
}
if strings.ToLower(ip) == "localhost" {
return true
}

return false
}
Loading

0 comments on commit e9cbc8e

Please sign in to comment.