1 /*
   2  * Copyright (c) 1999, 2018, 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 javax.net.ssl;
  27 
  28 import java.security.*;
  29 import java.util.Objects;
  30 
  31 import sun.security.jca.GetInstance;
  32 
  33 /**
  34  * Instances of this class represent a secure socket protocol
  35  * implementation which acts as a factory for secure socket
  36  * factories or {@code SSLEngine}s. This class is initialized
  37  * with an optional set of key and trust managers and source of
  38  * secure random bytes.
  39  *
  40  * <p> Every implementation of the Java platform is required to support the
  41  * following standard {@code SSLContext} protocol:
  42  * <ul>
  43  * <li>{@code TLSv1.2}</li>
  44  * </ul>
  45  * This protocol is described in the <a href=
  46  * "{@docRoot}/../specs/security/standard-names.html#sslcontext-algorithms">
  47  * SSLContext section</a> of the
  48  * Java Security Standard Algorithm Names Specification.
  49  * Consult the release documentation for your implementation to see if any
  50  * other protocols are supported.
  51  *
  52  * @since 1.4
  53  */
  54 public class SSLContext {
  55     private final Provider provider;
  56 
  57     private final SSLContextSpi contextSpi;
  58 
  59     private final String protocol;
  60 
  61     /**
  62      * Creates an SSLContext object.
  63      *
  64      * @param contextSpi the delegate
  65      * @param provider the provider
  66      * @param protocol the protocol
  67      */
  68     protected SSLContext(SSLContextSpi contextSpi, Provider provider,
  69             String protocol) {
  70         this.contextSpi = contextSpi;
  71         this.provider = provider;
  72         this.protocol = protocol;
  73     }
  74 
  75     private static SSLContext defaultContext;
  76 
  77     /**
  78      * Returns the default SSL context.
  79      *
  80      * <p>If a default context was set using the {@link #setDefault
  81      * SSLContext.setDefault()} method, it is returned. Otherwise, the first
  82      * call of this method triggers the call
  83      * {@code SSLContext.getInstance("Default")}.
  84      * If successful, that object is made the default SSL context and returned.
  85      *
  86      * <p>The default context is immediately
  87      * usable and does not require {@linkplain #init initialization}.
  88      *
  89      * @return the default SSL context
  90      * @throws NoSuchAlgorithmException if the
  91      *   {@link SSLContext#getInstance SSLContext.getInstance()} call fails
  92      * @since 1.6
  93      */
  94     public static synchronized SSLContext getDefault()
  95             throws NoSuchAlgorithmException {
  96         if (defaultContext == null) {
  97             defaultContext = SSLContext.getInstance("Default");
  98         }
  99         return defaultContext;
 100     }
 101 
 102     /**
 103      * Sets the default SSL context. It will be returned by subsequent calls
 104      * to {@link #getDefault}. The default context must be immediately usable
 105      * and not require {@linkplain #init initialization}.
 106      *
 107      * @param context the SSLContext
 108      * @throws  NullPointerException if context is null
 109      * @throws  SecurityException if a security manager exists and its
 110      *          {@code checkPermission} method does not allow
 111      *          {@code SSLPermission("setDefaultSSLContext")}
 112      * @since 1.6
 113      */
 114     public static synchronized void setDefault(SSLContext context) {
 115         if (context == null) {
 116             throw new NullPointerException();
 117         }
 118         SecurityManager sm = System.getSecurityManager();
 119         if (sm != null) {
 120             sm.checkPermission(new SSLPermission("setDefaultSSLContext"));
 121         }
 122         defaultContext = context;
 123     }
 124 
 125     /**
 126      * Returns a {@code SSLContext} object that implements the
 127      * specified secure socket protocol.
 128      *
 129      * <p> This method traverses the list of registered security Providers,
 130      * starting with the most preferred Provider.
 131      * A new SSLContext object encapsulating the
 132      * SSLContextSpi implementation from the first
 133      * Provider that supports the specified protocol is returned.
 134      *
 135      * <p> Note that the list of registered providers may be retrieved via
 136      * the {@link Security#getProviders() Security.getProviders()} method.
 137      *
 138      * @implNote
 139      * The JDK Reference Implementation additionally uses the
 140      * {@code jdk.security.provider.preferred}
 141      * {@link Security#getProperty(String) Security} property to determine
 142      * the preferred provider order for the specified algorithm. This
 143      * may be different than the order of providers returned by
 144      * {@link Security#getProviders() Security.getProviders()}.
 145      *
 146      * @param protocol the standard name of the requested protocol.
 147      *          See the SSLContext section in the <a href=
 148      * "{@docRoot}/../specs/security/standard-names.html#sslcontext-algorithms">
 149      *          Java Security Standard Algorithm Names Specification</a>
 150      *          for information about standard protocol names.
 151      *
 152      * @return the new {@code SSLContext} object
 153      *
 154      * @throws NoSuchAlgorithmException if no {@code Provider} supports a
 155      *         {@code SSLContextSpi} implementation for the
 156      *         specified protocol
 157      *
 158      * @throws NullPointerException if {@code protocol} is {@code null}
 159      *
 160      * @see java.security.Provider
 161      */
 162     public static SSLContext getInstance(String protocol)
 163             throws NoSuchAlgorithmException {
 164         Objects.requireNonNull(protocol, "null protocol name");
 165         GetInstance.Instance instance = GetInstance.getInstance
 166                 ("SSLContext", SSLContextSpi.class, protocol);
 167         return new SSLContext((SSLContextSpi)instance.impl, instance.provider,
 168                 protocol);
 169     }
 170 
 171     /**
 172      * Returns a {@code SSLContext} object that implements the
 173      * specified secure socket protocol.
 174      *
 175      * <p> A new SSLContext object encapsulating the
 176      * SSLContextSpi implementation from the specified provider
 177      * is returned.  The specified provider must be registered
 178      * in the security provider list.
 179      *
 180      * <p> Note that the list of registered providers may be retrieved via
 181      * the {@link Security#getProviders() Security.getProviders()} method.
 182      *
 183      * @param protocol the standard name of the requested protocol.
 184      *          See the SSLContext section in the <a href=
 185      * "{@docRoot}/../specs/security/standard-names.html#sslcontext-algorithms">
 186      *          Java Security Standard Algorithm Names Specification</a>
 187      *          for information about standard protocol names.
 188      *
 189      * @param provider the name of the provider.
 190      *
 191      * @return the new {@code SSLContext} object
 192      *
 193      * @throws IllegalArgumentException if the provider name is
 194      *         {@code null} or empty
 195      *
 196      * @throws NoSuchAlgorithmException if a {@code SSLContextSpi}
 197      *         implementation for the specified protocol is not
 198      *         available from the specified provider
 199      *
 200      * @throws NoSuchProviderException if the specified provider is not
 201      *         registered in the security provider list
 202      *
 203      * @throws NullPointerException if {@code protocol} is {@code null}
 204      *
 205      * @see java.security.Provider
 206      */
 207     public static SSLContext getInstance(String protocol, String provider)
 208             throws NoSuchAlgorithmException, NoSuchProviderException {
 209         Objects.requireNonNull(protocol, "null protocol name");
 210         GetInstance.Instance instance = GetInstance.getInstance
 211                 ("SSLContext", SSLContextSpi.class, protocol, provider);
 212         return new SSLContext((SSLContextSpi)instance.impl, instance.provider,
 213                 protocol);
 214     }
 215 
 216     /**
 217      * Returns a {@code SSLContext} object that implements the
 218      * specified secure socket protocol.
 219      *
 220      * <p> A new SSLContext object encapsulating the
 221      * SSLContextSpi implementation from the specified Provider
 222      * object is returned.  Note that the specified Provider object
 223      * does not have to be registered in the provider list.
 224      *
 225      * @param protocol the standard name of the requested protocol.
 226      *          See the SSLContext section in the <a href=
 227      * "{@docRoot}/../specs/security/standard-names.html#sslcontext-algorithms">
 228      *          Java Security Standard Algorithm Names Specification</a>
 229      *          for information about standard protocol names.
 230      *
 231      * @param provider an instance of the provider.
 232      *
 233      * @return the new {@code SSLContext} object
 234      *
 235      * @throws IllegalArgumentException if the provider is {@code null}
 236      *
 237      * @throws NoSuchAlgorithmException if a {@code SSLContextSpi}
 238      *         implementation for the specified protocol is not available
 239      *         from the specified {@code Provider} object
 240      *
 241      * @throws NullPointerException if {@code protocol} is {@code null}
 242      *
 243      * @see java.security.Provider
 244      */
 245     public static SSLContext getInstance(String protocol, Provider provider)
 246             throws NoSuchAlgorithmException {
 247         Objects.requireNonNull(protocol, "null protocol name");
 248         GetInstance.Instance instance = GetInstance.getInstance
 249                 ("SSLContext", SSLContextSpi.class, protocol, provider);
 250         return new SSLContext((SSLContextSpi)instance.impl, instance.provider,
 251                 protocol);
 252     }
 253 
 254     /**
 255      * Returns the protocol name of this {@code SSLContext} object.
 256      *
 257      * <p>This is the same name that was specified in one of the
 258      * {@code getInstance} calls that created this
 259      * {@code SSLContext} object.
 260      *
 261      * @return the protocol name of this {@code SSLContext} object.
 262      */
 263     public final String getProtocol() {
 264         return this.protocol;
 265     }
 266 
 267     /**
 268      * Returns the provider of this {@code SSLContext} object.
 269      *
 270      * @return the provider of this {@code SSLContext} object
 271      */
 272     public final Provider getProvider() {
 273         return this.provider;
 274     }
 275 
 276     /**
 277      * Initializes this context. Either of the first two parameters
 278      * may be null in which case the installed security providers will
 279      * be searched for the highest priority implementation of the
 280      * appropriate factory. Likewise, the secure random parameter may
 281      * be null in which case the default implementation will be used.
 282      * <P>
 283      * Only the first instance of a particular key and/or trust manager
 284      * implementation type in the array is used.  (For example, only
 285      * the first javax.net.ssl.X509KeyManager in the array will be used.)
 286      *
 287      * @param km the sources of authentication keys or null
 288      * @param tm the sources of peer authentication trust decisions or null
 289      * @param random the source of randomness for this generator or null
 290      * @throws KeyManagementException if this operation fails
 291      */
 292     public final void init(KeyManager[] km, TrustManager[] tm,
 293                                 SecureRandom random)
 294         throws KeyManagementException {
 295         contextSpi.engineInit(km, tm, random);
 296     }
 297 
 298     /**
 299      * Returns a {@code SocketFactory} object for this
 300      * context.
 301      *
 302      * @return the {@code SocketFactory} object
 303      * @throws UnsupportedOperationException if the underlying provider
 304      *         does not implement the operation.
 305      * @throws IllegalStateException if the SSLContextImpl requires
 306      *         initialization and the {@code init()} has not been called
 307      */
 308     public final SSLSocketFactory getSocketFactory() {
 309         return contextSpi.engineGetSocketFactory();
 310     }
 311 
 312     /**
 313      * Returns a {@code ServerSocketFactory} object for
 314      * this context.
 315      *
 316      * @return the {@code ServerSocketFactory} object
 317      * @throws UnsupportedOperationException if the underlying provider
 318      *         does not implement the operation.
 319      * @throws IllegalStateException if the SSLContextImpl requires
 320      *         initialization and the {@code init()} has not been called
 321      */
 322     public final SSLServerSocketFactory getServerSocketFactory() {
 323         return contextSpi.engineGetServerSocketFactory();
 324     }
 325 
 326     /**
 327      * Creates a new {@code SSLEngine} using this context.
 328      * <P>
 329      * Applications using this factory method are providing no hints
 330      * for an internal session reuse strategy. If hints are desired,
 331      * {@link #createSSLEngine(String, int)} should be used
 332      * instead.
 333      * <P>
 334      * Some cipher suites (such as Kerberos) require remote hostname
 335      * information, in which case this factory method should not be used.
 336      *
 337      * @return  the {@code SSLEngine} object
 338      * @throws  UnsupportedOperationException if the underlying provider
 339      *          does not implement the operation.
 340      * @throws  IllegalStateException if the SSLContextImpl requires
 341      *          initialization and the {@code init()} has not been called
 342      * @since   1.5
 343      */
 344     public final SSLEngine createSSLEngine() {
 345         try {
 346             return contextSpi.engineCreateSSLEngine();
 347         } catch (AbstractMethodError e) {
 348             UnsupportedOperationException unsup =
 349                 new UnsupportedOperationException(
 350                     "Provider: " + getProvider() +
 351                     " doesn't support this operation");
 352             unsup.initCause(e);
 353             throw unsup;
 354         }
 355     }
 356 
 357     /**
 358      * Creates a new {@code SSLEngine} using this context using
 359      * advisory peer information.
 360      * <P>
 361      * Applications using this factory method are providing hints
 362      * for an internal session reuse strategy.
 363      * <P>
 364      * Some cipher suites (such as Kerberos) require remote hostname
 365      * information, in which case peerHost needs to be specified.
 366      *
 367      * @param   peerHost the non-authoritative name of the host
 368      * @param   peerPort the non-authoritative port
 369      * @return  the new {@code SSLEngine} object
 370      * @throws  UnsupportedOperationException if the underlying provider
 371      *          does not implement the operation.
 372      * @throws  IllegalStateException if the SSLContextImpl requires
 373      *          initialization and the {@code init()} has not been called
 374      * @since   1.5
 375      */
 376     public final SSLEngine createSSLEngine(String peerHost, int peerPort) {
 377         try {
 378             return contextSpi.engineCreateSSLEngine(peerHost, peerPort);
 379         } catch (AbstractMethodError e) {
 380             UnsupportedOperationException unsup =
 381                 new UnsupportedOperationException(
 382                     "Provider: " + getProvider() +
 383                     " does not support this operation");
 384             unsup.initCause(e);
 385             throw unsup;
 386         }
 387     }
 388 
 389     /**
 390      * Returns the server session context, which represents the set of
 391      * SSL sessions available for use during the handshake phase of
 392      * server-side SSL sockets.
 393      * <P>
 394      * This context may be unavailable in some environments, in which
 395      * case this method returns null. For example, when the underlying
 396      * SSL provider does not provide an implementation of SSLSessionContext
 397      * interface, this method returns null. A non-null session context
 398      * is returned otherwise.
 399      *
 400      * @return server session context bound to this SSL context
 401      */
 402     public final SSLSessionContext getServerSessionContext() {
 403         return contextSpi.engineGetServerSessionContext();
 404     }
 405 
 406     /**
 407      * Returns the client session context, which represents the set of
 408      * SSL sessions available for use during the handshake phase of
 409      * client-side SSL sockets.
 410      * <P>
 411      * This context may be unavailable in some environments, in which
 412      * case this method returns null. For example, when the underlying
 413      * SSL provider does not provide an implementation of SSLSessionContext
 414      * interface, this method returns null. A non-null session context
 415      * is returned otherwise.
 416      *
 417      * @return client session context bound to this SSL context
 418      */
 419     public final SSLSessionContext getClientSessionContext() {
 420         return contextSpi.engineGetClientSessionContext();
 421     }
 422 
 423     /**
 424      * Returns a copy of the SSLParameters indicating the default
 425      * settings for this SSL context.
 426      *
 427      * <p>The parameters will always have the ciphersuites and protocols
 428      * arrays set to non-null values.
 429      *
 430      * @return a copy of the SSLParameters object with the default settings
 431      * @throws UnsupportedOperationException if the default SSL parameters
 432      *   could not be obtained.
 433      * @since 1.6
 434      */
 435     public final SSLParameters getDefaultSSLParameters() {
 436         return contextSpi.engineGetDefaultSSLParameters();
 437     }
 438 
 439     /**
 440      * Returns a copy of the SSLParameters indicating the supported
 441      * settings for this SSL context.
 442      *
 443      * <p>The parameters will always have the ciphersuites and protocols
 444      * arrays set to non-null values.
 445      *
 446      * @return a copy of the SSLParameters object with the supported
 447      *   settings
 448      * @throws UnsupportedOperationException if the supported SSL parameters
 449      *   could not be obtained.
 450      * @since 1.6
 451      */
 452     public final SSLParameters getSupportedSSLParameters() {
 453         return contextSpi.engineGetSupportedSSLParameters();
 454     }
 455 
 456 }