Clover Coverage Report - Subsonic-Android Coverage Report
Coverage timestamp: ven dic 19 2014 17:57:13 EST
../../../../../../img/srcFileCovDistChart3.png 80% of files have more coverage
87   497   46   3,78
36   280   0,53   23
23     2  
1    
This report was generated with an evaluation server license. Purchase Clover or configure your license.
 
  SSLSocketFactory       Line # 142 87 46 24,7% 0.24657534
 
No Tests
 
1    /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements. See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership. The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License. You may obtain a copy of the License at
10    *
11    * http://www.apache.org/licenses/LICENSE-2.0
12    *
13    * Unless required by applicable law or agreed to in writing,
14    * software distributed under the License is distributed on an
15    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16    * KIND, either express or implied. See the License for the
17    * specific language governing permissions and limitations
18    * under the License.
19    * ====================================================================
20    *
21    * This software consists of voluntary contributions made by many
22    * individuals on behalf of the Apache Software Foundation. For more
23    * information on the Apache Software Foundation, please see
24    * <http://www.apache.org/>.
25    *
26    */
27   
28    package net.sourceforge.subsonic.androidapp.service.ssl;
29   
30    import org.apache.http.conn.ConnectTimeoutException;
31    import org.apache.http.conn.scheme.HostNameResolver;
32    import org.apache.http.conn.scheme.LayeredSocketFactory;
33    import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
34    import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
35    import org.apache.http.conn.ssl.StrictHostnameVerifier;
36    import org.apache.http.conn.ssl.X509HostnameVerifier;
37    import org.apache.http.params.HttpConnectionParams;
38    import org.apache.http.params.HttpParams;
39   
40    import javax.net.ssl.HttpsURLConnection;
41    import javax.net.ssl.KeyManager;
42    import javax.net.ssl.KeyManagerFactory;
43    import javax.net.ssl.SSLContext;
44    import javax.net.ssl.SSLSocket;
45    import javax.net.ssl.TrustManager;
46    import javax.net.ssl.TrustManagerFactory;
47    import javax.net.ssl.X509TrustManager;
48   
49    import java.io.IOException;
50    import java.net.InetAddress;
51    import java.net.InetSocketAddress;
52    import java.net.Socket;
53    import java.net.SocketTimeoutException;
54    import java.net.UnknownHostException;
55    import java.security.KeyManagementException;
56    import java.security.KeyStore;
57    import java.security.KeyStoreException;
58    import java.security.NoSuchAlgorithmException;
59    import java.security.SecureRandom;
60    import java.security.UnrecoverableKeyException;
61   
62    /**
63    * Layered socket factory for TLS/SSL connections.
64    * <p>
65    * SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of
66    * trusted certificates and to authenticate to the HTTPS server using a private key.
67    * <p>
68    * SSLSocketFactory will enable server authentication when supplied with
69    * a {@link KeyStore trust-store} file containing one or several trusted certificates. The client
70    * secure socket will reject the connection during the SSL session handshake if the target HTTPS
71    * server attempts to authenticate itself with a non-trusted certificate.
72    * <p>
73    * Use JDK keytool utility to import a trusted certificate and generate a trust-store file:
74    * <pre>
75    * keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
76    * </pre>
77    * <p>
78    * In special cases the standard trust verification process can be bypassed by using a custom
79    * {@link TrustStrategy}. This interface is primarily intended for allowing self-signed
80    * certificates to be accepted as trusted without having to add them to the trust-store file.
81    * <p>
82    * The following parameters can be used to customize the behavior of this
83    * class:
84    * <ul>
85    * <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
86    * <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
87    * </ul>
88    * <p>
89    * SSLSocketFactory will enable client authentication when supplied with
90    * a {@link KeyStore key-store} file containing a private key/public certificate
91    * pair. The client secure socket will use the private key to authenticate
92    * itself to the target HTTPS server during the SSL session handshake if
93    * requested to do so by the server.
94    * The target HTTPS server will in its turn verify the certificate presented
95    * by the client in order to establish client's authenticity
96    * <p>
97    * Use the following sequence of actions to generate a key-store file
98    * </p>
99    * <ul>
100    * <li>
101    * <p>
102    * Use JDK keytool utility to generate a new key
103    * <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre>
104    * For simplicity use the same password for the key as that of the key-store
105    * </p>
106    * </li>
107    * <li>
108    * <p>
109    * Issue a certificate signing request (CSR)
110    * <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre>
111    * </p>
112    * </li>
113    * <li>
114    * <p>
115    * Send the certificate request to the trusted Certificate Authority for signature.
116    * One may choose to act as her own CA and sign the certificate request using a PKI
117    * tool, such as OpenSSL.
118    * </p>
119    * </li>
120    * <li>
121    * <p>
122    * Import the trusted CA root certificate
123    * <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre>
124    * </p>
125    * </li>
126    * <li>
127    * <p>
128    * Import the PKCS#7 file containg the complete certificate chain
129    * <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre>
130    * </p>
131    * </li>
132    * <li>
133    * <p>
134    * Verify the content the resultant keystore file
135    * <pre>keytool -list -v -keystore my.keystore</pre>
136    * </p>
137    * </li>
138    * </ul>
139    *
140    * @since 4.0
141    */
 
