src/java.base/share/classes/sun/security/jca/ProviderConfig.java

Print this page
7191662: JCE providers should be located via ServiceLoader
   1 /*
   2  * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.security.jca;
  27 
  28 import java.io.File;
  29 import java.lang.reflect.*;

  30 
  31 import java.security.*;
  32 
  33 import sun.security.util.PropertyExpander;
  34 
  35 /**
  36  * Class representing a configured provider. Encapsulates configuration
  37  * (className plus optional argument), the provider loading logic, and
  38  * the loaded Provider object itself.
  39  *
  40  * @author  Andreas Sterbenz
  41  * @since   1.5
  42  */
  43 final class ProviderConfig {
  44 
  45     private final static sun.security.util.Debug debug =
  46         sun.security.util.Debug.getInstance("jca", "ProviderConfig");
  47 
  48     // classname of the SunPKCS11-Solaris provider
  49     private static final String P11_SOL_NAME =
  50         "sun.security.pkcs11.SunPKCS11";
  51 
  52     // config file argument of the SunPKCS11-Solaris provider
  53     private static final String P11_SOL_ARG  =
  54         "${java.home}/conf/security/sunpkcs11-solaris.cfg";
  55 
  56     // maximum number of times to try loading a provider before giving up
  57     private final static int MAX_LOAD_TRIES = 30;
  58 
  59     // parameters for the Provider(String) constructor,
  60     // use by doLoadProvider()
  61     private final static Class<?>[] CL_STRING = { String.class };
  62 
  63     // name of the provider class
  64     private final String className;
  65 
  66     // argument to the provider constructor,
  67     // empty string indicates no-arg constructor
  68     private final String argument;
  69 
  70     // number of times we have already tried to load this provider
  71     private int tries;
  72 
  73     // Provider object, if loaded
  74     private volatile Provider provider;
  75 
  76     // flag indicating if we are currently trying to load the provider
  77     // used to detect recursion
  78     private boolean isLoading;
  79 
  80     ProviderConfig(String className, String argument) {
  81         if (className.equals(P11_SOL_NAME) && argument.equals(P11_SOL_ARG)) {
  82             checkSunPKCS11Solaris();
  83         }
  84         this.className = className;
  85         this.argument = expand(argument);
  86     }
  87 


 155     public String toString() {
 156         if (hasArgument()) {
 157             return className + "('" + argument + "')";
 158         } else {
 159             return className;
 160         }
 161     }
 162 
 163     /**
 164      * Get the provider object. Loads the provider if it is not already loaded.
 165      */
 166     synchronized Provider getProvider() {
 167         // volatile variable load
 168         Provider p = provider;
 169         if (p != null) {
 170             return p;
 171         }
 172         if (shouldLoad() == false) {
 173             return null;
 174         }











 175         if (isLoading) {
 176             // because this method is synchronized, this can only
 177             // happen if there is recursion.
 178             if (debug != null) {
 179                 debug.println("Recursion loading provider: " + this);
 180                 new Exception("Call trace").printStackTrace();
 181             }
 182             return null;
 183         }
 184         try {
 185             isLoading = true;
 186             tries++;
 187             p = doLoadProvider();
 188         } finally {
 189             isLoading = false;
 190         }

 191         provider = p;
 192         return p;
 193     }
 194 
 195     /**
 196      * Load and instantiate the Provider described by this class.
 197      *
 198      * NOTE use of doPrivileged().
 199      *
 200      * @return null if the Provider could not be loaded
 201      *
 202      * @throws ProviderException if executing the Provider's constructor
 203      * throws a ProviderException. All other Exceptions are ignored.
 204      */
 205     private Provider doLoadProvider() {
 206         return AccessController.doPrivileged(new PrivilegedAction<Provider>() {
 207             public Provider run() {
 208                 if (debug != null) {
 209                     debug.println("Loading provider: " + ProviderConfig.this);
 210                 }

 211                 try {
 212                     ClassLoader cl = ClassLoader.getSystemClassLoader();
 213                     Class<?> provClass;
 214                     if (cl != null) {
 215                         provClass = cl.loadClass(className);
 216                     } else {
 217                         provClass = Class.forName(className);
 218                     }
 219                     Object obj;
 220                     if (hasArgument() == false) {
 221                         obj = provClass.newInstance();
 222                     } else {
 223                         Constructor<?> cons = provClass.getConstructor(CL_STRING);
 224                         obj = cons.newInstance(argument);
 225                     }
 226                     if (obj instanceof Provider) {
 227                         if (debug != null) {
 228                             debug.println("Loaded provider " + obj);
 229                         }
 230                         return (Provider)obj;
 231                     } else {
 232                         if (debug != null) {
 233                             debug.println(className + " is not a provider");
 234                         }
 235                         disableLoad();
 236                         return null;
 237                     }

 238                 } catch (Exception e) {
 239                     Throwable t;
 240                     if (e instanceof InvocationTargetException) {
 241                         t = ((InvocationTargetException)e).getCause();
 242                     } else {
 243                         t = e;
 244                     }
 245                     if (debug != null) {
 246                         debug.println("Error loading provider " + ProviderConfig.this);
 247                         t.printStackTrace();
 248                     }
 249                     // provider indicates fatal error, pass through exception
 250                     if (t instanceof ProviderException) {
 251                         throw (ProviderException)t;
 252                     }
 253                     // provider indicates that loading should not be retried
 254                     if (t instanceof UnsupportedOperationException) {
 255                         disableLoad();
 256                     }
 257                     return null;
 258                 } catch (ExceptionInInitializerError err) {
 259                     // no sufficient permission to initialize provider class
 260                     if (debug != null) {
 261                         debug.println("Error loading provider " + ProviderConfig.this);
 262                         err.printStackTrace();
 263                     }
 264                     disableLoad();
 265                     return null;
 266                 }
 267             }
 268         });
 269     }
 270 
 271     /**
 272      * Perform property expansion of the provider value.
 273      *
 274      * NOTE use of doPrivileged().
 275      */
 276     private static String expand(final String value) {
 277         // shortcut if value does not contain any properties
 278         if (value.contains("${") == false) {
 279             return value;
 280         }
 281         return AccessController.doPrivileged(new PrivilegedAction<String>() {
 282             public String run() {
 283                 try {
 284                     return PropertyExpander.expand(value);
 285                 } catch (GeneralSecurityException e) {
 286                     throw new ProviderException(e);
 287                 }
 288             }
 289         });
 290     }
 291 


















































































































 292 }
   1 /*
   2  * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.security.jca;
  27 
  28 import java.io.File;
  29 import java.lang.reflect.*;
  30 import java.util.*;
  31 
  32 import java.security.*;
  33 
  34 import sun.security.util.PropertyExpander;
  35 
  36 /**
  37  * Class representing a configured provider which encapsulates configuration
  38  * (className + optional argument), the provider loading logic, and
  39  * the loaded Provider object itself.
  40  *
  41  * @author  Andreas Sterbenz
  42  * @since   1.5
  43  */
  44 final class ProviderConfig {
  45 
  46     private final static sun.security.util.Debug debug =
  47         sun.security.util.Debug.getInstance("jca", "ProviderConfig");
  48 
  49     // classname of the SunPKCS11-Solaris provider
  50     private static final String P11_SOL_NAME =
  51         "sun.security.pkcs11.SunPKCS11";
  52 
  53     // config file argument of the SunPKCS11-Solaris provider
  54     private static final String P11_SOL_ARG  =
  55         "${java.home}/conf/security/sunpkcs11-solaris.cfg";
  56 
  57     // maximum number of times to try loading a provider before giving up
  58     private final static int MAX_LOAD_TRIES = 30;
  59 




  60     // name of the provider class
  61     private final String className;
  62 
  63     // argument to the Provider.configure() call, never null

  64     private final String argument;
  65 
  66     // number of times we have already tried to load this provider
  67     private int tries;
  68 
  69     // Provider object, if loaded
  70     private volatile Provider provider;
  71 
  72     // flag indicating if we are currently trying to load the provider
  73     // used to detect recursion
  74     private boolean isLoading;
  75 
  76     ProviderConfig(String className, String argument) {
  77         if (className.equals(P11_SOL_NAME) && argument.equals(P11_SOL_ARG)) {
  78             checkSunPKCS11Solaris();
  79         }
  80         this.className = className;
  81         this.argument = expand(argument);
  82     }
  83 


 151     public String toString() {
 152         if (hasArgument()) {
 153             return className + "('" + argument + "')";
 154         } else {
 155             return className;
 156         }
 157     }
 158 
 159     /**
 160      * Get the provider object. Loads the provider if it is not already loaded.
 161      */
 162     synchronized Provider getProvider() {
 163         // volatile variable load
 164         Provider p = provider;
 165         if (p != null) {
 166             return p;
 167         }
 168         if (shouldLoad() == false) {
 169             return null;
 170         }
 171 
 172         // Create providers which are in java.base directly
 173         if (className.equals("sun.security.provider.Sun")) {
 174             p = new sun.security.provider.Sun();
 175         } else if (className.equals("sun.security.rsa.SunRsaSign")) {
 176             p = new sun.security.rsa.SunRsaSign();
 177         } else if (className.equals("com.sun.crypto.provider.SunJCE")) {
 178             p = new com.sun.crypto.provider.SunJCE();
 179         } else if (className.equals("com.sun.net.ssl.internal.ssl.Provider")) {
 180             p = new com.sun.net.ssl.internal.ssl.Provider();
 181         } else {
 182             if (isLoading) {
 183                 // because this method is synchronized, this can only
 184                 // happen if there is recursion.
 185                 if (debug != null) {
 186                     debug.println("Recursion loading provider: " + this);
 187                     new Exception("Call trace").printStackTrace();
 188                 }
 189                 return null;
 190             }
 191             try {
 192                 isLoading = true;
 193                 tries++;
 194                 p = doLoadProvider();
 195             } finally {
 196                 isLoading = false;
 197             }
 198         }
 199         provider = p;
 200         return p;
 201     }
 202 
 203     /**
 204      * Load and instantiate the Provider described by this class.
 205      *
 206      * NOTE use of doPrivileged().
 207      *
 208      * @return null if the Provider could not be loaded
 209      *
 210      * @throws ProviderException if executing the Provider's constructor
 211      * throws a ProviderException. All other Exceptions are ignored.
 212      */
 213     private Provider doLoadProvider() {
 214         return AccessController.doPrivileged(new PrivilegedAction<Provider>() {
 215             public Provider run() {
 216                 if (debug != null) {
 217                     debug.println("Loading provider: " + ProviderConfig.this);
 218                 }
 219                 ProviderLoader pl = new ProviderLoader();
 220                 try {
 221                     Provider p = pl.load(className);
 222                     if (p != null) {
 223                         if (hasArgument()) {
 224                             p = p.configure(argument);


 225                         }








 226                         if (debug != null) {
 227                             debug.println("Loaded provider " + p.getName());
 228                         }

 229                     } else {
 230                         if (debug != null) {
 231                             debug.println("Error loading " + className);
 232                         }
 233                         disableLoad();

 234                     }
 235                     return p;
 236                 } catch (Exception e) {
 237                     if (e instanceof ProviderException) {
 238                         // pass up
 239                         throw e;
 240                     } else {


 241                         if (debug != null) {
 242                             debug.println("Error loading " + className);
 243                             e.printStackTrace();
 244                         }






 245                         disableLoad();

 246                         return null;





 247                     }


 248                 }
 249             }
 250         });
 251     }
 252 
 253     /**
 254      * Perform property expansion of the provider value.
 255      *
 256      * NOTE use of doPrivileged().
 257      */
 258     private static String expand(final String value) {
 259         // shortcut if value does not contain any properties
 260         if (value.contains("${") == false) {
 261             return value;
 262         }
 263         return AccessController.doPrivileged(new PrivilegedAction<String>() {
 264             public String run() {
 265                 try {
 266                     return PropertyExpander.expand(value);
 267                 } catch (GeneralSecurityException e) {
 268                     throw new ProviderException(e);
 269                 }
 270             }
 271         });
 272     }
 273 
 274     // Inner class for loading security providers listed in java.security file
 275     private static final class ProviderLoader {
 276         ServiceLoader<Provider> services;
 277 
 278         ProviderLoader() {
 279             // VM should already been booted at this point, if not
 280             // - Only providers in java.base should be loaded, don't use
 281             //   ServiceLoader
 282             // - ClassLoader.getSystemClassLoader() will throw InternalError
 283             services = ServiceLoader.load(java.security.Provider.class,
 284                                           ClassLoader.getSystemClassLoader());
 285         }
 286 
 287         /**
 288          * Loads the provider with the specified class name.
 289          *
 290          * @param name the name of the provider class
 291          * @return the Provider, or null if it cannot be found or loaded
 292          * @throws ProviderException all other exceptions are ignored
 293          */
 294         public Provider load(String classname) {
 295             if (debug != null) {
 296                 debug.println("Attempt to load " + classname + " using SL");
 297             }
 298             Iterator<Provider> iter = services.iterator();
 299             while (iter.hasNext()) {
 300                 try {
 301                     Provider p = iter.next();
 302                     if (debug != null) {
 303                         debug.println("Found SL Provider named " + p.getName());
 304                     }
 305                     if (p.getClass().getName().equals(classname)) {
 306                         return p;
 307                     }
 308                 } catch (SecurityException | ServiceConfigurationError |
 309                          InvalidParameterException ex) {
 310                     // if provider loading fail due to security permission,
 311                     // log it and move on to next provider
 312                     if (debug != null) {
 313                         debug.println("Encountered " + ex +
 314                             " while iterating through SL, ignore and move on");
 315                             ex.printStackTrace();
 316                     }
 317                 }
 318             }
 319             // No success with ServiceLoader. Try loading provider the legacy,
 320             // i.e. pre-module, way via reflection
 321             try {
 322                 return legacyLoad(classname);
 323             } catch (ProviderException pe) {
 324                 // pass through
 325                 throw pe;
 326             } catch (Exception ex) {
 327                 // logged and ignored
 328                 if (debug != null) {
 329                     debug.println("Encountered " + ex +
 330                         " during legacy load of " + classname);
 331                         ex.printStackTrace();
 332                 }
 333                 return null;
 334             }
 335         }
 336 
 337         private Provider legacyLoad(String classname) {
 338 
 339             if (debug != null) {
 340                 debug.println("Loading legacy provider: " + classname);
 341             }
 342 
 343             try {
 344                 Class<?> provClass =
 345                     ClassLoader.getSystemClassLoader().loadClass(classname);
 346 
 347                 // only continue if the specified class extends Provider
 348                 if (!Provider.class.isAssignableFrom(provClass)) {
 349                     if (debug != null) {
 350                         debug.println(classname + " is not a provider");
 351                     }
 352                     return null;
 353                 }
 354 
 355                 Provider p = AccessController.doPrivileged
 356                     (new PrivilegedExceptionAction<Provider>() {
 357                     public Provider run() throws Exception {
 358                         return (Provider) provClass.newInstance();
 359                     }
 360                 });
 361                 return p;
 362             } catch (Exception e) {
 363                 Throwable t;
 364                 if (e instanceof InvocationTargetException) {
 365                     t = ((InvocationTargetException)e).getCause();
 366                 } else {
 367                     t = e;
 368                 }
 369                 if (debug != null) {
 370                     debug.println("Error loading legacy provider " + classname);
 371                     t.printStackTrace();
 372                 }
 373                 // provider indicates fatal error, pass through exception
 374                 if (t instanceof ProviderException) {
 375                     throw (ProviderException) t;
 376                 }
 377                 return null;
 378             } catch (ExceptionInInitializerError | NoClassDefFoundError err) {
 379                 // no sufficient permission to access/initialize provider class
 380                 if (debug != null) {
 381                     debug.println("Error loading legacy provider " + classname);
 382                     err.printStackTrace();
 383                 }
 384                 return null;
 385             }
 386         }
 387     }
 388 }