diff options
author | Kenny Root <kroot@google.com> | 2013-04-29 23:11:34 -0700 |
---|---|---|
committer | Android Git Automerger <android-git-automerger@android.com> | 2013-04-29 23:11:34 -0700 |
commit | 033c85712e2d91657e2f5df8743d2fd0ddbf5a2d (patch) | |
tree | b1182cb45be0b790b3bdf04cec1b070372fef42a /luni/src/test | |
parent | e3cfd0d894d8b3b4bf54367d3631334d85760bcc (diff) | |
parent | 0800e47a2e19f185b7a62f1d26a74748db0cc047 (diff) | |
download | libcore-033c85712e2d91657e2f5df8743d2fd0ddbf5a2d.zip libcore-033c85712e2d91657e2f5df8743d2fd0ddbf5a2d.tar.gz libcore-033c85712e2d91657e2f5df8743d2fd0ddbf5a2d.tar.bz2 |
am 0800e47a: Merge "Move JSSE to new package"
* commit '0800e47a2e19f185b7a62f1d26a74748db0cc047':
Move JSSE to new package
Diffstat (limited to 'luni/src/test')
12 files changed, 4 insertions, 4281 deletions
diff --git a/luni/src/test/java/libcore/java/security/SecureRandomTest.java b/luni/src/test/java/libcore/java/security/SecureRandomTest.java index 8199120..7adb9a9 100644 --- a/luni/src/test/java/libcore/java/security/SecureRandomTest.java +++ b/luni/src/test/java/libcore/java/security/SecureRandomTest.java @@ -16,8 +16,6 @@ package libcore.java.security; -import org.apache.harmony.xnet.provider.jsse.OpenSSLProvider; - import java.security.Provider; import java.security.SecureRandom; import java.security.Security; @@ -27,7 +25,7 @@ import java.util.Set; import junit.framework.TestCase; public class SecureRandomTest extends TestCase { - private static final Class<? extends Provider> EXPECTED_PROVIDER = OpenSSLProvider.class; + private static final String EXPECTED_PROVIDER = "org.conscrypt.OpenSSLProvider"; private static final byte[] STATIC_SEED_BYTES = new byte[] { 0x0A, (byte) 0xA0, 0x01, 0x10, (byte) 0xFF, (byte) 0xF0, 0x0F @@ -99,16 +97,16 @@ public class SecureRandomTest extends TestCase { public void testGetCommonInstances_Success() throws Exception { SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); assertNotNull(sr); - assertEquals(EXPECTED_PROVIDER, sr.getProvider().getClass()); + assertEquals(EXPECTED_PROVIDER, sr.getProvider().getClass().getName()); } public void testNewConstructors_Success() throws Exception { SecureRandom sr1 = new SecureRandom(); - assertEquals(EXPECTED_PROVIDER, sr1.getProvider().getClass()); + assertEquals(EXPECTED_PROVIDER, sr1.getProvider().getClass().getName()); test_SecureRandom(sr1); SecureRandom sr2 = new SecureRandom(STATIC_SEED_BYTES); - assertEquals(EXPECTED_PROVIDER, sr2.getProvider().getClass()); + assertEquals(EXPECTED_PROVIDER, sr2.getProvider().getClass().getName()); test_SecureRandom(sr2); } } diff --git a/luni/src/test/java/libcore/java/security/SignatureTest.java b/luni/src/test/java/libcore/java/security/SignatureTest.java index 4afc67d..7f8b4f4 100644 --- a/luni/src/test/java/libcore/java/security/SignatureTest.java +++ b/luni/src/test/java/libcore/java/security/SignatureTest.java @@ -16,10 +16,6 @@ package libcore.java.security; -import org.apache.harmony.xnet.provider.jsse.NativeCryptoTest; -import org.apache.harmony.xnet.provider.jsse.OpenSSLEngine; -import org.apache.harmony.xnet.provider.jsse.OpenSSLProvider; - import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.KeyFactory; @@ -31,7 +27,6 @@ import java.security.PublicKey; import java.security.Security; import java.security.Signature; import java.security.SignatureException; -import java.security.interfaces.RSAPrivateKey; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; @@ -86,78 +81,6 @@ public class SignatureTest extends TestCase { } } - public void test_getInstance_OpenSSL_ENGINE() throws Exception { - final String pem_private = "-----BEGIN RSA PRIVATE KEY-----\n" - + "MIICXAIBAAKBgQDpm4KamxulJnycEzNONGM7p0CvAaoZxJEd5Dvio5b6BROdCtRN\n" - + "lEsB+9vtB5thkyDVC7N+IW0AjtyDE6h2QP+AWa+c4dh0RM2uNVXkUWPrA8C++GHv\n" - + "EDlxZzRGiQEMuippYfIyBVkO+4+GRvnkG4dKjzxrQYPqKUK3C4PgFW2FewIDAQAB\n" - + "AoGAGUTSBsk6X03fcr588TundD9uNr/2V1002Ufj1msdnKPJ8FXIiy+8QVWt/2Cw\n" - + "RQi2J3VhkAYrlUDex2rr8Qas3E9uuwKgg/MZ4EsJbnKKgkd7uBZfmZ2ogcNJ82u7\n" - + "teVijFpdsVLDa9aczEppt5sZzyTaBrovrRb+AIRDpMw3I0ECQQD3JkWeQUA9Is1V\n" - + "z0X/ly/kaQKQLlrwYNdiKF0qOpyTLAguI7asAS72Zj7fThk5bHLM+mmgYwkicIIb\n" - + "67J32GQbAkEA8fkXqEnwMFYSkRmT9M/qUkwWUsMW12/AoZFI5gwKNDHZYxytGGLw\n" - + "mC//0qKnyeUG00vz06vLApe4/Sq4ODe6IQJBALEGastF9ZtUuDsEciD2y8kRJlLb\n" - + "wSt4Ug3u13yN6uTHnzxdPFTLrDW1WsdcC1lEQp5rpwjIpxxR9f/FvVl2V40CQHOY\n" - + "F6EhkUjGFaCTo4b0PHCMQK3Q3PyWOmP0z+p2HfnJRpx+eoKH4YASjhfF9HoSmywd\n" - + "wKGCFD1s1ca7vb29gYECQH86GmYZsDoLNWurEVJbkmCr7X1+xwim6umdrNKR27P7\n" - + "F1y0Sa3YY+LiiRb+IRSWE/onlP+28LIzWGF4lcTfDMc=\n" - + "-----END RSA PRIVATE KEY-----"; - - final byte[] der_public = new byte[] { - (byte) 0x30, (byte) 0x81, (byte) 0x9F, (byte) 0x30, (byte) 0x0D, (byte) 0x06, - (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xF7, - (byte) 0x0D, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x05, (byte) 0x00, - (byte) 0x03, (byte) 0x81, (byte) 0x8D, (byte) 0x00, (byte) 0x30, (byte) 0x81, - (byte) 0x89, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xE9, - (byte) 0x9B, (byte) 0x82, (byte) 0x9A, (byte) 0x9B, (byte) 0x1B, (byte) 0xA5, - (byte) 0x26, (byte) 0x7C, (byte) 0x9C, (byte) 0x13, (byte) 0x33, (byte) 0x4E, - (byte) 0x34, (byte) 0x63, (byte) 0x3B, (byte) 0xA7, (byte) 0x40, (byte) 0xAF, - (byte) 0x01, (byte) 0xAA, (byte) 0x19, (byte) 0xC4, (byte) 0x91, (byte) 0x1D, - (byte) 0xE4, (byte) 0x3B, (byte) 0xE2, (byte) 0xA3, (byte) 0x96, (byte) 0xFA, - (byte) 0x05, (byte) 0x13, (byte) 0x9D, (byte) 0x0A, (byte) 0xD4, (byte) 0x4D, - (byte) 0x94, (byte) 0x4B, (byte) 0x01, (byte) 0xFB, (byte) 0xDB, (byte) 0xED, - (byte) 0x07, (byte) 0x9B, (byte) 0x61, (byte) 0x93, (byte) 0x20, (byte) 0xD5, - (byte) 0x0B, (byte) 0xB3, (byte) 0x7E, (byte) 0x21, (byte) 0x6D, (byte) 0x00, - (byte) 0x8E, (byte) 0xDC, (byte) 0x83, (byte) 0x13, (byte) 0xA8, (byte) 0x76, - (byte) 0x40, (byte) 0xFF, (byte) 0x80, (byte) 0x59, (byte) 0xAF, (byte) 0x9C, - (byte) 0xE1, (byte) 0xD8, (byte) 0x74, (byte) 0x44, (byte) 0xCD, (byte) 0xAE, - (byte) 0x35, (byte) 0x55, (byte) 0xE4, (byte) 0x51, (byte) 0x63, (byte) 0xEB, - (byte) 0x03, (byte) 0xC0, (byte) 0xBE, (byte) 0xF8, (byte) 0x61, (byte) 0xEF, - (byte) 0x10, (byte) 0x39, (byte) 0x71, (byte) 0x67, (byte) 0x34, (byte) 0x46, - (byte) 0x89, (byte) 0x01, (byte) 0x0C, (byte) 0xBA, (byte) 0x2A, (byte) 0x69, - (byte) 0x61, (byte) 0xF2, (byte) 0x32, (byte) 0x05, (byte) 0x59, (byte) 0x0E, - (byte) 0xFB, (byte) 0x8F, (byte) 0x86, (byte) 0x46, (byte) 0xF9, (byte) 0xE4, - (byte) 0x1B, (byte) 0x87, (byte) 0x4A, (byte) 0x8F, (byte) 0x3C, (byte) 0x6B, - (byte) 0x41, (byte) 0x83, (byte) 0xEA, (byte) 0x29, (byte) 0x42, (byte) 0xB7, - (byte) 0x0B, (byte) 0x83, (byte) 0xE0, (byte) 0x15, (byte) 0x6D, (byte) 0x85, - (byte) 0x7B, (byte) 0x02, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x01 - }; - - // We only need to test this on the OpenSSL provider. - Provider p = Security.getProvider(OpenSSLProvider.PROVIDER_NAME); - - /* ENGINE-based private key */ - NativeCryptoTest.loadTestEngine(); - OpenSSLEngine engine = OpenSSLEngine.getInstance(NativeCryptoTest.TEST_ENGINE_ID); - PrivateKey privKey = engine.getPrivateKeyById(pem_private); - assertTrue(privKey instanceof RSAPrivateKey); - - /* Non-ENGINE-based public key */ - KeyFactory kf = KeyFactory.getInstance("RSA", p); - PublicKey pubKey = kf.generatePublic(new X509EncodedKeySpec(der_public)); - - KeyPair kp = new KeyPair(pubKey, privKey); - - Set<Provider.Service> services = p.getServices(); - for (Provider.Service service : services) { - if ("Signature".equals(service.getType()) && service.getAlgorithm().contains("RSA")) { - Signature sig1 = Signature.getInstance(service.getAlgorithm(), p); - test_Signature(sig1, kp); - } - } - - } - private final Map<String, KeyPair> keypairAlgorithmToInstance = new HashMap<String, KeyPair>(); diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java index d65dd4b..b1559f5 100644 --- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java +++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java @@ -22,7 +22,6 @@ package org.apache.harmony.crypto.tests.javax.crypto; -import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; @@ -30,7 +29,6 @@ import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; -import java.security.spec.DSAParameterSpec; import java.security.spec.PSSParameterSpec; import java.util.Arrays; @@ -44,9 +42,6 @@ import javax.crypto.spec.SecretKeySpec; import org.apache.harmony.crypto.tests.support.MyMacSpi; import org.apache.harmony.security.tests.support.SpiEngUtils; -import org.apache.harmony.xnet.provider.jsse.NativeCryptoTest; -import org.apache.harmony.xnet.provider.jsse.OpenSSLEngine; -import org.apache.harmony.xnet.provider.jsse.OpenSSLProvider; import junit.framework.TestCase; @@ -891,46 +886,6 @@ public class MacTest extends TestCase { } } - public void test_getInstance_OpenSSL_ENGINE() throws Exception { - final String secret = "-HMAC-test1"; - final byte[] testString = "testing123".getBytes(); - - Provider p = Security.getProvider(OpenSSLProvider.PROVIDER_NAME); - NativeCryptoTest.loadTestEngine(); - OpenSSLEngine engine = OpenSSLEngine.getInstance(NativeCryptoTest.TEST_ENGINE_ID); - - /* - * The "-HMAC-" prefix is a special prefix recognized by - * test_openssl_engine.cpp - */ - SecretKey key1 = engine.getSecretKeyById(secret, "HmacSHA256"); - SecretKey key1dupe = engine.getSecretKeyById(secret, "HmacSHA256"); - - /* Non-ENGINE-based SecretKey */ - SecretKey key2 = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); - - /* The one that is ENGINE-based can't be equal to a non-ENGINE one. */ - assertFalse(key1.equals(key2)); - assertEquals(key1, key1dupe); - assertNull(key1.getFormat()); - assertNull(key1.getEncoded()); - assertEquals("RAW", key2.getFormat()); - assertEquals(Arrays.toString(secret.getBytes()), Arrays.toString(key2.getEncoded())); - - Mac mac1 = Mac.getInstance("HmacSHA256", p); - mac1.init(key1); - mac1.update(testString); - byte[] output1 = mac1.doFinal(); - assertEquals(mac1.getMacLength(), output1.length); - - Mac mac2 = Mac.getInstance("HmacSHA256", p); - mac2.init(key2); - mac2.update(testString); - byte[] output2 = mac2.doFinal(); - - assertEquals(Arrays.toString(output2), Arrays.toString(output1)); - } - class Mock_Mac extends Mac { protected Mock_Mac(MacSpi arg0, Provider arg1, String arg2) { super(arg0, arg1, arg2); diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/CertPinManagerTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/CertPinManagerTest.java deleted file mode 100644 index 8359c99..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/CertPinManagerTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) 2012 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.apache.harmony.xnet.provider.jsse; - -import java.io.File; -import java.io.FileWriter; -import java.security.cert.X509Certificate; -import java.security.KeyStore; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.List; -import junit.framework.TestCase; -import libcore.java.security.TestKeyStore; - -public class CertPinManagerTest extends TestCase { - - private X509Certificate[] chain; - private List<X509Certificate> shortChain; - private List<X509Certificate> longChain; - private String shortPin; - private String longPin; - private List<File> tmpFiles = new ArrayList<File>(); - - private String writeTmpPinFile(String text) throws Exception { - File tmp = File.createTempFile("pins", null); - FileWriter fstream = new FileWriter(tmp); - fstream.write(text); - fstream.close(); - tmpFiles.add(tmp); - return tmp.getPath(); - } - - private static String getFingerprint(X509Certificate cert) throws NoSuchAlgorithmException { - MessageDigest dgst = MessageDigest.getInstance("SHA512"); - byte[] encoded = cert.getPublicKey().getEncoded(); - byte[] fingerprint = dgst.digest(encoded); - return IntegralToString.bytesToHexString(fingerprint, false); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - // build some valid chains - KeyStore.PrivateKeyEntry pke = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); - chain = (X509Certificate[]) pke.getCertificateChain(); - X509Certificate root = chain[2]; - X509Certificate server = chain[0]; - - // build the short and long chains - shortChain = new ArrayList<X509Certificate>(); - shortChain.add(root); - longChain = new ArrayList<X509Certificate>(); - longChain.add(server); - - // we'll use the root as the pin for the short entry and the server as the pin for the long - shortPin = getFingerprint(root); - longPin = getFingerprint(server); - } - - @Override - public void tearDown() throws Exception { - try { - for (File f : tmpFiles) { - f.delete(); - } - tmpFiles.clear(); - } finally { - super.tearDown(); - } - } - - public void testPinFileMaximumLookup() throws Exception { - - // write a pinfile with two entries, one longer than the other - String shortEntry = "*.google.com=true|" + shortPin; - String longEntry = "*.clients.google.com=true|" + longPin; - - // create the pinFile - String path = writeTmpPinFile(shortEntry + "\n" + longEntry); - CertPinManager pf = new CertPinManager(path, new TrustedCertificateStore()); - - // verify that the shorter chain doesn't work for a name matching the longer - assertTrue("short chain long uri failed", - pf.chainIsNotPinned("android.clients.google.com", shortChain)); - // verify that the longer chain doesn't work for a name matching the shorter - assertTrue("long chain short uri failed", - pf.chainIsNotPinned("android.google.com", longChain)); - // verify that the shorter chain works for the shorter domain - assertTrue("short chain short uri failed", - !pf.chainIsNotPinned("android.google.com", shortChain)); - // and the same for the longer - assertTrue("long chain long uri failed", - !pf.chainIsNotPinned("android.clients.google.com", longChain)); - } - - public void testPinEntryMalformedEntry() throws Exception { - // set up the pinEntry with a bogus entry - String entry = "*.google.com="; - try { - new PinListEntry(entry, new TrustedCertificateStore()); - fail("Accepted an empty pin list entry."); - } catch (PinEntryException expected) { - } - } - - public void testPinEntryNull() throws Exception { - // set up the pinEntry with a bogus entry - String entry = null; - try { - new PinListEntry(entry, new TrustedCertificateStore()); - fail("Accepted a basically wholly bogus entry."); - } catch (NullPointerException expected) { - } - } - - public void testPinEntryEmpty() throws Exception { - // set up the pinEntry with a bogus entry - try { - new PinListEntry("", new TrustedCertificateStore()); - fail("Accepted an empty entry."); - } catch (PinEntryException expected) { - } - } - - public void testPinEntryPinFailure() throws Exception { - // write a pinfile with two entries, one longer than the other - String shortEntry = "*.google.com=true|" + shortPin; - - // set up the pinEntry with a pinlist that doesn't match what we'll give it - PinListEntry e = new PinListEntry(shortEntry, new TrustedCertificateStore()); - assertTrue("Not enforcing!", e.getEnforcing()); - // verify that it doesn't accept - boolean retval = e.chainIsNotPinned(longChain); - assertTrue("Accepted an incorrect pinning, this is very bad", retval); - } - - public void testPinEntryPinSuccess() throws Exception { - // write a pinfile with two entries, one longer than the other - String shortEntry = "*.google.com=true|" + shortPin; - - // set up the pinEntry with a pinlist that matches what we'll give it - PinListEntry e = new PinListEntry(shortEntry, new TrustedCertificateStore()); - assertTrue("Not enforcing!", e.getEnforcing()); - // verify that it accepts - boolean retval = e.chainIsNotPinned(shortChain); - assertTrue("Failed on a correct pinning, this is very bad", !retval); - } - - public void testPinEntryNonEnforcing() throws Exception { - // write a pinfile with two entries, one longer than the other - String shortEntry = "*.google.com=false|" + shortPin; - - // set up the pinEntry with a pinlist that matches what we'll give it - PinListEntry e = new PinListEntry(shortEntry, new TrustedCertificateStore()); - assertFalse("Enforcing!", e.getEnforcing()); - // verify that it accepts - boolean retval = e.chainIsNotPinned(shortChain); - assertTrue("Failed on an unenforced pinning, this is bad-ish", !retval); - } -} diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ChainStrengthAnalyzerTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ChainStrengthAnalyzerTest.java deleted file mode 100644 index 42585b9..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ChainStrengthAnalyzerTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2011 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.apache.harmony.xnet.provider.jsse; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import junit.framework.TestCase; - -public class ChainStrengthAnalyzerTest extends TestCase { - - //openssl req -x509 -nodes -days 365 -subj '/C=US/ST=Testsota/L=Testville/CN=test.com' \ - //-newkey rsa:2048 -sha256 -keyout k.pem -out good.pem - private static final String GOOD_PEM = "" + - "-----BEGIN CERTIFICATE-----\n" + - "MIIDYTCCAkmgAwIBAgIJAPFX8KGuEZcgMA0GCSqGSIb3DQEBCwUAMEcxCzAJBgNV\n" + - "BAYTAlVTMREwDwYDVQQIDAhUZXN0c290YTESMBAGA1UEBwwJVGVzdHZpbGxlMREw\n" + - "DwYDVQQDDAh0ZXN0LmNvbTAeFw0xMjEwMTUyMTQ0MTBaFw0xMzEwMTUyMTQ0MTBa\n" + - "MEcxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhUZXN0c290YTESMBAGA1UEBwwJVGVz\n" + - "dHZpbGxlMREwDwYDVQQDDAh0ZXN0LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP\n" + - "ADCCAQoCggEBAM44hz3eTINuAIS9OYmg6DkUIj3MItn5dgbcMEdbXrhNpeWY93ho\n" + - "WQFfsqcSSx28NzqKJmnX+cyinzIUfVde/qciP9P7fxRDokRsf34DJ6gXQplz6P2t\n" + - "s4CWjYM+WXJrvEUgLUQ3CBV0CCrtYvG1B9wYsBdAdWkVaMxTvEt7aVxcvJYzp+KU\n" + - "ME7HDg0PVxptvUExIskcqKVmW7i748AgBLhd0r1nFWLuH20d42Aowja0Wi19fWl2\n" + - "SEMErDRjG8jIPUdSoOLPVLGTktEpex51xnAaZ+I7hy6zs55dq8ua/hE/v2cXIkiQ\n" + - "ZXpWyvI/MaKEfeydLnNpa7J3GpH3KW93HQcCAwEAAaNQME4wHQYDVR0OBBYEFA0M\n" + - "RI+3hIPCSpVVArisr3Y3/sheMB8GA1UdIwQYMBaAFA0MRI+3hIPCSpVVArisr3Y3\n" + - "/sheMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFgUNyuy2qaJvgDO\n" + - "plYudTrJR38O3id1B5oKOzgTEgRrfmHHfyloY4fL5gjAGNp7vdlDKSHC2Ebo23/X\n" + - "Wg535MJ2296R855jaTMdkSE0+4ASpdmon1D007H0FhLyojlKVta3pqMAF1zsp0YF\n" + - "Mf3V/rVMDxCOnbSnqAX0+1nW8Qm4Jgrr3AAMafZk6ypq0xuNQn+sUWuIWw3Xv5Jl\n" + - "KehjnuKtMgVYkn2ItRNnUdhm2dQK+Phdb5Yg8WHXN/r9sZQdORg8FQS9TfQJmimB\n" + - "CVYuqA9Dt0JJZPuO/Pd1yAxWP4NpxX1xr3lNQ5jrTO702QA3gOrscluULLzrYR50\n" + - "FoAjeos=\n" + - "-----END CERTIFICATE-----"; - - //openssl req -x509 -nodes -days 365 -subj '/C=US/ST=Testsota/L=Testville/CN=test.com' \ - //-newkey rsa:2048 -md5 -keyout k.pem -out md5.pem - private static final String MD5_PEM = "" + - "-----BEGIN CERTIFICATE-----\n" + - "MIIDYTCCAkmgAwIBAgIJAJsffMf2cyx0MA0GCSqGSIb3DQEBBAUAMEcxCzAJBgNV\n" + - "BAYTAlVTMREwDwYDVQQIDAhUZXN0c290YTESMBAGA1UEBwwJVGVzdHZpbGxlMREw\n" + - "DwYDVQQDDAh0ZXN0LmNvbTAeFw0xMjEwMTUyMTQzMzZaFw0xMzEwMTUyMTQzMzZa\n" + - "MEcxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhUZXN0c290YTESMBAGA1UEBwwJVGVz\n" + - "dHZpbGxlMREwDwYDVQQDDAh0ZXN0LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP\n" + - "ADCCAQoCggEBAOJyiUwgf/VsdbTTdx6dsb742adeBFBY1FpSWCeQW/JVtdMephbK\n" + - "AA00nu8Xq3dNx9bp8AqvzeyHi/RBsZOtb2eAsOXE3RbFy28ehDTHdG34fRQNT6kp\n" + - "RUHw8wrUGovMVqS8j+iW8HfAy3sjArje0ygz2NIETlNQbEOifAJtY+AEfZwZE0/0\n" + - "IMVP4hwTmIgyReJBDmAx31clwsWZSPar9x+WQfeJ3rfy5LBCtf3RUbdgnvynBHFk\n" + - "FjucwoqgOOXviCWxIa0F+ZAmZJBj5+pLN/V92RXOu0c2fR3Mf68J67OJ+K4ueo1N\n" + - "nBhRsulWMmGqIVjYOZQxiNzWYcOVXj3DTRMCAwEAAaNQME4wHQYDVR0OBBYEFJbY\n" + - "TU06RuJaiMBs2vzx5y0MbaQOMB8GA1UdIwQYMBaAFJbYTU06RuJaiMBs2vzx5y0M\n" + - "baQOMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBAFEky0jLTmKefDVX\n" + - "8O84KoupmQ2qQQBaQF3F5GEuhi0qJRwnmsWkCmsxPP55S67WDFp3JH+LX14UxL4T\n" + - "fbG2CXHt/BF1yU3Z8JBwx3bDmfUnUOAFkO3nmByb11FyZTHMzq4jp03DexWREv4q\n" + - "Ai5+5Xb56VECgCH/hnGqhQeFGhlZUcSXobVhAU+39L6azWELXxk1K4bpVxYFGn1N\n" + - "uZ+dWmb6snPKDzG6J5IIX8QIs6G8H6ptj+QNoU/qTcZEnuzMJxpqMsyq10AA+bY/\n" + - "VAYyXeZm3XZrtqYosDeiUdmcL0jjmyQtyOcAoVUQWj1EJuRjXg4BvI6xxRAIPWYT\n" + - "EDeWHJE=\n" + - "-----END CERTIFICATE-----"; - - //openssl req -x509 -nodes -days 365 -subj '/C=US/ST=Testsota/L=Testville/CN=test.com' \ - //-newkey rsa:512 -sha256 -keyout k.pem -out short.pem - private static final String SHORT_PEM = "" + - "-----BEGIN CERTIFICATE-----\n" + - "MIIB1zCCAYGgAwIBAgIJAOxaz9TreDNIMA0GCSqGSIb3DQEBCwUAMEcxCzAJBgNV\n" + - "BAYTAlVTMREwDwYDVQQIDAhUZXN0c290YTESMBAGA1UEBwwJVGVzdHZpbGxlMREw\n" + - "DwYDVQQDDAh0ZXN0LmNvbTAeFw0xMjEwMTUyMTQzMjNaFw0xMzEwMTUyMTQzMjNa\n" + - "MEcxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhUZXN0c290YTESMBAGA1UEBwwJVGVz\n" + - "dHZpbGxlMREwDwYDVQQDDAh0ZXN0LmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgC\n" + - "QQCoMgxK9HG0L+hXEht1mKq6ApN3+3lmIEVUcWQKL7EMmn9+L6rVSJyOAGwpTVG7\n" + - "eZ5uulC0Lkm5/bzKFSrCf1jlAgMBAAGjUDBOMB0GA1UdDgQWBBTda66RZsgUvR4e\n" + - "2RSsq65K1xcz0jAfBgNVHSMEGDAWgBTda66RZsgUvR4e2RSsq65K1xcz0jAMBgNV\n" + - "HRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA0EAZWYgoNDn6yEzcmWgsYnG3w2BT6fL\n" + - "Npi0+APKWkwxnEJk1kgpdeSTMgaHAphQ8qksHnSgeBAJSs2ZCQMinVPgOg==\n" + - "-----END CERTIFICATE-----"; - - public void testMD5() throws Exception { - assertBad(MD5_PEM, "Weak hash check did not fail as expected"); - } - - public void test512() throws Exception { - assertBad(SHORT_PEM, "Short modulus check did not fail as expected"); - } - - public void testGoodChain() throws Exception { - assertGood(GOOD_PEM); - } - - private static void assertBad(String pem, String msg) throws Exception { - try { - check(createCert(pem)); - fail(msg); - } catch (CertificateException expected) { - } - } - - private static void assertGood(String pem) throws Exception { - check(createCert(pem)); - } - - private static void check(X509Certificate cert) throws Exception { - X509Certificate[] chain = {cert}; - ChainStrengthAnalyzer.check(chain); - } - - private static X509Certificate createCert(String pem) throws Exception { - CertificateFactory cf = CertificateFactory.getInstance("X509"); - InputStream pemInput = new ByteArrayInputStream(pem.getBytes()); - return (X509Certificate) cf.generateCertificate(pemInput); - } -}
\ No newline at end of file diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/CipherSuiteTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/CipherSuiteTest.java deleted file mode 100644 index 7adecaf..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/CipherSuiteTest.java +++ /dev/null @@ -1,167 +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 org.apache.harmony.xnet.provider.jsse; - -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.crypto.Cipher; -import javax.crypto.Mac; -import junit.framework.TestCase; -import libcore.java.security.StandardNames; -import org.apache.harmony.xnet.provider.jsse.CipherSuite; - -public class CipherSuiteTest extends TestCase { - public void test_getByName() throws Exception { - for (String name : StandardNames.CIPHER_SUITES) { - if (name.equals(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION)) { - assertNull(CipherSuite.getByName(name)); - } else { - test_CipherSuite(name); - } - } - - assertNull(CipherSuite.getByName("bogus")); - try { - CipherSuite.getByName(null); - fail(); - } catch (NullPointerException expected) { - } - } - - private void test_CipherSuite(String name) throws Exception { - CipherSuite cs = CipherSuite.getByName(name); - assertNotNull(name, cs); - assertEquals(name, cs.getName()); - test_CipherSuite(cs); - } - - private void test_CipherSuite(CipherSuite cs) throws Exception { - assertNotNull(cs); - - String name = cs.getName(); - assertNotNull(name); - assertSame(name, cs, CipherSuite.getByName(name)); - assertTrue(name, StandardNames.CIPHER_SUITES.contains(name)); - assertTrue(name, name.startsWith("SSL_") || name.startsWith("TLS_")); - - assertEquals(cs.isAnonymous(), name.contains("_anon_")); - - byte[] bytes = cs.toBytes(); - assertNotNull(name, bytes); - assertEquals(name, 2, bytes.length); - assertTrue(name + bytes[0], bytes[0] == (byte) 0x00 || bytes[0] == (byte) 0xc0); - assertSame(name, cs, CipherSuite.getByCode(bytes[0], bytes[1])); - assertSame(name, cs, CipherSuite.getByCode((byte) 0, bytes[0], bytes[1])); - - assertTrue(name, cs.toString().contains(name)); - - String bulkEncryptionAlgorithm = cs.getBulkEncryptionAlgorithm(); - int blockSize = cs.getBlockSize(); - if (bulkEncryptionAlgorithm == null) { - assertTrue(name, name.contains("_NULL_")); - assertEquals(name, 0, blockSize); - } else { - assertNotNull(name, Cipher.getInstance(cs.getBulkEncryptionAlgorithm())); - assertTrue(name, blockSize == 0 || blockSize == 8 || blockSize == 16); - } - - String hmacName = cs.getHmacName(); - assertNotNull(name, hmacName); - assertNotNull(name, Mac.getInstance(hmacName)); - - String hashName = cs.getHashName(); - assertNotNull(name, hashName); - assertNotNull(name, MessageDigest.getInstance(hashName)); - - int macLength = cs.getMACLength(); - assertTrue(name, macLength == 0 || macLength == 16 || macLength == 20); - - assertTrue(name, - cs.isExportable() == name.contains("_EXPORT_") - || cs.isExportable() == name.contains("_NULL_")); - - String keyType = cs.getServerKeyType(); - assertEquals(name, cs.isAnonymous(), keyType == null); - assertTrue(name, keyType == null || StandardNames.KEY_TYPES.contains(keyType)); - } - - public void test_getByCode() { - // CipherSuite.getByCode is also covered by test_CipherSuite - assertUnknown(CipherSuite.getByCode((byte) 0x12, (byte) 0x34)); - assertUnknown(CipherSuite.getByCode((byte) 0x12, (byte) 0x34, (byte) 0x56)); - assertUnknown(CipherSuite.getByCode((byte) -1, (byte) -1)); - assertUnknown(CipherSuite.getByCode((byte) -1, (byte) -1, (byte) -1)); - } - private void assertUnknown(CipherSuite cs) { - assertNotNull(cs); - assertNotNull(cs.getName().contains("UNKNOWN")); - } - - public void test_getSupported() throws Exception { - CipherSuite[] suites = CipherSuite.getSupported(); - List<String> names = new ArrayList<String>(suites.length); - for (CipherSuite cs : suites) { - test_CipherSuite(cs); - names.add(cs.getName()); - } - assertEquals(Arrays.asList(CipherSuite.getSupportedCipherSuiteNames()), names); - } - - public void test_getSupportedCipherSuiteNames() throws Exception { - String[] names = CipherSuite.getSupportedCipherSuiteNames(); - StandardNames.assertSupportedCipherSuites(StandardNames.CIPHER_SUITES_SSLENGINE, names); - for (String name : names) { - test_CipherSuite(name); - } - } - - public void test_getClientKeyType() throws Exception { - byte b = Byte.MIN_VALUE; - do { - String byteString = Byte.toString(b); - String keyType = CipherSuite.getClientKeyType(b); - switch (b) { - case 1: - assertEquals(byteString, "RSA", keyType); - break; - case 2: - assertEquals(byteString, "DSA", keyType); - break; - case 3: - assertEquals(byteString, "DH_RSA", keyType); - break; - case 4: - assertEquals(byteString, "DH_DSA", keyType); - break; - case 64: - assertEquals(byteString, "EC", keyType); - break; - case 65: - assertEquals(byteString, "EC_RSA", keyType); - break; - case 66: - assertEquals(byteString, "EC_EC", keyType); - break; - default: - assertNull(byteString, keyType); - } - b++; - } while (b != Byte.MIN_VALUE); - } -} diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java deleted file mode 100644 index 6d17a25..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2009 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.apache.harmony.xnet.provider.jsse; - -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; -import javax.net.ssl.SSLSession; -import junit.framework.TestCase; -import libcore.javax.net.ssl.FakeSSLSession; - -public final class ClientSessionContextTest extends TestCase { - - public void testSimpleAddition() { - ClientSessionContext context = new ClientSessionContext(); - SSLSession a = new ValidSSLSession("a"); - SSLSession b = new ValidSSLSession("b"); - - context.putSession(a); - assertSessionContextContents(context, new SSLSession[] { a }, new SSLSession[] { b }); - - context.putSession(b); - assertSessionContextContents(context, new SSLSession[] { a, b }, new SSLSession[0]); - } - - public void testTrimToSize() { - ClientSessionContext context = new ClientSessionContext(); - ValidSSLSession a = new ValidSSLSession("a"); - ValidSSLSession b = new ValidSSLSession("b"); - ValidSSLSession c = new ValidSSLSession("c"); - ValidSSLSession d = new ValidSSLSession("d"); - - context.putSession(a); - assertSessionContextContents(context, new SSLSession[] { a }, new SSLSession[] { b, c, d }); - - context.putSession(b); - assertSessionContextContents(context, new SSLSession[] { a, b }, new SSLSession[] { c, d }); - - context.putSession(c); - assertSessionContextContents(context, new SSLSession[] { a, b, c }, new SSLSession[] { d }); - - context.putSession(d); - assertSessionContextContents(context, new SSLSession[] { a, b, c, d }, new SSLSession[0]); - - context.setSessionCacheSize(2); - assertSessionContextContents(context, new SSLSession[] { c, d }, new SSLSession[] { a, b }); - } - - public void testImplicitRemovalOfOldest() { - ClientSessionContext context = new ClientSessionContext(); - context.setSessionCacheSize(2); - ValidSSLSession a = new ValidSSLSession("a"); - ValidSSLSession b = new ValidSSLSession("b"); - ValidSSLSession c = new ValidSSLSession("c"); - ValidSSLSession d = new ValidSSLSession("d"); - - context.putSession(a); - assertSessionContextContents(context, new SSLSession[] { a }, new SSLSession[] { b, c, d }); - - context.putSession(b); - assertSessionContextContents(context, new SSLSession[] { a, b }, new SSLSession[] { c, d }); - - context.putSession(c); - assertSessionContextContents(context, new SSLSession[] { b, c }, new SSLSession[] { a, d }); - - context.putSession(d); - assertSessionContextContents(context, new SSLSession[] { c, d }, new SSLSession[] { a, b }); - } - - private static void assertSessionContextContents(ClientSessionContext context, - SSLSession[] contains, - SSLSession[] exludes) { - assertEquals(contains.length, context.size()); - - for (SSLSession s : contains) { - assertSame(s.getPeerHost(), s, context.getSession(s.getId())); - assertSame(s.getPeerHost(), s, context.getSession(s.getPeerHost(), 443)); - } - for (SSLSession s : exludes) { - assertNull(s.getPeerHost(), context.getSession(s.getId())); - assertNull(s.getPeerHost(), context.getSession(s.getPeerHost(), 443)); - } - - Set<SSLSession> sessions = new HashSet<SSLSession>(); - Enumeration<byte[]> ids = context.getIds(); - while (ids.hasMoreElements()) { - byte[] id = ids.nextElement(); - sessions.add(context.getSession(id)); - } - - Set<SSLSession> expected = new HashSet<SSLSession>(); - for (SSLSession s : sessions) { - expected.add(s); - } - assertEquals(expected, sessions); - } - - static class ValidSSLSession extends FakeSSLSession { - ValidSSLSession(String host) { - super(host); - } - @Override public boolean isValid() { - return true; - } - } -} diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java deleted file mode 100644 index 9714cc3..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2009 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.apache.harmony.xnet.provider.jsse; - -import java.io.File; -import java.io.IOException; -import junit.framework.TestCase; -import libcore.javax.net.ssl.FakeSSLSession; - -public class FileClientSessionCacheTest extends TestCase { - - public void testMaxSize() throws IOException, InterruptedException { - String tmpDir = System.getProperty("java.io.tmpdir"); - if (tmpDir == null) { - fail("Please set 'java.io.tmpdir' system property."); - } - File cacheDir = new File(tmpDir - + "/" + FileClientSessionCacheTest.class.getName() + "/cache"); - final SSLClientSessionCache cache - = FileClientSessionCache.usingDirectory(cacheDir); - Thread[] threads = new Thread[10]; - final int iterations = FileClientSessionCache.MAX_SIZE * 10; - for (int i = 0; i < threads.length; i++) { - final int id = i; - threads[i] = new Thread() { - @Override - public void run() { - for (int i = 0; i < iterations; i++) { - cache.putSessionData(new FakeSSLSession(id + "" + i), new byte[10]); - } - } - }; - } - for (Thread thread : threads) { - thread.start(); - } - for (Thread thread : threads) { - thread.join(); - } - assertEquals(FileClientSessionCache.MAX_SIZE, cacheDir.list().length); - } -} diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/NativeCryptoTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/NativeCryptoTest.java deleted file mode 100644 index f456f3e..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/NativeCryptoTest.java +++ /dev/null @@ -1,2573 +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 org.apache.harmony.xnet.provider.jsse; - -import dalvik.system.BaseDexClassLoader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileDescriptor; -import java.io.IOException; -import java.math.BigInteger; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore; -import java.security.KeyStore.PrivateKeyEntry; -import java.security.PrivateKey; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.security.interfaces.DSAPublicKey; -import java.security.interfaces.ECPublicKey; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.ECPrivateKeySpec; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLProtocolException; -import javax.security.auth.x500.X500Principal; -import junit.framework.TestCase; -import libcore.io.IoUtils; -import libcore.java.security.StandardNames; -import libcore.java.security.TestKeyStore; -import org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSLHandshakeCallbacks; -import static org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_MODE_HANDSHAKE_CUTTHROUGH; - -public class NativeCryptoTest extends TestCase { - /** Corresponds to the native test library "libjavacoretests.so" */ - public static final String TEST_ENGINE_ID = "javacoretests"; - - private static final long NULL = 0; - private static final FileDescriptor INVALID_FD = new FileDescriptor(); - private static final SSLHandshakeCallbacks DUMMY_CB - = new TestSSLHandshakeCallbacks(null, 0, null); - - private static final long TIMEOUT_SECONDS = 5; - - private static byte[] SERVER_PRIVATE_KEY; - private static byte[][] SERVER_CERTIFICATES; - private static byte[] CLIENT_PRIVATE_KEY; - private static byte[][] CLIENT_CERTIFICATES; - private static byte[][] CA_PRINCIPALS; - private static PrivateKey CHANNEL_ID_PRIVATE_KEY; - private static byte[] CHANNEL_ID; - - @Override - protected void tearDown() throws Exception { - assertEquals(0, NativeCrypto.ERR_peek_last_error()); - } - - private static byte[] getServerPrivateKey() { - initCerts(); - return SERVER_PRIVATE_KEY; - } - - private static byte[][] getServerCertificates() { - initCerts(); - return SERVER_CERTIFICATES; - } - - private static byte[] getClientPrivateKey() { - initCerts(); - return CLIENT_PRIVATE_KEY; - } - - private static byte[][] getClientCertificates() { - initCerts(); - return CLIENT_CERTIFICATES; - } - - private static byte[][] getCaPrincipals() { - initCerts(); - return CA_PRINCIPALS; - } - - /** - * Lazily create shared test certificates. - */ - private static synchronized void initCerts() { - if (SERVER_PRIVATE_KEY != null) { - return; - } - - try { - PrivateKeyEntry serverPrivateKeyEntry - = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); - SERVER_PRIVATE_KEY = serverPrivateKeyEntry.getPrivateKey().getEncoded(); - SERVER_CERTIFICATES = NativeCrypto.encodeCertificates( - serverPrivateKeyEntry.getCertificateChain()); - - PrivateKeyEntry clientPrivateKeyEntry - = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA"); - CLIENT_PRIVATE_KEY = clientPrivateKeyEntry.getPrivateKey().getEncoded(); - CLIENT_CERTIFICATES = NativeCrypto.encodeCertificates( - clientPrivateKeyEntry.getCertificateChain()); - - KeyStore ks = TestKeyStore.getClient().keyStore; - String caCertAlias = ks.aliases().nextElement(); - X509Certificate certificate = (X509Certificate) ks.getCertificate(caCertAlias); - X500Principal principal = certificate.getIssuerX500Principal(); - CA_PRINCIPALS = new byte[][] { principal.getEncoded() }; - initChannelIdKey(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static synchronized void initChannelIdKey() throws Exception { - if (CHANNEL_ID_PRIVATE_KEY != null) { - return; - } - - // NIST P-256 aka SECG secp256r1 aka X9.62 prime256v1 - OpenSSLECGroupContext openSslSpec = OpenSSLECGroupContext.getCurveByName("prime256v1"); - BigInteger s = new BigInteger( - "229cdbbf489aea584828a261a23f9ff8b0f66f7ccac98bf2096ab3aee41497c5", 16); - CHANNEL_ID_PRIVATE_KEY = new OpenSSLECPrivateKey( - new ECPrivateKeySpec(s, openSslSpec.getECParameterSpec())); - - // Channel ID is the concatenation of the X and Y coordinates of the public key. - CHANNEL_ID = new BigInteger( - "702b07871fd7955c320b26f15e244e47eed60272124c92b9ebecf0b42f90069b" + - "ab53592ebfeb4f167dbf3ce61513afb0e354c479b1c1b69874fa471293494f77", - 16).toByteArray(); - } - - public static void assertEqualSessions(long expected, long actual) { - assertEqualByteArrays(NativeCrypto.SSL_SESSION_session_id(expected), - NativeCrypto.SSL_SESSION_session_id(actual)); - } - public static void assertEqualByteArrays(byte[] expected, byte[] actual) { - assertEquals(Arrays.toString(expected), Arrays.toString(actual)); - } - - public static void assertEqualPrincipals(byte[][] expected, byte[][] actual) { - assertEqualByteArrays(expected, actual); - } - public static void assertEqualCertificateChains(byte[][] expected, byte[][] actual) { - assertEqualByteArrays(expected, actual); - } - public static void assertEqualByteArrays(byte[][] expected, byte[][] actual) { - assertEquals(Arrays.deepToString(expected), Arrays.deepToString(actual)); - } - - public void test_EVP_PKEY_cmp() throws Exception { - try { - NativeCrypto.EVP_PKEY_cmp(NULL, NULL); - fail("Should throw NullPointerException when arguments are NULL"); - } catch (NullPointerException expected) { - } - - KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); - kpg.initialize(512); - - KeyPair kp1 = kpg.generateKeyPair(); - RSAPrivateCrtKey privKey1 = (RSAPrivateCrtKey) kp1.getPrivate(); - - KeyPair kp2 = kpg.generateKeyPair(); - RSAPrivateCrtKey privKey2 = (RSAPrivateCrtKey) kp2.getPrivate(); - - long pkey1 = 0, pkey1_copy = 0, pkey2 = 0; - try { - pkey1 = NativeCrypto.EVP_PKEY_new_RSA(privKey1.getModulus().toByteArray(), - privKey1.getPublicExponent().toByteArray(), - privKey1.getPrivateExponent().toByteArray(), - privKey1.getPrimeP().toByteArray(), - privKey1.getPrimeQ().toByteArray(), - privKey1.getPrimeExponentP().toByteArray(), - privKey1.getPrimeExponentQ().toByteArray(), - privKey1.getCrtCoefficient().toByteArray()); - assertNotSame(NULL, pkey1); - - pkey1_copy = NativeCrypto.EVP_PKEY_new_RSA(privKey1.getModulus().toByteArray(), - privKey1.getPublicExponent().toByteArray(), - privKey1.getPrivateExponent().toByteArray(), - privKey1.getPrimeP().toByteArray(), - privKey1.getPrimeQ().toByteArray(), - privKey1.getPrimeExponentP().toByteArray(), - privKey1.getPrimeExponentQ().toByteArray(), - privKey1.getCrtCoefficient().toByteArray()); - assertNotSame(NULL, pkey1_copy); - - pkey2 = NativeCrypto.EVP_PKEY_new_RSA(privKey2.getModulus().toByteArray(), - privKey2.getPublicExponent().toByteArray(), - privKey2.getPrivateExponent().toByteArray(), - privKey2.getPrimeP().toByteArray(), - privKey2.getPrimeQ().toByteArray(), - privKey2.getPrimeExponentP().toByteArray(), - privKey2.getPrimeExponentQ().toByteArray(), - privKey2.getCrtCoefficient().toByteArray()); - assertNotSame(NULL, pkey2); - - try { - NativeCrypto.EVP_PKEY_cmp(pkey1, NULL); - fail("Should throw NullPointerException when arguments are NULL"); - } catch (NullPointerException expected) { - } - - try { - NativeCrypto.EVP_PKEY_cmp(NULL, pkey1); - fail("Should throw NullPointerException when arguments are NULL"); - } catch (NullPointerException expected) { - } - - assertEquals("Same keys should be the equal", 1, - NativeCrypto.EVP_PKEY_cmp(pkey1, pkey1)); - - assertEquals("Same keys should be the equal", 1, - NativeCrypto.EVP_PKEY_cmp(pkey1, pkey1_copy)); - - assertEquals("Different keys should not be equal", 0, - NativeCrypto.EVP_PKEY_cmp(pkey1, pkey2)); - } finally { - if (pkey1 != 0) { - NativeCrypto.EVP_PKEY_free(pkey1); - } - if (pkey1_copy != 0) { - NativeCrypto.EVP_PKEY_free(pkey1_copy); - } - if (pkey2 != 0) { - NativeCrypto.EVP_PKEY_free(pkey2); - } - } - } - - public void test_SSL_CTX_new() throws Exception { - long c = NativeCrypto.SSL_CTX_new(); - assertTrue(c != NULL); - long c2 = NativeCrypto.SSL_CTX_new(); - assertTrue(c != c2); - NativeCrypto.SSL_CTX_free(c); - NativeCrypto.SSL_CTX_free(c2); - } - - public void test_SSL_CTX_free() throws Exception { - try { - NativeCrypto.SSL_CTX_free(NULL); - fail(); - } catch (NullPointerException expected) { - } - - NativeCrypto.SSL_CTX_free(NativeCrypto.SSL_CTX_new()); - } - - public void test_SSL_CTX_set_session_id_context() throws Exception { - byte[] empty = new byte[0]; - try { - NativeCrypto.SSL_CTX_set_session_id_context(NULL, empty); - fail(); - } catch (NullPointerException expected) { - } - long c = NativeCrypto.SSL_CTX_new(); - try { - NativeCrypto.SSL_CTX_set_session_id_context(c, null); - fail(); - } catch (NullPointerException expected) { - } - NativeCrypto.SSL_CTX_set_session_id_context(c, empty); - NativeCrypto.SSL_CTX_set_session_id_context(c, new byte[32]); - try { - NativeCrypto.SSL_CTX_set_session_id_context(c, new byte[33]); - } catch (IllegalArgumentException expected) { - } - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_new() throws Exception { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - assertTrue(s != NULL); - assertTrue((NativeCrypto.SSL_get_options(s) & 0x01000000L) != 0); // SSL_OP_NO_SSLv2 - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_SSLv3) == 0); - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_TLSv1) == 0); - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_TLSv1_1) == 0); - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_TLSv1_2) == 0); - - long s2 = NativeCrypto.SSL_new(c); - assertTrue(s != s2); - NativeCrypto.SSL_free(s2); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_use_certificate() throws Exception { - try { - NativeCrypto.SSL_use_certificate(NULL, null); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - try { - NativeCrypto.SSL_use_certificate(s, null); - fail(); - } catch (NullPointerException expected) { - } - - NativeCrypto.SSL_use_certificate(s, getServerCertificates()); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_use_PrivateKey_for_tls_channel_id() throws Exception { - try { - NativeCrypto.SSL_set1_tls_channel_id(NULL, null); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - try { - NativeCrypto.SSL_set1_tls_channel_id(s, null); - fail(); - } catch (NullPointerException expected) { - } - - // Use the key via the wrapper that decides whether to use PKCS#8 or native OpenSSL. - NativeCrypto.SSL_set1_tls_channel_id(s, CHANNEL_ID_PRIVATE_KEY); - - // Use the key via its PKCS#8 representation. - assertEquals("PKCS#8", CHANNEL_ID_PRIVATE_KEY.getFormat()); - byte[] pkcs8EncodedKeyBytes = CHANNEL_ID_PRIVATE_KEY.getEncoded(); - assertNotNull(pkcs8EncodedKeyBytes); - NativeCrypto.SSL_use_PKCS8_PrivateKey_for_tls_channel_id(s, pkcs8EncodedKeyBytes); - - // Use the key natively. This works because the initChannelIdKey method ensures that the - // key is backed by OpenSSL. - NativeCrypto.SSL_use_OpenSSL_PrivateKey_for_tls_channel_id( - s, - ((OpenSSLECPrivateKey) CHANNEL_ID_PRIVATE_KEY).getOpenSSLKey().getPkeyContext()); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_use_PrivateKey() throws Exception { - try { - NativeCrypto.SSL_use_PrivateKey(NULL, null); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - try { - NativeCrypto.SSL_use_PrivateKey(s, null); - fail(); - } catch (NullPointerException expected) { - } - - NativeCrypto.SSL_use_PrivateKey(s, getServerPrivateKey()); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_check_private_key_null() throws Exception { - try { - NativeCrypto.SSL_check_private_key(NULL); - fail(); - } catch (NullPointerException expected) { - } - } - - public void test_SSL_check_private_key_no_key_no_cert() throws Exception { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - // neither private or certificate set - try { - NativeCrypto.SSL_check_private_key(s); - fail(); - } catch (SSLException expected) { - } - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_check_private_key_cert_then_key() throws Exception { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - // first certificate, then private - NativeCrypto.SSL_use_certificate(s, getServerCertificates()); - - try { - NativeCrypto.SSL_check_private_key(s); - fail(); - } catch (SSLException expected) { - } - - NativeCrypto.SSL_use_PrivateKey(s, getServerPrivateKey()); - NativeCrypto.SSL_check_private_key(s); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - public void test_SSL_check_private_key_key_then_cert() throws Exception { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - // first private, then certificate - NativeCrypto.SSL_use_PrivateKey(s, getServerPrivateKey()); - - try { - NativeCrypto.SSL_check_private_key(s); - fail(); - } catch (SSLException expected) { - } - - NativeCrypto.SSL_use_certificate(s, getServerCertificates()); - NativeCrypto.SSL_check_private_key(s); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_get_mode() throws Exception { - try { - NativeCrypto.SSL_get_mode(NULL); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - assertTrue(NativeCrypto.SSL_get_mode(s) != 0); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_set_mode_and_clear_mode() throws Exception { - try { - NativeCrypto.SSL_set_mode(NULL, 0); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - // check SSL_MODE_HANDSHAKE_CUTTHROUGH off by default - assertEquals(0, NativeCrypto.SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH); - // set SSL_MODE_HANDSHAKE_CUTTHROUGH on - NativeCrypto.SSL_set_mode(s, SSL_MODE_HANDSHAKE_CUTTHROUGH); - assertTrue((NativeCrypto.SSL_get_mode(s) - & SSL_MODE_HANDSHAKE_CUTTHROUGH) != 0); - // clear SSL_MODE_HANDSHAKE_CUTTHROUGH off - NativeCrypto.SSL_clear_mode(s, SSL_MODE_HANDSHAKE_CUTTHROUGH); - assertTrue((NativeCrypto.SSL_get_mode(s) - & SSL_MODE_HANDSHAKE_CUTTHROUGH) == 0); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_get_options() throws Exception { - try { - NativeCrypto.SSL_get_options(NULL); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - assertTrue(NativeCrypto.SSL_get_options(s) != 0); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_set_options() throws Exception { - try { - NativeCrypto.SSL_set_options(NULL, 0); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_SSLv3) == 0); - NativeCrypto.SSL_set_options(s, NativeCrypto.SSL_OP_NO_SSLv3); - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_SSLv3) != 0); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_clear_options() throws Exception { - try { - NativeCrypto.SSL_clear_options(NULL, 0); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_SSLv3) == 0); - NativeCrypto.SSL_set_options(s, NativeCrypto.SSL_OP_NO_SSLv3); - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_SSLv3) != 0); - NativeCrypto.SSL_clear_options(s, NativeCrypto.SSL_OP_NO_SSLv3); - assertTrue((NativeCrypto.SSL_get_options(s) & NativeCrypto.SSL_OP_NO_SSLv3) == 0); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_set_cipher_lists() throws Exception { - try { - NativeCrypto.SSL_set_cipher_lists(NULL, null); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - try { - NativeCrypto.SSL_set_cipher_lists(s, null); - fail(); - } catch (NullPointerException expected) { - } - - NativeCrypto.SSL_set_cipher_lists(s, new String[] {}); - - try { - NativeCrypto.SSL_set_cipher_lists(s, new String[] { null }); - fail(); - } catch (NullPointerException expected) { - } - - // see OpenSSL ciphers man page - String[] illegals = new String[] { - // empty - "", - // never standardized - "EXP1024-DES-CBC-SHA", "EXP1024-RC4-SHA", "DHE-DSS-RC4-SHA", - // IDEA - "IDEA-CBC-SHA", "IDEA-CBC-MD5" - }; - - for (String illegal : illegals) { - try { - NativeCrypto.SSL_set_cipher_lists(s, new String[] { illegal }); - fail(illegal); - } catch (IllegalArgumentException expected) { - } - } - - List<String> ciphers - = new ArrayList<String>(NativeCrypto.OPENSSL_TO_STANDARD_CIPHER_SUITES.keySet()); - NativeCrypto.SSL_set_cipher_lists(s, ciphers.toArray(new String[ciphers.size()])); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_set_verify() throws Exception { - try { - NativeCrypto.SSL_set_verify(NULL, 0); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - NativeCrypto.SSL_set_verify(s, NativeCrypto.SSL_VERIFY_NONE); - NativeCrypto.SSL_set_verify(s, NativeCrypto.SSL_VERIFY_PEER); - NativeCrypto.SSL_set_verify(s, NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - NativeCrypto.SSL_set_verify(s, (NativeCrypto.SSL_VERIFY_PEER - | NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT)); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - private static final boolean DEBUG = false; - - public static class Hooks { - private PrivateKey channelIdPrivateKey; - - public long getContext() throws SSLException { - return NativeCrypto.SSL_CTX_new(); - } - public long beforeHandshake(long context) throws SSLException { - long s = NativeCrypto.SSL_new(context); - // without this SSL_set_cipher_lists call the tests were - // negotiating DHE-RSA-AES256-SHA by default which had - // very slow ephemeral RSA key generation - NativeCrypto.SSL_set_cipher_lists(s, new String[] { "RC4-MD5" }); - - if (channelIdPrivateKey != null) { - NativeCrypto.SSL_set1_tls_channel_id(s, channelIdPrivateKey); - } - return s; - } - public void clientCertificateRequested(long s) {} - public void afterHandshake(long session, long ssl, long context, - Socket socket, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - if (session != NULL) { - NativeCrypto.SSL_SESSION_free(session); - } - if (ssl != NULL) { - try { - NativeCrypto.SSL_shutdown(ssl, fd, callback); - } catch (IOException e) { - } - NativeCrypto.SSL_free(ssl); - } - if (context != NULL) { - NativeCrypto.SSL_CTX_free(context); - } - if (socket != null) { - socket.close(); - } - } - } - - public static class TestSSLHandshakeCallbacks implements SSLHandshakeCallbacks { - private final Socket socket; - private final long sslNativePointer; - private final Hooks hooks; - - public TestSSLHandshakeCallbacks(Socket socket, - long sslNativePointer, - Hooks hooks) { - this.socket = socket; - this.sslNativePointer = sslNativePointer; - this.hooks = hooks; - } - - public byte[][] asn1DerEncodedCertificateChain; - public String authMethod; - public boolean verifyCertificateChainCalled; - - public void verifyCertificateChain(byte[][] asn1DerEncodedCertificateChain, - String authMethod) - throws CertificateException { - if (DEBUG) { - System.out.println("ssl=0x" + Long.toString(sslNativePointer, 16) - + " verifyCertificateChain" - + " asn1DerEncodedCertificateChain=" - + asn1DerEncodedCertificateChain - + " authMethod=" + authMethod); - } - this.asn1DerEncodedCertificateChain = asn1DerEncodedCertificateChain; - this.authMethod = authMethod; - this.verifyCertificateChainCalled = true; - } - - public byte[] keyTypes; - public byte[][] asn1DerEncodedX500Principals; - public boolean clientCertificateRequestedCalled; - public void clientCertificateRequested(byte[] keyTypes, - byte[][] asn1DerEncodedX500Principals) { - if (DEBUG) { - System.out.println("ssl=0x" + Long.toString(sslNativePointer, 16) - + " clientCertificateRequested" - + " keyTypes=" + keyTypes - + " asn1DerEncodedX500Principals=" - + asn1DerEncodedX500Principals); - } - this.keyTypes = keyTypes; - this.asn1DerEncodedX500Principals = asn1DerEncodedX500Principals; - this.clientCertificateRequestedCalled = true; - if (hooks != null ) { - hooks.clientCertificateRequested(sslNativePointer); - } - } - - public boolean handshakeCompletedCalled; - public void handshakeCompleted() { - if (DEBUG) { - System.out.println("ssl=0x" + Long.toString(sslNativePointer, 16) - + " handshakeCompleted"); - } - this.handshakeCompletedCalled = true; - } - - public Socket getSocket() { - return socket; - } - } - - public static class ServerHooks extends Hooks { - private final byte[] privateKey; - private final byte[][] certificates; - private boolean channelIdEnabled; - private byte[] channelIdAfterHandshake; - private Throwable channelIdAfterHandshakeException; - - public ServerHooks(byte[] privateKey, byte[][] certificates) { - this.privateKey = privateKey; - this.certificates = certificates; - } - - @Override - public long beforeHandshake(long c) throws SSLException { - long s = super.beforeHandshake(c); - if (privateKey != null) { - NativeCrypto.SSL_use_PrivateKey(s, privateKey); - } - if (certificates != null) { - NativeCrypto.SSL_use_certificate(s, certificates); - } - if (channelIdEnabled) { - NativeCrypto.SSL_enable_tls_channel_id(s); - } - return s; - } - - @Override - public void afterHandshake(long session, long ssl, long context, - Socket socket, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - if (channelIdEnabled) { - try { - channelIdAfterHandshake = NativeCrypto.SSL_get_tls_channel_id(ssl); - } catch (Exception e) { - channelIdAfterHandshakeException = e; - } - } - super.afterHandshake(session, ssl, context, socket, fd, callback); - } - - public void clientCertificateRequested(long s) { - fail("Server asked for client certificates"); - } - } - - public static Future<TestSSLHandshakeCallbacks> handshake(final ServerSocket listener, - final int timeout, final boolean client, final Hooks hooks, final byte[] npnProtocols) { - ExecutorService executor = Executors.newSingleThreadExecutor(); - Future<TestSSLHandshakeCallbacks> future = executor.submit( - new Callable<TestSSLHandshakeCallbacks>() { - @Override public TestSSLHandshakeCallbacks call() throws Exception { - Socket socket = (client - ? new Socket(listener.getInetAddress(), - listener.getLocalPort()) - : listener.accept()); - if (timeout == -1) { - return new TestSSLHandshakeCallbacks(socket, 0, null); - } - FileDescriptor fd = socket.getFileDescriptor$(); - long c = hooks.getContext(); - long s = hooks.beforeHandshake(c); - TestSSLHandshakeCallbacks callback - = new TestSSLHandshakeCallbacks(socket, s, hooks); - if (DEBUG) { - System.out.println("ssl=0x" + Long.toString(s, 16) - + " handshake" - + " context=0x" + Long.toString(c, 16) - + " socket=" + socket - + " fd=" + fd - + " timeout=" + timeout - + " client=" + client); - } - long session = NULL; - try { - session = NativeCrypto.SSL_do_handshake(s, fd, callback, timeout, client, - npnProtocols); - if (DEBUG) { - System.out.println("ssl=0x" + Long.toString(s, 16) - + " handshake" - + " session=0x" + Long.toString(session, 16)); - } - } finally { - // Ensure afterHandshake is called to free resources - hooks.afterHandshake(session, s, c, socket, fd, callback); - } - return callback; - } - }); - executor.shutdown(); - return future; - } - - public void test_SSL_do_handshake_NULL_SSL() throws Exception { - try { - NativeCrypto.SSL_do_handshake(NULL, null, null, 0, false, null); - fail(); - } catch (NullPointerException expected) { - } - } - - public void test_SSL_do_handshake_null_args() throws Exception { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - try { - NativeCrypto.SSL_do_handshake(s, null, null, 0, true, null); - fail(); - } catch (NullPointerException expected) { - } - - try { - NativeCrypto.SSL_do_handshake(s, INVALID_FD, null, 0, true, null); - fail(); - } catch (NullPointerException expected) { - } - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - public void test_SSL_do_handshake_normal() throws Exception { - // normal client and server case - final ServerSocket listener = new ServerSocket(0); - Hooks cHooks = new Hooks(); - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - TestSSLHandshakeCallbacks clientCallback = client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - TestSSLHandshakeCallbacks serverCallback = server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - assertTrue(clientCallback.verifyCertificateChainCalled); - assertEqualCertificateChains(getServerCertificates(), - clientCallback.asn1DerEncodedCertificateChain); - assertEquals("RSA", clientCallback.authMethod); - assertFalse(serverCallback.verifyCertificateChainCalled); - assertFalse(clientCallback.clientCertificateRequestedCalled); - assertFalse(serverCallback.clientCertificateRequestedCalled); - assertTrue(clientCallback.handshakeCompletedCalled); - assertTrue(serverCallback.handshakeCompletedCalled); - } - - public void test_SSL_do_handshake_optional_client_certificate() throws Exception { - // optional client certificate case - final ServerSocket listener = new ServerSocket(0); - - Hooks cHooks = new Hooks() { - @Override - public void clientCertificateRequested(long s) { - super.clientCertificateRequested(s); - NativeCrypto.SSL_use_PrivateKey(s, getClientPrivateKey()); - NativeCrypto.SSL_use_certificate(s, getClientCertificates()); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public long beforeHandshake(long c) throws SSLException { - long s = super.beforeHandshake(c); - NativeCrypto.SSL_set_client_CA_list(s, getCaPrincipals()); - NativeCrypto.SSL_set_verify(s, NativeCrypto.SSL_VERIFY_PEER); - return s; - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - TestSSLHandshakeCallbacks clientCallback = client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - TestSSLHandshakeCallbacks serverCallback = server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - assertTrue(clientCallback.verifyCertificateChainCalled); - assertEqualCertificateChains(getServerCertificates(), - clientCallback.asn1DerEncodedCertificateChain); - assertEquals("RSA", clientCallback.authMethod); - assertTrue(serverCallback.verifyCertificateChainCalled); - assertEqualCertificateChains(getClientCertificates(), - serverCallback.asn1DerEncodedCertificateChain); - assertEquals("RSA", serverCallback.authMethod); - - assertTrue(clientCallback.clientCertificateRequestedCalled); - assertNotNull(clientCallback.keyTypes); - // this depends on the SSL_set_cipher_lists call in beforeHandshake - // the three returned are the non-ephemeral cases. - assertEquals(3, clientCallback.keyTypes.length); - assertEquals("RSA", CipherSuite.getClientKeyType(clientCallback.keyTypes[0])); - assertEquals("DSA", CipherSuite.getClientKeyType(clientCallback.keyTypes[1])); - assertEquals("EC", CipherSuite.getClientKeyType(clientCallback.keyTypes[2])); - assertEqualPrincipals(getCaPrincipals(), - clientCallback.asn1DerEncodedX500Principals); - assertFalse(serverCallback.clientCertificateRequestedCalled); - - assertTrue(clientCallback.handshakeCompletedCalled); - assertTrue(serverCallback.handshakeCompletedCalled); - } - - public void test_SSL_do_handshake_missing_required_certificate() throws Exception { - // required client certificate negative case - final ServerSocket listener = new ServerSocket(0); - try { - Hooks cHooks = new Hooks(); - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public long beforeHandshake(long c) throws SSLException { - long s = super.beforeHandshake(c); - NativeCrypto.SSL_set_client_CA_list(s, getCaPrincipals()); - NativeCrypto.SSL_set_verify(s, - NativeCrypto.SSL_VERIFY_PEER - | NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - return s; - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - fail(); - } catch (ExecutionException expected) { - assertEquals(SSLProtocolException.class, expected.getCause().getClass()); - } - } - - /** - * Usually if a RuntimeException is thrown by the - * clientCertificateRequestedCalled callback, the caller sees it - * during the call to NativeCrypto_SSL_do_handshake. However, IIS - * does not request client certs until after the initial - * handshake. It does an SSL renegotiation, which means we need to - * be able to deliver the callback's exception in cases like - * SSL_read, SSL_write, and SSL_shutdown. - */ - public void test_SSL_do_handshake_clientCertificateRequested_throws_after_renegotiate() - throws Exception { - final ServerSocket listener = new ServerSocket(0); - - Hooks cHooks = new Hooks() { - @Override - public long beforeHandshake(long context) throws SSLException { - long s = super.beforeHandshake(context); - NativeCrypto.SSL_clear_mode(s, SSL_MODE_HANDSHAKE_CUTTHROUGH); - return s; - } - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - NativeCrypto.SSL_read(s, fd, callback, new byte[1], 0, 1, 0); - fail(); - super.afterHandshake(session, s, c, sock, fd, callback); - } - @Override - public void clientCertificateRequested(long s) { - super.clientCertificateRequested(s); - throw new RuntimeException("expected"); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - try { - NativeCrypto.SSL_set_verify(s, NativeCrypto.SSL_VERIFY_PEER); - NativeCrypto.SSL_set_options( - s, NativeCrypto.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); - NativeCrypto.SSL_renegotiate(s); - NativeCrypto.SSL_write(s, fd, callback, new byte[] { 42 }, 0, 1, - (int) ((TIMEOUT_SECONDS * 1000) / 2)); - } catch (IOException expected) { - } finally { - super.afterHandshake(session, s, c, sock, fd, callback); - } - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - try { - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } catch (ExecutionException e) { - if (!"expected".equals(e.getCause().getMessage())) { - throw e; - } - } - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_do_handshake_client_timeout() throws Exception { - // client timeout - final ServerSocket listener = new ServerSocket(0); - Socket serverSocket = null; - try { - Hooks cHooks = new Hooks(); - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 1, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, -1, false, sHooks, null); - serverSocket = server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS).getSocket(); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - fail(); - } catch (ExecutionException expected) { - if (SocketTimeoutException.class != expected.getCause().getClass()) { - expected.printStackTrace(); - } - assertEquals(SocketTimeoutException.class, expected.getCause().getClass()); - } finally { - // Manually close peer socket when testing timeout - IoUtils.closeQuietly(serverSocket); - } - } - - public void test_SSL_do_handshake_server_timeout() throws Exception { - // server timeout - final ServerSocket listener = new ServerSocket(0); - Socket clientSocket = null; - try { - Hooks cHooks = new Hooks(); - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, -1, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 1, false, sHooks, null); - clientSocket = client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS).getSocket(); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - fail(); - } catch (ExecutionException expected) { - assertEquals(SocketTimeoutException.class, expected.getCause().getClass()); - } finally { - // Manually close peer socket when testing timeout - IoUtils.closeQuietly(clientSocket); - } - } - - public void test_SSL_do_handshake_with_channel_id_normal() throws Exception { - initChannelIdKey(); - - // Normal handshake with TLS Channel ID. - final ServerSocket listener = new ServerSocket(0); - Hooks cHooks = new Hooks(); - cHooks.channelIdPrivateKey = CHANNEL_ID_PRIVATE_KEY; - ServerHooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - sHooks.channelIdEnabled = true; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - TestSSLHandshakeCallbacks clientCallback = client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - TestSSLHandshakeCallbacks serverCallback = server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - assertTrue(clientCallback.verifyCertificateChainCalled); - assertEqualCertificateChains(getServerCertificates(), - clientCallback.asn1DerEncodedCertificateChain); - assertEquals("RSA", clientCallback.authMethod); - assertFalse(serverCallback.verifyCertificateChainCalled); - assertFalse(clientCallback.clientCertificateRequestedCalled); - assertFalse(serverCallback.clientCertificateRequestedCalled); - assertTrue(clientCallback.handshakeCompletedCalled); - assertTrue(serverCallback.handshakeCompletedCalled); - assertNull(sHooks.channelIdAfterHandshakeException); - assertEqualByteArrays(CHANNEL_ID, sHooks.channelIdAfterHandshake); - } - - public void test_SSL_do_handshake_with_channel_id_not_supported_by_server() throws Exception { - initChannelIdKey(); - - // Client tries to use TLS Channel ID but the server does not enable/offer the extension. - final ServerSocket listener = new ServerSocket(0); - Hooks cHooks = new Hooks(); - cHooks.channelIdPrivateKey = CHANNEL_ID_PRIVATE_KEY; - ServerHooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - sHooks.channelIdEnabled = false; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - TestSSLHandshakeCallbacks clientCallback = client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - TestSSLHandshakeCallbacks serverCallback = server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - assertTrue(clientCallback.verifyCertificateChainCalled); - assertEqualCertificateChains(getServerCertificates(), - clientCallback.asn1DerEncodedCertificateChain); - assertEquals("RSA", clientCallback.authMethod); - assertFalse(serverCallback.verifyCertificateChainCalled); - assertFalse(clientCallback.clientCertificateRequestedCalled); - assertFalse(serverCallback.clientCertificateRequestedCalled); - assertTrue(clientCallback.handshakeCompletedCalled); - assertTrue(serverCallback.handshakeCompletedCalled); - assertNull(sHooks.channelIdAfterHandshakeException); - assertNull(sHooks.channelIdAfterHandshake); - } - - public void test_SSL_do_handshake_with_channel_id_not_enabled_by_client() throws Exception { - initChannelIdKey(); - - // Client does not use TLS Channel ID when the server has the extension enabled/offered. - final ServerSocket listener = new ServerSocket(0); - Hooks cHooks = new Hooks(); - cHooks.channelIdPrivateKey = null; - ServerHooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - sHooks.channelIdEnabled = true; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - TestSSLHandshakeCallbacks clientCallback = client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - TestSSLHandshakeCallbacks serverCallback = server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - assertTrue(clientCallback.verifyCertificateChainCalled); - assertEqualCertificateChains(getServerCertificates(), - clientCallback.asn1DerEncodedCertificateChain); - assertEquals("RSA", clientCallback.authMethod); - assertFalse(serverCallback.verifyCertificateChainCalled); - assertFalse(clientCallback.clientCertificateRequestedCalled); - assertFalse(serverCallback.clientCertificateRequestedCalled); - assertTrue(clientCallback.handshakeCompletedCalled); - assertTrue(serverCallback.handshakeCompletedCalled); - assertNull(sHooks.channelIdAfterHandshakeException); - assertNull(sHooks.channelIdAfterHandshake); - } - - public void test_SSL_set_session() throws Exception { - try { - NativeCrypto.SSL_set_session(NULL, NULL); - fail(); - } catch (NullPointerException expected) { - } - - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - NativeCrypto.SSL_set_session(s, NULL); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - { - final long clientContext = NativeCrypto.SSL_CTX_new(); - final long serverContext = NativeCrypto.SSL_CTX_new(); - final ServerSocket listener = new ServerSocket(0); - final long[] clientSession = new long[] { NULL }; - final long[] serverSession = new long[] { NULL }; - { - Hooks cHooks = new Hooks() { - @Override - public long getContext() throws SSLException { - return clientContext; - } - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - super.afterHandshake(NULL, s, NULL, sock, fd, callback); - clientSession[0] = session; - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public long getContext() throws SSLException { - return serverContext; - } - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - super.afterHandshake(NULL, s, NULL, sock, fd, callback); - serverSession[0] = session; - } - }; - Future<TestSSLHandshakeCallbacks> client - = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server - = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - assertEqualSessions(clientSession[0], serverSession[0]); - { - Hooks cHooks = new Hooks() { - @Override - public long getContext() throws SSLException { - return clientContext; - } - @Override - public long beforeHandshake(long c) throws SSLException { - long s = NativeCrypto.SSL_new(clientContext); - NativeCrypto.SSL_set_session(s, clientSession[0]); - return s; - } - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - assertEqualSessions(clientSession[0], session); - super.afterHandshake(NULL, s, NULL, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public long getContext() throws SSLException { - return serverContext; - } - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - assertEqualSessions(serverSession[0], session); - super.afterHandshake(NULL, s, NULL, sock, fd, callback); - } - }; - Future<TestSSLHandshakeCallbacks> client - = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server - = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - NativeCrypto.SSL_SESSION_free(clientSession[0]); - NativeCrypto.SSL_SESSION_free(serverSession[0]); - NativeCrypto.SSL_CTX_free(serverContext); - NativeCrypto.SSL_CTX_free(clientContext); - } - } - - public void test_SSL_set_session_creation_enabled() throws Exception { - try { - NativeCrypto.SSL_set_session_creation_enabled(NULL, false); - fail(); - } catch (NullPointerException expected) { - } - - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - NativeCrypto.SSL_set_session_creation_enabled(s, false); - NativeCrypto.SSL_set_session_creation_enabled(s, true); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - final ServerSocket listener = new ServerSocket(0); - - // negative test case for SSL_set_session_creation_enabled(false) on client - try { - Hooks cHooks = new Hooks() { - @Override - public long beforeHandshake(long c) throws SSLException { - long s = super.beforeHandshake(c); - NativeCrypto.SSL_set_session_creation_enabled(s, false); - return s; - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - fail(); - } catch (ExecutionException expected) { - assertEquals(SSLProtocolException.class, expected.getCause().getClass()); - } - - // negative test case for SSL_set_session_creation_enabled(false) on server - try { - Hooks cHooks = new Hooks(); - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public long beforeHandshake(long c) throws SSLException { - long s = super.beforeHandshake(c); - NativeCrypto.SSL_set_session_creation_enabled(s, false); - return s; - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - fail(); - } catch (ExecutionException expected) { - assertEquals(SSLProtocolException.class, expected.getCause().getClass()); - } - } - - public void test_SSL_set_tlsext_host_name() throws Exception { - // NULL SSL - try { - NativeCrypto.SSL_set_tlsext_host_name(NULL, null); - fail(); - } catch (NullPointerException expected) { - } - - final String hostname = "www.android.com"; - - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - - // null hostname - try { - NativeCrypto.SSL_set_tlsext_host_name(s, null); - fail(); - } catch (NullPointerException expected) { - } - - // too long hostname - try { - char[] longHostname = new char[256]; - Arrays.fill(longHostname, 'w'); - NativeCrypto.SSL_set_tlsext_host_name(s, new String(longHostname)); - fail(); - } catch (SSLException expected) { - } - - assertNull(NativeCrypto.SSL_get_servername(s)); - NativeCrypto.SSL_set_tlsext_host_name(s, new String(hostname)); - assertEquals(hostname, NativeCrypto.SSL_get_servername(s)); - - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - final ServerSocket listener = new ServerSocket(0); - - // normal - Hooks cHooks = new Hooks() { - @Override - public long beforeHandshake(long c) throws SSLException { - long s = super.beforeHandshake(c); - NativeCrypto.SSL_set_tlsext_host_name(s, hostname); - return s; - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - assertEquals(hostname, NativeCrypto.SSL_get_servername(s)); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_NpnNegotiateSuccess() throws Exception { - final byte[] clientNpnProtocols = new byte[] { - 8, 'h', 't', 't', 'p', '/', '1', '.', '1', - 3, 'f', 'o', 'o', - 6, 's', 'p', 'd', 'y', '/', '2', - }; - final byte[] serverNpnProtocols = new byte[] { - 6, 's', 'p', 'd', 'y', '/', '2', - 3, 'f', 'o', 'o', - 3, 'b', 'a', 'r', - }; - - Hooks cHooks = new Hooks() { - @Override public long beforeHandshake(long context) throws SSLException { - NativeCrypto.SSL_CTX_enable_npn(context); - return super.beforeHandshake(context); - } - @Override public void afterHandshake(long session, long ssl, long context, Socket socket, - FileDescriptor fd, SSLHandshakeCallbacks callback) throws Exception { - byte[] negotiated = NativeCrypto.SSL_get_npn_negotiated_protocol(ssl); - assertEquals("spdy/2", new String(negotiated)); - assertTrue("NPN should enable cutthrough on the client", - 0 != (NativeCrypto.SSL_get_mode(ssl) & SSL_MODE_HANDSHAKE_CUTTHROUGH)); - super.afterHandshake(session, ssl, context, socket, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override public long beforeHandshake(long context) throws SSLException { - NativeCrypto.SSL_CTX_enable_npn(context); - return super.beforeHandshake(context); - } - @Override public void afterHandshake(long session, long ssl, long c, Socket sock, - FileDescriptor fd, SSLHandshakeCallbacks callback) throws Exception { - byte[] negotiated = NativeCrypto.SSL_get_npn_negotiated_protocol(ssl); - assertEquals("spdy/2", new String(negotiated)); - assertEquals("NPN should not enable cutthrough on the server", - 0, NativeCrypto.SSL_get_mode(ssl) & SSL_MODE_HANDSHAKE_CUTTHROUGH); - super.afterHandshake(session, ssl, c, sock, fd, callback); - } - }; - - ServerSocket listener = new ServerSocket(0); - Future<TestSSLHandshakeCallbacks> client - = handshake(listener, 0, true, cHooks, clientNpnProtocols); - Future<TestSSLHandshakeCallbacks> server - = handshake(listener, 0, false, sHooks, serverNpnProtocols); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_get_servername_null() throws Exception { - // NULL SSL - try { - NativeCrypto.SSL_get_servername(NULL); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - assertNull(NativeCrypto.SSL_get_servername(s)); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - - // additional positive testing by test_SSL_set_tlsext_host_name - } - - public void test_SSL_renegotiate() throws Exception { - try { - NativeCrypto.SSL_renegotiate(NULL); - fail(); - } catch (NullPointerException expected) { - } - - final ServerSocket listener = new ServerSocket(0); - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - byte[] buffer = new byte[1]; - NativeCrypto.SSL_read(s, fd, callback, buffer, 0, 1, 0); - assertEquals(42, buffer[0]); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - NativeCrypto.SSL_renegotiate(s); - NativeCrypto.SSL_write(s, fd, callback, new byte[] { 42 }, 0, 1, 0); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_get_certificate() throws Exception { - try { - NativeCrypto.SSL_get_certificate(NULL); - fail(); - } catch (NullPointerException expected) { - } - - final ServerSocket listener = new ServerSocket(0); - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - assertNull(NativeCrypto.SSL_get_certificate(s)); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - assertEqualCertificateChains( - getServerCertificates(), - NativeCrypto.SSL_get_certificate(s)); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_get_peer_cert_chain() throws Exception { - try { - NativeCrypto.SSL_get_peer_cert_chain(NULL); - fail(); - } catch (NullPointerException expected) { - } - - final ServerSocket listener = new ServerSocket(0); - - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - byte[][] cc = NativeCrypto.SSL_get_peer_cert_chain(s); - assertEqualCertificateChains(getServerCertificates(), cc); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - final byte[] BYTES = new byte[] { 2, -3, 5, 127, 0, -128 }; - - public void test_SSL_read() throws Exception { - - // NULL ssl - try { - NativeCrypto.SSL_read(NULL, null, null, null, 0, 0, 0); - fail(); - } catch (NullPointerException expected) { - } - - // null FileDescriptor - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_read(s, null, DUMMY_CB, null, 0, 0, 0); - fail(); - } catch (NullPointerException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - // null SSLHandshakeCallbacks - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_read(s, INVALID_FD, null, null, 0, 0, 0); - fail(); - } catch (NullPointerException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - // null byte array - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_read(s, INVALID_FD, DUMMY_CB, null, 0, 0, 0); - fail(); - } catch (NullPointerException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - // handshaking not yet performed - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_read(s, INVALID_FD, DUMMY_CB, new byte[1], 0, 1, 0); - fail(); - } catch (SSLException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - final ServerSocket listener = new ServerSocket(0); - - // normal case - { - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - byte[] in = new byte[256]; - assertEquals(BYTES.length, - NativeCrypto.SSL_read(s, - fd, - callback, - in, - 0, - BYTES.length, - 0)); - for (int i = 0; i < BYTES.length; i++) { - assertEquals(BYTES[i], in[i]); - } - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - NativeCrypto.SSL_write(s, fd, callback, BYTES, 0, BYTES.length, 0); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - // timeout case - try { - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - NativeCrypto.SSL_read(s, fd, callback, new byte[1], 0, 1, 1); - fail(); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - NativeCrypto.SSL_read(s, fd, callback, new byte[1], 0, 1, 0); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - fail(); - } catch (ExecutionException expected) { - assertEquals(SocketTimeoutException.class, expected.getCause().getClass()); - } - } - - public void test_SSL_write() throws Exception { - try { - NativeCrypto.SSL_write(NULL, null, null, null, 0, 0, 0); - fail(); - } catch (NullPointerException expected) { - } - - // null FileDescriptor - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_write(s, null, DUMMY_CB, null, 0, 1, 0); - fail(); - } catch (NullPointerException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - // null SSLHandshakeCallbacks - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_write(s, INVALID_FD, null, null, 0, 1, 0); - fail(); - } catch (NullPointerException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - // null byte array - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_write(s, INVALID_FD, DUMMY_CB, null, 0, 1, 0); - fail(); - } catch (NullPointerException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - // handshaking not yet performed - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_write(s, INVALID_FD, DUMMY_CB, new byte[1], 0, 1, 0); - fail(); - } catch (SSLException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - // positively tested by test_SSL_read - } - - public void test_SSL_interrupt() throws Exception { - // SSL_interrupt is a rare case that tolerates a null SSL argument - NativeCrypto.SSL_interrupt(NULL); - - // also works without handshaking - { - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - NativeCrypto.SSL_interrupt(s); - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - } - - final ServerSocket listener = new ServerSocket(0); - - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - NativeCrypto.SSL_read(s, fd, callback, new byte[1], 0, 1, 0); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()) { - @Override - public void afterHandshake(long session, final long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - new Thread() { - public void run() { - try { - Thread.sleep(1*1000); - NativeCrypto.SSL_interrupt(s); - } catch (Exception e) { - } - } - }.start(); - assertEquals(-1, NativeCrypto.SSL_read(s, fd, callback, new byte[1], 0, 1, 0)); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_shutdown() throws Exception { - - // null FileDescriptor - try { - NativeCrypto.SSL_shutdown(NULL, null, DUMMY_CB); - } catch (NullPointerException expected) { - } - - // null SSLHandshakeCallbacks - try { - NativeCrypto.SSL_shutdown(NULL, INVALID_FD, null); - } catch (NullPointerException expected) { - } - - // SSL_shutdown is a rare case that tolerates a null SSL argument - NativeCrypto.SSL_shutdown(NULL, INVALID_FD, DUMMY_CB); - - // handshaking not yet performed - long c = NativeCrypto.SSL_CTX_new(); - long s = NativeCrypto.SSL_new(c); - try { - NativeCrypto.SSL_shutdown(s, INVALID_FD, DUMMY_CB); - } catch (SSLProtocolException expected) { - } - NativeCrypto.SSL_free(s); - NativeCrypto.SSL_CTX_free(c); - - // positively tested elsewhere because handshake uses use - // SSL_shutdown to ensure SSL_SESSIONs are reused. - } - - public void test_SSL_free() throws Exception { - try { - NativeCrypto.SSL_free(NULL); - fail(); - } catch (NullPointerException expected) { - } - - long c = NativeCrypto.SSL_CTX_new(); - NativeCrypto.SSL_free(NativeCrypto.SSL_new(c)); - NativeCrypto.SSL_CTX_free(c); - - // additional positive testing elsewhere because handshake - // uses use SSL_free to cleanup in afterHandshake. - } - - public void test_SSL_SESSION_session_id() throws Exception { - try { - NativeCrypto.SSL_SESSION_session_id(NULL); - fail(); - } catch (NullPointerException expected) { - } - - final ServerSocket listener = new ServerSocket(0); - - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - byte[] id = NativeCrypto.SSL_SESSION_session_id(session); - assertNotNull(id); - assertEquals(32, id.length); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_SESSION_get_time() throws Exception { - try { - NativeCrypto.SSL_SESSION_get_time(NULL); - fail(); - } catch (NullPointerException expected) { - } - - final ServerSocket listener = new ServerSocket(0); - - { - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - long time = NativeCrypto.SSL_SESSION_get_time(session); - assertTrue(time != 0); - assertTrue(time < System.currentTimeMillis()); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - } - - public void test_SSL_SESSION_get_version() throws Exception { - try { - NativeCrypto.SSL_SESSION_get_version(NULL); - fail(); - } catch (NullPointerException expected) { - } - - final ServerSocket listener = new ServerSocket(0); - - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - String v = NativeCrypto.SSL_SESSION_get_version(session); - assertTrue(StandardNames.SSL_SOCKET_PROTOCOLS.contains(v)); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_SESSION_cipher() throws Exception { - try { - NativeCrypto.SSL_SESSION_cipher(NULL); - fail(); - } catch (NullPointerException expected) { - } - - final ServerSocket listener = new ServerSocket(0); - - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - String a = NativeCrypto.SSL_SESSION_cipher(session); - assertTrue(NativeCrypto.OPENSSL_TO_STANDARD_CIPHER_SUITES.containsKey(a)); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_SSL_SESSION_free() throws Exception { - try { - NativeCrypto.SSL_SESSION_free(NULL); - fail(); - } catch (NullPointerException expected) { - } - - // additional positive testing elsewhere because handshake - // uses use SSL_SESSION_free to cleanup in afterHandshake. - } - - public void test_i2d_SSL_SESSION() throws Exception { - try { - NativeCrypto.i2d_SSL_SESSION(NULL); - fail(); - } catch (NullPointerException expected) { - } - - final ServerSocket listener = new ServerSocket(0); - - Hooks cHooks = new Hooks() { - @Override - public void afterHandshake(long session, long s, long c, - Socket sock, FileDescriptor fd, - SSLHandshakeCallbacks callback) - throws Exception { - byte[] b = NativeCrypto.i2d_SSL_SESSION(session); - assertNotNull(b); - long session2 = NativeCrypto.d2i_SSL_SESSION(b); - assertTrue(session2 != NULL); - - // Make sure d2i_SSL_SESSION retores SSL_SESSION_cipher value http://b/7091840 - assertTrue(NativeCrypto.SSL_SESSION_cipher(session2) != null); - assertEquals(NativeCrypto.SSL_SESSION_cipher(session), - NativeCrypto.SSL_SESSION_cipher(session2)); - - NativeCrypto.SSL_SESSION_free(session2); - super.afterHandshake(session, s, c, sock, fd, callback); - } - }; - Hooks sHooks = new ServerHooks(getServerPrivateKey(), getServerCertificates()); - Future<TestSSLHandshakeCallbacks> client = handshake(listener, 0, true, cHooks, null); - Future<TestSSLHandshakeCallbacks> server = handshake(listener, 0, false, sHooks, null); - client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - - public void test_d2i_SSL_SESSION() throws Exception { - try { - NativeCrypto.d2i_SSL_SESSION(null); - fail(); - } catch (NullPointerException expected) { - } - - assertEquals(NULL, NativeCrypto.d2i_SSL_SESSION(new byte[0])); - assertEquals(NULL, NativeCrypto.d2i_SSL_SESSION(new byte[1])); - - // positive testing by test_i2d_SSL_SESSION - } - - public void test_X509_NAME_hashes() { - // ensure these hash functions are stable over time since the - // /system/etc/security/cacerts CA filenames have to be - // consistent with the output. - X500Principal name = new X500Principal("CN=localhost"); - assertEquals(-1372642656, NativeCrypto.X509_NAME_hash(name)); // SHA1 - assertEquals(-1626170662, NativeCrypto.X509_NAME_hash_old(name)); // MD5 - } - - public void test_ENGINE_by_id_Failure() throws Exception { - NativeCrypto.ENGINE_load_dynamic(); - - long engine = NativeCrypto.ENGINE_by_id("non-existent"); - if (engine != 0) { - NativeCrypto.ENGINE_finish(engine); - fail("should not acquire reference to non-existent engine"); - } - } - - /** - * Loads the test OpenSSL ENGINE. If it's already loaded, returns - * immediately. - */ - public static void loadTestEngine() throws Exception { - long testEngine = NativeCrypto.ENGINE_by_id(TEST_ENGINE_ID); - if (testEngine != 0) { - NativeCrypto.ENGINE_finish(testEngine); - return; - } - - NativeCrypto.ENGINE_load_dynamic(); - long dynEngine = NativeCrypto.ENGINE_by_id("dynamic"); - try { - ClassLoader loader = NativeCryptoTest.class.getClassLoader(); - - final String libraryPaths; - if (loader instanceof BaseDexClassLoader) { - libraryPaths = ((BaseDexClassLoader) loader).getLdLibraryPath(); - } else { - libraryPaths = System.getProperty("java.library.path"); - } - assertNotNull(libraryPaths); - - String[] libraryPathArray = libraryPaths.split(":"); - for (String path : libraryPathArray) { - assertEquals(1, NativeCrypto.ENGINE_ctrl_cmd_string(dynEngine, "DIR_ADD", path, 0)); - } - - // We must add this to the list of ENGINEs - assertEquals(1, NativeCrypto.ENGINE_ctrl_cmd_string(dynEngine, "LIST_ADD", "2", 0)); - - // Do a direct load of the ENGINE. - assertEquals(1, - NativeCrypto.ENGINE_ctrl_cmd_string(dynEngine, "ID", TEST_ENGINE_ID, 0)); - assertEquals(1, NativeCrypto.ENGINE_ctrl_cmd_string(dynEngine, "LOAD", null, 0)); - } finally { - NativeCrypto.ENGINE_finish(dynEngine); - } - - testEngine = NativeCrypto.ENGINE_by_id(TEST_ENGINE_ID); - if (testEngine == 0) { - fail("could not load test engine"); - } - NativeCrypto.ENGINE_finish(testEngine); - } - - public void test_ENGINE_by_id_TestEngine() throws Exception { - loadTestEngine(); - - long engine = NativeCrypto.ENGINE_by_id(TEST_ENGINE_ID); - assertTrue(engine != 0); - NativeCrypto.ENGINE_add(engine); - - long pkey = NULL; - try { - final String rsaPem = - "-----BEGIN RSA PRIVATE KEY-----\n" - + "MIICXAIBAAKBgQCvvsYz1VKhU9PT0NHlotX22tcCjeaiVFNg0JrkjoK2XuMb+7a6\n" - + "R5bzgIr24+OnBB0LqgaKnHwxZTA73lo/Wy/Ms5Kvg4yX9UMkNE+PvH5vzcQBbFdI\n" - + "lwETFPvFokHO5OyOcEY+iVWG2fDloteH2JsrKYLh9Sx3Br5pHFCCm5qT5wIDAQAB\n" - + "AoGAWDxoNs371pPH3qkROUIwOuhU2ytziDzeP9V8bxQ9/GJXlE0kyRH4b/kxzBNO\n" - + "0SP3kUukTSOUFxi+xtA0b2rQ7Be2txtjzW1TGOHSCWbFrJAdTqeBcmQJSaZay8n1\n" - + "LOpk4/zvBl7VScBth1IgXP44v6lOzthsrDhMlUYs07ymwYECQQDonaLOhkmVThPa\n" - + "CIThdE5CN/wF5UDzGOz+ZBz3dt8D8QQMu0aZaPzibq9BC462j/fWeWS5OFzbq2+T\n" - + "+cor3nwPAkEAwWmTQdra6GMPEc40zNsM5ehF2FjOpX8aU8267eG56y0Y+GbHx2BN\n" - + "zAHfPxGBBH8cZ0cLhk4RSo/po7Vv+cRyqQJAAQz1N0mT+4Cmxk1TjFEiKVpnYP9w\n" - + "E6kBKQT6vINk7negNQ6Dex3mRn+Jexm6Q0jTLbzOn6eJg9R6ZIi0SQ5wMQJAKX2n\n" - + "fGohqdaORgiRZRzcsHlaemXatsAEetPYdO2Gf7/l6mvKEahEKC6CoLn1jmxiQHmK\n" - + "LF6U8QTcXyUuB0uwOQJBAIwWWjQGGc2sAQ1HW0C2wwCQbWneeBkiRBedonDBHtiB\n" - + "Wz0zS2CMCtBPNeHQmmsXH2Ca+ADdh53sKTuperLiuiw=\n" - + "-----END RSA PRIVATE KEY-----"; - pkey = NativeCrypto.ENGINE_load_private_key(engine, rsaPem); - assertTrue(pkey != 0); - } finally { - if (pkey != NULL) { - NativeCrypto.EVP_PKEY_free(pkey); - } - - NativeCrypto.ENGINE_free(engine); - NativeCrypto.ENGINE_finish(engine); - } - } - - public void test_RAND_bytes_Success() throws Exception { - byte[] output = new byte[128]; - NativeCrypto.RAND_bytes(output); - - boolean isZero = true; - for (int i = 0; i < output.length; i++) { - isZero &= (output[i] == 0); - } - - assertFalse("Random output was zero. This is a very low probability event (1 in 2^128) " - + "and probably indicates an error.", isZero); - } - - public void test_RAND_bytes_Null_Failure() throws Exception { - byte[] output = null; - try { - NativeCrypto.RAND_bytes(output); - fail("Should be an error on null buffer input"); - } catch (RuntimeException expected) { - } - } - - public void test_EVP_get_digestbyname() throws Exception { - assertTrue(NativeCrypto.EVP_get_digestbyname("sha256") != NULL); - - try { - NativeCrypto.EVP_get_digestbyname(null); - fail(); - } catch (NullPointerException expected) { - } - - try { - NativeCrypto.EVP_get_digestbyname(""); - NativeCrypto.EVP_get_digestbyname("foobar"); - fail(); - } catch (RuntimeException expected) { - } - } - - public void test_EVP_SignInit() throws Exception { - final long ctx = NativeCrypto.EVP_SignInit("RSA-SHA256"); - assertTrue(ctx != NULL); - NativeCrypto.EVP_MD_CTX_destroy(ctx); - - try { - NativeCrypto.EVP_SignInit("foobar"); - fail(); - } catch (RuntimeException expected) { - } - } - - public void test_get_RSA_private_params() throws Exception { - try { - NativeCrypto.get_RSA_private_params(NULL); - } catch (NullPointerException expected) { - } - - try { - NativeCrypto.get_RSA_private_params(NULL); - } catch (NullPointerException expected) { - } - - // Test getting params for the wrong kind of key. - final byte[] seed = new byte[20]; - long ctx = 0; - try { - ctx = NativeCrypto.DSA_generate_key(2048, seed, dsa2048_g, dsa2048_p, dsa2048_q); - assertTrue(ctx != NULL); - try { - NativeCrypto.get_RSA_private_params(ctx); - fail(); - } catch (RuntimeException expected) { - } - } finally { - if (ctx != 0) { - NativeCrypto.EVP_PKEY_free(ctx); - } - } - } - - public void test_get_RSA_public_params() throws Exception { - try { - NativeCrypto.get_RSA_public_params(NULL); - } catch (NullPointerException expected) { - } - - try { - NativeCrypto.get_RSA_public_params(NULL); - } catch (NullPointerException expected) { - } - - // Test getting params for the wrong kind of key. - final byte[] seed = new byte[20]; - long ctx = 0; - try { - ctx = NativeCrypto.DSA_generate_key(2048, seed, dsa2048_g, dsa2048_p, dsa2048_q); - assertTrue(ctx != NULL); - try { - NativeCrypto.get_RSA_public_params(ctx); - fail(); - } catch (RuntimeException expected) { - } - } finally { - if (ctx != 0) { - NativeCrypto.EVP_PKEY_free(ctx); - } - } - } - - final byte[] dsa2048_p = { - (byte) 0xC3, (byte) 0x16, (byte) 0xD4, (byte) 0xBA, (byte) 0xDC, (byte) 0x0E, - (byte) 0xB8, (byte) 0xFC, (byte) 0x40, (byte) 0xDB, (byte) 0xB0, (byte) 0x76, - (byte) 0x47, (byte) 0xB8, (byte) 0x8D, (byte) 0xC1, (byte) 0xF1, (byte) 0xAB, - (byte) 0x9B, (byte) 0x80, (byte) 0x9D, (byte) 0xDC, (byte) 0x55, (byte) 0x33, - (byte) 0xEC, (byte) 0xB6, (byte) 0x09, (byte) 0x8F, (byte) 0xB7, (byte) 0xD9, - (byte) 0xA5, (byte) 0x7F, (byte) 0xC1, (byte) 0xE3, (byte) 0xAD, (byte) 0xE1, - (byte) 0x7A, (byte) 0x58, (byte) 0xF4, (byte) 0x2D, (byte) 0xB9, (byte) 0x61, - (byte) 0xCF, (byte) 0x5B, (byte) 0xCA, (byte) 0x41, (byte) 0x9F, (byte) 0x73, - (byte) 0x8D, (byte) 0x81, (byte) 0x62, (byte) 0xD2, (byte) 0x19, (byte) 0x7D, - (byte) 0x18, (byte) 0xDB, (byte) 0xB3, (byte) 0x04, (byte) 0xE7, (byte) 0xB2, - (byte) 0x28, (byte) 0x59, (byte) 0x14, (byte) 0x73, (byte) 0x43, (byte) 0xF1, - (byte) 0x45, (byte) 0xC7, (byte) 0x47, (byte) 0xCC, (byte) 0xD1, (byte) 0x12, - (byte) 0x8E, (byte) 0x19, (byte) 0x00, (byte) 0x2C, (byte) 0xD0, (byte) 0x86, - (byte) 0x54, (byte) 0x64, (byte) 0x2D, (byte) 0x42, (byte) 0x6C, (byte) 0x6B, - (byte) 0x5C, (byte) 0x2D, (byte) 0x4D, (byte) 0x97, (byte) 0x6A, (byte) 0x1D, - (byte) 0x89, (byte) 0xB1, (byte) 0x2C, (byte) 0xA0, (byte) 0x05, (byte) 0x2B, - (byte) 0x3C, (byte) 0xDB, (byte) 0x1F, (byte) 0x89, (byte) 0x03, (byte) 0x03, - (byte) 0x92, (byte) 0x63, (byte) 0xB6, (byte) 0x08, (byte) 0x32, (byte) 0x50, - (byte) 0xB2, (byte) 0x54, (byte) 0xA3, (byte) 0xFE, (byte) 0x6C, (byte) 0x35, - (byte) 0x17, (byte) 0x2F, (byte) 0x7F, (byte) 0x54, (byte) 0xA4, (byte) 0xAE, - (byte) 0x96, (byte) 0x1E, (byte) 0x31, (byte) 0x83, (byte) 0xF1, (byte) 0x3F, - (byte) 0x9E, (byte) 0xB9, (byte) 0x5D, (byte) 0xD3, (byte) 0xA9, (byte) 0xCB, - (byte) 0xE5, (byte) 0x2F, (byte) 0xBC, (byte) 0xA4, (byte) 0x1A, (byte) 0x31, - (byte) 0x41, (byte) 0x91, (byte) 0x2C, (byte) 0xA0, (byte) 0xF4, (byte) 0x83, - (byte) 0xAC, (byte) 0xD5, (byte) 0xBA, (byte) 0x3D, (byte) 0x19, (byte) 0xED, - (byte) 0xF1, (byte) 0x6C, (byte) 0xD9, (byte) 0x3F, (byte) 0x30, (byte) 0xDA, - (byte) 0x80, (byte) 0x06, (byte) 0x56, (byte) 0x3A, (byte) 0x8C, (byte) 0x74, - (byte) 0x63, (byte) 0xF2, (byte) 0xED, (byte) 0x1E, (byte) 0xE3, (byte) 0x86, - (byte) 0x95, (byte) 0x64, (byte) 0x2A, (byte) 0xC4, (byte) 0x5F, (byte) 0xB2, - (byte) 0x64, (byte) 0x40, (byte) 0x9D, (byte) 0xA6, (byte) 0xB8, (byte) 0xF5, - (byte) 0x84, (byte) 0x03, (byte) 0x2E, (byte) 0x4A, (byte) 0x7A, (byte) 0x1A, - (byte) 0xB0, (byte) 0x0E, (byte) 0xBA, (byte) 0xB1, (byte) 0xF5, (byte) 0xD2, - (byte) 0xE7, (byte) 0x65, (byte) 0xCE, (byte) 0xEE, (byte) 0x2C, (byte) 0x7C, - (byte) 0x68, (byte) 0x20, (byte) 0x50, (byte) 0x53, (byte) 0x0F, (byte) 0x60, - (byte) 0x92, (byte) 0x81, (byte) 0xC0, (byte) 0x2C, (byte) 0x2A, (byte) 0xEA, - (byte) 0xE9, (byte) 0xB3, (byte) 0x2A, (byte) 0x81, (byte) 0xDA, (byte) 0x0F, - (byte) 0xBB, (byte) 0xFA, (byte) 0x5B, (byte) 0x47, (byte) 0xDA, (byte) 0x57, - (byte) 0x4E, (byte) 0xFC, (byte) 0x05, (byte) 0x2C, (byte) 0x6A, (byte) 0x90, - (byte) 0xA0, (byte) 0x99, (byte) 0x88, (byte) 0x71, (byte) 0x8A, (byte) 0xCC, - (byte) 0xD2, (byte) 0x97, (byte) 0x11, (byte) 0xB1, (byte) 0xCE, (byte) 0xF7, - (byte) 0x47, (byte) 0x53, (byte) 0x53, (byte) 0x68, (byte) 0xE1, (byte) 0x2A, - (byte) 0x56, (byte) 0xD5, (byte) 0x3D, (byte) 0xDF, (byte) 0x08, (byte) 0x16, - (byte) 0x1F, (byte) 0xAA, (byte) 0x54, (byte) 0x15, - }; - - final byte[] dsa2048_q = { - (byte) 0xAA, (byte) 0xDD, (byte) 0xE2, (byte) 0xCE, (byte) 0x08, (byte) 0xC0, - (byte) 0x0E, (byte) 0x91, (byte) 0x8C, (byte) 0xD9, (byte) 0xBC, (byte) 0x1E, - (byte) 0x05, (byte) 0x70, (byte) 0x07, (byte) 0x3B, (byte) 0xB5, (byte) 0xA9, - (byte) 0xB5, (byte) 0x8B, (byte) 0x21, (byte) 0x68, (byte) 0xA2, (byte) 0x76, - (byte) 0x53, (byte) 0x1E, (byte) 0x68, (byte) 0x1B, (byte) 0x4F, (byte) 0x88, - (byte) 0x6D, (byte) 0xCF, - }; - - final byte[] dsa2048_g = { - (byte) 0x6B, (byte) 0x4D, (byte) 0x21, (byte) 0x92, (byte) 0x24, (byte) 0x76, - (byte) 0xE5, (byte) 0xA2, (byte) 0xCE, (byte) 0x02, (byte) 0x85, (byte) 0x32, - (byte) 0x73, (byte) 0x70, (byte) 0xFF, (byte) 0xB9, (byte) 0xD4, (byte) 0x51, - (byte) 0xBA, (byte) 0x22, (byte) 0x8B, (byte) 0x75, (byte) 0x29, (byte) 0xE3, - (byte) 0xF2, (byte) 0x2E, (byte) 0x20, (byte) 0xF5, (byte) 0x6A, (byte) 0xD9, - (byte) 0x75, (byte) 0xA0, (byte) 0xC0, (byte) 0x3B, (byte) 0x12, (byte) 0x2F, - (byte) 0x4F, (byte) 0x9A, (byte) 0xF8, (byte) 0x5D, (byte) 0x45, (byte) 0xC5, - (byte) 0x80, (byte) 0x6C, (byte) 0x9B, (byte) 0x56, (byte) 0xBE, (byte) 0x8E, - (byte) 0x40, (byte) 0xF9, (byte) 0x0A, (byte) 0xF0, (byte) 0x3D, (byte) 0xD7, - (byte) 0x7C, (byte) 0xDE, (byte) 0x22, (byte) 0x10, (byte) 0x24, (byte) 0xCC, - (byte) 0xAE, (byte) 0x8A, (byte) 0xC0, (byte) 0x05, (byte) 0xCD, (byte) 0xDC, - (byte) 0x10, (byte) 0x29, (byte) 0x4D, (byte) 0xFC, (byte) 0xEC, (byte) 0xEF, - (byte) 0x51, (byte) 0x4B, (byte) 0xF9, (byte) 0xCC, (byte) 0x99, (byte) 0x84, - (byte) 0x1B, (byte) 0x14, (byte) 0x68, (byte) 0xEC, (byte) 0xF0, (byte) 0x5E, - (byte) 0x07, (byte) 0x10, (byte) 0x09, (byte) 0xA9, (byte) 0x2C, (byte) 0x04, - (byte) 0xD0, (byte) 0x14, (byte) 0xBF, (byte) 0x88, (byte) 0x9E, (byte) 0xBB, - (byte) 0xE3, (byte) 0x3F, (byte) 0xDE, (byte) 0x92, (byte) 0xE1, (byte) 0x64, - (byte) 0x07, (byte) 0x28, (byte) 0xC1, (byte) 0xCA, (byte) 0x48, (byte) 0xC1, - (byte) 0x1D, (byte) 0x33, (byte) 0xE4, (byte) 0x35, (byte) 0xBE, (byte) 0xDF, - (byte) 0x5E, (byte) 0x50, (byte) 0xF9, (byte) 0xC2, (byte) 0x0E, (byte) 0x25, - (byte) 0x0D, (byte) 0x20, (byte) 0x8C, (byte) 0x01, (byte) 0x0A, (byte) 0x23, - (byte) 0xD4, (byte) 0x6E, (byte) 0x42, (byte) 0x47, (byte) 0xE1, (byte) 0x9E, - (byte) 0x36, (byte) 0x91, (byte) 0xC8, (byte) 0x65, (byte) 0x44, (byte) 0xE0, - (byte) 0x04, (byte) 0x86, (byte) 0x2F, (byte) 0xD4, (byte) 0x90, (byte) 0x16, - (byte) 0x09, (byte) 0x14, (byte) 0xB1, (byte) 0xC5, (byte) 0x7D, (byte) 0xB2, - (byte) 0x7C, (byte) 0x36, (byte) 0x0D, (byte) 0x9C, (byte) 0x1F, (byte) 0x83, - (byte) 0x57, (byte) 0x94, (byte) 0x26, (byte) 0x32, (byte) 0x9C, (byte) 0x86, - (byte) 0x8E, (byte) 0xE5, (byte) 0x80, (byte) 0x3A, (byte) 0xA9, (byte) 0xAF, - (byte) 0x4A, (byte) 0x95, (byte) 0x78, (byte) 0x8D, (byte) 0xE6, (byte) 0xC3, - (byte) 0x0C, (byte) 0x78, (byte) 0x83, (byte) 0x4B, (byte) 0xF5, (byte) 0x40, - (byte) 0x04, (byte) 0x20, (byte) 0x90, (byte) 0x5C, (byte) 0xA1, (byte) 0x19, - (byte) 0xEB, (byte) 0x95, (byte) 0x70, (byte) 0x2B, (byte) 0x94, (byte) 0xA3, - (byte) 0x43, (byte) 0xDD, (byte) 0xEB, (byte) 0xD4, (byte) 0x0C, (byte) 0xBC, - (byte) 0xBD, (byte) 0x58, (byte) 0x2D, (byte) 0x75, (byte) 0xB0, (byte) 0x8D, - (byte) 0x8B, (byte) 0x70, (byte) 0xB9, (byte) 0xE7, (byte) 0xA3, (byte) 0xCC, - (byte) 0x8C, (byte) 0xB4, (byte) 0xCD, (byte) 0xBB, (byte) 0x4B, (byte) 0xB1, - (byte) 0x15, (byte) 0x18, (byte) 0x79, (byte) 0xDF, (byte) 0x22, (byte) 0xA6, - (byte) 0x5C, (byte) 0x90, (byte) 0x7C, (byte) 0x1F, (byte) 0xEA, (byte) 0x1B, - (byte) 0xF2, (byte) 0x89, (byte) 0x87, (byte) 0xB2, (byte) 0xEC, (byte) 0x57, - (byte) 0xFF, (byte) 0xB2, (byte) 0xDA, (byte) 0xF5, (byte) 0xAD, (byte) 0x73, - (byte) 0xC0, (byte) 0xA0, (byte) 0x20, (byte) 0x8B, (byte) 0x78, (byte) 0xA1, - (byte) 0x5D, (byte) 0x04, (byte) 0x0A, (byte) 0x29, (byte) 0xE3, (byte) 0xD7, - (byte) 0x37, (byte) 0xF6, (byte) 0xA2, (byte) 0xCA, - }; - - public void test_DSA_generate_key() throws Exception { - final byte[] seed = new byte[20]; - - // Real key - { - long ctx = 0; - try { - ctx = NativeCrypto.DSA_generate_key(2048, seed, dsa2048_g, dsa2048_p, dsa2048_q); - assertTrue(ctx != NULL); - } finally { - if (ctx != 0) { - NativeCrypto.EVP_PKEY_free(ctx); - } - } - } - - // Real key with minimum bit size (should be 512 bits) - { - long ctx = 0; - try { - ctx = NativeCrypto.DSA_generate_key(0, null, null, null, null); - assertTrue(ctx != NULL); - } finally { - if (ctx != 0) { - NativeCrypto.EVP_PKEY_free(ctx); - } - } - } - - // Bad DSA params. - { - long ctx = 0; - try { - ctx = NativeCrypto.DSA_generate_key(0, null, new byte[] {}, new byte[] {}, - new byte[] {}); - fail(); - } catch (RuntimeException expected) { - } finally { - if (ctx != 0) { - NativeCrypto.EVP_PKEY_free(ctx); - } - } - } - } - - /* - * Test vector generation: - * openssl rand -hex 16 - */ - private static final byte[] AES_128_KEY = new byte[] { - (byte) 0x3d, (byte) 0x4f, (byte) 0x89, (byte) 0x70, (byte) 0xb1, (byte) 0xf2, - (byte) 0x75, (byte) 0x37, (byte) 0xf4, (byte) 0x0a, (byte) 0x39, (byte) 0x29, - (byte) 0x8a, (byte) 0x41, (byte) 0x55, (byte) 0x5f, - }; - - private static final byte[] AES_IV_ZEROES = new byte[] { - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - }; - - public void testEC_GROUP() throws Exception { - /* Test using NIST's P-256 curve */ - check_EC_GROUP(NativeCrypto.EC_CURVE_GFP, "prime256v1", - "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", - "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", - "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", - "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", - "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", - "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", - 1L); - - check_EC_GROUP(NativeCrypto.EC_CURVE_GF2M, "sect283r1", - "0800000000000000000000000000000000000000000000000000000000000000000010A1", - "000000000000000000000000000000000000000000000000000000000000000000000001", - "027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5", - "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053", - "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4", - "03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307", - 2L); - } - - private void check_EC_GROUP(int type, String name, String pStr, String aStr, String bStr, - String xStr, String yStr, String nStr, long hLong) throws Exception { - long group1 = NULL, group2 = NULL, point1 = NULL, point2 = NULL, key1 = NULL; - try { - group1 = NativeCrypto.EC_GROUP_new_by_curve_name(name); - assertTrue(group1 != NULL); - assertEquals(NativeCrypto.OBJ_txt2nid_longName(name), - NativeCrypto.EC_GROUP_get_curve_name(group1)); - assertEquals(type, NativeCrypto.get_EC_GROUP_type(group1)); - - // prime - BigInteger p = new BigInteger(pStr, 16); - // first coefficient - BigInteger a = new BigInteger(aStr, 16); - // second coefficient - BigInteger b = new BigInteger(bStr, 16); - // x affine coordinate of generator - BigInteger x = new BigInteger(xStr, 16); - // y affine coordinate of generator - BigInteger y = new BigInteger(yStr, 16); - // order of the generator - BigInteger n = new BigInteger(nStr, 16); - // cofactor of generator - BigInteger h = BigInteger.valueOf(hLong); - - group2 = NativeCrypto.EC_GROUP_new_curve(type, p.toByteArray(), - a.toByteArray(), b.toByteArray()); - assertEquals(type, NativeCrypto.get_EC_GROUP_type(group2)); - - point2 = NativeCrypto.EC_POINT_new(group2); - - NativeCrypto.EC_POINT_set_affine_coordinates(group2, point2, x.toByteArray(), - y.toByteArray()); - - NativeCrypto.EC_GROUP_set_generator(group2, point2, n.toByteArray(), h.toByteArray()); - - point1 = NativeCrypto.EC_GROUP_get_generator(group2); - assertTrue(NativeCrypto.EC_POINT_cmp(group1, point1, point2)); - - byte[][] pab = NativeCrypto.EC_GROUP_get_curve(group2); - assertEquals(3, pab.length); - - BigInteger p2 = new BigInteger(pab[0]); - assertEquals(p, p2); - - BigInteger a2 = new BigInteger(pab[1]); - assertEquals(a, a2); - - BigInteger b2 = new BigInteger(pab[2]); - assertEquals(b, b2); - - byte[][] xy = NativeCrypto.EC_POINT_get_affine_coordinates(group2, point2); - assertEquals(2, xy.length); - - BigInteger x2 = new BigInteger(xy[0]); - assertEquals(x, x2); - - BigInteger y2 = new BigInteger(xy[1]); - assertEquals(y, y2); - - BigInteger n2 = new BigInteger(NativeCrypto.EC_GROUP_get_order(group1)); - assertEquals(n, n2); - - BigInteger h2 = new BigInteger(NativeCrypto.EC_GROUP_get_cofactor(group2)); - assertEquals(h, h2); - - assertTrue(NativeCrypto.EC_GROUP_cmp(group1, group2)); - - key1 = NativeCrypto.EC_KEY_generate_key(group1); - long groupTmp = NativeCrypto.EC_KEY_get0_group(key1); - assertEquals(NativeCrypto.EC_GROUP_get_curve_name(group1), - NativeCrypto.EC_GROUP_get_curve_name(groupTmp)); - - } finally { - if (group1 != NULL) { - NativeCrypto.EC_GROUP_clear_free(group1); - } - - if (group2 != NULL) { - NativeCrypto.EC_GROUP_clear_free(group2); - } - - if (point1 != NULL) { - NativeCrypto.EC_POINT_clear_free(point1); - } - - if (point2 != NULL) { - NativeCrypto.EC_POINT_clear_free(point2); - } - - if (key1 != NULL) { - NativeCrypto.EVP_PKEY_free(key1); - } - } - } - - public void test_EVP_CipherInit_ex_Null_Failure() throws Exception { - final long ctx = NativeCrypto.EVP_CIPHER_CTX_new(); - try { - final long evpCipher = NativeCrypto.EVP_get_cipherbyname("aes-128-ecb"); - - try { - NativeCrypto.EVP_CipherInit_ex(NULL, evpCipher, null, null, true); - fail("Null context should throw NullPointerException"); - } catch (NullPointerException expected) { - } - - /* Initialize encrypting. */ - NativeCrypto.EVP_CipherInit_ex(ctx, evpCipher, null, null, true); - NativeCrypto.EVP_CipherInit_ex(ctx, NULL, null, null, true); - - /* Initialize decrypting. */ - NativeCrypto.EVP_CipherInit_ex(ctx, evpCipher, null, null, false); - NativeCrypto.EVP_CipherInit_ex(ctx, NULL, null, null, false); - } finally { - NativeCrypto.EVP_CIPHER_CTX_cleanup(ctx); - } - } - - public void test_EVP_CipherInit_ex_Success() throws Exception { - final long ctx = NativeCrypto.EVP_CIPHER_CTX_new(); - try { - final long evpCipher = NativeCrypto.EVP_get_cipherbyname("aes-128-ecb"); - NativeCrypto.EVP_CipherInit_ex(ctx, evpCipher, AES_128_KEY, null, true); - } finally { - NativeCrypto.EVP_CIPHER_CTX_cleanup(ctx); - } - } - - public void test_EVP_CIPHER_iv_length() throws Exception { - long aes128ecb = NativeCrypto.EVP_get_cipherbyname("aes-128-ecb"); - assertEquals(0, NativeCrypto.EVP_CIPHER_iv_length(aes128ecb)); - - long aes128cbc = NativeCrypto.EVP_get_cipherbyname("aes-128-cbc"); - assertEquals(16, NativeCrypto.EVP_CIPHER_iv_length(aes128cbc)); - } - - public void test_OpenSSLKey_toJava() throws Exception { - OpenSSLKey key1; - - BigInteger e = BigInteger.valueOf(65537); - key1 = new OpenSSLKey(NativeCrypto.RSA_generate_key_ex(1024, e.toByteArray())); - assertTrue(key1.getPublicKey() instanceof RSAPublicKey); - - key1 = new OpenSSLKey(NativeCrypto.DSA_generate_key(1024, null, null, null, null)); - assertTrue(key1.getPublicKey() instanceof DSAPublicKey); - - long group1 = NULL; - try { - group1 = NativeCrypto.EC_GROUP_new_by_curve_name("prime256v1"); - assertTrue(group1 != NULL); - key1 = new OpenSSLKey(NativeCrypto.EC_KEY_generate_key(group1)); - } finally { - if (group1 != NULL) { - NativeCrypto.EC_GROUP_clear_free(group1); - } - } - assertTrue(key1.getPublicKey() instanceof ECPublicKey); - } - - public void test_create_BIO_InputStream() throws Exception { - byte[] actual = "Test".getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream(actual); - - long ctx = NativeCrypto.create_BIO_InputStream(new OpenSSLBIOInputStream(is)); - try { - byte[] buffer = new byte[1024]; - int numRead = NativeCrypto.BIO_read(ctx, buffer); - assertEquals(actual.length, numRead); - assertEquals(Arrays.toString(actual), - Arrays.toString(Arrays.copyOfRange(buffer, 0, numRead))); - } finally { - NativeCrypto.BIO_free(ctx); - } - - } - - public void test_create_BIO_OutputStream() throws Exception { - byte[] actual = "Test".getBytes(); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - - long ctx = NativeCrypto.create_BIO_OutputStream(os); - try { - NativeCrypto.BIO_write(ctx, actual, 0, actual.length); - assertEquals(actual.length, os.size()); - assertEquals(Arrays.toString(actual), Arrays.toString(os.toByteArray())); - } finally { - NativeCrypto.BIO_free(ctx); - } - } -} diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignatureTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignatureTest.java deleted file mode 100644 index 76e423c..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignatureTest.java +++ /dev/null @@ -1,37 +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 org.apache.harmony.xnet.provider.jsse; - -import java.security.NoSuchAlgorithmException; -import junit.framework.TestCase; -import org.apache.harmony.xnet.provider.jsse.OpenSSLSignature; - -public class OpenSSLSignatureTest extends TestCase { - - public void test_getInstance() throws Exception { - try { - OpenSSLSignature.getInstance("SHA1WITHDSA"); - OpenSSLSignature.getInstance("MD5WITHRSAENCRYPTION"); - OpenSSLSignature.getInstance("SHA1WITHRSAENCRYPTION"); - OpenSSLSignature.getInstance("SHA256WITHRSAENCRYPTION"); - OpenSSLSignature.getInstance("SHA384WITHRSAENCRYPTION"); - OpenSSLSignature.getInstance("SHA512WITHRSAENCRYPTION"); - } catch (NoSuchAlgorithmException e) { - fail("getInstance is not case insensitive"); - } - } -} diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImplTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImplTest.java deleted file mode 100644 index 9757bc5..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImplTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (C) 2011 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.apache.harmony.xnet.provider.jsse; - -import java.io.File; -import java.io.FileWriter; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.security.KeyStore; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; -import junit.framework.TestCase; -import libcore.java.security.TestKeyStore; - -public class TrustManagerImplTest extends TestCase { - - private List<File> tmpFiles = new ArrayList<File>(); - - private String getFingerprint(X509Certificate cert) throws Exception { - MessageDigest dgst = MessageDigest.getInstance("SHA512"); - byte[] encoded = cert.getPublicKey().getEncoded(); - byte[] fingerprint = dgst.digest(encoded); - return IntegralToString.bytesToHexString(fingerprint, false); - } - - private String writeTmpPinFile(String text) throws Exception { - File tmp = File.createTempFile("pins", null); - FileWriter fstream = new FileWriter(tmp); - fstream.write(text); - fstream.close(); - tmpFiles.add(tmp); - return tmp.getPath(); - } - - @Override - public void tearDown() throws Exception { - try { - for (File f : tmpFiles) { - f.delete(); - } - tmpFiles.clear(); - } finally { - super.tearDown(); - } - } - - /** - * Ensure that our non-standard behavior of learning to trust new - * intermediate CAs does not regress. http://b/3404902 - */ - public void testLearnIntermediate() throws Exception { - // chain3 should be server/intermediate/root - KeyStore.PrivateKeyEntry pke = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); - X509Certificate[] chain3 = (X509Certificate[])pke.getCertificateChain(); - X509Certificate root = chain3[2]; - X509Certificate intermediate = chain3[1]; - X509Certificate server = chain3[0]; - X509Certificate[] chain2 = new X509Certificate[] { server, intermediate }; - X509Certificate[] chain1 = new X509Certificate[] { server }; - - // Normal behavior - assertValid(chain3, trustManager(root)); - assertValid(chain2, trustManager(root)); - assertInvalid(chain1, trustManager(root)); - assertValid(chain3, trustManager(intermediate)); - assertValid(chain2, trustManager(intermediate)); - assertValid(chain1, trustManager(intermediate)); - assertValid(chain3, trustManager(server)); - assertValid(chain2, trustManager(server)); - assertValid(chain1, trustManager(server)); - - // non-standard behavior - X509TrustManager tm = trustManager(root); - // fail on short chain with only root trusted - assertInvalid(chain1, tm); - // succeed on longer chain, learn intermediate - assertValid(chain2, tm); - // now we can validate the short chain - assertValid(chain1, tm); - } - - // We should ignore duplicate cruft in the certificate chain - // See https://code.google.com/p/android/issues/detail?id=52295 http://b/8313312 - public void testDuplicateInChain() throws Exception { - // chain3 should be server/intermediate/root - KeyStore.PrivateKeyEntry pke = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); - X509Certificate[] chain3 = (X509Certificate[])pke.getCertificateChain(); - X509Certificate root = chain3[2]; - X509Certificate intermediate = chain3[1]; - X509Certificate server = chain3[0]; - - X509Certificate[] chain4 = new X509Certificate[] { server, intermediate, - server, intermediate - }; - assertValid(chain4, trustManager(root)); - } - - public void testGetFullChain() throws Exception { - // build the trust manager - KeyStore.PrivateKeyEntry pke = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); - X509Certificate[] chain3 = (X509Certificate[])pke.getCertificateChain(); - X509Certificate root = chain3[2]; - X509TrustManager tm = trustManager(root); - - // build the chains we'll use for testing - X509Certificate intermediate = chain3[1]; - X509Certificate server = chain3[0]; - X509Certificate[] chain2 = new X509Certificate[] { server, intermediate }; - X509Certificate[] chain1 = new X509Certificate[] { server }; - - assertTrue(tm instanceof TrustManagerImpl); - TrustManagerImpl tmi = (TrustManagerImpl) tm; - List<X509Certificate> certs = tmi.checkServerTrusted(chain2, "RSA", "purple.com"); - assertEquals(Arrays.asList(chain3), certs); - certs = tmi.checkServerTrusted(chain1, "RSA", "purple.com"); - assertEquals(Arrays.asList(chain3), certs); - } - - public void testCertPinning() throws Exception { - // chain3 should be server/intermediate/root - KeyStore.PrivateKeyEntry pke = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); - X509Certificate[] chain3 = (X509Certificate[]) pke.getCertificateChain(); - X509Certificate root = chain3[2]; - X509Certificate intermediate = chain3[1]; - X509Certificate server = chain3[0]; - X509Certificate[] chain2 = new X509Certificate[] { server, intermediate }; - X509Certificate[] chain1 = new X509Certificate[] { server }; - - // test without a hostname, expecting failure - assertInvalidPinned(chain1, trustManager(root, "gugle.com", root), null); - // test without a hostname, expecting success - assertValidPinned(chain3, trustManager(root, "gugle.com", root), null, chain3); - // test an unpinned hostname that should fail - assertInvalidPinned(chain1, trustManager(root, "gugle.com", root), "purple.com"); - // test an unpinned hostname that should succeed - assertValidPinned(chain3, trustManager(root, "gugle.com", root), "purple.com", chain3); - // test a pinned hostname that should fail - assertInvalidPinned(chain1, trustManager(intermediate, "gugle.com", root), "gugle.com"); - // test a pinned hostname that should succeed - assertValidPinned(chain2, trustManager(intermediate, "gugle.com", server), "gugle.com", - chain2); - } - - private X509TrustManager trustManager(X509Certificate ca) throws Exception { - KeyStore keyStore = TestKeyStore.createKeyStore(); - keyStore.setCertificateEntry("alias", ca); - - String algorithm = TrustManagerFactory.getDefaultAlgorithm(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); - tmf.init(keyStore); - return (X509TrustManager) tmf.getTrustManagers()[0]; - } - - private TrustManagerImpl trustManager(X509Certificate ca, String hostname, X509Certificate pin) - throws Exception { - // build the cert pin manager - CertPinManager cm = certManager(hostname, pin); - // insert it into the trust manager - KeyStore keyStore = TestKeyStore.createKeyStore(); - keyStore.setCertificateEntry("alias", ca); - return new TrustManagerImpl(keyStore, cm); - } - - private CertPinManager certManager(String hostname, X509Certificate pin) throws Exception { - String pinString = ""; - if (pin != null) { - pinString = hostname + "=true|" + getFingerprint(pin); - } - // write it to a pinfile - String path = writeTmpPinFile(pinString); - // build the certpinmanager - return new CertPinManager(path, new TrustedCertificateStore()); - } - - private void assertValid(X509Certificate[] chain, X509TrustManager tm) throws Exception { - if (tm instanceof TrustManagerImpl) { - TrustManagerImpl tmi = (TrustManagerImpl) tm; - tmi.checkServerTrusted(chain, "RSA"); - } - tm.checkServerTrusted(chain, "RSA"); - } - - private void assertValidPinned(X509Certificate[] chain, X509TrustManager tm, String hostname, - X509Certificate[] fullChain) throws Exception { - if (tm instanceof TrustManagerImpl) { - TrustManagerImpl tmi = (TrustManagerImpl) tm; - List<X509Certificate> checkedChain = tmi.checkServerTrusted(chain, "RSA", hostname); - assertEquals(checkedChain, Arrays.asList(fullChain)); - } - tm.checkServerTrusted(chain, "RSA"); - } - - private void assertInvalid(X509Certificate[] chain, X509TrustManager tm) { - try { - tm.checkClientTrusted(chain, "RSA"); - fail(); - } catch (CertificateException expected) { - } - try { - tm.checkServerTrusted(chain, "RSA"); - fail(); - } catch (CertificateException expected) { - } - } - - private void assertInvalidPinned(X509Certificate[] chain, X509TrustManager tm, String hostname) - throws Exception { - assertTrue(tm.getClass().getName(), tm instanceof TrustManagerImpl); - try { - TrustManagerImpl tmi = (TrustManagerImpl) tm; - tmi.checkServerTrusted(chain, "RSA", hostname); - fail(); - } catch (CertificateException expected) { - } - } -} diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/TrustedCertificateStoreTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/TrustedCertificateStoreTest.java deleted file mode 100644 index 8f9b7fa..0000000 --- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/TrustedCertificateStoreTest.java +++ /dev/null @@ -1,662 +0,0 @@ -/* - * Copyright (C) 2011 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.apache.harmony.xnet.provider.jsse; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Set; -import javax.security.auth.x500.X500Principal; -import junit.framework.TestCase; -import libcore.java.security.TestKeyStore; - -public class TrustedCertificateStoreTest extends TestCase { - - private static final File DIR_TEMP = new File(System.getProperty("java.io.tmpdir")); - private static final File DIR_TEST = new File(DIR_TEMP, "test"); - private static final File DIR_SYSTEM = new File(DIR_TEST, "system"); - private static final File DIR_ADDED = new File(DIR_TEST, "added"); - private static final File DIR_DELETED = new File(DIR_TEST, "removed"); - - private static X509Certificate CA1; - private static X509Certificate CA2; - - private static KeyStore.PrivateKeyEntry PRIVATE; - private static X509Certificate[] CHAIN; - - private static X509Certificate CA3_WITH_CA1_SUBJECT; - private static String ALIAS_SYSTEM_CA1; - private static String ALIAS_SYSTEM_CA2; - private static String ALIAS_USER_CA1; - private static String ALIAS_USER_CA2; - - private static String ALIAS_SYSTEM_CHAIN0; - private static String ALIAS_SYSTEM_CHAIN1; - private static String ALIAS_SYSTEM_CHAIN2; - private static String ALIAS_USER_CHAIN0; - private static String ALIAS_USER_CHAIN1; - private static String ALIAS_USER_CHAIN2; - - private static String ALIAS_SYSTEM_CA3; - private static String ALIAS_SYSTEM_CA3_COLLISION; - private static String ALIAS_USER_CA3; - private static String ALIAS_USER_CA3_COLLISION; - - private static X509Certificate getCa1() { - initCerts(); - return CA1; - } - private static X509Certificate getCa2() { - initCerts(); - return CA2; - } - - private static KeyStore.PrivateKeyEntry getPrivate() { - initCerts(); - return PRIVATE; - } - private static X509Certificate[] getChain() { - initCerts(); - return CHAIN; - } - - private static X509Certificate getCa3WithCa1Subject() { - initCerts(); - return CA3_WITH_CA1_SUBJECT; - } - - private static String getAliasSystemCa1() { - initCerts(); - return ALIAS_SYSTEM_CA1; - } - private static String getAliasSystemCa2() { - initCerts(); - return ALIAS_SYSTEM_CA2; - } - private static String getAliasUserCa1() { - initCerts(); - return ALIAS_USER_CA1; - } - private static String getAliasUserCa2() { - initCerts(); - return ALIAS_USER_CA2; - } - - private static String getAliasSystemChain0() { - initCerts(); - return ALIAS_SYSTEM_CHAIN0; - } - private static String getAliasSystemChain1() { - initCerts(); - return ALIAS_SYSTEM_CHAIN1; - } - private static String getAliasSystemChain2() { - initCerts(); - return ALIAS_SYSTEM_CHAIN2; - } - private static String getAliasUserChain0() { - initCerts(); - return ALIAS_USER_CHAIN0; - } - private static String getAliasUserChain1() { - initCerts(); - return ALIAS_USER_CHAIN1; - } - private static String getAliasUserChain2() { - initCerts(); - return ALIAS_USER_CHAIN2; - } - - private static String getAliasSystemCa3() { - initCerts(); - return ALIAS_SYSTEM_CA3; - } - private static String getAliasSystemCa3Collision() { - initCerts(); - return ALIAS_SYSTEM_CA3_COLLISION; - } - private static String getAliasUserCa3() { - initCerts(); - return ALIAS_USER_CA3; - } - private static String getAliasUserCa3Collision() { - initCerts(); - return ALIAS_USER_CA3_COLLISION; - } - - /** - * Lazily create shared test certificates. - */ - private static synchronized void initCerts() { - if (CA1 != null) { - return; - } - try { - CA1 = TestKeyStore.getClient().getRootCertificate("RSA"); - CA2 = TestKeyStore.getClientCA2().getRootCertificate("RSA"); - PRIVATE = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); - CHAIN = (X509Certificate[]) PRIVATE.getCertificateChain(); - CA3_WITH_CA1_SUBJECT = new TestKeyStore.Builder() - .aliasPrefix("unused") - .subject(CA1.getSubjectX500Principal()) - .ca(true) - .build().getRootCertificate("RSA"); - - - ALIAS_SYSTEM_CA1 = alias(false, CA1, 0); - ALIAS_SYSTEM_CA2 = alias(false, CA2, 0); - ALIAS_USER_CA1 = alias(true, CA1, 0); - ALIAS_USER_CA2 = alias(true, CA2, 0); - - ALIAS_SYSTEM_CHAIN0 = alias(false, getChain()[0], 0); - ALIAS_SYSTEM_CHAIN1 = alias(false, getChain()[1], 0); - ALIAS_SYSTEM_CHAIN2 = alias(false, getChain()[2], 0); - ALIAS_USER_CHAIN0 = alias(true, getChain()[0], 0); - ALIAS_USER_CHAIN1 = alias(true, getChain()[1], 0); - ALIAS_USER_CHAIN2 = alias(true, getChain()[2], 0); - - ALIAS_SYSTEM_CA3 = alias(false, CA3_WITH_CA1_SUBJECT, 0); - ALIAS_SYSTEM_CA3_COLLISION = alias(false, CA3_WITH_CA1_SUBJECT, 1); - ALIAS_USER_CA3 = alias(true, CA3_WITH_CA1_SUBJECT, 0); - ALIAS_USER_CA3_COLLISION = alias(true, CA3_WITH_CA1_SUBJECT, 1); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private TrustedCertificateStore store; - - @Override protected void setUp() { - setupStore(); - } - - private void setupStore() { - DIR_SYSTEM.mkdirs(); - createStore(); - } - - private void createStore() { - store = new TrustedCertificateStore(DIR_SYSTEM, DIR_ADDED, DIR_DELETED); - } - - @Override protected void tearDown() { - cleanStore(); - } - - private void cleanStore() { - for (File dir : new File[] { DIR_SYSTEM, DIR_ADDED, DIR_DELETED, DIR_TEST }) { - File[] files = dir.listFiles(); - if (files == null) { - continue; - } - for (File file : files) { - assertTrue(file.delete()); - } - } - store = null; - } - - private void resetStore() { - cleanStore(); - setupStore(); - } - - public void testEmptyDirectories() throws Exception { - assertEmpty(); - } - - public void testOneSystemOneDeleted() throws Exception { - install(getCa1(), getAliasSystemCa1()); - store.deleteCertificateEntry(getAliasSystemCa1()); - assertEmpty(); - assertDeleted(getCa1(), getAliasSystemCa1()); - } - - public void testTwoSystemTwoDeleted() throws Exception { - install(getCa1(), getAliasSystemCa1()); - store.deleteCertificateEntry(getAliasSystemCa1()); - install(getCa2(), getAliasSystemCa2()); - store.deleteCertificateEntry(getAliasSystemCa2()); - assertEmpty(); - assertDeleted(getCa1(), getAliasSystemCa1()); - assertDeleted(getCa2(), getAliasSystemCa2()); - } - - public void testPartialFileIsIgnored() throws Exception { - File file = file(getAliasSystemCa1()); - OutputStream os = new FileOutputStream(file); - os.write(0); - os.close(); - assertTrue(file.exists()); - assertEmpty(); - assertTrue(file.exists()); - } - - private void assertEmpty() throws Exception { - try { - store.getCertificate(null); - fail(); - } catch (NullPointerException expected) { - } - assertNull(store.getCertificate("")); - - try { - store.getCreationDate(null); - fail(); - } catch (NullPointerException expected) { - } - assertNull(store.getCreationDate("")); - - Set<String> s = store.aliases(); - assertNotNull(s); - assertTrue(s.isEmpty()); - assertAliases(); - - Set<String> u = store.userAliases(); - assertNotNull(u); - assertTrue(u.isEmpty()); - - try { - store.containsAlias(null); - fail(); - } catch (NullPointerException expected) { - } - assertFalse(store.containsAlias("")); - - assertNull(store.getCertificateAlias(null)); - assertNull(store.getCertificateAlias(getCa1())); - - try { - store.isTrustAnchor(null); - fail(); - } catch (NullPointerException expected) { - } - assertFalse(store.isTrustAnchor(getCa1())); - - try { - store.findIssuer(null); - fail(); - } catch (NullPointerException expected) { - } - assertNull(store.findIssuer(getCa1())); - - try { - store.installCertificate(null); - fail(); - } catch (NullPointerException expected) { - } - - store.deleteCertificateEntry(null); - store.deleteCertificateEntry(""); - - String[] userFiles = DIR_ADDED.list(); - assertTrue(userFiles == null || userFiles.length == 0); - } - - public void testTwoSystem() throws Exception { - testTwo(getCa1(), getAliasSystemCa1(), - getCa2(), getAliasSystemCa2()); - } - - public void testTwoUser() throws Exception { - testTwo(getCa1(), getAliasUserCa1(), - getCa2(), getAliasUserCa2()); - } - - public void testOneSystemOneUser() throws Exception { - testTwo(getCa1(), getAliasSystemCa1(), - getCa2(), getAliasUserCa2()); - } - - public void testTwoSystemSameSubject() throws Exception { - testTwo(getCa1(), getAliasSystemCa1(), - getCa3WithCa1Subject(), getAliasSystemCa3Collision()); - } - - public void testTwoUserSameSubject() throws Exception { - testTwo(getCa1(), getAliasUserCa1(), - getCa3WithCa1Subject(), getAliasUserCa3Collision()); - - store.deleteCertificateEntry(getAliasUserCa1()); - assertDeleted(getCa1(), getAliasUserCa1()); - assertTombstone(getAliasUserCa1()); - assertRootCa(getCa3WithCa1Subject(), getAliasUserCa3Collision()); - assertAliases(getAliasUserCa3Collision()); - - store.deleteCertificateEntry(getAliasUserCa3Collision()); - assertDeleted(getCa3WithCa1Subject(), getAliasUserCa3Collision()); - assertNoTombstone(getAliasUserCa3Collision()); - assertNoTombstone(getAliasUserCa1()); - assertEmpty(); - } - - public void testOneSystemOneUserSameSubject() throws Exception { - testTwo(getCa1(), getAliasSystemCa1(), - getCa3WithCa1Subject(), getAliasUserCa3()); - testTwo(getCa1(), getAliasUserCa1(), - getCa3WithCa1Subject(), getAliasSystemCa3()); - } - - private void testTwo(X509Certificate x1, String alias1, - X509Certificate x2, String alias2) { - install(x1, alias1); - install(x2, alias2); - assertRootCa(x1, alias1); - assertRootCa(x2, alias2); - assertAliases(alias1, alias2); - } - - - public void testOneSystemOneUserOneDeleted() throws Exception { - install(getCa1(), getAliasSystemCa1()); - store.installCertificate(getCa2()); - store.deleteCertificateEntry(getAliasSystemCa1()); - assertDeleted(getCa1(), getAliasSystemCa1()); - assertRootCa(getCa2(), getAliasUserCa2()); - assertAliases(getAliasUserCa2()); - } - - public void testOneSystemOneUserOneDeletedSameSubject() throws Exception { - install(getCa1(), getAliasSystemCa1()); - store.installCertificate(getCa3WithCa1Subject()); - store.deleteCertificateEntry(getAliasSystemCa1()); - assertDeleted(getCa1(), getAliasSystemCa1()); - assertRootCa(getCa3WithCa1Subject(), getAliasUserCa3()); - assertAliases(getAliasUserCa3()); - } - - public void testUserMaskingSystem() throws Exception { - install(getCa1(), getAliasSystemCa1()); - install(getCa1(), getAliasUserCa1()); - assertMasked(getCa1(), getAliasSystemCa1()); - assertRootCa(getCa1(), getAliasUserCa1()); - assertAliases(getAliasSystemCa1(), getAliasUserCa1()); - } - - public void testChain() throws Exception { - testChain(getAliasSystemChain1(), getAliasSystemChain2()); - testChain(getAliasSystemChain1(), getAliasUserChain2()); - testChain(getAliasUserChain1(), getAliasSystemCa1()); - testChain(getAliasUserChain1(), getAliasUserChain2()); - } - - private void testChain(String alias1, String alias2) throws Exception { - install(getChain()[1], alias1); - install(getChain()[2], alias2); - assertIntermediateCa(getChain()[1], alias1); - assertRootCa(getChain()[2], alias2); - assertAliases(alias1, alias2); - assertEquals(getChain()[2], store.findIssuer(getChain()[1])); - assertEquals(getChain()[1], store.findIssuer(getChain()[0])); - - X509Certificate[] expected = getChain(); - List<X509Certificate> actualList = store.getCertificateChain(expected[0]); - - assertEquals("Generated CA list should be same length", expected.length, actualList.size()); - for (int i = 0; i < expected.length; i++) { - assertEquals("Chain value should be the same for position " + i, expected[i], - actualList.get(i)); - } - resetStore(); - } - - public void testMissingSystemDirectory() throws Exception { - cleanStore(); - createStore(); - assertEmpty(); - } - - public void testWithExistingUserDirectories() throws Exception { - DIR_ADDED.mkdirs(); - DIR_DELETED.mkdirs(); - install(getCa1(), getAliasSystemCa1()); - assertRootCa(getCa1(), getAliasSystemCa1()); - assertAliases(getAliasSystemCa1()); - } - - public void testIsTrustAnchorWithReissuedgetCa() throws Exception { - PublicKey publicKey = getPrivate().getCertificate().getPublicKey(); - PrivateKey privateKey = getPrivate().getPrivateKey(); - String name = "CN=CA4"; - X509Certificate ca1 = TestKeyStore.createCa(publicKey, privateKey, name); - Thread.sleep(1 * 1000); // wait to ensure CAs vary by expiration - X509Certificate ca2 = TestKeyStore.createCa(publicKey, privateKey, name); - assertFalse(ca1.equals(ca2)); - - String systemAlias = alias(false, ca1, 0); - install(ca1, systemAlias); - assertRootCa(ca1, systemAlias); - assertTrue(store.isTrustAnchor(ca2)); - assertEquals(ca1, store.findIssuer(ca2)); - resetStore(); - - String userAlias = alias(true, ca1, 0); - store.installCertificate(ca1); - assertRootCa(ca1, userAlias); - assertTrue(store.isTrustAnchor(ca2)); - assertEquals(ca1, store.findIssuer(ca2)); - resetStore(); - } - - public void testInstallEmpty() throws Exception { - store.installCertificate(getCa1()); - assertRootCa(getCa1(), getAliasUserCa1()); - assertAliases(getAliasUserCa1()); - - // reinstalling should not change anything - store.installCertificate(getCa1()); - assertRootCa(getCa1(), getAliasUserCa1()); - assertAliases(getAliasUserCa1()); - } - - public void testInstallEmptySystemExists() throws Exception { - install(getCa1(), getAliasSystemCa1()); - assertRootCa(getCa1(), getAliasSystemCa1()); - assertAliases(getAliasSystemCa1()); - - // reinstalling should not affect system CA - store.installCertificate(getCa1()); - assertRootCa(getCa1(), getAliasSystemCa1()); - assertAliases(getAliasSystemCa1()); - - } - - public void testInstallEmptyDeletedSystemExists() throws Exception { - install(getCa1(), getAliasSystemCa1()); - store.deleteCertificateEntry(getAliasSystemCa1()); - assertEmpty(); - assertDeleted(getCa1(), getAliasSystemCa1()); - - // installing should restore deleted system CA - store.installCertificate(getCa1()); - assertRootCa(getCa1(), getAliasSystemCa1()); - assertAliases(getAliasSystemCa1()); - } - - public void testDeleteEmpty() throws Exception { - store.deleteCertificateEntry(getAliasSystemCa1()); - assertEmpty(); - assertDeleted(getCa1(), getAliasSystemCa1()); - } - - public void testDeleteUser() throws Exception { - store.installCertificate(getCa1()); - assertRootCa(getCa1(), getAliasUserCa1()); - assertAliases(getAliasUserCa1()); - - store.deleteCertificateEntry(getAliasUserCa1()); - assertEmpty(); - assertDeleted(getCa1(), getAliasUserCa1()); - assertNoTombstone(getAliasUserCa1()); - } - - public void testDeleteSystem() throws Exception { - install(getCa1(), getAliasSystemCa1()); - assertRootCa(getCa1(), getAliasSystemCa1()); - assertAliases(getAliasSystemCa1()); - - store.deleteCertificateEntry(getAliasSystemCa1()); - assertEmpty(); - assertDeleted(getCa1(), getAliasSystemCa1()); - - // deleting again should not change anything - store.deleteCertificateEntry(getAliasSystemCa1()); - assertEmpty(); - assertDeleted(getCa1(), getAliasSystemCa1()); - } - - public void testIsUserAddedCertificate() throws Exception { - assertFalse(store.isUserAddedCertificate(getCa1())); - assertFalse(store.isUserAddedCertificate(getCa2())); - install(getCa1(), getAliasSystemCa1()); - assertFalse(store.isUserAddedCertificate(getCa1())); - assertFalse(store.isUserAddedCertificate(getCa2())); - install(getCa1(), getAliasUserCa1()); - assertTrue(store.isUserAddedCertificate(getCa1())); - assertFalse(store.isUserAddedCertificate(getCa2())); - install(getCa2(), getAliasUserCa2()); - assertTrue(store.isUserAddedCertificate(getCa1())); - assertTrue(store.isUserAddedCertificate(getCa2())); - store.deleteCertificateEntry(getAliasUserCa1()); - assertFalse(store.isUserAddedCertificate(getCa1())); - assertTrue(store.isUserAddedCertificate(getCa2())); - store.deleteCertificateEntry(getAliasUserCa2()); - assertFalse(store.isUserAddedCertificate(getCa1())); - assertFalse(store.isUserAddedCertificate(getCa2())); - } - - private void assertRootCa(X509Certificate x, String alias) { - assertIntermediateCa(x, alias); - assertEquals(x, store.findIssuer(x)); - } - - private void assertTrusted(X509Certificate x, String alias) { - assertEquals(x, store.getCertificate(alias)); - assertEquals(file(alias).lastModified(), store.getCreationDate(alias).getTime()); - assertTrue(store.containsAlias(alias)); - assertTrue(store.isTrustAnchor(x)); - } - - private void assertIntermediateCa(X509Certificate x, String alias) { - assertTrusted(x, alias); - assertEquals(alias, store.getCertificateAlias(x)); - } - - private void assertMasked(X509Certificate x, String alias) { - assertTrusted(x, alias); - assertFalse(alias.equals(store.getCertificateAlias(x))); - } - - private void assertDeleted(X509Certificate x, String alias) { - assertNull(store.getCertificate(alias)); - assertFalse(store.containsAlias(alias)); - assertNull(store.getCertificateAlias(x)); - assertFalse(store.isTrustAnchor(x)); - assertEquals(store.allSystemAliases().contains(alias), - store.getCertificate(alias, true) != null); - } - - private void assertTombstone(String alias) { - assertTrue(TrustedCertificateStore.isUser(alias)); - File file = file(alias); - assertTrue(file.exists()); - assertEquals(0, file.length()); - } - - private void assertNoTombstone(String alias) { - assertTrue(TrustedCertificateStore.isUser(alias)); - assertFalse(file(alias).exists()); - } - - private void assertAliases(String... aliases) { - Set<String> expected = new HashSet<String>(Arrays.asList(aliases)); - Set<String> actual = new HashSet<String>(); - for (String alias : store.aliases()) { - boolean system = TrustedCertificateStore.isSystem(alias); - boolean user = TrustedCertificateStore.isUser(alias); - if (system || user) { - assertEquals(system, store.allSystemAliases().contains(alias)); - assertEquals(user, store.userAliases().contains(alias)); - actual.add(alias); - } else { - throw new AssertionError(alias); - } - } - assertEquals(expected, actual); - } - - /** - * format a certificate alias - */ - private static String alias(boolean user, X509Certificate x, int index) { - String prefix = user ? "user:" : "system:"; - - X500Principal subject = x.getSubjectX500Principal(); - int intHash = NativeCrypto.X509_NAME_hash_old(subject); - String strHash = IntegralToString.intToHexString(intHash, false, 8); - - return prefix + strHash + '.' + index; - } - - /** - * Install certificate under specified alias - */ - private static void install(X509Certificate x, String alias) { - try { - File file = file(alias); - file.getParentFile().mkdirs(); - OutputStream out = new FileOutputStream(file); - out.write(x.getEncoded()); - out.close(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Compute file for an alias - */ - private static File file(String alias) { - File dir; - if (TrustedCertificateStore.isSystem(alias)) { - dir = DIR_SYSTEM; - } else if (TrustedCertificateStore.isUser(alias)) { - dir = DIR_ADDED; - } else { - throw new IllegalArgumentException(alias); - } - - int index = alias.lastIndexOf(":"); - if (index == -1) { - throw new IllegalArgumentException(alias); - } - String filename = alias.substring(index+1); - - return new File(dir, filename); - } -} |