istio

Форк
0
423 строки · 13.9 Кб
1
// Copyright Istio Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
package model
16

17
import (
18
	"fmt"
19
	"strings"
20

21
	rbacpb "github.com/envoyproxy/go-control-plane/envoy/config/rbac/v3"
22
	matcherpb "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3"
23

24
	"istio.io/istio/pilot/pkg/networking/util"
25
	"istio.io/istio/pilot/pkg/security/authz/matcher"
26
	"istio.io/istio/pilot/pkg/xds/filters"
27
	"istio.io/istio/pkg/spiffe"
28
)
29

30
type generator interface {
31
	permission(key, value string, forTCP bool) (*rbacpb.Permission, error)
32
	principal(key, value string, forTCP bool, useAuthenticated bool) (*rbacpb.Principal, error)
33
}
34

35
type extendedGenerator interface {
36
	extendedPermission(key string, value []string, forTCP bool) (*rbacpb.Permission, error)
37
	extendedPrincipal(key string, value []string, forTCP bool) (*rbacpb.Principal, error)
38
}
39

40
type destIPGenerator struct{}
41

42
func (destIPGenerator) permission(_, value string, _ bool) (*rbacpb.Permission, error) {
43
	cidrRange, err := util.AddrStrToCidrRange(value)
44
	if err != nil {
45
		return nil, err
46
	}
47
	return permissionDestinationIP(cidrRange), nil
48
}
49

50
func (destIPGenerator) principal(_, _ string, _ bool, _ bool) (*rbacpb.Principal, error) {
51
	return nil, fmt.Errorf("unimplemented")
52
}
53

54
type destPortGenerator struct{}
55

56
func (destPortGenerator) permission(_, value string, _ bool) (*rbacpb.Permission, error) {
57
	portValue, err := convertToPort(value)
58
	if err != nil {
59
		return nil, err
60
	}
61
	return permissionDestinationPort(portValue), nil
62
}
63

64
func (destPortGenerator) principal(_, _ string, _ bool, _ bool) (*rbacpb.Principal, error) {
65
	return nil, fmt.Errorf("unimplemented")
66
}
67

68
type connSNIGenerator struct{}
69

70
func (connSNIGenerator) permission(_, value string, _ bool) (*rbacpb.Permission, error) {
71
	m := matcher.StringMatcher(value)
72
	return permissionRequestedServerName(m), nil
73
}
74

75
func (connSNIGenerator) principal(_, _ string, _ bool, _ bool) (*rbacpb.Principal, error) {
76
	return nil, fmt.Errorf("unimplemented")
77
}
78

79
type envoyFilterGenerator struct{}
80

81
func (efg envoyFilterGenerator) permission(key, value string, _ bool) (*rbacpb.Permission, error) {
82
	// Split key of format "experimental.envoy.filters.a.b[c]" to "envoy.filters.a.b" and "c".
83
	parts := strings.SplitN(strings.TrimSuffix(strings.TrimPrefix(key, "experimental."), "]"), "[", 2)
84

85
	if len(parts) != 2 {
86
		return nil, fmt.Errorf("invalid key: %v", key)
87
	}
88

89
	// If value is of format [v], create a list matcher.
90
	// Else, if value is of format v, create a string matcher.
91
	if strings.HasPrefix(value, "[") && strings.HasSuffix(value, "]") {
92
		m := matcher.MetadataListMatcher(parts[0], parts[1:], matcher.StringMatcher(strings.Trim(value, "[]")), false)
93
		return permissionMetadata(m), nil
94
	}
95
	m := matcher.MetadataStringMatcher(parts[0], parts[1], matcher.StringMatcher(value))
96
	return permissionMetadata(m), nil
97
}
98

99
func (efg envoyFilterGenerator) extendedPermission(key string, values []string, _ bool) (*rbacpb.Permission, error) {
100
	// Split key of format "experimental.envoy.filters.a.b[c]" to "envoy.filters.a.b" and "c".
101
	parts := strings.SplitN(strings.TrimSuffix(strings.TrimPrefix(key, "experimental."), "]"), "[", 2)
102

103
	if len(parts) != 2 {
104
		return nil, fmt.Errorf("invalid key: %v", key)
105
	}
106

107
	matchers := []*matcherpb.ValueMatcher{}
108
	for _, value := range values {
109
		if strings.HasPrefix(value, "[") && strings.HasSuffix(value, "]") {
110
			matchers = append(matchers, &matcherpb.ValueMatcher{
111
				MatchPattern: &matcherpb.ValueMatcher_ListMatch{
112
					ListMatch: &matcherpb.ListMatcher{
113
						MatchPattern: &matcherpb.ListMatcher_OneOf{
114
							OneOf: &matcherpb.ValueMatcher{
115
								MatchPattern: &matcherpb.ValueMatcher_StringMatch{
116
									StringMatch: matcher.StringMatcher(strings.Trim(value, "[]")),
117
								},
118
							},
119
						},
120
					},
121
				},
122
			})
123
		} else {
124
			matchers = append(matchers, &matcherpb.ValueMatcher{
125
				MatchPattern: &matcherpb.ValueMatcher_StringMatch{
126
					StringMatch: matcher.StringMatcher(value),
127
				},
128
			})
129
		}
130
	}
131
	m := matcher.MetadataValueMatcher(parts[0], parts[1], matcher.OrMatcher(matchers))
132
	return permissionMetadata(m), nil
133
}
134

