forked from grpc/grpc-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GrpcAuthorizationEngine.java
487 lines (423 loc) · 15.6 KB
/
GrpcAuthorizationEngine.java
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
* Copyright 2021 The gRPC 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 io.grpc.xds.internal.rbac.engine;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
import com.google.common.io.BaseEncoding;
import io.grpc.Grpc;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.xds.internal.Matchers;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
/**
* Implementation of gRPC server access control based on envoy RBAC protocol:
* https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/rbac/v3/rbac.proto
*
* <p>One GrpcAuthorizationEngine is initialized with one action type and a list of policies.
* Policies are examined sequentially in order in an any match fashion, and the first matched policy
* will be returned. If not matched at all, the opposite action type is returned as a result.
*/
public final class GrpcAuthorizationEngine {
private static final Logger log = Logger.getLogger(GrpcAuthorizationEngine.class.getName());
private final AuthConfig authConfig;
/** Instantiated with envoy policyMatcher configuration. */
public GrpcAuthorizationEngine(AuthConfig authConfig) {
this.authConfig = authConfig;
}
/** Return the auth decision for the request argument against the policies. */
public AuthDecision evaluate(Metadata metadata, ServerCall<?,?> serverCall) {
checkNotNull(metadata, "metadata");
checkNotNull(serverCall, "serverCall");
String firstMatch = null;
EvaluateArgs args = new EvaluateArgs(metadata, serverCall);
for (PolicyMatcher policyMatcher : authConfig.policies) {
if (policyMatcher.matches(args)) {
firstMatch = policyMatcher.name;
break;
}
}
Action decisionType = Action.DENY;
if (Action.DENY.equals(authConfig.action) == (firstMatch == null)) {
decisionType = Action.ALLOW;
}
log.log(Level.FINER, "RBAC decision: {0}, policy match: {1}.",
new Object[]{decisionType, firstMatch});
return AuthDecision.create(decisionType, firstMatch);
}
public enum Action {
ALLOW,
DENY,
}
/**
* An authorization decision provides information about the decision type and the policy name
* identifier based on the authorization engine evaluation. */
@AutoValue
public abstract static class AuthDecision {
public abstract Action decision();
@Nullable
public abstract String matchingPolicyName();
static AuthDecision create(Action decisionType, @Nullable String matchingPolicy) {
return new AutoValue_GrpcAuthorizationEngine_AuthDecision(decisionType, matchingPolicy);
}
}
/** Represents authorization config policy that the engine will evaluate against. */
public static final class AuthConfig {
private final List<PolicyMatcher> policies;
private final Action action;
public AuthConfig(List<PolicyMatcher> policies, Action action) {
this.policies = Collections.unmodifiableList(new ArrayList<>(policies));
this.action = action;
}
}
/**
* Implements a top level {@link Matcher} for a single RBAC policy configuration per envoy
* protocol:
* https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/rbac/v3/rbac.proto#config-rbac-v3-policy.
*
* <p>Currently we only support matching some of the request fields. Those unsupported fields are
* considered not match until we stop ignoring them.
*/
public static final class PolicyMatcher implements Matcher {
private final OrMatcher permissions;
private final OrMatcher principals;
private final String name;
/** Constructs a matcher for one RBAC policy. */
public PolicyMatcher(String name, OrMatcher permissions, OrMatcher principals) {
this.name = name;
this.permissions = permissions;
this.principals = principals;
}
@Override
public boolean matches(EvaluateArgs args) {
return permissions.matches(args) && principals.matches(args);
}
}
public static final class AuthenticatedMatcher implements Matcher {
private final Matchers.StringMatcher delegate;
/**
* Passing in null will match all authenticated user, i.e. SSL session is present.
* https://github.com/envoyproxy/envoy/blob/main/api/envoy/config/rbac/v3/rbac.proto#L240
* */
public AuthenticatedMatcher(@Nullable Matchers.StringMatcher delegate) {
this.delegate = delegate;
}
@Override
public boolean matches(EvaluateArgs args) {
Collection<String> principalNames = args.getPrincipalNames();
log.log(Level.FINER, "Matching principal names: {0}", new Object[]{principalNames});
// Null means unauthenticated connection.
if (principalNames == null) {
return false;
}
// Connection is authenticated, so returns match when delegated string matcher is not present.
if (delegate == null) {
return true;
}
for (String name : principalNames) {
if (delegate.matches(name)) {
return true;
}
}
return false;
}
}
public static final class DestinationIpMatcher implements Matcher {
private final Matchers.CidrMatcher delegate;
public DestinationIpMatcher(Matchers.CidrMatcher delegate) {
this.delegate = checkNotNull(delegate, "delegate");
}
@Override
public boolean matches(EvaluateArgs args) {
return delegate.matches(args.getDestinationIp());
}
}
public static final class SourceIpMatcher implements Matcher {
private final Matchers.CidrMatcher delegate;
public SourceIpMatcher(Matchers.CidrMatcher delegate) {
this.delegate = checkNotNull(delegate, "delegate");
}
@Override
public boolean matches(EvaluateArgs args) {
return delegate.matches(args.getSourceIp());
}
}
public static final class PathMatcher implements Matcher {
private final Matchers.StringMatcher delegate;
public PathMatcher(Matchers.StringMatcher delegate) {
this.delegate = checkNotNull(delegate, "delegate");
}
@Override
public boolean matches(EvaluateArgs args) {
return delegate.matches(args.getPath());
}
}
public static final class AuthHeaderMatcher implements Matcher {
private final Matchers.HeaderMatcher delegate;
public AuthHeaderMatcher(Matchers.HeaderMatcher delegate) {
this.delegate = checkNotNull(delegate, "delegate");
}
@Override
public boolean matches(EvaluateArgs args) {
return delegate.matches(args.getHeader(delegate.name()));
}
}
public static final class DestinationPortMatcher implements Matcher {
private final int port;
public DestinationPortMatcher(int port) {
this.port = port;
}
@Override
public boolean matches(EvaluateArgs args) {
return port == args.getDestinationPort();
}
}
public static final class DestinationPortRangeMatcher implements Matcher {
private final int start;
private final int end;
/** Start of the range is inclusive. End of the range is exclusive.*/
public DestinationPortRangeMatcher(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public boolean matches(EvaluateArgs args) {
int port = args.getDestinationPort();
return port >= start && port < end;
}
}
public static final class RequestedServerNameMatcher implements Matcher {
private final Matchers.StringMatcher delegate;
public RequestedServerNameMatcher(Matchers.StringMatcher delegate) {
this.delegate = checkNotNull(delegate, "delegate");
}
@Override
public boolean matches(EvaluateArgs args) {
return delegate.matches(args.getRequestedServerName());
}
}
private static final class EvaluateArgs {
private final Metadata metadata;
private final ServerCall<?,?> serverCall;
// https://github.com/envoyproxy/envoy/blob/63619d578e1abe0c1725ea28ba02f361466662e1/api/envoy/config/rbac/v3/rbac.proto#L238-L240
private static final int URI_SAN = 6;
private static final int DNS_SAN = 2;
private EvaluateArgs(Metadata metadata, ServerCall<?,?> serverCall) {
this.metadata = metadata;
this.serverCall = serverCall;
}
private String getPath() {
return "/" + serverCall.getMethodDescriptor().getFullMethodName();
}
/**
* Returns null for unauthenticated connection.
* Returns empty string collection if no valid certificate and no
* principal names we are interested in.
* https://github.com/envoyproxy/envoy/blob/0fae6970ddaf93f024908ba304bbd2b34e997a51/envoy/ssl/connection.h#L70
*/
@Nullable
private Collection<String> getPrincipalNames() {
SSLSession sslSession = serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION);
if (sslSession == null) {
return null;
}
try {
Certificate[] certs = sslSession.getPeerCertificates();
if (certs == null || certs.length < 1) {
return Collections.singleton("");
}
X509Certificate cert = (X509Certificate)certs[0];
if (cert == null) {
return Collections.singleton("");
}
Collection<List<?>> names = cert.getSubjectAlternativeNames();
List<String> principalNames = new ArrayList<>();
if (names != null) {
for (List<?> name : names) {
if (URI_SAN == (Integer) name.get(0)) {
principalNames.add((String) name.get(1));
}
}
if (!principalNames.isEmpty()) {
return Collections.unmodifiableCollection(principalNames);
}
for (List<?> name : names) {
if (DNS_SAN == (Integer) name.get(0)) {
principalNames.add((String) name.get(1));
}
}
if (!principalNames.isEmpty()) {
return Collections.unmodifiableCollection(principalNames);
}
}
if (cert.getSubjectDN() == null || cert.getSubjectDN().getName() == null) {
return Collections.singleton("");
}
return Collections.singleton(cert.getSubjectDN().getName());
} catch (SSLPeerUnverifiedException | CertificateParsingException ex) {
log.log(Level.FINE, "Unexpected getPrincipalNames error.", ex);
return Collections.singleton("");
}
}
@Nullable
private String getHeader(String headerName) {
headerName = headerName.toLowerCase(Locale.ROOT);
if ("te".equals(headerName)) {
return null;
}
if (":authority".equals(headerName)) {
headerName = "host";
}
if ("host".equals(headerName)) {
return serverCall.getAuthority();
}
if (":path".equals(headerName)) {
return getPath();
}
if (":method".equals(headerName)) {
return "POST";
}
return deserializeHeader(headerName);
}
@Nullable
private String deserializeHeader(String headerName) {
if (headerName.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
Metadata.Key<byte[]> key;
try {
key = Metadata.Key.of(headerName, Metadata.BINARY_BYTE_MARSHALLER);
} catch (IllegalArgumentException e) {
return null;
}
Iterable<byte[]> values = metadata.getAll(key);
if (values == null) {
return null;
}
List<String> encoded = new ArrayList<>();
for (byte[] v : values) {
encoded.add(BaseEncoding.base64().omitPadding().encode(v));
}
return Joiner.on(",").join(encoded);
}
Metadata.Key<String> key;
try {
key = Metadata.Key.of(headerName, Metadata.ASCII_STRING_MARSHALLER);
} catch (IllegalArgumentException e) {
return null;
}
Iterable<String> values = metadata.getAll(key);
return values == null ? null : Joiner.on(",").join(values);
}
private InetAddress getDestinationIp() {
SocketAddress addr = serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_LOCAL_ADDR);
return addr == null ? null : ((InetSocketAddress) addr).getAddress();
}
private InetAddress getSourceIp() {
SocketAddress addr = serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
return addr == null ? null : ((InetSocketAddress) addr).getAddress();
}
private int getDestinationPort() {
SocketAddress addr = serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_LOCAL_ADDR);
return addr == null ? -1 : ((InetSocketAddress) addr).getPort();
}
private String getRequestedServerName() {
return "";
}
}
public interface Matcher {
boolean matches(EvaluateArgs args);
}
public static final class OrMatcher implements Matcher {
private final List<? extends Matcher> anyMatch;
/** Matches when any of the matcher matches. */
public OrMatcher(List<? extends Matcher> matchers) {
checkNotNull(matchers, "matchers");
for (Matcher matcher : matchers) {
checkNotNull(matcher, "matcher");
}
this.anyMatch = Collections.unmodifiableList(new ArrayList<>(matchers));
}
public static OrMatcher create(Matcher...matchers) {
return new OrMatcher(Arrays.asList(matchers));
}
@Override
public boolean matches(EvaluateArgs args) {
for (Matcher m : anyMatch) {
if (m.matches(args)) {
return true;
}
}
return false;
}
}
public static final class AndMatcher implements Matcher {
private final List<? extends Matcher> allMatch;
/** Matches when all of the matchers match. */
public AndMatcher(List<? extends Matcher> matchers) {
checkNotNull(matchers, "matchers");
for (Matcher matcher : matchers) {
checkNotNull(matcher, "matcher");
}
this.allMatch = Collections.unmodifiableList(new ArrayList<>(matchers));
}
public static AndMatcher create(Matcher...matchers) {
return new AndMatcher(Arrays.asList(matchers));
}
@Override
public boolean matches(EvaluateArgs args) {
for (Matcher m : allMatch) {
if (!m.matches(args)) {
return false;
}
}
return true;
}
}
/** Always true matcher.*/
public static final class AlwaysTrueMatcher implements Matcher {
public static AlwaysTrueMatcher INSTANCE = new AlwaysTrueMatcher();
@Override
public boolean matches(EvaluateArgs args) {
return true;
}
}
/** Negate matcher.*/
public static final class InvertMatcher implements Matcher {
private final Matcher toInvertMatcher;
public InvertMatcher(Matcher matcher) {
this.toInvertMatcher = checkNotNull(matcher, "matcher");
}
@Override
public boolean matches(EvaluateArgs args) {
return !toInvertMatcher.matches(args);
}
}
}