Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ok-http: Per-rpc call option authority verification #11754

Open
wants to merge 35 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
c31995e
In-progress changes for Authority verify in okhttp transport.
kannanjgithub Nov 29, 2024
dd95f8f
in-progress changes.
kannanjgithub Dec 2, 2024
4d71cce
commit
kannanjgithub Dec 4, 2024
909b863
Fixes.
kannanjgithub Dec 4, 2024
24500f4
Changes.
kannanjgithub Dec 4, 2024
60bfa06
In progress changes.
kannanjgithub Dec 14, 2024
23a0822
in-progress changes.
kannanjgithub Dec 14, 2024
0a9124c
in-progress changes.
kannanjgithub Dec 14, 2024
f9305e7
in-progress changes.
kannanjgithub Dec 14, 2024
4af94ec
in-progress changes.
kannanjgithub Dec 14, 2024
ece5487
Merge branch 'grpc:master' into authorityverifyokhttp
kannanjgithub Dec 15, 2024
aa59965
Unit tests and using HostnameVerifier in per-rpc.
kannanjgithub Dec 15, 2024
20fa07d
Merge remote-tracking branch 'origin/authorityverifyokhttp' into auth…
kannanjgithub Dec 15, 2024
746717e
Revert unintended changes.
kannanjgithub Dec 16, 2024
0d310b3
Revert unintended changes.
kannanjgithub Dec 16, 2024
3e2ef72
Address review comments.
kannanjgithub Dec 18, 2024
30b1e14
Address review comments.
kannanjgithub Dec 18, 2024
f996474
Added flag with default false for the per-rpc authority check and rem…
kannanjgithub Dec 19, 2024
f5b3614
Update README etc to reference 1.69.0
kannanjgithub Dec 9, 2024
86b9529
:Revert "Update README etc to reference 1.69.0"
kannanjgithub Dec 20, 2024
60b1ee0
Fix style.
kannanjgithub Jan 7, 2025
89b24f2
Merge branch 'master' into authorityverifyokhttp
kannanjgithub Jan 13, 2025
ecbf7b7
Use reflection to access X509ExtendedTrustManager.
kannanjgithub Jan 13, 2025
26a94c9
Merge remote-tracking branch 'origin/master' into authorityverifyokhttp
kannanjgithub Jan 13, 2025
ce800f7
Merge remote-tracking branch 'origin/authorityverifyokhttp' into auth…
kannanjgithub Jan 13, 2025
649f53c
Some changes based on similar comments in the authority check for Net…
kannanjgithub Jan 17, 2025
73bb42f
Animal sniffer suppress
kannanjgithub Jan 17, 2025
2af1cca
Ignore animal sniffer errors via annotation in tests.
kannanjgithub Jan 22, 2025
fb0e733
Changes to move the authority verification logic to the stream creati…
kannanjgithub Feb 3, 2025
a8f696f
fix style
kannanjgithub Feb 4, 2025
49f058d
Fix test
kannanjgithub Feb 4, 2025
2a04f62
style checks.
kannanjgithub Feb 4, 2025
8880733
Review comments
kannanjgithub Feb 28, 2025
0c5f1af
Merge remote-tracking branch 'origin/master' into authorityverifyokhttp
kannanjgithub Feb 28, 2025
671b6a7
Style fixes
kannanjgithub Feb 28, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 15 additions & 15 deletions api/src/main/java/io/grpc/ManagedChannelRegistry.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ public int compare(ManagedChannelProvider o1, ManagedChannelProvider o2) {
public static synchronized ManagedChannelRegistry getDefaultRegistry() {
if (instance == null) {
List<ManagedChannelProvider> providerList = ServiceProviders.loadAll(
ManagedChannelProvider.class,
getHardCodedClasses(),
ManagedChannelProvider.class.getClassLoader(),
new ManagedChannelPriorityAccessor());
ManagedChannelProvider.class,
getHardCodedClasses(),
ManagedChannelProvider.class.getClassLoader(),
new ManagedChannelPriorityAccessor());
instance = new ManagedChannelRegistry();
for (ManagedChannelProvider provider : providerList) {
logger.fine("Service loader found " + provider);
Expand Down Expand Up @@ -157,7 +157,7 @@ ManagedChannelBuilder<?> newChannelBuilder(String target, ChannelCredentials cre

@VisibleForTesting
ManagedChannelBuilder<?> newChannelBuilder(NameResolverRegistry nameResolverRegistry,
String target, ChannelCredentials creds) {
String target, ChannelCredentials creds) {
NameResolverProvider nameResolverProvider = null;
try {
URI uri = new URI(target);
Expand All @@ -167,23 +167,23 @@ ManagedChannelBuilder<?> newChannelBuilder(NameResolverRegistry nameResolverRegi
}
if (nameResolverProvider == null) {
nameResolverProvider = nameResolverRegistry.getProviderForScheme(
nameResolverRegistry.getDefaultScheme());
nameResolverRegistry.getDefaultScheme());
}
Collection<Class<? extends SocketAddress>> nameResolverSocketAddressTypes
= (nameResolverProvider != null)
? nameResolverProvider.getProducedSocketAddressTypes() :
Collections.emptySet();
= (nameResolverProvider != null)
? nameResolverProvider.getProducedSocketAddressTypes() :
Collections.emptySet();

List<ManagedChannelProvider> providers = providers();
if (providers.isEmpty()) {
throw new ProviderNotFoundException("No functional channel service provider found. "
+ "Try adding a dependency on the grpc-okhttp, grpc-netty, or grpc-netty-shaded "
+ "artifact");
+ "Try adding a dependency on the grpc-okhttp, grpc-netty, or grpc-netty-shaded "
+ "artifact");
}
StringBuilder error = new StringBuilder();
for (ManagedChannelProvider provider : providers()) {
Collection<Class<? extends SocketAddress>> channelProviderSocketAddressTypes
= provider.getSupportedSocketAddressTypes();
= provider.getSupportedSocketAddressTypes();
if (!channelProviderSocketAddressTypes.containsAll(nameResolverSocketAddressTypes)) {
error.append("; ");
error.append(provider.getClass().getName());
Expand All @@ -192,7 +192,7 @@ ManagedChannelBuilder<?> newChannelBuilder(NameResolverRegistry nameResolverRegi
continue;
}
ManagedChannelProvider.NewChannelBuilderResult result
= provider.newChannelBuilder(target, creds);
= provider.newChannelBuilder(target, creds);
if (result.getChannelBuilder() != null) {
return result.getChannelBuilder();
}
Expand All @@ -205,7 +205,7 @@ ManagedChannelBuilder<?> newChannelBuilder(NameResolverRegistry nameResolverRegi
}

private static final class ManagedChannelPriorityAccessor
implements ServiceProviders.PriorityAccessor<ManagedChannelProvider> {
implements ServiceProviders.PriorityAccessor<ManagedChannelProvider> {
@Override
public boolean isAvailable(ManagedChannelProvider provider) {
return provider.isAvailable();
Expand All @@ -225,4 +225,4 @@ public ProviderNotFoundException(String msg) {
super(msg);
}
}
}
}
80 changes: 80 additions & 0 deletions core/src/main/java/io/grpc/internal/CertificateUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Copyright 2024 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.internal;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.x500.X500Principal;

/**
* Contains certificate/key PEM file utility method(s) for internal usage.
*/
public class CertificateUtils {

Check warning on line 36 in core/src/main/java/io/grpc/internal/CertificateUtils.java

View check run for this annotation

Codecov / codecov/patch

core/src/main/java/io/grpc/internal/CertificateUtils.java#L36

Added line #L36 was not covered by tests
/**
* Creates X509TrustManagers using the provided CA certs.
*/
public static TrustManager[] createTrustManager(byte[] rootCerts)
throws GeneralSecurityException {
InputStream rootCertsStream = new ByteArrayInputStream(rootCerts);
try {
return io.grpc.internal.CertificateUtils.createTrustManager(rootCertsStream);
} finally {
GrpcUtil.closeQuietly(rootCertsStream);
}
}

/**
* Creates X509TrustManagers using the provided input stream of CA certs.
*/
public static TrustManager[] createTrustManager(InputStream rootCerts)
throws GeneralSecurityException {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
try {
ks.load(null, null);
} catch (IOException ex) {

Check warning on line 58 in core/src/main/java/io/grpc/internal/CertificateUtils.java

View check run for this annotation

Codecov / codecov/patch

core/src/main/java/io/grpc/internal/CertificateUtils.java#L58

Added line #L58 was not covered by tests
// Shouldn't really happen, as we're not loading any data.
throw new GeneralSecurityException(ex);

Check warning on line 60 in core/src/main/java/io/grpc/internal/CertificateUtils.java

View check run for this annotation

Codecov / codecov/patch

core/src/main/java/io/grpc/internal/CertificateUtils.java#L60

Added line #L60 was not covered by tests
}
X509Certificate[] certs = CertificateUtils.getX509Certificates(rootCerts);
for (X509Certificate cert : certs) {
X500Principal principal = cert.getSubjectX500Principal();
ks.setCertificateEntry(principal.getName("RFC2253"), cert);
}

TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(ks);
return trustManagerFactory.getTrustManagers();
}

private static X509Certificate[] getX509Certificates(InputStream inputStream)
throws CertificateException {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certs = factory.generateCertificates(inputStream);
return certs.toArray(new X509Certificate[0]);
}
}
2 changes: 2 additions & 0 deletions examples/example-tls/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ def grpcVersion = '1.70.0-SNAPSHOT' // CURRENT_GRPC_VERSION
def protocVersion = '3.25.5'

dependencies {
implementation "io.grpc:grpc-api:${grpcVersion}"
implementation "io.grpc:grpc-okhttp:${grpcVersion}"
implementation "io.grpc:grpc-protobuf:${grpcVersion}"
implementation "io.grpc:grpc-stub:${grpcVersion}"
compileOnly "org.apache.tomcat:annotations-api:6.0.53"
Expand Down
49 changes: 14 additions & 35 deletions okhttp/src/main/java/io/grpc/okhttp/OkHttpChannelBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package io.grpc.okhttp;

import static com.google.common.base.Preconditions.checkNotNull;
import static io.grpc.internal.CertificateUtils.createTrustManager;
import static io.grpc.internal.GrpcUtil.DEFAULT_KEEPALIVE_TIMEOUT_NANOS;
import static io.grpc.internal.GrpcUtil.KEEPALIVE_TIME_NANOS_DISABLED;

Expand Down Expand Up @@ -81,8 +82,6 @@
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.x500.X500Principal;

/** Convenience class for building channels with the OkHttp transport. */
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1785")
Expand All @@ -91,6 +90,7 @@ public final class OkHttpChannelBuilder extends ForwardingChannelBuilder2<OkHttp
public static final int DEFAULT_FLOW_CONTROL_WINDOW = 65535;

private final ManagedChannelImplBuilder managedChannelImplBuilder;
private final ChannelCredentials channelCredentials;
private TransportTracer.Factory transportTracerFactory = TransportTracer.getDefaultFactory();


Expand Down Expand Up @@ -208,6 +208,7 @@ private OkHttpChannelBuilder(String target) {
new OkHttpChannelTransportFactoryBuilder(),
new OkHttpChannelDefaultPortProvider());
this.freezeSecurityConfiguration = false;
this.channelCredentials = null;
}

OkHttpChannelBuilder(
Expand All @@ -220,6 +221,7 @@ private OkHttpChannelBuilder(String target) {
this.sslSocketFactory = factory;
this.negotiationType = factory == null ? NegotiationType.PLAINTEXT : NegotiationType.TLS;
this.freezeSecurityConfiguration = true;
this.channelCredentials = channelCreds;
}

private final class OkHttpChannelTransportFactoryBuilder
Expand Down Expand Up @@ -536,7 +538,8 @@ OkHttpTransportFactory buildTransportFactory() {
keepAliveWithoutCalls,
maxInboundMetadataSize,
transportTracerFactory,
useGetForSafeMethods);
useGetForSafeMethods,
channelCredentials);
}

OkHttpChannelBuilder disableCheckAuthority() {
Expand Down Expand Up @@ -702,35 +705,6 @@ static KeyManager[] createKeyManager(InputStream certChain, InputStream privateK
return keyManagerFactory.getKeyManagers();
}

static TrustManager[] createTrustManager(byte[] rootCerts) throws GeneralSecurityException {
InputStream rootCertsStream = new ByteArrayInputStream(rootCerts);
try {
return createTrustManager(rootCertsStream);
} finally {
GrpcUtil.closeQuietly(rootCertsStream);
}
}

static TrustManager[] createTrustManager(InputStream rootCerts) throws GeneralSecurityException {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
try {
ks.load(null, null);
} catch (IOException ex) {
// Shouldn't really happen, as we're not loading any data.
throw new GeneralSecurityException(ex);
}
X509Certificate[] certs = CertificateUtils.getX509Certificates(rootCerts);
for (X509Certificate cert : certs) {
X500Principal principal = cert.getSubjectX500Principal();
ks.setCertificateEntry(principal.getName("RFC2253"), cert);
}

TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(ks);
return trustManagerFactory.getTrustManagers();
}

static Collection<Class<? extends SocketAddress>> getSupportedSocketAddressTypes() {
return Collections.singleton(InetSocketAddress.class);
}
Expand Down Expand Up @@ -799,6 +773,7 @@ static final class OkHttpTransportFactory implements ClientTransportFactory {
private final boolean keepAliveWithoutCalls;
final int maxInboundMetadataSize;
final boolean useGetForSafeMethods;
private final ChannelCredentials channelCredentials;
private boolean closed;

private OkHttpTransportFactory(
Expand All @@ -816,7 +791,8 @@ private OkHttpTransportFactory(
boolean keepAliveWithoutCalls,
int maxInboundMetadataSize,
TransportTracer.Factory transportTracerFactory,
boolean useGetForSafeMethods) {
boolean useGetForSafeMethods,
ChannelCredentials channelCredentials) {
this.executorPool = executorPool;
this.executor = executorPool.getObject();
this.scheduledExecutorServicePool = scheduledExecutorServicePool;
Expand All @@ -834,6 +810,7 @@ private OkHttpTransportFactory(
this.keepAliveWithoutCalls = keepAliveWithoutCalls;
this.maxInboundMetadataSize = maxInboundMetadataSize;
this.useGetForSafeMethods = useGetForSafeMethods;
this.channelCredentials = channelCredentials;

this.transportTracerFactory =
Preconditions.checkNotNull(transportTracerFactory, "transportTracerFactory");
Expand Down Expand Up @@ -861,7 +838,8 @@ public void run() {
options.getUserAgent(),
options.getEagAttributes(),
options.getHttpConnectProxiedSocketAddress(),
tooManyPingsRunnable);
tooManyPingsRunnable,
channelCredentials);
if (enableKeepAlive) {
transport.enableKeepAlive(
true, keepAliveTimeNanosState.get(), keepAliveTimeoutNanos, keepAliveWithoutCalls);
Expand Down Expand Up @@ -897,7 +875,8 @@ public SwapChannelCredentialsResult swapChannelCredentials(ChannelCredentials ch
keepAliveWithoutCalls,
maxInboundMetadataSize,
transportTracerFactory,
useGetForSafeMethods);
useGetForSafeMethods,
channelCredentials);
return new SwapChannelCredentialsResult(factory, result.callCredentials);
}

Expand Down
Loading
Loading