135
func (envoyFilterGenerator) principal(_, _ string, _ bool, _ bool) (*rbacpb.Principal, error) {
136
	return nil, fmt.Errorf("unimplemented")
137
}
138

139
func (envoyFilterGenerator) extendedPrincipal(_ string, _ []string, _ bool) (*rbacpb.Principal, error) {
140
	return nil, fmt.Errorf("unimplemented")
141
}
142

143
type srcIPGenerator struct{}
144

145
func (srcIPGenerator) permission(_, _ string, _ bool) (*rbacpb.Permission, error) {
146
	return nil, fmt.Errorf("unimplemented")
147
}
148

149
func (srcIPGenerator) principal(_, value string, _ bool, _ bool) (*rbacpb.Principal, error) {
150
	cidr, err := util.AddrStrToCidrRange(value)
151
	if err != nil {
152
		return nil, err
153
	}
154
	return principalDirectRemoteIP(cidr), nil
155
}
156

157
type remoteIPGenerator struct{}
158

159
func (remoteIPGenerator) permission(_, _ string, _ bool) (*rbacpb.Permission, error) {
160
	return nil, fmt.Errorf("unimplemented")
161
}
162

163
func (remoteIPGenerator) principal(_, value string, _ bool, _ bool) (*rbacpb.Principal, error) {
164
	cidr, err := util.AddrStrToCidrRange(value)
165
	if err != nil {
166
		return nil, err
167
	}
168
	return principalRemoteIP(cidr), nil
169
}
170

171
type srcNamespaceGenerator struct{}
172

173
func (srcNamespaceGenerator) permission(_, _ string, _ bool) (*rbacpb.Permission, error) {
174
	return nil, fmt.Errorf("unimplemented")
175
}
176

177
func (srcNamespaceGenerator) principal(_, value string, _ bool, useAuthenticated bool) (*rbacpb.Principal, error) {
178
	v := strings.Replace(value, "*", ".*", -1)
179
	m := matcher.StringMatcherRegex(fmt.Sprintf(".*/ns/%s/.*", v))
180
	return principalAuthenticated(m, useAuthenticated), nil
181
}
182

183
type srcPrincipalGenerator struct{}
184

185
func (srcPrincipalGenerator) permission(_, _ string, _ bool) (*rbacpb.Permission, error) {
186
	return nil, fmt.Errorf("unimplemented")
187
}
188

189
func (srcPrincipalGenerator) principal(key, value string, _ bool, useAuthenticated bool) (*rbacpb.Principal, error) {
190
	m := matcher.StringMatcherWithPrefix(value, spiffe.URIPrefix)
191
	return principalAuthenticated(m, useAuthenticated), nil
192
}
193

194
type requestPrincipalGenerator struct{}
195

196
func (requestPrincipalGenerator) permission(_, _ string, _ bool) (*rbacpb.Permission, error) {
197
	return nil, fmt.Errorf("unimplemented")
198
}
199

200
func (requestPrincipalGenerator) extendedPermission(_ string, _ []string, _ bool) (*rbacpb.Permission, error) {
201
	return nil, fmt.Errorf("unimplemented")
202
}
203

204
func (rpg requestPrincipalGenerator) principal(key, value string, forTCP bool, _ bool) (*rbacpb.Principal, error) {
205
	if forTCP {
206
		return nil, fmt.Errorf("%q is HTTP only", key)
207
	}
208
	m := matcher.MetadataStringMatcher(filters.AuthnFilterName, key, matcher.StringMatcher(value))
209
	return principalMetadata(m), nil
210
}
211

212
var matchAny = matcher.StringMatcherRegex(".+")
213

