-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
iptables_types.go
387 lines (330 loc) · 11.7 KB
/
iptables_types.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
// Copyright 2019 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package stack
import (
"fmt"
"strings"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/header"
)
// A Hook specifies one of the hooks built into the network stack.
//
// Userspace app Userspace app
// ^ |
// | v
// [Input] [Output]
// ^ |
// | v
// | routing
// | |
// | v
// ----->[Prerouting]----->routing----->[Forward]---------[Postrouting]----->
type Hook uint
const (
// Prerouting happens before a packet is routed to applications or to
// be forwarded.
Prerouting Hook = iota
// Input happens before a packet reaches an application.
Input
// Forward happens once it's decided that a packet should be forwarded
// to another host.
Forward
// Output happens after a packet is written by an application to be
// sent out.
Output
// Postrouting happens just before a packet goes out on the wire.
Postrouting
// NumHooks is the total number of hooks.
NumHooks
)
// A RuleVerdict is what a rule decides should be done with a packet.
type RuleVerdict int
const (
// RuleAccept indicates the packet should continue through netstack.
RuleAccept RuleVerdict = iota
// RuleDrop indicates the packet should be dropped.
RuleDrop
// RuleJump indicates the packet should jump to another chain.
RuleJump
// RuleReturn indicates the packet should return to the previous chain.
RuleReturn
)
// IPTables holds all the tables for a netstack.
//
// +stateify savable
type IPTables struct {
connections ConnTrack
reaper tcpip.Timer
mu ipTablesRWMutex `state:"nosave"`
// v4Tables and v6tables map tableIDs to tables. They hold builtin
// tables only, not user tables.
//
// mu protects the array of tables, but not the tables themselves.
// +checklocks:mu
v4Tables [NumTables]Table
//
// mu protects the array of tables, but not the tables themselves.
// +checklocks:mu
v6Tables [NumTables]Table
// modified is whether tables have been modified at least once. It is
// used to elide the iptables performance overhead for workloads that
// don't utilize iptables.
//
// +checklocks:mu
modified bool
}
// Modified returns whether iptables has been modified. It is inherently racy
// and intended for use only in tests.
func (it *IPTables) Modified() bool {
it.mu.Lock()
defer it.mu.Unlock()
return it.modified
}
// VisitTargets traverses all the targets of all tables and replaces each with
// transform(target).
func (it *IPTables) VisitTargets(transform func(Target) Target) {
it.mu.Lock()
defer it.mu.Unlock()
for tid := range it.v4Tables {
for i, rule := range it.v4Tables[tid].Rules {
it.v4Tables[tid].Rules[i].Target = transform(rule.Target)
}
}
for tid := range it.v6Tables {
for i, rule := range it.v6Tables[tid].Rules {
it.v6Tables[tid].Rules[i].Target = transform(rule.Target)
}
}
}
// A Table defines a set of chains and hooks into the network stack.
//
// It is a list of Rules, entry points (BuiltinChains), and error handlers
// (Underflows). As packets traverse netstack, they hit hooks. When a packet
// hits a hook, iptables compares it to Rules starting from that hook's entry
// point. So if a packet hits the Input hook, we look up the corresponding
// entry point in BuiltinChains and jump to that point.
//
// If the Rule doesn't match the packet, iptables continues to the next Rule.
// If a Rule does match, it can issue a verdict on the packet (e.g. RuleAccept
// or RuleDrop) that causes the packet to stop traversing iptables. It can also
// jump to other rules or perform custom actions based on Rule.Target.
//
// Underflow Rules are invoked when a chain returns without reaching a verdict.
//
// +stateify savable
type Table struct {
// Rules holds the rules that make up the table.
Rules []Rule
// BuiltinChains maps builtin chains to their entrypoint rule in Rules.
BuiltinChains [NumHooks]int
// Underflows maps builtin chains to their underflow rule in Rules
// (i.e. the rule to execute if the chain returns without a verdict).
Underflows [NumHooks]int
}
// ValidHooks returns a bitmap of the builtin hooks for the given table.
func (table *Table) ValidHooks() uint32 {
hooks := uint32(0)
for hook, ruleIdx := range table.BuiltinChains {
if ruleIdx != HookUnset {
hooks |= 1 << hook
}
}
return hooks
}
// A Rule is a packet processing rule. It consists of two pieces. First it
// contains zero or more matchers, each of which is a specification of which
// packets this rule applies to. If there are no matchers in the rule, it
// applies to any packet.
//
// +stateify savable
type Rule struct {
// Filter holds basic IP filtering fields common to every rule.
Filter IPHeaderFilter
// Matchers is the list of matchers for this rule.
Matchers []Matcher
// Target is the action to invoke if all the matchers match the packet.
Target Target
}
// IPHeaderFilter performs basic IP header matching common to every rule.
//
// +stateify savable
type IPHeaderFilter struct {
// Protocol matches the transport protocol.
Protocol tcpip.TransportProtocolNumber
// CheckProtocol determines whether the Protocol field should be
// checked during matching.
CheckProtocol bool
// Dst matches the destination IP address.
Dst tcpip.Address
// DstMask masks bits of the destination IP address when comparing with
// Dst.
DstMask tcpip.Address
// DstInvert inverts the meaning of the destination IP check, i.e. when
// true the filter will match packets that fail the destination
// comparison.
DstInvert bool
// Src matches the source IP address.
Src tcpip.Address
// SrcMask masks bits of the source IP address when comparing with Src.
SrcMask tcpip.Address
// SrcInvert inverts the meaning of the source IP check, i.e. when true the
// filter will match packets that fail the source comparison.
SrcInvert bool
// InputInterface matches the name of the incoming interface for the packet.
InputInterface string
// InputInterfaceMask masks the characters of the interface name when
// comparing with InputInterface.
InputInterfaceMask string
// InputInterfaceInvert inverts the meaning of incoming interface check,
// i.e. when true the filter will match packets that fail the incoming
// interface comparison.
InputInterfaceInvert bool
// OutputInterface matches the name of the outgoing interface for the packet.
OutputInterface string
// OutputInterfaceMask masks the characters of the interface name when
// comparing with OutputInterface.
OutputInterfaceMask string
// OutputInterfaceInvert inverts the meaning of outgoing interface check,
// i.e. when true the filter will match packets that fail the outgoing
// interface comparison.
OutputInterfaceInvert bool
}
// EmptyFilter4 returns an initialized IPv4 header filter.
func EmptyFilter4() IPHeaderFilter {
return IPHeaderFilter{
Dst: tcpip.AddrFrom4([4]byte{}),
DstMask: tcpip.AddrFrom4([4]byte{}),
Src: tcpip.AddrFrom4([4]byte{}),
SrcMask: tcpip.AddrFrom4([4]byte{}),
}
}
// EmptyFilter6 returns an initialized IPv6 header filter.
func EmptyFilter6() IPHeaderFilter {
return IPHeaderFilter{
Dst: tcpip.AddrFrom16([16]byte{}),
DstMask: tcpip.AddrFrom16([16]byte{}),
Src: tcpip.AddrFrom16([16]byte{}),
SrcMask: tcpip.AddrFrom16([16]byte{}),
}
}
// match returns whether pkt matches the filter.
//
// Preconditions: pkt.NetworkHeader is set and is at least of the minimal IPv4
// or IPv6 header length.
func (fl IPHeaderFilter) match(pkt *PacketBuffer, hook Hook, inNicName, outNicName string) bool {
// Extract header fields.
var (
transProto tcpip.TransportProtocolNumber
dstAddr tcpip.Address
srcAddr tcpip.Address
)
switch proto := pkt.NetworkProtocolNumber; proto {
case header.IPv4ProtocolNumber:
hdr := header.IPv4(pkt.NetworkHeader().Slice())
transProto = hdr.TransportProtocol()
dstAddr = hdr.DestinationAddress()
srcAddr = hdr.SourceAddress()
case header.IPv6ProtocolNumber:
hdr := header.IPv6(pkt.NetworkHeader().Slice())
transProto = hdr.TransportProtocol()
dstAddr = hdr.DestinationAddress()
srcAddr = hdr.SourceAddress()
default:
panic(fmt.Sprintf("unknown network protocol with EtherType: %d", proto))
}
// Check the transport protocol.
if fl.CheckProtocol && fl.Protocol != transProto {
return false
}
// Check the addresses.
if !filterAddress(dstAddr, fl.DstMask, fl.Dst, fl.DstInvert) ||
!filterAddress(srcAddr, fl.SrcMask, fl.Src, fl.SrcInvert) {
return false
}
switch hook {
case Prerouting, Input:
return matchIfName(inNicName, fl.InputInterface, fl.InputInterfaceInvert)
case Output:
return matchIfName(outNicName, fl.OutputInterface, fl.OutputInterfaceInvert)
case Forward:
if !matchIfName(inNicName, fl.InputInterface, fl.InputInterfaceInvert) {
return false
}
if !matchIfName(outNicName, fl.OutputInterface, fl.OutputInterfaceInvert) {
return false
}
return true
case Postrouting:
return true
default:
panic(fmt.Sprintf("unknown hook: %d", hook))
}
}
func matchIfName(nicName string, ifName string, invert bool) bool {
n := len(ifName)
if n == 0 {
// If the interface name is omitted in the filter, any interface will match.
return true
}
// If the interface name ends with '+', any interface which begins with the
// name should be matched.
var matches bool
if strings.HasSuffix(ifName, "+") {
matches = strings.HasPrefix(nicName, ifName[:n-1])
} else {
matches = nicName == ifName
}
return matches != invert
}
// NetworkProtocol returns the protocol (IPv4 or IPv6) on to which the header
// applies.
func (fl IPHeaderFilter) NetworkProtocol() tcpip.NetworkProtocolNumber {
switch fl.Src.BitLen() {
case header.IPv4AddressSizeBits:
return header.IPv4ProtocolNumber
case header.IPv6AddressSizeBits:
return header.IPv6ProtocolNumber
}
panic(fmt.Sprintf("invalid address in IPHeaderFilter: %s", fl.Src))
}
// filterAddress returns whether addr matches the filter.
func filterAddress(addr, mask, filterAddr tcpip.Address, invert bool) bool {
matches := true
addrBytes := addr.AsSlice()
maskBytes := mask.AsSlice()
filterBytes := filterAddr.AsSlice()
for i := range filterAddr.AsSlice() {
if addrBytes[i]&maskBytes[i] != filterBytes[i] {
matches = false
break
}
}
return matches != invert
}
// A Matcher is the interface for matching packets.
type Matcher interface {
// Match returns whether the packet matches and whether the packet
// should be "hotdropped", i.e. dropped immediately. This is usually
// used for suspicious packets.
//
// Precondition: packet.NetworkHeader is set.
Match(hook Hook, packet *PacketBuffer, inputInterfaceName, outputInterfaceName string) (matches bool, hotdrop bool)
}
// A Target is the interface for taking an action for a packet.
type Target interface {
// Action takes an action on the packet and returns a verdict on how
// traversal should (or should not) continue. If the return value is
// Jump, it also returns the index of the rule to jump to.
Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int)
}