@Test public void testLocallyTrustedCertificateChain() throws Exception { mKeyStore.addCertificate(MATCHING_HOST, PORT1, mCert3); X509TrustManager trustManager = TrustManagerFactory.get(MATCHING_HOST, PORT1); trustManager.checkServerTrusted(new X509Certificate[] { mCert3, mCaCert }, "authType"); }
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException { this.origTm = tm; this.verifyServerCert = verifyServerCertificate; if (verifyServerCertificate) { try { Set<TrustAnchor> anch = new HashSet<TrustAnchor>(); for (X509Certificate cert : tm.getAcceptedIssuers()) { anch.add(new TrustAnchor(cert, null)); } this.validatorParams = new PKIXParameters(anch); this.validatorParams.setRevocationEnabled(false); this.validator = CertPathValidator.getInstance("PKIX"); this.certFactory = CertificateFactory.getInstance("X.509"); } catch (Exception e) { throw new CertificateException(e); } } }
@Override public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { CertificateException catchException = null; for (X509TrustManager tm : trustManagers) { try { tm.checkServerTrusted(certificates, authType); return; } catch (CertificateException e) { catchException = e; } } throw catchException; }
private void create(Path path) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException { TrustManager[] trustManagers; KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); installCertificates(path, keyStore); String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(defaultAlgorithm); trustManagerFactory.init(keyStore); trustManagers = trustManagerFactory.getTrustManagers(); sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, null); trustManager = (X509TrustManager) trustManagers[0]; X509Certificate[] acceptedIssuers = trustManager.getAcceptedIssuers(); for (X509Certificate acceptedIssuer : acceptedIssuers) { logger.info("installed cert details: subject={} issuer={}", acceptedIssuer.getSubjectX500Principal(), acceptedIssuer.getIssuerX500Principal()); } }
private OkHttpClient createClient() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.followSslRedirects(followRedirects); if (connectTimeout != DEFAULT_TIMEOUT) { builder.connectTimeout(connectTimeout, SECONDS); } if (readTimeout != DEFAULT_TIMEOUT) { builder.readTimeout(readTimeout, SECONDS); } if (allowInsecure) { X509TrustManager trustManager = createInsecureTrustManager(); SSLSocketFactory sslSocketFactory = createInsecureSslSocketFactory(trustManager); builder.sslSocketFactory(sslSocketFactory, trustManager); builder.hostnameVerifier(createInsecureHostnameVerifier()); } return builder.build(); }
private X509TrustManager getX509TrustManager() { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length == 1 && (trustManagers[0] instanceof X509TrustManager)) { return (X509TrustManager) trustManagers[0]; } else { LOG.error(String.format("Error while retrieving X509 trust manager! " + "(TrustMangers: %s)", Arrays.toString(trustManagers))); return null; } } catch (NoSuchAlgorithmException | KeyStoreException e) { LOG.error("Error while retrieving X509 trust manager!", e); return null; } }
@Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { for (final X509TrustManager trustManager : trustManagers) { try { trustManager.checkClientTrusted(chain, authType); return; } catch (final CertificateException e) { LOGGER.debug(e.getMessage(), e); } } throw new CertificateException("None of the TrustManagers trust this certificate chain"); }
public KeyStoresTrustManager(KeyStore... keyStores) throws NoSuchAlgorithmException, KeyStoreException { super(); for (KeyStore keystore : keyStores) { TrustManagerFactory factory = TrustManagerFactory.getInstance("JKS"); factory.init(keystore); TrustManager[] tms = factory.getTrustManagers(); if (tms.length == 0) { throw new NoSuchAlgorithmException("Unable to load keystore"); } trustManagers.add((X509TrustManager) tms[0]); } //Build accepted issuers list Set<X509Certificate> issuers = new HashSet<X509Certificate>(); for (X509TrustManager tm : trustManagers) { for (X509Certificate issuer : tm.getAcceptedIssuers()) { issuers.add(issuer); } } acceptedIssuers = issuers.toArray(new X509Certificate[issuers.size()]); }
private OkHttpClient getDefaultOkHttpClient(boolean isSecured, boolean followRedirects, boolean followProtocolRedirects, String[] publicKeys, Collection<Interceptor> interceptors, LogLevel logLevel) { ClientSSLSocketFactory.setIsSecured(isSecured); ClientSSLSocketFactory.setPublicKeys(publicKeys); SSLSocketFactory sslSocketFactory = ClientSSLSocketFactory.getSocketFactory(); X509TrustManager trustManager = ClientSSLSocketFactory.get509TrustManager(); OkHttpClient.Builder builder = new OkHttpClient.Builder() .sslSocketFactory(sslSocketFactory, trustManager); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(logLevel); builder.addInterceptor(loggingInterceptor); for (Interceptor interceptor : interceptors) { builder.addInterceptor(interceptor); } builder.followRedirects(followRedirects); builder.followSslRedirects(followProtocolRedirects); return builder.build(); }
@Test public void testValidateResponse() throws Exception { context = Mockito.mock(Activity.class); PowerMockito.mockStatic(LiClientManager.class); LiClientManager liClientManager = PowerMockito.mock(LiClientManager.class); PowerMockito.mockStatic(SSLContext.class); SSLContext sslContext = PowerMockito.mock(SSLContext.class); when(sslContext.getInstance("SSL")).thenReturn(sslContext); Mockito.doNothing().when(sslContext).init(isA(KeyManager[].class), isA(TrustManager[].class), isA(SecureRandom.class)); SSLSocketFactory socketFactory = mock(SSLSocketFactory.class); when(sslContext.getSocketFactory()).thenReturn(socketFactory); PowerMockito.mockStatic(Platform.class); Platform platform = PowerMockito.mock(Platform.class); X509TrustManager trustManager = mock(X509TrustManager.class); when(platform.trustManager(socketFactory)).thenReturn(trustManager); BDDMockito.given(Platform.get()).willReturn(platform); BDDMockito.given(SSLContext.getInstance("SSL")).willReturn(sslContext); LiRestv2Client liRestv2Client = LiRestv2Client.getInstance(); final LiBaseResponse liBaseResponse = mock(LiBaseResponse.class); when(liBaseResponse.getHttpCode()).thenReturn(200); LiRestv2Client liRestv2ClientSpy = spy(LiRestv2Client.class); doReturn(liBaseResponse).when(liRestv2ClientSpy).processSync(isA(LiBaseRestRequest.class)); LiRestV2Request liBaseRestRequest = new LiRestV2Request(context, liql, "message"); liBaseRestRequest.addQueryParam("test"); LiBaseResponse liBaseResponse1 = liRestv2ClientSpy.processSync(liBaseRestRequest); Assert.assertEquals(200, liBaseResponse1.getHttpCode()); PowerMockito.verifyStatic(); }
/** * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose * certificates have not been signed by these certificates will fail with a {@code * SSLHandshakeException}. * * <p>This can be used to replace the host platform's built-in trusted certificates with a custom * set. This is useful in development where certificate authority-trusted certificates aren't * available. Or in production, to avoid reliance on third-party certificate authorities. * * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using * the host platform's built-in trust store. * * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3> * * <p>Relying on your own trusted certificates limits your server team's ability to update their * TLS certificates. By installing a specific set of trusted certificates, you take on additional * operational complexity and limit your ability to migrate between certificate authorities. Do * not use custom trusted certificates in production without the blessing of your server's TLS * administrator. */ private X509TrustManager trustManagerForCertificates(InputStream in) throws GeneralSecurityException { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in); if (certificates.isEmpty()) { throw new IllegalArgumentException("expected non-empty set of trusted certificates"); } // Put the certificates a key store. char[] password = "password".toCharArray(); // Any password will work. KeyStore keyStore = newEmptyKeyStore(password); int index = 0; for (Certificate certificate : certificates) { String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, certificate); } // Use it to build an X509 trust manager. KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } return (X509TrustManager) trustManagers[0]; }
@Test public void testLocallyTrustedCertificateChainNotMatchingHost() throws Exception { mKeyStore.addCertificate(NOT_MATCHING_HOST, PORT1, mCert3); X509TrustManager trustManager = TrustManagerFactory.get(NOT_MATCHING_HOST, PORT1); trustManager.checkServerTrusted(new X509Certificate[] { mCert3, mCaCert }, "authType"); }
/** * Constructor for EasyX509TrustManager. */ public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { super(); TrustManagerFactory factory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(keystore); TrustManager[] trustmanagers = factory.getTrustManagers(); if (trustmanagers.length == 0) { throw new NoSuchAlgorithmException("no trust manager found"); } this.standardTrustManager = (X509TrustManager) trustmanagers[0]; }
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) { for (TrustManager trustManager : trustManagers) { if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } } return null; }
private void assertCertificateRejection(X509TrustManager trustManager, X509Certificate[] certificates) { boolean certificateValid; try { trustManager.checkServerTrusted(certificates, "authType"); certificateValid = true; } catch (CertificateException e) { certificateValid = false; } assertFalse("The certificate should have been rejected but wasn't", certificateValid); }
/** * Android version Nougat has a regression where elliptic curve cipher suites are supported, but * only the curve secp256r1 is allowed. So, first it's best to just disable all elliptic * ciphers, try the connection, and fall back to the all cipher suites enabled list after. */ private static void addNougatFixConnectionSpec(List<ConnectionSpec> specList) { if (Build.VERSION.SDK_INT != Build.VERSION_CODES.N) { return; } SSLSocketFactory socketFactory; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } X509TrustManager trustManager = (X509TrustManager) trustManagers[0]; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, null); socketFactory = sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException|KeyStoreException|KeyManagementException e) { Log.e(TAG, "Failed obtaining the SSL socket factory."); return; } String[] cipherSuites = socketFactory.getDefaultCipherSuites(); ArrayList<String> allowedList = new ArrayList<>(); for (String suite : cipherSuites) { if (!suite.contains("ECDH")) { allowedList.add(suite); } } ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .cipherSuites(allowedList.toArray(new String[0])) .supportsTlsExtensions(true) .build(); specList.add(spec); }
public SSLSocketFactoryCompat(@NonNull X509TrustManager trustManager) { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new X509TrustManager[] {trustManager}, null); delegate = sslContext.getSocketFactory(); } catch (GeneralSecurityException e) { throw new AssertionError(); // The system has no TLS. Just give up. } }
@Override public X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) { // Not supported due to access checks on JDK 9+: // java.lang.reflect.InaccessibleObjectException: Unable to make member of class // sun.security.ssl.SSLSocketFactoryImpl accessible: module java.base does not export // sun.security.ssl to unnamed module @xxx throw new UnsupportedOperationException( "clientBuilder.sslSocketFactory(SSLSocketFactory) not supported on JDK 9+"); }
public static void main(String[] args) throws Exception { if (initSecmod() == false) { return; } if ("sparc".equals(System.getProperty("os.arch")) == false) { // we have not updated other platforms with the proper NSS libraries yet System.out.println("Test currently works only on solaris-sparc, skipping"); return; } String configName = BASE + SEP + "fips.cfg"; Provider p = getSunPKCS11(configName); System.out.println(p); Security.addProvider(p); Security.removeProvider("SunJSSE"); Provider jsse = new com.sun.net.ssl.internal.ssl.Provider(p); Security.addProvider(jsse); System.out.println(jsse.getInfo()); KeyStore ks = KeyStore.getInstance("PKCS11", p); ks.load(null, "test12".toCharArray()); X509Certificate server = loadCertificate("certs/server.cer"); X509Certificate ca = loadCertificate("certs/ca.cer"); X509Certificate anchor = loadCertificate("certs/anchor.cer"); if (args.length > 1 && "sm".equals(args[0])) { Policy.setPolicy(Policy.getInstance("JavaPolicy", new URIParameter(new File(BASE, args[1]).toURI()))); System.setSecurityManager(new SecurityManager()); } KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(null, null); trustStore.setCertificateEntry("anchor", anchor); TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); tmf.init(trustStore); X509TrustManager tm = (X509TrustManager)tmf.getTrustManagers()[0]; X509Certificate[] chain = {server, ca, anchor}; tm.checkServerTrusted(chain, "RSA"); System.out.println("OK"); }
private X509TrustManager chooseTrustManager(TrustManager[] trustManagers) { for (TrustManager trustManager : trustManagers) { if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } } return null; }
@Test public void equalsFromTrustManager() throws Exception { SslClient client = new SslClient.Builder().build(); X509TrustManager x509TrustManager = client.trustManager; assertEquals( CertificateChainCleaner.get(x509TrustManager), CertificateChainCleaner.get(x509TrustManager)); }
public CustomCipherSuites() throws GeneralSecurityException { // Configure cipher suites to demonstrate how to customize which cipher suites will be used for // an OkHttp request. In order to be selected a cipher suite must be included in both OkHttp's // connection spec and in the SSLSocket's enabled cipher suites array. Most applications should // not customize the cipher suites list. List<CipherSuite> customCipherSuites = Arrays.asList( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384); final ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .cipherSuites(customCipherSuites.toArray(new CipherSuite[0])) .build(); X509TrustManager trustManager = defaultTrustManager(); SSLSocketFactory sslSocketFactory = defaultSslSocketFactory(trustManager); SSLSocketFactory customSslSocketFactory = new DelegatingSSLSocketFactory(sslSocketFactory) { @Override protected SSLSocket configureSocket(SSLSocket socket) throws IOException { socket.setEnabledCipherSuites(javaNames(spec.cipherSuites())); return socket; } }; client = new OkHttpClient.Builder() .connectionSpecs(Collections.singletonList(spec)) .sslSocketFactory(customSslSocketFactory, trustManager) .build(); }
@Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { X509TrustManager tm = trustManagerRef.get(); if (tm != null) { tm.checkClientTrusted(chain, authType); } else { throw new CertificateException("Unknown client chain certificate: " + chain[0].toString()); } }
/** Returns a trust manager that trusts the VM's default certificate authorities. */ private X509TrustManager defaultTrustManager() throws GeneralSecurityException { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } return (X509TrustManager) trustManagers[0]; }
private SSLSocketFactory systemDefaultSslSocketFactory(X509TrustManager trustManager) { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, null); return sslContext.getSocketFactory(); } catch (GeneralSecurityException e) { throw assertionError("No System TLS", e); // The system has no TLS. Just give up. } }
public CertificateChainCleaner buildCertificateChainCleaner(X509TrustManager trustManager) { try { Class<?> extensionsClass = Class.forName("android.net.http.X509TrustManagerExtensions"); Constructor<?> constructor = extensionsClass.getConstructor(X509TrustManager.class); Object extensions = constructor.newInstance(trustManager); Method checkServerTrusted = extensionsClass.getMethod( "checkServerTrusted", X509Certificate[].class, String.class, String.class); return new AndroidCertificateChainCleaner(extensions, checkServerTrusted); } catch (Exception e) { return super.buildCertificateChainCleaner(trustManager); } }
protected X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) { // Attempt to get the trust manager from an OpenJDK socket factory. We attempt this on all // platforms in order to support Robolectric, which mixes classes from both Android and the // Oracle JDK. Note that we don't support HTTP/2 or other nice features on Robolectric. try { Class<?> sslContextClass = Class.forName("sun.security.ssl.SSLContextImpl"); Object context = readFieldOrNull(sslSocketFactory, sslContextClass, "context"); if (context == null) return null; return readFieldOrNull(context, X509TrustManager.class, "trustManager"); } catch (ClassNotFoundException e) { return null; } }
public AlwaysTrustManager(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory. getDefaultAlgorithm()); tmf.init(keyStore); TrustManager tms[] = tmf.getTrustManagers(); for (TrustManager tm : tms) { trustManager = (X509TrustManager) tm; return; } }
private static X509TrustManager findX509TrustManager(TrustManagerFactory tmf) { TrustManager tms[] = tmf.getTrustManagers(); for (final TrustManager tm : tms) { if (tm instanceof X509TrustManager) { return (X509TrustManager) tm; } } return null; }
/** * Returns the VM's default SSL socket factory, using {@code trustManager} for trusted root * certificates. */ private SSLSocketFactory defaultSslSocketFactory(X509TrustManager trustManager) throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, null); return sslContext.getSocketFactory(); }
public CustomTrust() { X509TrustManager trustManager; SSLSocketFactory sslSocketFactory; try { trustManager = trustManagerForCertificates(trustedCertificatesInputStream()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, null); sslSocketFactory = sslContext.getSocketFactory(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } client = new OkHttpClient.Builder() .sslSocketFactory(sslSocketFactory, trustManager) .build(); }