142    public class SSLSocketFactory implements LayeredSocketFactory {
143   
144    public static final String TLS = "TLS";
145    public static final String SSL = "SSL";
146    public static final String SSLV2 = "SSLv2";
147   
148    public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER
149    = new AllowAllHostnameVerifier();
150   
151    public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
152    = new BrowserCompatHostnameVerifier();
153   
154    public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER
155    = new StrictHostnameVerifier();
156   
157    /**
158    * The default factory using the default JVM settings for secure connections.
159    */
160    private static final SSLSocketFactory DEFAULT_FACTORY = new SSLSocketFactory();
161   
162    /**
163    * Gets the default factory, which uses the default JVM settings for secure
164    * connections.
165    *
166    * @return the default factory
167    */
 
168  0 toggle public static SSLSocketFactory getSocketFactory() {
169  0 return DEFAULT_FACTORY;
170    }
171   
172    private final javax.net.ssl.SSLSocketFactory socketfactory;
173    private final HostNameResolver nameResolver;
174    // TODO: make final
175    private volatile X509HostnameVerifier hostnameVerifier;
176   
 
177  2 toggle private static SSLContext createSSLContext(
178    String algorithm,
179    final KeyStore keystore,
180    final String keystorePassword,
181    final KeyStore truststore,
182    final SecureRandom random,
183    final TrustStrategy trustStrategy)
184    throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
185  2 if (algorithm == null) {
186  0 algorithm = TLS;
187    }
188  2 KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
189    KeyManagerFactory.getDefaultAlgorithm());
190  2 kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray(): null);
191  2 KeyManager[] keymanagers = kmfactory.getKeyManagers();
192  2 TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
193    TrustManagerFactory.getDefaultAlgorithm());
194  2 tmfactory.init(keystore);
195  2 TrustManager[] trustmanagers = tmfactory.getTrustManagers();
196  2 if (trustmanagers != null && trustStrategy != null) {
197  4 for (int i = 0; i < trustmanagers.length; i++) {
198  2 TrustManager tm = trustmanagers[i];
199  2 if (tm instanceof X509TrustManager) {
200  2 trustmanagers[i] = new TrustManagerDecorator(
201    (X509TrustManager) tm, trustStrategy);
202    }
203    }
204    }
205   
206  2 SSLContext sslcontext = SSLContext.getInstance(algorithm);
207  2 sslcontext.init(keymanagers, trustmanagers, random);
208  2 return sslcontext;
209    }
210   
211    /**
212    * @deprecated Use {@link #SSLSocketFactory(String, KeyStore, String, KeyStore, SecureRandom, X509HostnameVerifier)}
213    */
 
214  0 toggle @Deprecated
215    public SSLSocketFactory(
216    final String algorithm,
217    final KeyStore keystore,
218    final String keystorePassword,
219    final KeyStore truststore,
220    final SecureRandom random,
221    final HostNameResolver nameResolver)
222    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
223  0 this(createSSLContext(
224    algorithm, keystore, keystorePassword, truststore, random, null),
225    nameResolver);
226    }
227   
228    /**
229    * @since 4.1
230    */
 
231  0 toggle public SSLSocketFactory(
232    String algorithm,
233    final KeyStore keystore,
234    final String keystorePassword,
235    final KeyStore truststore,
236    final SecureRandom random,
237    final X509HostnameVerifier hostnameVerifier)
238    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
239  0 this(createSSLContext(
240    algorithm, keystore, keystorePassword, truststore, random, null),
241    hostnameVerifier);
242    }
243   
244    /**
245    * @since 4.1
246    */
 
