1 package net.trajano.commons.testing;
2
3 import static javax.net.ssl.HttpsURLConnection.getDefaultHostnameVerifier;
4 import static javax.net.ssl.HttpsURLConnection.getDefaultSSLSocketFactory;
5 import static javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier;
6 import static javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory;
7
8 import java.io.IOException;
9 import java.net.URL;
10 import java.security.GeneralSecurityException;
11 import java.util.logging.Level;
12 import java.util.logging.Logger;
13
14 import javax.net.ssl.HostnameVerifier;
15 import javax.net.ssl.SSLContext;
16 import javax.net.ssl.SSLSocketFactory;
17 import javax.net.ssl.TrustManager;
18 import javax.net.ssl.X509TrustManager;
19
20 import net.trajano.commons.testing.internal.NullHostnameVerifier;
21 import net.trajano.commons.testing.internal.NullX509TrustManager;
22
23
24
25
26
27 public final class DisableSslCertificateCheckUtil {
28
29
30
31
32 private static boolean disabled;
33
34
35
36
37 private static final Logger LOG = Logger
38 .getLogger(DisableSslCertificateCheckUtil.class.getName(),
39 "META-INF.Messages");
40
41
42
43
44
45 public static final HostnameVerifier NULL_HOSTNAME_VERIFIER = new NullHostnameVerifier();
46
47
48
49
50
51 public static final X509TrustManager NULL_TRUST_MANAGER = new NullX509TrustManager();
52
53
54
55
56 private static HostnameVerifier originalHostnameVerifier;
57
58
59
60
61 private static SSLSocketFactory originalSslSocketFactory;
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83 public static SSLContext buildUnsecureSslContext()
84 throws GeneralSecurityException {
85 final SSLContext context = SSLContext.getInstance("TLSv1");
86 final TrustManager[] trustManagerArray = { NULL_TRUST_MANAGER };
87 context.init(null, trustManagerArray, null);
88 return context;
89 }
90
91
92
93
94
95
96
97
98
99
100 public static void disableChecks() throws GeneralSecurityException {
101 if (disabled) {
102 return;
103 }
104 try {
105 new URL("https", "0", "/").getContent();
106 } catch (final IOException e) {
107
108
109 LOG.log(Level.FINEST,
110 "DisableSSLCertificateCheckUtil.disableCertificateCheck", e);
111 }
112 originalSslSocketFactory = getDefaultSSLSocketFactory();
113 originalHostnameVerifier = getDefaultHostnameVerifier();
114 final SSLContext context = buildUnsecureSslContext();
115 setDefaultSSLSocketFactory(context.getSocketFactory());
116 setDefaultHostnameVerifier(NULL_HOSTNAME_VERIFIER);
117 disabled = true;
118 }
119
120
121
122
123
124 public static void reenableChecks() {
125 if (!disabled) {
126 return;
127 }
128 setDefaultSSLSocketFactory(originalSslSocketFactory);
129 setDefaultHostnameVerifier(originalHostnameVerifier);
130 disabled = false;
131 }
132
133
134
135
136 private DisableSslCertificateCheckUtil() {
137 }
138 }