-
Notifications
You must be signed in to change notification settings - Fork 51
/
iptables_windows.go
431 lines (406 loc) · 12.9 KB
/
iptables_windows.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// +build windows
package windows
import (
"bytes"
"errors"
"fmt"
"math"
"strconv"
"strings"
"github.com/DavidGamba/go-getoptions"
"go.aporeto.io/trireme-lib/v11/controller/internal/windows/frontman"
"go.aporeto.io/trireme-lib/v11/controller/pkg/packet"
)
// structure representing result of parsed --match-set
type WindowsRuleMatchSet struct {
MatchSetName string
MatchSetNegate bool
MatchSetDstIp bool
MatchSetDstPort bool
MatchSetSrcIp bool
MatchSetSrcPort bool
}
// structure representing parsed port range
type WindowsRulePortRange struct {
PortStart int
PortEnd int
}
// structure representing result of parsed iptables rule
type WindowsRuleSpec struct {
Protocol int
Action int // FilterAction (allow, drop, nfq, proxy)
ProxyPort int
Mark int
Log bool
LogPrefix string
GroupId int
MatchSrcPort []*WindowsRulePortRange
MatchDstPort []*WindowsRulePortRange
MatchBytes []byte
MatchBytesOffset int
MatchSet []*WindowsRuleMatchSet
}
// converts a WindowsRuleSpec back into a string for an iptables rule
func MakeRuleSpecText(winRuleSpec *WindowsRuleSpec, validate bool) (string, error) {
rulespec := ""
if winRuleSpec.Protocol > 0 && winRuleSpec.Protocol < math.MaxUint8 {
rulespec += fmt.Sprintf("-p %d ", winRuleSpec.Protocol)
}
if len(winRuleSpec.MatchBytes) > 0 {
rulespec += fmt.Sprintf("-m string --string %s --offset %d ", string(winRuleSpec.MatchBytes), winRuleSpec.MatchBytesOffset)
}
if len(winRuleSpec.MatchSrcPort) > 0 {
rulespec += "--sports "
for i, pr := range winRuleSpec.MatchSrcPort {
rulespec += strconv.Itoa(pr.PortStart)
if pr.PortStart != pr.PortEnd {
rulespec += fmt.Sprintf(":%d", pr.PortEnd)
}
if i+1 < len(winRuleSpec.MatchSrcPort) {
rulespec += ","
}
}
rulespec += " "
}
if len(winRuleSpec.MatchDstPort) > 0 {
rulespec += "--dports "
for i, pr := range winRuleSpec.MatchDstPort {
rulespec += strconv.Itoa(pr.PortStart)
if pr.PortStart != pr.PortEnd {
rulespec += fmt.Sprintf(":%d", pr.PortEnd)
}
if i+1 < len(winRuleSpec.MatchDstPort) {
rulespec += ","
}
}
rulespec += " "
}
if len(winRuleSpec.MatchSet) > 0 {
for _, ms := range winRuleSpec.MatchSet {
rulespec += "-m set "
if ms.MatchSetNegate {
rulespec += "! "
}
rulespec += fmt.Sprintf("--match-set %s ", ms.MatchSetName)
if ms.MatchSetSrcIp {
rulespec += "srcIP"
if ms.MatchSetSrcPort || ms.MatchSetDstPort {
rulespec += ","
}
} else if ms.MatchSetDstIp {
rulespec += "dstIP"
if ms.MatchSetSrcPort || ms.MatchSetDstPort {
rulespec += ","
}
}
if ms.MatchSetSrcPort {
rulespec += "srcPort"
} else if ms.MatchSetDstPort {
rulespec += "dstPort"
}
rulespec += " "
}
}
switch winRuleSpec.Action {
case frontman.FilterActionAllow:
rulespec += "-j ACCEPT "
case frontman.FilterActionBlock:
rulespec += "-j DROP "
case frontman.FilterActionProxy:
rulespec += fmt.Sprintf("-j REDIRECT --to-ports %d ", winRuleSpec.ProxyPort)
case frontman.FilterActionNfq:
rulespec += fmt.Sprintf("-j NFQUEUE -j MARK %d ", winRuleSpec.Mark)
case frontman.FilterActionForceNfq:
rulespec += fmt.Sprintf("-j NFQUEUE --queue-force -j MARK %d ", winRuleSpec.Mark)
}
if winRuleSpec.Log {
rulespec += fmt.Sprintf("-j NFLOG --nflog-group %d --nflog-prefix %s ", winRuleSpec.GroupId, winRuleSpec.LogPrefix)
}
rulespec = strings.TrimSpace(rulespec)
if validate {
if _, err := ParseRuleSpec(rulespec); err != nil {
return "", err
}
}
return rulespec, nil
}
// parse comma-separated list of port or port ranges
func ParsePortString(portString string) ([]*WindowsRulePortRange, error) {
var result []*WindowsRulePortRange
if portString != "" {
portList := strings.Split(portString, ",")
for _, portListItem := range portList {
portEnd := 0
portStart, err := strconv.Atoi(portListItem)
if err != nil {
portRange := strings.SplitN(portListItem, ":", 2)
if len(portRange) != 2 {
return nil, errors.New("invalid port string")
}
portStart, err = strconv.Atoi(portRange[0])
if err != nil {
return nil, errors.New("invalid port string")
}
portEnd, err = strconv.Atoi(portRange[1])
if err != nil {
return nil, errors.New("invalid port string")
}
}
if portEnd == 0 {
portEnd = portStart
}
result = append(result, &WindowsRulePortRange{portStart, portEnd})
}
}
return result, nil
}
// ParseRuleSpec parses a windows iptable rule
func ParseRuleSpec(rulespec ...string) (*WindowsRuleSpec, error) {
opt := getoptions.New()
protocolOpt := opt.String("p", "")
sPortOpt := opt.String("sports", "")
dPortOpt := opt.String("dports", "")
actionOpt := opt.StringSlice("j", 1, 10, opt.Required())
modeOpt := opt.StringSlice("m", 1, 10)
matchSetOpt := opt.StringSlice("match-set", 2, 10)
matchStringOpt := opt.String("string", "")
matchStringOffsetOpt := opt.Int("offset", 0)
redirectPortOpt := opt.Int("to-ports", 0)
opt.String("state", "") // "--state NEW" et al ignored
opt.String("match", "") // "--match multiport" ignored
groupIdOpt := opt.Int("nflog-group", 0)
logPrefixOpt := opt.String("nflog-prefix", "")
nfqForceOpt := opt.Bool("queue-force", false)
_, err := opt.Parse(rulespec)
if err != nil {
return nil, err
}
result := &WindowsRuleSpec{}
// protocol
isProtoAnyRule := false
switch strings.ToLower(*protocolOpt) {
case "tcp":
result.Protocol = packet.IPProtocolTCP
case "udp":
result.Protocol = packet.IPProtocolUDP
case "icmp":
result.Protocol = 1
case "": // not specified = all
fallthrough
case "all":
result.Protocol = -1
isProtoAnyRule = true
default:
result.Protocol, err = strconv.Atoi(*protocolOpt)
if err != nil {
return nil, errors.New("rulespec not valid: invalid protocol")
}
if result.Protocol < 0 || result.Protocol > math.MaxUint8 {
return nil, errors.New("rulespec not valid: invalid protocol")
}
// iptables man page says protocol zero is equivalent to 'all' (sorry, IPv6 Hop-by-Hop Option)
if result.Protocol == 0 {
result.Protocol = -1
}
}
// src/dest port: either port or port range or list of such
result.MatchSrcPort, err = ParsePortString(*sPortOpt)
if err != nil {
return nil, errors.New("rulespec not valid: invalid match port")
}
result.MatchDstPort, err = ParsePortString(*dPortOpt)
if err != nil {
return nil, errors.New("rulespec not valid: invalid match port")
}
// -m options
for i, modeOptSetNum := 0, 0; i < len(*modeOpt); i++ {
switch (*modeOpt)[i] {
case "set":
matchSet := &WindowsRuleMatchSet{}
// see if negate of --match-set occurred
if i+1 < len(*modeOpt) && (*modeOpt)[i+1] == "!" {
matchSet.MatchSetNegate = true
i++
}
// now check corresponding match-set by index
matchSetIndex := 2 * modeOptSetNum
modeOptSetNum++
if matchSetIndex+1 >= len(*matchSetOpt) {
return nil, errors.New("rulespec not valid: --match-set not found for -m set")
}
// first part is the ipset name
matchSet.MatchSetName = (*matchSetOpt)[matchSetIndex]
// second part is the dst/src match specifier
ipPortSpecLower := strings.ToLower((*matchSetOpt)[matchSetIndex+1])
if strings.HasPrefix(ipPortSpecLower, "dstip") {
matchSet.MatchSetDstIp = true
} else if strings.HasPrefix(ipPortSpecLower, "srcip") {
matchSet.MatchSetSrcIp = true
}
if strings.HasSuffix(ipPortSpecLower, "dstport") {
matchSet.MatchSetDstPort = true
if result.Protocol < 1 {
return nil, errors.New("rulespec not valid: ipset match on port requires protocol be set")
}
} else if strings.HasSuffix(ipPortSpecLower, "srcport") {
matchSet.MatchSetSrcPort = true
if result.Protocol < 1 {
return nil, errors.New("rulespec not valid: ipset match on port requires protocol be set")
}
}
if !matchSet.MatchSetDstIp && !matchSet.MatchSetDstPort && !matchSet.MatchSetSrcIp && !matchSet.MatchSetSrcPort {
// look for acl-created iptables-conforming match on 'dst' or 'src'.
// a dst or src by itself we take to mean match both. otherwise, we take it as ip-match,port-match.
if strings.HasPrefix(ipPortSpecLower, "dst") {
matchSet.MatchSetDstIp = true
} else if strings.HasPrefix(ipPortSpecLower, "src") {
matchSet.MatchSetSrcIp = true
}
if strings.HasSuffix(ipPortSpecLower, "dst") && !isProtoAnyRule {
matchSet.MatchSetDstPort = true
if result.Protocol < 1 {
return nil, errors.New("rulespec not valid: ipset match on port requires protocol be set")
}
} else if strings.HasSuffix(ipPortSpecLower, "src") && !isProtoAnyRule {
matchSet.MatchSetSrcPort = true
if result.Protocol < 1 {
return nil, errors.New("rulespec not valid: ipset match on port requires protocol be set")
}
}
}
if !matchSet.MatchSetDstIp && !matchSet.MatchSetDstPort && !matchSet.MatchSetSrcIp && !matchSet.MatchSetSrcPort {
return nil, errors.New("rulespec not valid: ipset match needs ip/port specifier")
}
result.MatchSet = append(result.MatchSet, matchSet)
case "string":
if *matchStringOpt == "" {
return nil, errors.New("rulespec not valid: no match string given")
}
result.MatchBytes = []byte(*matchStringOpt)
result.MatchBytesOffset = *matchStringOffsetOpt
case "state":
// for "-m state --state NEW"
// skip it for now
break
default:
return nil, errors.New("rulespec not valid: unknown -m option")
}
}
// action: either NFQUEUE, REDIRECT, MARK, ACCEPT, DROP, NFLOG
for i := 0; i < len(*actionOpt); i++ {
switch (*actionOpt)[i] {
case "NFQUEUE":
result.Action = frontman.FilterActionNfq
if *nfqForceOpt {
result.Action = frontman.FilterActionForceNfq
}
case "REDIRECT":
result.Action = frontman.FilterActionProxy
case "ACCEPT":
result.Action = frontman.FilterActionAllow
case "DROP":
result.Action = frontman.FilterActionBlock
case "MARK":
i++
if i >= len(*actionOpt) {
return nil, errors.New("rulespec not valid: no mark given")
}
result.Mark, err = strconv.Atoi((*actionOpt)[i])
if err != nil {
return nil, errors.New("rulespec not valid: mark should be int32")
}
case "NFLOG":
// if no other action specified, it will default to 'continue' action (zero)
result.Log = true
result.LogPrefix = *logPrefixOpt
result.GroupId = *groupIdOpt
default:
return nil, errors.New("rulespec not valid: invalid action")
}
}
if result.Mark == 0 && (result.Action == frontman.FilterActionNfq || result.Action == frontman.FilterActionForceNfq) {
return nil, errors.New("rulespec not valid: nfq action needs to set mark")
}
// redirect port
result.ProxyPort = *redirectPortOpt
if result.Action == frontman.FilterActionProxy && result.ProxyPort == 0 {
return nil, errors.New("rulespec not valid: no redirect port given")
}
return result, nil
}
// Equal compares a WindowsRuleMatchSet to another for equality
func (w *WindowsRuleMatchSet) Equal(other *WindowsRuleMatchSet) bool {
if other == nil {
return false
}
return w.MatchSetName == other.MatchSetName &&
w.MatchSetNegate == other.MatchSetNegate &&
w.MatchSetDstIp == other.MatchSetDstIp &&
w.MatchSetDstPort == other.MatchSetDstPort &&
w.MatchSetSrcIp == other.MatchSetSrcIp &&
w.MatchSetSrcPort == other.MatchSetSrcPort
}
// Equal compares a WindowsRulePortRange to another for equality
func (w *WindowsRulePortRange) Equal(other *WindowsRulePortRange) bool {
if other == nil {
return false
}
return w.PortStart == other.PortStart && w.PortEnd == other.PortEnd
}
// Equal compares a WindowsRuleSpec to another for equality
func (w *WindowsRuleSpec) Equal(other *WindowsRuleSpec) bool {
if other == nil {
return false
}
equalSoFar := w.Protocol == other.Protocol &&
w.Action == other.Action &&
w.ProxyPort == other.ProxyPort &&
w.Mark == other.Mark &&
w.Log == other.Log &&
w.LogPrefix == other.LogPrefix &&
w.GroupId == other.GroupId &&
w.MatchBytesOffset == other.MatchBytesOffset &&
bytes.Equal(w.MatchBytes, other.MatchBytes) &&
len(w.MatchSrcPort) == len(other.MatchSrcPort) &&
len(w.MatchDstPort) == len(other.MatchDstPort) &&
len(w.MatchSet) == len(other.MatchSet)
if !equalSoFar {
return false
}
// we checked lengths above, but now continue to compare slices for equality.
// note: we assume equal slices have elements in the same order.
for i := 0; i < len(w.MatchSrcPort); i++ {
if w.MatchSrcPort[i] == nil {
if other.MatchSrcPort[i] != nil {
return false
}
continue
}
if !w.MatchSrcPort[i].Equal(other.MatchSrcPort[i]) {
return false
}
}
for i := 0; i < len(w.MatchDstPort); i++ {
if w.MatchDstPort[i] == nil {
if other.MatchDstPort[i] != nil {
return false
}
continue
}
if !w.MatchDstPort[i].Equal(other.MatchDstPort[i]) {
return false
}
}
for i := 0; i < len(w.MatchSet); i++ {
if w.MatchSet[i] == nil {
if other.MatchSet[i] != nil {
return false
}
continue
}
if !w.MatchSet[i].Equal(other.MatchSet[i]) {
return false
}
}
return true
}