1/* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.security.net.config; 18 19import java.net.Socket; 20import java.net.URL; 21import javax.net.ssl.HttpsURLConnection; 22import javax.net.ssl.SSLContext; 23import javax.net.ssl.SSLHandshakeException; 24import javax.net.ssl.TrustManager; 25import javax.net.ssl.TrustManagerFactory; 26 27import junit.framework.Assert; 28 29public final class TestUtils extends Assert { 30 31 private TestUtils() { 32 } 33 34 public static void assertConnectionFails(SSLContext context, String host, int port) 35 throws Exception { 36 try { 37 Socket s = context.getSocketFactory().createSocket(host, port); 38 s.getInputStream(); 39 fail("Expected connection to " + host + ":" + port + " to fail."); 40 } catch (SSLHandshakeException expected) { 41 } 42 } 43 44 public static void assertConnectionSucceeds(SSLContext context, String host, int port) 45 throws Exception { 46 Socket s = context.getSocketFactory().createSocket(host, port); 47 s.getInputStream(); 48 } 49 50 public static void assertUrlConnectionFails(SSLContext context, String host, int port) 51 throws Exception { 52 URL url = new URL("https://" + host + ":" + port); 53 HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); 54 connection.setSSLSocketFactory(context.getSocketFactory()); 55 try { 56 connection.getInputStream(); 57 fail("Connection to " + host + ":" + port + " expected to fail"); 58 } catch (SSLHandshakeException expected) { 59 // ignored. 60 } 61 } 62 63 public static void assertUrlConnectionSucceeds(SSLContext context, String host, int port) 64 throws Exception { 65 URL url = new URL("https://" + host + ":" + port); 66 HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); 67 connection.setSSLSocketFactory(context.getSocketFactory()); 68 connection.getInputStream(); 69 } 70 71 public static SSLContext getSSLContext(ConfigSource source) throws Exception { 72 ApplicationConfig config = new ApplicationConfig(source); 73 TrustManagerFactory tmf = 74 TrustManagerFactory.getInstance("PKIX", new NetworkSecurityConfigProvider()); 75 tmf.init(new RootTrustManagerFactorySpi.ApplicationConfigParameters(config)); 76 SSLContext context = SSLContext.getInstance("TLS"); 77 context.init(null, tmf.getTrustManagers(), null); 78 return context; 79 } 80} 81