214
func (rpg requestPrincipalGenerator) extendedPrincipal(key string, values []string, forTCP bool) (*rbacpb.Principal, error) {
215
	if forTCP {
216
		return nil, fmt.Errorf("%q is HTTP only", key)
217
	}
218
	var or []*rbacpb.Principal
219
	for _, value := range values {
220
		// Use the last index of "/" since issuer may be an URL
221
		idx := strings.LastIndex(value, "/")
222
		found := idx >= 0
223
		iss, sub := "", ""
224
		if found {
225
			iss, sub = value[:idx], value[idx+1:]
226
		} else {
227
			iss = value
228
		}
229
		var matchIss, matchSub *matcherpb.StringMatcher
230
		switch {
231
		case value == "*":
232
			matchIss = matchAny
233
			matchSub = matchAny
234
		case strings.HasPrefix(value, "*"):
235
			if found {
236
				if iss == "*" {
237
					matchIss = matchAny
238
				} else {
239
					matchIss = matcher.StringMatcherSuffix(strings.TrimPrefix(iss, "*"), false)
240
				}
241
				matchSub = matcher.StringMatcherExact(sub, false)
242
			} else {
243
				matchIss = matchAny
244
				matchSub = matcher.StringMatcherSuffix(strings.TrimPrefix(value, "*"), false)
245
			}
246
		case strings.HasSuffix(value, "*"):
247
			if found {
248
				matchIss = matcher.StringMatcherExact(iss, false)
249
				if sub == "*" {
250
					matchSub = matchAny
251
				} else {
252
					matchSub = matcher.StringMatcherPrefix(strings.TrimSuffix(sub, "*"), false)
253
				}
254
			} else {
255
				matchIss = matcher.StringMatcherPrefix(strings.TrimSuffix(value, "*"), false)
256
				matchSub = matchAny
257
			}
258
		default:
259
			matchSub = matcher.StringMatcherExact(sub, false)
260
			matchIss = matcher.StringMatcherExact(iss, false)
261
		}
262
		im := MetadataStringMatcherForJWTClaim("iss", matchIss)
263
		sm := MetadataStringMatcherForJWTClaim("sub", matchSub)
264
		or = append(or, principalAnd([]*rbacpb.Principal{principalMetadata(im), principalMetadata(sm)}))
265
	}
266
	if len(or) == 1 {
267
		return or[0], nil
268
	} else if len(or) > 0 {
269
		return principalOr(or), nil
270
	}
271
	return nil, nil
272
}
273

274
type requestAudiencesGenerator struct{}
275

276
func (requestAudiencesGenerator) permission(key, value string, forTCP bool) (*rbacpb.Permission, error) {
277
	return requestPrincipalGenerator{}.permission(key, value, forTCP)
278
}
279

280
func (requestAudiencesGenerator) extendedPermission(key string, values []string, forTCP bool) (*rbacpb.Permission, error) {
281
	return requestPrincipalGenerator{}.extendedPermission(key, values, forTCP)
282
}
283

284
func (rag requestAudiencesGenerator) principal(key, value string, forTCP bool, useAuthenticated bool) (*rbacpb.Principal, error) {
285
	if forTCP {
286
		return nil, fmt.Errorf("%q is HTTP only", key)
287
	}
288
	m := matcher.MetadataStringMatcher(filters.AuthnFilterName, key, matcher.StringMatcher(value))
289
	return principalMetadata(m), nil
290
}
291

292
func (rag requestAudiencesGenerator) extendedPrincipal(key string, values []string, forTCP bool) (*rbacpb.Principal, error) {
293
	if forTCP {
294
		return nil, fmt.Errorf("%q is HTTP only", key)
295
	}
296
	return principalMetadata(MetadataValueMatcherForJWTClaim("aud", matcher.StringOrMatcher(values))), nil
297
}
298

299
type requestPresenterGenerator struct{}
300

301
func (requestPresenterGenerator) permission(key, value string, forTCP bool) (*rbacpb.Permission, error) {
302
	return requestPrincipalGenerator{}.permission(key, value, forTCP)
303
}
304

305
func (requestPresenterGenerator) extendedPermission(key string, values []string, forTCP bool) (*rbacpb.Permission, error) {
306
	return requestPrincipalGenerator{}.extendedPermission(key, values, forTCP)
307
}
308

309
func (rpg requestPresenterGenerator) principal(key, value string, forTCP bool, useAuthenticated bool) (*rbacpb.Principal, error) {
310
	if forTCP {
311
		return nil, fmt.Errorf("%q is HTTP only", key)
312
	}
313
	m := matcher.MetadataStringMatcher(filters.AuthnFilterName, key, matcher.StringMatcher(value))
314
	return principalMetadata(m), nil
315
}
316

