aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTobias Thierer <tobiast@google.com>2017-06-20 15:26:19 +0100
committerTobias Thierer <tobiast@google.com>2017-06-20 15:27:20 +0100
commit000ce05d401c1b93b4d1fb8274b57ece1c452a59 (patch)
treee0dcf08fffd3b90666e337b0cbce9e528a4aa570
parentd7b47681aee17cb023ebd352ac51a96c1bd0c8f1 (diff)
downloadconscrypt-000ce05d401c1b93b4d1fb8274b57ece1c452a59.tar.gz
Revert "Merge upstream master". DO NOT MERGE ANYWHERE.
The update of conscrypt changed APIs that affected tests covered by CTS. This reverts commit e550f1a85730f12adee263689af2f47f2e913b63, reversing changes made to d4695f2bf909c88216bbe23087eb167d1c68eede. This is a clean revert. The upload hook to fix lint errors was not run (this CL was uploaded with --no-verify). Bug: 62424503 Test: make checkbuild Test: cts-tradefed run singleCommand cts -a arm64-v8a -m CtsLibcoreTestCases Change-Id: I54f055a2b50bcf45e78b490f7cd9258037ff408b
-rw-r--r--build.gradle2
-rw-r--r--common/src/jni/main/cpp/NativeCrypto.cpp13
-rw-r--r--common/src/main/java/org/conscrypt/NativeCrypto.java9
-rw-r--r--common/src/main/java/org/conscrypt/OpenSSLEngineImpl.java20
-rw-r--r--common/src/main/java/org/conscrypt/OpenSSLEngineSocketImpl.java89
-rw-r--r--common/src/main/java/org/conscrypt/OpenSSLExtendedSessionImpl.java30
-rw-r--r--common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java75
-rw-r--r--common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java18
-rw-r--r--common/src/main/java/org/conscrypt/OpenSSLSocketImplWrapper.java6
-rw-r--r--common/src/main/java/org/conscrypt/SSLParametersImpl.java18
-rw-r--r--gradle/wrapper/gradle-wrapper.jarbin54783 -> 54213 bytes
-rw-r--r--gradle/wrapper/gradle-wrapper.properties4
-rw-r--r--libcore-stub/src/main/java/libcore/java/security/CpuFeatures.java72
-rw-r--r--libcore-stub/src/main/java/libcore/java/security/StandardNames.java194
-rw-r--r--libcore-stub/src/main/java/libcore/java/security/TestKeyStore.java (renamed from testing/src/main/java/libcore/java/security/TestKeyStore.java)0
-rw-r--r--libcore-stub/src/main/java/libcore/javax/net/ssl/FakeSSLSession.java (renamed from testing/src/main/java/libcore/javax/net/ssl/FakeSSLSession.java)0
-rw-r--r--libcore-stub/src/main/java/libcore/javax/net/ssl/TestKeyManager.java (renamed from testing/src/main/java/libcore/javax/net/ssl/TestKeyManager.java)0
-rw-r--r--libcore-stub/src/main/java/libcore/javax/net/ssl/TestTrustManager.java (renamed from testing/src/main/java/libcore/javax/net/ssl/TestTrustManager.java)0
-rw-r--r--openjdk-benchmarks/build.gradle21
-rw-r--r--openjdk-integ-tests/build.gradle29
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/AbstractSSLTest.java31
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/HttpsURLConnectionTest.java164
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java304
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/KeyStoreBuilderParametersTest.java99
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SNIHostNameTest.java46
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLContextTest.java640
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java885
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLParametersTest.java226
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java32
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java76
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSessionContextTest.java337
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java346
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java93
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java2261
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java333
-rw-r--r--openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/X509KeyManagerTest.java79
-rw-r--r--openjdk/build.gradle201
-rw-r--r--openjdk/src/main/java/org/conscrypt/Platform.java199
-rw-r--r--openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java12
-rw-r--r--openjdk/src/test/java/org/conscrypt/OpenSSLEngineImplTest.java2
-rw-r--r--openjdk/src/test/java/org/conscrypt/OpenSSLExtendedSessionImplTest.java46
-rw-r--r--openjdk/src/test/java/org/conscrypt/OpenSSLSocketImplTest.java202
-rw-r--r--openjdk/src/test/java/org/conscrypt/PlatformTest.java86
-rw-r--r--settings.gradle30
-rw-r--r--testing/src/main/java/libcore/javax/net/ssl/ForwardingX509ExtendedKeyManager.java64
-rw-r--r--testing/src/main/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java95
-rw-r--r--testing/src/main/java/libcore/javax/net/ssl/RandomPrivateKeyX509ExtendedKeyManager.java85
-rw-r--r--testing/src/main/java/libcore/javax/net/ssl/SSLConfigurationAsserts.java228
-rw-r--r--testing/src/main/java/libcore/javax/net/ssl/TestSSLContext.java474
-rw-r--r--testing/src/main/java/libcore/javax/net/ssl/TestSSLEnginePair.java213
-rw-r--r--testing/src/main/java/libcore/javax/net/ssl/TestSSLSessions.java66
-rw-r--r--testing/src/main/java/libcore/javax/net/ssl/TestSSLSocketPair.java125
-rw-r--r--testing/src/main/java/libcore/tlswire/handshake/CipherSuite.java455
-rw-r--r--testing/src/main/java/libcore/tlswire/handshake/ClientHello.java100
-rw-r--r--testing/src/main/java/libcore/tlswire/handshake/CompressionMethod.java67
-rw-r--r--testing/src/main/java/libcore/tlswire/handshake/EllipticCurve.java77
-rw-r--r--testing/src/main/java/libcore/tlswire/handshake/EllipticCurvesHelloExtension.java54
-rw-r--r--testing/src/main/java/libcore/tlswire/handshake/HandshakeMessage.java58
-rw-r--r--testing/src/main/java/libcore/tlswire/handshake/HelloExtension.java99
-rw-r--r--testing/src/main/java/libcore/tlswire/handshake/ServerNameHelloExtension.java52
-rw-r--r--testing/src/main/java/libcore/tlswire/record/TlsProtocols.java27
-rw-r--r--testing/src/main/java/libcore/tlswire/record/TlsRecord.java38
-rw-r--r--testing/src/main/java/libcore/tlswire/util/IoUtils.java52
-rw-r--r--testing/src/main/java/libcore/tlswire/util/TlsProtocolVersion.java87
-rw-r--r--testing/src/main/java/org/conscrypt/TestUtils.java98
-rw-r--r--testing/src/main/java/tests/net/DelegatingSSLSocketFactory.java81
-rw-r--r--testing/src/main/java/tests/net/DelegatingSocketFactory.java66
-rw-r--r--testing/src/main/java/tests/util/ForEachRunner.java49
-rw-r--r--testing/src/main/java/tests/util/Pair.java98
69 files changed, 512 insertions, 9726 deletions
diff --git a/build.gradle b/build.gradle
index e821006a..18e8b483 100644
--- a/build.gradle
+++ b/build.gradle
@@ -12,7 +12,7 @@ buildscript {
// so we can access Git from our
// build script.
classpath 'org.ajoberstar:grgit:1.1.0'
- classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.10'
+ classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.9'
}
}
diff --git a/common/src/jni/main/cpp/NativeCrypto.cpp b/common/src/jni/main/cpp/NativeCrypto.cpp
index b8ca3c33..e021b935 100644
--- a/common/src/jni/main/cpp/NativeCrypto.cpp
+++ b/common/src/jni/main/cpp/NativeCrypto.cpp
@@ -568,10 +568,6 @@ size_t RsaMethodSize(const RSA *rsa) {
return ex_data->cached_size;
}
-// TODO(davidben): Remove this once
-// https://boringssl-review.googlesource.com/c/15864/ is in all Conscrypt
-// consumers.
-#if BORINGSSL_API_VERSION < 4
int RsaMethodEncrypt(RSA* /* rsa */,
size_t* /* out_len */,
uint8_t* /* out */,
@@ -582,7 +578,6 @@ int RsaMethodEncrypt(RSA* /* rsa */,
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE);
return 0;
}
-#endif
int RsaMethodSignRaw(RSA* rsa,
size_t* out_len,
@@ -755,12 +750,8 @@ void init_engine_globals() {
g_rsa_method.common.is_static = 1;
g_rsa_method.size = RsaMethodSize;
- // TODO(davidben): Remove this once
- // https://boringssl-review.googlesource.com/c/15864/ is in all Conscrypt
- // consumers.
-#if BORINGSSL_API_VERSION < 4
+ // TODO(davidben): Update BoringSSL to ignore this hook and remove this.
g_rsa_method.encrypt = RsaMethodEncrypt;
-#endif
g_rsa_method.sign_raw = RsaMethodSignRaw;
g_rsa_method.decrypt = RsaMethodDecrypt;
g_rsa_method.flags = RSA_FLAG_OPAQUE;
@@ -7631,6 +7622,8 @@ static void NativeCrypto_SSL_shutdown(JNIEnv* env, jclass, jlong ssl_address,
return;
}
if (fdObject == nullptr) {
+ Errors::jniThrowNullPointerException(env, "fd == null");
+ JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown => fd == null", ssl);
return;
}
if (shc == nullptr) {
diff --git a/common/src/main/java/org/conscrypt/NativeCrypto.java b/common/src/main/java/org/conscrypt/NativeCrypto.java
index 33e470a2..509b2ef1 100644
--- a/common/src/main/java/org/conscrypt/NativeCrypto.java
+++ b/common/src/main/java/org/conscrypt/NativeCrypto.java
@@ -724,8 +724,7 @@ public final class NativeCrypto {
// prevent apps from connecting to servers they were previously able to connect to.
/** X.509 based cipher suites enabled by default (if requested), in preference order. */
- static final boolean HAS_AES_HARDWARE = EVP_has_aes_hardware() == 1;
- static final String[] DEFAULT_X509_CIPHER_SUITES = HAS_AES_HARDWARE ?
+ static final String[] DEFAULT_X509_CIPHER_SUITES = EVP_has_aes_hardware() == 1 ?
new String[] {
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
@@ -761,10 +760,8 @@ public final class NativeCrypto {
/** TLS-PSK cipher suites enabled by default (if requested), in preference order. */
static final String[] DEFAULT_PSK_CIPHER_SUITES = new String[] {
- "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA",
- "TLS_PSK_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", "TLS_PSK_WITH_AES_128_CBC_SHA",
"TLS_PSK_WITH_AES_256_CBC_SHA",
};
diff --git a/common/src/main/java/org/conscrypt/OpenSSLEngineImpl.java b/common/src/main/java/org/conscrypt/OpenSSLEngineImpl.java
index d12d4d8c..86245be8 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLEngineImpl.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLEngineImpl.java
@@ -369,7 +369,7 @@ final class OpenSSLEngineImpl extends SSLEngine implements NativeCrypto.SSLHands
String logMessage = String.format("ssl_unexpected_ccs: host=%s", getSniHostname());
Platform.logEvent(logMessage);
}
- throw SSLUtils.toSSLHandshakeException(e);
+ throw new SSLException(e);
} finally {
if (releaseResources) {
engineState = EngineState.CLOSED;
@@ -399,7 +399,7 @@ final class OpenSSLEngineImpl extends SSLEngine implements NativeCrypto.SSLHands
if (engineState == EngineState.CLOSED || engineState == EngineState.CLOSED_OUTBOUND) {
return;
}
- if (isHandshakeStarted()) {
+ if (engineState != EngineState.MODE_SET && engineState != EngineState.NEW) {
shutdownAndFreeSslNative();
}
if (engineState == EngineState.CLOSED_INBOUND) {
@@ -575,7 +575,7 @@ final class OpenSSLEngineImpl extends SSLEngine implements NativeCrypto.SSLHands
@Override
public void setUseClientMode(boolean mode) {
synchronized (stateLock) {
- if (isHandshakeStarted()) {
+ if (engineState != EngineState.MODE_SET && engineState != EngineState.NEW) {
throw new IllegalArgumentException(
"Can not change mode after handshake: engineState == " + engineState);
}
@@ -1317,11 +1317,6 @@ final class OpenSSLEngineImpl extends SSLEngine implements NativeCrypto.SSLHands
public void onSSLStateChange(int type, int val) {
synchronized (stateLock) {
switch (type) {
- case SSL_CB_HANDSHAKE_START:
- // For clients, this will allow the NEED_UNWRAP status to be
- // returned.
- engineState = EngineState.HANDSHAKE_STARTED;
- break;
case SSL_CB_HANDSHAKE_DONE:
if (engineState != EngineState.HANDSHAKE_STARTED
&& engineState != EngineState.READY_HANDSHAKE_CUT_THROUGH) {
@@ -1330,7 +1325,11 @@ final class OpenSSLEngineImpl extends SSLEngine implements NativeCrypto.SSLHands
}
engineState = EngineState.HANDSHAKE_COMPLETED;
break;
-
+ case SSL_CB_HANDSHAKE_START:
+ // For clients, this will allow the NEED_UNWRAP status to be
+ // returned.
+ engineState = EngineState.HANDSHAKE_STARTED;
+ break;
}
}
}
@@ -1357,7 +1356,8 @@ final class OpenSSLEngineImpl extends SSLEngine implements NativeCrypto.SSLHands
NativeCrypto.SSL_get1_session(sslNativePointer), null, peerCertChain, ocspData,
tlsSctData, getSniHostname(), getPeerPort(), null);
- if (getUseClientMode()) {
+ boolean client = sslParameters.getUseClientMode();
+ if (client) {
Platform.checkServerTrusted(x509tm, peerCertChain, authMethod, this);
} else {
String authType = peerCertChain[0].getPublicKey().getAlgorithm();
diff --git a/common/src/main/java/org/conscrypt/OpenSSLEngineSocketImpl.java b/common/src/main/java/org/conscrypt/OpenSSLEngineSocketImpl.java
index 7e711d8a..e87e9a0d 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLEngineSocketImpl.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLEngineSocketImpl.java
@@ -23,7 +23,6 @@ import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
@@ -50,31 +49,6 @@ final class OpenSSLEngineSocketImpl extends OpenSSLSocketImplWrapper {
private final InputStreamWrapper inputStreamWrapper;
private boolean handshakeComplete;
- OpenSSLEngineSocketImpl(SSLParametersImpl sslParameters) throws IOException {
- this(new Socket(), null, -1, false, sslParameters);
- }
-
- OpenSSLEngineSocketImpl(String host, int port, SSLParametersImpl sslParameters)
- throws IOException {
- this(new Socket(host, port), host, port, false, sslParameters);
- }
-
- OpenSSLEngineSocketImpl(String host, int port, InetAddress clientAddress, int clientPort,
- SSLParametersImpl sslParameters) throws IOException {
- this(new Socket(host, port, clientAddress, clientPort), host, port, false, sslParameters);
- }
-
- OpenSSLEngineSocketImpl(InetAddress address, int port, SSLParametersImpl sslParameters)
- throws IOException {
- this(new Socket(address, port), null, port, false, sslParameters);
- }
-
- OpenSSLEngineSocketImpl(InetAddress address, int port, InetAddress clientAddress,
- int clientPort, SSLParametersImpl sslParameters) throws IOException {
- this(new Socket(address, port, clientAddress, clientPort), null, port, false,
- sslParameters);
- }
-
OpenSSLEngineSocketImpl(Socket socket, String hostname, int port, boolean autoClose,
SSLParametersImpl sslParameters) throws IOException {
super(socket, hostname, port, autoClose, sslParameters);
@@ -98,44 +72,37 @@ final class OpenSSLEngineSocketImpl extends OpenSSLSocketImplWrapper {
@Override
public void startHandshake() throws IOException {
- try {
- // Trigger the handshake
- boolean beginHandshakeCalled = false;
- while (!handshakeComplete) {
- switch (engine.getHandshakeStatus()) {
- case NOT_HANDSHAKING: {
- if (!beginHandshakeCalled) {
- beginHandshakeCalled = true;
- engine.beginHandshake();
- break;
- }
+ // Trigger the handshake
+ boolean beginHandshakeCalled = false;
+ while (!handshakeComplete) {
+ switch (engine.getHandshakeStatus()) {
+ case NOT_HANDSHAKING: {
+ if (!beginHandshakeCalled) {
+ beginHandshakeCalled = true;
+ engine.beginHandshake();
break;
}
- case FINISHED: {
- return;
- }
- case NEED_WRAP: {
- outputStreamWrapper.write(EMPTY_BUFFER);
- break;
- }
- case NEED_UNWRAP: {
- if (inputStreamWrapper.read(EmptyArray.BYTE) == -1) {
- // Can't complete the handshake due to EOF.
- throw SSLUtils.toSSLHandshakeException(new EOFException());
- }
- break;
- }
- case NEED_TASK: {
- throw new IllegalStateException("OpenSSLEngineImpl returned NEED_TASK");
- }
- default: {
- break;
+ break;
+ }
+ case FINISHED: {
+ return;
+ }
+ case NEED_WRAP: {
+ outputStreamWrapper.write(EMPTY_BUFFER);
+ break;
+ }
+ case NEED_UNWRAP: {
+ if (inputStreamWrapper.read(EmptyArray.BYTE) == -1) {
+ // Can't complete the handshake due to EOF.
+ throw new EOFException();
}
+ break;
+ }
+ case NEED_TASK: {
+ throw new IllegalStateException("OpenSSLEngineImpl returned NEED_TASK");
}
+ default: { break; }
}
- } catch (Exception e) {
- close();
- throw SSLUtils.toSSLHandshakeException(e);
}
}
@@ -427,8 +394,10 @@ final class OpenSSLEngineSocketImpl extends OpenSSLSocketImplWrapper {
}
} while (len > 0);
} catch (IOException e) {
+ e.printStackTrace();
throw e;
} catch (RuntimeException e) {
+ e.printStackTrace();
throw e;
}
}
@@ -572,8 +541,10 @@ final class OpenSSLEngineSocketImpl extends OpenSSLSocketImplWrapper {
// Continue the loop and return the data from the engine buffer.
}
} catch (IOException e) {
+ e.printStackTrace();
throw e;
} catch (RuntimeException e) {
+ e.printStackTrace();
throw e;
}
}
diff --git a/common/src/main/java/org/conscrypt/OpenSSLExtendedSessionImpl.java b/common/src/main/java/org/conscrypt/OpenSSLExtendedSessionImpl.java
index dead13d2..56411aad 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLExtendedSessionImpl.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLExtendedSessionImpl.java
@@ -15,13 +15,13 @@
*/
package org.conscrypt;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collections;
import java.util.List;
import javax.net.ssl.ExtendedSSLSession;
+import javax.net.ssl.SNIHostName;
+import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSessionContext;
import javax.security.cert.X509Certificate;
@@ -71,26 +71,14 @@ final class OpenSSLExtendedSessionImpl extends ExtendedSSLSession {
}
/* @Override */
- // For Android/Java7 backward-compatibility.
- @SuppressWarnings({"MissingOverride", "unchecked", "rawtypes", "LiteralClassName"})
- public List getRequestedServerNames() {
- try {
- String requestedServerName = delegate.getRequestedServerName();
- if (requestedServerName == null) {
- return null;
- }
-
- Constructor sniHostNameConstructor =
- Class.forName("javax.net.ssl.SNIHostName").getConstructor(String.class);
- return Collections.singletonList(sniHostNameConstructor.newInstance(requestedServerName));
-
- } catch (NoSuchMethodException e) {
- } catch (InvocationTargetException e) {
- } catch (IllegalAccessException e) {
- } catch (ClassNotFoundException e) {
- } catch (InstantiationException e) {
+ @SuppressWarnings("MissingOverride") // For Android backward-compatibility.
+ public List<SNIServerName> getRequestedServerNames() {
+ String requestedServerName = delegate.getRequestedServerName();
+ if (requestedServerName == null) {
+ return null;
}
- return null;
+
+ return Collections.<SNIServerName> singletonList(new SNIHostName(requestedServerName));
}
@Override
diff --git a/common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java b/common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java
index 1794d9b9..8e38e535 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java
@@ -80,47 +80,27 @@ final class OpenSSLSocketFactoryImpl extends SSLSocketFactory {
if (instantiationException != null) {
throw instantiationException;
}
- if (useEngineSocket) {
- return new OpenSSLEngineSocketImpl((SSLParametersImpl) sslParameters.clone());
- } else {
- return new OpenSSLSocketImpl((SSLParametersImpl) sslParameters.clone());
- }
+ return new OpenSSLSocketImpl((SSLParametersImpl) sslParameters.clone());
}
@Override
public Socket createSocket(String hostname, int port) throws IOException, UnknownHostException {
- if (useEngineSocket) {
- return new OpenSSLEngineSocketImpl(hostname, port, (SSLParametersImpl) sslParameters.clone());
- } else {
- return new OpenSSLSocketImpl(hostname, port, (SSLParametersImpl) sslParameters.clone());
- }
+ return new OpenSSLSocketImpl(hostname, port, (SSLParametersImpl) sslParameters.clone());
}
@Override
public Socket createSocket(String hostname, int port, InetAddress localHost, int localPort)
throws IOException, UnknownHostException {
- if (useEngineSocket) {
- return new OpenSSLEngineSocketImpl(hostname,
- port,
- localHost,
- localPort,
- (SSLParametersImpl) sslParameters.clone());
- } else {
- return new OpenSSLSocketImpl(hostname,
- port,
- localHost,
- localPort,
- (SSLParametersImpl) sslParameters.clone());
- }
+ return new OpenSSLSocketImpl(hostname,
+ port,
+ localHost,
+ localPort,
+ (SSLParametersImpl) sslParameters.clone());
}
@Override
public Socket createSocket(InetAddress address, int port) throws IOException {
- if (useEngineSocket) {
- return new OpenSSLEngineSocketImpl(address, port, (SSLParametersImpl) sslParameters.clone());
- } else {
- return new OpenSSLSocketImpl(address, port, (SSLParametersImpl) sslParameters.clone());
- }
+ return new OpenSSLSocketImpl(address, port, (SSLParametersImpl) sslParameters.clone());
}
@Override
@@ -129,25 +109,25 @@ final class OpenSSLSocketFactoryImpl extends SSLSocketFactory {
InetAddress localAddress,
int localPort)
throws IOException {
- if (useEngineSocket) {
- return new OpenSSLEngineSocketImpl(address,
- port,
- localAddress,
- localPort,
- (SSLParametersImpl) sslParameters.clone());
- } else {
- return new OpenSSLSocketImpl(address,
- port,
- localAddress,
- localPort,
- (SSLParametersImpl) sslParameters.clone());
- }
+ return new OpenSSLSocketImpl(address,
+ port,
+ localAddress,
+ localPort,
+ (SSLParametersImpl) sslParameters.clone());
}
@Override
public Socket createSocket(Socket s, String hostname, int port, boolean autoClose)
throws IOException {
- if (hasFileDescriptor(s) && !useEngineSocket) {
+ boolean socketHasFd = false;
+ try {
+ // If socket has a file descriptor we can use OpenSSLSocketImplWrapper directly
+ // otherwise we need to use the engine.
+ socketHasFd = Platform.getFileDescriptor(s) != null;
+ } catch (RuntimeException re) {
+ // Ignore
+ }
+ if (socketHasFd && !useEngineSocket) {
return new OpenSSLSocketImplWrapper(
s, hostname, port, autoClose, (SSLParametersImpl) sslParameters.clone());
} else {
@@ -155,15 +135,4 @@ final class OpenSSLSocketFactoryImpl extends SSLSocketFactory {
s, hostname, port, autoClose, (SSLParametersImpl) sslParameters.clone());
}
}
-
- private boolean hasFileDescriptor(Socket s) {
- try {
- // If socket has a file descriptor we can use OpenSSLSocketImplWrapper directly
- // otherwise we need to use the engine.
- Platform.getFileDescriptor(s);
- return true;
- } catch (RuntimeException re) {
- return false;
- }
- }
}
diff --git a/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java b/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java
index b1dd9219..a50f121a 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java
@@ -438,7 +438,7 @@ public class OpenSSLSocketImpl
try {
shutdownAndFreeSslNative();
} catch (IOException ignored) {
- // Ignored.
+
}
}
}
@@ -702,6 +702,8 @@ public class OpenSSLSocketImpl
* Reads one byte. If there is no data in the underlying buffer,
* this operation can block until the data will be
* available.
+ * @return read value.
+ * @throws IOException
*/
@Override
public int read() throws IOException {
@@ -820,17 +822,9 @@ public class OpenSSLSocketImpl
@Override
public SSLSession getSession() {
if (sslSession == null) {
- boolean handshakeCompleted = false;
try {
- if (isConnected()) {
- waitForHandshake();
- handshakeCompleted = true;
- }
+ waitForHandshake();
} catch (IOException e) {
- // Fall through.
- }
-
- if (!handshakeCompleted) {
// return an invalid session with
// invalid cipher suite of "SSL_NULL_WITH_NULL_NULL"
return SSLNullSession.getNullSession();
@@ -1120,8 +1114,8 @@ public class OpenSSLSocketImpl
public void close() throws IOException {
// TODO: Close SSL sockets using a background thread so they close gracefully.
- SSLInputStream sslInputStream;
- SSLOutputStream sslOutputStream;
+ SSLInputStream sslInputStream = null;
+ SSLOutputStream sslOutputStream = null;
synchronized (stateLock) {
if (state == STATE_CLOSED) {
diff --git a/common/src/main/java/org/conscrypt/OpenSSLSocketImplWrapper.java b/common/src/main/java/org/conscrypt/OpenSSLSocketImplWrapper.java
index 848ef7f8..126dbb24 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLSocketImplWrapper.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLSocketImplWrapper.java
@@ -42,17 +42,17 @@ class OpenSSLSocketImplWrapper extends OpenSSLSocketImpl {
@Override
public void connect(SocketAddress sockaddr, int timeout)
throws IOException {
- socket.connect(sockaddr, timeout);
+ throw new IOException("Underlying socket is already connected.");
}
@Override
public void connect(SocketAddress sockaddr) throws IOException {
- socket.connect(sockaddr);
+ throw new IOException("Underlying socket is already connected.");
}
@Override
public void bind(SocketAddress sockaddr) throws IOException {
- socket.bind(sockaddr);
+ throw new IOException("Underlying socket is already connected.");
}
@Override
diff --git a/common/src/main/java/org/conscrypt/SSLParametersImpl.java b/common/src/main/java/org/conscrypt/SSLParametersImpl.java
index 939401e7..1b1e567a 100644
--- a/common/src/main/java/org/conscrypt/SSLParametersImpl.java
+++ b/common/src/main/java/org/conscrypt/SSLParametersImpl.java
@@ -629,18 +629,14 @@ final class SSLParametersImpl implements Cloneable {
* sockets. For more information on SNI, see RFC 6066 section 3.
*/
private boolean isSniEnabledByDefault() {
- try {
- String enableSNI = System.getProperty("jsse.enableSNIExtension", "true");
- if ("true".equalsIgnoreCase(enableSNI)) {
- return true;
- } else if ("false".equalsIgnoreCase(enableSNI)) {
- return false;
- } else {
- throw new RuntimeException(
- "Can only set \"jsse.enableSNIExtension\" to \"true\" or \"false\"");
- }
- } catch (SecurityException e) {
+ String enableSNI = System.getProperty("jsse.enableSNIExtension", "true");
+ if ("true".equalsIgnoreCase(enableSNI)) {
return true;
+ } else if ("false".equalsIgnoreCase(enableSNI)) {
+ return false;
+ } else {
+ throw new RuntimeException(
+ "Can only set \"jsse.enableSNIExtension\" to \"true\" or \"false\"");
}
}
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 63baaa64..ba146f55 100644
--- a/gradle/wrapper/gradle-wrapper.jar
+++ b/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 5699de36..bf0777a6 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Tue May 16 10:43:56 PDT 2017
+#Mon Jan 30 14:52:09 PST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip
diff --git a/libcore-stub/src/main/java/libcore/java/security/CpuFeatures.java b/libcore-stub/src/main/java/libcore/java/security/CpuFeatures.java
index 1188f4e5..3b7ce36d 100644
--- a/libcore-stub/src/main/java/libcore/java/security/CpuFeatures.java
+++ b/libcore-stub/src/main/java/libcore/java/security/CpuFeatures.java
@@ -16,12 +16,9 @@
package libcore.java.security;
-import static java.nio.charset.StandardCharsets.UTF_8;
-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
-import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
@@ -43,43 +40,22 @@ public class CpuFeatures {
return true;
}
- features = getCpuFeaturesMac();
- if (features != null && features.contains("aes")) {
- return true;
- }
-
// If we're in an emulated ABI, Conscrypt's NativeCrypto might bridge to
// a library that has accelerated AES instructions. See if Conscrypt
// detects that condition.
- Class<?> nativeCrypto = findNativeCrypto();
- if (nativeCrypto != null) {
- try {
- Method EVP_has_aes_hardware =
- nativeCrypto.getDeclaredMethod("EVP_has_aes_hardware");
- EVP_has_aes_hardware.setAccessible(true);
- return ((Integer) EVP_has_aes_hardware.invoke(null)) == 1;
- } catch (NoSuchMethodException | SecurityException | IllegalAccessException
- | IllegalArgumentException ignored) {
- } catch (InvocationTargetException e) {
- throw new IllegalArgumentException(e);
- }
+ try {
+ Class<?> nativeCrypto = Class.forName("com.android.org.conscrypt.NativeCrypto");
+ Method EVP_has_aes_hardware = nativeCrypto.getDeclaredMethod("EVP_has_aes_hardware");
+ return ((Integer) EVP_has_aes_hardware.invoke(null)) == 1;
+ } catch (ClassNotFoundException | NoSuchMethodException | SecurityException
+ | IllegalAccessException | IllegalArgumentException ignored) {
+ } catch (InvocationTargetException e) {
+ throw new IllegalArgumentException(e);
}
return false;
}
- private static Class<?> findNativeCrypto() {
- for (String packageName : new String[]{"com.android.org.conscrypt", "org.conscrypt"}) {
- String name = packageName + ".NativeCrypto";
- try {
- return Class.forName(name);
- } catch (ClassNotFoundException e) {
- // Try the next one.
- }
- }
- return null;
- }
-
private static String getFieldFromCpuinfo(String field) {
try {
@SuppressWarnings("DefaultCharset")
@@ -98,7 +74,6 @@ public class CpuFeatures {
br.close();
}
} catch (IOException ignored) {
- // Ignored.
}
return null;
@@ -111,35 +86,4 @@ public class CpuFeatures {
return Arrays.asList(features.split("\\s"));
}
-
- private static List<String> getCpuFeaturesMac() {
- try {
- StringBuilder output = new StringBuilder();
- Process proc = Runtime.getRuntime().exec("sysctl -a");
- if (proc.waitFor() == 0) {
- BufferedReader reader =
- new BufferedReader(new InputStreamReader(proc.getInputStream(), UTF_8));
-
- final String linePrefix = "machdep.cpu.features:";
-
- String line;
- while ((line = reader.readLine()) != null) {
- line = line.toLowerCase();
- if (line.startsWith(linePrefix)) {
- // Strip the line prefix from the results.
- output.append(line.substring(linePrefix.length())).append(' ');
- }
- }
- if (output.length() > 0) {
- String outputString = output.toString();
- String[] parts = outputString.split("\\s+");
- return Arrays.asList(parts);
- }
- }
- } catch (Exception ignored) {
- // Ignored.
- }
-
- return null;
- }
}
diff --git a/libcore-stub/src/main/java/libcore/java/security/StandardNames.java b/libcore-stub/src/main/java/libcore/java/security/StandardNames.java
index 47231b83..f1560a46 100644
--- a/libcore-stub/src/main/java/libcore/java/security/StandardNames.java
+++ b/libcore-stub/src/main/java/libcore/java/security/StandardNames.java
@@ -28,6 +28,7 @@ import java.security.spec.ECPublicKeySpec;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -37,7 +38,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
-import java.util.TreeSet;
import javax.crypto.spec.DHPrivateKeySpec;
import javax.crypto.spec.DHPublicKeySpec;
@@ -69,7 +69,7 @@ import javax.crypto.spec.DHPublicKeySpec;
public final class StandardNames {
public static final boolean IS_RI =
!"Dalvik Core Library".equals(System.getProperty("java.specification.name"));
- public static final String JSSE_PROVIDER_NAME = "AndroidOpenSSL";
+ public static final String JSSE_PROVIDER_NAME = (IS_RI) ? "SunJSSE" : "AndroidOpenSSL";
public static final String SECURITY_PROVIDER_NAME = (IS_RI) ? "SUN" : "BC";
public static final String KEY_MANAGER_FACTORY_DEFAULT = (IS_RI) ? "SunX509" : "PKIX";
@@ -236,6 +236,10 @@ public final class StandardNames {
provide("MessageDigest", "SHA-384");
provide("MessageDigest", "SHA-512");
provide("Policy", "JavaPolicy");
+ // Android does not support SSLv3
+ if (IS_RI) {
+ provide("SSLContext", "SSLv3");
+ }
provide("SSLContext", "TLSv1");
provide("SSLContext", "TLSv1.1");
provide("SSLContext", "TLSv1.2");
@@ -299,6 +303,10 @@ public final class StandardNames {
// Not documented as in RI 6 but mentioned in Standard Names
provide("AlgorithmParameters", "PBE");
+ // Android does not support SSLv3
+ if (IS_RI) {
+ provide("SSLContext", "SSL");
+ }
provide("SSLContext", "TLS");
// Not documented as in RI 6 but that exist in RI 6
@@ -578,11 +586,21 @@ public final class StandardNames {
}
}
- provideSslContextEnabledProtocols("TLS", TLSVersion.TLSv1, TLSVersion.TLSv12);
- provideSslContextEnabledProtocols("TLSv1", TLSVersion.TLSv1, TLSVersion.TLSv12);
- provideSslContextEnabledProtocols("TLSv1.1", TLSVersion.TLSv1, TLSVersion.TLSv12);
- provideSslContextEnabledProtocols("TLSv1.2", TLSVersion.TLSv1, TLSVersion.TLSv12);
- provideSslContextEnabledProtocols("Default", TLSVersion.TLSv1, TLSVersion.TLSv12);
+ if (IS_RI) {
+ provideSslContextEnabledProtocols("SSL", TLSVersion.SSLv3, TLSVersion.TLSv1);
+ provideSslContextEnabledProtocols("SSLv3", TLSVersion.SSLv3, TLSVersion.TLSv1);
+ provideSslContextEnabledProtocols("TLS", TLSVersion.SSLv3, TLSVersion.TLSv1);
+ provideSslContextEnabledProtocols("TLSv1", TLSVersion.SSLv3, TLSVersion.TLSv1);
+ provideSslContextEnabledProtocols("TLSv1.1", TLSVersion.SSLv3, TLSVersion.TLSv11);
+ provideSslContextEnabledProtocols("TLSv1.2", TLSVersion.SSLv3, TLSVersion.TLSv12);
+ provideSslContextEnabledProtocols("Default", TLSVersion.SSLv3, TLSVersion.TLSv1);
+ } else {
+ provideSslContextEnabledProtocols("TLS", TLSVersion.TLSv1, TLSVersion.TLSv12);
+ provideSslContextEnabledProtocols("TLSv1", TLSVersion.TLSv1, TLSVersion.TLSv12);
+ provideSslContextEnabledProtocols("TLSv1.1", TLSVersion.TLSv1, TLSVersion.TLSv12);
+ provideSslContextEnabledProtocols("TLSv1.2", TLSVersion.TLSv1, TLSVersion.TLSv12);
+ provideSslContextEnabledProtocols("Default", TLSVersion.TLSv1, TLSVersion.TLSv12);
+ }
}
public static final String SSL_CONTEXT_PROTOCOLS_DEFAULT = "Default";
@@ -606,8 +624,23 @@ public final class StandardNames {
new HashSet<String>(Arrays.asList("TLSv1", "TLSv1.1", "TLSv1.2"));
public static final Set<String> SSL_SOCKET_PROTOCOLS_SERVER_DEFAULT =
new HashSet<String>(Arrays.asList("TLSv1", "TLSv1.1", "TLSv1.2"));
+ static {
+ if (IS_RI) {
+ /* Even though we use OpenSSL's SSLv23_method which
+ * supports sending SSLv2 client hello messages, the
+ * OpenSSL implementation in s23_client_hello disables
+ * this if SSL_OP_NO_SSLv2 is specified, which we always
+ * do to disable general use of SSLv2.
+ */
+ SSL_SOCKET_PROTOCOLS.add("SSLv2Hello");
+
+ /* The RI still has SSLv3 as a default protocol. */
+ SSL_SOCKET_PROTOCOLS_CLIENT_DEFAULT.add("SSLv3");
+ SSL_SOCKET_PROTOCOLS_SERVER_DEFAULT.add("SSLv3");
+ }
+ }
- private enum TLSVersion {
+ private static enum TLSVersion {
SSLv3("SSLv3"),
TLSv1("TLSv1"),
TLSv11("TLSv1.1"),
@@ -619,6 +652,7 @@ public final class StandardNames {
this.name = name;
}
}
+ ;
/**
* Valid values for X509TrustManager.checkClientTrusted authType,
@@ -669,9 +703,11 @@ public final class StandardNames {
addBoth("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA");
addBoth("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
addBoth("TLS_RSA_WITH_AES_256_CBC_SHA");
+ addBoth("TLS_DHE_RSA_WITH_AES_256_CBC_SHA");
addBoth("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA");
addBoth("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
addBoth("TLS_RSA_WITH_AES_128_CBC_SHA");
+ addBoth("TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
addBoth("SSL_RSA_WITH_3DES_EDE_CBC_SHA");
// TLSv1.2 cipher suites
@@ -679,6 +715,10 @@ public final class StandardNames {
addBoth("TLS_RSA_WITH_AES_256_CBC_SHA256");
addOpenSsl("TLS_RSA_WITH_AES_128_GCM_SHA256");
addOpenSsl("TLS_RSA_WITH_AES_256_GCM_SHA384");
+ addBoth("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256");
+ addBoth("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256");
+ addOpenSsl("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256");
+ addOpenSsl("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384");
addBoth("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256");
addBoth("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384");
addOpenSsl("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
@@ -738,6 +778,9 @@ public final class StandardNames {
// Dropped
addNeither("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA");
addNeither("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA");
+ addRi("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA");
+ addRi("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA");
+ addRi("SSL_DHE_RSA_WITH_DES_CBC_SHA");
addRi("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
addRi("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5");
addRi("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA");
@@ -793,92 +836,94 @@ public final class StandardNames {
addNeither("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA");
addNeither("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5");
- CIPHER_SUITES = CIPHER_SUITES_OPENSSL;
+ CIPHER_SUITES = (IS_RI) ? CIPHER_SUITES_RI : CIPHER_SUITES_OPENSSL;
}
/**
* Cipher suites that are not negotiated when TLSv1.2 is selected on the RI.
*/
public static final List<String> CIPHER_SUITES_OBSOLETE_TLS12 = Arrays.asList(
- "SSL_RSA_WITH_DES_CBC_SHA",
- "SSL_DHE_RSA_WITH_DES_CBC_SHA",
- "SSL_DHE_DSS_WITH_DES_CBC_SHA",
- "SSL_DH_anon_WITH_DES_CBC_SHA",
- "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
- "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",
- "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
- "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
- "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
- "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
+ "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA",
+ "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_DH_anon_WITH_DES_CBC_SHA",
+ "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",
+ "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
+ "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
// NOTE: This list needs to be kept in sync with Javadoc of javax.net.ssl.SSLSocket and
// javax.net.ssl.SSLEngine.
- private static final List<String> CIPHER_SUITES_AES_HARDWARE = Arrays.asList(
- "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
+ private static final List<String> CIPHER_SUITES_ANDROID_AES_HARDWARE = Arrays.asList(
+ "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
- "TLS_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_RSA_WITH_AES_128_CBC_SHA",
- "TLS_RSA_WITH_AES_256_CBC_SHA",
- CIPHER_SUITE_SECURE_RENEGOTIATION);
+ "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
+ "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_RSA_WITH_AES_256_CBC_SHA", CIPHER_SUITE_SECURE_RENEGOTIATION);
// NOTE: This list needs to be kept in sync with Javadoc of javax.net.ssl.SSLSocket and
// javax.net.ssl.SSLEngine.
- private static final List<String> CIPHER_SUITES_SOFTWARE = Arrays.asList(
+ private static final List<String> CIPHER_SUITES_ANDROID_SOFTWARE = Arrays.asList(
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
- "TLS_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_RSA_WITH_AES_128_CBC_SHA",
- "TLS_RSA_WITH_AES_256_CBC_SHA",
- CIPHER_SUITE_SECURE_RENEGOTIATION);
+ "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
+ "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_RSA_WITH_AES_256_CBC_SHA", CIPHER_SUITE_SECURE_RENEGOTIATION);
// NOTE: This list needs to be kept in sync with Javadoc of javax.net.ssl.SSLSocket and
// javax.net.ssl.SSLEngine.
- public static final List<String> CIPHER_SUITES_DEFAULT = CpuFeatures.isAESHardwareAccelerated()
- ? CIPHER_SUITES_AES_HARDWARE
- : CIPHER_SUITES_SOFTWARE;
+ public static final List<String> CIPHER_SUITES_DEFAULT = (IS_RI)
+ ? Arrays.asList("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
+ "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_RSA_WITH_AES_256_CBC_SHA256",
+ "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",
+ "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
+ "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA",
+ "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
+ "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
+ "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
+ "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA256",
+ "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",
+ "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
+ "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
+ "SSL_RSA_WITH_RC4_128_SHA", "TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
+ "TLS_ECDH_RSA_WITH_RC4_128_SHA", "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", "SSL_RSA_WITH_3DES_EDE_CBC_SHA",
+ "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
+ "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
+ "SSL_RSA_WITH_RC4_128_MD5", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV")
+ : CpuFeatures.isAESHardwareAccelerated() ? CIPHER_SUITES_ANDROID_AES_HARDWARE
+ : CIPHER_SUITES_ANDROID_SOFTWARE;
// NOTE: This list needs to be kept in sync with Javadoc of javax.net.ssl.SSLSocket and
// javax.net.ssl.SSLEngine.
- public static final List<String> CIPHER_SUITES_DEFAULT_PSK = Arrays.asList(
- "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA",
- "TLS_PSK_WITH_AES_128_CBC_SHA",
- "TLS_PSK_WITH_AES_256_CBC_SHA");
+ public static final List<String> CIPHER_SUITES_DEFAULT_PSK =
+ Arrays.asList("TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256",
+ "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA", "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA",
+ "TLS_PSK_WITH_AES_128_CBC_SHA", "TLS_PSK_WITH_AES_256_CBC_SHA");
// Should be updated to match BoringSSL's defaults when they change.
- // https://boringssl.googlesource.com/boringssl/+/master/ssl/t1_lib.c#306
+ // https://android.googlesource.com/platform/external/boringssl/+/master/src/ssl/t1_lib.c#305
public static final List<String> ELLIPTIC_CURVES_DEFAULT =
- Arrays.asList("x25519 (29)", "secp256r1 (23)", "secp384r1 (24)");
+ Arrays.asList("x25519 (29)", "secp256r1 (23)", "secp384r1 (24)", "secp521r1 (25)");
private static final Set<String> PERMITTED_DEFAULT_KEY_EXCHANGE_ALGS = new HashSet<String>(
Arrays.asList("RSA", "DHE_RSA", "DHE_DSS", "ECDHE_RSA", "ECDHE_ECDSA"));
private static final Set<String> PERMITTED_DEFAULT_BULK_ENCRYPTION_CIPHERS =
- new HashSet<String>(Arrays.asList(
- "AES_128_CBC",
- "AES_256_CBC",
- "AES_128_GCM",
- "AES_256_GCM",
- "CHACHA20_POLY1305"));
+ new HashSet<String>(Arrays.asList("AES_128_CBC", "AES_256_CBC", "AES_128_GCM",
+ "AES_256_GCM", "CHACHA20_POLY1305"));
private static final Set<String> PERMITTED_DEFAULT_MACS =
new HashSet<String>(Arrays.asList("SHA", "SHA256", "SHA384"));
@@ -1013,10 +1058,21 @@ public final class StandardNames {
*/
public static void assertDefaultCipherSuites(String[] cipherSuites) {
assertValidCipherSuites(cipherSuites);
+ assertEquals(CIPHER_SUITES_DEFAULT, Arrays.asList(cipherSuites));
- Set<String> expected = new TreeSet<>(CIPHER_SUITES_DEFAULT);
- Set<String> actual = new TreeSet<>(Arrays.asList(cipherSuites));
- assertEquals(expected, actual);
+ // Assert that all the cipher suites are permitted to be in the default list.
+ // This assertion is a backup for the stricter assertion above.
+ //
+ // There is no point in asserting this for the RI as it's outside of our control.
+ if (!IS_RI) {
+ List<String> disallowedDefaultCipherSuites = new ArrayList<String>();
+ for (String cipherSuite : cipherSuites) {
+ if (!isPermittedDefaultCipherSuite(cipherSuite)) {
+ disallowedDefaultCipherSuites.add(cipherSuite);
+ }
+ }
+ assertEquals(Collections.EMPTY_LIST, disallowedDefaultCipherSuites);
+ }
}
public static void assertDefaultEllipticCurves(String[] curves) {
diff --git a/testing/src/main/java/libcore/java/security/TestKeyStore.java b/libcore-stub/src/main/java/libcore/java/security/TestKeyStore.java
index d6f4ad85..d6f4ad85 100644
--- a/testing/src/main/java/libcore/java/security/TestKeyStore.java
+++ b/libcore-stub/src/main/java/libcore/java/security/TestKeyStore.java
diff --git a/testing/src/main/java/libcore/javax/net/ssl/FakeSSLSession.java b/libcore-stub/src/main/java/libcore/javax/net/ssl/FakeSSLSession.java
index 4f2ae723..4f2ae723 100644
--- a/testing/src/main/java/libcore/javax/net/ssl/FakeSSLSession.java
+++ b/libcore-stub/src/main/java/libcore/javax/net/ssl/FakeSSLSession.java
diff --git a/testing/src/main/java/libcore/javax/net/ssl/TestKeyManager.java b/libcore-stub/src/main/java/libcore/javax/net/ssl/TestKeyManager.java
index 7fbbc776..7fbbc776 100644
--- a/testing/src/main/java/libcore/javax/net/ssl/TestKeyManager.java
+++ b/libcore-stub/src/main/java/libcore/javax/net/ssl/TestKeyManager.java
diff --git a/testing/src/main/java/libcore/javax/net/ssl/TestTrustManager.java b/libcore-stub/src/main/java/libcore/javax/net/ssl/TestTrustManager.java
index ac6f0e65..ac6f0e65 100644
--- a/testing/src/main/java/libcore/javax/net/ssl/TestTrustManager.java
+++ b/libcore-stub/src/main/java/libcore/javax/net/ssl/TestTrustManager.java
diff --git a/openjdk-benchmarks/build.gradle b/openjdk-benchmarks/build.gradle
index 73a08092..f26196e3 100644
--- a/openjdk-benchmarks/build.gradle
+++ b/openjdk-benchmarks/build.gradle
@@ -6,20 +6,6 @@ apply plugin: 'idea'
description = 'Conscrypt: OpenJDK Benchmarks'
-evaluationDependsOn(':conscrypt-openjdk')
-
-def preferredNativeConfiguration = project(':conscrypt-openjdk').preferredNativeConfiguration
-def preferredNativeFileDir = project(':conscrypt-openjdk').preferredNativeFileDir
-
-sourceSets {
- main {
- resources {
- // This shouldn't be needed but seems to help IntelliJ locate the native artifact.
- srcDirs += preferredNativeFileDir
- }
- }
-}
-
jmh {
jmhVersion = "$jmhVersion"
warmupIterations = 10
@@ -34,14 +20,15 @@ configurations {
}
dependencies {
- compile project(':conscrypt-openjdk'),
- project(':conscrypt-testing'),
+ compile project(':conscrypt-testing'),
libraries.junit,
libraries.netty_handler,
libraries.netty_tcnative
// Add the preferred native openjdk configuration for this platform.
- compile project(path: ':conscrypt-openjdk', configuration: "$preferredNativeConfiguration")
+ compile project(
+ path: ':conscrypt-openjdk',
+ configuration: project(':conscrypt-openjdk').preferredNativeConfiguration)
jmh libraries.jmh_core
diff --git a/openjdk-integ-tests/build.gradle b/openjdk-integ-tests/build.gradle
deleted file mode 100644
index a4ca5463..00000000
--- a/openjdk-integ-tests/build.gradle
+++ /dev/null
@@ -1,29 +0,0 @@
-description = 'Conscrypt: OpenJDK Integration Tests'
-
-evaluationDependsOn(':conscrypt-openjdk')
-
-def preferredNativeConfiguration = project(':conscrypt-openjdk').preferredNativeConfiguration
-def preferredNativeFileDir = project(':conscrypt-openjdk').preferredNativeFileDir
-
-sourceSets {
- main {
- resources {
- // This shouldn't be needed but seems to help IntelliJ locate the native artifact.
- srcDirs += preferredNativeFileDir
- }
- }
-}
-
-dependencies {
- compile project(':conscrypt-openjdk')
-
- // Add the preferred native openjdk configuration for this platform.
- compile project(path: ':conscrypt-openjdk', configuration: "$preferredNativeConfiguration")
-
- testCompile project(':conscrypt-constants'),
- project(':conscrypt-testing')
-}
-
-// Don't include this artifact in the distribution.
-tasks.install.enabled = false
-tasks.uploadArchives.enabled = false;
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/AbstractSSLTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/AbstractSSLTest.java
deleted file mode 100644
index 3bfc8e7b..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/AbstractSSLTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.conscrypt.TestUtils.installConscryptAsDefaultProvider;
-
-import org.junit.BeforeClass;
-
-/**
- * Abstract base class for all SSL integration tests. This sets up the default TLS provider.
- */
-public abstract class AbstractSSLTest {
-
- @BeforeClass
- public static void setupStatic() {
- installConscryptAsDefaultProvider();
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/HttpsURLConnectionTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/HttpsURLConnectionTest.java
deleted file mode 100644
index fec135da..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/HttpsURLConnectionTest.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.URL;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocketFactory;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class HttpsURLConnectionTest extends AbstractSSLTest {
- /**
- * HTTPS URL which cannot be resolved and is thus safe to use in tests where network traffic
- * should be avoided.
- */
- private static final String UNRESOLVABLE_HTTPS_URL = "https:///";
-
- @Test
- public void testDefaultHostnameVerifierNotNull() {
- assertNotNull(HttpsURLConnection.getDefaultHostnameVerifier());
- }
-
- @Test
- public void testDefaultHostnameVerifierUsedForNewConnectionsByDefault() throws IOException {
- HostnameVerifier originalHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
- HttpsURLConnection connection =
- (HttpsURLConnection) new URL(UNRESOLVABLE_HTTPS_URL).openConnection();
- try {
- assertSame(originalHostnameVerifier, connection.getHostnameVerifier());
- } finally {
- connection.disconnect();
- }
-
- HostnameVerifier anotherVerifier = new FakeHostnameVerifier();
- try {
- HttpsURLConnection.setDefaultHostnameVerifier(anotherVerifier);
- connection = (HttpsURLConnection) new URL(UNRESOLVABLE_HTTPS_URL).openConnection();
- try {
- assertSame(anotherVerifier, connection.getHostnameVerifier());
- } finally {
- connection.disconnect();
- }
-
- HttpsURLConnection.setDefaultHostnameVerifier(originalHostnameVerifier);
- connection = (HttpsURLConnection) new URL(UNRESOLVABLE_HTTPS_URL).openConnection();
- try {
- assertSame(originalHostnameVerifier, connection.getHostnameVerifier());
- } finally {
- connection.disconnect();
- }
- } finally {
- HttpsURLConnection.setDefaultHostnameVerifier(originalHostnameVerifier);
- }
- }
-
- @Test
- public void testDefaultSSLSocketFactoryNotNull() {
- assertNotNull(HttpsURLConnection.getDefaultSSLSocketFactory());
- }
-
- @Test
- public void testDefaultSSLSocketFactoryUsedForNewConnectionsByDefault() throws IOException {
- SSLSocketFactory originalFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
- HttpsURLConnection connection =
- (HttpsURLConnection) new URL(UNRESOLVABLE_HTTPS_URL).openConnection();
- try {
- assertSame(originalFactory, connection.getSSLSocketFactory());
- } finally {
- connection.disconnect();
- }
-
- SSLSocketFactory anotherFactory = new FakeSSLSocketFactory();
- try {
- HttpsURLConnection.setDefaultSSLSocketFactory(anotherFactory);
- connection = (HttpsURLConnection) new URL(UNRESOLVABLE_HTTPS_URL).openConnection();
- try {
- assertSame(anotherFactory, connection.getSSLSocketFactory());
- } finally {
- connection.disconnect();
- }
-
- HttpsURLConnection.setDefaultSSLSocketFactory(originalFactory);
- connection = (HttpsURLConnection) new URL(UNRESOLVABLE_HTTPS_URL).openConnection();
- try {
- assertSame(originalFactory, connection.getSSLSocketFactory());
- } finally {
- connection.disconnect();
- }
- } finally {
- HttpsURLConnection.setDefaultSSLSocketFactory(originalFactory);
- }
- }
-
- private static final class FakeHostnameVerifier implements HostnameVerifier {
- @Override
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
- }
-
- private static final class FakeSSLSocketFactory extends SSLSocketFactory {
- FakeSSLSocketFactory() {}
-
- @Override
- public String[] getDefaultCipherSuites() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Socket createSocket(Socket s, String host, int port, boolean autoClose) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Socket createSocket(
- InetAddress address, int port, InetAddress localAddress, int localPort) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Socket createSocket(InetAddress host, int port) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Socket createSocket(String host, int port) {
- throw new UnsupportedOperationException();
- }
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
deleted file mode 100644
index e02394c2..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore.Builder;
-import java.security.KeyStore.PasswordProtection;
-import java.security.KeyStore.PrivateKeyEntry;
-import java.security.PrivateKey;
-import java.security.Provider;
-import java.security.Security;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Set;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.KeyStoreBuilderParameters;
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.X509ExtendedKeyManager;
-import javax.net.ssl.X509KeyManager;
-import libcore.java.security.StandardNames;
-import libcore.java.security.TestKeyStore;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class KeyManagerFactoryTest extends AbstractSSLTest {
- private TestKeyStore testKeyStore;
-
- @Before
- public void setUp() throws Exception {
- // note the rare usage of DSA keys here in addition to RSA
- testKeyStore = new TestKeyStore.Builder()
- .keyAlgorithms("RSA", "DSA", "EC", "EC_RSA")
- .aliasPrefix("rsa-dsa-ec-dh")
- .build();
- }
-
- private TestKeyStore getTestKeyStore() throws Exception {
- return testKeyStore;
- }
-
- @Test
- public void test_KeyManagerFactory_getDefaultAlgorithm() throws Exception {
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- assertEquals(StandardNames.KEY_MANAGER_FACTORY_DEFAULT, algorithm);
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
- test_KeyManagerFactory(kmf);
- }
-
- private static class UselessManagerFactoryParameters implements ManagerFactoryParameters {}
-
- private static boolean supportsManagerFactoryParameters(String algorithm) {
- // Only the "New" one supports ManagerFactoryParameters
- return algorithm.equals("NewSunX509");
- }
-
- private static String[] keyTypes(String algorithm) {
- // Although the "New" one supports ManagerFactoryParameters,
- // it can't handle nulls in the key types array.
- return (algorithm.equals("NewSunX509") ? KEY_TYPES_WITH_EMPTY
- : KEY_TYPES_WITH_EMPTY_AND_NULL);
- }
-
- private void test_KeyManagerFactory(KeyManagerFactory kmf) throws Exception {
- assertNotNull(kmf);
- assertNotNull(kmf.getAlgorithm());
- assertNotNull(kmf.getProvider());
-
- // before init
- try {
- kmf.getKeyManagers();
- fail();
- } catch (IllegalStateException expected) {
- // Ignore
- }
-
- // init with null ManagerFactoryParameters
- try {
- kmf.init(null);
- fail();
- } catch (InvalidAlgorithmParameterException expected) {
- // Ignore
- }
-
- // init with useless ManagerFactoryParameters
- try {
- kmf.init(new UselessManagerFactoryParameters());
- fail();
- } catch (InvalidAlgorithmParameterException expected) {
- // Ignore
- }
-
- // init with KeyStoreBuilderParameters ManagerFactoryParameters
- PasswordProtection pp = new PasswordProtection(getTestKeyStore().storePassword);
- Builder builder = Builder.newInstance(getTestKeyStore().keyStore, pp);
- KeyStoreBuilderParameters ksbp = new KeyStoreBuilderParameters(builder);
- if (supportsManagerFactoryParameters(kmf.getAlgorithm())) {
- kmf.init(ksbp);
- test_KeyManagerFactory_getKeyManagers(kmf, false);
- } else {
- try {
- kmf.init(ksbp);
- fail();
- } catch (InvalidAlgorithmParameterException expected) {
- // Ignore
- }
- }
-
- // init with null for default behavior
- kmf.init(null, null);
- test_KeyManagerFactory_getKeyManagers(kmf, true);
-
- // init with specific key store and password
- kmf.init(getTestKeyStore().keyStore, getTestKeyStore().storePassword);
- test_KeyManagerFactory_getKeyManagers(kmf, false);
- }
-
- private void test_KeyManagerFactory_getKeyManagers(KeyManagerFactory kmf, boolean empty)
- throws Exception {
- KeyManager[] keyManagers = kmf.getKeyManagers();
- assertNotNull(keyManagers);
- assertTrue(keyManagers.length > 0);
- for (KeyManager keyManager : keyManagers) {
- assertNotNull(keyManager);
- if (keyManager instanceof X509KeyManager) {
- test_X509KeyManager((X509KeyManager) keyManager, empty, kmf.getAlgorithm());
- }
- }
- }
-
- private static final String[] KEY_TYPES_ONLY =
- StandardNames.KEY_TYPES.toArray(new String[StandardNames.KEY_TYPES.size()]);
- private static final String[] KEY_TYPES_WITH_EMPTY = new String[KEY_TYPES_ONLY.length + 1];
- private static final String[] KEY_TYPES_WITH_EMPTY_AND_NULL =
- new String[KEY_TYPES_ONLY.length + 2];
- static {
- System.arraycopy(KEY_TYPES_ONLY, 0, KEY_TYPES_WITH_EMPTY, 0, KEY_TYPES_ONLY.length);
- KEY_TYPES_WITH_EMPTY[KEY_TYPES_WITH_EMPTY.length - 1] = "";
-
- System.arraycopy(KEY_TYPES_WITH_EMPTY, 0, KEY_TYPES_WITH_EMPTY_AND_NULL, 0,
- KEY_TYPES_WITH_EMPTY.length);
- // extra null at end requires no initialization
- }
-
- private void test_X509KeyManager(X509KeyManager km, boolean empty, String algorithm)
- throws Exception {
- String[] keyTypes = keyTypes(algorithm);
- for (String keyType : keyTypes) {
- String[] aliases = km.getClientAliases(keyType, null);
- if (empty || keyType == null || keyType.isEmpty()) {
- assertNull(keyType, aliases);
- continue;
- }
- assertNotNull(keyType, aliases);
- for (String alias : aliases) {
- test_X509KeyManager_alias(km, alias, keyType, false, empty);
- }
- }
- for (String keyType : keyTypes) {
- String[] aliases = km.getServerAliases(keyType, null);
- if (empty || keyType == null || keyType.isEmpty()) {
- assertNull(keyType, aliases);
- continue;
- }
- assertNotNull(keyType, aliases);
- for (String alias : aliases) {
- test_X509KeyManager_alias(km, alias, keyType, false, empty);
- }
- }
-
- String a = km.chooseClientAlias(keyTypes, null, null);
- test_X509KeyManager_alias(km, a, null, true, empty);
-
- for (String keyType : keyTypes) {
- String[] array = new String[] {keyType};
- String alias = km.chooseClientAlias(array, null, null);
- test_X509KeyManager_alias(km, alias, keyType, false, empty);
- }
- for (String keyType : keyTypes) {
- String alias = km.chooseServerAlias(keyType, null, null);
- test_X509KeyManager_alias(km, alias, keyType, false, empty);
- }
- if (km instanceof X509ExtendedKeyManager) {
- test_X509ExtendedKeyManager((X509ExtendedKeyManager) km, empty, algorithm);
- }
- }
-
- private void test_X509ExtendedKeyManager(
- X509ExtendedKeyManager km, boolean empty, String algorithm) throws Exception {
- String[] keyTypes = keyTypes(algorithm);
- String a = km.chooseEngineClientAlias(keyTypes, null, null);
- test_X509KeyManager_alias(km, a, null, true, empty);
- for (String keyType : keyTypes) {
- String[] array = new String[] {keyType};
- String alias = km.chooseEngineClientAlias(array, null, null);
- test_X509KeyManager_alias(km, alias, keyType, false, empty);
- }
- for (String keyType : keyTypes) {
- String alias = km.chooseEngineServerAlias(keyType, null, null);
- test_X509KeyManager_alias(km, alias, keyType, false, empty);
- }
- }
-
- private void test_X509KeyManager_alias(X509KeyManager km, String alias, String keyType,
- boolean many, boolean empty) throws Exception {
- if (empty || (!many && (keyType == null || keyType.isEmpty()))) {
- assertNull(keyType, alias);
- assertNull(keyType, km.getCertificateChain(alias));
- assertNull(keyType, km.getPrivateKey(alias));
- return;
- }
- assertNotNull(keyType, alias);
-
- X509Certificate[] certificateChain = km.getCertificateChain(alias);
- PrivateKey privateKey = km.getPrivateKey(alias);
-
- String keyAlgName = privateKey.getAlgorithm();
-
- X509Certificate certificate = certificateChain[0];
- assertEquals(keyType, keyAlgName, certificate.getPublicKey().getAlgorithm());
-
- String sigAlgName = certificate.getSigAlgName();
-
- PrivateKeyEntry privateKeyEntry = getTestKeyStore().getPrivateKey(keyAlgName, sigAlgName);
-
- assertEquals(keyType, Arrays.asList(privateKeyEntry.getCertificateChain()),
- Arrays.<Certificate>asList(certificateChain));
- assertEquals(keyType, privateKeyEntry.getPrivateKey(), privateKey);
-
- if (keyType != null) {
- assertEquals(TestKeyStore.keyAlgorithm(keyType), keyAlgName);
-
- // Skip this when we're given only "DH" or "EC" instead of "DH_DSA",
- // "EC_RSA", etc. since we don't know what the expected
- // algorithm was.
- if (!keyType.equals("DH") && !keyType.equals("EC")) {
- assertTrue(sigAlgName.contains(TestKeyStore.signatureAlgorithm(keyType)));
- }
- }
- }
-
- @Test
- public void test_KeyManagerFactory_getInstance() throws Exception {
- Provider[] providers = Security.getProviders();
- for (Provider provider : providers) {
- Set<Provider.Service> services = provider.getServices();
- for (Provider.Service service : services) {
- String type = service.getType();
- if (!type.equals("KeyManagerFactory")) {
- continue;
- }
- String algorithm = service.getAlgorithm();
- try {
- {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
- assertEquals(algorithm, kmf.getAlgorithm());
- test_KeyManagerFactory(kmf);
- }
-
- {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm, provider);
- assertEquals(algorithm, kmf.getAlgorithm());
- assertEquals(provider, kmf.getProvider());
- test_KeyManagerFactory(kmf);
- }
-
- {
- KeyManagerFactory kmf =
- KeyManagerFactory.getInstance(algorithm, provider.getName());
- assertEquals(algorithm, kmf.getAlgorithm());
- assertEquals(provider, kmf.getProvider());
- test_KeyManagerFactory(kmf);
- }
- } catch (Exception e) {
- throw new Exception("Problem with algorithm " + algorithm, e);
- }
- }
- }
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/KeyStoreBuilderParametersTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/KeyStoreBuilderParametersTest.java
deleted file mode 100644
index 8303cd27..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/KeyStoreBuilderParametersTest.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-
-import java.security.KeyStore.Builder;
-import java.security.KeyStore.PasswordProtection;
-import java.util.Arrays;
-import java.util.List;
-import javax.net.ssl.KeyStoreBuilderParameters;
-import libcore.java.security.TestKeyStore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class KeyStoreBuilderParametersTest extends AbstractSSLTest {
- @Test
- public void test_init_Builder_null() {
- try {
- new KeyStoreBuilderParameters((Builder) null);
- fail();
- } catch (NullPointerException expected) {
- // Ignored.
- }
- }
-
- @Test
- public void test_init_Builder() {
- TestKeyStore testKeyStore = TestKeyStore.getClient();
- Builder builder = Builder.newInstance(
- testKeyStore.keyStore, new PasswordProtection(testKeyStore.storePassword));
- KeyStoreBuilderParameters ksbp = new KeyStoreBuilderParameters(builder);
- assertNotNull(ksbp);
- assertNotNull(ksbp.getParameters());
- assertEquals(1, ksbp.getParameters().size());
- assertSame(builder, ksbp.getParameters().get(0));
- }
-
- @Test
- public void test_init_List_null() {
- try {
- new KeyStoreBuilderParameters((List<Builder>) null);
- fail();
- } catch (NullPointerException expected) {
- // Ignored.
- }
- }
-
- @Test
- public void test_init_List() {
- TestKeyStore testKeyStore1 = TestKeyStore.getClient();
- TestKeyStore testKeyStore2 = TestKeyStore.getServer();
- Builder builder1 = Builder.newInstance(
- testKeyStore1.keyStore, new PasswordProtection(testKeyStore1.storePassword));
- Builder builder2 = Builder.newInstance(
- testKeyStore2.keyStore, new PasswordProtection(testKeyStore2.storePassword));
-
- List<Builder> list = Arrays.asList(builder1, builder2);
- KeyStoreBuilderParameters ksbp = new KeyStoreBuilderParameters(list);
- assertNotNull(ksbp);
- assertNotNull(ksbp.getParameters());
- assertNotSame(list, ksbp.getParameters());
- assertEquals(2, ksbp.getParameters().size());
- assertSame(builder1, ksbp.getParameters().get(0));
- assertSame(builder2, ksbp.getParameters().get(1));
-
- // confirm result is not modifiable
- try {
- ksbp.getParameters().set(0, builder2);
- fail();
- } catch (UnsupportedOperationException expected) {
- // Ignored.
- }
-
- // confirm result is a copy of original
- list.set(0, builder2);
- assertSame(builder1, ksbp.getParameters().get(0));
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SNIHostNameTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SNIHostNameTest.java
deleted file mode 100644
index da1598dc..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SNIHostNameTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright 2016 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.Arrays;
-import javax.net.ssl.SNIHostName;
-import javax.net.ssl.StandardConstants;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SNIHostNameTest extends AbstractSSLTest {
- @Test
- public void test_byteArray_Constructor() throws Exception {
- // From draft-josefsson-idn-test-vectors-00 section 5.2
- byte[] idnEncoded = new byte[] {
- (byte) 0xE4, (byte) 0xBB, (byte) 0x96, (byte) 0xE4, (byte) 0xBB, (byte) 0xAC,
- (byte) 0xE4, (byte) 0xB8, (byte) 0xBA, (byte) 0xE4, (byte) 0xBB, (byte) 0x80,
- (byte) 0xE4, (byte) 0xB9, (byte) 0x88, (byte) 0xE4, (byte) 0xB8, (byte) 0x8D,
- (byte) 0xE8, (byte) 0xAF, (byte) 0xB4, (byte) 0xE4, (byte) 0xB8, (byte) 0xAD,
- (byte) 0xE6, (byte) 0x96, (byte) 0x87,
- };
-
- SNIHostName hostName = new SNIHostName(idnEncoded);
- assertEquals("xn--ihqwcrb4cv8a8dqg056pqjye", hostName.getAsciiName());
- assertEquals(StandardConstants.SNI_HOST_NAME, hostName.getType());
- assertEquals(Arrays.toString(idnEncoded), Arrays.toString(hostName.getEncoded()));
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLContextTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLContextTest.java
deleted file mode 100644
index 63c3d3bb..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLContextTest.java
+++ /dev/null
@@ -1,640 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.Provider;
-import java.security.Security;
-import java.security.UnrecoverableKeyException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.Callable;
-import javax.net.ServerSocketFactory;
-import javax.net.SocketFactory;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.KeyManagerFactorySpi;
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.TrustManagerFactorySpi;
-import javax.net.ssl.X509KeyManager;
-import junit.framework.AssertionFailedError;
-import libcore.java.security.StandardNames;
-import org.conscrypt.TestUtils;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SSLContextTest extends AbstractSSLTest {
-
- @Test
- public void test_SSLContext_getDefault() throws Exception {
- SSLContext sslContext = SSLContext.getDefault();
- assertNotNull(sslContext);
- try {
- sslContext.init(null, null, null);
- fail();
- } catch (KeyManagementException expected) {
- // Ignored.
- }
- }
-
- @Test
- public void test_SSLContext_setDefault() throws Exception {
- try {
- SSLContext.setDefault(null);
- fail();
- } catch (NullPointerException expected) {
- // Ignored.
- }
-
- SSLContext defaultContext = SSLContext.getDefault();
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- SSLContext oldContext = SSLContext.getDefault();
- assertNotNull(oldContext);
- SSLContext newContext = SSLContext.getInstance(protocol);
- assertNotNull(newContext);
- assertNotSame(oldContext, newContext);
- SSLContext.setDefault(newContext);
- assertSame(newContext, SSLContext.getDefault());
- }
- SSLContext.setDefault(defaultContext);
- }
-
- @Test
- public void test_SSLContext_defaultConfiguration() throws Exception {
- SSLConfigurationAsserts.assertSSLContextDefaultConfiguration(SSLContext.getDefault());
-
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- SSLContext sslContext = SSLContext.getInstance(protocol);
- if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- sslContext.init(null, null, null);
- }
- SSLConfigurationAsserts.assertSSLContextDefaultConfiguration(sslContext);
- }
- }
-
- @Test
- public void test_SSLContext_pskOnlyConfiguration_defaultProviderOnly() throws Exception {
- // Test the scenario where only a PSKKeyManager is provided and no TrustManagers are
- // provided.
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(new KeyManager[] {PSKKeyManagerProxy.getConscryptPSKKeyManager(
- new PSKKeyManagerProxy())},
- new TrustManager[0], null);
- List<String> expectedCipherSuites =
- new ArrayList<>(StandardNames.CIPHER_SUITES_DEFAULT_PSK);
- expectedCipherSuites.add(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION);
- assertEnabledCipherSuites(expectedCipherSuites, sslContext);
- }
-
- @Test
- public void test_SSLContext_x509AndPskConfiguration_defaultProviderOnly() throws Exception {
- // Test the scenario where an X509TrustManager and PSKKeyManager are provided.
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(new KeyManager[] {PSKKeyManagerProxy.getConscryptPSKKeyManager(
- new PSKKeyManagerProxy())},
- null, // Use default trust managers, one of which is an X.509 one.
- null);
- List<String> expectedCipherSuites =
- new ArrayList<>(StandardNames.CIPHER_SUITES_DEFAULT_PSK);
- expectedCipherSuites.addAll(StandardNames.CIPHER_SUITES_DEFAULT);
- assertEnabledCipherSuites(expectedCipherSuites, sslContext);
-
- // Test the scenario where an X509KeyManager and PSKKeyManager are provided.
- sslContext = SSLContext.getInstance("TLS");
- // Just an arbitrary X509KeyManager -- it won't be invoked in this test.
- X509KeyManager x509KeyManager = new RandomPrivateKeyX509ExtendedKeyManager(null);
- sslContext.init(
- new KeyManager[] {x509KeyManager,
- PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy())},
- new TrustManager[0], null);
- assertEnabledCipherSuites(expectedCipherSuites, sslContext);
- }
-
- @Test
- public void test_SSLContext_emptyConfiguration_defaultProviderOnly() throws Exception {
- // Test the scenario where neither X.509 nor PSK KeyManagers or TrustManagers are provided.
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(new KeyManager[0], new TrustManager[0], null);
- assertEnabledCipherSuites(
- Collections.singletonList(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION),
- sslContext);
- }
-
- @Test
- public void test_SSLContext_init_correctProtocolVersionsEnabled() throws Exception {
- for (String tlsVersion : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- // Don't test the "Default" instance.
- if (StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT.equals(tlsVersion)) {
- continue;
- }
-
- SSLContext context = SSLContext.getInstance(tlsVersion);
- context.init(null, null, null);
-
- StandardNames.assertSSLContextEnabledProtocols(
- tlsVersion, ((SSLSocket) (context.getSocketFactory().createSocket()))
- .getEnabledProtocols());
- StandardNames.assertSSLContextEnabledProtocols(tlsVersion,
- ((SSLServerSocket) (context.getServerSocketFactory().createServerSocket()))
- .getEnabledProtocols());
- StandardNames.assertSSLContextEnabledProtocols(
- tlsVersion, context.getDefaultSSLParameters().getProtocols());
- StandardNames.assertSSLContextEnabledProtocols(
- tlsVersion, context.createSSLEngine().getEnabledProtocols());
- }
- }
-
- private static void assertEnabledCipherSuites(
- List<String> expectedCipherSuites, SSLContext sslContext) throws Exception {
- assertContentsInOrder(
- expectedCipherSuites, sslContext.createSSLEngine().getEnabledCipherSuites());
- assertContentsInOrder(expectedCipherSuites,
- sslContext.createSSLEngine().getSSLParameters().getCipherSuites());
- assertContentsInOrder(
- expectedCipherSuites, sslContext.getSocketFactory().getDefaultCipherSuites());
- assertContentsInOrder(
- expectedCipherSuites, sslContext.getServerSocketFactory().getDefaultCipherSuites());
-
- SSLSocket sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket();
- try {
- assertContentsInOrder(expectedCipherSuites, sslSocket.getEnabledCipherSuites());
- assertContentsInOrder(
- expectedCipherSuites, sslSocket.getSSLParameters().getCipherSuites());
- } finally {
- try {
- sslSocket.close();
- } catch (IOException ignored) {
- }
- }
-
- SSLServerSocket sslServerSocket =
- (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();
- try {
- assertContentsInOrder(expectedCipherSuites, sslServerSocket.getEnabledCipherSuites());
- } finally {
- try {
- sslSocket.close();
- } catch (IOException ignored) {
- }
- }
- }
-
- @Test
- public void test_SSLContext_getInstance() throws Exception {
- try {
- SSLContext.getInstance(null);
- fail();
- } catch (NullPointerException expected) {
- // Ignored.
- }
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- assertNotNull(SSLContext.getInstance(protocol));
- assertNotSame(SSLContext.getInstance(protocol), SSLContext.getInstance(protocol));
- }
-
- try {
- SSLContext.getInstance(null, (String) null);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- SSLContext.getInstance(null, "");
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- try {
- SSLContext.getInstance(protocol, (String) null);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- }
- try {
- SSLContext.getInstance(null, StandardNames.JSSE_PROVIDER_NAME);
- fail();
- } catch (NullPointerException expected) {
- // Ignored.
- }
- }
-
- @Test
- public void test_SSLContext_getProtocol() throws Exception {
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- String protocolName = SSLContext.getInstance(protocol).getProtocol();
- assertNotNull(protocolName);
- assertTrue(protocol.startsWith(protocolName));
- }
- }
-
- @Test
- public void test_SSLContext_getProvider() throws Exception {
- Provider provider = SSLContext.getDefault().getProvider();
- assertNotNull(provider);
- assertEquals(StandardNames.JSSE_PROVIDER_NAME, provider.getName());
- }
-
- @Test
- public void test_SSLContext_init_Default() throws Exception {
- // Assert that initializing a default SSLContext fails because it's supposed to be
- // initialized already.
- SSLContext sslContext = SSLContext.getInstance(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT);
- try {
- sslContext.init(null, null, null);
- fail();
- } catch (KeyManagementException expected) {
- // Ignored.
- }
- try {
- sslContext.init(new KeyManager[0], new TrustManager[0], null);
- fail();
- } catch (KeyManagementException expected) {
- // Ignored.
- }
- try {
- sslContext.init(new KeyManager[] {new KeyManager(){}},
- new TrustManager[] {new TrustManager(){}}, null);
- fail();
- } catch (KeyManagementException expected) {
- // Ignored.
- }
- }
-
- @Test
- public void test_SSLContext_init_withNullManagerArrays() throws Exception {
- // Assert that SSLContext.init works fine even when provided with null arrays of
- // KeyManagers and TrustManagers.
- // The contract of SSLContext.init is that it will for default X.509 KeyManager and
- // TrustManager from the highest priority KeyManagerFactory and TrustManagerFactory.
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- // Default SSLContext is provided in an already initialized state
- continue;
- }
- SSLContext sslContext = SSLContext.getInstance(protocol);
- sslContext.init(null, null, null);
- }
- }
-
- @Test
- public void test_SSLContext_init_withEmptyManagerArrays() throws Exception {
- // Assert that SSLContext.init works fine even when provided with empty arrays of
- // KeyManagers and TrustManagers.
- // The contract of SSLContext.init is that it will not look for default X.509 KeyManager and
- // TrustManager.
- // This test thus installs a Provider of KeyManagerFactory and TrustManagerFactory whose
- // factories throw exceptions which will make this test fail if the factories are used.
- Provider provider = new ThrowExceptionKeyAndTrustManagerFactoryProvider();
- invokeWithHighestPrioritySecurityProvider(provider, (Callable<Void>) () -> {
- assertEquals(ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
- TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
- .getProvider()
- .getClass());
- assertEquals(ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
- KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
- .getProvider()
- .getClass());
-
- KeyManager[] keyManagers = new KeyManager[0];
- TrustManager[] trustManagers = new TrustManager[0];
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- // Default SSLContext is provided in an already initialized state
- continue;
- }
- SSLContext sslContext = SSLContext.getInstance(protocol);
- sslContext.init(keyManagers, trustManagers, null);
- }
-
- return null;
- });
- }
-
- @Test
- public void test_SSLContext_init_withoutX509() throws Exception {
- // Assert that SSLContext.init works fine even when provided with KeyManagers and
- // TrustManagers which don't include the X.509 ones.
- // The contract of SSLContext.init is that it will not look for default X.509 KeyManager and
- // TrustManager.
- // This test thus installs a Provider of KeyManagerFactory and TrustManagerFactory whose
- // factories throw exceptions which will make this test fail if the factories are used.
- Provider provider = new ThrowExceptionKeyAndTrustManagerFactoryProvider();
- invokeWithHighestPrioritySecurityProvider(provider, (Callable<Void>) () -> {
- assertEquals(ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
- TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
- .getProvider()
- .getClass());
- assertEquals(ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
- KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
- .getProvider()
- .getClass());
-
- KeyManager[] keyManagers = new KeyManager[] {new KeyManager(){}};
- TrustManager[] trustManagers = new TrustManager[] {new TrustManager(){}};
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- // Default SSLContext is provided in an already initialized state
- continue;
- }
- SSLContext sslContext = SSLContext.getInstance(protocol);
- sslContext.init(keyManagers, trustManagers, null);
- }
-
- return null;
- });
- }
-
- public static class ThrowExceptionKeyAndTrustManagerFactoryProvider extends Provider {
- public ThrowExceptionKeyAndTrustManagerFactoryProvider() {
- super("ThrowExceptionKeyAndTrustManagerProvider", 1.0,
- "SSLContextTest fake KeyManagerFactory and TrustManagerFactory provider");
-
- put("TrustManagerFactory." + TrustManagerFactory.getDefaultAlgorithm(),
- ThrowExceptionTrustManagagerFactorySpi.class.getName());
- put("TrustManagerFactory.PKIX", ThrowExceptionTrustManagagerFactorySpi.class.getName());
-
- put("KeyManagerFactory." + KeyManagerFactory.getDefaultAlgorithm(),
- ThrowExceptionKeyManagagerFactorySpi.class.getName());
- put("KeyManagerFactory.PKIX", ThrowExceptionKeyManagagerFactorySpi.class.getName());
- }
- }
-
- public static class ThrowExceptionTrustManagagerFactorySpi extends TrustManagerFactorySpi {
- @Override
- protected void engineInit(KeyStore ks) throws KeyStoreException {
- fail();
- }
-
- @Override
- protected void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException {
- fail();
- }
-
- @Override
- protected TrustManager[] engineGetTrustManagers() {
- throw new AssertionFailedError();
- }
- }
-
- public static class ThrowExceptionKeyManagagerFactorySpi extends KeyManagerFactorySpi {
- @Override
- protected void engineInit(KeyStore ks, char[] password)
- throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
- fail();
- }
-
- @Override
- protected void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException {
- fail();
- }
-
- @Override
- protected KeyManager[] engineGetKeyManagers() {
- throw new AssertionFailedError();
- }
- }
-
- /**
- * Installs the specified security provider as the highest provider, invokes the provided
- * {@link Callable}, and removes the provider.
- *
- * @return result returned by the {@code callable}.
- */
- private static <T> T invokeWithHighestPrioritySecurityProvider(
- Provider provider, Callable<T> callable) throws Exception {
- int providerPosition = -1;
- try {
- providerPosition = Security.insertProviderAt(provider, 1);
- assertEquals(1, providerPosition);
- return callable.call();
- } finally {
- if (providerPosition != -1) {
- Security.removeProvider(provider.getName());
- }
- }
- }
-
- @Test
- public void test_SSLContext_getSocketFactory() throws Exception {
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- SSLContext.getInstance(protocol).getSocketFactory();
- } else {
- try {
- SSLContext.getInstance(protocol).getSocketFactory();
- fail();
- } catch (IllegalStateException expected) {
- // Ignored.
- }
- }
-
- SSLContext sslContext = SSLContext.getInstance(protocol);
- if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- sslContext.init(null, null, null);
- }
- SocketFactory sf = sslContext.getSocketFactory();
- assertNotNull(sf);
- assertTrue(SSLSocketFactory.class.isAssignableFrom(sf.getClass()));
- }
- }
-
- @Test
- public void test_SSLContext_getServerSocketFactory() throws Exception {
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- SSLContext.getInstance(protocol).getServerSocketFactory();
- } else {
- try {
- SSLContext.getInstance(protocol).getServerSocketFactory();
- fail();
- } catch (IllegalStateException expected) {
- // Ignored.
- }
- }
-
- SSLContext sslContext = SSLContext.getInstance(protocol);
- if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- sslContext.init(null, null, null);
- }
- ServerSocketFactory ssf = sslContext.getServerSocketFactory();
- assertNotNull(ssf);
- assertTrue(SSLServerSocketFactory.class.isAssignableFrom(ssf.getClass()));
- }
- }
-
- @Test
- public void test_SSLContext_createSSLEngine() throws Exception {
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- SSLContext.getInstance(protocol).createSSLEngine();
- } else {
- try {
- SSLContext.getInstance(protocol).createSSLEngine();
- fail();
- } catch (IllegalStateException expected) {
- // Ignored.
- }
- }
-
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- SSLContext.getInstance(protocol).createSSLEngine(null, -1);
- } else {
- try {
- SSLContext.getInstance(protocol).createSSLEngine(null, -1);
- fail();
- } catch (IllegalStateException expected) {
- // Ignored.
- }
- }
-
- {
- SSLContext sslContext = SSLContext.getInstance(protocol);
- if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- sslContext.init(null, null, null);
- }
- SSLEngine se = sslContext.createSSLEngine();
- assertNotNull(se);
- }
-
- {
- SSLContext sslContext = SSLContext.getInstance(protocol);
- if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- sslContext.init(null, null, null);
- }
- SSLEngine se = sslContext.createSSLEngine(null, -1);
- assertNotNull(se);
- }
- }
- }
-
- @Test
- public void test_SSLContext_getServerSessionContext() throws Exception {
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- SSLContext sslContext = SSLContext.getInstance(protocol);
- SSLSessionContext sessionContext = sslContext.getServerSessionContext();
- assertNotNull(sessionContext);
-
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- assertSame(
- SSLContext.getInstance(protocol).getServerSessionContext(), sessionContext);
- } else {
- assertNotSame(
- SSLContext.getInstance(protocol).getServerSessionContext(), sessionContext);
- }
- }
- }
-
- @Test
- public void test_SSLContext_getClientSessionContext() throws Exception {
- for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- SSLContext sslContext = SSLContext.getInstance(protocol);
- SSLSessionContext sessionContext = sslContext.getClientSessionContext();
- assertNotNull(sessionContext);
-
- if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
- assertSame(
- SSLContext.getInstance(protocol).getClientSessionContext(), sessionContext);
- } else {
- assertNotSame(
- SSLContext.getInstance(protocol).getClientSessionContext(), sessionContext);
- }
- }
- }
-
- @Test
- public void test_SSLContextTest_TestSSLContext_create() {
- TestSSLContext testContext = TestSSLContext.create();
- assertNotNull(testContext);
- assertNotNull(testContext.clientKeyStore);
- assertNull(testContext.clientStorePassword);
- assertNotNull(testContext.serverKeyStore);
- assertNotNull(testContext.clientKeyManagers);
- assertNotNull(testContext.serverKeyManagers);
- if (testContext.clientKeyManagers.length == 0) {
- fail("No client KeyManagers");
- }
- if (testContext.serverKeyManagers.length == 0) {
- fail("No server KeyManagers");
- }
- assertNotNull(testContext.clientKeyManagers[0]);
- assertNotNull(testContext.serverKeyManagers[0]);
- assertNotNull(testContext.clientTrustManager);
- assertNotNull(testContext.serverTrustManager);
- assertNotNull(testContext.clientContext);
- assertNotNull(testContext.serverContext);
- assertNotNull(testContext.serverSocket);
- assertNotNull(testContext.host);
- assertTrue(testContext.port != 0);
- testContext.close();
- }
-
- @Test(expected = NoSuchAlgorithmException.class)
- public void test_SSLContext_SSLv3Unsupported() throws Exception {
- // Find the default provider for TLS and verify that it does NOT support SSLv3.
- Provider defaultTlsProvider = null;
- for (Provider p : Security.getProviders()) {
- if (p.get(TestUtils.PROVIDER_PROPERTY) != null) {
- defaultTlsProvider = p;
- break;
- }
- }
- assertNotNull(defaultTlsProvider);
- SSLContext.getInstance("SSLv3", defaultTlsProvider);
- }
-
- private static void assertContentsInOrder(List<String> expected, String... actual) {
- if (expected.size() != actual.length) {
- fail("Unexpected length. Expected len <" + expected.size() + ">, actual len <"
- + actual.length + ">, expected <" + expected + ">, actual <"
- + Arrays.asList(actual) + ">");
- }
- if (!expected.equals(Arrays.asList(actual))) {
- fail("Unexpected element(s). Expected <" + expected + ">, actual <"
- + Arrays.asList(actual) + ">");
- }
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
deleted file mode 100644
index 01c94e4a..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
+++ /dev/null
@@ -1,885 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import javax.crypto.SecretKey;
-import javax.crypto.spec.SecretKeySpec;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLParameters;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.X509ExtendedKeyManager;
-import libcore.java.security.StandardNames;
-import libcore.java.security.TestKeyStore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SSLEngineTest extends AbstractSSLTest {
-
- @Test
- public void test_SSLEngine_defaultConfiguration() throws Exception {
- SSLConfigurationAsserts.assertSSLEngineDefaultConfiguration(
- TestSSLContext.create().clientContext.createSSLEngine());
- }
-
- @Test
- public void test_SSLEngine_getSupportedCipherSuites_returnsCopies() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- assertNotSame(e.getSupportedCipherSuites(), e.getSupportedCipherSuites());
- c.close();
- }
-
- @Test
- public void test_SSLEngine_getSupportedCipherSuites_connect() throws Exception {
- // note the rare usage of non-RSA keys
- TestKeyStore testKeyStore = new TestKeyStore.Builder()
- .keyAlgorithms("RSA", "DSA", "EC", "EC_RSA")
- .aliasPrefix("rsa-dsa-ec")
- .ca(true)
- .build();
- test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, false);
- test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, true);
- }
-
- // http://b/18554122
- @Test
- public void test_SSLEngine_underflowsOnEmptyBuffersDuringHandshake() throws Exception {
- final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
- sslEngine.setUseClientMode(false);
- ByteBuffer input = ByteBuffer.allocate(1024);
- input.flip();
- ByteBuffer output = ByteBuffer.allocate(1024);
- sslEngine.beginHandshake();
- assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, sslEngine.getHandshakeStatus());
- SSLEngineResult result = sslEngine.unwrap(input, output);
- assertEquals(SSLEngineResult.Status.BUFFER_UNDERFLOW, result.getStatus());
- assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP, result.getHandshakeStatus());
- }
-
- // http://b/18554122
- @Test
- public void test_SSLEngine_underflowsOnEmptyBuffersAfterHandshake() throws Exception {
- // Note that create performs the handshake.
- final TestSSLEnginePair engines = TestSSLEnginePair.create(null /* hooks */);
- ByteBuffer input = ByteBuffer.allocate(1024);
- input.flip();
- ByteBuffer output = ByteBuffer.allocate(1024);
- assertEquals(SSLEngineResult.Status.BUFFER_UNDERFLOW,
- engines.client.unwrap(input, output).getStatus());
- }
-
- private void test_SSLEngine_getSupportedCipherSuites_connect(
- TestKeyStore testKeyStore, boolean secureRenegotiation) throws Exception {
- KeyManager pskKeyManager =
- PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy() {
- @Override
- protected SecretKey getKey(
- String identityHint, String identity, SSLEngine engine) {
- return new SecretKeySpec("Just an arbitrary key".getBytes(UTF_8), "RAW");
- }
- });
- TestSSLContext c = TestSSLContext.newBuilder()
- .client(testKeyStore)
- .server(testKeyStore)
- .additionalClientKeyManagers(new KeyManager[] {pskKeyManager})
- .additionalServerKeyManagers(new KeyManager[] {pskKeyManager})
- .build();
-
- // Create a TestSSLContext where the KeyManager returns wrong (randomly generated) private
- // keys, matching the algorithm and parameters of the correct keys.
- // I couldn't find a more elegant way to achieve this other than temporarily replacing the
- // first X509ExtendedKeyManager element of TestKeyStore.keyManagers while invoking
- // TestSSLContext.create.
- TestSSLContext cWithWrongPrivateKeys;
- {
- // Create a RandomPrivateKeyX509ExtendedKeyManager based on the first
- // X509ExtendedKeyManager in c.serverKeyManagers.
- KeyManager randomPrivateKeyX509ExtendedKeyManager = null;
- for (KeyManager keyManager : c.serverKeyManagers) {
- if (keyManager instanceof X509ExtendedKeyManager) {
- randomPrivateKeyX509ExtendedKeyManager =
- new RandomPrivateKeyX509ExtendedKeyManager(
- (X509ExtendedKeyManager) keyManager);
- break;
- }
- }
- if (randomPrivateKeyX509ExtendedKeyManager == null) {
- fail("No X509ExtendedKeyManager in c.serverKeyManagers");
- }
-
- // Find the first X509ExtendedKeyManager in testKeyStore.keyManagers
- int replaceIndex = -1;
- for (int i = 0; i < testKeyStore.keyManagers.length; i++) {
- KeyManager keyManager = testKeyStore.keyManagers[i];
- if (keyManager instanceof X509ExtendedKeyManager) {
- replaceIndex = i;
- break;
- }
- }
- if (replaceIndex == -1) {
- fail("No X509ExtendedKeyManager in testKeyStore.keyManagers");
- }
-
- // Temporarily substitute the RandomPrivateKeyX509ExtendedKeyManager in place of the
- // original X509ExtendedKeyManager.
- KeyManager originalKeyManager = testKeyStore.keyManagers[replaceIndex];
- testKeyStore.keyManagers[replaceIndex] = randomPrivateKeyX509ExtendedKeyManager;
- cWithWrongPrivateKeys = TestSSLContext.create(testKeyStore, testKeyStore);
- testKeyStore.keyManagers[replaceIndex] = originalKeyManager;
- }
-
- // To catch all the errors.
- StringBuilder error = new StringBuilder();
-
- String[] cipherSuites = c.clientContext.createSSLEngine().getSupportedCipherSuites();
- for (String cipherSuite : cipherSuites) {
- try {
- // Skip cipher suites that are obsoleted.
- if (StandardNames.IS_RI && "TLSv1.2".equals(c.clientContext.getProtocol())
- && StandardNames.CIPHER_SUITES_OBSOLETE_TLS12.contains(cipherSuite)) {
- continue;
- }
- /*
- * Signaling Cipher Suite Values (SCSV) cannot be used on their own, but instead in
- * conjunction with other cipher suites.
- */
- if (cipherSuite.equals(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION)
- || cipherSuite.equals(StandardNames.CIPHER_SUITE_FALLBACK)) {
- continue;
- }
- /*
- * Kerberos cipher suites require external setup. See "Kerberos Requirements" in
- * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html
- * #KRBRequire
- */
- if (cipherSuite.startsWith("TLS_KRB5_")) {
- continue;
- }
-
- final String[] cipherSuiteArray = (secureRenegotiation
- ? new String[] {cipherSuite,
- StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION}
- : new String[] {cipherSuite});
-
- // Check that handshake succeeds.
- TestSSLEnginePair pair = null;
- try {
- pair = TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- client.setEnabledCipherSuites(cipherSuiteArray);
- server.setEnabledCipherSuites(cipherSuiteArray);
- }
- });
- assertConnected(pair);
-
- boolean needsRecordSplit = "TLS".equalsIgnoreCase(c.clientContext.getProtocol())
- && cipherSuite.contains("_CBC_");
-
- assertSendsCorrectly("This is the client. Hello!".getBytes(UTF_8), pair.client,
- pair.server, needsRecordSplit);
- assertSendsCorrectly("This is the server. Hi!".getBytes(UTF_8), pair.server,
- pair.client, needsRecordSplit);
- } finally {
- if (pair != null) {
- pair.close();
- }
- }
-
- // Check that handshake fails when the server does not possess the private key
- // corresponding to the server's certificate. This is achieved by using SSLContext
- // cWithWrongPrivateKeys whose KeyManager returns wrong private keys that match
- // the algorithm (and parameters) of the correct keys.
- boolean serverAuthenticatedUsingPublicKey = true;
- if (cipherSuite.contains("_anon_")) {
- serverAuthenticatedUsingPublicKey = false;
- } else if ((cipherSuite.startsWith("TLS_PSK_"))
- || (cipherSuite.startsWith("TLS_ECDHE_PSK_"))) {
- serverAuthenticatedUsingPublicKey = false;
- }
- if (serverAuthenticatedUsingPublicKey) {
- TestSSLEnginePair p = null;
- try {
- p = TestSSLEnginePair.create(
- cWithWrongPrivateKeys, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- client.setEnabledCipherSuites(cipherSuiteArray);
- server.setEnabledCipherSuites(cipherSuiteArray);
- }
- });
- assertNotConnected(p);
- } catch (IOException expected) {
- // Ignored.
- } finally {
- if (p != null) {
- p.close();
- }
- }
- }
- } catch (Exception e) {
- String message = ("Problem trying to connect cipher suite " + cipherSuite);
- System.out.println(message);
- e.printStackTrace();
- error.append(message);
- error.append('\n');
- }
- }
- c.close();
-
- if (error.length() > 0) {
- throw new Exception("One or more problems in "
- + "test_SSLEngine_getSupportedCipherSuites_connect:\n" + error);
- }
- }
-
- private static void assertSendsCorrectly(final byte[] sourceBytes, SSLEngine source,
- SSLEngine dest, boolean needsRecordSplit) throws SSLException {
- ByteBuffer sourceOut = ByteBuffer.wrap(sourceBytes);
- SSLSession sourceSession = source.getSession();
- ByteBuffer sourceToDest = ByteBuffer.allocate(sourceSession.getPacketBufferSize());
- SSLEngineResult sourceOutRes = source.wrap(sourceOut, sourceToDest);
- sourceToDest.flip();
-
- String sourceCipherSuite = source.getSession().getCipherSuite();
- assertEquals(sourceCipherSuite, sourceBytes.length, sourceOutRes.bytesConsumed());
- assertEquals(sourceCipherSuite, HandshakeStatus.NOT_HANDSHAKING,
- sourceOutRes.getHandshakeStatus());
-
- SSLSession destSession = dest.getSession();
- ByteBuffer destIn = ByteBuffer.allocate(destSession.getApplicationBufferSize());
-
- int numUnwrapCalls = 0;
- while (destIn.position() != sourceOut.limit()) {
- SSLEngineResult destRes = dest.unwrap(sourceToDest, destIn);
- assertEquals(sourceCipherSuite, HandshakeStatus.NOT_HANDSHAKING,
- destRes.getHandshakeStatus());
- if (needsRecordSplit && numUnwrapCalls == 0) {
- assertEquals(sourceCipherSuite, 1, destRes.bytesProduced());
- }
- numUnwrapCalls++;
- }
-
- destIn.flip();
- byte[] actual = new byte[destIn.remaining()];
- destIn.get(actual);
- assertEquals(sourceCipherSuite, Arrays.toString(sourceBytes), Arrays.toString(actual));
-
- if (needsRecordSplit) {
- assertEquals(sourceCipherSuite, 2, numUnwrapCalls);
- } else {
- assertEquals(sourceCipherSuite, 1, numUnwrapCalls);
- }
- }
-
- @Test
- public void test_SSLEngine_getEnabledCipherSuites_returnsCopies() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- assertNotSame(e.getEnabledCipherSuites(), e.getEnabledCipherSuites());
- c.close();
- }
-
- @Test
- public void test_SSLEngine_setEnabledCipherSuites_storesCopy() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- String[] array = new String[] {e.getEnabledCipherSuites()[0]};
- String originalFirstElement = array[0];
- e.setEnabledCipherSuites(array);
- array[0] = "Modified after having been set";
- assertEquals(originalFirstElement, e.getEnabledCipherSuites()[0]);
- }
-
- @Test
- public void test_SSLEngine_setEnabledCipherSuites() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
-
- try {
- e.setEnabledCipherSuites(null);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- e.setEnabledCipherSuites(new String[1]);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- e.setEnabledCipherSuites(new String[] {"Bogus"});
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
-
- e.setEnabledCipherSuites(new String[0]);
- e.setEnabledCipherSuites(e.getEnabledCipherSuites());
- e.setEnabledCipherSuites(e.getSupportedCipherSuites());
-
- // Check that setEnabledCipherSuites affects getEnabledCipherSuites
- String[] cipherSuites = new String[] {e.getSupportedCipherSuites()[0]};
- e.setEnabledCipherSuites(cipherSuites);
- assertEquals(Arrays.asList(cipherSuites), Arrays.asList(e.getEnabledCipherSuites()));
-
- c.close();
- }
-
- @Test
- public void test_SSLEngine_getSupportedProtocols_returnsCopies() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- assertNotSame(e.getSupportedProtocols(), e.getSupportedProtocols());
- c.close();
- }
-
- @Test
- public void test_SSLEngine_getEnabledProtocols_returnsCopies() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- assertNotSame(e.getEnabledProtocols(), e.getEnabledProtocols());
- c.close();
- }
-
- @Test
- public void test_SSLEngine_setEnabledProtocols_storesCopy() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- String[] array = new String[] {e.getEnabledProtocols()[0]};
- String originalFirstElement = array[0];
- e.setEnabledProtocols(array);
- array[0] = "Modified after having been set";
- assertEquals(originalFirstElement, e.getEnabledProtocols()[0]);
- }
-
- @Test
- public void test_SSLEngine_setEnabledProtocols() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
-
- try {
- e.setEnabledProtocols(null);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- e.setEnabledProtocols(new String[1]);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- e.setEnabledProtocols(new String[] {"Bogus"});
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- e.setEnabledProtocols(new String[0]);
- e.setEnabledProtocols(e.getEnabledProtocols());
- e.setEnabledProtocols(e.getSupportedProtocols());
-
- // Check that setEnabledProtocols affects getEnabledProtocols
- for (String protocol : e.getSupportedProtocols()) {
- if ("SSLv2Hello".equals(protocol)) {
- try {
- e.setEnabledProtocols(new String[] {protocol});
- fail("Should fail when SSLv2Hello is set by itself");
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- } else {
- String[] protocols = new String[] {protocol};
- e.setEnabledProtocols(protocols);
- assertEquals(Arrays.deepToString(protocols),
- Arrays.deepToString(e.getEnabledProtocols()));
- }
- }
-
- c.close();
- }
-
- @Test
- public void test_SSLEngine_getSession() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- SSLSession session = e.getSession();
- assertNotNull(session);
- assertFalse(session.isValid());
- c.close();
- }
-
- @Test
- public void test_SSLEngine_beginHandshake() throws Exception {
- TestSSLContext c = TestSSLContext.create();
-
- try {
- c.clientContext.createSSLEngine().beginHandshake();
- fail();
- } catch (IllegalStateException expected) {
- // Ignored.
- }
- c.close();
-
- TestSSLEnginePair p = TestSSLEnginePair.create(null);
- assertConnected(p);
- p.close();
- }
-
- @Test
- public void test_SSLEngine_beginHandshake_noKeyStore() throws Exception {
- TestSSLContext c = TestSSLContext.newBuilder()
- .useDefaults(false)
- .clientContext(SSLContext.getDefault())
- .serverContext(SSLContext.getDefault())
- .build();
- SSLEngine[] p = null;
- try {
- // TODO Fix KnownFailure AlertException "NO SERVER CERTIFICATE FOUND"
- // ServerHandshakeImpl.selectSuite should not select a suite without a required cert
- p = TestSSLEnginePair.connect(c, null);
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- } finally {
- if (p != null) {
- TestSSLEnginePair.close(p);
- }
- }
- c.close();
- }
-
- @Test
- public void test_SSLEngine_beginHandshake_noClientCertificate() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine[] engines = TestSSLEnginePair.connect(c, null);
- assertConnected(engines[0], engines[1]);
- c.close();
- TestSSLEnginePair.close(engines);
- }
-
- @Test
- public void test_SSLEngine_getUseClientMode() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- assertFalse(c.clientContext.createSSLEngine().getUseClientMode());
- assertFalse(c.clientContext.createSSLEngine(null, -1).getUseClientMode());
- c.close();
- }
-
- @Test
- public void test_SSLEngine_setUseClientMode() throws Exception {
- boolean[] finished;
- TestSSLEnginePair p;
-
- // client is client, server is server
- finished = new boolean[2];
- p = test_SSLEngine_setUseClientMode(true, false, finished);
- assertConnected(p);
- assertTrue(finished[0]);
- assertTrue(finished[1]);
- p.close();
-
- // client is server, server is client
- finished = new boolean[2];
- p = test_SSLEngine_setUseClientMode(false, true, finished);
- assertConnected(p);
- assertTrue(finished[0]);
- assertTrue(finished[1]);
- p.close();
-
- // both are client
- /*
- * Our implementation throws an SSLHandshakeException, but RI just
- * stalls forever
- */
- p = null;
- try {
- p = test_SSLEngine_setUseClientMode(true, true, null);
- assertNotConnected(p);
- } catch (SSLHandshakeException maybeExpected) {
- // Ignored.
- } finally {
- if (p != null) {
- p.close();
- }
- }
-
- p = test_SSLEngine_setUseClientMode(false, false, null);
- // both are server
- assertNotConnected(p);
- p.close();
- }
-
- @Test
- public void test_SSLEngine_setUseClientMode_afterHandshake() throws Exception {
- // can't set after handshake
- TestSSLEnginePair pair = TestSSLEnginePair.create(null);
- try {
- pair.server.setUseClientMode(false);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- pair.client.setUseClientMode(false);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- pair.close();
- }
-
- private TestSSLEnginePair test_SSLEngine_setUseClientMode(final boolean clientClientMode,
- final boolean serverClientMode, final boolean[] finished) throws Exception {
- TestSSLContext c;
- if (!clientClientMode && serverClientMode) {
- c = TestSSLContext.create(TestKeyStore.getServer(), TestKeyStore.getClient());
- } else {
- c = TestSSLContext.create();
- }
-
- return TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- client.setUseClientMode(clientClientMode);
- server.setUseClientMode(serverClientMode);
- }
- }, finished);
- }
-
- @Test
- public void test_SSLEngine_clientAuth() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
-
- assertFalse(e.getWantClientAuth());
- assertFalse(e.getNeedClientAuth());
-
- // confirm turning one on by itself
- e.setWantClientAuth(true);
- assertTrue(e.getWantClientAuth());
- assertFalse(e.getNeedClientAuth());
-
- // confirm turning setting on toggles the other
- e.setNeedClientAuth(true);
- assertFalse(e.getWantClientAuth());
- assertTrue(e.getNeedClientAuth());
-
- // confirm toggling back
- e.setWantClientAuth(true);
- assertTrue(e.getWantClientAuth());
- assertFalse(e.getNeedClientAuth());
-
- // TODO Fix KnownFailure "init - invalid private key"
- TestSSLContext clientAuthContext = TestSSLContext.create(
- TestKeyStore.getClientCertificate(), TestKeyStore.getServer());
- TestSSLEnginePair p =
- TestSSLEnginePair.create(clientAuthContext, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- server.setWantClientAuth(true);
- }
- });
- assertConnected(p);
- assertNotNull(p.client.getSession().getLocalCertificates());
- TestKeyStore.assertChainLength(p.client.getSession().getLocalCertificates());
- TestSSLContext.assertClientCertificateChain(
- clientAuthContext.clientTrustManager, p.client.getSession().getLocalCertificates());
- clientAuthContext.close();
- c.close();
- p.close();
- }
-
- /**
- * http://code.google.com/p/android/issues/detail?id=31903
- * This test case directly tests the fix for the issue.
- */
- @Test
- public void test_SSLEngine_clientAuthWantedNoClientCert() throws Exception {
- TestSSLContext clientAuthContext =
- TestSSLContext.create(TestKeyStore.getClient(), TestKeyStore.getServer());
- TestSSLEnginePair p =
- TestSSLEnginePair.create(clientAuthContext, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- server.setWantClientAuth(true);
- }
- });
- assertConnected(p);
- clientAuthContext.close();
- p.close();
- }
-
- /**
- * http://code.google.com/p/android/issues/detail?id=31903
- * This test case verifies that if the server requires a client cert
- * (setNeedClientAuth) but the client does not provide one SSL connection
- * establishment will fail
- */
- @Test
- public void test_SSLEngine_clientAuthNeededNoClientCert() throws Exception {
- TestSSLContext clientAuthContext =
- TestSSLContext.create(TestKeyStore.getClient(), TestKeyStore.getServer());
- TestSSLEnginePair p = null;
- try {
- p = TestSSLEnginePair.create(clientAuthContext, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- server.setNeedClientAuth(true);
- }
- });
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- } finally {
- clientAuthContext.close();
- if (p != null) {
- p.close();
- }
- }
- }
-
- @Test
- public void test_SSLEngine_endpointVerification_Success() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- TestSSLEnginePair p = TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- SSLParameters p = client.getSSLParameters();
- p.setEndpointIdentificationAlgorithm("HTTPS");
- client.setSSLParameters(p);
- }
- });
- assertConnected(p);
- c.close();
- }
-
- @Test
- public void test_SSLEngine_getEnableSessionCreation() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- assertTrue(e.getEnableSessionCreation());
- c.close();
- TestSSLEnginePair.close(new SSLEngine[] {e});
- }
-
- @Test
- public void test_SSLEngine_setEnableSessionCreation_server() throws Exception {
- TestSSLEnginePair p = null;
- try {
- p = TestSSLEnginePair.create(new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- server.setEnableSessionCreation(false);
- }
- });
- assertNotConnected(p);
- } catch (SSLException maybeExpected) {
- // Ignored.
- } finally {
- if (p != null) {
- p.close();
- }
- }
- }
-
- @Test
- public void test_SSLEngine_setEnableSessionCreation_client() throws Exception {
- TestSSLEnginePair p = null;
- try {
- p = TestSSLEnginePair.create(new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- client.setEnableSessionCreation(false);
- }
- });
- fail();
- } catch (SSLException expected) {
- // Ignored.
- } finally {
- if (p != null) {
- p.close();
- }
- }
- }
-
- @Test
- public void test_SSLEngine_getSSLParameters() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
-
- SSLParameters p = e.getSSLParameters();
- assertNotNull(p);
-
- String[] cipherSuites = p.getCipherSuites();
- assertNotSame(cipherSuites, e.getEnabledCipherSuites());
- assertEquals(Arrays.asList(cipherSuites), Arrays.asList(e.getEnabledCipherSuites()));
-
- String[] protocols = p.getProtocols();
- assertNotSame(protocols, e.getEnabledProtocols());
- assertEquals(Arrays.asList(protocols), Arrays.asList(e.getEnabledProtocols()));
-
- assertEquals(p.getWantClientAuth(), e.getWantClientAuth());
- assertEquals(p.getNeedClientAuth(), e.getNeedClientAuth());
-
- c.close();
- }
-
- @Test
- public void test_SSLEngine_setSSLParameters() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLEngine e = c.clientContext.createSSLEngine();
- String[] defaultCipherSuites = e.getEnabledCipherSuites();
- String[] defaultProtocols = e.getEnabledProtocols();
- String[] supportedCipherSuites = e.getSupportedCipherSuites();
- String[] supportedProtocols = e.getSupportedProtocols();
-
- {
- SSLParameters p = new SSLParameters();
- e.setSSLParameters(p);
- assertEquals(
- Arrays.asList(defaultCipherSuites), Arrays.asList(e.getEnabledCipherSuites()));
- assertEquals(Arrays.asList(defaultProtocols), Arrays.asList(e.getEnabledProtocols()));
- }
-
- {
- SSLParameters p = new SSLParameters(supportedCipherSuites, supportedProtocols);
- e.setSSLParameters(p);
- assertEquals(Arrays.asList(supportedCipherSuites),
- Arrays.asList(e.getEnabledCipherSuites()));
- assertEquals(Arrays.asList(supportedProtocols), Arrays.asList(e.getEnabledProtocols()));
- }
- {
- SSLParameters p = new SSLParameters();
-
- p.setNeedClientAuth(true);
- assertFalse(e.getNeedClientAuth());
- assertFalse(e.getWantClientAuth());
- e.setSSLParameters(p);
- assertTrue(e.getNeedClientAuth());
- assertFalse(e.getWantClientAuth());
-
- p.setWantClientAuth(true);
- assertTrue(e.getNeedClientAuth());
- assertFalse(e.getWantClientAuth());
- e.setSSLParameters(p);
- assertFalse(e.getNeedClientAuth());
- assertTrue(e.getWantClientAuth());
-
- p.setWantClientAuth(false);
- assertFalse(e.getNeedClientAuth());
- assertTrue(e.getWantClientAuth());
- e.setSSLParameters(p);
- assertFalse(e.getNeedClientAuth());
- assertFalse(e.getWantClientAuth());
- }
- c.close();
- }
-
- @Test
- public void test_TestSSLEnginePair_create() throws Exception {
- TestSSLEnginePair test = TestSSLEnginePair.create(null);
- assertNotNull(test.c);
- assertNotNull(test.server);
- assertNotNull(test.client);
- assertConnected(test);
- test.close();
- }
-
- private final int NUM_STRESS_ITERATIONS = 1000;
-
- @Test
- public void test_SSLEngine_Multiple_Thread_Success() throws Exception {
- try (final TestSSLEnginePair pair = TestSSLEnginePair.create()) {
- assertConnected(pair);
-
- final CountDownLatch startUpSync = new CountDownLatch(2);
- ExecutorService executor = Executors.newFixedThreadPool(2);
- Future<Void> client = executor.submit(() -> {
- startUpSync.countDown();
-
- for (int i = 0; i < NUM_STRESS_ITERATIONS; i++) {
- assertSendsCorrectly("This is the client. Hello!".getBytes(UTF_8), pair.client,
- pair.server, false);
- }
-
- return null;
- });
- Future<Void> server = executor.submit(() -> {
- startUpSync.countDown();
-
- for (int i = 0; i < NUM_STRESS_ITERATIONS; i++) {
- assertSendsCorrectly("This is the server. Hi!".getBytes(UTF_8), pair.server,
- pair.client, false);
- }
-
- return null;
- });
- executor.shutdown();
- client.get();
- server.get();
- }
- }
-
- private void assertConnected(TestSSLEnginePair e) {
- assertConnected(e.client, e.server);
- }
-
- private void assertNotConnected(TestSSLEnginePair e) {
- assertNotConnected(e.client, e.server);
- }
-
- private void assertConnected(SSLEngine a, SSLEngine b) {
- assertTrue(connected(a, b));
- }
-
- private void assertNotConnected(SSLEngine a, SSLEngine b) {
- assertFalse(connected(a, b));
- }
-
- private boolean connected(SSLEngine a, SSLEngine b) {
- return (a.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING
- && b.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING
- && a.getSession() != null && b.getSession() != null && !a.isInboundDone()
- && !b.isInboundDone() && !a.isOutboundDone() && !b.isOutboundDone());
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLParametersTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLParametersTest.java
deleted file mode 100644
index 1831533d..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLParametersTest.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import javax.net.ssl.SNIHostName;
-import javax.net.ssl.SNIMatcher;
-import javax.net.ssl.SNIServerName;
-import javax.net.ssl.SSLParameters;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SSLParametersTest extends AbstractSSLTest {
-
- @Test
- public void test_SSLParameters_emptyConstructor() {
- SSLParameters p = new SSLParameters();
- assertNull(p.getCipherSuites());
- assertNull(p.getProtocols());
- assertFalse(p.getWantClientAuth());
- assertFalse(p.getNeedClientAuth());
- }
-
- @Test
- public void test_SSLParameters_cipherSuitesConstructor() {
- String[] cipherSuites = new String[] {"foo", null, "bar"};
- SSLParameters p = new SSLParameters(cipherSuites);
- assertNotNull(p.getCipherSuites());
- assertNotSame(cipherSuites, p.getCipherSuites());
- assertEquals(Arrays.asList(cipherSuites), Arrays.asList(p.getCipherSuites()));
- assertNull(p.getProtocols());
- assertFalse(p.getWantClientAuth());
- assertFalse(p.getNeedClientAuth());
- }
-
- @Test
- public void test_SSLParameters_cpherSuitesProtocolsConstructor() {
- String[] cipherSuites = new String[] {"foo", null, "bar"};
- String[] protocols = new String[] {"baz", null, "qux"};
- SSLParameters p = new SSLParameters(cipherSuites, protocols);
- assertNotNull(p.getCipherSuites());
- assertNotNull(p.getProtocols());
- assertNotSame(cipherSuites, p.getCipherSuites());
- assertNotSame(protocols, p.getProtocols());
- assertEquals(Arrays.asList(cipherSuites), Arrays.asList(p.getCipherSuites()));
- assertEquals(Arrays.asList(protocols), Arrays.asList(p.getProtocols()));
- assertFalse(p.getWantClientAuth());
- assertFalse(p.getNeedClientAuth());
- }
-
- @Test
- public void test_SSLParameters_CipherSuites() {
- SSLParameters p = new SSLParameters();
- assertNull(p.getCipherSuites());
-
- // confirm clone on input
- String[] cipherSuites = new String[] {"fnord"};
- String[] copy = cipherSuites.clone();
- p.setCipherSuites(copy);
- copy[0] = null;
- assertEquals(Arrays.asList(cipherSuites), Arrays.asList(p.getCipherSuites()));
-
- // confirm clone on output
- assertNotSame(p.getCipherSuites(), p.getCipherSuites());
- }
-
- @Test
- public void test_SSLParameters_Protocols() {
- SSLParameters p = new SSLParameters();
- assertNull(p.getProtocols());
-
- // confirm clone on input
- String[] protocols = new String[] {"fnord"};
- String[] copy = protocols.clone();
- p.setProtocols(copy);
- copy[0] = null;
- assertEquals(Arrays.asList(protocols), Arrays.asList(p.getProtocols()));
-
- // confirm clone on output
- assertNotSame(p.getProtocols(), p.getProtocols());
- }
-
- @Test
- public void test_SSLParameters_ClientAuth() {
- SSLParameters p = new SSLParameters();
- assertFalse(p.getWantClientAuth());
- assertFalse(p.getNeedClientAuth());
-
- // confirm turning one on by itself
- p.setWantClientAuth(true);
- assertTrue(p.getWantClientAuth());
- assertFalse(p.getNeedClientAuth());
-
- // confirm turning setting on toggles the other
- p.setNeedClientAuth(true);
- assertFalse(p.getWantClientAuth());
- assertTrue(p.getNeedClientAuth());
-
- // confirm toggling back
- p.setWantClientAuth(true);
- assertTrue(p.getWantClientAuth());
- assertFalse(p.getNeedClientAuth());
- }
-
- @Test
- public void test_SSLParameters_setServerNames_duplicatedNameThrows() throws Exception {
- SSLParameters p = new SSLParameters();
- ArrayList<SNIServerName> dupeNames = new ArrayList<>();
- dupeNames.add(new SNIHostName("www.example.com"));
- dupeNames.add(new SNIHostName("www.example.com"));
- try {
- p.setServerNames(dupeNames);
- fail("Should throw IllegalArgumentException when names are duplicated");
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- }
-
- @Test
- public void test_SSLParameters_setServerNames_setNull_getNull() throws Exception {
- SSLParameters p = new SSLParameters();
- p.setServerNames(Collections.singletonList(new SNIHostName("www.example.com")));
- assertNotNull(p.getServerNames());
- p.setServerNames(null);
- assertNull(p.getServerNames());
- }
-
- @Test
- public void test_SSLParameters_setServerNames_setEmpty_getEmpty() throws Exception {
- SSLParameters p = new SSLParameters();
- p.setServerNames(new ArrayList<>());
- Collection<SNIServerName> actual = p.getServerNames();
- assertNotNull(actual);
- assertEquals(0, actual.size());
- }
-
- @Test
- public void test_SSLParameters_getServerNames_unmodifiable() throws Exception {
- SSLParameters p = new SSLParameters();
- p.setServerNames(Collections.singletonList(new SNIHostName("www.example.com")));
- Collection<SNIServerName> actual = p.getServerNames();
- try {
- actual.add(new SNIHostName("www.foo.com"));
- fail("Should not allow modifications to the list");
- } catch (UnsupportedOperationException expected) {
- // Ignored.
- }
- }
-
- @Test
- public void test_SSLParameters_setSNIMatchers_duplicatedNameThrows() throws Exception {
- SSLParameters p = new SSLParameters();
- ArrayList<SNIMatcher> dupeMatchers = new ArrayList<>();
- dupeMatchers.add(SNIHostName.createSNIMatcher("www\\.example\\.com"));
- dupeMatchers.add(SNIHostName.createSNIMatcher("www\\.example\\.com"));
- try {
- p.setSNIMatchers(dupeMatchers);
- fail("Should throw IllegalArgumentException when matchers are duplicated");
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- }
-
- @Test
- public void test_SSLParameters_setSNIMatchers_setNull_getNull() throws Exception {
- SSLParameters p = new SSLParameters();
- p.setSNIMatchers(
- Collections.singletonList(SNIHostName.createSNIMatcher("www\\.example\\.com")));
- assertNotNull(p.getSNIMatchers());
- p.setSNIMatchers(null);
- assertNull(p.getSNIMatchers());
- }
-
- @Test
- public void test_SSLParameters_setSNIMatchers_setEmpty_getEmpty() throws Exception {
- SSLParameters p = new SSLParameters();
- p.setSNIMatchers(
- Collections.singletonList(SNIHostName.createSNIMatcher("www\\.example\\.com")));
- assertEquals(1, p.getSNIMatchers().size());
- p.setSNIMatchers(Collections.emptyList());
- Collection<SNIMatcher> actual = p.getSNIMatchers();
- assertNotNull(actual);
- assertEquals(0, actual.size());
- }
-
- @Test
- public void test_SSLParameters_getSNIMatchers_unmodifiable() throws Exception {
- SSLParameters p = new SSLParameters();
- p.setSNIMatchers(
- Collections.singletonList(SNIHostName.createSNIMatcher("www\\.example\\.com")));
- Collection<SNIMatcher> actual = p.getSNIMatchers();
- try {
- actual.add(SNIHostName.createSNIMatcher("www\\.google\\.com"));
- fail("Should not allow modification of list");
- } catch (UnsupportedOperationException expected) {
- // Ignored.
- }
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java
deleted file mode 100644
index 48a0cc31..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLServerSocketFactoryTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import javax.net.ssl.SSLServerSocketFactory;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SSLServerSocketFactoryTest extends AbstractSSLTest {
-
- @Test
- public void testDefaultConfiguration() throws Exception {
- SSLConfigurationAsserts.assertSSLServerSocketFactoryDefaultConfiguration(
- (SSLServerSocketFactory) SSLServerSocketFactory.getDefault());
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java
deleted file mode 100644
index 0898622f..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLServerSocketTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.Arrays;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLServerSocketFactory;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SSLServerSocketTest extends AbstractSSLTest {
-
- @Test
- public void testDefaultConfiguration() throws Exception {
- SSLConfigurationAsserts.assertSSLServerSocketDefaultConfiguration(
- (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket());
- }
-
- @Test
- public void testSetEnabledCipherSuitesAffectsGetter() throws Exception {
- SSLServerSocket socket =
- (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
- String[] cipherSuites = new String[] {socket.getSupportedCipherSuites()[0]};
- socket.setEnabledCipherSuites(cipherSuites);
- assertEquals(Arrays.asList(cipherSuites), Arrays.asList(socket.getEnabledCipherSuites()));
- }
-
- @Test
- public void testSetEnabledCipherSuitesStoresCopy() throws Exception {
- SSLServerSocket socket =
- (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
- String[] array = new String[] {socket.getEnabledCipherSuites()[0]};
- String originalFirstElement = array[0];
- socket.setEnabledCipherSuites(array);
- array[0] = "Modified after having been set";
- assertEquals(originalFirstElement, socket.getEnabledCipherSuites()[0]);
- }
-
- @Test
- public void testSetEnabledProtocolsAffectsGetter() throws Exception {
- SSLServerSocket socket =
- (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
- String[] protocols = new String[] {socket.getSupportedProtocols()[0]};
- socket.setEnabledProtocols(protocols);
- assertEquals(Arrays.asList(protocols), Arrays.asList(socket.getEnabledProtocols()));
- }
-
- @Test
- public void testSetEnabledProtocolsStoresCopy() throws Exception {
- SSLServerSocket socket =
- (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
- String[] array = new String[] {socket.getEnabledProtocols()[0]};
- String originalFirstElement = array[0];
- socket.setEnabledProtocols(array);
- array[0] = "Modified after having been set";
- assertEquals(originalFirstElement, socket.getEnabledProtocols()[0]);
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSessionContextTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSessionContextTest.java
deleted file mode 100644
index 72de22f1..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSessionContextTest.java
+++ /dev/null
@@ -1,337 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.security.Provider;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSocket;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SSLSessionContextTest extends AbstractSSLTest {
-
- @Test
- public void test_SSLSessionContext_getIds() {
- TestSSLContext c = TestSSLContext.create();
- assertSSLSessionContextSize(0, c);
- c.close();
-
- TestSSLSocketPair s = TestSSLSocketPair.create();
- assertSSLSessionContextSize(1, s.c);
- Enumeration<byte[]> clientIds = s.c.clientContext.getClientSessionContext().getIds();
- Enumeration<byte[]> serverIds = s.c.serverContext.getServerSessionContext().getIds();
- byte[] clientId = clientIds.nextElement();
- assertEquals(32, clientId.length);
- if (TestSSLContext.sslServerSocketSupportsSessionTickets()) {
- assertFalse(serverIds.hasMoreElements());
- } else {
- byte[] serverId = serverIds.nextElement();
- assertEquals(32, serverId.length);
- assertTrue(Arrays.equals(clientId, serverId));
- }
- s.close();
- }
-
- @Test
- public void test_SSLSessionContext_getSession() {
- TestSSLContext c = TestSSLContext.create();
- try {
- c.clientContext.getClientSessionContext().getSession(null);
- fail();
- } catch (NullPointerException expected) {
- // Ignored.
- }
- assertNull(c.clientContext.getClientSessionContext().getSession(new byte[0]));
- assertNull(c.clientContext.getClientSessionContext().getSession(new byte[1]));
- try {
- c.serverContext.getServerSessionContext().getSession(null);
- fail();
- } catch (NullPointerException expected) {
- // Ignored.
- }
- assertNull(c.serverContext.getServerSessionContext().getSession(new byte[0]));
- assertNull(c.serverContext.getServerSessionContext().getSession(new byte[1]));
- c.close();
-
- TestSSLSocketPair s = TestSSLSocketPair.create();
- SSLSessionContext client = s.c.clientContext.getClientSessionContext();
- SSLSessionContext server = s.c.serverContext.getServerSessionContext();
- byte[] clientId = client.getIds().nextElement();
- assertNotNull(client.getSession(clientId));
- assertTrue(Arrays.equals(clientId, client.getSession(clientId).getId()));
- if (TestSSLContext.sslServerSocketSupportsSessionTickets()) {
- assertFalse(server.getIds().hasMoreElements());
- } else {
- byte[] serverId = server.getIds().nextElement();
- assertNotNull(server.getSession(serverId));
- assertTrue(Arrays.equals(serverId, server.getSession(serverId).getId()));
- }
- s.close();
- }
-
- @Test
- public void test_SSLSessionContext_getSessionCacheSize() {
- TestSSLContext c = TestSSLContext.create();
- int expectedClientSessionCacheSize = expectedClientSslSessionCacheSize(c);
- int expectedServerSessionCacheSize = expectedServerSslSessionCacheSize(c);
- assertEquals(expectedClientSessionCacheSize,
- c.clientContext.getClientSessionContext().getSessionCacheSize());
- assertEquals(expectedServerSessionCacheSize,
- c.serverContext.getServerSessionContext().getSessionCacheSize());
- c.close();
-
- TestSSLSocketPair s = TestSSLSocketPair.create();
- assertEquals(expectedClientSessionCacheSize,
- s.c.clientContext.getClientSessionContext().getSessionCacheSize());
- assertEquals(expectedServerSessionCacheSize,
- s.c.serverContext.getServerSessionContext().getSessionCacheSize());
- s.close();
- }
-
- @Test
- public void test_SSLSessionContext_setSessionCacheSize_noConnect() {
- TestSSLContext c = TestSSLContext.create();
- int expectedClientSessionCacheSize = expectedClientSslSessionCacheSize(c);
- int expectedServerSessionCacheSize = expectedServerSslSessionCacheSize(c);
- assertNoConnectSetSessionCacheSizeBehavior(
- expectedClientSessionCacheSize,
- c.clientContext.getClientSessionContext());
- assertNoConnectSetSessionCacheSizeBehavior(
- expectedServerSessionCacheSize,
- c.serverContext.getServerSessionContext());
- c.close();
- }
-
- private static void assertNoConnectSetSessionCacheSizeBehavior(
- int expectedDefault, SSLSessionContext s) {
- try {
- s.setSessionCacheSize(-1);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- assertEquals(expectedDefault, s.getSessionCacheSize());
- s.setSessionCacheSize(1);
- assertEquals(1, s.getSessionCacheSize());
- }
-
- @Test
- public void test_SSLSessionContext_setSessionCacheSize_oneConnect() {
- TestSSLSocketPair s = TestSSLSocketPair.create();
- int expectedClientSessionCacheSize = expectedClientSslSessionCacheSize(s.c);
- int expectedServerSessionCacheSize = expectedServerSslSessionCacheSize(s.c);
- SSLSessionContext client = s.c.clientContext.getClientSessionContext();
- SSLSessionContext server = s.c.serverContext.getServerSessionContext();
- assertEquals(expectedClientSessionCacheSize,
- client.getSessionCacheSize());
- assertEquals(expectedServerSessionCacheSize,
- server.getSessionCacheSize());
- assertSSLSessionContextSize(1, s.c);
- s.close();
- }
-
- @Test
- public void test_SSLSessionContext_setSessionCacheSize_dynamic() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLSessionContext client = c.clientContext.getClientSessionContext();
- SSLSessionContext server = c.serverContext.getServerSessionContext();
-
- String[] supportedCipherSuites = c.serverSocket.getSupportedCipherSuites();
- c.serverSocket.setEnabledCipherSuites(supportedCipherSuites);
- LinkedList<String> uniqueCipherSuites =
- new LinkedList<>(Arrays.asList(supportedCipherSuites));
- // only use RSA cipher suites which will work with our TrustProvider
- Iterator<String> i = uniqueCipherSuites.iterator();
- while (i.hasNext()) {
- String cipherSuite = i.next();
-
- // Certificate key length too long for export ciphers
- if (cipherSuite.startsWith("SSL_RSA_EXPORT_")) {
- i.remove();
- continue;
- }
-
- if (cipherSuite.startsWith("SSL_RSA_")) {
- continue;
- }
- if (cipherSuite.startsWith("TLS_RSA_")) {
- continue;
- }
- if (cipherSuite.startsWith("TLS_DHE_RSA_")) {
- continue;
- }
- if (cipherSuite.startsWith("SSL_DHE_RSA_")) {
- continue;
- }
- i.remove();
- }
-
- /*
- * having more than 3 uniqueCipherSuites is a test
- * requirement, not a requirement of the interface or
- * implementation. It simply allows us to make sure that we
- * will not get a cached session ID since we'll have to
- * renegotiate a new session due to the new cipher suite
- * requirement. even this test only really needs three if it
- * reused the unique cipher suites every time it resets the
- * session cache.
- */
- assertTrue(uniqueCipherSuites.size() >= 3);
- String cipherSuite1 = uniqueCipherSuites.get(0);
- String cipherSuite2 = uniqueCipherSuites.get(1);
- String cipherSuite3 = uniqueCipherSuites.get(2);
-
- List<SSLSocket[]> toClose = new ArrayList<>();
- toClose.add(TestSSLSocketPair.connect(c, new String[] {cipherSuite1}, null));
- assertSSLSessionContextSize(1, c);
- toClose.add(TestSSLSocketPair.connect(c, new String[] {cipherSuite2}, null));
- assertSSLSessionContextSize(2, c);
- toClose.add(TestSSLSocketPair.connect(c, new String[] {cipherSuite3}, null));
- assertSSLSessionContextSize(3, c);
-
- client.setSessionCacheSize(1);
- server.setSessionCacheSize(1);
- assertEquals(1, client.getSessionCacheSize());
- assertEquals(1, server.getSessionCacheSize());
- assertSSLSessionContextSize(1, c);
- toClose.add(TestSSLSocketPair.connect(c, new String[] {cipherSuite1}, null));
- assertSSLSessionContextSize(1, c);
-
- client.setSessionCacheSize(2);
- server.setSessionCacheSize(2);
- toClose.add(TestSSLSocketPair.connect(c, new String[] {cipherSuite2}, null));
- assertSSLSessionContextSize(2, c);
- toClose.add(TestSSLSocketPair.connect(c, new String[] {cipherSuite3}, null));
- assertSSLSessionContextSize(2, c);
-
- for (SSLSocket[] pair : toClose) {
- for (SSLSocket s : pair) {
- s.close();
- }
- }
- c.close();
- }
-
- @Test
- public void test_SSLSessionContext_getSessionTimeout() {
- TestSSLContext c = TestSSLContext.create();
- int expectedCacheTimeout = expectedSslSessionCacheTimeout(c);
- assertEquals(expectedCacheTimeout,
- c.clientContext.getClientSessionContext().getSessionTimeout());
- assertEquals(expectedCacheTimeout,
- c.serverContext.getServerSessionContext().getSessionTimeout());
- c.close();
-
- TestSSLSocketPair s = TestSSLSocketPair.create();
- assertEquals(expectedCacheTimeout,
- s.c.clientContext.getClientSessionContext().getSessionTimeout());
- assertEquals(expectedCacheTimeout,
- s.c.serverContext.getServerSessionContext().getSessionTimeout());
- s.close();
- }
-
- @Test
- public void test_SSLSessionContext_setSessionTimeout() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- int expectedCacheTimeout = expectedSslSessionCacheTimeout(c);
- assertEquals(expectedCacheTimeout,
- c.clientContext.getClientSessionContext().getSessionTimeout());
- assertEquals(expectedCacheTimeout,
- c.serverContext.getServerSessionContext().getSessionTimeout());
- c.clientContext.getClientSessionContext().setSessionTimeout(0);
- c.serverContext.getServerSessionContext().setSessionTimeout(0);
- assertEquals(0, c.clientContext.getClientSessionContext().getSessionTimeout());
- assertEquals(0, c.serverContext.getServerSessionContext().getSessionTimeout());
-
- try {
- c.clientContext.getClientSessionContext().setSessionTimeout(-1);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- c.serverContext.getServerSessionContext().setSessionTimeout(-1);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- c.close();
-
- TestSSLSocketPair s = TestSSLSocketPair.create();
- assertSSLSessionContextSize(1, s.c);
- Thread.sleep(1000);
- s.c.clientContext.getClientSessionContext().setSessionTimeout(1);
- s.c.serverContext.getServerSessionContext().setSessionTimeout(1);
- assertSSLSessionContextSize(0, s.c);
- s.close();
- }
-
- private static void assertSSLSessionContextSize(int expected, TestSSLContext c) {
- assertSSLSessionContextSize(expected, c.clientContext.getClientSessionContext(),
- c.serverContext.getServerSessionContext());
- assertSSLSessionContextSize(0, c.serverContext.getClientSessionContext(),
- c.clientContext.getServerSessionContext());
- }
-
- private static void assertSSLSessionContextSize(
- int expected, SSLSessionContext client, SSLSessionContext server) {
- assertSSLSessionContextSize(expected, client, false);
- assertSSLSessionContextSize(expected, server, true);
- }
-
- private static void assertSSLSessionContextSize(
- int expected, SSLSessionContext s, boolean server) {
- int size = Collections.list(s.getIds()).size();
- if (server && TestSSLContext.sslServerSocketSupportsSessionTickets()) {
- assertEquals(0, size);
- } else {
- assertEquals(expected, size);
- }
- }
-
- private int expectedClientSslSessionCacheSize(TestSSLContext c) {
- return isConscrypt(c.clientContext.getProvider()) ? 10 : 0;
- }
-
- private int expectedServerSslSessionCacheSize(TestSSLContext c) {
- return isConscrypt(c.serverContext.getProvider()) ? 100 : 0;
- }
-
- private int expectedSslSessionCacheTimeout(TestSSLContext c) {
- return (isConscrypt(c.serverContext.getProvider())) ? 8 * 3600 : 24 * 3600;
- }
-
- private boolean isConscrypt(Provider provider) {
- return "AndroidOpenSSL".equals(provider.getName());
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java
deleted file mode 100644
index cf6b8416..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java
+++ /dev/null
@@ -1,346 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.util.Arrays;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import libcore.java.security.StandardNames;
-import libcore.java.security.TestKeyStore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SSLSessionTest extends AbstractSSLTest {
- @Test
- public void test_SSLSocket_TestSSLSessions_create() {
- TestSSLSessions s = TestSSLSessions.create();
- assertNotNull(s.invalid);
- assertFalse(s.invalid.isValid());
- assertTrue(s.server.isValid());
- assertTrue(s.client.isValid());
- s.close();
- }
-
- @Test
- public void test_SSLSession_getApplicationBufferSize() {
- TestSSLSessions s = TestSSLSessions.create();
- assertTrue(s.invalid.getApplicationBufferSize() > 0);
- assertTrue(s.server.getApplicationBufferSize() > 0);
- assertTrue(s.client.getApplicationBufferSize() > 0);
- s.close();
- }
-
- @Test
- public void test_SSLSession_getCipherSuite() {
- TestSSLSessions s = TestSSLSessions.create();
- assertNotNull(s.invalid.getCipherSuite());
- assertEquals(StandardNames.CIPHER_SUITE_INVALID, s.invalid.getCipherSuite());
- assertNotNull(s.server.getCipherSuite());
- assertNotNull(s.client.getCipherSuite());
- assertEquals(s.server.getCipherSuite(), s.client.getCipherSuite());
- StandardNames.assertValidCipherSuites(new String[] {s.server.getCipherSuite()});
- s.close();
- }
-
- @Test
- public void test_SSLSession_getCreationTime() {
- // We use OpenSSL, which only returns times accurate to the nearest second.
- // NativeCrypto just multiplies by 1000, which looks like truncation, which
- // would make it appear as if the OpenSSL side of things was created before
- // we called it.
- long t0 = System.currentTimeMillis() / 1000;
- TestSSLSessions s = TestSSLSessions.create();
- long t1 = System.currentTimeMillis() / 1000;
-
- assertTrue(s.invalid.getCreationTime() > 0);
-
- long sTime = s.server.getCreationTime() / 1000;
- assertTrue(sTime + " >= " + t0, sTime >= t0);
- assertTrue(sTime + " <= " + t1, sTime <= t1);
-
- long cTime = s.client.getCreationTime() / 1000;
- assertTrue(cTime + " >= " + t0, cTime >= t0);
- assertTrue(cTime + " <= " + t1, cTime <= t1);
-
- s.close();
- }
-
- @Test
- public void test_SSLSession_getId() {
- TestSSLSessions s = TestSSLSessions.create();
- assertNotNull(s.invalid.getId());
- assertNotNull(s.server.getId());
- assertNotNull(s.client.getId());
- assertEquals(0, s.invalid.getId().length);
- if (TestSSLContext.sslServerSocketSupportsSessionTickets()) {
- assertEquals(0, s.server.getId().length);
- } else {
- assertEquals(32, s.server.getId().length);
- assertTrue(Arrays.equals(s.server.getId(), s.client.getId()));
- }
- assertEquals(32, s.client.getId().length);
- s.close();
- }
-
- @Test
- public void test_SSLSession_getLastAccessedTime() {
- TestSSLSessions s = TestSSLSessions.create();
- assertTrue(s.invalid.getLastAccessedTime() > 0);
- assertTrue(s.server.getLastAccessedTime() > 0);
- assertTrue(s.client.getLastAccessedTime() > 0);
- assertTrue("s.server.getLastAccessedTime()=" + s.server.getLastAccessedTime() + " "
- + "s.client.getLastAccessedTime()=" + s.client.getLastAccessedTime(),
- Math.abs(s.server.getLastAccessedTime() - s.client.getLastAccessedTime())
- <= 1000);
- assertTrue(s.server.getLastAccessedTime() >= s.server.getCreationTime());
- assertTrue(s.client.getLastAccessedTime() >= s.client.getCreationTime());
- s.close();
- }
-
- @Test
- public void test_SSLSession_getLocalCertificates() throws Exception {
- TestSSLSessions s = TestSSLSessions.create();
- assertNull(s.invalid.getLocalCertificates());
- assertNull(s.client.getLocalCertificates());
- assertNotNull(s.server.getLocalCertificates());
- TestKeyStore.assertChainLength(s.server.getLocalCertificates());
- TestSSLContext.assertServerCertificateChain(
- s.s.c.serverTrustManager, s.server.getLocalCertificates());
- TestSSLContext.assertCertificateInKeyStore(
- s.server.getLocalCertificates()[0], s.s.c.serverKeyStore);
- s.close();
- }
-
- @Test
- public void test_SSLSession_getLocalPrincipal() throws Exception {
- TestSSLSessions s = TestSSLSessions.create();
- assertNull(s.invalid.getLocalPrincipal());
- assertNull(s.client.getLocalPrincipal());
- assertNotNull(s.server.getLocalPrincipal());
- assertNotNull(s.server.getLocalPrincipal().getName());
- TestSSLContext.assertCertificateInKeyStore(
- s.server.getLocalPrincipal(), s.s.c.serverKeyStore);
- s.close();
- }
-
- @Test
- public void test_SSLSession_getPacketBufferSize() {
- TestSSLSessions s = TestSSLSessions.create();
- assertTrue(s.invalid.getPacketBufferSize() > 0);
- assertTrue(s.server.getPacketBufferSize() > 0);
- assertTrue(s.client.getPacketBufferSize() > 0);
- s.close();
- }
-
- @Test
- public void test_SSLSession_getPeerCertificateChain() throws Exception {
- TestSSLSessions s = TestSSLSessions.create();
- try {
- s.invalid.getPeerCertificateChain();
- fail();
- } catch (SSLPeerUnverifiedException expected) {
- // Ignored.
- }
- assertNotNull(s.client.getPeerCertificates());
- TestKeyStore.assertChainLength(s.client.getPeerCertificateChain());
- try {
- assertNull(s.server.getPeerCertificateChain());
- fail();
- } catch (SSLPeerUnverifiedException expected) {
- // Ignored.
- }
- s.close();
- }
-
- @Test
- public void test_SSLSession_getPeerCertificates() throws Exception {
- TestSSLSessions s = TestSSLSessions.create();
- try {
- s.invalid.getPeerCertificates();
- fail();
- } catch (SSLPeerUnverifiedException expected) {
- // Ignored.
- }
- assertNotNull(s.client.getPeerCertificates());
- TestKeyStore.assertChainLength(s.client.getPeerCertificates());
- TestSSLContext.assertServerCertificateChain(
- s.s.c.serverTrustManager, s.client.getPeerCertificates());
- TestSSLContext.assertCertificateInKeyStore(
- s.client.getPeerCertificates()[0], s.s.c.serverKeyStore);
- try {
- s.server.getPeerCertificates();
- fail();
- } catch (SSLPeerUnverifiedException expected) {
- // Ignored.
- }
- s.close();
- }
-
- @Test
- public void test_SSLSession_getPeerHost() {
- TestSSLSessions s = TestSSLSessions.create();
- assertNull(s.invalid.getPeerHost());
- assertNotNull(s.server.getPeerHost());
- assertNotNull(s.client.getPeerHost());
- s.close();
- }
-
- @Test
- public void test_SSLSession_getPeerPort() {
- TestSSLSessions s = TestSSLSessions.create();
- assertEquals(-1, s.invalid.getPeerPort());
- assertTrue(s.server.getPeerPort() > 0);
- assertEquals(s.s.c.port, s.client.getPeerPort());
- s.close();
- }
-
- @Test
- public void test_SSLSession_getPeerPrincipal() throws Exception {
- TestSSLSessions s = TestSSLSessions.create();
- try {
- s.invalid.getPeerPrincipal();
- fail();
- } catch (SSLPeerUnverifiedException expected) {
- // Ignored.
- }
- try {
- s.server.getPeerPrincipal();
- fail();
- } catch (SSLPeerUnverifiedException expected) {
- // Ignored.
- }
- assertNotNull(s.client.getPeerPrincipal());
- assertNotNull(s.client.getPeerPrincipal().getName());
- TestSSLContext.assertCertificateInKeyStore(
- s.client.getPeerPrincipal(), s.s.c.serverKeyStore);
- s.close();
- }
-
- @Test
- public void test_SSLSession_getProtocol() {
- TestSSLSessions s = TestSSLSessions.create();
- assertNotNull(s.invalid.getProtocol());
- assertEquals("NONE", s.invalid.getProtocol());
- assertNotNull(s.server.getProtocol());
- assertNotNull(s.client.getProtocol());
- assertEquals(s.server.getProtocol(), s.client.getProtocol());
- assertTrue(StandardNames.SSL_SOCKET_PROTOCOLS.contains(s.server.getProtocol()));
- s.close();
- }
-
- @Test
- public void test_SSLSession_getSessionContext() {
- TestSSLSessions s = TestSSLSessions.create();
- assertNull(s.invalid.getSessionContext());
- assertNotNull(s.server.getSessionContext());
- assertNotNull(s.client.getSessionContext());
- assertEquals(s.s.c.serverContext.getServerSessionContext(), s.server.getSessionContext());
- assertEquals(s.s.c.clientContext.getClientSessionContext(), s.client.getSessionContext());
- assertNotSame(s.server.getSessionContext(), s.client.getSessionContext());
- s.close();
- }
-
- @Test
- public void test_SSLSession_getValue() {
- TestSSLSessions s = TestSSLSessions.create();
- try {
- s.invalid.getValue(null);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- assertNull(s.invalid.getValue("BOGUS"));
- s.close();
- }
-
- @Test
- public void test_SSLSession_getValueNames() {
- TestSSLSessions s = TestSSLSessions.create();
- assertNotNull(s.invalid.getValueNames());
- assertEquals(0, s.invalid.getValueNames().length);
- s.close();
- }
-
- @Test
- public void test_SSLSession_invalidate() {
- TestSSLSessions s = TestSSLSessions.create();
-
- assertFalse(s.invalid.isValid());
- s.invalid.invalidate();
- assertFalse(s.invalid.isValid());
- assertNull(s.invalid.getSessionContext());
-
- assertTrue(s.server.isValid());
- s.server.invalidate();
- assertFalse(s.server.isValid());
- assertNull(s.server.getSessionContext());
-
- assertTrue(s.client.isValid());
- s.client.invalidate();
- assertFalse(s.client.isValid());
- assertNull(s.client.getSessionContext());
-
- s.close();
- }
-
- @Test
- public void test_SSLSession_isValid() {
- TestSSLSessions s = TestSSLSessions.create();
- assertFalse(s.invalid.isValid());
- assertTrue(s.server.isValid());
- assertTrue(s.client.isValid());
- s.close();
- }
-
- @Test
- public void test_SSLSession_putValue() {
- TestSSLSessions s = TestSSLSessions.create();
- String key = "KEY";
- String value = "VALUE";
- assertNull(s.invalid.getValue(key));
- assertEquals(0, s.invalid.getValueNames().length);
- s.invalid.putValue(key, value);
- assertSame(value, s.invalid.getValue(key));
- assertEquals(1, s.invalid.getValueNames().length);
- assertEquals(key, s.invalid.getValueNames()[0]);
- s.close();
- }
-
- @Test
- public void test_SSLSession_removeValue() {
- TestSSLSessions s = TestSSLSessions.create();
- String key = "KEY";
- String value = "VALUE";
- s.invalid.putValue(key, value);
- assertEquals(1, s.invalid.getValueNames().length);
- assertEquals(key, s.invalid.getValueNames()[0]);
- s.invalid.removeValue(key);
- assertNull(s.invalid.getValue(key));
- assertEquals(0, s.invalid.getValueNames().length);
- s.close();
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java
deleted file mode 100644
index 8147579f..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSocketFactoryTest.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketException;
-import javax.net.ServerSocketFactory;
-import javax.net.SocketFactory;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class SSLSocketFactoryTest extends AbstractSSLTest {
-
- @Test
- public void test_SSLSocketFactory_getDefault() {
- SocketFactory sf = SSLSocketFactory.getDefault();
- assertNotNull(sf);
- assertTrue(SSLSocketFactory.class.isAssignableFrom(sf.getClass()));
- }
-
- @Test
- public void test_SSLSocketFactory_defaultConfiguration() throws Exception {
- SSLConfigurationAsserts.assertSSLSocketFactoryDefaultConfiguration(
- (SSLSocketFactory) SSLSocketFactory.getDefault());
- }
-
- @Test
- public void test_SSLSocketFactory_getDefaultCipherSuitesReturnsCopies() {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- assertNotSame(sf.getDefaultCipherSuites(), sf.getDefaultCipherSuites());
- }
-
- @Test
- public void test_SSLSocketFactory_getSupportedCipherSuitesReturnsCopies() {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- assertNotSame(sf.getSupportedCipherSuites(), sf.getSupportedCipherSuites());
- }
-
- @Test
- public void test_SSLSocketFactory_createSocket() throws Exception {
- try {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- sf.createSocket(null, null, -1, false);
- fail();
- } catch (NullPointerException expected) {
- // Ignored.
- }
-
- try {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- sf.createSocket(new Socket(), null, -1, false);
- fail();
- } catch (SocketException expected) {
- // Ignored.
- }
-
- ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(0);
- InetSocketAddress sa = (InetSocketAddress) ss.getLocalSocketAddress();
- InetAddress host = sa.getAddress();
- int port = sa.getPort();
- Socket s = new Socket(host, port);
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- Socket ssl = sf.createSocket(s, null, -1, false);
- assertNotNull(ssl);
- assertTrue(SSLSocket.class.isAssignableFrom(ssl.getClass()));
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
deleted file mode 100644
index e0c36568..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
+++ /dev/null
@@ -1,2261 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeNotNull;
-import static org.junit.Assume.assumeTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.Closeable;
-import java.io.DataInputStream;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.Thread.UncaughtExceptionHandler;
-import java.lang.reflect.Method;
-import java.math.BigInteger;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketException;
-import java.net.SocketTimeoutException;
-import java.security.AlgorithmParameters;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.InvalidKeyException;
-import java.security.InvalidParameterException;
-import java.security.Key;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.Provider;
-import java.security.PublicKey;
-import java.security.SecureRandom;
-import java.security.Security;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.SignatureSpi;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.ECKey;
-import java.security.interfaces.ECPrivateKey;
-import java.security.interfaces.RSAKey;
-import java.security.interfaces.RSAPrivateKey;
-import java.security.spec.AlgorithmParameterSpec;
-import java.security.spec.ECParameterSpec;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.CipherSpi;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.SecretKey;
-import javax.crypto.ShortBufferException;
-import javax.crypto.spec.SecretKeySpec;
-import javax.net.ServerSocketFactory;
-import javax.net.SocketFactory;
-import javax.net.ssl.ExtendedSSLSession;
-import javax.net.ssl.HandshakeCompletedListener;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SNIHostName;
-import javax.net.ssl.SNIServerName;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLParameters;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLProtocolException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.StandardConstants;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509KeyManager;
-import javax.net.ssl.X509TrustManager;
-import libcore.java.security.StandardNames;
-import libcore.java.security.TestKeyStore;
-import libcore.tlswire.handshake.CipherSuite;
-import libcore.tlswire.handshake.ClientHello;
-import libcore.tlswire.handshake.CompressionMethod;
-import libcore.tlswire.handshake.EllipticCurve;
-import libcore.tlswire.handshake.EllipticCurvesHelloExtension;
-import libcore.tlswire.handshake.HandshakeMessage;
-import libcore.tlswire.handshake.HelloExtension;
-import libcore.tlswire.handshake.ServerNameHelloExtension;
-import libcore.tlswire.record.TlsProtocols;
-import libcore.tlswire.record.TlsRecord;
-import libcore.tlswire.util.TlsProtocolVersion;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-import tests.net.DelegatingSSLSocketFactory;
-import tests.util.ForEachRunner;
-import tests.util.Pair;
-
-@RunWith(JUnit4.class)
-public class SSLSocketTest extends AbstractSSLTest {
- private ExecutorService executor;
- private ThreadGroup threadGroup;
-
- @Before
- public void setup() {
- threadGroup = new ThreadGroup("SSLSocketTest");
- executor = Executors.newCachedThreadPool(r -> new Thread(threadGroup, r));
- }
-
- @After
- public void teardown() throws InterruptedException {
- executor.shutdownNow();
- executor.awaitTermination(5, TimeUnit.SECONDS);
- }
-
- @Test
- public void test_SSLSocket_defaultConfiguration() throws Exception {
- SSLConfigurationAsserts.assertSSLSocketDefaultConfiguration(
- (SSLSocket) SSLSocketFactory.getDefault().createSocket());
- }
- @Test
- public void test_SSLSocket_getSupportedCipherSuites_returnsCopies() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- assertNotSame(ssl.getSupportedCipherSuites(), ssl.getSupportedCipherSuites());
- }
- @Test
- public void test_SSLSocket_getSupportedCipherSuites_connect() throws Exception {
- // note the rare usage of non-RSA keys
- TestKeyStore testKeyStore = new TestKeyStore.Builder()
- .keyAlgorithms("RSA", "DSA", "EC", "EC_RSA")
- .aliasPrefix("rsa-dsa-ec")
- .ca(true)
- .build();
- StringBuilder error = new StringBuilder();
- test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore, error);
- if (error.length() > 0) {
- throw new Exception("One or more problems in "
- + "test_SSLSocket_getSupportedCipherSuites_connect:\n" + error);
- }
- }
- private void test_SSLSocket_getSupportedCipherSuites_connect(
- TestKeyStore testKeyStore, StringBuilder error) throws Exception {
- String clientToServerString = "this is sent from the client to the server...";
- String serverToClientString = "... and this from the server to the client";
- byte[] clientToServer = clientToServerString.getBytes(UTF_8);
- byte[] serverToClient = serverToClientString.getBytes(UTF_8);
- KeyManager pskKeyManager =
- PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy() {
- @Override
- protected SecretKey getKey(
- String identityHint, String identity, Socket socket) {
- return new SecretKeySpec("Just an arbitrary key".getBytes(UTF_8), "RAW");
- }
- });
- TestSSLContext c = TestSSLContext.newBuilder()
- .client(testKeyStore)
- .server(testKeyStore)
- .additionalClientKeyManagers(new KeyManager[] {pskKeyManager})
- .additionalServerKeyManagers(new KeyManager[] {pskKeyManager})
- .build();
- String[] cipherSuites = c.clientContext.getSocketFactory().getSupportedCipherSuites();
- for (String cipherSuite : cipherSuites) {
- try {
- /*
- * TLS_EMPTY_RENEGOTIATION_INFO_SCSV cannot be used on
- * its own, but instead in conjunction with other
- * cipher suites.
- */
- if (cipherSuite.equals(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION)) {
- continue;
- }
- /*
- * Similarly with the TLS_FALLBACK_SCSV suite, it is not
- * a selectable suite, but is used in conjunction with
- * other cipher suites.
- */
- if (cipherSuite.equals(StandardNames.CIPHER_SUITE_FALLBACK)) {
- continue;
- }
- /*
- * Kerberos cipher suites require external setup. See "Kerberos Requirements" in
- * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html
- * #KRBRequire
- */
- if (cipherSuite.startsWith("TLS_KRB5_")) {
- continue;
- }
- String[] clientCipherSuiteArray =
- new String[] {cipherSuite, StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION};
- SSLSocket[] pair = TestSSLSocketPair.connect(
- c, clientCipherSuiteArray, clientCipherSuiteArray);
- SSLSocket server = pair[0];
- SSLSocket client = pair[1];
- // Check that the client can read the message sent by the server
- server.getOutputStream().write(serverToClient);
- byte[] clientFromServer = new byte[serverToClient.length];
- readFully(client.getInputStream(), clientFromServer);
- assertEquals(serverToClientString, new String(clientFromServer, UTF_8));
- // Check that the server can read the message sent by the client
- client.getOutputStream().write(clientToServer);
- byte[] serverFromClient = new byte[clientToServer.length];
- readFully(server.getInputStream(), serverFromClient);
- assertEquals(clientToServerString, new String(serverFromClient, UTF_8));
- // Check that the server and the client cannot read anything else
- // (reads should time out)
- server.setSoTimeout(10);
- try {
- @SuppressWarnings("unused")
- int value = server.getInputStream().read();
- fail();
- } catch (IOException expected) {
- // Ignored.
- }
- client.setSoTimeout(10);
- try {
- @SuppressWarnings("unused")
- int value = client.getInputStream().read();
- fail();
- } catch (IOException expected) {
- // Ignored.
- }
- client.close();
- server.close();
- } catch (Exception maybeExpected) {
- String message = ("Problem trying to connect cipher suite " + cipherSuite);
- System.out.println(message);
- maybeExpected.printStackTrace();
- error.append(message);
- error.append('\n');
- }
- }
- c.close();
- }
- @Test
- public void test_SSLSocket_getEnabledCipherSuites_returnsCopies() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- assertNotSame(ssl.getEnabledCipherSuites(), ssl.getEnabledCipherSuites());
- }
- @Test
- public void test_SSLSocket_setEnabledCipherSuites_storesCopy() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- String[] array = new String[] {ssl.getEnabledCipherSuites()[0]};
- String originalFirstElement = array[0];
- ssl.setEnabledCipherSuites(array);
- array[0] = "Modified after having been set";
- assertEquals(originalFirstElement, ssl.getEnabledCipherSuites()[0]);
- }
- @Test
- public void test_SSLSocket_setEnabledCipherSuites() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- try {
- ssl.setEnabledCipherSuites(null);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- ssl.setEnabledCipherSuites(new String[1]);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- ssl.setEnabledCipherSuites(new String[] {"Bogus"});
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- ssl.setEnabledCipherSuites(new String[0]);
- ssl.setEnabledCipherSuites(ssl.getEnabledCipherSuites());
- ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
- // Check that setEnabledCipherSuites affects getEnabledCipherSuites
- String[] cipherSuites = new String[] {ssl.getSupportedCipherSuites()[0]};
- ssl.setEnabledCipherSuites(cipherSuites);
- assertEquals(Arrays.asList(cipherSuites), Arrays.asList(ssl.getEnabledCipherSuites()));
- }
- @Test
- public void test_SSLSocket_getSupportedProtocols_returnsCopies() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- assertNotSame(ssl.getSupportedProtocols(), ssl.getSupportedProtocols());
- }
- @Test
- public void test_SSLSocket_getEnabledProtocols_returnsCopies() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- assertNotSame(ssl.getEnabledProtocols(), ssl.getEnabledProtocols());
- }
- @Test
- public void test_SSLSocket_setEnabledProtocols_storesCopy() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- String[] array = new String[] {ssl.getEnabledProtocols()[0]};
- String originalFirstElement = array[0];
- ssl.setEnabledProtocols(array);
- array[0] = "Modified after having been set";
- assertEquals(originalFirstElement, ssl.getEnabledProtocols()[0]);
- }
- @Test
- public void test_SSLSocket_setEnabledProtocols() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- try {
- ssl.setEnabledProtocols(null);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- ssl.setEnabledProtocols(new String[1]);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- ssl.setEnabledProtocols(new String[] {"Bogus"});
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- ssl.setEnabledProtocols(new String[0]);
- ssl.setEnabledProtocols(ssl.getEnabledProtocols());
- ssl.setEnabledProtocols(ssl.getSupportedProtocols());
- // Check that setEnabledProtocols affects getEnabledProtocols
- for (String protocol : ssl.getSupportedProtocols()) {
- if ("SSLv2Hello".equals(protocol)) {
- try {
- ssl.setEnabledProtocols(new String[] {protocol});
- fail("Should fail when SSLv2Hello is set by itself");
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- } else {
- String[] protocols = new String[] {protocol};
- ssl.setEnabledProtocols(protocols);
- assertEquals(Arrays.deepToString(protocols),
- Arrays.deepToString(ssl.getEnabledProtocols()));
- }
- }
- }
- @Test
- public void test_SSLSocket_getSession() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- SSLSession session = ssl.getSession();
- assertNotNull(session);
- assertFalse(session.isValid());
- }
- @Test
- public void test_SSLSocket_getHandshakeSession() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- SSLSession session = ssl.getHandshakeSession();
- assertNull(session);
- }
- @Test
- public void test_SSLSocket_startHandshake() throws Exception {
- final TestSSLContext c = TestSSLContext.create();
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- server.startHandshake();
- assertNotNull(server.getSession());
- assertNull(server.getHandshakeSession());
- try {
- server.getSession().getPeerCertificates();
- fail();
- } catch (SSLPeerUnverifiedException expected) {
- // Ignored.
- }
- Certificate[] localCertificates = server.getSession().getLocalCertificates();
- assertNotNull(localCertificates);
- TestKeyStore.assertChainLength(localCertificates);
- assertNotNull(localCertificates[0]);
- TestSSLContext.assertServerCertificateChain(
- c.serverTrustManager, localCertificates);
- TestSSLContext.assertCertificateInKeyStore(localCertificates[0], c.serverKeyStore);
- return null;
- });
- client.startHandshake();
- assertNotNull(client.getSession());
- assertNull(client.getSession().getLocalCertificates());
- Certificate[] peerCertificates = client.getSession().getPeerCertificates();
- assertNotNull(peerCertificates);
- TestKeyStore.assertChainLength(peerCertificates);
- assertNotNull(peerCertificates[0]);
- TestSSLContext.assertServerCertificateChain(c.clientTrustManager, peerCertificates);
- TestSSLContext.assertCertificateInKeyStore(peerCertificates[0], c.serverKeyStore);
- future.get();
- client.close();
- server.close();
- c.close();
- }
- private static final class SSLServerSessionIdCallable implements Callable<byte[]> {
- private final SSLSocket server;
- private SSLServerSessionIdCallable(SSLSocket server) {
- this.server = server;
- }
- @Override
- public byte[] call() throws Exception {
- server.startHandshake();
- assertNotNull(server.getSession());
- assertNotNull(server.getSession().getId());
- return server.getSession().getId();
- }
- }
- @Test
- public void test_SSLSocket_confirmSessionReuse() throws Exception {
- final TestSSLContext c = TestSSLContext.create();
- final SSLSocket client1 = (SSLSocket) c.clientContext.getSocketFactory().createSocket(
- c.host.getHostName(), c.port);
- final SSLSocket server1 = (SSLSocket) c.serverSocket.accept();
- final Future<byte[]> future1 = runAsync(new SSLServerSessionIdCallable(server1));
- client1.startHandshake();
- assertNotNull(client1.getSession());
- assertNotNull(client1.getSession().getId());
- final byte[] clientSessionId1 = client1.getSession().getId();
- final byte[] serverSessionId1 = future1.get();
- assertTrue(Arrays.equals(clientSessionId1, serverSessionId1));
- client1.close();
- server1.close();
- final SSLSocket client2 = (SSLSocket) c.clientContext.getSocketFactory().createSocket(
- c.host.getHostName(), c.port);
- final SSLSocket server2 = (SSLSocket) c.serverSocket.accept();
- final Future<byte[]> future2 = runAsync(new SSLServerSessionIdCallable(server2));
- client2.startHandshake();
- assertNotNull(client2.getSession());
- assertNotNull(client2.getSession().getId());
- final byte[] clientSessionId2 = client2.getSession().getId();
- final byte[] serverSessionId2 = future2.get();
- assertTrue(Arrays.equals(clientSessionId2, serverSessionId2));
- client2.close();
- server2.close();
- assertTrue(Arrays.equals(clientSessionId1, clientSessionId2));
- c.close();
- }
- @Test
- public void test_SSLSocket_NoEnabledCipherSuites_Failure() throws Exception {
- TestSSLContext c = TestSSLContext.newBuilder()
- .useDefaults(false)
- .clientContext(SSLContext.getDefault())
- .serverContext(SSLContext.getDefault())
- .build();
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- client.setEnabledCipherSuites(new String[0]);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- try {
- server.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- }
- return null;
- });
- try {
- client.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- }
- future.get();
- server.close();
- client.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_startHandshake_noKeyStore() throws Exception {
- TestSSLContext c = TestSSLContext.newBuilder()
- .useDefaults(false)
- .clientContext(SSLContext.getDefault())
- .serverContext(SSLContext.getDefault())
- .build();
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- try {
- server.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- }
- return null;
- });
- try {
- client.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- }
- future.get();
- server.close();
- client.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_startHandshake_noClientCertificate() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLContext clientContext = c.clientContext;
- SSLSocket client =
- (SSLSocket) clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- server.startHandshake();
- return null;
- });
- client.startHandshake();
- future.get();
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_HandshakeCompletedListener() throws Exception {
- final TestSSLContext c = TestSSLContext.create();
- final SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- server.startHandshake();
- return null;
- });
- final boolean[] handshakeCompletedListenerCalled = new boolean[1];
- client.addHandshakeCompletedListener(event -> {
- try {
- SSLSession session = event.getSession();
- String cipherSuite = event.getCipherSuite();
- Certificate[] localCertificates = event.getLocalCertificates();
- Certificate[] peerCertificates = event.getPeerCertificates();
- javax.security.cert.X509Certificate[] peerCertificateChain =
- event.getPeerCertificateChain();
- Principal peerPrincipal = event.getPeerPrincipal();
- Principal localPrincipal = event.getLocalPrincipal();
- Socket socket = event.getSocket();
- assertNotNull(session);
- byte[] id = session.getId();
- assertNotNull(id);
- assertEquals(32, id.length);
- assertNotNull(c.clientContext.getClientSessionContext().getSession(id));
- assertNotNull(cipherSuite);
- assertTrue(
- Arrays.asList(client.getEnabledCipherSuites()).contains(cipherSuite));
- assertTrue(Arrays.asList(c.serverSocket.getEnabledCipherSuites())
- .contains(cipherSuite));
- assertNull(localCertificates);
- assertNotNull(peerCertificates);
- TestKeyStore.assertChainLength(peerCertificates);
- assertNotNull(peerCertificates[0]);
- TestSSLContext.assertServerCertificateChain(
- c.clientTrustManager, peerCertificates);
- TestSSLContext.assertCertificateInKeyStore(
- peerCertificates[0], c.serverKeyStore);
- assertNotNull(peerCertificateChain);
- TestKeyStore.assertChainLength(peerCertificateChain);
- assertNotNull(peerCertificateChain[0]);
- TestSSLContext.assertCertificateInKeyStore(
- peerCertificateChain[0].getSubjectDN(), c.serverKeyStore);
- assertNotNull(peerPrincipal);
- TestSSLContext.assertCertificateInKeyStore(peerPrincipal, c.serverKeyStore);
- assertNull(localPrincipal);
- assertNotNull(socket);
- assertSame(client, socket);
- assertNull(((SSLSocket) socket).getHandshakeSession());
- synchronized (handshakeCompletedListenerCalled) {
- handshakeCompletedListenerCalled[0] = true;
- handshakeCompletedListenerCalled.notify();
- }
- handshakeCompletedListenerCalled[0] = true;
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- });
- client.startHandshake();
- future.get();
- assertNotNull(c.serverContext.getServerSessionContext().getSession(
- client.getSession().getId()));
- synchronized (handshakeCompletedListenerCalled) {
- while (!handshakeCompletedListenerCalled[0]) {
- handshakeCompletedListenerCalled.wait();
- }
- }
- client.close();
- server.close();
- c.close();
- }
- private static final class TestUncaughtExceptionHandler implements UncaughtExceptionHandler {
- Throwable actualException;
- @Override
- public void uncaughtException(Thread thread, Throwable ex) {
- assertNull(actualException);
- actualException = ex;
- }
- }
- @Test
- public void test_SSLSocket_HandshakeCompletedListener_RuntimeException() throws Exception {
- final Thread self = Thread.currentThread();
- final UncaughtExceptionHandler original = self.getUncaughtExceptionHandler();
- final RuntimeException expectedException = new RuntimeException("expected");
- final TestUncaughtExceptionHandler test = new TestUncaughtExceptionHandler();
- self.setUncaughtExceptionHandler(test);
- final TestSSLContext c = TestSSLContext.create();
- final SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- server.startHandshake();
- return null;
- });
- client.addHandshakeCompletedListener(event -> {
- throw expectedException;
- });
- client.startHandshake();
- future.get();
- client.close();
- server.close();
- c.close();
- assertSame(expectedException, test.actualException);
- self.setUncaughtExceptionHandler(original);
- }
- @Test
- public void test_SSLSocket_getUseClientMode() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- SSLSocket server = (SSLSocket) c.serverSocket.accept();
- assertTrue(client.getUseClientMode());
- assertFalse(server.getUseClientMode());
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_setUseClientMode() throws Exception {
- // client is client, server is server
- test_SSLSocket_setUseClientMode(true, false);
- // client is server, server is client
- test_SSLSocket_setUseClientMode(true, false);
- // both are client
- try {
- test_SSLSocket_setUseClientMode(true, true);
- fail();
- } catch (SSLProtocolException | SSLHandshakeException expected) {
- // Ignored.
- }
- // both are server
- try {
- test_SSLSocket_setUseClientMode(false, false);
- fail();
- } catch (SocketTimeoutException expected) {
- // Ignored.
- }
- }
- private void test_SSLSocket_setUseClientMode(
- final boolean clientClientMode, final boolean serverClientMode) throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<IOException> future = runAsync(() -> {
- try {
- if (!serverClientMode) {
- server.setSoTimeout(1000);
- }
- server.setUseClientMode(serverClientMode);
- server.startHandshake();
- return null;
- } catch (SSLHandshakeException | SocketTimeoutException e) {
- return e;
- }
- });
- if (!clientClientMode) {
- client.setSoTimeout(1000);
- }
- client.setUseClientMode(clientClientMode);
- client.startHandshake();
- IOException ioe = future.get();
- if (ioe != null) {
- throw ioe;
- }
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_setUseClientMode_afterHandshake() throws Exception {
- // can't set after handshake
- TestSSLSocketPair pair = TestSSLSocketPair.create();
- try {
- pair.server.setUseClientMode(false);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- try {
- pair.client.setUseClientMode(false);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- }
- @Test
- public void test_SSLSocket_untrustedServer() throws Exception {
- TestSSLContext c =
- TestSSLContext.create(TestKeyStore.getClientCA2(), TestKeyStore.getServer());
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- try {
- server.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- }
- return null;
- });
- try {
- client.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- assertTrue(expected.getCause() instanceof CertificateException);
- }
- future.get();
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_clientAuth() throws Exception {
- TestSSLContext c = TestSSLContext.create(
- TestKeyStore.getClientCertificate(), TestKeyStore.getServer());
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- assertFalse(server.getWantClientAuth());
- assertFalse(server.getNeedClientAuth());
- // confirm turning one on by itself
- server.setWantClientAuth(true);
- assertTrue(server.getWantClientAuth());
- assertFalse(server.getNeedClientAuth());
- // confirm turning setting on toggles the other
- server.setNeedClientAuth(true);
- assertFalse(server.getWantClientAuth());
- assertTrue(server.getNeedClientAuth());
- // confirm toggling back
- server.setWantClientAuth(true);
- assertTrue(server.getWantClientAuth());
- assertFalse(server.getNeedClientAuth());
- server.startHandshake();
- return null;
- });
- client.startHandshake();
- assertNotNull(client.getSession().getLocalCertificates());
- TestKeyStore.assertChainLength(client.getSession().getLocalCertificates());
- TestSSLContext.assertClientCertificateChain(
- c.clientTrustManager, client.getSession().getLocalCertificates());
- future.get();
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_clientAuth_bogusAlias() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLContext clientContext = SSLContext.getInstance("TLS");
- X509KeyManager keyManager = new X509KeyManager() {
- @Override
- public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
- return "bogus";
- }
- @Override
- public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
- throw new AssertionError();
- }
- @Override
- public X509Certificate[] getCertificateChain(String alias) {
- // return null for "bogus" alias
- return null;
- }
- @Override
- public String[] getClientAliases(String keyType, Principal[] issuers) {
- throw new AssertionError();
- }
- @Override
- public String[] getServerAliases(String keyType, Principal[] issuers) {
- throw new AssertionError();
- }
- @Override
- public PrivateKey getPrivateKey(String alias) {
- // return null for "bogus" alias
- return null;
- }
- };
- clientContext.init(
- new KeyManager[] {keyManager}, new TrustManager[] {c.clientTrustManager}, null);
- SSLSocket client =
- (SSLSocket) clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- try {
- server.setNeedClientAuth(true);
- server.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- }
- return null;
- });
- try {
- client.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // before we would get a NullPointerException from passing
- // due to the null PrivateKey return by the X509KeyManager.
- }
- future.get();
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_clientAuth_OpaqueKey_RSA() throws Exception {
- run_SSLSocket_clientAuth_OpaqueKey(TestKeyStore.getClientCertificate());
- }
- @Test
- public void test_SSLSocket_clientAuth_OpaqueKey_EC_RSA() throws Exception {
- run_SSLSocket_clientAuth_OpaqueKey(TestKeyStore.getClientEcRsaCertificate());
- }
- @Test
- public void test_SSLSocket_clientAuth_OpaqueKey_EC_EC() throws Exception {
- run_SSLSocket_clientAuth_OpaqueKey(TestKeyStore.getClientEcEcCertificate());
- }
- private void run_SSLSocket_clientAuth_OpaqueKey(TestKeyStore keyStore) throws Exception {
- try {
- Security.insertProviderAt(new OpaqueProvider(), 1);
- final TestSSLContext c = TestSSLContext.create(keyStore, TestKeyStore.getServer());
- SSLContext clientContext = SSLContext.getInstance("TLS");
- final X509KeyManager delegateKeyManager = (X509KeyManager) c.clientKeyManagers[0];
- X509KeyManager keyManager = new X509KeyManager() {
- @Override
- public String chooseClientAlias(
- String[] keyType, Principal[] issuers, Socket socket) {
- return delegateKeyManager.chooseClientAlias(keyType, issuers, socket);
- }
- @Override
- public String chooseServerAlias(
- String keyType, Principal[] issuers, Socket socket) {
- return delegateKeyManager.chooseServerAlias(keyType, issuers, socket);
- }
- @Override
- public X509Certificate[] getCertificateChain(String alias) {
- return delegateKeyManager.getCertificateChain(alias);
- }
- @Override
- public String[] getClientAliases(String keyType, Principal[] issuers) {
- return delegateKeyManager.getClientAliases(keyType, issuers);
- }
- @Override
- public String[] getServerAliases(String keyType, Principal[] issuers) {
- return delegateKeyManager.getServerAliases(keyType, issuers);
- }
- @Override
- public PrivateKey getPrivateKey(String alias) {
- PrivateKey privKey = delegateKeyManager.getPrivateKey(alias);
- if (privKey instanceof RSAPrivateKey) {
- return new OpaqueDelegatingRSAPrivateKey((RSAPrivateKey) privKey);
- } else if (privKey instanceof ECPrivateKey) {
- return new OpaqueDelegatingECPrivateKey((ECPrivateKey) privKey);
- } else {
- return null;
- }
- }
- };
- clientContext.init(
- new KeyManager[] {keyManager}, new TrustManager[] {c.clientTrustManager}, null);
- SSLSocket client =
- (SSLSocket) clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- server.setNeedClientAuth(true);
- server.startHandshake();
- return null;
- });
- client.startHandshake();
- assertNotNull(client.getSession().getLocalCertificates());
- TestKeyStore.assertChainLength(client.getSession().getLocalCertificates());
- TestSSLContext.assertClientCertificateChain(
- c.clientTrustManager, client.getSession().getLocalCertificates());
- future.get();
- client.close();
- server.close();
- c.close();
- } finally {
- Security.removeProvider(OpaqueProvider.NAME);
- }
- }
- @SuppressWarnings("serial")
- public static class OpaqueProvider extends Provider {
- static final String NAME = "OpaqueProvider";
- public OpaqueProvider() {
- super(NAME, 1.0, "test provider");
- put("Signature.NONEwithRSA", OpaqueSignatureSpi.RSA.class.getName());
- put("Signature.NONEwithECDSA", OpaqueSignatureSpi.ECDSA.class.getName());
- put("Cipher.RSA/ECB/NoPadding", OpaqueCipherSpi.class.getName());
- }
- }
- protected static class OpaqueSignatureSpi extends SignatureSpi {
- private final String algorithm;
- private Signature delegate;
- OpaqueSignatureSpi(String algorithm) {
- this.algorithm = algorithm;
- }
- public final static class RSA extends OpaqueSignatureSpi {
- public RSA() {
- super("NONEwithRSA");
- }
- }
- public final static class ECDSA extends OpaqueSignatureSpi {
- public ECDSA() {
- super("NONEwithECDSA");
- }
- }
- @Override
- protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
- fail("Cannot verify");
- }
- @Override
- protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
- DelegatingPrivateKey opaqueKey = (DelegatingPrivateKey) privateKey;
- try {
- delegate = Signature.getInstance(algorithm);
- } catch (NoSuchAlgorithmException e) {
- throw new InvalidKeyException(e);
- }
- delegate.initSign(opaqueKey.getDelegate());
- }
- @Override
- protected void engineUpdate(byte b) throws SignatureException {
- delegate.update(b);
- }
- @Override
- protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
- delegate.update(b, off, len);
- }
- @Override
- protected byte[] engineSign() throws SignatureException {
- return delegate.sign();
- }
- @Override
- protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
- return delegate.verify(sigBytes);
- }
- @SuppressWarnings("deprecation")
- @Override
- protected void engineSetParameter(String param, Object value)
- throws InvalidParameterException {
- delegate.setParameter(param, value);
- }
- @SuppressWarnings("deprecation")
- @Override
- protected Object engineGetParameter(String param) throws InvalidParameterException {
- return delegate.getParameter(param);
- }
- }
- public static class OpaqueCipherSpi extends CipherSpi {
- private Cipher delegate;
- public OpaqueCipherSpi() {}
- @Override
- protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
- fail();
- }
- @Override
- protected void engineSetPadding(String padding) throws NoSuchPaddingException {
- fail();
- }
- @Override
- protected int engineGetBlockSize() {
- return delegate.getBlockSize();
- }
- @Override
- protected int engineGetOutputSize(int inputLen) {
- return delegate.getOutputSize(inputLen);
- }
- @Override
- protected byte[] engineGetIV() {
- return delegate.getIV();
- }
- @Override
- protected AlgorithmParameters engineGetParameters() {
- return delegate.getParameters();
- }
- @Override
- protected void engineInit(int opmode, Key key, SecureRandom random)
- throws InvalidKeyException {
- getCipher();
- delegate.init(opmode, key, random);
- }
- void getCipher() throws InvalidKeyException {
- try {
- delegate = Cipher.getInstance("RSA/ECB/NoPadding");
- } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
- throw new InvalidKeyException(e);
- }
- }
- @Override
- protected void engineInit(
- int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random)
- throws InvalidKeyException, InvalidAlgorithmParameterException {
- getCipher();
- delegate.init(opmode, key, params, random);
- }
- @Override
- protected void engineInit(
- int opmode, Key key, AlgorithmParameters params, SecureRandom random)
- throws InvalidKeyException, InvalidAlgorithmParameterException {
- getCipher();
- delegate.init(opmode, key, params, random);
- }
- @Override
- protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) {
- return delegate.update(input, inputOffset, inputLen);
- }
- @Override
- protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output,
- int outputOffset) throws ShortBufferException {
- return delegate.update(input, inputOffset, inputLen, output, outputOffset);
- }
- @Override
- protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
- throws IllegalBlockSizeException, BadPaddingException {
- return delegate.update(input, inputOffset, inputLen);
- }
- @Override
- protected int engineDoFinal(
- byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
- throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
- return delegate.doFinal(input, inputOffset, inputLen, output, outputOffset);
- }
- }
- private interface DelegatingPrivateKey { PrivateKey getDelegate(); }
- @SuppressWarnings("serial")
- private static class OpaqueDelegatingECPrivateKey
- implements ECKey, PrivateKey, DelegatingPrivateKey {
- private final ECPrivateKey delegate;
- OpaqueDelegatingECPrivateKey(ECPrivateKey delegate) {
- this.delegate = delegate;
- }
- @Override
- public PrivateKey getDelegate() {
- return delegate;
- }
- @Override
- public String getAlgorithm() {
- return delegate.getAlgorithm();
- }
- @Override
- public String getFormat() {
- return null;
- }
- @Override
- public byte[] getEncoded() {
- return null;
- }
- @Override
- public ECParameterSpec getParams() {
- return delegate.getParams();
- }
- }
- @SuppressWarnings("serial")
- private static class OpaqueDelegatingRSAPrivateKey
- implements RSAKey, PrivateKey, DelegatingPrivateKey {
- private final RSAPrivateKey delegate;
- OpaqueDelegatingRSAPrivateKey(RSAPrivateKey delegate) {
- this.delegate = delegate;
- }
- @Override
- public String getAlgorithm() {
- return delegate.getAlgorithm();
- }
- @Override
- public String getFormat() {
- return null;
- }
- @Override
- public byte[] getEncoded() {
- return null;
- }
- @Override
- public BigInteger getModulus() {
- return delegate.getModulus();
- }
- @Override
- public PrivateKey getDelegate() {
- return delegate;
- }
- }
- @Test
- public void test_SSLSocket_TrustManagerRuntimeException() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLContext clientContext = SSLContext.getInstance("TLS");
- X509TrustManager trustManager = new X509TrustManager() {
- @Override
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- throw new AssertionError();
- }
- @Override
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- throw new RuntimeException(); // throw a RuntimeException from custom TrustManager
- }
- @Override
- public X509Certificate[] getAcceptedIssuers() {
- throw new AssertionError();
- }
- };
- clientContext.init(null, new TrustManager[] {trustManager}, null);
- SSLSocket client =
- (SSLSocket) clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- try {
- server.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // Ignored.
- }
- return null;
- });
- try {
- client.startHandshake();
- fail();
- } catch (SSLHandshakeException expected) {
- // before we would get a RuntimeException from checkServerTrusted.
- }
- future.get();
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_getEnableSessionCreation() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- SSLSocket server = (SSLSocket) c.serverSocket.accept();
- assertTrue(client.getEnableSessionCreation());
- assertTrue(server.getEnableSessionCreation());
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_setEnableSessionCreation_server() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- server.setEnableSessionCreation(false);
- try {
- server.startHandshake();
- fail();
- } catch (SSLException expected) {
- // Ignored.
- }
- return null;
- });
- try {
- client.startHandshake();
- fail();
- } catch (SSLException expected) {
- // Ignored.
- }
- future.get();
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_setEnableSessionCreation_client() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- try {
- server.startHandshake();
- fail();
- } catch (SSLException expected) {
- // Ignored.
- }
- return null;
- });
- client.setEnableSessionCreation(false);
- try {
- client.startHandshake();
- fail();
- } catch (SSLException expected) {
- // Ignored.
- }
- future.get();
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_getSSLParameters() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- SSLParameters p = ssl.getSSLParameters();
- assertNotNull(p);
- String[] cipherSuites = p.getCipherSuites();
- assertNotSame(cipherSuites, ssl.getEnabledCipherSuites());
- assertEquals(Arrays.asList(cipherSuites), Arrays.asList(ssl.getEnabledCipherSuites()));
- String[] protocols = p.getProtocols();
- assertNotSame(protocols, ssl.getEnabledProtocols());
- assertEquals(Arrays.asList(protocols), Arrays.asList(ssl.getEnabledProtocols()));
- assertEquals(p.getWantClientAuth(), ssl.getWantClientAuth());
- assertEquals(p.getNeedClientAuth(), ssl.getNeedClientAuth());
- assertNull(p.getEndpointIdentificationAlgorithm());
- p.setEndpointIdentificationAlgorithm(null);
- assertNull(p.getEndpointIdentificationAlgorithm());
- p.setEndpointIdentificationAlgorithm("HTTPS");
- assertEquals("HTTPS", p.getEndpointIdentificationAlgorithm());
- p.setEndpointIdentificationAlgorithm("FOO");
- assertEquals("FOO", p.getEndpointIdentificationAlgorithm());
- }
- @Test
- public void test_SSLSocket_setSSLParameters() throws Exception {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- String[] defaultCipherSuites = ssl.getEnabledCipherSuites();
- String[] defaultProtocols = ssl.getEnabledProtocols();
- String[] supportedCipherSuites = ssl.getSupportedCipherSuites();
- String[] supportedProtocols = ssl.getSupportedProtocols();
- {
- SSLParameters p = new SSLParameters();
- ssl.setSSLParameters(p);
- assertEquals(Arrays.asList(defaultCipherSuites),
- Arrays.asList(ssl.getEnabledCipherSuites()));
- assertEquals(Arrays.asList(defaultProtocols), Arrays.asList(ssl.getEnabledProtocols()));
- }
- {
- SSLParameters p = new SSLParameters(supportedCipherSuites, supportedProtocols);
- ssl.setSSLParameters(p);
- assertEquals(Arrays.asList(supportedCipherSuites),
- Arrays.asList(ssl.getEnabledCipherSuites()));
- assertEquals(
- Arrays.asList(supportedProtocols), Arrays.asList(ssl.getEnabledProtocols()));
- }
- {
- SSLParameters p = new SSLParameters();
- p.setNeedClientAuth(true);
- assertFalse(ssl.getNeedClientAuth());
- assertFalse(ssl.getWantClientAuth());
- ssl.setSSLParameters(p);
- assertTrue(ssl.getNeedClientAuth());
- assertFalse(ssl.getWantClientAuth());
- p.setWantClientAuth(true);
- assertTrue(ssl.getNeedClientAuth());
- assertFalse(ssl.getWantClientAuth());
- ssl.setSSLParameters(p);
- assertFalse(ssl.getNeedClientAuth());
- assertTrue(ssl.getWantClientAuth());
- p.setWantClientAuth(false);
- assertFalse(ssl.getNeedClientAuth());
- assertTrue(ssl.getWantClientAuth());
- ssl.setSSLParameters(p);
- assertFalse(ssl.getNeedClientAuth());
- assertFalse(ssl.getWantClientAuth());
- }
- }
- @Test
- public void test_SSLSocket_close() throws Exception {
- TestSSLSocketPair pair = TestSSLSocketPair.create();
- SSLSocket server = pair.server;
- SSLSocket client = pair.client;
- assertFalse(server.isClosed());
- assertFalse(client.isClosed());
- InputStream input = client.getInputStream();
- OutputStream output = client.getOutputStream();
- server.close();
- client.close();
- assertTrue(server.isClosed());
- assertTrue(client.isClosed());
- // close after close is okay...
- server.close();
- client.close();
- // ...so are a lot of other operations...
- HandshakeCompletedListener l = e -> {};
- client.addHandshakeCompletedListener(l);
- assertNotNull(client.getEnabledCipherSuites());
- assertNotNull(client.getEnabledProtocols());
- client.getEnableSessionCreation();
- client.getNeedClientAuth();
- assertNotNull(client.getSession());
- assertNotNull(client.getSSLParameters());
- assertNotNull(client.getSupportedProtocols());
- client.getUseClientMode();
- client.getWantClientAuth();
- client.removeHandshakeCompletedListener(l);
- client.setEnabledCipherSuites(new String[0]);
- client.setEnabledProtocols(new String[0]);
- client.setEnableSessionCreation(false);
- client.setNeedClientAuth(false);
- client.setSSLParameters(client.getSSLParameters());
- client.setWantClientAuth(false);
- // ...but some operations are expected to give SocketException...
- try {
- client.startHandshake();
- fail();
- } catch (SocketException expected) {
- // Ignored.
- }
- try {
- client.getInputStream();
- fail();
- } catch (SocketException expected) {
- // Ignored.
- }
- try {
- client.getOutputStream();
- fail();
- } catch (SocketException expected) {
- // Ignored.
- }
- try {
- @SuppressWarnings("unused")
- int value = input.read();
- fail();
- } catch (SocketException expected) {
- // Ignored.
- }
- try {
- @SuppressWarnings("unused")
- int bytesRead = input.read(null, -1, -1);
- fail();
- } catch (NullPointerException | SocketException expected) {
- // Ignored.
- }
- try {
- output.write(-1);
- fail();
- } catch (SocketException expected) {
- // Ignored.
- }
- try {
- output.write(null, -1, -1);
- fail();
- } catch (NullPointerException | SocketException expected) {
- // Ignored.
- }
- // ... and one gives IllegalArgumentException
- try {
- client.setUseClientMode(false);
- fail();
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- pair.close();
- }
- /**
- * b/3350645 Test to confirm that an SSLSocket.close() performing
- * an SSL_shutdown does not throw an IOException if the peer
- * socket has been closed.
- */
- @Test
- public void test_SSLSocket_shutdownCloseOnClosedPeer() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- final Socket underlying = new Socket(c.host, c.port);
- final SSLSocket wrapping = (SSLSocket) c.clientContext.getSocketFactory().createSocket(
- underlying, c.host.getHostName(), c.port, false);
- Future<Void> clientFuture = runAsync(() -> {
- wrapping.startHandshake();
- wrapping.getOutputStream().write(42);
- // close the underlying socket,
- // so that no SSL shutdown is sent
- underlying.close();
- wrapping.close();
- return null;
- });
- SSLSocket server = (SSLSocket) c.serverSocket.accept();
- server.startHandshake();
- @SuppressWarnings("unused")
- int value = server.getInputStream().read();
- // wait for thread to finish so we know client is closed.
- clientFuture.get();
- // close should cause an SSL_shutdown which will fail
- // because the peer has closed, but it shouldn't throw.
- server.close();
- }
- @Test
- public void test_SSLSocket_endpointIdentification_Success() throws Exception {
- final TestSSLContext c = TestSSLContext.create();
- SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();
- SSLParameters p = client.getSSLParameters();
- p.setEndpointIdentificationAlgorithm("HTTPS");
- client.connect(new InetSocketAddress(c.host, c.port));
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- server.startHandshake();
- assertNotNull(server.getSession());
- try {
- server.getSession().getPeerCertificates();
- fail();
- } catch (SSLPeerUnverifiedException expected) {
- // Ignored.
- }
- Certificate[] localCertificates = server.getSession().getLocalCertificates();
- assertNotNull(localCertificates);
- TestKeyStore.assertChainLength(localCertificates);
- assertNotNull(localCertificates[0]);
- TestSSLContext.assertCertificateInKeyStore(localCertificates[0], c.serverKeyStore);
- return null;
- });
- client.startHandshake();
- assertNotNull(client.getSession());
- assertNull(client.getSession().getLocalCertificates());
- Certificate[] peerCertificates = client.getSession().getPeerCertificates();
- assertNotNull(peerCertificates);
- TestKeyStore.assertChainLength(peerCertificates);
- assertNotNull(peerCertificates[0]);
- TestSSLContext.assertCertificateInKeyStore(peerCertificates[0], c.serverKeyStore);
- future.get();
- client.close();
- server.close();
- c.close();
- }
- @Test
- public void test_SSLSocket_endpointIdentification_Failure() throws Exception {
- final TestSSLContext c = TestSSLContext.create();
- SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();
- SSLParameters p = client.getSSLParameters();
- p.setEndpointIdentificationAlgorithm("HTTPS");
- client.setSSLParameters(p);
- client.connect(c.getLoopbackAsHostname("unmatched.example.com", c.port));
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- try {
- server.startHandshake();
- fail("Should receive SSLHandshakeException as server");
- } catch (SSLHandshakeException expected) {
- // Ignored.
- }
- return null;
- });
- try {
- client.startHandshake();
- fail("Should throw when hostname does not match expected");
- } catch (SSLHandshakeException expected) {
- // Ignored.
- } finally {
- try {
- future.get();
- } finally {
- client.close();
- server.close();
- c.close();
- }
- }
- }
- @Test
- public void test_SSLSocket_setSoTimeout_basic() throws Exception {
- ServerSocket listening = new ServerSocket(0);
- Socket underlying = new Socket(listening.getInetAddress(), listening.getLocalPort());
- assertEquals(0, underlying.getSoTimeout());
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- Socket wrapping = sf.createSocket(underlying, null, -1, false);
- assertEquals(0, wrapping.getSoTimeout());
- // setting wrapper sets underlying and ...
- int expectedTimeoutMillis = 1000; // 10 was too small because it was affected by rounding
- wrapping.setSoTimeout(expectedTimeoutMillis);
- // The kernel can round the requested value based on the HZ setting. We allow up to 10ms.
- assertTrue(Math.abs(expectedTimeoutMillis - wrapping.getSoTimeout()) <= 10);
- assertTrue(Math.abs(expectedTimeoutMillis - underlying.getSoTimeout()) <= 10);
- // ... getting wrapper inspects underlying
- underlying.setSoTimeout(0);
- assertEquals(0, wrapping.getSoTimeout());
- assertEquals(0, underlying.getSoTimeout());
- }
- @Test
- public void test_SSLSocket_setSoTimeout_wrapper() throws Exception {
- ServerSocket listening = new ServerSocket(0);
- // setSoTimeout applies to read, not connect, so connect first
- Socket underlying = new Socket(listening.getInetAddress(), listening.getLocalPort());
- Socket server = listening.accept();
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- Socket clientWrapping = sf.createSocket(underlying, null, -1, false);
- underlying.setSoTimeout(1);
- try {
- @SuppressWarnings("unused")
- int value = clientWrapping.getInputStream().read();
- fail();
- } catch (SocketTimeoutException expected) {
- // Ignored.
- }
- clientWrapping.close();
- server.close();
- underlying.close();
- listening.close();
- }
- @Test(expected = SocketTimeoutException.class)
- public void test_SSLSocket_setSoWriteTimeout() throws Exception {
- // Only run this test on Linux since it relies on non-posix methods.
- assumeTrue("Test only runs on Linux. Current OS: " + osName(), isLinux());
-
- // In jb-mr2 it was found that we need to also set SO_RCVBUF
- // to a minimal size or the write would not block.
- final int receiveBufferSize = 128;
- TestSSLContext c =
- TestSSLContext.newBuilder().serverReceiveBufferSize(receiveBufferSize).build();
-
- SSLSocket client =
- (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
-
- Method writeTimeoutMethod = getWriteTimeoutSetter(client);
- assumeNotNull("Client socket does not support setting write timeout", writeTimeoutMethod);
-
- // Try to make the client SO_SNDBUF size as small as possible
- // (it can default to 512k or even megabytes). Note that
- // socket(7) says that the kernel will double the request to
- // leave room for its own book keeping and that the minimal
- // value will be 2048. Also note that tcp(7) says the value
- // needs to be set before connect(2).
- int sendBufferSize = 1024;
- client.setSendBufferSize(sendBufferSize);
- sendBufferSize = client.getSendBufferSize();
-
- // Start the handshake.
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- Future<Void> future = runAsync(() -> {
- client.startHandshake();
- return null;
- });
- server.startHandshake();
-
- writeTimeoutMethod.invoke(client, 1);
- try {
- // Add extra space to the write to exceed the send buffer
- // size and cause the write to block.
- final int extra = 1;
- client.getOutputStream().write(new byte[sendBufferSize + extra]);
- } finally {
- future.get();
- client.close();
- server.close();
- c.close();
- }
- }
-
- private static Method getWriteTimeoutSetter(Object socket) {
- try {
- return socket.getClass().getDeclaredMethod("setSoWriteTimeout", int.class);
- } catch (Exception e) {
- return null;
- }
- }
-
- private static String osName() {
- return System.getProperty("os.name").toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "");
- }
-
- private static boolean isLinux() {
- return osName().startsWith("linux");
- }
-
- @Ignore("TODO(nmittler): Fix this.")
- @Test
- public void test_SSLSocket_interrupt() throws Exception {
- test_SSLSocket_interrupt_case(true, true);
- test_SSLSocket_interrupt_case(true, false);
- test_SSLSocket_interrupt_case(false, true);
- test_SSLSocket_interrupt_case(false, false);
- }
- private void test_SSLSocket_interrupt_case(boolean readUnderlying, boolean closeUnderlying)
- throws Exception {
- final int readingTimeoutMillis = 5000;
- TestSSLContext c = TestSSLContext.create();
- final Socket underlying = new Socket(c.host, c.port);
- final SSLSocket clientWrapping = (SSLSocket) c.clientContext.getSocketFactory().createSocket(
- underlying, c.host.getHostName(), c.port, false);
- SSLSocket server = (SSLSocket) c.serverSocket.accept();
-
- // Start the handshake.
- Future<Void> handshakeFuture = runAsync(() -> {
- clientWrapping.startHandshake();
- return null;
- });
- server.startHandshake();
- handshakeFuture.get();
-
- final Socket toRead = (readUnderlying) ? underlying : clientWrapping;
- final Socket toClose = (closeUnderlying) ? underlying : clientWrapping;
-
- // Schedule the socket to be closes in 1 second.
- Future<Void> future = runAsync(() -> {
- Thread.sleep(1000);
- toClose.close();
- return null;
- });
-
- // Read from the socket.
- try {
- toRead.setSoTimeout(readingTimeoutMillis);
- final InputStream inputStream = toRead.getInputStream();
- @SuppressWarnings("unused")
- int value = inputStream.read();
- fail();
- } catch (SocketException expected) {
- // Ignored.
- }
-
- future.get();
- server.close();
- underlying.close();
- server.close();
- }
- /**
- * b/7014266 Test to confirm that an SSLSocket.close() on one
- * thread will interrupt another thread blocked reading on the same
- * socket.
- */
- @Test
- public void test_SSLSocket_interrupt_read() throws Exception {
- final int readingTimeoutMillis = 5000;
- TestSSLContext c = TestSSLContext.create();
- final Socket underlying = new Socket(c.host, c.port);
- final SSLSocket wrapping = (SSLSocket) c.clientContext.getSocketFactory().createSocket(
- underlying, c.host.getHostName(), c.port, false);
- Future<Void> clientFuture = runAsync(() -> {
- wrapping.startHandshake();
- wrapping.setSoTimeout(readingTimeoutMillis);
- assertEquals(-1, wrapping.getInputStream().read());
- return null;
- });
- SSLSocket server = (SSLSocket) c.serverSocket.accept();
- server.startHandshake();
-
- // Wait for the client to at least be in the "read" method before calling close()
- Thread[] threads = new Thread[1];
- threadGroup.enumerate(threads);
- if (threads[0] != null) {
- boolean clientInRead = false;
- while (!clientInRead) {
- StackTraceElement[] elements = threads[0].getStackTrace();
- for (StackTraceElement element : elements) {
- if ("read".equals(element.getMethodName())) {
- // The client might be executing "read" but still not have reached the
- // point in which it's blocked reading. This is causing flakiness
- // (b/24367646). Delaying for a fraction of the timeout.
- Thread.sleep(1000);
- clientInRead = true;
- break;
- }
- }
- }
- }
-
- wrapping.close();
- clientFuture.get();
- server.close();
- }
- @Test
- public void test_TestSSLSocketPair_create() {
- TestSSLSocketPair test = TestSSLSocketPair.create();
- assertNotNull(test.c);
- assertNotNull(test.server);
- assertNotNull(test.client);
- assertTrue(test.server.isConnected());
- assertTrue(test.client.isConnected());
- assertFalse(test.server.isClosed());
- assertFalse(test.client.isClosed());
- assertNotNull(test.server.getSession());
- assertNotNull(test.client.getSession());
- assertTrue(test.server.getSession().isValid());
- assertTrue(test.client.getSession().isValid());
- test.close();
- }
- @Test
- public void test_SSLSocket_ClientHello_record_size() throws Exception {
- // This test checks the size of ClientHello of the default SSLSocket. TLS/SSL handshakes
- // with older/unpatched F5/BIG-IP appliances are known to stall and time out when
- // the fragment containing ClientHello is between 256 and 511 (inclusive) bytes long.
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(null, null, null);
- SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
- sslSocketFactory = new DelegatingSSLSocketFactory(sslSocketFactory) {
- @Override
- protected SSLSocket configureSocket(SSLSocket socket) {
- // Enable SNI extension on the socket (this is typically enabled by default)
- // to increase the size of ClientHello.
- try {
- Method setHostname = socket.getClass().getMethod("setHostname", String.class);
- setHostname.invoke(socket, "sslsockettest.androidcts.google.com");
- } catch (NoSuchMethodException ignored) {
- // Ignored.
- } catch (Exception e) {
- throw new RuntimeException("Failed to enable SNI", e);
- }
- // Enable Session Tickets extension on the socket (this is typically enabled
- // by default) to increase the size of ClientHello.
- try {
- Method setUseSessionTickets =
- socket.getClass().getMethod("setUseSessionTickets", boolean.class);
- setUseSessionTickets.invoke(socket, true);
- } catch (NoSuchMethodException ignored) {
- // Ignored.
- } catch (Exception e) {
- throw new RuntimeException("Failed to enable Session Tickets", e);
- }
- return socket;
- }
- };
- TlsRecord firstReceivedTlsRecord = captureTlsHandshakeFirstTlsRecord(sslSocketFactory);
- assertEquals("TLS record type", TlsProtocols.HANDSHAKE, firstReceivedTlsRecord.type);
- HandshakeMessage handshakeMessage = HandshakeMessage.read(
- new DataInputStream(new ByteArrayInputStream(firstReceivedTlsRecord.fragment)));
- assertEquals(
- "HandshakeMessage type", HandshakeMessage.TYPE_CLIENT_HELLO, handshakeMessage.type);
- int fragmentLength = firstReceivedTlsRecord.fragment.length;
- if ((fragmentLength >= 256) && (fragmentLength <= 511)) {
- fail("Fragment containing ClientHello is of dangerous length: " + fragmentLength
- + " bytes");
- }
- }
- @Test
- public void test_SSLSocket_ClientHello_cipherSuites() throws Exception {
- ForEachRunner.runNamed(sslSocketFactory -> {
- ClientHello clientHello = captureTlsHandshakeClientHello(sslSocketFactory);
- final String[] cipherSuites;
- // RFC 5746 allows you to send an empty "renegotiation_info" extension *or*
- // a special signaling cipher suite. The TLS API has no way to check or
- // indicate that a certain TLS extension should be used.
- HelloExtension renegotiationInfoExtension =
- clientHello.findExtensionByType(HelloExtension.TYPE_RENEGOTIATION_INFO);
- if (renegotiationInfoExtension != null
- && renegotiationInfoExtension.data.length == 1
- && renegotiationInfoExtension.data[0] == 0) {
- cipherSuites = new String[clientHello.cipherSuites.size() + 1];
- cipherSuites[clientHello.cipherSuites.size()] =
- StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION;
- } else {
- cipherSuites = new String[clientHello.cipherSuites.size()];
- }
- for (int i = 0; i < clientHello.cipherSuites.size(); i++) {
- CipherSuite cipherSuite = clientHello.cipherSuites.get(i);
- cipherSuites[i] = cipherSuite.getAndroidName();
- }
- StandardNames.assertDefaultCipherSuites(cipherSuites);
- }, getSSLSocketFactoriesToTest());
- }
- @Test
- public void test_SSLSocket_ClientHello_supportedCurves() throws Exception {
- ForEachRunner.runNamed(sslSocketFactory -> {
- ClientHello clientHello = captureTlsHandshakeClientHello(sslSocketFactory);
- EllipticCurvesHelloExtension ecExtension =
- (EllipticCurvesHelloExtension) clientHello.findExtensionByType(
- HelloExtension.TYPE_ELLIPTIC_CURVES);
- final String[] supportedCurves;
- if (ecExtension == null) {
- supportedCurves = new String[0];
- } else {
- assertTrue(ecExtension.wellFormed);
- supportedCurves = new String[ecExtension.supported.size()];
- for (int i = 0; i < ecExtension.supported.size(); i++) {
- EllipticCurve curve = ecExtension.supported.get(i);
- supportedCurves[i] = curve.toString();
- }
- }
- StandardNames.assertDefaultEllipticCurves(supportedCurves);
- }, getSSLSocketFactoriesToTest());
- }
- @Test
- public void test_SSLSocket_ClientHello_clientProtocolVersion() throws Exception {
- ForEachRunner.runNamed(sslSocketFactory -> {
- ClientHello clientHello = captureTlsHandshakeClientHello(sslSocketFactory);
- assertEquals(TlsProtocolVersion.TLSv1_2, clientHello.clientVersion);
- }, getSSLSocketFactoriesToTest());
- }
- @Test
- public void test_SSLSocket_ClientHello_compressionMethods() throws Exception {
- ForEachRunner.runNamed(sslSocketFactory -> {
- ClientHello clientHello = captureTlsHandshakeClientHello(sslSocketFactory);
- assertEquals(Collections.singletonList(CompressionMethod.NULL),
- clientHello.compressionMethods);
- }, getSSLSocketFactoriesToTest());
- }
- @Test
- public void test_SSLSocket_ClientHello_SNI() throws Exception {
- ForEachRunner.runNamed(sslSocketFactory -> {
- ClientHello clientHello = captureTlsHandshakeClientHello(sslSocketFactory);
- ServerNameHelloExtension sniExtension =
- (ServerNameHelloExtension) clientHello.findExtensionByType(
- HelloExtension.TYPE_SERVER_NAME);
- assertNotNull(sniExtension);
- assertEquals(
- Collections.singletonList("localhost.localdomain"), sniExtension.hostnames);
- }, getSSLSocketFactoriesToTest());
- }
- private List<Pair<String, SSLSocketFactory>> getSSLSocketFactoriesToTest()
- throws NoSuchAlgorithmException, KeyManagementException {
- List<Pair<String, SSLSocketFactory>> result =
- new ArrayList<>();
- result.add(Pair.of("default", (SSLSocketFactory) SSLSocketFactory.getDefault()));
- for (String sslContextProtocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
- SSLContext sslContext = SSLContext.getInstance(sslContextProtocol);
- if (StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT.equals(sslContextProtocol)) {
- continue;
- }
- sslContext.init(null, null, null);
- result.add(Pair.of("SSLContext(\"" + sslContext.getProtocol() + "\")",
- sslContext.getSocketFactory()));
- }
- return result;
- }
- private ClientHello captureTlsHandshakeClientHello(SSLSocketFactory sslSocketFactory)
- throws Exception {
- TlsRecord record = captureTlsHandshakeFirstTlsRecord(sslSocketFactory);
- assertEquals("TLS record type", TlsProtocols.HANDSHAKE, record.type);
- ByteArrayInputStream fragmentIn = new ByteArrayInputStream(record.fragment);
- HandshakeMessage handshakeMessage = HandshakeMessage.read(new DataInputStream(fragmentIn));
- assertEquals(
- "HandshakeMessage type", HandshakeMessage.TYPE_CLIENT_HELLO, handshakeMessage.type);
- // Assert that the fragment does not contain any more messages
- assertEquals(0, fragmentIn.available());
- return (ClientHello) handshakeMessage;
- }
- private TlsRecord captureTlsHandshakeFirstTlsRecord(SSLSocketFactory sslSocketFactory)
- throws Exception {
- byte[] firstReceivedChunk = captureTlsHandshakeFirstTransmittedChunkBytes(sslSocketFactory);
- ByteArrayInputStream firstReceivedChunkIn = new ByteArrayInputStream(firstReceivedChunk);
- TlsRecord record = TlsRecord.read(new DataInputStream(firstReceivedChunkIn));
- // Assert that the chunk does not contain any more data
- assertEquals(0, firstReceivedChunkIn.available());
- return record;
- }
- @SuppressWarnings("FutureReturnValueIgnored")
- private byte[] captureTlsHandshakeFirstTransmittedChunkBytes(
- final SSLSocketFactory sslSocketFactory) throws Exception {
- // Since there's no straightforward way to obtain a ClientHello from SSLSocket, this test
- // does the following:
- // 1. Creates a listening server socket (a plain one rather than a TLS/SSL one).
- // 2. Creates a client SSLSocket, which connects to the server socket and initiates the
- // TLS/SSL handshake.
- // 3. Makes the server socket accept an incoming connection on the server socket, and reads
- // the first chunk of data received. This chunk is assumed to be the ClientHello.
- // NOTE: Steps 2 and 3 run concurrently.
- ServerSocket listeningSocket = null;
- // Some Socket operations are not interruptible via Thread.interrupt for some reason. To
- // work around, we unblock these sockets using Socket.close.
- final Socket[] sockets = new Socket[2];
- try {
- // 1. Create the listening server socket.
- listeningSocket = ServerSocketFactory.getDefault().createServerSocket(0);
- final ServerSocket finalListeningSocket = listeningSocket;
- // 2. (in background) Wait for an incoming connection and read its first chunk.
- final Future<byte[]> readFirstReceivedChunkFuture =
- runAsync(() -> {
- Socket socket = finalListeningSocket.accept();
- sockets[1] = socket;
- try {
- byte[] buffer = new byte[64 * 1024];
- int bytesRead = socket.getInputStream().read(buffer);
- if (bytesRead == -1) {
- throw new EOFException("Failed to read anything");
- }
- return Arrays.copyOf(buffer, bytesRead);
- } finally {
- closeQuietly(socket);
- }
- });
- // 3. Create a client socket, connect it to the server socket, and start the TLS/SSL
- // handshake.
- runAsync((Callable<Void>) () -> {
- Socket client = new Socket();
- sockets[0] = client;
- try {
- client.connect(finalListeningSocket.getLocalSocketAddress());
- // Initiate the TLS/SSL handshake which is expected to fail as soon as the
- // server socket receives a ClientHello.
- try {
- SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(client,
- "localhost.localdomain", finalListeningSocket.getLocalPort(),
- true);
- sslSocket.startHandshake();
- fail();
- return null;
- } catch (IOException expected) {
- // Ignored.
- }
- return null;
- } finally {
- closeQuietly(client);
- }
- });
- // Wait for the ClientHello to arrive
- return readFirstReceivedChunkFuture.get(10, TimeUnit.SECONDS);
- } finally {
- closeQuietly(listeningSocket);
- closeQuietly(sockets[0]);
- closeQuietly(sockets[1]);
- }
- }
- // http://b/18428603
- @Test
- public void test_SSLSocket_getPortWithSNI() throws Exception {
- TestSSLContext context = TestSSLContext.create();
- try (SSLSocket client = (SSLSocket) context.clientContext.getSocketFactory()
- .createSocket()) {
- client.connect(new InetSocketAddress(context.host, context.port));
- try {
- // This is crucial to reproducing issue 18428603.
- Method setHostname = client.getClass().getMethod("setHostname", String.class);
- setHostname.invoke(client, "sslsockettest.androidcts.google.com");
- } catch (NoSuchMethodException ignored) {
- // Ignored.
- }
- assertTrue(client.getPort() > 0);
- } finally {
- context.close();
- }
- }
- @Test
- public void test_SSLSocket_SNIHostName() throws Exception {
- TestSSLContext c = TestSSLContext.create();
- final SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();
- SSLParameters clientParams = client.getSSLParameters();
- clientParams.setServerNames(
- Collections.singletonList(new SNIHostName("www.example.com")));
- client.setSSLParameters(clientParams);
- SSLParameters serverParams = c.serverSocket.getSSLParameters();
- serverParams.setSNIMatchers(
- Collections.singletonList(SNIHostName.createSNIMatcher("www\\.example\\.com")));
- c.serverSocket.setSSLParameters(serverParams);
- client.connect(new InetSocketAddress(c.host, c.port));
- final SSLSocket server = (SSLSocket) c.serverSocket.accept();
- @SuppressWarnings("unused")
- Future<?> future = runAsync(() -> {
- client.startHandshake();
- return null;
- });
- server.startHandshake();
- SSLSession serverSession = server.getSession();
- assertTrue(serverSession instanceof ExtendedSSLSession);
- ExtendedSSLSession extendedServerSession = (ExtendedSSLSession) serverSession;
- List<SNIServerName> requestedNames = extendedServerSession.getRequestedServerNames();
- assertNotNull(requestedNames);
- assertEquals(1, requestedNames.size());
- SNIServerName serverName = requestedNames.get(0);
- assertEquals(StandardConstants.SNI_HOST_NAME, serverName.getType());
- assertTrue(serverName instanceof SNIHostName);
- SNIHostName serverHostName = (SNIHostName) serverName;
- assertEquals("www.example.com", serverHostName.getAsciiName());
- }
- @Test
- public void test_SSLSocket_sendsTlsFallbackScsv_Fallback_Success() throws Exception {
- TestSSLContext context = TestSSLContext.create();
- final SSLSocket client = (SSLSocket) context.clientContext.getSocketFactory().createSocket(
- context.host, context.port);
- final SSLSocket server = (SSLSocket) context.serverSocket.accept();
- final String[] serverCipherSuites = server.getEnabledCipherSuites();
- final String[] clientCipherSuites = new String[serverCipherSuites.length + 1];
- System.arraycopy(serverCipherSuites, 0, clientCipherSuites, 0, serverCipherSuites.length);
- clientCipherSuites[serverCipherSuites.length] = StandardNames.CIPHER_SUITE_FALLBACK;
- Future<Void> s = runAsync(() -> {
- server.setEnabledProtocols(new String[] {"TLSv1.2"});
- server.setEnabledCipherSuites(serverCipherSuites);
- server.startHandshake();
- return null;
- });
- Future<Void> c = runAsync(() -> {
- client.setEnabledProtocols(new String[] {"TLSv1.2"});
- client.setEnabledCipherSuites(clientCipherSuites);
- client.startHandshake();
- return null;
- });
- s.get();
- c.get();
- client.close();
- server.close();
- context.close();
- }
- // Confirms that communication without the TLS_FALLBACK_SCSV cipher works as it always did.
- @Test
- public void test_SSLSocket_sendsNoTlsFallbackScsv_Fallback_Success() throws Exception {
- TestSSLContext context = TestSSLContext.create();
- final SSLSocket client = (SSLSocket) context.clientContext.getSocketFactory().createSocket(
- context.host, context.port);
- final SSLSocket server = (SSLSocket) context.serverSocket.accept();
- // Confirm absence of TLS_FALLBACK_SCSV.
- assertFalse(Arrays.asList(client.getEnabledCipherSuites())
- .contains(StandardNames.CIPHER_SUITE_FALLBACK));
- Future<Void> s = runAsync(() -> {
- server.setEnabledProtocols(new String[] {"TLSv1.2", "TLSv1.1"});
- server.startHandshake();
- return null;
- });
- Future<Void> c = runAsync(() -> {
- client.setEnabledProtocols(new String[] {"TLSv1.1"});
- client.startHandshake();
- return null;
- });
- s.get();
- c.get();
- client.close();
- server.close();
- context.close();
- }
- private static void assertInappropriateFallbackIsCause(Throwable cause) {
- assertTrue(cause.getMessage(), cause.getMessage().contains("inappropriate fallback")
- || cause.getMessage().contains("INAPPROPRIATE_FALLBACK"));
- }
- @Test
- public void test_SSLSocket_sendsTlsFallbackScsv_InappropriateFallback_Failure()
- throws Exception {
- TestSSLContext context = TestSSLContext.create();
- final SSLSocket client = (SSLSocket) context.clientContext.getSocketFactory().createSocket(
- context.host, context.port);
- final SSLSocket server = (SSLSocket) context.serverSocket.accept();
- final String[] serverCipherSuites = server.getEnabledCipherSuites();
- // Add TLS_FALLBACK_SCSV
- final String[] clientCipherSuites = new String[serverCipherSuites.length + 1];
- System.arraycopy(serverCipherSuites, 0, clientCipherSuites, 0, serverCipherSuites.length);
- clientCipherSuites[serverCipherSuites.length] = StandardNames.CIPHER_SUITE_FALLBACK;
- Future<Void> s = runAsync(() -> {
- server.setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1"});
- server.setEnabledCipherSuites(serverCipherSuites);
- try {
- server.startHandshake();
- fail("Should result in inappropriate fallback");
- } catch (SSLHandshakeException expected) {
- Throwable cause = expected.getCause();
- assertEquals(SSLProtocolException.class, cause.getClass());
- assertInappropriateFallbackIsCause(cause);
- }
- return null;
- });
- Future<Void> c = runAsync(() -> {
- client.setEnabledProtocols(new String[] {"TLSv1"});
- client.setEnabledCipherSuites(clientCipherSuites);
- try {
- client.startHandshake();
- fail("Should receive TLS alert inappropriate fallback");
- } catch (SSLHandshakeException expected) {
- Throwable cause = expected.getCause();
- assertEquals(SSLProtocolException.class, cause.getClass());
- assertInappropriateFallbackIsCause(cause);
- }
- return null;
- });
- s.get();
- c.get();
- client.close();
- server.close();
- context.close();
- }
- @Test
- public void test_SSLSocket_ClientGetsAlertDuringHandshake_HasGoodExceptionMessage()
- throws Exception {
- TestSSLContext context = TestSSLContext.create();
- final ServerSocket listener = ServerSocketFactory.getDefault().createServerSocket(0);
- final SSLSocket client = (SSLSocket) context.clientContext.getSocketFactory().createSocket(
- context.host, listener.getLocalPort());
- final Socket server = listener.accept();
- Future<Void> c = runAsync(() -> {
- try {
- client.startHandshake();
- fail("Should receive handshake exception");
- } catch (SSLHandshakeException expected) {
- assertFalse(expected.getMessage().contains("SSL_ERROR_ZERO_RETURN"));
- assertFalse(expected.getMessage().contains("You should never see this."));
- }
- return null;
- });
- Future<Void> s = runAsync(() -> {
- // Wait until the client sends something.
- byte[] scratch = new byte[8192];
- @SuppressWarnings("unused")
- int bytesRead = server.getInputStream().read(scratch);
- // Write a bogus TLS alert:
- // TLSv1.2 Record Layer: Alert (Level: Warning, Description: Protocol Version)
- server.getOutputStream().write(
- new byte[] {0x15, 0x03, 0x03, 0x00, 0x02, 0x01, 0x46});
- // TLSv1.2 Record Layer: Alert (Level: Warning, Description: Close Notify)
- server.getOutputStream().write(
- new byte[] {0x15, 0x03, 0x03, 0x00, 0x02, 0x01, 0x00});
- return null;
- });
- c.get(5, TimeUnit.SECONDS);
- s.get(5, TimeUnit.SECONDS);
- client.close();
- server.close();
- listener.close();
- context.close();
- }
- @Test
- public void test_SSLSocket_ServerGetsAlertDuringHandshake_HasGoodExceptionMessage()
- throws Exception {
- TestSSLContext context = TestSSLContext.create();
- final Socket client = SocketFactory.getDefault().createSocket(context.host, context.port);
- final SSLSocket server = (SSLSocket) context.serverSocket.accept();
- Future<Void> s = runAsync(() -> {
- try {
- server.startHandshake();
- fail("Should receive handshake exception");
- } catch (SSLHandshakeException expected) {
- assertFalse(expected.getMessage().contains("SSL_ERROR_ZERO_RETURN"));
- assertFalse(expected.getMessage().contains("You should never see this."));
- }
- return null;
- });
- Future<Void> c = runAsync(() -> {
- // Send bogus ClientHello:
- // TLSv1.2 Record Layer: Handshake Protocol: Client Hello
- client.getOutputStream().write(new byte[] {
- (byte) 0x16, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0xb9,
- (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xb5, (byte) 0x03,
- (byte) 0x03, (byte) 0x5a, (byte) 0x31, (byte) 0xba, (byte) 0x44,
- (byte) 0x24, (byte) 0xfd, (byte) 0xf0, (byte) 0x56, (byte) 0x46,
- (byte) 0xea, (byte) 0xee, (byte) 0x1c, (byte) 0x62, (byte) 0x8f,
- (byte) 0x18, (byte) 0x04, (byte) 0xbd, (byte) 0x1c, (byte) 0xbc,
- (byte) 0xbf, (byte) 0x6d, (byte) 0x84, (byte) 0x12, (byte) 0xe9,
- (byte) 0x94, (byte) 0xf5, (byte) 0x1c, (byte) 0x15, (byte) 0x3e,
- (byte) 0x79, (byte) 0x01, (byte) 0xe2, (byte) 0x00, (byte) 0x00,
- (byte) 0x28, (byte) 0xc0, (byte) 0x2b, (byte) 0xc0, (byte) 0x2c,
- (byte) 0xc0, (byte) 0x2f, (byte) 0xc0, (byte) 0x30, (byte) 0x00,
- (byte) 0x9e, (byte) 0x00, (byte) 0x9f, (byte) 0xc0, (byte) 0x09,
- (byte) 0xc0, (byte) 0x0a, (byte) 0xc0, (byte) 0x13, (byte) 0xc0,
- (byte) 0x14, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x39,
- (byte) 0xc0, (byte) 0x07, (byte) 0xc0, (byte) 0x11, (byte) 0x00,
- (byte) 0x9c, (byte) 0x00, (byte) 0x9d, (byte) 0x00, (byte) 0x2f,
- (byte) 0x00, (byte) 0x35, (byte) 0x00, (byte) 0x05, (byte) 0x00,
- (byte) 0xff, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x64,
- (byte) 0x00, (byte) 0x0b, (byte) 0x00, (byte) 0x04, (byte) 0x03,
- (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x00, (byte) 0x0a,
- (byte) 0x00, (byte) 0x34, (byte) 0x00, (byte) 0x32, (byte) 0x00,
- (byte) 0x0e, (byte) 0x00, (byte) 0x0d, (byte) 0x00, (byte) 0x19,
- (byte) 0x00, (byte) 0x0b, (byte) 0x00, (byte) 0x0c, (byte) 0x00,
- (byte) 0x18, (byte) 0x00, (byte) 0x09, (byte) 0x00, (byte) 0x0a,
- (byte) 0x00, (byte) 0x16, (byte) 0x00, (byte) 0x17, (byte) 0x00,
- (byte) 0x08, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x07,
- (byte) 0x00, (byte) 0x14, (byte) 0x00, (byte) 0x15, (byte) 0x00,
- (byte) 0x04, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x12,
- (byte) 0x00, (byte) 0x13, (byte) 0x00, (byte) 0x01, (byte) 0x00,
- (byte) 0x02, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x0f,
- (byte) 0x00, (byte) 0x10, (byte) 0x00, (byte) 0x11, (byte) 0x00,
- (byte) 0x0d, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x1e,
- (byte) 0x06, (byte) 0x01, (byte) 0x06, (byte) 0x02, (byte) 0x06,
- (byte) 0x03, (byte) 0x05, (byte) 0x01, (byte) 0x05, (byte) 0x02,
- (byte) 0x05, (byte) 0x03, (byte) 0x04, (byte) 0x01, (byte) 0x04,
- (byte) 0x02, (byte) 0x04, (byte) 0x03, (byte) 0x03, (byte) 0x01,
- (byte) 0x03, (byte) 0x02, (byte) 0x03, (byte) 0x03, (byte) 0x02,
- (byte) 0x01, (byte) 0x02, (byte) 0x02, (byte) 0x02, (byte) 0x03,
- });
- // Wait until the server sends something.
- byte[] scratch = new byte[8192];
- @SuppressWarnings("unused")
- int bytesRead = client.getInputStream().read(scratch);
- // Write a bogus TLS alert:
- // TLSv1.2 Record Layer: Alert (Level: Warning, Description:
- // Protocol Version)
- client.getOutputStream().write(
- new byte[] {0x15, 0x03, 0x03, 0x00, 0x02, 0x01, 0x46});
- // TLSv1.2 Record Layer: Alert (Level: Warning, Description:
- // Close Notify)
- client.getOutputStream().write(
- new byte[] {0x15, 0x03, 0x03, 0x00, 0x02, 0x01, 0x00});
- return null;
- });
- c.get(5, TimeUnit.SECONDS);
- s.get(5, TimeUnit.SECONDS);
- client.close();
- server.close();
- context.close();
- }
- @Test
- public void test_SSLSocket_SSLv3Unsupported() throws Exception {
- TestSSLContext context = TestSSLContext.create();
- final SSLSocket client =
- (SSLSocket) context.clientContext.getSocketFactory().createSocket();
- // For app compatibility, SSLv3 is stripped out when setting only.
- client.setEnabledProtocols(new String[] {"SSLv3"});
- assertEquals(0, client.getEnabledProtocols().length);
- try {
- client.setEnabledProtocols(new String[] {"SSL"});
- fail("SSLSocket should not support SSL protocol");
- } catch (IllegalArgumentException expected) {
- // Ignored.
- }
- }
-
- private <T> Future<T> runAsync(Callable<T> callable) {
- return executor.submit(callable);
- }
-
- private static void readFully(InputStream in, byte[] dst) throws IOException {
- int offset = 0;
- int byteCount = dst.length;
- while (byteCount > 0) {
- int bytesRead = in.read(dst, offset, byteCount);
- if (bytesRead < 0) {
- throw new EOFException();
- }
- offset += bytesRead;
- byteCount -= bytesRead;
- }
- }
- private static void closeQuietly(Closeable socket) {
- if (socket != null) {
- try {
- socket.close();
- } catch (Exception ignored) {
- // Ignored.
- }
- }
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java
deleted file mode 100644
index 556d89fb..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStore.PrivateKeyEntry;
-import java.security.Provider;
-import java.security.Security;
-import java.security.cert.CertificateException;
-import java.security.cert.PKIXBuilderParameters;
-import java.security.cert.PKIXParameters;
-import java.security.cert.X509CertSelector;
-import java.security.cert.X509Certificate;
-import java.util.Set;
-import javax.net.ssl.CertPathTrustManagerParameters;
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509TrustManager;
-import libcore.java.security.StandardNames;
-import libcore.java.security.TestKeyStore;
-import org.bouncycastle.asn1.x509.KeyPurposeId;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class TrustManagerFactoryTest extends AbstractSSLTest {
- private static final String[] KEY_TYPES = new String[] {"RSA", "DSA", "EC", "EC_RSA"};
-
- private static TestKeyStore TEST_KEY_STORE;
-
- // note the rare usage of DSA keys here in addition to RSA
- private static TestKeyStore getTestKeyStore() throws Exception {
- if (TEST_KEY_STORE == null) {
- TEST_KEY_STORE = new TestKeyStore.Builder()
- .keyAlgorithms(KEY_TYPES)
- .aliasPrefix("rsa-dsa-ec")
- .build();
- }
- return TEST_KEY_STORE;
- }
-
- private static boolean supportsManagerFactoryParameters(String algorithm) {
- return (StandardNames.IS_RI && algorithm.equals("PKIX"));
- }
-
- @Test
- public void test_TrustManagerFactory_getDefaultAlgorithm() throws Exception {
- String algorithm = TrustManagerFactory.getDefaultAlgorithm();
- assertEquals(StandardNames.TRUST_MANAGER_FACTORY_DEFAULT, algorithm);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
- test_TrustManagerFactory(tmf);
- }
-
- private static class UselessManagerFactoryParameters implements ManagerFactoryParameters {}
-
- private void test_TrustManagerFactory(TrustManagerFactory tmf) throws Exception {
- assertNotNull(tmf);
- assertNotNull(tmf.getAlgorithm());
- assertNotNull(tmf.getProvider());
-
- // before init
- try {
- tmf.getTrustManagers();
- fail();
- } catch (IllegalStateException expected) {
- // Ignored.
- }
-
- // init with null ManagerFactoryParameters
- try {
- tmf.init((ManagerFactoryParameters) null);
- fail();
- } catch (InvalidAlgorithmParameterException expected) {
- // Ignored.
- }
-
- // init with useless ManagerFactoryParameters
- try {
- tmf.init(new UselessManagerFactoryParameters());
- fail();
- } catch (InvalidAlgorithmParameterException expected) {
- // Ignored.
- }
-
- // init with PKIXParameters ManagerFactoryParameters
- try {
- PKIXParameters pp = new PKIXParameters(getTestKeyStore().keyStore);
- CertPathTrustManagerParameters cptmp = new CertPathTrustManagerParameters(pp);
- tmf.init(cptmp);
- fail();
- } catch (InvalidAlgorithmParameterException expected) {
- // Ignored.
- }
-
- // init with PKIXBuilderParameters ManagerFactoryParameters
- X509CertSelector xcs = new X509CertSelector();
- PKIXBuilderParameters pbp = new PKIXBuilderParameters(getTestKeyStore().keyStore, xcs);
- CertPathTrustManagerParameters cptmp = new CertPathTrustManagerParameters(pbp);
- if (supportsManagerFactoryParameters(tmf.getAlgorithm())) {
- tmf.init(cptmp);
- test_TrustManagerFactory_getTrustManagers(tmf);
- } else {
- try {
- tmf.init(cptmp);
- fail();
- } catch (InvalidAlgorithmParameterException expected) {
- // Ignored.
- }
- }
-
- // init with null for default KeyStore
- tmf.init((KeyStore) null);
- test_TrustManagerFactory_getTrustManagers(tmf);
-
- // init with specific key store
- tmf.init(getTestKeyStore().keyStore);
- test_TrustManagerFactory_getTrustManagers(tmf);
- }
-
- private void test_TrustManagerFactory_getTrustManagers(TrustManagerFactory tmf)
- throws Exception {
- TrustManager[] trustManagers = tmf.getTrustManagers();
- assertNotNull(trustManagers);
- assertTrue(trustManagers.length > 0);
- for (TrustManager trustManager : trustManagers) {
- assertNotNull(trustManager);
- if (trustManager instanceof X509TrustManager) {
- test_X509TrustManager((X509TrustManager) trustManager);
- }
- }
- }
-
- private void test_X509TrustManager(X509TrustManager tm) throws Exception {
- for (String keyType : KEY_TYPES) {
- X509Certificate[] issuers = tm.getAcceptedIssuers();
- assertNotNull(issuers);
- assertTrue(issuers.length > 1);
- assertNotSame(issuers, tm.getAcceptedIssuers());
- boolean defaultTrustManager
- // RI de-duplicates certs from TrustedCertificateEntry and PrivateKeyEntry
- = issuers.length > (StandardNames.IS_RI ? 1 : 2) * KEY_TYPES.length;
-
- String keyAlgName = TestKeyStore.keyAlgorithm(keyType);
- String sigAlgName = TestKeyStore.signatureAlgorithm(keyType);
- PrivateKeyEntry pke = getTestKeyStore().getPrivateKey(keyAlgName, sigAlgName);
- X509Certificate[] chain = (X509Certificate[]) pke.getCertificateChain();
- if (defaultTrustManager) {
- try {
- tm.checkClientTrusted(chain, keyType);
- fail();
- } catch (CertificateException expected) {
- // Ignored.
- }
- try {
- tm.checkServerTrusted(chain, keyType);
- fail();
- } catch (CertificateException expected) {
- // Ignored.
- }
- } else {
- tm.checkClientTrusted(chain, keyType);
- tm.checkServerTrusted(chain, keyType);
- }
- }
- }
-
- @Test
- public void test_TrustManagerFactory_getInstance() throws Exception {
- Provider[] providers = Security.getProviders();
- for (Provider provider : providers) {
- Set<Provider.Service> services = provider.getServices();
- for (Provider.Service service : services) {
- String type = service.getType();
- if (!type.equals("TrustManagerFactory")) {
- continue;
- }
- String algorithm = service.getAlgorithm();
- {
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
- assertEquals(algorithm, tmf.getAlgorithm());
- test_TrustManagerFactory(tmf);
- }
-
- {
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm, provider);
- assertEquals(algorithm, tmf.getAlgorithm());
- assertEquals(provider, tmf.getProvider());
- test_TrustManagerFactory(tmf);
- }
-
- {
- TrustManagerFactory tmf =
- TrustManagerFactory.getInstance(algorithm, provider.getName());
- assertEquals(algorithm, tmf.getAlgorithm());
- assertEquals(provider, tmf.getProvider());
- test_TrustManagerFactory(tmf);
- }
- }
- }
- }
-
- @Test
- public void test_TrustManagerFactory_intermediate() throws Exception {
- // chain should be server/intermediate/root
- PrivateKeyEntry pke = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
- X509Certificate[] chain = (X509Certificate[]) pke.getCertificateChain();
- assertEquals(3, chain.length);
-
- // keyStore should contain only the intermediate CA so we can
- // test proper validation even if there are extra certs after
- // the trusted one (in this case the original root is "extra")
- KeyStore keyStore = TestKeyStore.createKeyStore();
- keyStore.setCertificateEntry("alias", chain[1]);
-
- Provider[] providers = Security.getProviders();
- for (Provider provider : providers) {
- Set<Provider.Service> services = provider.getServices();
- for (Provider.Service service : services) {
- String type = service.getType();
- if (!type.equals("TrustManagerFactory")) {
- continue;
- }
- String algorithm = service.getAlgorithm();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
- tmf.init(keyStore);
- TrustManager[] trustManagers = tmf.getTrustManagers();
- for (TrustManager trustManager : trustManagers) {
- if (!(trustManager instanceof X509TrustManager)) {
- continue;
- }
- X509TrustManager tm = (X509TrustManager) trustManager;
- tm.checkClientTrusted(chain, "RSA");
- tm.checkServerTrusted(chain, "RSA");
- }
- }
- }
- }
-
- @Test
- public void test_TrustManagerFactory_keyOnly() throws Exception {
- // create a KeyStore containing only a private key with chain.
- // unlike PKIXParameters(KeyStore), the cert chain of the key should be trusted.
- KeyStore ks = TestKeyStore.createKeyStore();
- KeyStore.PrivateKeyEntry pke = getTestKeyStore().getPrivateKey("RSA", "RSA");
- ks.setKeyEntry("key", pke.getPrivateKey(), "pw".toCharArray(), pke.getCertificateChain());
-
- String algorithm = TrustManagerFactory.getDefaultAlgorithm();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
- tmf.init(ks);
- X509TrustManager trustManager = (X509TrustManager) tmf.getTrustManagers()[0];
- trustManager.checkServerTrusted((X509Certificate[]) pke.getCertificateChain(), "RSA");
- }
-
- @Test
- public void test_TrustManagerFactory_extendedKeyUsage() throws Exception {
- // anyExtendedKeyUsage should work for client or server
- test_TrustManagerFactory_extendedKeyUsage(
- KeyPurposeId.anyExtendedKeyUsage, false, true, true);
- test_TrustManagerFactory_extendedKeyUsage(
- KeyPurposeId.anyExtendedKeyUsage, true, true, true);
-
- // critical clientAuth should work for client
- test_TrustManagerFactory_extendedKeyUsage(
- KeyPurposeId.id_kp_clientAuth, false, true, false);
- test_TrustManagerFactory_extendedKeyUsage(KeyPurposeId.id_kp_clientAuth, true, true, false);
-
- // critical serverAuth should work for server
- test_TrustManagerFactory_extendedKeyUsage(
- KeyPurposeId.id_kp_serverAuth, false, false, true);
- test_TrustManagerFactory_extendedKeyUsage(KeyPurposeId.id_kp_serverAuth, true, false, true);
-
- // codeSigning should not work
- test_TrustManagerFactory_extendedKeyUsage(
- KeyPurposeId.id_kp_codeSigning, false, false, false);
- test_TrustManagerFactory_extendedKeyUsage(
- KeyPurposeId.id_kp_codeSigning, true, false, false);
- }
-
- private void test_TrustManagerFactory_extendedKeyUsage(KeyPurposeId keyPurposeId,
- boolean critical, boolean client, boolean server) throws Exception {
- String algorithm = "RSA";
- TestKeyStore intermediateCa = TestKeyStore.getIntermediateCa();
- TestKeyStore leaf = new TestKeyStore.Builder()
- .keyAlgorithms(algorithm)
- .aliasPrefix("criticalCodeSigning")
- .signer(intermediateCa.getPrivateKey("RSA", "RSA"))
- .rootCa(intermediateCa.getRootCertificate("RSA"))
- .addExtendedKeyUsage(keyPurposeId, critical)
- .build();
- // leaf.dump("test_TrustManagerFactory_criticalCodeSigning");
- PrivateKeyEntry privateKeyEntry = leaf.getPrivateKey(algorithm, algorithm);
- X509Certificate[] chain = (X509Certificate[]) privateKeyEntry.getCertificateChain();
-
- TestKeyStore rootCa = TestKeyStore.getRootCa();
- X509TrustManager trustManager = (X509TrustManager) rootCa.trustManagers[0];
- try {
- trustManager.checkClientTrusted(chain, algorithm);
- assertTrue(client);
- } catch (Exception e) {
- assertFalse(client);
- }
- try {
- trustManager.checkServerTrusted(chain, algorithm);
- assertTrue(server);
- } catch (Exception e) {
- assertFalse(server);
- }
- }
-}
diff --git a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/X509KeyManagerTest.java b/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/X509KeyManagerTest.java
deleted file mode 100644
index 63ebd55f..00000000
--- a/openjdk-integ-tests/src/test/java/libcore/javax/net/ssl/X509KeyManagerTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.X509KeyManager;
-import libcore.java.security.TestKeyStore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-@RunWith(JUnit4.class)
-public class X509KeyManagerTest extends AbstractSSLTest {
- /**
- * Tests whether the key manager will select the right key when the CA is of
- * one key type and the client is of a possibly different key type.
- *
- * <p>There was a bug where EC was being interpreted as EC_EC and only
- * accepting EC signatures when it should accept any signature type.
- */
- @Test
- public void testChooseClientAlias_Combinations() throws Exception {
- test_ChooseClientAlias_KeyType("RSA", "RSA", "RSA", true);
- test_ChooseClientAlias_KeyType("RSA", "EC", "RSA", true);
- test_ChooseClientAlias_KeyType("RSA", "EC", "EC", false);
-
- test_ChooseClientAlias_KeyType("EC", "RSA", "EC_RSA", true);
- test_ChooseClientAlias_KeyType("EC", "EC", "EC_RSA", false);
-
- test_ChooseClientAlias_KeyType("EC", "EC", "EC_EC", true);
- test_ChooseClientAlias_KeyType("EC", "RSA", "EC_EC", false);
-
- test_ChooseClientAlias_KeyType("EC", "RSA", "RSA", false);
- }
-
- private void test_ChooseClientAlias_KeyType(String clientKeyType, String caKeyType,
- String selectedKeyType, boolean succeeds) throws Exception {
- TestKeyStore ca = new TestKeyStore.Builder().keyAlgorithms(caKeyType).build();
- TestKeyStore client = new TestKeyStore.Builder()
- .keyAlgorithms(clientKeyType)
- .signer(ca.getPrivateKey(caKeyType, caKeyType))
- .build();
-
- KeyManagerFactory kmf =
- KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
- kmf.init(client.keyStore, client.keyPassword);
-
- String[] keyTypes = new String[] {selectedKeyType};
- KeyManager[] managers = kmf.getKeyManagers();
- for (KeyManager manager : managers) {
- if (manager instanceof X509KeyManager) {
- String alias = ((X509KeyManager) manager).chooseClientAlias(keyTypes, null, null);
- if (succeeds) {
- assertNotNull(alias);
- } else {
- assertNull(alias);
- }
- }
- }
- }
-}
diff --git a/openjdk/build.gradle b/openjdk/build.gradle
index 02777a73..898e5a6b 100644
--- a/openjdk/build.gradle
+++ b/openjdk/build.gradle
@@ -11,43 +11,19 @@ ext {
javaExecutable32 = properties['javaExecutable32'] ?: System.env.CONSCRYPT_JAVA_EXECUTABLE_32
javaExecutable64 = properties['javaExecutable64'] ?: System.env.CONSCRYPT_JAVA_EXECUTABLE_64
nativeClassifiers = []
- nativeClassifier64Bit = null
- nativeClassifier32Bit = null
- nativeConfiguration64Bit = null
- nativeConfiguration32Bit = null
- preferredNativeConfiguration = null
- preferredClassifier = null
- preferredSourceSet = null
- preferredNativeFileDir = null
if (build64Bit) {
// Add the 64-Bit classifier first, as the preferred classifier.
- nativeClassifier64Bit = classifierFor(osName, arch64Name)
- nativeClassifiers += nativeClassifier64Bit
- preferredClassifier = nativeClassifier64Bit
- preferredSourceSet = sourceSetName(preferredClassifier)
- preferredNativeFileDir = nativeResourcesDir(preferredClassifier)
-
- nativeConfiguration64Bit = compileConfigurationName(nativeClassifier64Bit)
- preferredNativeConfiguration = nativeConfiguration64Bit
+ nativeClassifiers += classifierFor(osName, arch64Name)
}
if (build32Bit) {
- nativeClassifier32Bit = classifierFor(osName, arch32Name)
- nativeClassifiers += nativeClassifier32Bit
- if (preferredClassifier == null) {
- preferredClassifier = nativeClassifier32Bit
- preferredSourceSet = sourceSetName(preferredClassifier)
- preferredNativeFileDir = nativeResourcesDir(preferredClassifier)
- }
-
- nativeConfiguration32Bit = compileConfigurationName(nativeClassifier32Bit)
- if (preferredNativeConfiguration == null) {
- preferredNativeConfiguration = nativeConfiguration32Bit
- }
+ nativeClassifiers += classifierFor(osName, arch32Name)
}
+
+ // Create a "preferred" configuration that can be used by other modules (e.g. tests/benchmarks)
+ preferredNativeConfiguration = normalizeClassifier(nativeClassifiers[0])
}
sourceSets {
-
main {
java {
srcDirs += "${rootDir}/common/src/main/java"
@@ -61,38 +37,6 @@ sourceSets {
includes = [ "org/conscrypt/Platform.java" ]
}
}
-
- test {
- resources {
- // This shouldn't be needed but seems to help IntelliJ locate the native artifact.
- srcDirs += preferredNativeFileDir
- }
- }
-
- // Add the source sets for each of the native build
- nativeClassifiers.each { nativeClassifier ->
- def sourceSetName = sourceSetName(nativeClassifier)
- def testSourceSetName = testSourceSetName(nativeClassifier)
-
- // Main sources for the native build
- "$sourceSetName" {
- resources {
- srcDirs = [nativeResourcesDir(nativeClassifier)]
- }
- }
-
- // Test sources for the native build
- "${testSourceSetName}" {
- java {
- // Include the test source.
- srcDirs = test.java.srcDirs
- }
- resources {
- srcDirs = ["src/test/resources"]
- srcDirs += sourceSets["$sourceSetName"].resources.srcDirs
- }
- }
- }
}
task platformJar(type: Jar) {
@@ -120,73 +64,84 @@ dependencies {
compileOnly project(':conscrypt-constants')
testCompile project(':conscrypt-constants'),
- project(':conscrypt-testing'),
- libraries.junit,
- libraries.mockito
-
- // Need to add the native artifact to classpath when running the tests.
- testRuntime configurations["${preferredNativeConfiguration}"]
-
- // Configure the dependencies for the native tests.
- nativeClassifiers.each { nativeClassifier ->
- def testCompileConfigName = testSourceSet(nativeClassifier).compileConfigurationName
- "${testCompileConfigName}" (
- sourceSets.main.output, // Explicitly add the main classes
- project(':conscrypt-constants'),
project(':conscrypt-testing'),
libraries.junit,
libraries.mockito
- )
- }
platformCompileOnly sourceSets.main.output
}
+javadoc {
+ options.doclet = "org.conscrypt.doclet.FilterDoclet"
+ options.docletpath = configurations.publicApiDocs.files as List
+}
+
+/**
+ * Create Jar and Test tasks for each native classifier.
+ */
nativeClassifiers.each { nativeClassifier ->
+ // Create all native configurations
+ addNativeSourceSet(nativeClassifier)
+ addNativeSourceSet("${nativeClassifier}Test")
+
// Create the JAR task and add it's output to the published archives for this project
addNativeJar(nativeClassifier)
// Create the test task and have it auto run whenever the test task runs.
addNativeTest(nativeClassifier)
+}
+
+def nativeFileDir(nativeClassifier) {
+ def normalizedClassifier = normalizeClassifier(nativeClassifier)
+ "${buildDir}/${normalizedClassifier}/resources/main"
+}
+
+// Creates a source set (and resulting configurations) containing only the
+// native shared library.
+def addNativeSourceSet(nativeClassifier) {
+ def normalizedClassifier = normalizeClassifier(nativeClassifier)
- // Build the classes as part of the standard build.
- classes.dependsOn sourceSet(nativeClassifier).classesTaskName
- testClasses.dependsOn testSourceSet(nativeClassifier).classesTaskName
+ // Create a configuration which will contain the artifact.
+ configurations.create(normalizedClassifier)
+
+ // Create a new source set. This will automatically create configurations for:
+ // ${normalizedClassifier}Compile
+ // ${normalizedClassifier}Runtime
+ def sources = sourceSets.create(normalizedClassifier)
+ sources.resources {
+ srcDirs += files(nativeFileDir(nativeClassifier))
+ }
}
// Adds a JAR task for the native library.
def addNativeJar(nativeClassifier) {
+ def normalizedClassifier = normalizeClassifier(nativeClassifier)
// Create a JAR for this configuration and add it to the output archives.
- SourceSet sourceSet = sourceSet(nativeClassifier)
- def jarTaskName = sourceSet.jarTaskName
+ def jarTaskName = "create${normalizedClassifier}Jar"
+ // The testRuntime configuration is created automatically when we created the source set.
+ def testRuntimeConfigName = "${normalizedClassifier}TestRuntime"
task "$jarTaskName"(type: Jar) {
- // Depend on the regular classes task
dependsOn classes
+ dependsOn configurations[testRuntimeConfigName]
+ from sourceSets.main.output + files(nativeFileDir(nativeClassifier))
manifest = jar.manifest
classifier = nativeClassifier
-
- from sourceSet.output + sourceSets.main.output
}
-
- def jarTask = tasks["$jarTaskName"]
-
- // Add the jar task to the standard build.
- jar.dependsOn jarTask
-
// Add it to the 'archives' configuration so that the artifact will be automatically built and
// installed/deployed.
- artifacts.add('archives', jarTask)
+ artifacts.add('archives', tasks["$jarTaskName"])
+
+ // Also add the artifact to its own configuration so that it can be referenced from other projects.
+ artifacts.add(normalizedClassifier, tasks["$jarTaskName"])
}
// Optionally adds a test task for the given platform
def addNativeTest(nativeClassifier) {
- SourceSet testSourceSet = testSourceSet(nativeClassifier)
-
- // Just use the same name as the source set for the task.
- def testTaskName = "${testSourceSet.name}"
+ def normalizedClassifier = normalizeClassifier(nativeClassifier)
+ def testTaskName = "${normalizedClassifier}Test"
def javaExecutable
def javaArchFlag
- if (testSourceSet.name.endsWith(arch32Name)) {
+ if (normalizedClassifier.endsWith(arch32Name)) {
// 32-bit test
javaExecutable = javaExecutable32 != null ? javaExecutable32 : test.executable
javaArchFlag = '-d32'
@@ -209,16 +164,10 @@ def addNativeTest(nativeClassifier) {
def archSupported = !javaError.toString().toLowerCase().contains('error')
if (archSupported) {
task "$testTaskName"(type: Test) {
- dependsOn testSourceSet.classesTaskName
+ testClassesDir = test.testClassesDir
+ classpath = test.classpath + files(nativeFileDir(nativeClassifier))
jvmArgs javaArchFlag
executable = javaExecutable
- testClassesDir = testSourceSet.output.classesDir
-
- // Set the classpath just before we run the test so that the runtime classpath
- // is fully resolved.
- doFirst {
- classpath = testSourceSet.runtimeClasspath
- }
}
test.dependsOn "$testTaskName"
}
@@ -228,11 +177,6 @@ def addNativeTest(nativeClassifier) {
// We will test each available native artifact separately (see nativeClassifiers).
test.exclude("**")
-javadoc {
- options.doclet = "org.conscrypt.doclet.FilterDoclet"
- options.docletpath = configurations.publicApiDocs.files as List
-}
-
model {
platforms {
x86 {
@@ -355,17 +299,17 @@ model {
// Build the native artifact classifier from the OS and architecture.
def archName = binary.targetPlatform.architecture.name.replaceAll('-', '_')
def classifier = classifierFor(osName, archName)
- def sourceSetName = sourceSetName("$classifier")
+ def normalizedClassifier = normalizeClassifier("$classifier")
def source = binary.sharedLibraryFile
// Copies the native library to a resource location that will be included in the jar.
- def copyTaskName = "copyNativeLib${sourceSetName}"
+ def copyTaskName = "copyNativeLib${normalizedClassifier}"
task "$copyTaskName"(type: Copy, dependsOn: binary.buildTask) {
from source
// Rename the artifact to include the generated classifier
rename '(.+)(\\.[^\\.]+)', "\$1-$classifier\$2"
- // Everything under will be included in the native jar.
- into nativeResourcesDir(classifier) + '/META-INF/native'
+ // This location will automatically be included in the jar.
+ into "${buildDir}/${normalizedClassifier}/resources/main/META-INF/native"
}
// Make sure we build and copy the native library to the output directory.
@@ -386,32 +330,15 @@ model {
}
}
-String nativeResourcesDir(nativeClassifier) {
- def sourceSetName = sourceSetName(nativeClassifier)
- "${buildDir}/${sourceSetName}/resources"
+static classifierFor(osName, archName) {
+ return "${osName}-${archName}"
}
-SourceSet sourceSet(classifier) {
- sourceSets[sourceSetName(classifier)]
+static normalizeClassifier(classifier) {
+ return classifier.replaceAll("-", "_")
}
-SourceSet testSourceSet(classifier) {
- sourceSets[testSourceSetName(classifier)]
+// Manually add the native library to help IntelliJ run tests.
+idea.module {
+ scopes.PROVIDED.plus += [ configurations["$preferredNativeConfiguration"] ]
}
-
-static String classifierFor(osName, archName) {
- "${osName}-${archName}"
-}
-
-static String sourceSetName(classifier) {
- classifier.replaceAll("-", "_")
-}
-
-static String testSourceSetName(classifier) {
- "${sourceSetName(classifier)}Test"
-}
-
-static String compileConfigurationName(classifier) {
- sourceSetName(classifier) + "Compile"
-}
-
diff --git a/openjdk/src/main/java/org/conscrypt/Platform.java b/openjdk/src/main/java/org/conscrypt/Platform.java
index 090980ac..6708cda3 100644
--- a/openjdk/src/main/java/org/conscrypt/Platform.java
+++ b/openjdk/src/main/java/org/conscrypt/Platform.java
@@ -17,9 +17,7 @@
package org.conscrypt;
import java.io.FileDescriptor;
-import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
@@ -37,19 +35,22 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.crypto.spec.GCMParameterSpec;
+import javax.net.ssl.SNIHostName;
+import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.StandardConstants;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.net.ssl.X509TrustManager;
import sun.security.x509.AlgorithmId;
/**
- * Platform-specific methods for OpenJDK.
- *
- * Uses reflection to implement Java 8 SSL features for backwards compatibility.
+ * Platform-specific methods for OpenJDK
*/
final class Platform {
+ private static final String TAG = "Conscrypt";
+
private static Method m_getCurveName;
static {
try {
@@ -59,9 +60,11 @@ final class Platform {
}
}
- private Platform() {}
+ private Platform() {
+ }
- static void setup() {}
+ static void setup() {
+ }
static FileDescriptor getFileDescriptor(Socket s) {
try {
@@ -102,139 +105,91 @@ final class Platform {
}
}
- static void setCurveName(@SuppressWarnings("unused") ECParameterSpec spec,
- @SuppressWarnings("unused") String curveName) {
+ static void setCurveName(ECParameterSpec spec, String curveName) {
// This doesn't appear to be needed.
}
/*
* Call Os.setsockoptTimeval via reflection.
*/
- static void setSocketWriteTimeout(@SuppressWarnings("unused") Socket s,
- @SuppressWarnings("unused") long timeoutMillis) throws SocketException {
+ static void setSocketWriteTimeout(Socket s, long timeoutMillis) throws SocketException {
// TODO: figure this out on the RI
}
- @SuppressWarnings("unchecked")
- public static void setSSLParameters(
- SSLParameters params, SSLParametersImpl impl, OpenSSLSocketImpl socket) {
+ static void setSSLParameters(SSLParameters params, SSLParametersImpl impl,
+ OpenSSLSocketImpl socket) {
impl.setEndpointIdentificationAlgorithm(params.getEndpointIdentificationAlgorithm());
- try {
- Method getUseCipherSuitesOrder =
- SSLParameters.class.getMethod("getUseCipherSuitesOrder");
- impl.setUseCipherSuitesOrder((boolean) getUseCipherSuitesOrder.invoke(params));
- Method getServerNames = SSLParameters.class.getMethod("getServerNames");
- List<Object> serverNames = (List<Object>) getServerNames.invoke(params);
-
- // javax.net.ssl.StandardConstants.SNI_HOST_NAME
- int hostNameType = 0;
- if (serverNames != null) {
- for (Object serverName : serverNames) {
- if ((int) serverName.getClass().getMethod("getType").invoke(serverName)
- == hostNameType) {
- socket.setHostname((String) serverName.getClass()
- .getMethod("getAsciiName")
- .invoke(serverName));
- break;
- }
+ impl.setUseCipherSuitesOrder(params.getUseCipherSuitesOrder());
+ List<SNIServerName> serverNames = params.getServerNames();
+ if (serverNames != null) {
+ for (SNIServerName serverName : serverNames) {
+ if (serverName.getType() == StandardConstants.SNI_HOST_NAME) {
+ socket.setHostname(((SNIHostName) serverName).getAsciiName());
+ break;
}
}
- } catch (NoSuchMethodException ignored) {
- } catch (IllegalAccessException ignored) {
- } catch (InvocationTargetException ignored) {
}
}
- @SuppressWarnings({"LiteralClassName", "rawtypes"})
- public static void getSSLParameters(
- SSLParameters params, SSLParametersImpl impl, OpenSSLSocketImpl socket) {
+ static void getSSLParameters(SSLParameters params, SSLParametersImpl impl,
+ OpenSSLSocketImpl socket) {
params.setEndpointIdentificationAlgorithm(impl.getEndpointIdentificationAlgorithm());
- try {
- Method setUseCipherSuitesOrder =
- SSLParameters.class.getMethod("setUseCipherSuitesOrder", boolean.class);
- setUseCipherSuitesOrder.invoke(params, impl.getUseCipherSuitesOrder());
- Method setServerNames = SSLParameters.class.getMethod("setServerNames", List.class);
- if (impl.getUseSni() && AddressUtils.isValidSniHostname(socket.getHostname())) {
- Constructor sniHostNameConstructor =
- Class.forName("javax.net.ssl.SNIHostName").getConstructor(String.class);
- setServerNames.invoke(params,
- (Collections.singletonList(
- sniHostNameConstructor.newInstance(socket.getHostname()))));
- }
- } catch (NoSuchMethodException ignored) {
- } catch (IllegalAccessException ignored) {
- } catch (InvocationTargetException ignored) {
- } catch (ClassNotFoundException ignored) {
- } catch (InstantiationException ignored) {
+ params.setUseCipherSuitesOrder(impl.getUseCipherSuitesOrder());
+ if (impl.getUseSni() && AddressUtils.isValidSniHostname(socket.getHostname())) {
+ params.setServerNames(Collections.<SNIServerName> singletonList(
+ new SNIHostName(socket.getHostname())));
}
}
- @SuppressWarnings("unchecked")
- public static void setSSLParameters(
+ static void setSSLParameters(
SSLParameters params, SSLParametersImpl impl, OpenSSLEngineImpl engine) {
impl.setEndpointIdentificationAlgorithm(params.getEndpointIdentificationAlgorithm());
- try {
- Method getUseCipherSuitesOrder =
- SSLParameters.class.getMethod("getUseCipherSuitesOrder");
- impl.setUseCipherSuitesOrder((boolean) getUseCipherSuitesOrder.invoke(params));
- Method getServerNames = SSLParameters.class.getMethod("getServerNames");
- List<Object> serverNames = (List<Object>) getServerNames.invoke(params);
-
- int hostNameType = 0;
- if (serverNames != null) {
- for (Object serverName : serverNames) {
- if ((int) serverName.getClass().getMethod("getType").invoke(serverName)
- == hostNameType) {
- engine.setSniHostname((String) serverName.getClass()
- .getMethod("getAsciiName")
- .invoke(serverName));
- break;
- }
+ impl.setUseCipherSuitesOrder(params.getUseCipherSuitesOrder());
+ List<SNIServerName> serverNames = params.getServerNames();
+ if (serverNames != null) {
+ for (SNIServerName serverName : serverNames) {
+ if (serverName.getType() == StandardConstants.SNI_HOST_NAME) {
+ engine.setSniHostname(((SNIHostName) serverName).getAsciiName());
+ break;
}
}
- } catch (NoSuchMethodException ignored) {
- } catch (IllegalAccessException ignored) {
- } catch (InvocationTargetException ignored) {
}
}
- @SuppressWarnings({"LiteralClassName", "rawtypes"})
- public static void getSSLParameters(
+ static void getSSLParameters(
SSLParameters params, SSLParametersImpl impl, OpenSSLEngineImpl engine) {
params.setEndpointIdentificationAlgorithm(impl.getEndpointIdentificationAlgorithm());
- try {
- Method setUseCipherSuitesOrder =
- SSLParameters.class.getMethod("setUseCipherSuitesOrder", boolean.class);
- setUseCipherSuitesOrder.invoke(params, impl.getUseCipherSuitesOrder());
- Method setServerNames = SSLParameters.class.getMethod("setServerNames", List.class);
- if (impl.getUseSni() && AddressUtils.isValidSniHostname(engine.getSniHostname())) {
- Constructor sniHostNameConstructor =
- Class.forName("javax.net.ssl.SNIHostName").getConstructor(String.class);
- setServerNames.invoke(params,
- (Collections.singletonList(
- sniHostNameConstructor.newInstance(engine.getSniHostname()))));
+ params.setUseCipherSuitesOrder(impl.getUseCipherSuitesOrder());
+ if (impl.getUseSni() && AddressUtils.isValidSniHostname(engine.getSniHostname())) {
+ params.setServerNames(Collections.<SNIServerName>singletonList(
+ new SNIHostName(engine.getSniHostname())));
+ }
+ }
+
+ /**
+ * Tries to return a Class reference of one of the supplied class names.
+ */
+ private static Class<?> getClass(String... klasses) {
+ for (String klass : klasses) {
+ try {
+ return Class.forName(klass);
+ } catch (Exception ignored) {
}
- } catch (NoSuchMethodException ignored) {
- } catch (IllegalAccessException ignored) {
- } catch (InvocationTargetException ignored) {
- } catch (ClassNotFoundException ignored) {
- } catch (InstantiationException ignored) {
}
+ return null;
}
- @SuppressWarnings("unused")
- static void setEndpointIdentificationAlgorithm(
- SSLParameters params, String endpointIdentificationAlgorithm) {
+ static void setEndpointIdentificationAlgorithm(SSLParameters params,
+ String endpointIdentificationAlgorithm) {
params.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm);
}
- @SuppressWarnings("unused")
static String getEndpointIdentificationAlgorithm(SSLParameters params) {
return params.getEndpointIdentificationAlgorithm();
}
- static void checkClientTrusted(X509TrustManager tm, X509Certificate[] chain, String authType,
- OpenSSLSocketImpl socket) throws CertificateException {
+ static void checkClientTrusted(X509TrustManager tm, X509Certificate[] chain,
+ String authType, OpenSSLSocketImpl socket) throws CertificateException {
if (tm instanceof X509ExtendedTrustManager) {
X509ExtendedTrustManager x509etm = (X509ExtendedTrustManager) tm;
x509etm.checkClientTrusted(chain, authType, socket);
@@ -243,8 +198,8 @@ final class Platform {
}
}
- static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain, String authType,
- OpenSSLSocketImpl socket) throws CertificateException {
+ static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain,
+ String authType, OpenSSLSocketImpl socket) throws CertificateException {
if (tm instanceof X509ExtendedTrustManager) {
X509ExtendedTrustManager x509etm = (X509ExtendedTrustManager) tm;
x509etm.checkServerTrusted(chain, authType, socket);
@@ -253,8 +208,8 @@ final class Platform {
}
}
- static void checkClientTrusted(X509TrustManager tm, X509Certificate[] chain, String authType,
- OpenSSLEngineImpl engine) throws CertificateException {
+ static void checkClientTrusted(X509TrustManager tm, X509Certificate[] chain,
+ String authType, OpenSSLEngineImpl engine) throws CertificateException {
if (tm instanceof X509ExtendedTrustManager) {
X509ExtendedTrustManager x509etm = (X509ExtendedTrustManager) tm;
x509etm.checkClientTrusted(chain, authType, engine);
@@ -263,8 +218,8 @@ final class Platform {
}
}
- static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain, String authType,
- OpenSSLEngineImpl engine) throws CertificateException {
+ static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain,
+ String authType, OpenSSLEngineImpl engine) throws CertificateException {
if (tm instanceof X509ExtendedTrustManager) {
X509ExtendedTrustManager x509etm = (X509ExtendedTrustManager) tm;
x509etm.checkServerTrusted(chain, authType, engine);
@@ -276,14 +231,15 @@ final class Platform {
/**
* Wraps an old AndroidOpenSSL key instance. This is not needed on RI.
*/
- static OpenSSLKey wrapRsaKey(@SuppressWarnings("unused") PrivateKey javaKey) {
+ static OpenSSLKey wrapRsaKey(PrivateKey javaKey) {
return null;
}
/**
* Logs to the system EventLog system.
*/
- static void logEvent(@SuppressWarnings("unused") String message) {}
+ static void logEvent(String message) {
+ }
/**
* Returns true if the supplied hostname is an literal IP address.
@@ -296,7 +252,6 @@ final class Platform {
/**
* For unbundled versions, SNI is always enabled by default.
*/
- @SuppressWarnings("unused")
static boolean isSniEnabledByDefault() {
return true;
}
@@ -334,18 +289,21 @@ final class Platform {
return null;
}
- static void closeGuardOpen(@SuppressWarnings("unused") Object guardObj,
- @SuppressWarnings("unused") String message) {}
+ static void closeGuardOpen(Object guardObj, String message) {
+ }
- static void closeGuardClose(@SuppressWarnings("unused") Object guardObj) {}
+ static void closeGuardClose(Object guardObj) {
+ }
- static void closeGuardWarnIfOpen(@SuppressWarnings("unused") Object guardObj) {}
+ static void closeGuardWarnIfOpen(Object guardObj) {
+ }
/*
* BlockGuard functions.
*/
- static void blockGuardOnNetwork() {}
+ static void blockGuardOnNetwork() {
+ }
/**
* OID to Algorithm Name mapping.
@@ -366,7 +324,6 @@ final class Platform {
return new OpenSSLExtendedSessionImpl(sslSession);
}
- @SuppressWarnings("unused")
static SSLSession unwrapSSLSession(SSLSession sslSession) {
if (sslSession instanceof OpenSSLExtendedSessionImpl) {
return ((OpenSSLExtendedSessionImpl) sslSession).getDelegate();
@@ -404,7 +361,7 @@ final class Platform {
}
String property = Security.getProperty("conscrypt.ct.enable");
- if (property == null || !Boolean.valueOf(property.toLowerCase())) {
+ if (property == null || Boolean.valueOf(property.toLowerCase()) == false) {
return false;
}
@@ -412,19 +369,19 @@ final class Platform {
Collections.reverse(parts);
boolean enable = false;
- StringBuilder propertyName = new StringBuilder("conscrypt.ct.enforce");
+ String propertyName = "conscrypt.ct.enforce";
// The loop keeps going on even once we've found a match
// This allows for finer grained settings on subdomains
- for (String part : parts) {
+ for (String part: parts) {
property = Security.getProperty(propertyName + ".*");
if (property != null) {
enable = Boolean.valueOf(property.toLowerCase());
}
- propertyName.append(".").append(part);
+ propertyName = propertyName + "." + part;
}
- property = Security.getProperty(propertyName.toString());
+ property = Security.getProperty(propertyName);
if (property != null) {
enable = Boolean.valueOf(property.toLowerCase());
}
diff --git a/openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java b/openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java
index e684e1a0..96687879 100644
--- a/openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java
+++ b/openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java
@@ -99,7 +99,8 @@ public class NativeCryptoTest {
@BeforeClass
public static void getPlatformMethods() throws Exception {
- Class<?> c_Platform = TestUtils.conscryptClass("Platform");
+ Class<?> c_Platform =
+ Class.forName(NativeCryptoTest.class.getPackage().getName() + ".Platform");
m_Platform_getFileDescriptor =
c_Platform.getDeclaredMethod("getFileDescriptor", Socket.class);
m_Platform_getFileDescriptor.setAccessible(true);
@@ -2255,11 +2256,15 @@ public class NativeCryptoTest {
@Test
public void test_SSL_shutdown() throws Exception {
- // We tolerate a null FileDescriptor
+ // null FileDescriptor
wrapWithSSLSession(new SSLSessionWrappedTask() {
@Override
public void run(long sslSession) throws Exception {
- NativeCrypto.SSL_shutdown(sslSession, null, DUMMY_CB);
+ try {
+ NativeCrypto.SSL_shutdown(sslSession, null, DUMMY_CB);
+ fail();
+ } catch (NullPointerException expected) {
+ }
}
});
@@ -2271,7 +2276,6 @@ public class NativeCryptoTest {
NativeCrypto.SSL_shutdown(sslSession, INVALID_FD, null);
fail();
} catch (NullPointerException expected) {
- // Ignored.
}
}
});
diff --git a/openjdk/src/test/java/org/conscrypt/OpenSSLEngineImplTest.java b/openjdk/src/test/java/org/conscrypt/OpenSSLEngineImplTest.java
index 27df90e8..02ee53ed 100644
--- a/openjdk/src/test/java/org/conscrypt/OpenSSLEngineImplTest.java
+++ b/openjdk/src/test/java/org/conscrypt/OpenSSLEngineImplTest.java
@@ -189,7 +189,7 @@ public class OpenSSLEngineImplTest {
@Test
public void exchangeLargeMessage() throws Exception {
setupEngines(TestKeyStore.getClient(), TestKeyStore.getServer());
- TestUtils.doEngineHandshake(clientEngine, serverEngine);
+ TestUtil.doEngineHandshake(clientEngine, serverEngine);
// Create the input message.
final int largeMessageSize = 16413;
diff --git a/openjdk/src/test/java/org/conscrypt/OpenSSLExtendedSessionImplTest.java b/openjdk/src/test/java/org/conscrypt/OpenSSLExtendedSessionImplTest.java
deleted file mode 100644
index f3414a92..00000000
--- a/openjdk/src/test/java/org/conscrypt/OpenSSLExtendedSessionImplTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- *
- * 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 impli$
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.conscrypt;
-
-import java.util.List;
-import javax.net.ssl.ExtendedSSLSession;
-import javax.net.ssl.SNIHostName;
-import javax.net.ssl.SNIServerName;
-import junit.framework.TestCase;
-
-/**
- * Test for OpenSSLExtendedSessionImpl
- */
-public class OpenSSLExtendedSessionImplTest extends TestCase {
- static class MockSSLSession extends OpenSSLSessionImpl {
- MockSSLSession() {
- super(0, null, null, null, null, null, 0, null);
- }
-
- @Override
- public String getRequestedServerName() {
- return "server.name";
- }
- }
-
- public void test_getRequestedServerNames() {
- AbstractOpenSSLSession session = new MockSSLSession();
- ExtendedSSLSession extendedSession = new OpenSSLExtendedSessionImpl(session);
- List<SNIServerName> names = extendedSession.getRequestedServerNames();
- assertEquals("server.name", ((SNIHostName) names.get(0)).getAsciiName());
- }
-}
diff --git a/openjdk/src/test/java/org/conscrypt/OpenSSLSocketImplTest.java b/openjdk/src/test/java/org/conscrypt/OpenSSLSocketImplTest.java
index 8c59e8f2..8689dbb9 100644
--- a/openjdk/src/test/java/org/conscrypt/OpenSSLSocketImplTest.java
+++ b/openjdk/src/test/java/org/conscrypt/OpenSSLSocketImplTest.java
@@ -25,16 +25,15 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
+import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
-import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
-import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
-import java.util.Arrays;
+import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -48,119 +47,48 @@ import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
-import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameter;
-import org.junit.runners.Parameterized.Parameters;
-@RunWith(Parameterized.class)
public class OpenSSLSocketImplTest {
private static final long TIMEOUT_SECONDS = 5;
private static final char[] EMPTY_PASSWORD = new char[0];
- /**
- * Various factories for SSL server sockets.
- */
- public enum SocketType {
- DEFAULT(false) {
- @Override
- void assertSocketType(Socket socket) {
- assertTrue("Unexpected socket type: " + socket.getClass().getName(),
- socket instanceof OpenSSLSocketImpl);
- }
- },
- ENGINE(true) {
- @Override
- void assertSocketType(Socket socket) {
- assertTrue("Unexpected socket type: " + socket.getClass().getName(),
- socket instanceof OpenSSLEngineSocketImpl);
- }
- };
-
- private final boolean useEngineSocket;
-
- SocketType(boolean useEngineSocket) {
- this.useEngineSocket = useEngineSocket;
- }
-
- OpenSSLSocketImpl createClientSocket(OpenSSLContextImpl context, ServerSocket listener)
- throws IOException {
- SSLSocketFactory factory = context.engineGetSocketFactory();
- Conscrypt.SocketFactories.setUseEngineSocket(factory, useEngineSocket);
- OpenSSLSocketImpl socket = (OpenSSLSocketImpl) factory.createSocket(
- listener.getInetAddress(), listener.getLocalPort());
- assertSocketType(socket);
- socket.setUseClientMode(true);
- return socket;
- }
-
- OpenSSLSocketImpl createServerSocket(OpenSSLContextImpl context, ServerSocket listener)
- throws IOException {
- SSLSocketFactory factory = context.engineGetSocketFactory();
- Conscrypt.SocketFactories.setUseEngineSocket(factory, useEngineSocket);
- OpenSSLSocketImpl socket = (OpenSSLSocketImpl) factory.createSocket(listener.accept(),
- null, -1, // hostname, port
- true); // autoclose
- assertSocketType(socket);
- socket.setUseClientMode(false);
- return socket;
- }
-
- abstract void assertSocketType(Socket socket);
- }
-
- @Parameters(name = "{0}")
- public static Iterable<SocketType> data() {
- return Arrays.asList(SocketType.DEFAULT, SocketType.ENGINE);
- }
-
- @Parameter public SocketType socketType;
-
private X509Certificate ca;
private X509Certificate cert;
private X509Certificate certEmbedded;
private PrivateKey certKey;
private Field contextSSLParameters;
- private ExecutorService executor;
+ private Field sslParametersTrustManager;
@Before
public void setUp() throws Exception {
contextSSLParameters = OpenSSLContextImpl.class.getDeclaredField("sslParameters");
contextSSLParameters.setAccessible(true);
+ sslParametersTrustManager = SSLParametersImpl.class.getDeclaredField("x509TrustManager");
+ sslParametersTrustManager.setAccessible(true);
+
ca = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("ca-cert.pem"));
cert = OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("cert.pem"));
certEmbedded =
OpenSSLX509Certificate.fromX509PemInputStream(openTestFile("cert-ct-embedded.pem"));
certKey = OpenSSLKey.fromPrivateKeyPemInputStream(openTestFile("cert-key.pem"))
.getPrivateKey();
- executor = Executors.newCachedThreadPool();
- }
-
- @After
- public void teardown() throws Exception {
- executor.shutdown();
- executor.awaitTermination(5, TimeUnit.SECONDS);
}
abstract class Hooks implements HandshakeCompletedListener {
KeyManager[] keyManagers;
TrustManager[] trustManagers;
- abstract OpenSSLSocketImpl createSocket(ServerSocket listener) throws IOException;
+ abstract OpenSSLSocketImpl createSocket(SSLSocketFactory factory, ServerSocket listener)
+ throws IOException;
- OpenSSLContextImpl createContext() throws IOException {
+ public OpenSSLContextImpl createContext() throws Exception {
OpenSSLContextImpl context = OpenSSLContextImpl.getPreferred();
- try {
- context.engineInit(keyManagers, trustManagers, null);
- } catch (KeyManagementException e) {
- throw new IOException(e);
- }
+ context.engineInit(keyManagers, trustManagers, null);
return context;
}
@@ -170,31 +98,39 @@ public class OpenSSLSocketImplTest {
isHandshakeCompleted = true;
}
- SSLParametersImpl getContextSSLParameters(OpenSSLContextImpl context)
+ protected SSLParametersImpl getContextSSLParameters(OpenSSLContextImpl context)
throws IllegalAccessException {
return (SSLParametersImpl) contextSSLParameters.get(context);
}
+
+ protected TrustManager getSSLParametersTrustManager(SSLParametersImpl params)
+ throws IllegalAccessException {
+ return (TrustManager) sslParametersTrustManager.get(params);
+ }
}
class ClientHooks extends Hooks {
+ boolean ctVerificationEnabled;
String hostname = "example.com";
@Override
- public OpenSSLContextImpl createContext() throws IOException {
+ public OpenSSLContextImpl createContext() throws Exception {
OpenSSLContextImpl context = super.createContext();
- try {
- SSLParametersImpl sslParameters = getContextSSLParameters(context);
- sslParameters.setCTVerificationEnabled(true);
- } catch (IllegalAccessException e) {
- throw new IOException(e);
+ SSLParametersImpl sslParameters = getContextSSLParameters(context);
+ if (ctVerificationEnabled) {
+ sslParameters.setCTVerificationEnabled(ctVerificationEnabled);
}
return context;
}
@Override
- OpenSSLSocketImpl createSocket(ServerSocket listener) throws IOException {
- OpenSSLSocketImpl socket = socketType.createClientSocket(createContext(), listener);
+ public OpenSSLSocketImpl createSocket(SSLSocketFactory factory, ServerSocket listener)
+ throws IOException {
+ OpenSSLSocketImpl socket = (OpenSSLSocketImpl) factory.createSocket(
+ listener.getInetAddress(), listener.getLocalPort());
+ socket.setUseClientMode(true);
socket.setHostname(hostname);
+
return socket;
}
}
@@ -204,21 +140,22 @@ public class OpenSSLSocketImplTest {
byte[] ocspResponse;
@Override
- public OpenSSLContextImpl createContext() throws IOException {
+ public OpenSSLContextImpl createContext() throws Exception {
OpenSSLContextImpl context = super.createContext();
- try {
- SSLParametersImpl sslParameters = getContextSSLParameters(context);
- sslParameters.setSCTExtension(sctTLSExtension);
- sslParameters.setOCSPResponse(ocspResponse);
- return context;
- } catch (IllegalAccessException e) {
- throw new IOException(e);
- }
+ SSLParametersImpl sslParameters = getContextSSLParameters(context);
+ sslParameters.setSCTExtension(sctTLSExtension);
+ sslParameters.setOCSPResponse(ocspResponse);
+ return context;
}
@Override
- OpenSSLSocketImpl createSocket(ServerSocket listener) throws IOException {
- return socketType.createServerSocket(createContext(), listener);
+ public OpenSSLSocketImpl createSocket(SSLSocketFactory factory, ServerSocket listener)
+ throws IOException {
+ OpenSSLSocketImpl socket = (OpenSSLSocketImpl) factory.createSocket(listener.accept(),
+ null, -1, // hostname, port
+ true); // autoclose
+ socket.setUseClientMode(false);
+ return socket;
}
}
@@ -232,7 +169,7 @@ public class OpenSSLSocketImplTest {
Exception clientException;
Exception serverException;
- TestConnection(X509Certificate[] chain, PrivateKey key) throws Exception {
+ public TestConnection(X509Certificate[] chain, PrivateKey key) throws Exception {
clientHooks = new ClientHooks();
serverHooks = new ServerHooks();
setCertificates(chain, key);
@@ -272,11 +209,12 @@ public class OpenSSLSocketImplTest {
}
}
- void doHandshake() throws Exception {
- ServerSocket listener = newServerSocket();
+ public void doHandshake() throws Exception {
+ ServerSocket listener = new ServerSocket(0);
Future<OpenSSLSocketImpl> clientFuture = handshake(listener, clientHooks);
Future<OpenSSLSocketImpl> serverFuture = handshake(listener, serverHooks);
+ Exception cause = null;
try {
client = getOrThrowCause(clientFuture, TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (Exception e) {
@@ -290,14 +228,24 @@ public class OpenSSLSocketImplTest {
}
Future<OpenSSLSocketImpl> handshake(final ServerSocket listener, final Hooks hooks) {
- return executor.submit(() -> {
- OpenSSLSocketImpl socket = hooks.createSocket(listener);
- socket.addHandshakeCompletedListener(hooks);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ Future<OpenSSLSocketImpl> future = executor.submit(new Callable<OpenSSLSocketImpl>() {
+ @Override
+ public OpenSSLSocketImpl call() throws Exception {
+ OpenSSLContextImpl context = hooks.createContext();
+ SSLSocketFactory factory = context.engineGetSocketFactory();
+ OpenSSLSocketImpl socket = hooks.createSocket(factory, listener);
+ socket.addHandshakeCompletedListener(hooks);
+
+ socket.startHandshake();
+
+ return socket;
+ }
+ });
- socket.startHandshake();
+ executor.shutdown();
- return socket;
- });
+ return future;
}
}
@@ -315,6 +263,8 @@ public class OpenSSLSocketImplTest {
TestConnection connection =
new TestConnection(new X509Certificate[] {certEmbedded, ca}, certKey);
+ connection.clientHooks.ctVerificationEnabled = true;
+
connection.doHandshake();
assertTrue(connection.clientHooks.isHandshakeCompleted);
@@ -325,6 +275,7 @@ public class OpenSSLSocketImplTest {
public void test_handshakeWithSCTFromOCSPResponse() throws Exception {
TestConnection connection = new TestConnection(new X509Certificate[] {cert, ca}, certKey);
+ connection.clientHooks.ctVerificationEnabled = true;
connection.serverHooks.ocspResponse = readTestFile("ocsp-response.der");
connection.doHandshake();
@@ -337,6 +288,7 @@ public class OpenSSLSocketImplTest {
public void test_handshakeWithSCTFromTLSExtension() throws Exception {
TestConnection connection = new TestConnection(new X509Certificate[] {cert, ca}, certKey);
+ connection.clientHooks.ctVerificationEnabled = true;
connection.serverHooks.sctTLSExtension = readTestFile("ct-signed-timestamp-list");
connection.doHandshake();
@@ -350,6 +302,8 @@ public class OpenSSLSocketImplTest {
public void test_handshake_failsWithMissingSCT() throws Exception {
TestConnection connection = new TestConnection(new X509Certificate[] {cert, ca}, certKey);
+ connection.clientHooks.ctVerificationEnabled = true;
+
connection.doHandshake();
assertThat(connection.clientException, instanceOf(SSLHandshakeException.class));
assertThat(connection.clientException.getCause(), instanceOf(CertificateException.class));
@@ -360,6 +314,7 @@ public class OpenSSLSocketImplTest {
public void test_handshake_failsWithInvalidSCT() throws Exception {
TestConnection connection = new TestConnection(new X509Certificate[] {cert, ca}, certKey);
+ connection.clientHooks.ctVerificationEnabled = true;
connection.serverHooks.sctTLSExtension = readTestFile("ct-signed-timestamp-list-invalid");
connection.doHandshake();
@@ -370,18 +325,20 @@ public class OpenSSLSocketImplTest {
// http://b/27250522
@Test
public void test_setSoTimeout_doesNotCreateSocketImpl() throws Exception {
- ServerSocket listening = newServerSocket();
+ ServerSocket listening = new ServerSocket(0);
Socket underlying = new Socket(listening.getInetAddress(), listening.getLocalPort());
- Socket socket = TestUtils.getConscryptSocketFactory(socketType == SocketType.ENGINE)
- .createSocket(underlying, null, listening.getLocalPort(), false);
- socketType.assertSocketType(socket);
- socket.setSoTimeout(1000);
- socket.close();
+ Constructor<OpenSSLSocketImpl> cons = OpenSSLSocketImpl.class.getDeclaredConstructor(
+ Socket.class, String.class, Integer.TYPE, Boolean.TYPE, SSLParametersImpl.class);
+ cons.setAccessible(true);
+ OpenSSLSocketImpl simpl =
+ cons.newInstance(underlying, null, listening.getLocalPort(), false, null);
+ simpl.setSoTimeout(1000);
+ simpl.close();
Field f = Socket.class.getDeclaredField("created");
f.setAccessible(true);
- assertFalse(f.getBoolean(socket));
+ assertFalse(f.getBoolean(simpl));
}
@Test
@@ -390,8 +347,9 @@ public class OpenSSLSocketImplTest {
connection.clientHooks = new ClientHooks() {
@Override
- public OpenSSLSocketImpl createSocket(ServerSocket listener) throws IOException {
- OpenSSLSocketImpl socket = super.createSocket(listener);
+ public OpenSSLSocketImpl createSocket(SSLSocketFactory factory, ServerSocket listener)
+ throws IOException {
+ OpenSSLSocketImpl socket = super.createSocket(factory, listener);
socket.setEnabledProtocols(new String[] {"SSLv3"});
assertEquals(
"SSLv3 should be filtered out", 0, socket.getEnabledProtocols().length);
@@ -408,8 +366,4 @@ public class OpenSSLSocketImplTest {
assertFalse(connection.clientHooks.isHandshakeCompleted);
assertFalse(connection.serverHooks.isHandshakeCompleted);
}
-
- private static ServerSocket newServerSocket() throws IOException {
- return new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
- }
}
diff --git a/openjdk/src/test/java/org/conscrypt/PlatformTest.java b/openjdk/src/test/java/org/conscrypt/PlatformTest.java
deleted file mode 100644
index c090d2d2..00000000
--- a/openjdk/src/test/java/org/conscrypt/PlatformTest.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- *
- * 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 org.conscrypt;
-
-import java.net.Socket;
-import java.util.ArrayList;
-import java.util.List;
-import javax.net.ssl.SNIHostName;
-import javax.net.ssl.SNIServerName;
-import javax.net.ssl.SSLParameters;
-import junit.framework.TestCase;
-
-/**
- * Test for Platform
- */
-public class PlatformTest extends TestCase {
- public void test_setSSLParameters_Socket() throws Exception {
- Socket socket = new OpenSSLSocketFactoryImpl().createSocket();
- SSLParametersImpl impl = SSLParametersImpl.getDefault();
- SSLParameters params = new SSLParameters();
- List<SNIServerName> names = new ArrayList<SNIServerName>();
- names.add(new SNIHostName("some.host"));
- params.setServerNames(names);
- params.setUseCipherSuitesOrder(false);
- params.setEndpointIdentificationAlgorithm("ABC");
- Platform.setSSLParameters(params, impl, (OpenSSLSocketImpl)socket);
- assertEquals("some.host", ((OpenSSLSocketImpl)socket).getHostname());
- assertFalse(impl.getUseCipherSuitesOrder());
- assertEquals("ABC", impl.getEndpointIdentificationAlgorithm());
- }
-
- public void test_getSSLParameters_Socket() throws Exception {
- Socket socket = new OpenSSLSocketFactoryImpl().createSocket();
- SSLParametersImpl impl = SSLParametersImpl.getDefault();
- SSLParameters params = new SSLParameters();
- impl.setUseCipherSuitesOrder(false);
- impl.setEndpointIdentificationAlgorithm("ABC");
- ((OpenSSLSocketImpl)socket).setHostname("some.host");
- Platform.getSSLParameters(params, impl, (OpenSSLSocketImpl)socket);
- assertEquals("some.host", ((SNIHostName)params.getServerNames().get(0)).getAsciiName());
- assertFalse(params.getUseCipherSuitesOrder());
- assertEquals("ABC", params.getEndpointIdentificationAlgorithm());
- }
-
- public void test_setSSLParameters_Engine() throws Exception {
- SSLParametersImpl impl = SSLParametersImpl.getDefault();
- SSLParameters params = new SSLParameters();
- OpenSSLEngineImpl engine = new OpenSSLEngineImpl(impl);
- List<SNIServerName> names = new ArrayList<SNIServerName>();
- names.add(new SNIHostName("some.host"));
- params.setServerNames(names);
- params.setUseCipherSuitesOrder(false);
- params.setEndpointIdentificationAlgorithm("ABC");
- Platform.setSSLParameters(params, impl, engine);
- assertEquals("some.host", engine.getSniHostname());
- assertFalse(impl.getUseCipherSuitesOrder());
- assertEquals("ABC", impl.getEndpointIdentificationAlgorithm());
- }
-
- public void test_getSSLParameters_Engine() throws Exception {
- SSLParametersImpl impl = SSLParametersImpl.getDefault();
- SSLParameters params = new SSLParameters();
- OpenSSLEngineImpl engine = new OpenSSLEngineImpl(impl);
- impl.setUseCipherSuitesOrder(false);
- impl.setEndpointIdentificationAlgorithm("ABC");
- engine.setSniHostname("some.host");
- Platform.getSSLParameters(params, impl, engine);
- assertEquals("some.host", ((SNIHostName)params.getServerNames().get(0)).getAsciiName());
- assertFalse(params.getUseCipherSuitesOrder());
- assertEquals("ABC", params.getEndpointIdentificationAlgorithm());
- }
-}
diff --git a/settings.gradle b/settings.gradle
index f2cadcb0..894bf758 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -1,26 +1,24 @@
rootProject.name = "conscrypt"
-include ":conscrypt-android"
-include ":conscrypt-android-platform"
-include ":conscrypt-android-stub"
-include ":conscrypt-api-doclet"
-include ":conscrypt-benchmark-graphs"
include ":conscrypt-constants"
-include ":conscrypt-libcore-stub"
include ":conscrypt-openjdk"
include ":conscrypt-openjdk-benchmarks"
-include ":conscrypt-openjdk-integ-tests"
-include ":conscrypt-openjdk-uber"
include ":conscrypt-testing"
+include ":conscrypt-openjdk-uber"
+include ":conscrypt-android"
+include ":conscrypt-android-stub"
+include ":conscrypt-android-platform"
+include ":conscrypt-libcore-stub"
+include ":conscrypt-api-doclet"
+include ":conscrypt-benchmark-graphs"
-project(':conscrypt-android').projectDir = "$rootDir/android" as File
-project(':conscrypt-android-platform').projectDir = "$rootDir/platform" as File
-project(':conscrypt-android-stub').projectDir = "$rootDir/android-stub" as File
-project(':conscrypt-api-doclet').projectDir = "$rootDir/api-doclet" as File
-project(':conscrypt-benchmark-graphs').projectDir = "$rootDir/benchmark-graphs" as File
project(':conscrypt-constants').projectDir = "$rootDir/constants" as File
-project(':conscrypt-libcore-stub').projectDir = "$rootDir/libcore-stub" as File
project(':conscrypt-openjdk').projectDir = "$rootDir/openjdk" as File
project(':conscrypt-openjdk-benchmarks').projectDir = "$rootDir/openjdk-benchmarks" as File
-project(':conscrypt-openjdk-integ-tests').projectDir = "$rootDir/openjdk-integ-tests" as File
-project(':conscrypt-openjdk-uber').projectDir = "$rootDir/openjdk-uber" as File
project(':conscrypt-testing').projectDir = "$rootDir/testing" as File
+project(':conscrypt-openjdk-uber').projectDir = "$rootDir/openjdk-uber" as File
+project(':conscrypt-android').projectDir = "$rootDir/android" as File
+project(':conscrypt-android-stub').projectDir = "$rootDir/android-stub" as File
+project(':conscrypt-libcore-stub').projectDir = "$rootDir/libcore-stub" as File
+project(':conscrypt-android-platform').projectDir = "$rootDir/platform" as File
+project(':conscrypt-api-doclet').projectDir = "$rootDir/api-doclet" as File
+project(':conscrypt-benchmark-graphs').projectDir = "$rootDir/benchmark-graphs" as File
diff --git a/testing/src/main/java/libcore/javax/net/ssl/ForwardingX509ExtendedKeyManager.java b/testing/src/main/java/libcore/javax/net/ssl/ForwardingX509ExtendedKeyManager.java
deleted file mode 100644
index e72725c1..00000000
--- a/testing/src/main/java/libcore/javax/net/ssl/ForwardingX509ExtendedKeyManager.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-import java.net.Socket;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.X509ExtendedKeyManager;
-/**
- * {@link X509ExtendedKeyManager} which delegates all calls to the provided
- * {@code X509ExtendedKeyManager} instance.
- */
-public class ForwardingX509ExtendedKeyManager extends X509ExtendedKeyManager {
- private final X509ExtendedKeyManager delegate;
- public ForwardingX509ExtendedKeyManager(X509ExtendedKeyManager delegate) {
- this.delegate = delegate;
- }
- @Override
- public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
- return delegate.chooseClientAlias(keyType, issuers, socket);
- }
- @Override
- public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
- return delegate.chooseServerAlias(keyType, issuers, socket);
- }
- @Override
- public X509Certificate[] getCertificateChain(String alias) {
- return delegate.getCertificateChain(alias);
- }
- @Override
- public String[] getClientAliases(String keyType, Principal[] issuers) {
- return delegate.getClientAliases(keyType, issuers);
- }
- @Override
- public String[] getServerAliases(String keyType, Principal[] issuers) {
- return delegate.getServerAliases(keyType, issuers);
- }
- @Override
- public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
- return delegate.chooseEngineClientAlias(keyType, issuers, engine);
- }
- @Override
- public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
- return delegate.chooseEngineServerAlias(keyType, issuers, engine);
- }
- @Override
- public PrivateKey getPrivateKey(String alias) {
- return delegate.getPrivateKey(alias);
- }
-}
diff --git a/testing/src/main/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java b/testing/src/main/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java
deleted file mode 100644
index 89a7accb..00000000
--- a/testing/src/main/java/libcore/javax/net/ssl/PSKKeyManagerProxy.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.Socket;
-import javax.crypto.SecretKey;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLEngine;
-
-/**
- * Reflection-based implementation of {@code PSKKeyManager} from Conscrypt on which these tests
- * cannot depend directly.
- */
-class PSKKeyManagerProxy implements InvocationHandler {
- static KeyManager getConscryptPSKKeyManager(PSKKeyManagerProxy delegate) {
- Class<?> pskKeyManagerInterface;
- try {
- pskKeyManagerInterface = Class.forName("org.conscrypt.PSKKeyManager");
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- }
- return (KeyManager) Proxy.newProxyInstance(
- PSKKeyManagerProxy.class.getClassLoader(),
- new Class<?>[] {pskKeyManagerInterface},
- delegate);
- }
- @SuppressWarnings("unused")
- protected SecretKey getKey(String identityHint, String identity, Socket socket) {
- return null;
- }
- @SuppressWarnings("unused")
- protected SecretKey getKey(String identityHint, String identity, SSLEngine engine) {
- return null;
- }
- @SuppressWarnings("unused")
- protected String chooseServerKeyIdentityHint(Socket socket) {
- return null;
- }
- @SuppressWarnings("unused")
- protected String chooseServerKeyIdentityHint(SSLEngine engine) {
- return null;
- }
- @SuppressWarnings("unused")
- protected String chooseClientKeyIdentity(String identityHint, Socket socket) {
- return null;
- }
- @SuppressWarnings("unused")
- protected String chooseClientKeyIdentity(String identityHint, SSLEngine engine) {
- return null;
- }
- @Override
- public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- String methodName = method.getName();
- Class<?>[] parameterTypes = method.getParameterTypes();
- boolean sslEngineVariant = (parameterTypes.length > 0)
- && (SSLEngine.class.equals(parameterTypes[parameterTypes.length - 1]));
- if ("getKey".equals(methodName)) {
- if (sslEngineVariant) {
- return getKey((String) args[0], (String) args[1], (SSLEngine) args[2]);
- } else {
- return getKey((String) args[0], (String) args[1], (Socket) args[2]);
- }
- } else if ("chooseServerKeyIdentityHint".equals(methodName)) {
- if (sslEngineVariant) {
- return chooseServerKeyIdentityHint((SSLEngine) args[0]);
- } else {
- return chooseServerKeyIdentityHint((Socket) args[0]);
- }
- } else if ("chooseClientKeyIdentity".equals(methodName)) {
- if (sslEngineVariant) {
- return chooseClientKeyIdentity((String) args[0], (SSLEngine) args[1]);
- } else {
- return chooseClientKeyIdentity((String) args[0], (Socket) args[1]);
- }
- } else {
- throw new IllegalArgumentException("Unexpected method: " + method);
- }
- }
-}
diff --git a/testing/src/main/java/libcore/javax/net/ssl/RandomPrivateKeyX509ExtendedKeyManager.java b/testing/src/main/java/libcore/javax/net/ssl/RandomPrivateKeyX509ExtendedKeyManager.java
deleted file mode 100644
index 1e32b2fc..00000000
--- a/testing/src/main/java/libcore/javax/net/ssl/RandomPrivateKeyX509ExtendedKeyManager.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.fail;
-
-import java.security.GeneralSecurityException;
-import java.security.KeyFactory;
-import java.security.KeyPairGenerator;
-import java.security.PrivateKey;
-import java.security.interfaces.ECPrivateKey;
-import java.security.spec.DSAParameterSpec;
-import java.security.spec.DSAPrivateKeySpec;
-import java.security.spec.RSAPrivateKeySpec;
-import java.util.HashMap;
-import java.util.Map;
-import javax.net.ssl.X509ExtendedKeyManager;
-
-/**
- * {@link X509ExtendedKeyManager} which forwards all calls to a delegate while substituting
- * the returned private key with its own randomly generated keys of the same type (and parameters).
- */
-public class RandomPrivateKeyX509ExtendedKeyManager extends ForwardingX509ExtendedKeyManager {
- private final Map<String, PrivateKey> cachedKeys = new HashMap<String, PrivateKey>();
- public RandomPrivateKeyX509ExtendedKeyManager(X509ExtendedKeyManager delegate) {
- super(delegate);
- }
- @Override
- public PrivateKey getPrivateKey(String alias) {
- PrivateKey originalPrivateKey = super.getPrivateKey(alias);
- if (originalPrivateKey == null) {
- return null;
- }
- PrivateKey result;
- String keyAlgorithm = originalPrivateKey.getAlgorithm();
- try {
- KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
- if ("RSA".equals(keyAlgorithm)) {
- RSAPrivateKeySpec originalKeySpec =
- keyFactory.getKeySpec(originalPrivateKey, RSAPrivateKeySpec.class);
- int keyLengthBits = originalKeySpec.getModulus().bitLength();
- // Use a cache because RSA key generation is slow.
- String cacheKey = keyAlgorithm + "-" + keyLengthBits;
- result = cachedKeys.get(cacheKey);
- if (result == null) {
- KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
- keyPairGenerator.initialize(keyLengthBits);
- result = keyPairGenerator.generateKeyPair().getPrivate();
- cachedKeys.put(cacheKey, result);
- }
- } else if ("DSA".equals(keyAlgorithm)) {
- DSAPrivateKeySpec originalKeySpec =
- keyFactory.getKeySpec(originalPrivateKey, DSAPrivateKeySpec.class);
- KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
- keyPairGenerator.initialize(new DSAParameterSpec(
- originalKeySpec.getP(), originalKeySpec.getQ(), originalKeySpec.getG()));
- result = keyPairGenerator.generateKeyPair().getPrivate();
- } else if ("EC".equals(keyAlgorithm)) {
- KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
- keyPairGenerator.initialize(((ECPrivateKey) originalPrivateKey).getParams());
- result = keyPairGenerator.generateKeyPair().getPrivate();
- } else {
- fail("Unsupported key algorithm: " + originalPrivateKey.getAlgorithm());
- result = null;
- }
- } catch (GeneralSecurityException e) {
- fail("Failed to generate private key: " + e);
- result = null;
- }
- return result;
- }
-}
diff --git a/testing/src/main/java/libcore/javax/net/ssl/SSLConfigurationAsserts.java b/testing/src/main/java/libcore/javax/net/ssl/SSLConfigurationAsserts.java
deleted file mode 100644
index 51bf5175..00000000
--- a/testing/src/main/java/libcore/javax/net/ssl/SSLConfigurationAsserts.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLParameters;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import libcore.java.security.StandardNames;
-
-/**
- * Assertions about the configuration of TLS/SSL primitives.
- */
-public class SSLConfigurationAsserts {
- /** Hidden constructor to prevent instantiation. */
- private SSLConfigurationAsserts() {}
- /**
- * Asserts that the provided {@link SSLContext} has the expected default configuration, and that
- * {@link SSLSocketFactory}, {@link SSLServerSocketFactory}, {@link SSLSocket},
- * {@link SSLServerSocket} and {@link SSLEngine} instances created from the context match the
- * configuration.
- */
- public static void assertSSLContextDefaultConfiguration(SSLContext sslContext)
- throws IOException {
- SSLParameters defaultParameters = sslContext.getDefaultSSLParameters();
- StandardNames.assertSSLContextEnabledProtocols(
- sslContext.getProtocol(), defaultParameters.getProtocols());
- StandardNames.assertDefaultCipherSuites(defaultParameters.getCipherSuites());
- assertFalse(defaultParameters.getWantClientAuth());
- assertFalse(defaultParameters.getNeedClientAuth());
- SSLParameters supportedParameters = sslContext.getSupportedSSLParameters();
- StandardNames.assertSupportedCipherSuites(supportedParameters.getCipherSuites());
- StandardNames.assertSupportedProtocols(supportedParameters.getProtocols());
- assertFalse(supportedParameters.getWantClientAuth());
- assertFalse(supportedParameters.getNeedClientAuth());
- assertContainsAll("Unsupported enabled cipher suites",
- supportedParameters.getCipherSuites(), defaultParameters.getCipherSuites());
- assertContainsAll("Unsupported enabled protocols", supportedParameters.getProtocols(),
- defaultParameters.getProtocols());
- assertSSLSocketFactoryConfigSameAsSSLContext(sslContext.getSocketFactory(), sslContext);
- assertSSLServerSocketFactoryConfigSameAsSSLContext(
- sslContext.getServerSocketFactory(), sslContext);
- SSLEngine sslEngine = sslContext.createSSLEngine();
- assertFalse(sslEngine.getUseClientMode());
- assertSSLEngineConfigSameAsSSLContext(sslEngine, sslContext);
- }
- /**
- * Asserts that the provided {@link SSLSocketFactory} has the expected default configuration and
- * that {@link SSLSocket} instances created by the factory match the configuration.
- */
- public static void assertSSLSocketFactoryDefaultConfiguration(SSLSocketFactory sslSocketFactory)
- throws Exception {
- assertSSLSocketFactoryConfigSameAsSSLContext(sslSocketFactory, SSLContext.getDefault());
- }
- /**
- * Asserts that {@link SSLSocketFactory}'s configuration matches {@code SSLContext}'s
- * configuration, and that {@link SSLSocket} instances obtained from the factory match this
- * configuration as well.
- */
- private static void assertSSLSocketFactoryConfigSameAsSSLContext(
- SSLSocketFactory sslSocketFactory, SSLContext sslContext) throws IOException {
- assertCipherSuitesEqual(sslContext.getDefaultSSLParameters().getCipherSuites(),
- sslSocketFactory.getDefaultCipherSuites());
- assertCipherSuitesEqual(sslContext.getSupportedSSLParameters().getCipherSuites(),
- sslSocketFactory.getSupportedCipherSuites());
- try (SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket()) {
- assertTrue(sslSocket.getUseClientMode());
- assertTrue(sslSocket.getEnableSessionCreation());
- assertSSLSocketConfigSameAsSSLContext(sslSocket, sslContext);
- }
- }
- /**
- * Asserts that the provided {@link SSLSocket} has the expected default configuration.
- */
- public static void assertSSLSocketDefaultConfiguration(SSLSocket sslSocket) throws Exception {
- assertTrue(sslSocket.getUseClientMode());
- assertTrue(sslSocket.getEnableSessionCreation());
- assertSSLSocketConfigSameAsSSLContext(sslSocket, SSLContext.getDefault());
- }
- /**
- * Asserts that {@link SSLSocket}'s configuration matches {@code SSLContext's} configuration.
- */
- private static void assertSSLSocketConfigSameAsSSLContext(
- SSLSocket sslSocket, SSLContext sslContext) {
- assertSSLParametersEqual(
- sslSocket.getSSLParameters(), sslContext.getDefaultSSLParameters());
- assertCipherSuitesEqual(sslSocket.getEnabledCipherSuites(),
- sslContext.getDefaultSSLParameters().getCipherSuites());
- assertProtocolsEqual(sslSocket.getEnabledProtocols(),
- sslContext.getDefaultSSLParameters().getProtocols());
- assertCipherSuitesEqual(sslSocket.getSupportedCipherSuites(),
- sslContext.getSupportedSSLParameters().getCipherSuites());
- assertProtocolsEqual(sslSocket.getSupportedProtocols(),
- sslContext.getSupportedSSLParameters().getProtocols());
- }
- /**
- * Asserts that the provided {@link SSLServerSocketFactory} has the expected default
- * configuration, and that {@link SSLServerSocket} instances created by the factory match the
- * configuration.
- */
- public static void assertSSLServerSocketFactoryDefaultConfiguration(
- SSLServerSocketFactory sslServerSocketFactory) throws Exception {
- assertSSLServerSocketFactoryConfigSameAsSSLContext(
- sslServerSocketFactory, SSLContext.getDefault());
- }
- /**
- * Asserts that {@link SSLServerSocketFactory}'s configuration matches {@code SSLContext}'s
- * configuration, and that {@link SSLServerSocket} instances obtained from the factory match
- * this
- * configuration as well.
- */
- private static void assertSSLServerSocketFactoryConfigSameAsSSLContext(
- SSLServerSocketFactory sslServerSocketFactory, SSLContext sslContext)
- throws IOException {
- assertCipherSuitesEqual(sslContext.getDefaultSSLParameters().getCipherSuites(),
- sslServerSocketFactory.getDefaultCipherSuites());
- assertCipherSuitesEqual(sslContext.getSupportedSSLParameters().getCipherSuites(),
- sslServerSocketFactory.getSupportedCipherSuites());
- try (SSLServerSocket sslServerSocket =
- (SSLServerSocket) sslServerSocketFactory.createServerSocket()) {
- assertFalse(sslServerSocket.getUseClientMode());
- assertTrue(sslServerSocket.getEnableSessionCreation());
- assertSSLServerSocketConfigSameAsSSLContext(sslServerSocket, sslContext);
- }
- }
- /**
- * Asserts that the provided {@link SSLServerSocket} has the expected default configuration.
- */
- public static void assertSSLServerSocketDefaultConfiguration(SSLServerSocket sslServerSocket)
- throws Exception {
- assertFalse(sslServerSocket.getUseClientMode());
- assertTrue(sslServerSocket.getEnableSessionCreation());
- assertSSLServerSocketConfigSameAsSSLContext(sslServerSocket, SSLContext.getDefault());
- // TODO: Check SSLParameters when supported by SSLServerSocket API
- }
- /**
- * Asserts that {@link SSLServerSocket}'s configuration matches {@code SSLContext's}
- * configuration.
- */
- private static void assertSSLServerSocketConfigSameAsSSLContext(
- SSLServerSocket sslServerSocket, SSLContext sslContext) {
- assertCipherSuitesEqual(sslServerSocket.getEnabledCipherSuites(),
- sslContext.getDefaultSSLParameters().getCipherSuites());
- assertProtocolsEqual(sslServerSocket.getEnabledProtocols(),
- sslContext.getDefaultSSLParameters().getProtocols());
- assertCipherSuitesEqual(sslServerSocket.getSupportedCipherSuites(),
- sslContext.getSupportedSSLParameters().getCipherSuites());
- assertProtocolsEqual(sslServerSocket.getSupportedProtocols(),
- sslContext.getSupportedSSLParameters().getProtocols());
- assertEquals(sslServerSocket.getNeedClientAuth(),
- sslContext.getDefaultSSLParameters().getNeedClientAuth());
- assertEquals(sslServerSocket.getWantClientAuth(),
- sslContext.getDefaultSSLParameters().getWantClientAuth());
- }
- /**
- * Asserts that the provided {@link SSLEngine} has the expected default configuration.
- */
- public static void assertSSLEngineDefaultConfiguration(SSLEngine sslEngine) throws Exception {
- assertFalse(sslEngine.getUseClientMode());
- assertTrue(sslEngine.getEnableSessionCreation());
- assertSSLEngineConfigSameAsSSLContext(sslEngine, SSLContext.getDefault());
- }
- /**
- * Asserts that {@link SSLEngine}'s configuration matches {@code SSLContext's} configuration.
- */
- private static void assertSSLEngineConfigSameAsSSLContext(
- SSLEngine sslEngine, SSLContext sslContext) {
- assertSSLParametersEqual(
- sslEngine.getSSLParameters(), sslContext.getDefaultSSLParameters());
- assertCipherSuitesEqual(sslEngine.getEnabledCipherSuites(),
- sslContext.getDefaultSSLParameters().getCipherSuites());
- assertProtocolsEqual(sslEngine.getEnabledProtocols(),
- sslContext.getDefaultSSLParameters().getProtocols());
- assertCipherSuitesEqual(sslEngine.getSupportedCipherSuites(),
- sslContext.getSupportedSSLParameters().getCipherSuites());
- assertProtocolsEqual(sslEngine.getSupportedProtocols(),
- sslContext.getSupportedSSLParameters().getProtocols());
- }
- private static void assertSSLParametersEqual(SSLParameters expected, SSLParameters actual) {
- assertCipherSuitesEqual(expected.getCipherSuites(), actual.getCipherSuites());
- assertProtocolsEqual(expected.getProtocols(), actual.getProtocols());
- assertEquals(expected.getNeedClientAuth(), actual.getNeedClientAuth());
- assertEquals(expected.getWantClientAuth(), actual.getWantClientAuth());
- }
- private static void assertCipherSuitesEqual(String[] expected, String[] actual) {
- assertEquals(Arrays.asList(expected), Arrays.asList(actual));
- }
- private static void assertProtocolsEqual(String[] expected, String[] actual) {
- // IMPLEMENTATION NOTE: The order of protocols versions does not matter. Similarly, it only
- // matters whether a protocol version is present or absent in the array. These arrays are
- // supposed to represent sets of protocol versions. Thus, we treat them as such.
- assertEquals(new HashSet<String>(Arrays.asList(expected)),
- new HashSet<String>(Arrays.asList(actual)));
- }
- /**
- * Asserts that the {@code container} contains all the {@code elements}.
- */
- private static void assertContainsAll(String message, String[] container, String[] elements) {
- Set<String> elementsNotInContainer = new HashSet<String>(Arrays.asList(elements));
- elementsNotInContainer.removeAll(Arrays.asList(container));
- assertEquals(message, Collections.EMPTY_SET, elementsNotInContainer);
- }
-}
diff --git a/testing/src/main/java/libcore/javax/net/ssl/TestSSLContext.java b/testing/src/main/java/libcore/javax/net/ssl/TestSSLContext.java
deleted file mode 100644
index aa58a80c..00000000
--- a/testing/src/main/java/libcore/javax/net/ssl/TestSSLContext.java
+++ /dev/null
@@ -1,474 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.security.KeyStore;
-import java.security.Principal;
-import java.security.SecureRandom;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.Collections;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509ExtendedTrustManager;
-import javax.net.ssl.X509TrustManager;
-import libcore.java.security.TestKeyStore;
-
-/**
- * TestSSLContext is a convenience class for other tests that
- * want a canned SSLContext and related state for testing so they
- * don't have to duplicate the logic.
- */
-public final class TestSSLContext {
- /**
- * The Android SSLSocket and SSLServerSocket implementations are
- * based on a version of OpenSSL which includes support for RFC
- * 4507 session tickets. When using session tickets, the server
- * does not need to keep a cache mapping session IDs to SSL
- * sessions for reuse. Instead, the client presents the server
- * with a session ticket it received from the server earlier,
- * which is an SSL session encrypted by the server's secret
- * key. Since in this case the server does not need to keep a
- * cache, some tests may find different results depending on
- * whether or not the session tickets are in use. These tests can
- * use this function to determine if loopback SSL connections are
- * expected to use session tickets and conditionalize their
- * results appropriately.
- */
- public static boolean sslServerSocketSupportsSessionTickets() {
- // Disabled session tickets for better compatability b/2682876
- // return !IS_RI;
- return false;
- }
- public final KeyStore clientKeyStore;
- public final char[] clientStorePassword;
- public final KeyStore serverKeyStore;
- public final char[] serverStorePassword;
- public final KeyManager[] clientKeyManagers;
- public final KeyManager[] serverKeyManagers;
- public final X509ExtendedTrustManager clientTrustManager;
- public final X509ExtendedTrustManager serverTrustManager;
- public final SSLContext clientContext;
- public final SSLContext serverContext;
- public final SSLServerSocket serverSocket;
- public final InetAddress host;
- public final int port;
- /**
- * Used for replacing the hostname in an InetSocketAddress object during
- * serialization.
- */
- private static class HostnameRewritingObjectOutputStream extends ObjectOutputStream {
- private final String hostname;
- public HostnameRewritingObjectOutputStream(OutputStream out, String hostname)
- throws IOException {
- super(out);
- this.hostname = hostname;
- }
- @Override
- public PutField putFields() throws IOException {
- return new PutFieldProxy(super.putFields(), hostname);
- }
- private static class PutFieldProxy extends ObjectOutputStream.PutField {
- private final PutField delegate;
- private final String hostname;
- public PutFieldProxy(ObjectOutputStream.PutField delegate, String hostname) {
- this.delegate = delegate;
- this.hostname = hostname;
- }
- @Override
- public void put(String name, boolean val) {
- delegate.put(name, val);
- }
- @Override
- public void put(String name, byte val) {
- delegate.put(name, val);
- }
- @Override
- public void put(String name, char val) {
- delegate.put(name, val);
- }
- @Override
- public void put(String name, short val) {
- delegate.put(name, val);
- }
- @Override
- public void put(String name, int val) {
- delegate.put(name, val);
- }
- @Override
- public void put(String name, long val) {
- delegate.put(name, val);
- }
- @Override
- public void put(String name, float val) {
- delegate.put(name, val);
- }
- @Override
- public void put(String name, double val) {
- delegate.put(name, val);
- }
- @Override
- public void put(String name, Object val) {
- if ("hostname".equals(name)) {
- delegate.put(name, hostname);
- } else {
- delegate.put(name, val);
- }
- }
- @SuppressWarnings("deprecation")
- @Override
- public void write(ObjectOutput out) throws IOException {
- delegate.write(out);
- }
- }
- }
- /**
- * Creates an InetSocketAddress where the hostname points to an arbitrary
- * hostname, but the address points to the loopback address. Useful for
- * testing SNI where both "localhost" and IP addresses are not allowed.
- */
- public InetSocketAddress getLoopbackAsHostname(String hostname, int port)
- throws IOException, ClassNotFoundException {
- InetSocketAddress addr = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- HostnameRewritingObjectOutputStream oos =
- new HostnameRewritingObjectOutputStream(baos, hostname);
- oos.writeObject(addr);
- oos.close();
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
- return (InetSocketAddress) ois.readObject();
- }
- private TestSSLContext(KeyStore clientKeyStore, char[] clientStorePassword,
- KeyStore serverKeyStore, char[] serverStorePassword, KeyManager[] clientKeyManagers,
- KeyManager[] serverKeyManagers, X509ExtendedTrustManager clientTrustManager,
- X509ExtendedTrustManager serverTrustManager, SSLContext clientContext,
- SSLContext serverContext, SSLServerSocket serverSocket, InetAddress host, int port) {
- this.clientKeyStore = clientKeyStore;
- this.clientStorePassword = clientStorePassword;
- this.serverKeyStore = serverKeyStore;
- this.serverStorePassword = serverStorePassword;
- this.clientKeyManagers = clientKeyManagers;
- this.serverKeyManagers = serverKeyManagers;
- this.clientTrustManager = clientTrustManager;
- this.serverTrustManager = serverTrustManager;
- this.clientContext = clientContext;
- this.serverContext = serverContext;
- this.serverSocket = serverSocket;
- this.host = host;
- this.port = port;
- }
- public void close() {
- try {
- serverSocket.close();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static Builder newBuilder() {
- return new Builder();
- }
-
- public static final class Builder {
- private TestKeyStore client;
- private char[] clientStorePassword;
- private TestKeyStore server;
- private char[] serverStorePassword;
- private KeyManager[] additionalClientKeyManagers;
- private KeyManager[] additionalServerKeyManagers;
- private TrustManager clientTrustManager;
- private TrustManager serverTrustManager;
- private SSLContext clientContext;
- private SSLContext serverContext;
- private int serverReceiveBufferSize;
- private boolean useDefaults = true;
-
- public Builder useDefaults(boolean useDefaults) {
- this.useDefaults = useDefaults;
- return this;
- }
-
- public Builder client(TestKeyStore client) {
- this.client = client;
- return this;
- }
-
- public Builder clientStorePassword(char[] clientStorePassword) {
- this.clientStorePassword = clientStorePassword;
- return this;
- }
-
- public Builder server(TestKeyStore server) {
- this.server = server;
- return this;
- }
-
- public Builder serverStorePassword(char[] serverStorePassword) {
- this.serverStorePassword = serverStorePassword;
- return this;
- }
-
- public Builder additionalClientKeyManagers(KeyManager[] additionalClientKeyManagers) {
- this.additionalClientKeyManagers = additionalClientKeyManagers;
- return this;
- }
-
- public Builder additionalServerKeyManagers(KeyManager[] additionalServerKeyManagers) {
- this.additionalServerKeyManagers = additionalServerKeyManagers;
- return this;
- }
-
- public Builder clientTrustManager(TrustManager clientTrustManager) {
- this.clientTrustManager = clientTrustManager;
- return this;
- }
-
- public Builder serverTrustManager(TrustManager serverTrustManager) {
- this.serverTrustManager = serverTrustManager;
- return this;
- }
-
- public Builder clientContext(SSLContext clientContext) {
- this.clientContext = clientContext;
- return this;
- }
-
- public Builder serverContext(SSLContext serverContext) {
- this.serverContext = serverContext;
- return this;
- }
-
- public Builder serverReceiveBufferSize(int serverReceiveBufferSize) {
- this.serverReceiveBufferSize = serverReceiveBufferSize;
- return this;
- }
-
- TestSSLContext build() {
- // Get the current values for all the things.
- TestKeyStore client = this.client;
- TestKeyStore server = this.server;
- char[] clientStorePassword = this.clientStorePassword;
- char[] serverStorePassword = this.serverStorePassword;
- KeyManager[] clientKeyManagers = client != null ? client.keyManagers : null;
- KeyManager[] serverKeyManagers = server != null ? server.keyManagers : null;
- TrustManager clientTrustManager = this.clientTrustManager;
- TrustManager serverTrustManager = this.serverTrustManager;
- SSLContext clientContext = this.clientContext;
- SSLContext serverContext = this.serverContext;
-
- // Apply default values if configured to do so.
- if (useDefaults) {
- client = client != null ? client : TestKeyStore.getClient();
- server = server != null ? server : TestKeyStore.getServer();
- clientStorePassword =
- clientStorePassword != null ? clientStorePassword : client.storePassword;
- serverStorePassword =
- serverStorePassword != null ? serverStorePassword : server.storePassword;
- clientKeyManagers =
- clientKeyManagers != null ? clientKeyManagers : client.keyManagers;
- serverKeyManagers =
- serverKeyManagers != null ? serverKeyManagers : server.keyManagers;
- clientKeyManagers = concat(clientKeyManagers, additionalClientKeyManagers);
- serverKeyManagers = concat(serverKeyManagers, additionalServerKeyManagers);
- clientTrustManager =
- clientTrustManager != null ? clientTrustManager : client.trustManagers[0];
- serverTrustManager =
- serverTrustManager != null ? serverTrustManager : server.trustManagers[0];
-
- String protocol = "TLSv1.2";
- clientContext = clientContext != null
- ? clientContext
- : createSSLContext(protocol, clientKeyManagers,
- new TrustManager[] {clientTrustManager});
- serverContext = serverContext != null
- ? serverContext
- : createSSLContext(protocol, serverKeyManagers,
- new TrustManager[] {serverTrustManager});
- }
-
- // Create the context.
- try {
- SSLServerSocket serverSocket =
- (SSLServerSocket) serverContext.getServerSocketFactory()
- .createServerSocket();
- if (serverReceiveBufferSize > 0) {
- // The TCP spec says that this should occur before listen.
- serverSocket.setReceiveBufferSize(serverReceiveBufferSize);
- }
- InetAddress host = InetAddress.getLoopbackAddress();
- serverSocket.bind(new InetSocketAddress(host, 0));
- int port = serverSocket.getLocalPort();
- return new TestSSLContext(client != null ? client.keyStore : null,
- clientStorePassword, server != null ? server.keyStore : null,
- serverStorePassword, clientKeyManagers, serverKeyManagers,
- (X509ExtendedTrustManager) clientTrustManager,
- (X509ExtendedTrustManager) serverTrustManager, clientContext, serverContext,
- serverSocket, host, port);
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- /**
- * Usual TestSSLContext creation method, creates underlying
- * SSLContext with certificate and key as well as SSLServerSocket
- * listening provided host and port.
- */
- public static TestSSLContext create() {
- return new Builder().build();
- }
-
- /**
- * TestSSLContext creation method that allows separate creation of server key store
- */
- public static TestSSLContext create(TestKeyStore client, TestKeyStore server) {
- return new Builder().client(client).server(server).build();
- }
- /**
- * Create a SSLContext with a KeyManager using the private key and
- * certificate chain from the given KeyStore and a TrustManager
- * using the certificates authorities from the same KeyStore.
- */
- public static SSLContext createSSLContext(final String protocol, final KeyManager[] keyManagers,
- final TrustManager[] trustManagers) {
- try {
- SSLContext context = SSLContext.getInstance(protocol);
- context.init(keyManagers, trustManagers, new SecureRandom());
- return context;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- public static void assertCertificateInKeyStore(Principal principal, KeyStore keyStore)
- throws Exception {
- String subjectName = principal.getName();
- boolean found = false;
- for (String alias : Collections.list(keyStore.aliases())) {
- if (!keyStore.isCertificateEntry(alias)) {
- continue;
- }
- X509Certificate keyStoreCertificate = (X509Certificate) keyStore.getCertificate(alias);
- if (subjectName.equals(keyStoreCertificate.getSubjectDN().getName())) {
- found = true;
- break;
- }
- }
- assertTrue(found);
- }
- public static void assertCertificateInKeyStore(Certificate certificate, KeyStore keyStore)
- throws Exception {
- boolean found = false;
- for (String alias : Collections.list(keyStore.aliases())) {
- if (!keyStore.isCertificateEntry(alias)) {
- continue;
- }
- Certificate keyStoreCertificate = keyStore.getCertificate(alias);
- if (certificate.equals(keyStoreCertificate)) {
- found = true;
- break;
- }
- }
- assertTrue(found);
- }
- public static void assertServerCertificateChain(
- X509TrustManager trustManager, Certificate[] serverChain) throws CertificateException {
- X509Certificate[] chain = (X509Certificate[]) serverChain;
- trustManager.checkServerTrusted(chain, chain[0].getPublicKey().getAlgorithm());
- }
- public static void assertClientCertificateChain(
- X509TrustManager trustManager, Certificate[] clientChain) throws CertificateException {
- X509Certificate[] chain = (X509Certificate[]) clientChain;
- trustManager.checkClientTrusted(chain, chain[0].getPublicKey().getAlgorithm());
- }
- /**
- * Returns an SSLSocketFactory that calls setWantClientAuth and
- * setNeedClientAuth as specified on all returned sockets.
- */
- public static SSLSocketFactory clientAuth(
- final SSLSocketFactory sf, final boolean want, final boolean need) {
- return new SSLSocketFactory() {
- private SSLSocket set(Socket socket) {
- SSLSocket s = (SSLSocket) socket;
- s.setWantClientAuth(want);
- s.setNeedClientAuth(need);
- return s;
- }
- @Override
- public Socket createSocket(String host, int port) throws IOException {
- return set(sf.createSocket(host, port));
- }
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException {
- return set(sf.createSocket(host, port, localHost, localPort));
- }
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- return set(sf.createSocket(host, port));
- }
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException {
- return set(sf.createSocket(address, port));
- }
- @Override
- public String[] getDefaultCipherSuites() {
- return sf.getDefaultCipherSuites();
- }
- @Override
- public String[] getSupportedCipherSuites() {
- return sf.getSupportedCipherSuites();
- }
- @Override
- public Socket createSocket(Socket s, String host, int port, boolean autoClose)
- throws IOException {
- return set(sf.createSocket(s, host, port, autoClose));
- }
- };
- }
- private static KeyManager[] concat(KeyManager[] a, KeyManager[] b) {
- if ((a == null) || (a.length == 0)) {
- return b;
- }
- if ((b == null) || (b.length == 0)) {
- return a;
- }
- KeyManager[] result = new KeyManager[a.length + b.length];
- System.arraycopy(a, 0, result, 0, a.length);
- System.arraycopy(b, 0, result, a.length, b.length);
- return result;
- }
-}
diff --git a/testing/src/main/java/libcore/javax/net/ssl/TestSSLEnginePair.java b/testing/src/main/java/libcore/javax/net/ssl/TestSSLEnginePair.java
deleted file mode 100644
index 1146c691..00000000
--- a/testing/src/main/java/libcore/javax/net/ssl/TestSSLEnginePair.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-
-/**
- * TestSSLEnginePair is a convenience class for other tests that want
- * a pair of connected and handshaked client and server SSLEngines for
- * testing.
- */
-public final class TestSSLEnginePair implements AutoCloseable {
- public final TestSSLContext c;
- public final SSLEngine server;
- public final SSLEngine client;
- private TestSSLEnginePair(TestSSLContext c,
- SSLEngine server,
- SSLEngine client) {
- this.c = c;
- this.server = server;
- this.client = client;
- }
- public static TestSSLEnginePair create() throws IOException {
- return create(null);
- }
- public static TestSSLEnginePair create(Hooks hooks) throws IOException {
- return create(TestSSLContext.create(), hooks);
- }
- public static TestSSLEnginePair create(TestSSLContext c, Hooks hooks) throws IOException {
- return create(c, hooks, null);
- }
- public static TestSSLEnginePair create(TestSSLContext c, Hooks hooks, boolean[] finished)
- throws IOException {
- SSLEngine[] engines = connect(c, hooks, finished);
- return new TestSSLEnginePair(c, engines[0], engines[1]);
- }
- public static SSLEngine[] connect(TestSSLContext c, Hooks hooks) throws IOException {
- return connect(c, hooks, null);
- }
- /**
- * Create a new connected server/client engine pair within a
- * existing SSLContext. Optionally specify clientCipherSuites to
- * allow forcing new SSLSession to test SSLSessionContext
- * caching. Optionally specify serverCipherSuites for testing
- * cipher suite negotiation.
- */
- public static SSLEngine[] connect(final TestSSLContext c,
- Hooks hooks,
- boolean finished[]) throws IOException {
- if (hooks == null) {
- hooks = new Hooks();
- }
- // FINISHED state should be returned only once.
- boolean[] clientFinished = new boolean[1];
- boolean[] serverFinished = new boolean[1];
- SSLSession session = c.clientContext.createSSLEngine().getSession();
- int packetBufferSize = session.getPacketBufferSize();
- ByteBuffer clientToServer = ByteBuffer.allocate(packetBufferSize);
- ByteBuffer serverToClient = ByteBuffer.allocate(packetBufferSize);
- int applicationBufferSize = session.getApplicationBufferSize();
- ByteBuffer scratch = ByteBuffer.allocate(applicationBufferSize);
- SSLEngine client = c.clientContext.createSSLEngine(c.host.getHostName(), c.port);
- SSLEngine server = c.serverContext.createSSLEngine();
- client.setUseClientMode(true);
- server.setUseClientMode(false);
- hooks.beforeBeginHandshake(client, server);
- client.beginHandshake();
- server.beginHandshake();
- while (true) {
- boolean clientDone = client.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING;
- boolean serverDone = server.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING;
- if (clientDone && serverDone) {
- break;
- }
- boolean progress = false;
- if (!clientDone) {
- progress = handshakeCompleted(client,
- clientToServer,
- serverToClient,
- scratch,
- clientFinished);
- }
- if (!serverDone) {
- progress |= handshakeCompleted(server,
- serverToClient,
- clientToServer,
- scratch,
- serverFinished);
- }
- if (!progress) {
- break;
- }
- }
- if (finished != null) {
- assertEquals(2, finished.length);
- finished[0] = clientFinished[0];
- finished[1] = serverFinished[0];
- }
- return new SSLEngine[] { server, client };
- }
- public static class Hooks {
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {}
- }
- @Override
- public void close() throws SSLException {
- close(new SSLEngine[] { client, server });
- }
- public static void close(SSLEngine[] engines) {
- try {
- for (SSLEngine engine : engines) {
- if (engine != null) {
- engine.closeInbound();
- engine.closeOutbound();
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- private static boolean handshakeCompleted(SSLEngine engine,
- ByteBuffer output,
- ByteBuffer input,
- ByteBuffer scratch,
- boolean[] finished) throws IOException {
- try {
- // make the other side's output into our input
- input.flip();
- HandshakeStatus status = engine.getHandshakeStatus();
- switch (status) {
- case NEED_TASK: {
- boolean progress = false;
- while (true) {
- Runnable runnable = engine.getDelegatedTask();
- if (runnable == null) {
- return progress;
- }
- runnable.run();
- progress = true;
- }
- }
- case NEED_UNWRAP: {
- // avoid underflow
- if (input.remaining() == 0) {
- return false;
- }
- int inputPositionBefore = input.position();
- SSLEngineResult unwrapResult = engine.unwrap(input, scratch);
- assertEquals(SSLEngineResult.Status.OK, unwrapResult.getStatus());
- assertEquals(0, scratch.position());
- assertEquals(0, unwrapResult.bytesProduced());
- assertEquals(input.position() - inputPositionBefore, unwrapResult.bytesConsumed());
- assertFinishedOnce(finished, unwrapResult);
- return true;
- }
- case NEED_WRAP: {
- // avoid possible overflow
- if (output.remaining() != output.capacity()) {
- return false;
- }
- ByteBuffer emptyByteBuffer = ByteBuffer.allocate(0);
- int inputPositionBefore = emptyByteBuffer.position();
- int outputPositionBefore = output.position();
- SSLEngineResult wrapResult = engine.wrap(emptyByteBuffer, output);
- assertEquals(SSLEngineResult.Status.OK, wrapResult.getStatus());
- assertEquals(0, wrapResult.bytesConsumed());
- assertEquals(inputPositionBefore, emptyByteBuffer.position());
- assertEquals(output.position() - outputPositionBefore,
- wrapResult.bytesProduced());
- assertFinishedOnce(finished, wrapResult);
- return true;
- }
- case NOT_HANDSHAKING:
- // should have been checked by caller before calling
- case FINISHED:
- // only returned by wrap/unrap status, not getHandshakeStatus
- throw new IllegalStateException("Unexpected HandshakeStatus = " + status);
- default:
- throw new IllegalStateException("Unknown HandshakeStatus = " + status);
- }
- } finally {
- // shift consumed input, restore to output mode
- input.compact();
- }
- }
- private static void assertFinishedOnce(boolean[] finishedOut, SSLEngineResult result) {
- if (result.getHandshakeStatus() == HandshakeStatus.FINISHED) {
- assertFalse("should only return FINISHED once", finishedOut[0]);
- finishedOut[0] = true;
- }
- }
-}
diff --git a/testing/src/main/java/libcore/javax/net/ssl/TestSSLSessions.java b/testing/src/main/java/libcore/javax/net/ssl/TestSSLSessions.java
deleted file mode 100644
index 34596bc5..00000000
--- a/testing/src/main/java/libcore/javax/net/ssl/TestSSLSessions.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-/**
- * TestSSLSessions is a convenience class for other tests that want
- * precreated SSLSessions for testing. It contains a connected
- * client/server pair of SSLSession as well as an invalid SSLSession.
- */
-public final class TestSSLSessions {
- /**
- * An invalid session that is not connected
- */
- public final SSLSession invalid;
- /**
- * The server side of a connected session
- */
- public final SSLSession server;
- /**
- * The client side of a connected session
- */
- public final SSLSession client;
- /**
- * The associated SSLSocketTest.Helper that is the source of
- * the client and server SSLSessions.
- */
- public final TestSSLSocketPair s;
- private TestSSLSessions(SSLSession invalid,
- SSLSession server,
- SSLSession client,
- TestSSLSocketPair s) {
- this.invalid = invalid;
- this.server = server;
- this.client = client;
- this.s = s;
- }
- public void close() {
- s.close();
- }
- public static final TestSSLSessions create() {
- try {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- SSLSocket ssl = (SSLSocket) sf.createSocket();
- SSLSession invalid = ssl.getSession();
- TestSSLSocketPair s = TestSSLSocketPair.create();
- return new TestSSLSessions(invalid, s.server.getSession(), s.client.getSession(), s);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/testing/src/main/java/libcore/javax/net/ssl/TestSSLSocketPair.java b/testing/src/main/java/libcore/javax/net/ssl/TestSSLSocketPair.java
deleted file mode 100644
index 66e7ac72..00000000
--- a/testing/src/main/java/libcore/javax/net/ssl/TestSSLSocketPair.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 libcore.javax.net.ssl;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import javax.net.ssl.SSLSocket;
-
-/**
- * TestSSLSocketPair is a convenience class for other tests that want
- * a pair of connected and handshaked client and server SSLSockets for
- * testing.
- */
-public final class TestSSLSocketPair {
- public final TestSSLContext c;
- public final SSLSocket server;
- public final SSLSocket client;
- private TestSSLSocketPair (TestSSLContext c,
- SSLSocket server,
- SSLSocket client) {
- this.c = c;
- this.server = server;
- this.client = client;
- }
- public void close() {
- c.close();
- try {
- server.close();
- client.close();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * based on test_SSLSocket_startHandshake
- */
- public static TestSSLSocketPair create () {
- TestSSLContext c = TestSSLContext.create();
- SSLSocket[] sockets = connect(c, null, null);
- return new TestSSLSocketPair(c, sockets[0], sockets[1]);
- }
- /**
- * Create a new connected server/client socket pair within a
- * existing SSLContext. Optionally specify clientCipherSuites to
- * allow forcing new SSLSession to test SSLSessionContext
- * caching. Optionally specify serverCipherSuites for testing
- * cipher suite negotiation.
- */
- public static SSLSocket[] connect (final TestSSLContext context,
- final String[] clientCipherSuites,
- final String[] serverCipherSuites) {
- try {
- final SSLSocket client = (SSLSocket)
- context.clientContext.getSocketFactory().createSocket(context.host, context.port);
- final SSLSocket server = (SSLSocket) context.serverSocket.accept();
- ExecutorService executor = Executors.newFixedThreadPool(2);
- Future<Void> s = executor.submit(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- if (serverCipherSuites != null) {
- server.setEnabledCipherSuites(serverCipherSuites);
- }
- server.startHandshake();
- return null;
- }
- });
- Future<Void> c = executor.submit(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- if (clientCipherSuites != null) {
- client.setEnabledCipherSuites(clientCipherSuites);
- }
- client.startHandshake();
- return null;
- }
- });
- executor.shutdown();
- // catch client and server exceptions separately so we can
- // potentially log both.
- Exception serverException;
- try {
- s.get(30, TimeUnit.SECONDS);
- serverException = null;
- } catch (Exception e) {
- serverException = e;
- e.printStackTrace();
- }
- Exception clientException;
- try {
- c.get(30, TimeUnit.SECONDS);
- clientException = null;
- } catch (Exception e) {
- clientException = e;
- e.printStackTrace();
- }
- if (serverException != null) {
- throw serverException;
- }
- if (clientException != null) {
- throw clientException;
- }
- return new SSLSocket[] { server, client };
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/handshake/CipherSuite.java b/testing/src/main/java/libcore/tlswire/handshake/CipherSuite.java
deleted file mode 100644
index cd14c75d..00000000
--- a/testing/src/main/java/libcore/tlswire/handshake/CipherSuite.java
+++ /dev/null
@@ -1,455 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.handshake;
-import java.util.HashMap;
-import java.util.Map;
-/**
- * {@code CipherSuite} enum from TLS 1.2 RFC 5246.
- */
-public class CipherSuite {
- // The list of cipher suites below is based on IANA registry
- // https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml
- private static final CipherSuite[] CIPHER_SUITES = new CipherSuite[] {
- new CipherSuite(0x0000, "TLS_NULL_WITH_NULL_NULL"),
- new CipherSuite(0x0001, "TLS_RSA_WITH_NULL_MD5", "SSL_RSA_WITH_NULL_MD5"),
- new CipherSuite(0x0002, "TLS_RSA_WITH_NULL_SHA", "SSL_RSA_WITH_NULL_SHA"),
- new CipherSuite(0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_RC4_40_MD5"),
- new CipherSuite(0x0004, "TLS_RSA_WITH_RC4_128_MD5", "SSL_RSA_WITH_RC4_128_MD5"),
- new CipherSuite(0x0005, "TLS_RSA_WITH_RC4_128_SHA", "SSL_RSA_WITH_RC4_128_SHA"),
- new CipherSuite(0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"),
- new CipherSuite(0x0007, "TLS_RSA_WITH_IDEA_CBC_SHA"),
- new CipherSuite(0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA",
- "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"),
- new CipherSuite(0x0009, "TLS_RSA_WITH_DES_CBC_SHA", "SSL_RSA_WITH_DES_CBC_SHA"),
- new CipherSuite(0x000a, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", "SSL_RSA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x000b, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"),
- new CipherSuite(0x000c, "TLS_DH_DSS_WITH_DES_CBC_SHA"),
- new CipherSuite(0x000d, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x000e, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"),
- new CipherSuite(0x000f, "TLS_DH_RSA_WITH_DES_CBC_SHA"),
- new CipherSuite(0x0010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
- "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"),
- new CipherSuite(0x0012, "TLS_DHE_DSS_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA"),
- new CipherSuite(0x0013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
- "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
- "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"),
- new CipherSuite(0x0015, "TLS_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA"),
- new CipherSuite(0x0016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
- "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5",
- "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5"),
- new CipherSuite(0x0018, "TLS_DH_anon_WITH_RC4_128_MD5", "SSL_DH_anon_WITH_RC4_128_MD5"),
- new CipherSuite(0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA",
- "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"),
- new CipherSuite(0x001a, "TLS_DH_anon_WITH_DES_CBC_SHA", "SSL_DH_anon_WITH_DES_CBC_SHA"),
- new CipherSuite(0x001b, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA",
- "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x001e, "TLS_KRB5_WITH_DES_CBC_SHA"),
- new CipherSuite(0x001f, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x0020, "TLS_KRB5_WITH_RC4_128_SHA"),
- new CipherSuite(0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA"),
- new CipherSuite(0x0022, "TLS_KRB5_WITH_DES_CBC_MD5"),
- new CipherSuite(0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5"),
- new CipherSuite(0x0024, "TLS_KRB5_WITH_RC4_128_MD5"),
- new CipherSuite(0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5"),
- new CipherSuite(0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA"),
- new CipherSuite(0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"),
- new CipherSuite(0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA"),
- new CipherSuite(0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5"),
- new CipherSuite(0x002a, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"),
- new CipherSuite(0x002b, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5"),
- new CipherSuite(0x002c, "TLS_PSK_WITH_NULL_SHA"),
- new CipherSuite(0x002d, "TLS_DHE_PSK_WITH_NULL_SHA"),
- new CipherSuite(0x002e, "TLS_RSA_PSK_WITH_NULL_SHA"),
- new CipherSuite(0x002f, "TLS_RSA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x003a, "TLS_DH_anon_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x003b, "TLS_RSA_WITH_NULL_SHA256"),
- new CipherSuite(0x003c, "TLS_RSA_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x003d, "TLS_RSA_WITH_AES_256_CBC_SHA256"),
- new CipherSuite(0x003e, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x003f, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"),
- new CipherSuite(0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA"),
- new CipherSuite(0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA"),
- new CipherSuite(0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"),
- new CipherSuite(0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"),
- new CipherSuite(0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"),
- new CipherSuite(0x0060, "TLS_RSA_EXPORT1024_WITH_RC4_56_MD5"),
- new CipherSuite(0x0061, "TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5"),
- new CipherSuite(0x0062, "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA"),
- new CipherSuite(0x0063, "TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA"),
- new CipherSuite(0x0064, "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA"),
- new CipherSuite(0x0065, "TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA"),
- new CipherSuite(0x0066, "TLS_DHE_DSS_WITH_RC4_128_SHA"),
- new CipherSuite(0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"),
- new CipherSuite(0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"),
- new CipherSuite(0x006a, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"),
- new CipherSuite(0x006b, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"),
- new CipherSuite(0x006c, "TLS_DH_anon_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x006d, "TLS_DH_anon_WITH_AES_256_CBC_SHA256"),
- new CipherSuite(0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"),
- new CipherSuite(0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA"),
- new CipherSuite(0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA"),
- new CipherSuite(0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"),
- new CipherSuite(0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"),
- new CipherSuite(0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"),
- new CipherSuite(0x008a, "TLS_PSK_WITH_RC4_128_SHA"),
- new CipherSuite(0x008b, "TLS_PSK_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x008c, "TLS_PSK_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x008d, "TLS_PSK_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x008e, "TLS_DHE_PSK_WITH_RC4_128_SHA"),
- new CipherSuite(0x008f, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA"),
- new CipherSuite(0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0x0096, "TLS_RSA_WITH_SEED_CBC_SHA"),
- new CipherSuite(0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA"),
- new CipherSuite(0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA"),
- new CipherSuite(0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA"),
- new CipherSuite(0x009a, "TLS_DHE_RSA_WITH_SEED_CBC_SHA"),
- new CipherSuite(0x009b, "TLS_DH_anon_WITH_SEED_CBC_SHA"),
- new CipherSuite(0x009c, "TLS_RSA_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x009d, "TLS_RSA_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x009e, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x009f, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x00a0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x00a1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x00a2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x00a3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x00a4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x00a5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x00a6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x00a7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x00a8, "TLS_PSK_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x00a9, "TLS_PSK_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x00aa, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x00ab, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x00ac, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0x00ad, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0x00ae, "TLS_PSK_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x00af, "TLS_PSK_WITH_AES_256_CBC_SHA384"),
- new CipherSuite(0x00b0, "TLS_PSK_WITH_NULL_SHA256"),
- new CipherSuite(0x00b1, "TLS_PSK_WITH_NULL_SHA384"),
- new CipherSuite(0x00b2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x00b3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"),
- new CipherSuite(0x00b4, "TLS_DHE_PSK_WITH_NULL_SHA256"),
- new CipherSuite(0x00b5, "TLS_DHE_PSK_WITH_NULL_SHA384"),
- new CipherSuite(0x00b6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0x00b7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"),
- new CipherSuite(0x00b8, "TLS_RSA_PSK_WITH_NULL_SHA256"),
- new CipherSuite(0x00b9, "TLS_RSA_PSK_WITH_NULL_SHA384"),
- new CipherSuite(0x00ba, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0x00bb, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0x00bc, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0x00bd, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0x00be, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0x00bf, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0x00c0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"),
- new CipherSuite(0x00c1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256"),
- new CipherSuite(0x00c2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256"),
- new CipherSuite(0x00c3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"),
- new CipherSuite(0x00c4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"),
- new CipherSuite(0x00c5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"),
- new CipherSuite(0x00ff, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"),
- new CipherSuite(0x5600, "TLS_FALLBACK_SCSV"),
- new CipherSuite(0xc001, "TLS_ECDH_ECDSA_WITH_NULL_SHA"),
- new CipherSuite(0xc002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"),
- new CipherSuite(0xc003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA"),
- new CipherSuite(0xc007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"),
- new CipherSuite(0xc008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc00a, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc00b, "TLS_ECDH_RSA_WITH_NULL_SHA"),
- new CipherSuite(0xc00c, "TLS_ECDH_RSA_WITH_RC4_128_SHA"),
- new CipherSuite(0xc00d, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc00e, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc00f, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc010, "TLS_ECDHE_RSA_WITH_NULL_SHA"),
- new CipherSuite(0xc011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA"),
- new CipherSuite(0xc012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc015, "TLS_ECDH_anon_WITH_NULL_SHA"),
- new CipherSuite(0xc016, "TLS_ECDH_anon_WITH_RC4_128_SHA"),
- new CipherSuite(0xc017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc01a, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc01b, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc01c, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc01d, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc01e, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc01f, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0xc024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"),
- new CipherSuite(0xc025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0xc026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"),
- new CipherSuite(0xc027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0xc028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"),
- new CipherSuite(0xc029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0xc02a, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"),
- new CipherSuite(0xc02b, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0xc02c, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0xc02d, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0xc02e, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0xc02f, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0xc030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0xc031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"),
- new CipherSuite(0xc032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"),
- new CipherSuite(0xc033, "TLS_ECDHE_PSK_WITH_RC4_128_SHA"),
- new CipherSuite(0xc034, "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA"),
- new CipherSuite(0xc035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"),
- new CipherSuite(0xc036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"),
- new CipherSuite(0xc037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"),
- new CipherSuite(0xc038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"),
- new CipherSuite(0xc039, "TLS_ECDHE_PSK_WITH_NULL_SHA"),
- new CipherSuite(0xc03a, "TLS_ECDHE_PSK_WITH_NULL_SHA256"),
- new CipherSuite(0xc03b, "TLS_ECDHE_PSK_WITH_NULL_SHA384"),
- new CipherSuite(0xc03c, "TLS_RSA_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc03d, "TLS_RSA_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc03e, "TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc03f, "TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc040, "TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc041, "TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc042, "TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc043, "TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc044, "TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc045, "TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc046, "TLS_DH_anon_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc047, "TLS_DH_anon_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc048, "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc049, "TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc04a, "TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc04b, "TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc04c, "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc04d, "TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc04e, "TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc04f, "TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc050, "TLS_RSA_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc051, "TLS_RSA_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc052, "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc053, "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc054, "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc055, "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc056, "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc057, "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc058, "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc059, "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc05a, "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc05b, "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc05c, "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc05d, "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc05e, "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc05f, "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc060, "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc061, "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc062, "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc063, "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc064, "TLS_PSK_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc065, "TLS_PSK_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc066, "TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc067, "TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc068, "TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc069, "TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc06a, "TLS_PSK_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc06b, "TLS_PSK_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc06c, "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc06d, "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc06e, "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256"),
- new CipherSuite(0xc06f, "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384"),
- new CipherSuite(0xc070, "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256"),
- new CipherSuite(0xc071, "TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384"),
- new CipherSuite(0xc072, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0xc073, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"),
- new CipherSuite(0xc074, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0xc075, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"),
- new CipherSuite(0xc076, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0xc077, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384"),
- new CipherSuite(0xc078, "TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0xc079, "TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384"),
- new CipherSuite(0xc07a, "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc07b, "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc07c, "TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc07d, "TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc07e, "TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc07f, "TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc080, "TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc081, "TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc082, "TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc083, "TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc084, "TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc085, "TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc086, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc087, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc088, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc089, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc08a, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc08b, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc08c, "TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc08d, "TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc08e, "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc08f, "TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc090, "TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc091, "TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc092, "TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256"),
- new CipherSuite(0xc093, "TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384"),
- new CipherSuite(0xc094, "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0xc095, "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384"),
- new CipherSuite(0xc096, "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0xc097, "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"),
- new CipherSuite(0xc098, "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0xc099, "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384"),
- new CipherSuite(0xc09a, "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"),
- new CipherSuite(0xc09b, "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"),
- new CipherSuite(0xc09c, "TLS_RSA_WITH_AES_128_CCM"),
- new CipherSuite(0xc09d, "TLS_RSA_WITH_AES_256_CCM"),
- new CipherSuite(0xc09e, "TLS_DHE_RSA_WITH_AES_128_CCM"),
- new CipherSuite(0xc09f, "TLS_DHE_RSA_WITH_AES_256_CCM"),
- new CipherSuite(0xc0a0, "TLS_RSA_WITH_AES_128_CCM_8"),
- new CipherSuite(0xc0a1, "TLS_RSA_WITH_AES_256_CCM_8"),
- new CipherSuite(0xc0a2, "TLS_DHE_RSA_WITH_AES_128_CCM_8"),
- new CipherSuite(0xc0a3, "TLS_DHE_RSA_WITH_AES_256_CCM_8"),
- new CipherSuite(0xc0a4, "TLS_PSK_WITH_AES_128_CCM"),
- new CipherSuite(0xc0a5, "TLS_PSK_WITH_AES_256_CCM"),
- new CipherSuite(0xc0a6, "TLS_DHE_PSK_WITH_AES_128_CCM"),
- new CipherSuite(0xc0a7, "TLS_DHE_PSK_WITH_AES_256_CCM"),
- new CipherSuite(0xc0a8, "TLS_PSK_WITH_AES_128_CCM_8"),
- new CipherSuite(0xc0a9, "TLS_PSK_WITH_AES_256_CCM_8"),
- new CipherSuite(0xc0aa, "TLS_PSK_DHE_WITH_AES_128_CCM_8"),
- new CipherSuite(0xc0ab, "TLS_PSK_DHE_WITH_AES_256_CCM_8"),
- new CipherSuite(0xc0ac, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM"),
- new CipherSuite(0xc0ad, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM"),
- new CipherSuite(0xc0ae, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8"),
- new CipherSuite(0xc0af, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"),
- new CipherSuite(0xcc13, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_OLD"),
- new CipherSuite(0xcc14, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_OLD"),
- new CipherSuite(0xcc15, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_OLD"),
- new CipherSuite(0xcca8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"),
- new CipherSuite(0xcca9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"),
- new CipherSuite(0xccaa, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"),
- new CipherSuite(0xccab, "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256"),
- new CipherSuite(0xccac, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256"),
- new CipherSuite(0xccad, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256"),
- new CipherSuite(0xccae, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256"),
- };
- private static final Map<Integer, CipherSuite> CODE_TO_CIPHER_SUITE;
- private static final Map<String, CipherSuite> NAME_TO_CIPHER_SUITE;
- static {
- Map<Integer, CipherSuite> byCode = new HashMap<Integer, CipherSuite>();
- Map<String, CipherSuite> byName = new HashMap<String, CipherSuite>();
- for (CipherSuite cipherSuite : CIPHER_SUITES) {
- if (byCode.put(cipherSuite.code, cipherSuite) != null) {
- throw new RuntimeException(
- "Cipher suite multiply defined: " + Integer.toHexString(cipherSuite.code));
- }
- String name = cipherSuite.name;
- if (byName.put(name, cipherSuite) != null) {
- throw new RuntimeException(
- "Cipher suite multiply defined: " + cipherSuite.name);
- }
- String androidName = cipherSuite.getAndroidName();
- if (!name.equals(androidName)) {
- if (byName.put(androidName, cipherSuite) != null) {
- throw new RuntimeException(
- "Cipher suite multiply defined: " + cipherSuite.androidName);
- }
- }
- }
- CODE_TO_CIPHER_SUITE = byCode;
- NAME_TO_CIPHER_SUITE = byName;
- }
- public final int code;
- public final String name;
- private final String androidName;
- private CipherSuite(int code, String name) {
- this.code = code;
- this.name = name;
- this.androidName = null;
- }
- private CipherSuite(int code, String name, String androidName) {
- this.code = code;
- this.name = name;
- this.androidName = androidName;
- }
- public static CipherSuite valueOf(String name) {
- CipherSuite result = NAME_TO_CIPHER_SUITE.get(name);
- if (result != null) {
- return result;
- }
- throw new IllegalArgumentException("Unknown cipher suite: " + name);
- }
- public static CipherSuite valueOf(int code) {
- CipherSuite result = CODE_TO_CIPHER_SUITE.get(code);
- if (result != null) {
- return result;
- }
- return new CipherSuite(code, Integer.toHexString(code));
- }
- public String getAndroidName() {
- return (androidName != null) ? androidName : name;
- }
- @Override
- public String toString() {
- return name;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + code;
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- CipherSuite other = (CipherSuite) obj;
- if (code != other.code) {
- return false;
- }
- return true;
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/handshake/ClientHello.java b/testing/src/main/java/libcore/tlswire/handshake/ClientHello.java
deleted file mode 100644
index 6349a1ab..00000000
--- a/testing/src/main/java/libcore/tlswire/handshake/ClientHello.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.handshake;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInput;
-import java.io.DataInputStream;
-import java.io.EOFException;
-import java.io.IOException;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import libcore.tlswire.util.IoUtils;
-import libcore.tlswire.util.TlsProtocolVersion;
-
-/**
- * {@link ClientHello} {@link HandshakeMessage} from TLS 1.2 RFC 5246.
- */
-public class ClientHello extends HandshakeMessage {
- public TlsProtocolVersion clientVersion;
- public byte[] random;
- public byte[] sessionId;
- public List<CipherSuite> cipherSuites;
- public List<CompressionMethod> compressionMethods;
- /** Extensions or {@code null} for no extensions. */
- public List<HelloExtension> extensions;
- @Override
- protected void parseBody(DataInput in) throws IOException {
- clientVersion = TlsProtocolVersion.read(in);
- random = new byte[32];
- in.readFully(random);
- sessionId = IoUtils.readTlsVariableLengthByteVector(in, 32);
- int[] cipherSuiteCodes = IoUtils.readTlsVariableLengthUnsignedShortVector(in, 0xfffe);
- cipherSuites = new ArrayList<CipherSuite>(cipherSuiteCodes.length);
- for (int i = 0; i < cipherSuiteCodes.length; i++) {
- cipherSuites.add(CipherSuite.valueOf(cipherSuiteCodes[i]));
- }
- byte[] compressionMethodCodes = IoUtils.readTlsVariableLengthByteVector(in, 0xff);
- compressionMethods = new ArrayList<CompressionMethod>(compressionMethodCodes.length);
- for (int i = 0; i < compressionMethodCodes.length; i++) {
- int code = compressionMethodCodes[i] & 0xff;
- compressionMethods.add(CompressionMethod.valueOf(code));
- }
- int extensionsSectionSize;
- try {
- extensionsSectionSize = in.readUnsignedShort();
- } catch (EOFException e) {
- // No extensions present
- extensionsSectionSize = 0;
- }
- if (extensionsSectionSize > 0) {
- extensions = new ArrayList<HelloExtension>();
- byte[] extensionsBytes = new byte[extensionsSectionSize];
- in.readFully(extensionsBytes);
- ByteArrayInputStream extensionsIn = new ByteArrayInputStream(extensionsBytes);
- DataInput extensionsDataIn = new DataInputStream(extensionsIn);
- while (extensionsIn.available() > 0) {
- try {
- extensions.add(HelloExtension.read(extensionsDataIn));
- } catch (IOException e) {
- throw new IOException(
- "Failed to read HelloExtension #" + (extensions.size() + 1));
- }
- }
- }
- }
- public HelloExtension findExtensionByType(int extensionType) {
- if (extensions == null) {
- return null;
- }
- for (HelloExtension extension : extensions) {
- if (extension.type == extensionType) {
- return extension;
- }
- }
- return null;
- }
- @Override
- public String toString() {
- return "ClientHello{client version: " + clientVersion + ", random: "
- + new BigInteger(1, random).toString(16) + ", sessionId: "
- + new BigInteger(1, sessionId).toString(16) + ", cipher suites: " + cipherSuites
- + ", compression methods: " + compressionMethods
- + ((extensions != null) ? (", extensions: " + String.valueOf(extensions)) : "")
- + "}";
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/handshake/CompressionMethod.java b/testing/src/main/java/libcore/tlswire/handshake/CompressionMethod.java
deleted file mode 100644
index 937e77e0..00000000
--- a/testing/src/main/java/libcore/tlswire/handshake/CompressionMethod.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.handshake;
-/**
- * {@code CompressionMethod} enum from TLS 1.2 RFC 5246.
- */
-public class CompressionMethod {
- public static final CompressionMethod NULL = new CompressionMethod(0, "null");
- public static final CompressionMethod DEFLATE = new CompressionMethod(1, "deflate");
- public final int type;
- public final String name;
- private CompressionMethod(int type, String name) {
- this.type = type;
- this.name = name;
- }
- public static CompressionMethod valueOf(int type) {
- switch (type) {
- case 0:
- return NULL;
- case 1:
- return DEFLATE;
- default:
- return new CompressionMethod(type, String.valueOf(type));
- }
- }
- @Override
- public String toString() {
- return name;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + type;
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- CompressionMethod other = (CompressionMethod) obj;
- if (type != other.type) {
- return false;
- }
- return true;
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/handshake/EllipticCurve.java b/testing/src/main/java/libcore/tlswire/handshake/EllipticCurve.java
deleted file mode 100644
index dbcee294..00000000
--- a/testing/src/main/java/libcore/tlswire/handshake/EllipticCurve.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 libcore.tlswire.handshake;
-/**
- * {@code EllipticCurve} enum from RFC 4492 section 5.1.1. Curves are assigned
- * via the
- * <a href="https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8">IANA registry</a>.
- */
-public enum EllipticCurve {
- SECT163K1(1, "sect163k1"),
- SECT163R1(2, "sect163r1"),
- SECT163R2(3, "sect163r2"),
- SECT193R1(4, "sect193r1"),
- SECT193R2(5, "sect193r2"),
- SECT233K1(6, "sect233k1"),
- SECT233R1(7, "sect233r1"),
- SECT239K1(8, "sect239k1"),
- SECT283K1(9, "sect283k1"),
- SECT283R1(10, "sect283r1"),
- SECT409K1(11, "sect409k1"),
- SECT409R1(12, "sect409r1"),
- SECT571K1(13, "sect571k1"),
- SECT571R1(14, "sect571r1"),
- SECP160K1(15, "secp160k1"),
- SECP160R1(16, "secp160r1"),
- SECP160R2(17, "secp160r2"),
- SECP192K1(18, "secp192k1"),
- SECP192R1(19, "secp192r1"),
- SECP224K1(20, "secp224k1"),
- SECP224R1(21, "secp224r1"),
- SECP256K1(22, "secp256k1"),
- SECP256R1(23, "secp256r1"),
- SECP384R1(24, "secp384r1"),
- SECP521R1(25, "secp521r1"),
- BRAINPOOLP256R1(26, "brainpoolP256r1"),
- BRAINPOOLP384R1(27, "brainpoolP384r1"),
- BRAINPOOLP521R1(28, "brainpoolP521r1"),
- X25519(29, "x25519"),
- X448(30, "x448"),
- ARBITRARY_PRIME(0xFF01, "arbitrary_explicit_prime_curves"),
- ARBITRARY_CHAR2(0xFF02, "arbitrary_explicit_char2_curves");
- public final int identifier;
- public final String name;
- private EllipticCurve(int identifier, String name) {
- this.identifier = identifier;
- this.name = name;
- }
- public static EllipticCurve fromIdentifier(int identifier) {
- for (EllipticCurve curve : values()) {
- if (curve.identifier == identifier) {
- return curve;
- }
- }
- throw new AssertionError("Unknown curve identifier " + identifier);
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder(name);
- sb.append(" (");
- sb.append(identifier);
- sb.append(')');
- return sb.toString();
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/handshake/EllipticCurvesHelloExtension.java b/testing/src/main/java/libcore/tlswire/handshake/EllipticCurvesHelloExtension.java
deleted file mode 100644
index 8a6932ae..00000000
--- a/testing/src/main/java/libcore/tlswire/handshake/EllipticCurvesHelloExtension.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 libcore.tlswire.handshake;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import libcore.tlswire.util.IoUtils;
-
-/**
- * {@code elliptic_curves} {@link HelloExtension} from RFC 4492 section 5.1.1.
- */
-public class EllipticCurvesHelloExtension extends HelloExtension {
- public List<EllipticCurve> supported;
- public boolean wellFormed;
- @Override
- protected void parseData() throws IOException {
- byte[] ellipticCurvesListBytes = IoUtils.readTlsVariableLengthByteVector(
- new DataInputStream(new ByteArrayInputStream(data)), 0xffff);
- ByteArrayInputStream ellipticCurvesListIn =
- new ByteArrayInputStream(ellipticCurvesListBytes);
- DataInputStream in = new DataInputStream(ellipticCurvesListIn);
- wellFormed = (ellipticCurvesListIn.available() % 2) == 0;
- supported = new ArrayList<EllipticCurve>(ellipticCurvesListIn.available() / 2);
- while (ellipticCurvesListIn.available() >= 2) {
- int curve_id = in.readUnsignedShort();
- supported.add(EllipticCurve.fromIdentifier(curve_id));
- }
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("HelloExtension{type: elliptic_curves, wellFormed: ");
- sb.append(wellFormed);
- sb.append(", supported: ");
- sb.append(supported);
- sb.append('}');
- return sb.toString();
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/handshake/HandshakeMessage.java b/testing/src/main/java/libcore/tlswire/handshake/HandshakeMessage.java
deleted file mode 100644
index 6287bf8f..00000000
--- a/testing/src/main/java/libcore/tlswire/handshake/HandshakeMessage.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.handshake;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInput;
-import java.io.DataInputStream;
-import java.io.IOException;
-import libcore.tlswire.util.IoUtils;
-
-/**
- * Handshake Protocol message from TLS 1.2 RFC 5246.
- */
-public class HandshakeMessage {
- public static final int TYPE_CLIENT_HELLO = 1;
- public int type;
- public byte[] body;
- /**
- * Parses the provided TLS record as a handshake message.
- */
- public static HandshakeMessage read(DataInput in) throws IOException {
- int type = in.readUnsignedByte();
- HandshakeMessage result;
- switch (type) {
- case TYPE_CLIENT_HELLO:
- result = new ClientHello();
- break;
- default:
- result = new HandshakeMessage();
- break;
- }
- result.type = type;
- int bodyLength = IoUtils.readUnsignedInt24(in);
- result.body = new byte[bodyLength];
- in.readFully(result.body);
- result.parseBody(new DataInputStream(new ByteArrayInputStream(result.body)));
- return result;
- }
- /**
- * Parses the provided body. The default implementation does nothing.
- *
- * @throws IOException if an I/O error occurs.
- */
- protected void parseBody(@SuppressWarnings("unused") DataInput in) throws IOException {}
-}
diff --git a/testing/src/main/java/libcore/tlswire/handshake/HelloExtension.java b/testing/src/main/java/libcore/tlswire/handshake/HelloExtension.java
deleted file mode 100644
index b49c4cea..00000000
--- a/testing/src/main/java/libcore/tlswire/handshake/HelloExtension.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.handshake;
-
-import java.io.DataInput;
-import java.io.IOException;
-import java.math.BigInteger;
-import java.util.HashMap;
-import java.util.Map;
-import libcore.tlswire.util.IoUtils;
-
-/**
- * {@code HelloExtension} struct from TLS 1.2 RFC 5246.
- */
-public class HelloExtension {
- public static final int TYPE_SERVER_NAME = 0;
- public static final int TYPE_ELLIPTIC_CURVES = 10;
- public static final int TYPE_PADDING = 21;
- public static final int TYPE_SESSION_TICKET = 35;
- public static final int TYPE_RENEGOTIATION_INFO = 65281;
- private static final Map<Integer, String> TYPE_TO_NAME = new HashMap<Integer, String>();
- static {
- TYPE_TO_NAME.put(TYPE_SERVER_NAME, "server_name");
- TYPE_TO_NAME.put(1, "max_fragment_length");
- TYPE_TO_NAME.put(2, "client_certificate_url");
- TYPE_TO_NAME.put(3, "trusted_ca_keys");
- TYPE_TO_NAME.put(4, "truncated_hmac");
- TYPE_TO_NAME.put(5, "status_request");
- TYPE_TO_NAME.put(6, "user_mapping");
- TYPE_TO_NAME.put(7, "client_authz");
- TYPE_TO_NAME.put(8, "server_authz");
- TYPE_TO_NAME.put(9, "cert_type");
- TYPE_TO_NAME.put(TYPE_ELLIPTIC_CURVES, "elliptic_curves");
- TYPE_TO_NAME.put(11, "ec_point_formats");
- TYPE_TO_NAME.put(12, "srp");
- TYPE_TO_NAME.put(13, "signature_algorithms");
- TYPE_TO_NAME.put(14, "use_srtp");
- TYPE_TO_NAME.put(15, "heartbeat");
- TYPE_TO_NAME.put(16, "application_layer_protocol_negotiation");
- TYPE_TO_NAME.put(17, "status_request_v2");
- TYPE_TO_NAME.put(18, "signed_certificate_timestamp");
- TYPE_TO_NAME.put(19, "client_certificate_type");
- TYPE_TO_NAME.put(20, "server_certificate_type");
- TYPE_TO_NAME.put(TYPE_PADDING, "padding");
- TYPE_TO_NAME.put(TYPE_SESSION_TICKET, "SessionTicket");
- TYPE_TO_NAME.put(13172, "next_protocol_negotiation");
- TYPE_TO_NAME.put(30031, "Channel ID (old)");
- TYPE_TO_NAME.put(30032, "Channel ID (new)");
- TYPE_TO_NAME.put(TYPE_RENEGOTIATION_INFO, "renegotiation_info");
- }
- public int type;
- public String name;
- public byte[] data;
- public static HelloExtension read(DataInput in) throws IOException {
- int type = in.readUnsignedShort();
- HelloExtension result;
- switch (type) {
- case TYPE_SERVER_NAME:
- result = new ServerNameHelloExtension();
- break;
- case TYPE_ELLIPTIC_CURVES:
- result = new EllipticCurvesHelloExtension();
- break;
- default:
- result = new HelloExtension();
- break;
- }
- result.type = type;
- result.name = TYPE_TO_NAME.get(result.type);
- if (result.name == null) {
- result.name = String.valueOf(result.type);
- }
- result.data = IoUtils.readTlsVariableLengthByteVector(in, 0xffff);
- result.parseData();
- return result;
- }
- /**
- * @throws IOException
- */
- protected void parseData() throws IOException {}
- @Override
- public String toString() {
- return "HelloExtension{type: " + name + ", data: " + new BigInteger(1, data).toString(16)
- + "}";
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/handshake/ServerNameHelloExtension.java b/testing/src/main/java/libcore/tlswire/handshake/ServerNameHelloExtension.java
deleted file mode 100644
index 438c3341..00000000
--- a/testing/src/main/java/libcore/tlswire/handshake/ServerNameHelloExtension.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.handshake;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import libcore.tlswire.util.IoUtils;
-
-/**
- * {@code server_name} (SNI) {@link HelloExtension} from TLS 1.2 RFC 5246.
- */
-public class ServerNameHelloExtension extends HelloExtension {
- private static final int TYPE_HOST_NAME = 0;
- public List<String> hostnames;
- @Override
- protected void parseData() throws IOException {
- byte[] serverNameListBytes = IoUtils.readTlsVariableLengthByteVector(
- new DataInputStream(new ByteArrayInputStream(data)), 0xffff);
- ByteArrayInputStream serverNameListIn = new ByteArrayInputStream(serverNameListBytes);
- DataInputStream in = new DataInputStream(serverNameListIn);
- hostnames = new ArrayList<String>();
- while (serverNameListIn.available() > 0) {
- int type = in.readUnsignedByte();
- if (type != TYPE_HOST_NAME) {
- throw new IOException("Unsupported ServerName type: " + type);
- }
- byte[] hostnameBytes = IoUtils.readTlsVariableLengthByteVector(in, 0xffff);
- String hostname = new String(hostnameBytes, "US-ASCII");
- hostnames.add(hostname);
- }
- }
- @Override
- public String toString() {
- return "HelloExtension{type: server_name, hostnames: " + hostnames + "}";
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/record/TlsProtocols.java b/testing/src/main/java/libcore/tlswire/record/TlsProtocols.java
deleted file mode 100644
index e9c29c4c..00000000
--- a/testing/src/main/java/libcore/tlswire/record/TlsProtocols.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.record;
-/**
- * Protocols that can run over the TLS Record Protocol from TLS 1.2 RFC 5246.
- */
-public class TlsProtocols {
- public static final int CHANGE_CIPHER_SPEC = 20;
- public static final int ALERT = 21;
- public static final int HANDSHAKE = 22;
- public static final int APPLICATION_DATA = 23;
- public static final int HEARTBEAT = 24;
- private TlsProtocols() {}
-}
diff --git a/testing/src/main/java/libcore/tlswire/record/TlsRecord.java b/testing/src/main/java/libcore/tlswire/record/TlsRecord.java
deleted file mode 100644
index ea653684..00000000
--- a/testing/src/main/java/libcore/tlswire/record/TlsRecord.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.record;
-
-import java.io.DataInput;
-import java.io.IOException;
-import libcore.tlswire.util.TlsProtocolVersion;
-
-/**
- * TLS Record Protocol record from TLS 1.2 RFC 5246.
- */
-public class TlsRecord {
- public int type;
- public TlsProtocolVersion version;
- public byte[] fragment;
- public static TlsRecord read(DataInput in) throws IOException {
- TlsRecord result = new TlsRecord();
- result.type = in.readUnsignedByte();
- result.version = TlsProtocolVersion.read(in);
- int fragmentLength = in.readUnsignedShort();
- result.fragment = new byte[fragmentLength];
- in.readFully(result.fragment);
- return result;
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/util/IoUtils.java b/testing/src/main/java/libcore/tlswire/util/IoUtils.java
deleted file mode 100644
index f700c1aa..00000000
--- a/testing/src/main/java/libcore/tlswire/util/IoUtils.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.util;
-import java.io.DataInput;
-import java.io.IOException;
-public class IoUtils {
- public static int readUnsignedInt24(DataInput in) throws IOException {
- return (in.readUnsignedByte() << 16) | in.readUnsignedShort();
- }
- public static byte[] readTlsVariableLengthByteVector(DataInput in, int maxSizeBytes)
- throws IOException {
- int sizeBytes = readTlsVariableLengthVectorSizeBytes(in, maxSizeBytes);
- byte[] result = new byte[sizeBytes];
- in.readFully(result);
- return result;
- }
- public static int[] readTlsVariableLengthUnsignedShortVector(DataInput in, int maxSizeBytes)
- throws IOException {
- int sizeBytes = readTlsVariableLengthVectorSizeBytes(in, maxSizeBytes);
- int elementCount = sizeBytes / 2;
- int[] result = new int[elementCount];
- for (int i = 0; i < elementCount; i++) {
- result[i] = in.readUnsignedShort();
- }
- return result;
- }
- private static int readTlsVariableLengthVectorSizeBytes(DataInput in, int maxSizeBytes)
- throws IOException {
- if (maxSizeBytes < 0x100) {
- return in.readUnsignedByte();
- } else if (maxSizeBytes < 0x10000) {
- return in.readUnsignedShort();
- } else if (maxSizeBytes < 0x1000000) {
- return readUnsignedInt24(in);
- } else {
- return in.readInt();
- }
- }
-}
diff --git a/testing/src/main/java/libcore/tlswire/util/TlsProtocolVersion.java b/testing/src/main/java/libcore/tlswire/util/TlsProtocolVersion.java
deleted file mode 100644
index a1774c13..00000000
--- a/testing/src/main/java/libcore/tlswire/util/TlsProtocolVersion.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 libcore.tlswire.util;
-import java.io.DataInput;
-import java.io.IOException;
-/**
- * {@code ProtovolVersion} struct from TLS 1.2 RFC 5246.
- */
-public class TlsProtocolVersion {
- public static final TlsProtocolVersion SSLV3 = new TlsProtocolVersion(3, 0, "SSLv3");
- public static final TlsProtocolVersion TLSv1_0 = new TlsProtocolVersion(3, 1, "TLSv1.0");
- public static final TlsProtocolVersion TLSv1_1 = new TlsProtocolVersion(3, 2, "TLSv1.1");
- public static final TlsProtocolVersion TLSv1_2 = new TlsProtocolVersion(3, 3, "TLSv1.2");
- public final int major;
- public final int minor;
- public final String name;
- private TlsProtocolVersion(int major, int minor, String name) {
- this.major = major;
- this.minor = minor;
- this.name = name;
- }
- public static TlsProtocolVersion valueOf(int major, int minor) {
- if (major == 3) {
- switch (minor) {
- case 0:
- return SSLV3;
- case 1:
- return TLSv1_0;
- case 2:
- return TLSv1_1;
- case 3:
- return TLSv1_2;
- }
- }
- return new TlsProtocolVersion(major, minor, major + "." + minor);
- }
- public static TlsProtocolVersion read(DataInput in) throws IOException {
- int major = in.readUnsignedByte();
- int minor = in.readUnsignedByte();
- return TlsProtocolVersion.valueOf(major, minor);
- }
- @Override
- public String toString() {
- return name;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + major;
- result = prime * result + minor;
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- TlsProtocolVersion other = (TlsProtocolVersion) obj;
- if (major != other.major) {
- return false;
- }
- if (minor != other.minor) {
- return false;
- }
- return true;
- }
-}
diff --git a/testing/src/main/java/org/conscrypt/TestUtils.java b/testing/src/main/java/org/conscrypt/TestUtils.java
index ef14e4ba..9f496ea9 100644
--- a/testing/src/main/java/org/conscrypt/TestUtils.java
+++ b/testing/src/main/java/org/conscrypt/TestUtils.java
@@ -45,45 +45,16 @@ public final class TestUtils {
static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Provider JDK_PROVIDER = getDefaultTlsProvider();
+ private static final Provider CONSCRYPT_PROVIDER = getConscryptProvider();
private static final byte[] CHARS =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".getBytes(UTF_8);
public static final String PROTOCOL_TLS_V1_2 = "TLSv1.2";
- public static final String PROVIDER_PROPERTY = "SSLContext.TLSv1.2";
+ private static final String PROVIDER_PROPERTY = "SSLContext.TLSv1.2";
public static final String LOCALHOST = "localhost";
private TestUtils() {}
- private static Provider getDefaultTlsProvider() {
- for (Provider p : Security.getProviders()) {
- if (p.get(PROVIDER_PROPERTY) != null) {
- return p;
- }
- }
- throw new RuntimeException("Unable to find a default provider for " + PROVIDER_PROPERTY);
- }
-
- public static Provider getConscryptProvider() {
- try {
- return (Provider) conscryptClass("OpenSSLProvider")
- .getConstructor()
- .newInstance();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void installConscryptAsDefaultProvider() {
- final Provider conscryptProvider = getConscryptProvider();
- synchronized (getConscryptProvider()) {
- Provider[] providers = Security.getProviders();
- if (providers.length == 0 || !providers[0].equals(conscryptProvider)) {
- Security.insertProviderAt(conscryptProvider, 1);
- return;
- }
- }
- }
-
public static InputStream openTestFile(String name) throws FileNotFoundException {
InputStream is = TestUtils.class.getResourceAsStream("/" + name);
if (is == null) {
@@ -97,42 +68,26 @@ public final class TestUtils {
}
/**
- * Looks up the conscrypt class for the given simple name (i.e. no package prefix).
- */
- public static Class<?> conscryptClass(String simpleName) throws ClassNotFoundException {
- ClassNotFoundException ex = null;
- for (String packageName : new String[]{"com.android.org.conscrypt", "org.conscrypt"}) {
- String name = packageName + "." + simpleName;
- try {
- return Class.forName(name);
- } catch (ClassNotFoundException e) {
- ex = e;
- }
- }
- throw ex;
- }
-
- /**
* Returns an array containing only {@link #PROTOCOL_TLS_V1_2}.
*/
- public static String[] getProtocols() {
+ static String[] getProtocols() {
return new String[] {PROTOCOL_TLS_V1_2};
}
- public static SSLSocketFactory getJdkSocketFactory() {
+ static SSLSocketFactory getJdkSocketFactory() {
return getSocketFactory(JDK_PROVIDER);
}
- public static SSLServerSocketFactory getJdkServerSocketFactory() {
+ static SSLServerSocketFactory getJdkServerSocketFactory() {
return getServerSocketFactory(JDK_PROVIDER);
}
- public static SSLSocketFactory getConscryptSocketFactory(boolean useEngineSocket) {
+ static SSLSocketFactory getConscryptSocketFactory(boolean useEngineSocket) {
try {
- Class<?> clazz = conscryptClass("Conscrypt$SocketFactories");
+ Class<?> clazz = Class.forName("org.conscrypt.Conscrypt$SocketFactories");
Method method = clazz.getMethod("setUseEngineSocket", SSLSocketFactory.class, boolean.class);
- SSLSocketFactory socketFactory = getSocketFactory(getConscryptProvider());
+ SSLSocketFactory socketFactory = getSocketFactory(CONSCRYPT_PROVIDER);
method.invoke(null, socketFactory, useEngineSocket);
return socketFactory;
} catch (Exception e) {
@@ -140,12 +95,12 @@ public final class TestUtils {
}
}
- public static SSLServerSocketFactory getConscryptServerSocketFactory(boolean useEngineSocket) {
+ static SSLServerSocketFactory getConscryptServerSocketFactory(boolean useEngineSocket) {
try {
- Class<?> clazz = conscryptClass("Conscrypt$ServerSocketFactories");
+ Class<?> clazz = Class.forName("org.conscrypt.Conscrypt$ServerSocketFactories");
Method method = clazz.getMethod("setUseEngineSocket", SSLServerSocketFactory.class, boolean.class);
- SSLServerSocketFactory socketFactory = getServerSocketFactory(getConscryptProvider());
+ SSLServerSocketFactory socketFactory = getServerSocketFactory(CONSCRYPT_PROVIDER);
method.invoke(null, socketFactory, useEngineSocket);
return socketFactory;
} catch (Exception e) {
@@ -177,7 +132,7 @@ public final class TestUtils {
* returned port to create a new server socket when other threads/processes are concurrently
* creating new sockets without a specific port.
*/
- public static int pickUnusedPort() {
+ static int pickUnusedPort() {
try {
ServerSocket serverSocket = new ServerSocket(0);
int port = serverSocket.getLocalPort();
@@ -191,7 +146,7 @@ public final class TestUtils {
/**
* Creates a text message of the given length.
*/
- public static byte[] newTextMessage(int length) {
+ static byte[] newTextMessage(int length) {
byte[] msg = new byte[length];
for (int msgIndex = 0; msgIndex < length;) {
int remaining = length - msgIndex;
@@ -205,7 +160,7 @@ public final class TestUtils {
/**
* Initializes the given engine with the cipher and client mode.
*/
- public static SSLEngine initEngine(SSLEngine engine, String cipher, boolean client) {
+ static SSLEngine initEngine(SSLEngine engine, String cipher, boolean client) {
engine.setEnabledProtocols(getProtocols());
engine.setEnabledCipherSuites(new String[] {cipher});
engine.setUseClientMode(client);
@@ -215,14 +170,14 @@ public final class TestUtils {
/**
* Initializes the given client-side {@code context} with a default cert.
*/
- public static SSLContext initClientSslContext(SSLContext context) {
+ private static SSLContext initClientSslContext(SSLContext context) {
return initSslContext(context, TestKeyStore.getClient());
}
/**
* Initializes the given server-side {@code context} with the given cert chain and private key.
*/
- public static SSLContext initServerSslContext(SSLContext context) {
+ private static SSLContext initServerSslContext(SSLContext context) {
return initSslContext(context, TestKeyStore.getServer());
}
@@ -241,7 +196,7 @@ public final class TestUtils {
/**
* Performs the intial TLS handshake between the two {@link SSLEngine} instances.
*/
- public static void doEngineHandshake(SSLEngine clientEngine, SSLEngine serverEngine)
+ static void doEngineHandshake(SSLEngine clientEngine, SSLEngine serverEngine)
throws SSLException {
ByteBuffer cTOs = ByteBuffer.allocate(clientEngine.getSession().getPacketBufferSize());
ByteBuffer sTOc = ByteBuffer.allocate(serverEngine.getSession().getPacketBufferSize());
@@ -339,4 +294,23 @@ public final class TestUtils {
}
}
}
+
+ private static Provider getDefaultTlsProvider() {
+ for (Provider p : Security.getProviders()) {
+ if (p.get(PROVIDER_PROPERTY) != null) {
+ return p;
+ }
+ }
+ throw new RuntimeException("Unable to find a default provider for " + PROVIDER_PROPERTY);
+ }
+
+ private static Provider getConscryptProvider() {
+ try {
+ return (Provider) Class.forName("org.conscrypt.OpenSSLProvider")
+ .getConstructor()
+ .newInstance();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/testing/src/main/java/tests/net/DelegatingSSLSocketFactory.java b/testing/src/main/java/tests/net/DelegatingSSLSocketFactory.java
deleted file mode 100644
index d2754f6d..00000000
--- a/testing/src/main/java/tests/net/DelegatingSSLSocketFactory.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * 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 tests.net;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-/**
- * {@link SSLSocketFactory} which delegates all invocations to the provided delegate
- * {@code SSLSocketFactory}.
- */
-public class DelegatingSSLSocketFactory extends SSLSocketFactory {
- private final SSLSocketFactory mDelegate;
- public DelegatingSSLSocketFactory(SSLSocketFactory delegate) {
- this.mDelegate = delegate;
- }
- /**
- * Invoked after obtaining a socket from the delegate and before returning it to the caller.
- *
- * <p>The default implementation does nothing.
- */
- protected SSLSocket configureSocket(SSLSocket socket) throws IOException {
- return socket;
- }
- @Override
- public String[] getDefaultCipherSuites() {
- return mDelegate.getDefaultCipherSuites();
- }
- @Override
- public String[] getSupportedCipherSuites() {
- return mDelegate.getSupportedCipherSuites();
- }
- @Override
- public Socket createSocket() throws IOException {
- SSLSocket socket = (SSLSocket) mDelegate.createSocket();
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(Socket s, String host, int port, boolean autoClose)
- throws IOException {
- SSLSocket socket = (SSLSocket) mDelegate.createSocket(s, host, port, autoClose);
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- SSLSocket socket = (SSLSocket) mDelegate.createSocket(host, port);
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- SSLSocket socket = (SSLSocket) mDelegate.createSocket(host, port, localHost, localPort);
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- SSLSocket socket = (SSLSocket) mDelegate.createSocket(host, port);
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException {
- SSLSocket socket = (SSLSocket) mDelegate.createSocket(address, port, localAddress, localPort);
- return configureSocket(socket);
- }
-}
diff --git a/testing/src/main/java/tests/net/DelegatingSocketFactory.java b/testing/src/main/java/tests/net/DelegatingSocketFactory.java
deleted file mode 100644
index e4bce79f..00000000
--- a/testing/src/main/java/tests/net/DelegatingSocketFactory.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * 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 tests.net;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import javax.net.SocketFactory;
-/**
- * {@link SocketFactory} which delegates all invocations to the provided delegate
- * {@code SocketFactory}.
- */
-public class DelegatingSocketFactory extends SocketFactory {
- private final SocketFactory mDelegate;
- public DelegatingSocketFactory(SocketFactory delegate) {
- this.mDelegate = delegate;
- }
- /**
- * Invoked after obtaining a socket from the delegate and before returning it to the caller.
- *
- * <p>The default implementation does nothing.
- */
- protected Socket configureSocket(Socket socket) throws IOException {
- return socket;
- }
- @Override
- public Socket createSocket() throws IOException {
- Socket socket = mDelegate.createSocket();
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- Socket socket = mDelegate.createSocket(host, port);
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- Socket socket = mDelegate.createSocket(host, port, localHost, localPort);
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- Socket socket = mDelegate.createSocket(host, port);
- return configureSocket(socket);
- }
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException {
- Socket socket = mDelegate.createSocket(address, port, localAddress, localPort);
- return configureSocket(socket);
- }
-}
diff --git a/testing/src/main/java/tests/util/ForEachRunner.java b/testing/src/main/java/tests/util/ForEachRunner.java
deleted file mode 100644
index 1c246aad..00000000
--- a/testing/src/main/java/tests/util/ForEachRunner.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * 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 tests.util;
-/**
- * Runner which executes the provided code under test (via a callback) for each provided input
- * value.
- */
-public final class ForEachRunner {
- /**
- * Callback parameterized with a value.
- */
- public interface Callback<T> {
- /**
- * Invokes the callback for the provided value.
- */
- void run(T value) throws Exception;
- }
- private ForEachRunner() {}
- /**
- * Invokes the provided callback for each of the provided named values.
- *
- * @param namesAndValues named values represented as name-value pairs.
- *
- * @param <T> type of value.
- */
- public static <T> void runNamed(Callback<T> callback, Iterable<Pair<String, T>> namesAndValues)
- throws Exception {
- for (Pair<String, T> nameAndValue : namesAndValues) {
- try {
- callback.run(nameAndValue.getSecond());
- } catch (Throwable e) {
- throw new Exception("Failed for " + nameAndValue.getFirst() + ": " + e.getMessage(), e);
- }
- }
- }
-}
diff --git a/testing/src/main/java/tests/util/Pair.java b/testing/src/main/java/tests/util/Pair.java
deleted file mode 100644
index 979fc447..00000000
--- a/testing/src/main/java/tests/util/Pair.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * 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 tests.util;
-/**
- * Pair of typed values.
- *
- * <p>Pairs are obtained using {@link #of(Object, Object) of}.
- *
- * @param <F> type of the first value.
- * @param <S> type of the second value.
- */
-public class Pair<F, S> {
- private final F mFirst;
- private final S mSecond;
- private Pair(F first, S second) {
- mFirst = first;
- mSecond = second;
- }
- /**
- * Gets the pair consisting of the two provided values.
- *
- * @param first first value or {@code null}.
- * @param second second value or {@code null}.
- */
- public static <F, S> Pair<F, S> of(F first, S second) {
- return new Pair<F, S>(first, second);
- }
- /**
- * Gets the first value from this pair.
- *
- * @return value or {@code null}.
- */
- public F getFirst() {
- return mFirst;
- }
- /**
- * Gets the second value from this pair.
- *
- * @return value or {@code null}.
- */
- public S getSecond() {
- return mSecond;
- }
- @Override
- public String toString() {
- return "Pair[" + mFirst + ", " + mSecond + "]";
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode());
- result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- @SuppressWarnings("rawtypes")
- Pair other = (Pair) obj;
- if (mFirst == null) {
- if (other.mFirst != null) {
- return false;
- }
- } else if (!mFirst.equals(other.mFirst)) {
- return false;
- }
- if (mSecond == null) {
- if (other.mSecond != null) {
- return false;
- }
- } else if (!mSecond.equals(other.mSecond)) {
- return false;
- }
- return true;
- }
-}