-
Notifications
You must be signed in to change notification settings - Fork 923
/
SSLConnectionSocketFactory.java
361 lines (331 loc) · 14.5 KB
/
SSLConnectionSocketFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.client5.http.ssl;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory;
import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.ThreadingBehavior;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.http.ssl.TlsCiphers;
import org.apache.hc.core5.io.Closer;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.SSLInitializationException;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.Asserts;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Layered socket factory for TLS/SSL connections.
* <p>
* SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of
* trusted certificates and to authenticate to the HTTPS server using a private key.
*
* @since 4.3
*/
@Contract(threading = ThreadingBehavior.STATELESS)
public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactory {
private static final String WEAK_KEY_EXCHANGES
= "^(TLS|SSL)_(NULL|ECDH_anon|DH_anon|DH_anon_EXPORT|DHE_RSA_EXPORT|DHE_DSS_EXPORT|"
+ "DSS_EXPORT|DH_DSS_EXPORT|DH_RSA_EXPORT|RSA_EXPORT|KRB5_EXPORT)_(.*)";
private static final String WEAK_CIPHERS
= "^(TLS|SSL)_(.*)_WITH_(NULL|DES_CBC|DES40_CBC|DES_CBC_40|3DES_EDE_CBC|RC4_128|RC4_40|RC2_CBC_40)_(.*)";
private static final List<Pattern> WEAK_CIPHER_SUITE_PATTERNS = Collections.unmodifiableList(Arrays.asList(
Pattern.compile(WEAK_KEY_EXCHANGES, Pattern.CASE_INSENSITIVE),
Pattern.compile(WEAK_CIPHERS, Pattern.CASE_INSENSITIVE)));
private static final Logger LOG = LoggerFactory.getLogger(SSLConnectionSocketFactory.class);
/**
* Obtains default SSL socket factory with an SSL context based on the standard JSSE
* trust material ({@code cacerts} file in the security properties directory).
* System properties are not taken into consideration.
*
* @return default SSL socket factory
*/
public static SSLConnectionSocketFactory getSocketFactory() throws SSLInitializationException {
return new SSLConnectionSocketFactory(SSLContexts.createDefault(), HttpsSupport.getDefaultHostnameVerifier());
}
/**
* Obtains default SSL socket factory with an SSL context based on system properties
* as described in
* <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html">
* Java™ Secure Socket Extension (JSSE) Reference Guide</a>.
*
* @return default system SSL socket factory
*/
public static SSLConnectionSocketFactory getSystemSocketFactory() throws SSLInitializationException {
return new SSLConnectionSocketFactory(
(javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault(),
HttpsSupport.getSystemProtocols(),
HttpsSupport.getSystemCipherSuits(),
HttpsSupport.getDefaultHostnameVerifier());
}
static boolean isWeakCipherSuite(final String cipherSuite) {
for (final Pattern pattern : WEAK_CIPHER_SUITE_PATTERNS) {
if (pattern.matcher(cipherSuite).matches()) {
return true;
}
}
return false;
}
private final javax.net.ssl.SSLSocketFactory socketFactory;
private final HostnameVerifier hostnameVerifier;
private final String[] supportedProtocols;
private final String[] supportedCipherSuites;
private final TlsSessionValidator tlsSessionValidator;
public SSLConnectionSocketFactory(final SSLContext sslContext) {
this(sslContext, HttpsSupport.getDefaultHostnameVerifier());
}
/**
* @since 4.4
*/
public SSLConnectionSocketFactory(
final SSLContext sslContext, final HostnameVerifier hostnameVerifier) {
this(Args.notNull(sslContext, "SSL context").getSocketFactory(),
null, null, hostnameVerifier);
}
/**
* @since 4.4
*/
public SSLConnectionSocketFactory(
final SSLContext sslContext,
final String[] supportedProtocols,
final String[] supportedCipherSuites,
final HostnameVerifier hostnameVerifier) {
this(Args.notNull(sslContext, "SSL context").getSocketFactory(),
supportedProtocols, supportedCipherSuites, hostnameVerifier);
}
/**
* @since 4.4
*/
public SSLConnectionSocketFactory(
final javax.net.ssl.SSLSocketFactory socketFactory,
final HostnameVerifier hostnameVerifier) {
this(socketFactory, null, null, hostnameVerifier);
}
/**
* @since 4.4
*/
public SSLConnectionSocketFactory(
final javax.net.ssl.SSLSocketFactory socketFactory,
final String[] supportedProtocols,
final String[] supportedCipherSuites,
final HostnameVerifier hostnameVerifier) {
this.socketFactory = Args.notNull(socketFactory, "SSL socket factory");
this.supportedProtocols = supportedProtocols;
this.supportedCipherSuites = supportedCipherSuites;
this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier : HttpsSupport.getDefaultHostnameVerifier();
this.tlsSessionValidator = new TlsSessionValidator(LOG);
}
/**
* @deprecated Use {@link #prepareSocket(SSLSocket, HttpContext)}
*/
@Deprecated
protected void prepareSocket(final SSLSocket socket) throws IOException {
}
/**
* Performs any custom initialization for a newly created SSLSocket
* (before the SSL handshake happens).
*
* The default implementation is a no-op, but could be overridden to, e.g.,
* call {@link javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[])}.
* @throws IOException may be thrown if overridden
*/
@SuppressWarnings("deprecation")
protected void prepareSocket(final SSLSocket socket, final HttpContext context) throws IOException {
prepareSocket(socket);
}
@Override
public Socket createSocket(final HttpContext context) throws IOException {
return new Socket();
}
@Override
public Socket createSocket(final Proxy proxy, final HttpContext context) throws IOException {
return new Socket(proxy);
}
@Override
public Socket connectSocket(
final TimeValue connectTimeout,
final Socket socket,
final HttpHost host,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpContext context) throws IOException {
final Timeout timeout = connectTimeout != null ? Timeout.of(connectTimeout.getDuration(), connectTimeout.getTimeUnit()) : null;
return connectSocket(socket, host, remoteAddress, localAddress, timeout, timeout, context);
}
@Override
public Socket connectSocket(
final Socket socket,
final HttpHost host,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final Timeout connectTimeout,
final Object attachment,
final HttpContext context) throws IOException {
Args.notNull(host, "HTTP host");
Args.notNull(remoteAddress, "Remote address");
final Socket sock = socket != null ? socket : createSocket(context);
if (localAddress != null) {
sock.bind(localAddress);
}
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting socket to {} with timeout {}", remoteAddress, connectTimeout);
}
// Run this under a doPrivileged to support lib users that run under a SecurityManager this allows granting connect permissions
// only to this library
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
sock.connect(remoteAddress, Timeout.defaultsToDisabled(connectTimeout).toMillisecondsIntBound());
return null;
});
} catch (final PrivilegedActionException e) {
Asserts.check(e.getCause() instanceof IOException,
"method contract violation only checked exceptions are wrapped: " + e.getCause());
// only checked exceptions are wrapped - error and RTExceptions are rethrown by doPrivileged
throw (IOException) e.getCause();
}
} catch (final IOException ex) {
Closer.closeQuietly(sock);
throw ex;
}
// Setup SSL layering if necessary
if (sock instanceof SSLSocket) {
final SSLSocket sslsock = (SSLSocket) sock;
executeHandshake(sslsock, host.getHostName(), attachment, context);
return sock;
}
return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), attachment, context);
}
@Override
public Socket createLayeredSocket(
final Socket socket,
final String target,
final int port,
final HttpContext context) throws IOException {
return createLayeredSocket(socket, target, port, null, context);
}
@Override
public Socket createLayeredSocket(
final Socket socket,
final String target,
final int port,
final Object attachment,
final HttpContext context) throws IOException {
final SSLSocket sslsock = (SSLSocket) this.socketFactory.createSocket(
socket,
target,
port,
true);
executeHandshake(sslsock, target, attachment, context);
return sslsock;
}
private void executeHandshake(
final SSLSocket sslsock,
final String target,
final Object attachment,
final HttpContext context) throws IOException {
final TlsConfig tlsConfig = attachment instanceof TlsConfig ? (TlsConfig) attachment : TlsConfig.DEFAULT;
if (supportedProtocols != null) {
sslsock.setEnabledProtocols(supportedProtocols);
} else {
sslsock.setEnabledProtocols((TLS.excludeWeak(sslsock.getEnabledProtocols())));
}
if (supportedCipherSuites != null) {
sslsock.setEnabledCipherSuites(supportedCipherSuites);
} else {
sslsock.setEnabledCipherSuites(TlsCiphers.excludeWeak(sslsock.getEnabledCipherSuites()));
}
final Timeout handshakeTimeout = tlsConfig.getHandshakeTimeout();
if (handshakeTimeout != null) {
sslsock.setSoTimeout(handshakeTimeout.toMillisecondsIntBound());
}
prepareSocket(sslsock, context);
if (LOG.isDebugEnabled()) {
LOG.debug("Enabled protocols: {}", (Object) sslsock.getEnabledProtocols());
LOG.debug("Enabled cipher suites: {}", (Object) sslsock.getEnabledCipherSuites());
LOG.debug("Starting handshake ({})", handshakeTimeout);
}
sslsock.startHandshake();
verifyHostname(sslsock, target);
}
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
try {
SSLSession session = sslsock.getSession();
if (session == null) {
// In our experience this only happens under IBM 1.4.x when
// spurious (unrelated) certificates show up in the server'
// chain. Hopefully this will unearth the real problem:
final InputStream in = sslsock.getInputStream();
in.available();
// If ssl.getInputStream().available() didn't cause an
// exception, maybe at least now the session is available?
session = sslsock.getSession();
if (session == null) {
// If it's still null, probably a startHandshake() will
// unearth the real problem.
sslsock.startHandshake();
session = sslsock.getSession();
}
}
if (session == null) {
throw new SSLHandshakeException("SSL session not available");
}
verifySession(hostname, session);
} catch (final IOException iox) {
// close the socket before re-throwing the exception
Closer.closeQuietly(sslsock);
throw iox;
}
}
protected void verifySession(
final String hostname,
final SSLSession sslSession) throws SSLException {
tlsSessionValidator.verifySession(hostname, sslSession, hostnameVerifier);
}
}