247  2 toggle public SSLSocketFactory(
248    String algorithm,
249    final KeyStore keystore,
250    final String keystorePassword,
251    final KeyStore truststore,
252    final SecureRandom random,
253    final TrustStrategy trustStrategy,
254    final X509HostnameVerifier hostnameVerifier)
255    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
256  2 this(createSSLContext(
257    algorithm, keystore, keystorePassword, truststore, random, trustStrategy),
258    hostnameVerifier);
259    }
260   
 
261  0 toggle public SSLSocketFactory(
262    final KeyStore keystore,
263    final String keystorePassword,
264    final KeyStore truststore)
265    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
266  0 this(TLS, keystore, keystorePassword, truststore, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
267    }
268   
 
269  0 toggle public SSLSocketFactory(
270    final KeyStore keystore,
271    final String keystorePassword)
272    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException{
273  0 this(TLS, keystore, keystorePassword, null, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
274    }
275   
 
276  0 toggle public SSLSocketFactory(
277    final KeyStore truststore)
278    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
279  0 this(TLS, null, null, truststore, null, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
280    }
281   
282    /**
283    * @since 4.1
284    */
 
285  2 toggle public SSLSocketFactory(
286    final TrustStrategy trustStrategy,
287    final X509HostnameVerifier hostnameVerifier)
288    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
289  2 this(TLS, null, null, null, null, trustStrategy, hostnameVerifier);
290    }
291   
292    /**
293    * @since 4.1
294    */
 
295  0 toggle public SSLSocketFactory(
296    final TrustStrategy trustStrategy)
297    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
298  0 this(TLS, null, null, null, null, trustStrategy, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
299    }
300   
 
301  0 toggle public SSLSocketFactory(final SSLContext sslContext) {
302  0 this(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
303    }
304   
305    /**
306    * @deprecated Use {@link #SSLSocketFactory(SSLContext)}
307    */
 
308  0 toggle @Deprecated
309    public SSLSocketFactory(
310    final SSLContext sslContext, final HostNameResolver nameResolver) {
311  0 super();
312  0 this.socketfactory = sslContext.getSocketFactory();
313  0 this.hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
314  0 this.nameResolver = nameResolver;
315    }
316   
317    /**
318    * @since 4.1
319    */
 
320  2 toggle public SSLSocketFactory(
321    final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) {
322  2 super();
323  2 this.socketfactory = sslContext.getSocketFactory();
324  2 this.hostnameVerifier = hostnameVerifier;
325  2 this.nameResolver = null;
326    }
327   
 
328  1 toggle private SSLSocketFactory() {
329  1 super();
330  1 this.socketfactory = HttpsURLConnection.getDefaultSSLSocketFactory();
331  1 this.hostnameVerifier = null;
332  1 this.nameResolver = null;
333    }
334   
335    /**
336    * @param params Optional parameters. Parameters passed to this method will have no effect.
337    * This method will create a unconnected instance of {@link Socket} class
338    * using {@link javax.net.ssl.SSLSocketFactory#createSocket()} method.
339    * @since 4.1
340    */
 
341  0 toggle @SuppressWarnings("cast")
342    public Socket createSocket(final HttpParams params) throws IOException {
343    // the cast makes sure that the factory is working as expected
344  0 return (SSLSocket) this.socketfactory.createSocket();
345    }
346   
 
347  0 toggle @SuppressWarnings("cast")
348    public Socket createSocket() throws IOException {
349    // the cast makes sure that the factory is working as expected
350  0 return (SSLSocket) this.socketfactory.createSocket();
351    }
352   
353    /**
354    * @since 4.1
355    */
 
356  0 toggle public Socket connectSocket(
357    final Socket sock,
358    final InetSocketAddress remoteAddress,
359    final InetSocketAddress localAddress,
360    final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
361  0 if (remoteAddress == null) {
362  0 throw new IllegalArgumentException("Remote address may not be null");
363    }
364  0 if (params == null) {
365  0 throw new IllegalArgumentException("HTTP parameters may not be null");
366    }
367  0 SSLSocket sslsock = (SSLSocket) (sock != null ? sock : createSocket());
368  0 if (localAddress != null) {
369    // sslsock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
370  0 sslsock.bind(localAddress);
371    }
372   
373  0 int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
374  0 int soTimeout = HttpConnectionParams.getSoTimeout(params);
375   
376  0 try {
377  0 sslsock.connect(remoteAddress, connTimeout);
378    } catch (SocketTimeoutException ex) {
379  0 throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
380    + remoteAddress.getAddress() + " timed out");
381    }
382  0 sslsock.setSoTimeout(soTimeout);
383  0 if (this.hostnameVerifier != null) {
384  0 try {
385  0 this.hostnameVerifier.verify(remoteAddress.getHostName(), sslsock);
386    // verifyHostName() didn't blowup - good!
387    } catch (IOException iox) {
388    // close the socket before re-throwing the exception
389  0 try { sslsock.close(); } catch (Exception x) { /*ignore*/ }
390  0 throw iox;
391    }
392    }
393  0 return sslsock;
394    }
395   
396   
397    /**
398    * Checks whether a socket connection is secure.
399    * This factory creates TLS/SSL socket connections
400    * which, by default, are considered secure.
401    * <br/>
402    * Derived classes may override this method to perform
403    * runtime checks, for example based on the cypher suite.
404    *
405    * @param sock the connected socket
406    *
407    * @return <code>true</code>
408    *
409    * @throws IllegalArgumentException if the argument is invalid
410    */
 
