1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 2003, 2011, 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 package sun.security.jca;
28 
29 import dalvik.system.VMRuntime;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.Provider;
32 import java.util.Arrays;
33 import java.util.HashSet;
34 import java.util.Locale;
35 import java.util.Set;
36 
37 /**
38  * Collection of methods to get and set provider list. Also includes
39  * special code for the provider list during JAR verification.
40  *
41  * @author  Andreas Sterbenz
42  * @since   1.5
43  */
44 public class Providers {
45 
46     private static final ThreadLocal<ProviderList> threadLists =
47         new InheritableThreadLocal<>();
48 
49     // number of threads currently using thread-local provider lists
50     // tracked to allow an optimization if == 0
51     private static volatile int threadListsUsed;
52 
53     // current system-wide provider list
54     // Note volatile immutable object, so no synchronization needed.
55     private static volatile ProviderList providerList;
56 
57     // Android-added: Keep reference to system-created Bouncy Castle provider
58     // See comments near deprecation methods at the bottom of this file.
59     private static volatile Provider SYSTEM_BOUNCY_CASTLE_PROVIDER;
60 
61     static {
62         // set providerList to empty list first in case initialization somehow
63         // triggers a getInstance() call (although that should not happen)
64         providerList = ProviderList.EMPTY;
65         providerList = ProviderList.fromSecurityProperties();
66 
67         // BEGIN Android-added: Initialize all providers and assert that this succeeds.
68         // removeInvalid is specified to try initializing all configured providers
69         // and removing those that aren't instantiable. This has the side effect
70         // of eagerly initializing all providers.
71         final int numConfiguredProviders = providerList.size();
72         providerList = providerList.removeInvalid();
73         if (numConfiguredProviders != providerList.size()) {
74             throw new AssertionError("Unable to configure default providers");
75         }
76         // END Android-added: Initialize all providers and assert that this succeeds.
77         // Android-added: Set BC provider instance
78         SYSTEM_BOUNCY_CASTLE_PROVIDER = providerList.getProvider("BC");
79     }
80 
Providers()81     private Providers() {
82         // empty
83     }
84 
85     // we need special handling to resolve circularities when loading
86     // signed JAR files during startup. The code below is part of that.
87 
88     // Basically, before we load data from a signed JAR file, we parse
89     // the PKCS#7 file and verify the signature. We need a
90     // CertificateFactory, Signatures, etc. to do that. We have to make
91     // sure that we do not try to load the implementation from the JAR
92     // file we are just verifying.
93     //
94     // To avoid that, we use different provider settings during JAR
95     // verification.  However, we do not want those provider settings to
96     // interfere with other parts of the system. Therefore, we make them local
97     // to the Thread executing the JAR verification code.
98     //
99     // The code here is used by sun.security.util.SignatureFileVerifier.
100     // See there for details.
101 
102     private static final String BACKUP_PROVIDER_CLASSNAME =
103         "sun.security.provider.VerificationProvider";
104 
105     // Hardcoded classnames of providers to use for JAR verification.
106     // MUST NOT be on the bootclasspath and not in signed JAR files.
107     private static final String[] jarVerificationProviders = {
108         // BEGIN Android-changed: Use Conscrypt and BC, not the sun.security providers.
109         /*
110         "sun.security.provider.Sun",
111         "sun.security.rsa.SunRsaSign",
112         // Note: SunEC *is* in a signed JAR file, but it's not signed
113         // by EC itself. So it's still safe to be listed here.
114         "sun.security.ec.SunEC",
115         */
116         "com.android.org.conscrypt.OpenSSLProvider",
117         "com.android.org.bouncycastle.jce.provider.BouncyCastleProvider",
118         "com.android.org.conscrypt.JSSEProvider",
119         // END Android-changed: Use Conscrypt and BC, not the sun.security providers.
120         BACKUP_PROVIDER_CLASSNAME,
121     };
122 
123     // Return to Sun provider or its backup.
124     // This method should only be called by
125     // sun.security.util.ManifestEntryVerifier and java.security.SecureRandom.
getSunProvider()126     public static Provider getSunProvider() {
127         try {
128             Class<?> clazz = Class.forName(jarVerificationProviders[0]);
129             return (Provider)clazz.newInstance();
130         } catch (Exception e) {
131             try {
132                 Class<?> clazz = Class.forName(BACKUP_PROVIDER_CLASSNAME);
133                 return (Provider)clazz.newInstance();
134             } catch (Exception ee) {
135                 throw new RuntimeException("Sun provider not found", e);
136             }
137         }
138     }
139 
140     /**
141      * Start JAR verification. This sets a special provider list for
142      * the current thread. You MUST save the return value from this
143      * method and you MUST call {@link #stopJarVerification(Object)} with that object
144      * once you are done.
145      *
146      * @return old thread-local provider
147      */
startJarVerification()148     public static Object startJarVerification() {
149         ProviderList currentList = getProviderList();
150         ProviderList jarList = currentList.getJarList(jarVerificationProviders);
151         // return the old thread-local provider list, usually null
152         return beginThreadProviderList(jarList);
153     }
154 
155     /**
156      * Stop JAR verification. Call once you have completed JAR verification,
157      * passing previously saved return value of {@link #startJarVerification()}.
158      *
159      * @param obj previously saved from {@link #startJarVerification()} old
160      *            thread-local provider list
161      */
stopJarVerification(Object obj)162     public static void stopJarVerification(Object obj) {
163         // restore old thread-local provider list
164         endThreadProviderList((ProviderList)obj);
165     }
166 
167     /**
168      * Return the current ProviderList. If the thread-local list is set,
169      * it is returned. Otherwise, the system wide list is returned.
170      */
getProviderList()171     public static ProviderList getProviderList() {
172         ProviderList list = getThreadProviderList();
173         if (list == null) {
174             list = getSystemProviderList();
175         }
176         return list;
177     }
178 
179     /**
180      * Set the current ProviderList. Affects the thread-local list if set,
181      * otherwise the system wide list.
182      */
setProviderList(ProviderList newList)183     public static void setProviderList(ProviderList newList) {
184         if (getThreadProviderList() == null) {
185             setSystemProviderList(newList);
186         } else {
187             changeThreadProviderList(newList);
188         }
189     }
190 
191     /**
192      * Get the full provider list with invalid providers (those that
193      * could not be loaded) removed. This is the list we need to
194      * present to applications.
195      */
getFullProviderList()196     public static ProviderList getFullProviderList() {
197         ProviderList list;
198         synchronized (Providers.class) {
199             list = getThreadProviderList();
200             if (list != null) {
201                 ProviderList newList = list.removeInvalid();
202                 if (newList != list) {
203                     changeThreadProviderList(newList);
204                     list = newList;
205                 }
206                 return list;
207             }
208         }
209         list = getSystemProviderList();
210         ProviderList newList = list.removeInvalid();
211         if (newList != list) {
212             setSystemProviderList(newList);
213             list = newList;
214         }
215         return list;
216     }
217 
getSystemProviderList()218     private static ProviderList getSystemProviderList() {
219         return providerList;
220     }
221 
setSystemProviderList(ProviderList list)222     private static void setSystemProviderList(ProviderList list) {
223         providerList = list;
224     }
225 
getThreadProviderList()226     public static ProviderList getThreadProviderList() {
227         // avoid accessing the threadlocal if none are currently in use
228         // (first use of ThreadLocal.get() for a Thread allocates a Map)
229         if (threadListsUsed == 0) {
230             return null;
231         }
232         return threadLists.get();
233     }
234 
235     // Change the thread local provider list. Use only if the current thread
236     // is already using a thread local list and you want to change it in place.
237     // In other cases, use the begin/endThreadProviderList() methods.
changeThreadProviderList(ProviderList list)238     private static void changeThreadProviderList(ProviderList list) {
239         threadLists.set(list);
240     }
241 
242     /**
243      * Methods to manipulate the thread local provider list. It is for use by
244      * JAR verification (see above) and the SunJSSE FIPS mode only.
245      *
246      * It should be used as follows:
247      *
248      *   ProviderList list = ...;
249      *   ProviderList oldList = Providers.beginThreadProviderList(list);
250      *   try {
251      *     // code that needs thread local provider list
252      *   } finally {
253      *     Providers.endThreadProviderList(oldList);
254      *   }
255      *
256      */
257 
beginThreadProviderList(ProviderList list)258     public static synchronized ProviderList beginThreadProviderList(ProviderList list) {
259         if (ProviderList.debug != null) {
260             ProviderList.debug.println("ThreadLocal providers: " + list);
261         }
262         ProviderList oldList = threadLists.get();
263         threadListsUsed++;
264         threadLists.set(list);
265         return oldList;
266     }
267 
endThreadProviderList(ProviderList list)268     public static synchronized void endThreadProviderList(ProviderList list) {
269         if (list == null) {
270             if (ProviderList.debug != null) {
271                 ProviderList.debug.println("Disabling ThreadLocal providers");
272             }
273             threadLists.remove();
274         } else {
275             if (ProviderList.debug != null) {
276                 ProviderList.debug.println
277                     ("Restoring previous ThreadLocal providers: " + list);
278             }
279             threadLists.set(list);
280         }
281         threadListsUsed--;
282     }
283 
284     // BEGIN Android-added: Check for requests of deprecated Bouncy Castle algorithms.
285     // Beginning in Android P, Bouncy Castle versions of algorithms available through
286     // Conscrypt are deprecated.  We will no longer supply them to applications
287     // with a target API level of P or later, and will print a warning for applications
288     // with a target API level before P.
289     //
290     // We only care about the system-provided Bouncy Castle provider; applications are allowed to
291     // install their own copy of Bouncy Castle if they want to continue using those implementations.
292 
293     /**
294      * Maximum target API level for which we will provide the deprecated Bouncy Castle algorithms.
295      *
296      * Only exists for testing and shouldn't be changed.
297      *
298      * @hide
299      */
300     public static final int DEFAULT_MAXIMUM_ALLOWABLE_TARGET_API_LEVEL_FOR_BC_DEPRECATION = 27;
301 
302     private static int maximumAllowableApiLevelForBcDeprecation =
303             DEFAULT_MAXIMUM_ALLOWABLE_TARGET_API_LEVEL_FOR_BC_DEPRECATION;
304 
305     /**
306      * Sets the target API level for BC deprecation, only for use in tests.
307      *
308      * @hide
309      */
setMaximumAllowableApiLevelForBcDeprecation(int targetApiLevel)310     public static void setMaximumAllowableApiLevelForBcDeprecation(int targetApiLevel) {
311         maximumAllowableApiLevelForBcDeprecation = targetApiLevel;
312     }
313 
314     /**
315      * Returns the target API level for BC deprecation, only for use in tests.
316      *
317      * @hide
318      */
getMaximumAllowableApiLevelForBcDeprecation()319     public static int getMaximumAllowableApiLevelForBcDeprecation() {
320         return maximumAllowableApiLevelForBcDeprecation;
321     }
322 
323     /**
324      * Checks if the installed provider with the given name is the system-installed Bouncy
325      * Castle provider.  If so, throws {@code NoSuchAlgorithmException} if the algorithm
326      * being requested is deprecated and the application targets a late-enough API level.
327      *
328      * @hide
329      */
checkBouncyCastleDeprecation(String provider, String service, String algorithm)330     public static synchronized void checkBouncyCastleDeprecation(String provider,
331             String service, String algorithm) throws NoSuchAlgorithmException {
332         // Applications may install their own BC provider, only the algorithms from the system
333         // provider are deprecated.
334         if ("BC".equals(provider)
335                 && providerList.getProvider(provider) == SYSTEM_BOUNCY_CASTLE_PROVIDER) {
336             checkBouncyCastleDeprecation(service, algorithm);
337         }
338     }
339 
340     /**
341      * Checks if the given provider is the system-installed Bouncy Castle provider.  If so,
342      * throws {@code NoSuchAlgorithmException} if the algorithm being requested is deprecated
343      * and the application targets a late-enough API level.
344      *
345      * @hide
346      */
checkBouncyCastleDeprecation(Provider provider, String service, String algorithm)347     public static synchronized void checkBouncyCastleDeprecation(Provider provider,
348             String service, String algorithm) throws NoSuchAlgorithmException {
349         // Applications may install their own BC provider, only the algorithms from the system
350         // provider are deprecated.
351         if (provider == SYSTEM_BOUNCY_CASTLE_PROVIDER) {
352             checkBouncyCastleDeprecation(service, algorithm);
353         }
354     }
355 
356     // The set of algorithms that are deprecated.  This list is created using
357     // libcore/tools/crypto/src/java/libcore/java/security/ProviderOverlap.java.
358     private static final Set<String> DEPRECATED_ALGORITHMS = new HashSet<String>();
359     static {
360         DEPRECATED_ALGORITHMS.addAll(Arrays.asList(
361             "KEYFACTORY.RSA"
362         ));
363     }
364 
365     /**
366      * Throws an exception or logs a warning if the supplied service and algorithm identify
367      * a deprecated algorithm from Bouncy Castle, depending on the application's target API level.
368      * Only called if we have already determined that the request is for the system Bouncy Castle
369      * provider.
370      */
checkBouncyCastleDeprecation(String service, String algorithm)371     private static void checkBouncyCastleDeprecation(String service, String algorithm)
372             throws NoSuchAlgorithmException {
373         String key = service + "." + algorithm;
374         if (DEPRECATED_ALGORITHMS.contains(key.toUpperCase(Locale.US))) {
375             if (VMRuntime.getRuntime().getTargetSdkVersion()
376                     <= maximumAllowableApiLevelForBcDeprecation) {
377                 // This application is allowed to access these functions, only print a warning
378                 System.logE(" ******** DEPRECATED FUNCTIONALITY ********");
379                 System.logE(" * The implementation of the " + key + " algorithm from");
380                 System.logE(" * the BC provider is deprecated in this version of Android.");
381                 System.logE(" * It will be removed in a future version of Android and your");
382                 System.logE(" * application will no longer be able to request it.  Please see");
383                 System.logE(" * https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html");
384                 System.logE(" * for more details.");
385             } else {
386                 throw new NoSuchAlgorithmException("The BC provider no longer provides an"
387                         + " implementation for " + key + ".  Please see"
388                         + " https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html"
389                         + " for more details.");
390             }
391         }
392     }
393     // END Android-added: Check for requests of deprecated Bouncy Castle algorithms.
394 
395 }
396