317
func (rpg requestPresenterGenerator) extendedPrincipal(key string, values []string, forTCP bool) (*rbacpb.Principal, error) {
318
	if forTCP {
319
		return nil, fmt.Errorf("%q is HTTP only", key)
320
	}
321
	return principalMetadata(MetadataListValueMatcherForJWTClaims([]string{"azp"}, matcher.StringOrMatcher(values))), nil
322
}
323

324
type requestHeaderGenerator struct{}
325

326
func (requestHeaderGenerator) permission(_, _ string, _ bool) (*rbacpb.Permission, error) {
327
	return nil, fmt.Errorf("unimplemented")
328
}
329

330
func (requestHeaderGenerator) principal(key, value string, forTCP bool, _ bool) (*rbacpb.Principal, error) {
331
	if forTCP {
332
		return nil, fmt.Errorf("%q is HTTP only", key)
333
	}
334

335
	header, err := extractNameInBrackets(strings.TrimPrefix(key, attrRequestHeader))
336
	if err != nil {
337
		return nil, err
338
	}
339
	m := matcher.HeaderMatcher(header, value)
340
	return principalHeader(m), nil
341
}
342

343
type requestClaimGenerator struct{}
344

345
func (requestClaimGenerator) permission(_, _ string, _ bool) (*rbacpb.Permission, error) {
346
	return nil, fmt.Errorf("unimplemented")
347
}
348

349
func (requestClaimGenerator) extendedPermission(_ string, _ []string, _ bool) (*rbacpb.Permission, error) {
350
	return nil, fmt.Errorf("unimplemented")
351
}
352

353
func (rcg requestClaimGenerator) principal(key, value string, forTCP bool, _ bool) (*rbacpb.Principal, error) {
354
	if forTCP {
355
		return nil, fmt.Errorf("%q is HTTP only", key)
356
	}
357

358
	claims, err := extractNameInNestedBrackets(strings.TrimPrefix(key, attrRequestClaims))
359
	if err != nil {
360
		return nil, err
361
	}
362
	// Generate a metadata list matcher for the given path keys and value.
363
	// On proxy side, the value should be of list type.
364
	m := MetadataMatcherForJWTClaims(claims, matcher.StringMatcher(value), false)
365
	return principalMetadata(m), nil
366
}
367

368
func (rcg requestClaimGenerator) extendedPrincipal(key string, values []string, forTCP bool) (*rbacpb.Principal, error) {
369
	if forTCP {
370
		return nil, fmt.Errorf("%q is HTTP only", key)
371
	}
372

373
	claims, err := extractNameInNestedBrackets(strings.TrimPrefix(key, attrRequestClaims))
374
	if err != nil {
375
		return nil, err
376
	}
377
	m := MetadataListValueMatcherForJWTClaims(claims, matcher.StringOrMatcher(values))
378
	return principalMetadata(m), nil
379
}
380

381
type hostGenerator struct{}
382

383
func (hg hostGenerator) permission(key, value string, forTCP bool) (*rbacpb.Permission, error) {
384
	if forTCP {
385
		return nil, fmt.Errorf("%q is HTTP only", key)
386
	}
387

388
	return permissionHeader(matcher.HostMatcher(hostHeader, value)), nil
389
}
390

391
func (hostGenerator) principal(key, value string, forTCP bool, _ bool) (*rbacpb.Principal, error) {
392
	return nil, fmt.Errorf("unimplemented")
393
}
394

395
type pathGenerator struct{}
396

397
func (g pathGenerator) permission(key, value string, forTCP bool) (*rbacpb.Permission, error) {
398
	if forTCP {
399
		return nil, fmt.Errorf("%q is HTTP only", key)
400
	}
401

402
	m := matcher.PathMatcher(value)
403
	return permissionPath(m), nil
404
}
405

406
func (pathGenerator) principal(key, value string, forTCP bool, _ bool) (*rbacpb.Principal, error) {
407
	return nil, fmt.Errorf("unimplemented")
408
}
409

410
type methodGenerator struct{}
411

412
func (methodGenerator) permission(key, value string, forTCP bool) (*rbacpb.Permission, error) {
413
	if forTCP {
414
		return nil, fmt.Errorf("%q is HTTP only", key)
415
	}
416

417
	m := matcher.HeaderMatcher(methodHeader, value)
418
	return permissionHeader(m), nil
419
}
420

421
func (methodGenerator) principal(key, value string, forTCP bool, _ bool) (*rbacpb.Principal, error) {
422
	return nil, fmt.Errorf("unimplemented")
423
}
424

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.