forked from projectcalico/app-policy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
match.go
379 lines (344 loc) · 11.5 KB
/
match.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
// Copyright (c) 2018 Tigera, Inc. All rights reserved.
// 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 checker
import (
"net"
"strings"
"github.com/projectcalico/app-policy/proto"
"github.com/projectcalico/libcalico-go/lib/selector"
"fmt"
core "github.com/envoyproxy/data-plane-api/envoy/api/v2/core"
authz "github.com/envoyproxy/data-plane-api/envoy/service/auth/v2alpha"
log "github.com/sirupsen/logrus"
)
var (
// Envoy supports TCP only. Add a k:v into this map if more protocol is supported in the future.
protocolMapL4 = map[int32]string{6: "tcp"}
)
type namespaceMatch struct {
Names []string
Selector string
}
// InvalidDataFromDataPlane is an error is used when we get data from
// dataplane (Envoy) which is invalid.
type InvalidDataFromDataPlane struct {
string
}
func (i *InvalidDataFromDataPlane) Error() string {
return "Invalid data from dataplane " + i.string
}
// match checks if the Rule matches the request. It returns true if the Rule matches, false otherwise.
func match(rule *proto.Rule, req *requestCache, policyNamespace string) bool {
log.Debugf("Checking rule %v on request %v", rule, req)
attr := req.Request.GetAttributes()
return matchSource(rule, req, policyNamespace) &&
matchDestination(rule, req, policyNamespace) &&
matchRequest(rule, attr.GetRequest()) &&
matchL4Protocol(rule, attr.GetDestination())
}
func matchSource(r *proto.Rule, req *requestCache, policyNamespace string) bool {
nsMatch := computeNamespaceMatch(
policyNamespace,
r.GetOriginalSrcNamespaceSelector(),
r.GetOriginalSrcSelector(),
r.GetOriginalNotSrcSelector(),
r.GetSrcServiceAccountMatch())
addr := req.Request.GetAttributes().GetSource().GetAddress()
return matchServiceAccounts(r.GetSrcServiceAccountMatch(), req.SourcePeer()) &&
matchNamespace(nsMatch, req.SourceNamespace()) &&
matchSrcIPSets(r, req) &&
matchPort("src", r.GetSrcPorts(), r.GetSrcNamedPortIpSetIds(), req, addr) &&
matchNet("src", r.GetSrcNet(), addr)
}
func computeNamespaceMatch(
policyNamespace, nsSelector, podSelector, notPodSelector string, saMatch *proto.ServiceAccountMatch,
) *namespaceMatch {
nsMatch := &namespaceMatch{}
if nsSelector != "" {
// In all cases, if a namespace label selector is present, it takes precedence.
nsMatch.Selector = nsSelector
} else {
// NetworkPolicies have `policyNamespace` set, GlobalNetworkPolicy and Profiles have it set to empty string.
// If this is a NetworkPolicy and there is pod label selector (or not selector) or service account match, then
// we must only accept connections from this namespace. GlobalNetworkPolicy, Profile, or those without a pod
// selector/service account match can match any namespace.
if policyNamespace != "" &&
(podSelector != "" ||
notPodSelector != "" ||
len(saMatch.GetNames()) != 0 ||
saMatch.GetSelector() != "") {
nsMatch.Names = []string{policyNamespace}
}
}
return nsMatch
}
func matchDestination(r *proto.Rule, req *requestCache, policyNamespace string) bool {
nsMatch := computeNamespaceMatch(
policyNamespace,
r.GetOriginalDstNamespaceSelector(),
r.GetOriginalDstSelector(),
r.GetOriginalNotDstSelector(),
r.GetDstServiceAccountMatch())
addr := req.Request.GetAttributes().GetDestination().GetAddress()
return matchServiceAccounts(r.GetDstServiceAccountMatch(), req.DestinationPeer()) &&
matchNamespace(nsMatch, req.DestinationNamespace()) &&
matchDstIPSets(r, req) &&
matchPort("dst", r.GetDstPorts(), r.GetDstNamedPortIpSetIds(), req, addr) &&
matchNet("dst", r.GetDstNet(), addr)
}
func matchRequest(rule *proto.Rule, req *authz.AttributeContext_Request) bool {
log.WithField("request", req).Debug("Matching request.")
return matchHTTP(rule.GetHttpMatch(), req.GetHttp())
}
func matchServiceAccounts(saMatch *proto.ServiceAccountMatch, p peer) bool {
log.WithFields(log.Fields{
"name": p.Name,
"namespace": p.Namespace,
"labels": p.Labels,
"rule": saMatch},
).Debug("Matching service account.")
if saMatch == nil {
log.Debug("nil ServiceAccountMatch. Return true.")
return true
}
return matchName(saMatch.GetNames(), p.Name) &&
matchLabels(saMatch.GetSelector(), p.Labels)
}
func matchName(names []string, name string) bool {
log.WithFields(log.Fields{
"names": names,
"name": name,
}).Debug("Matching name")
if len(names) == 0 {
log.Debug("No names on rule.")
return true
}
for _, n := range names {
if n == name {
return true
}
}
return false
}
func matchLabels(selectorStr string, labels map[string]string) bool {
log.WithFields(log.Fields{
"selector": selectorStr,
"labels": labels,
}).Debug("Matching labels.")
sel, err := selector.Parse(selectorStr)
if err != nil {
log.Warnf("Could not parse label selector %v, %v", selectorStr, err)
return false
}
log.Debugf("Parsed selector.", sel)
return sel.Evaluate(labels)
}
func matchNamespace(nsMatch *namespaceMatch, ns namespace) bool {
log.WithFields(log.Fields{
"namespace": ns.Name,
"labels": ns.Labels,
"rule": nsMatch},
).Debug("Matching namespace.")
return matchName(nsMatch.Names, ns.Name) && matchLabels(nsMatch.Selector, ns.Labels)
}
func matchHTTP(rule *proto.HTTPMatch, req *authz.AttributeContext_HttpRequest) bool {
log.WithFields(log.Fields{
"rule": rule,
}).Debug("Matching HTTP.")
if rule == nil {
log.Debug("nil HTTPRule. Return true")
return true
}
return matchHTTPMethods(rule.GetMethods(), req.GetMethod()) && matchHTTPPaths(rule.GetPaths(), req.GetPath())
}
func matchHTTPMethods(methods []string, reqMethod string) bool {
log.WithFields(log.Fields{
"methods": methods,
"reqMethod": reqMethod,
}).Debug("Matching HTTP Methods")
if len(methods) == 0 {
log.Debug("Rule has 0 HTTP Methods, matched.")
return true
}
for _, method := range methods {
if method == "*" {
log.Debug("Rule matches all methods with wildcard *")
return true
}
if method == reqMethod {
log.Debug("HTTP Method matched.")
return true
}
}
log.Debug("HTTP Method not matched.")
return false
}
func matchHTTPPaths(paths []*proto.HTTPMatch_PathMatch, reqPath string) bool {
log.WithFields(log.Fields{
"paths": paths,
"reqPath": reqPath,
}).Debug("Matching HTTP Paths")
if len(paths) == 0 {
log.Debug("Rule has 0 HTTP Paths, matched.")
return true
}
// Accept only valid paths
if !strings.HasPrefix(reqPath, "/") {
s := fmt.Sprintf("Invalid HTTP Path \"%s\"", reqPath)
log.Error(s)
// Let the caller recover from the panic.
panic(&InvalidDataFromDataPlane{s})
}
// Strip out the query '?' and fragment '#' identifier
for _, s := range []string{"?", "#"} {
reqPath = strings.Split(reqPath, s)[0]
}
for _, pathMatch := range paths {
switch pathMatch.GetPathMatch().(type) {
case *proto.HTTPMatch_PathMatch_Exact:
if reqPath == pathMatch.GetExact() {
log.Debug("HTTP Path exact matched.")
return true
}
case *proto.HTTPMatch_PathMatch_Prefix:
if strings.HasPrefix(reqPath, pathMatch.GetPrefix()) {
log.Debugf("HTTP Path prefix %s matched.", pathMatch.GetPrefix())
return true
}
}
}
log.Debug("HTTP Path not matched.")
return false
}
func matchSrcIPSets(r *proto.Rule, req *requestCache) bool {
log.WithFields(log.Fields{
"SrcIpSetIds": r.SrcIpSetIds,
"NotSrcIpSetIds": r.NotSrcIpSetIds,
}).Debug("matching source IP sets")
addr := req.Request.GetAttributes().GetSource().GetAddress()
return matchIPSetsAll(r.SrcIpSetIds, req, addr) &&
matchIPSetsNotAny(r.NotSrcIpSetIds, req, addr)
}
func matchDstIPSets(r *proto.Rule, req *requestCache) bool {
log.WithFields(log.Fields{
"DstIpSetIds": r.DstIpSetIds,
"NotDstIpSetIds": r.NotDstIpSetIds,
}).Debug("matching destination IP sets")
addr := req.Request.GetAttributes().GetDestination().GetAddress()
return matchIPSetsAll(r.DstIpSetIds, req, addr) &&
matchIPSetsNotAny(r.NotDstIpSetIds, req, addr)
}
// matchIPSetsAll returns true if the address matches all of the IP set ids, false otherwise.
func matchIPSetsAll(ids []string, req *requestCache, addr *core.Address) bool {
for _, id := range ids {
s := req.GetIPSet(id)
if !s.ContainsAddress(addr) {
return false
}
}
return true
}
// matchIPSetsNotAny returns true if the address does not match any of the ipset ids, false otherwise.
func matchIPSetsNotAny(ids []string, req *requestCache, addr *core.Address) bool {
for _, id := range ids {
s := req.GetIPSet(id)
if s.ContainsAddress(addr) {
return false
}
}
return true
}
func matchPort(dir string, ranges []*proto.PortRange, namedPortSets []string, req *requestCache, addr *core.Address) bool {
log.WithFields(log.Fields{
"ranges": ranges,
"namedPortSets": namedPortSets,
"addr": addr,
"dir": dir,
}).Debug("matching port")
if len(ranges) == 0 && len(namedPortSets) == 0 {
return true
}
p := int32(addr.GetSocketAddress().GetPortValue())
for _, r := range ranges {
if r.GetFirst() <= p && p <= r.GetLast() {
return true
}
}
for _, id := range namedPortSets {
s := req.GetIPSet(id)
if s.ContainsAddress(addr) {
return true
}
}
return false
}
func matchNet(dir string, nets []string, addr *core.Address) bool {
log.WithFields(log.Fields{
"nets": nets,
"addr": addr,
"dir": dir,
}).Debug("matching net")
if len(nets) == 0 {
return true
}
ip := net.ParseIP(addr.GetSocketAddress().GetAddress())
if ip == nil {
// Envoy should not send us malformed IP addresses, but its possible we could get requests from non-IP
// connections, like Pipes.
log.WithField("ip", addr.GetSocketAddress().GetAddress()).Warn("unable to parse IP")
return false
}
for _, n := range nets {
_, ipn, err := net.ParseCIDR(n)
if err != nil {
// Don't match CIDRs if they are malformed. This case should generally be weeded out by validation earlier
// in processing before it gets to Dikastes.
log.WithField("cidr", n).Warn("unable to parse CIDR")
return false
}
if ipn.Contains(ip) {
return true
}
}
return false
}
func matchL4Protocol(rule *proto.Rule, dest *authz.AttributeContext_Peer) bool {
// Extract L4 protocol type of socket address for destination peer context. Match against rules.
if dest == nil {
log.Warn("Matching L4 protocol. nil request destination peer.")
return false
}
// Default protocol is TCP. Convert to lowercase.
reqProtocol := strings.ToLower(dest.GetAddress().GetSocketAddress().GetProtocol().String())
log.WithFields(log.Fields{
"isProtocol": rule.GetProtocol(),
"isNotProtocol": rule.NotProtocol,
"requestProtocol": reqProtocol,
}).Debug("Matching L4 protocol")
checkStringInRuleProtocol := func(p *proto.Protocol, s string, defaultResult bool) bool {
if p == nil {
return defaultResult
}
// Check if given protocol string matches what is specified in rule.
// Note we compare names in lowercase.
if name := p.GetName(); name != "" {
return strings.ToLower(name) == s
}
if name, ok := protocolMapL4[p.GetNumber()]; ok {
return name == s
}
return false
}
return checkStringInRuleProtocol(rule.GetProtocol(), reqProtocol, true) &&
!checkStringInRuleProtocol(rule.GetNotProtocol(), reqProtocol, false)
}