411  0 toggle public boolean isSecure(final Socket sock) throws IllegalArgumentException {
412  0 if (sock == null) {
413  0 throw new IllegalArgumentException("Socket may not be null");
414    }
415    // This instanceof check is in line with createSocket() above.
416  0 if (!(sock instanceof SSLSocket)) {
417  0 throw new IllegalArgumentException("Socket not created by this factory");
418    }
419    // This check is performed last since it calls the argument object.
420  0 if (sock.isClosed()) {
421  0 throw new IllegalArgumentException("Socket is closed");
422    }
423  0 return true;
424    }
425   
426    /**
427    * @since 4.1
428    */
 
429  0 toggle public Socket createLayeredSocket(
430    final Socket socket,
431    final String host,
432    final int port,
433    final boolean autoClose) throws IOException, UnknownHostException {
434  0 SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(
435    socket,
436    host,
437    port,
438    autoClose
439    );
440  0 if (this.hostnameVerifier != null) {
441  0 this.hostnameVerifier.verify(host, sslSocket);
442    }
443    // verifyHostName() didn't blowup - good!
444  0 return sslSocket;
445    }
446   
 
447  0 toggle @Deprecated
448    public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) {
449  0 if ( hostnameVerifier == null ) {
450  0 throw new IllegalArgumentException("Hostname verifier may not be null");
451    }
452  0 this.hostnameVerifier = hostnameVerifier;
453    }
454   
 
455  0 toggle public X509HostnameVerifier getHostnameVerifier() {
456  0 return this.hostnameVerifier;
457    }
458   
459    /**
460    * @deprecated Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}
461    */
 
462  0 toggle @Deprecated
463    public Socket connectSocket(
464    final Socket socket,
465    final String host, int port,
466    final InetAddress localAddress, int localPort,
467    final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
468  0 InetSocketAddress local = null;
469  0 if (localAddress != null || localPort > 0) {
470    // we need to bind explicitly
471  0 if (localPort < 0) {
472  0 localPort = 0; // indicates "any"
473    }
474  0 local = new InetSocketAddress(localAddress, localPort);
475    }
476  0 InetAddress remoteAddress;
477  0 if (this.nameResolver != null) {
478  0 remoteAddress = this.nameResolver.resolve(host);
479    } else {
480  0 remoteAddress = InetAddress.getByName(host);
481    }
482  0 InetSocketAddress remote = new InetSocketAddress(remoteAddress, port);
483  0 return connectSocket(socket, remote, local, params);
484    }
485   
486    /**
487    * @deprecated Use {@link #createLayeredSocket(Socket, String, int, boolean)}
488    */
 
489  0 toggle @Deprecated
490    public Socket createSocket(
491    final Socket socket,
492    final String host, int port,
493    boolean autoClose) throws IOException, UnknownHostException {
494  0 return createLayeredSocket(socket, host, port, autoClose);
495    }
496   
497    }