1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 
28 package javax.net.ssl;
29 
30 import java.io.IOException;
31 import java.net.InetAddress;
32 import java.net.ServerSocket;
33 import java.net.SocketException;
34 import javax.net.ServerSocketFactory;
35 import java.security.*;
36 
37 /**
38  * <code>SSLServerSocketFactory</code>s create
39  * <code>SSLServerSocket</code>s.
40  *
41  * @since 1.4
42  * @see SSLSocket
43  * @see SSLServerSocket
44  * @author David Brownell
45  */
46 public abstract class SSLServerSocketFactory extends ServerSocketFactory
47 {
48     // Android-changed: Renamed field.
49     // Some apps rely on changing this field via reflection, so we can't change the name
50     // without introducing app compatibility problems.  See http://b/62248930.
51     private static SSLServerSocketFactory defaultServerSocketFactory;
52 
53     // Android-changed: Check Security.getVersion() on each update.
54     // If the set of providers or other such things changes, it may change the default
55     // factory, so we track the version returned from Security.getVersion() instead of
56     // only having a flag that says if we've ever initialized the default.
57     // private static boolean propertyChecked;
58     private static int lastVersion = -1;
59 
log(String msg)60     private static void log(String msg) {
61         if (SSLSocketFactory.DEBUG) {
62             System.out.println(msg);
63         }
64     }
65 
66     /**
67      * Constructor is used only by subclasses.
68      */
SSLServerSocketFactory()69     protected SSLServerSocketFactory() { /* NOTHING */ }
70 
71     /**
72      * Returns the default SSL server socket factory.
73      *
74      * <p>The first time this method is called, the security property
75      * "ssl.ServerSocketFactory.provider" is examined. If it is non-null, a
76      * class by that name is loaded and instantiated. If that is successful and
77      * the object is an instance of SSLServerSocketFactory, it is made the
78      * default SSL server socket factory.
79      *
80      * <p>Otherwise, this method returns
81      * <code>SSLContext.getDefault().getServerSocketFactory()</code>. If that
82      * call fails, an inoperative factory is returned.
83      *
84      * @return the default <code>ServerSocketFactory</code>
85      * @see SSLContext#getDefault
86      */
getDefault()87     public static synchronized ServerSocketFactory getDefault() {
88         // Android-changed: Check Security.getVersion() on each update.
89         if (defaultServerSocketFactory != null && lastVersion == Security.getVersion()) {
90             return defaultServerSocketFactory;
91         }
92 
93         lastVersion = Security.getVersion();
94         SSLServerSocketFactory previousDefaultServerSocketFactory = defaultServerSocketFactory;
95         defaultServerSocketFactory = null;
96 
97         String clsName = SSLSocketFactory.getSecurityProperty
98                                     ("ssl.ServerSocketFactory.provider");
99         if (clsName != null) {
100             // Android-changed: Check if we already have an instance of the default factory class.
101             // The instance for the default socket factory is checked for updates quite
102             // often (for instance, every time a security provider is added). Which leads
103             // to unnecessary overload and excessive error messages in case of class-loading
104             // errors. Avoid creating a new object if the class name is the same as before.
105             if (previousDefaultServerSocketFactory != null
106                     && clsName.equals(previousDefaultServerSocketFactory.getClass().getName())) {
107                 defaultServerSocketFactory = previousDefaultServerSocketFactory;
108                 return defaultServerSocketFactory;
109             }
110             log("setting up default SSLServerSocketFactory");
111             try {
112                 Class<?> cls = null;
113                 try {
114                     cls = Class.forName(clsName);
115                 } catch (ClassNotFoundException e) {
116                     // Android-changed; Try the contextClassLoader first.
117                     ClassLoader cl = Thread.currentThread().getContextClassLoader();
118                     if (cl == null) {
119                         cl = ClassLoader.getSystemClassLoader();
120                     }
121 
122                     if (cl != null) {
123                         // Android-changed: Use Class.forName() so the class gets initialized.
124                         cls = Class.forName(clsName, true, cl);
125                     }
126                 }
127                 log("class " + clsName + " is loaded");
128                 SSLServerSocketFactory fac = (SSLServerSocketFactory)cls.newInstance();
129                 log("instantiated an instance of class " + clsName);
130                 defaultServerSocketFactory = fac;
131                 return fac;
132             } catch (Exception e) {
133                 log("SSLServerSocketFactory instantiation failed: " + e);
134                 // Android-changed: Fallback to the default SSLContext on exception.
135             }
136         }
137 
138         try {
139             // Android-changed: Allow for {@code null} SSLContext.getDefault.
140             SSLContext context = SSLContext.getDefault();
141             if (context != null) {
142                 defaultServerSocketFactory = context.getServerSocketFactory();
143             } else {
144                 defaultServerSocketFactory = new DefaultSSLServerSocketFactory(new IllegalStateException("No factory found."));
145             }
146             return defaultServerSocketFactory;
147         } catch (NoSuchAlgorithmException e) {
148             return new DefaultSSLServerSocketFactory(e);
149         }
150     }
151 
152     /**
153      * Returns the list of cipher suites which are enabled by default.
154      * Unless a different list is enabled, handshaking on an SSL connection
155      * will use one of these cipher suites.  The minimum quality of service
156      * for these defaults requires confidentiality protection and server
157      * authentication (that is, no anonymous cipher suites).
158      *
159      * @see #getSupportedCipherSuites()
160      * @return array of the cipher suites enabled by default
161      */
getDefaultCipherSuites()162     public abstract String [] getDefaultCipherSuites();
163 
164 
165     // Android-changed: Added warnings about misuse
166     /**
167      * Returns the names of the cipher suites which could be enabled for use
168      * on an SSL connection created by this factory.
169      * Normally, only a subset of these will actually
170      * be enabled by default, since this list may include cipher suites which
171      * do not meet quality of service requirements for those defaults.  Such
172      * cipher suites are useful in specialized applications.
173      *
174      * <p class="caution">Applications should not blindly enable all supported
175      * cipher suites.  The supported cipher suites can include signaling cipher suite
176      * values that can cause connection problems if enabled inappropriately.
177      *
178      * <p>The proper way to use this method is to either check if a specific cipher
179      * suite is supported via {@code Arrays.asList(getSupportedCipherSuites()).contains(...)}
180      * or to filter a desired list of cipher suites to only the supported ones via
181      * {@code desiredSuiteSet.retainAll(Arrays.asList(getSupportedCipherSuites()))}.
182      *
183      * @return an array of cipher suite names
184      * @see #getDefaultCipherSuites()
185      */
getSupportedCipherSuites()186     public abstract String [] getSupportedCipherSuites();
187 }
188 
189 
190 //
191 // The default factory does NOTHING.
192 //
193 class DefaultSSLServerSocketFactory extends SSLServerSocketFactory {
194 
195     private final Exception reason;
196 
DefaultSSLServerSocketFactory(Exception reason)197     DefaultSSLServerSocketFactory(Exception reason) {
198         this.reason = reason;
199     }
200 
throwException()201     private ServerSocket throwException() throws SocketException {
202         throw (SocketException)
203             new SocketException(reason.toString()).initCause(reason);
204     }
205 
206     @Override
createServerSocket()207     public ServerSocket createServerSocket() throws IOException {
208         return throwException();
209     }
210 
211 
212     @Override
createServerSocket(int port)213     public ServerSocket createServerSocket(int port)
214     throws IOException
215     {
216         return throwException();
217     }
218 
219     @Override
createServerSocket(int port, int backlog)220     public ServerSocket createServerSocket(int port, int backlog)
221     throws IOException
222     {
223         return throwException();
224     }
225 
226     @Override
227     public ServerSocket
createServerSocket(int port, int backlog, InetAddress ifAddress)228     createServerSocket(int port, int backlog, InetAddress ifAddress)
229     throws IOException
230     {
231         return throwException();
232     }
233 
234     @Override
getDefaultCipherSuites()235     public String [] getDefaultCipherSuites() {
236         return new String[0];
237     }
238 
239     @Override
getSupportedCipherSuites()240     public String [] getSupportedCipherSuites() {
241         return new String[0];
242     }
243 }
244