forked from go-freebsd/pf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule_string.go
99 lines (79 loc) · 2.27 KB
/
rule_string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package pf
import (
"fmt"
"strings"
)
// #include <sys/ioctl.h>
// #include <net/if.h>
// #include <net/pfvar.h>
import "C"
// String returns the rule as pf.conf representation
func (r Rule) String() string {
var dump []string
dump = append(dump, r.Action().String())
dump = append(dump, r.Direction().String())
if r.Log() {
dump = append(dump, "log")
}
if r.Quick() {
dump = append(dump, "quick")
}
if af := r.AddressFamily(); af != AddressFamilyAny {
dump = append(dump, r.AddressFamily().String())
}
if proto := r.Protocol(); proto != ProtocolAny {
dump = append(dump, "proto", proto.String())
}
dump = append(dump, "from")
dump = addressDump(dump, &r.wrap.rule.src, r.wrap.rule.af)
dump = append(dump, "to")
dump = addressDump(dump, &r.wrap.rule.dst, r.wrap.rule.af)
if s := r.State(); s != StateNo {
dump = append(dump, s.String())
}
return strings.Join(dump, " ")
}
// addressDump returns the pf.conf representation of the address
func addressDump(dump []string, addr *C.struct_pf_rule_addr, af C.sa_family_t) []string {
if addr.neg == 1 {
dump = append(dump, "!")
}
dump = append(dump, Address{wrap: &addr.addr, af: af}.String())
return portRangeDump(dump, addr)
}
// portRangeDump returns the pf.conf representation of the port range
func portRangeDump(dump []string, addr *C.struct_pf_rule_addr) []string {
startPort := uint16(C.ntohs(C.uint16_t(addr.port[0])))
endPort := uint16(C.ntohs(C.uint16_t(addr.port[1])))
operation := uint8(addr.port_op)
if startPort == 0 && endPort == 0 {
return dump
}
dump = append(dump, "port")
def := ""
switch operation {
case C.PF_OP_RRG:
def = fmt.Sprintf("%d:%d", startPort, endPort)
case C.PF_OP_IRG:
def = fmt.Sprintf("%d><%d", startPort, endPort)
case C.PF_OP_EQ:
def = fmt.Sprintf("%d", startPort)
case C.PF_OP_NE:
def = fmt.Sprintf("!=%d", startPort)
case C.PF_OP_LT:
def = fmt.Sprintf("<%d", startPort)
case C.PF_OP_LE:
def = fmt.Sprintf("<=%d", startPort)
case C.PF_OP_GT:
def = fmt.Sprintf(">%d", startPort)
case C.PF_OP_GE:
def = fmt.Sprintf(">=%d", startPort)
case C.PF_OP_XRG:
def = fmt.Sprintf("%d<>%d", startPort, endPort)
case C.PF_OP_NONE:
default:
panic(fmt.Errorf("Port operation unknown: %d (%d:%d)", operation,
startPort, endPort))
}
return append(dump, def)
}