Path: blob/master/src/java.base/share/classes/javax/net/ssl/SSLContext.java
41159 views
/*1* Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.net.ssl;2627import java.security.*;28import java.lang.invoke.MethodHandles;29import java.lang.invoke.VarHandle;30import java.util.Objects;31import sun.security.jca.GetInstance;3233/**34* Instances of this class represent a secure socket protocol35* implementation which acts as a factory for secure socket36* factories or {@code SSLEngine}s. This class is initialized37* with an optional set of key and trust managers and source of38* secure random bytes.39*40* <p> Every implementation of the Java platform is required to support the41* 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 the48* Java Security Standard Algorithm Names Specification.49* Consult the release documentation for your implementation to see if any50* other protocols are supported.51*52* @since 1.453*/54public class SSLContext {55private final Provider provider;5657private final SSLContextSpi contextSpi;5859private final String protocol;6061private static volatile SSLContext defaultContext;6263private static final VarHandle VH_DEFAULT_CONTEXT;6465static {66try {67VH_DEFAULT_CONTEXT = MethodHandles.lookup()68.findStaticVarHandle(69SSLContext.class, "defaultContext", SSLContext.class);70} catch (Exception e) {71throw new ExceptionInInitializerError(e);72}73}7475/**76* Creates an SSLContext object.77*78* @param contextSpi the delegate79* @param provider the provider80* @param protocol the protocol81*/82protected SSLContext(SSLContextSpi contextSpi, Provider provider,83String protocol) {84this.contextSpi = contextSpi;85this.provider = provider;86this.protocol = protocol;87}8889/**90* Returns the default SSL context.91*92* <p>If a default context was set using the {@link #setDefault93* SSLContext.setDefault()} method, it is returned. Otherwise, the first94* call of this method triggers the call95* {@code SSLContext.getInstance("Default")}.96* If successful, that object is made the default SSL context and returned.97*98* <p>The default context is immediately99* usable and does not require {@linkplain #init initialization}.100*101* @return the default SSL context102* @throws NoSuchAlgorithmException if the103* {@link SSLContext#getInstance SSLContext.getInstance()} call fails104* @since 1.6105*/106public static SSLContext getDefault() throws NoSuchAlgorithmException {107SSLContext temporaryContext = defaultContext;108if (temporaryContext == null) {109temporaryContext = SSLContext.getInstance("Default");110if (!VH_DEFAULT_CONTEXT.compareAndSet(null, temporaryContext)) {111temporaryContext = defaultContext;112}113}114115return temporaryContext;116}117118/**119* Sets the default SSL context. It will be returned by subsequent calls120* to {@link #getDefault}. The default context must be immediately usable121* and not require {@linkplain #init initialization}.122*123* @param context the SSLContext124* @throws NullPointerException if context is null125* @throws SecurityException if a security manager exists and its126* {@code checkPermission} method does not allow127* {@code SSLPermission("setDefaultSSLContext")}128* @since 1.6129*/130public static void setDefault(SSLContext context) {131if (context == null) {132throw new NullPointerException();133}134@SuppressWarnings("removal")135SecurityManager sm = System.getSecurityManager();136if (sm != null) {137sm.checkPermission(new SSLPermission("setDefaultSSLContext"));138}139140defaultContext = context;141}142143/**144* Returns a {@code SSLContext} object that implements the145* specified secure socket protocol.146*147* <p> This method traverses the list of registered security Providers,148* starting with the most preferred Provider.149* A new SSLContext object encapsulating the150* SSLContextSpi implementation from the first151* Provider that supports the specified protocol is returned.152*153* <p> Note that the list of registered providers may be retrieved via154* the {@link Security#getProviders() Security.getProviders()} method.155*156* @implNote157* The JDK Reference Implementation additionally uses the158* {@code jdk.security.provider.preferred}159* {@link Security#getProperty(String) Security} property to determine160* the preferred provider order for the specified algorithm. This161* may be different than the order of providers returned by162* {@link Security#getProviders() Security.getProviders()}.163*164* @param protocol the standard name of the requested protocol.165* See the SSLContext section in the <a href=166* "{@docRoot}/../specs/security/standard-names.html#sslcontext-algorithms">167* Java Security Standard Algorithm Names Specification</a>168* for information about standard protocol names.169*170* @return the new {@code SSLContext} object171*172* @throws NoSuchAlgorithmException if no {@code Provider} supports a173* {@code SSLContextSpi} implementation for the174* specified protocol175*176* @throws NullPointerException if {@code protocol} is {@code null}177*178* @see java.security.Provider179*/180public static SSLContext getInstance(String protocol)181throws NoSuchAlgorithmException {182Objects.requireNonNull(protocol, "null protocol name");183GetInstance.Instance instance = GetInstance.getInstance184("SSLContext", SSLContextSpi.class, protocol);185return new SSLContext((SSLContextSpi)instance.impl, instance.provider,186protocol);187}188189/**190* Returns a {@code SSLContext} object that implements the191* specified secure socket protocol.192*193* <p> A new SSLContext object encapsulating the194* SSLContextSpi implementation from the specified provider195* is returned. The specified provider must be registered196* in the security provider list.197*198* <p> Note that the list of registered providers may be retrieved via199* the {@link Security#getProviders() Security.getProviders()} method.200*201* @param protocol the standard name of the requested protocol.202* See the SSLContext section in the <a href=203* "{@docRoot}/../specs/security/standard-names.html#sslcontext-algorithms">204* Java Security Standard Algorithm Names Specification</a>205* for information about standard protocol names.206*207* @param provider the name of the provider.208*209* @return the new {@code SSLContext} object210*211* @throws IllegalArgumentException if the provider name is212* {@code null} or empty213*214* @throws NoSuchAlgorithmException if a {@code SSLContextSpi}215* implementation for the specified protocol is not216* available from the specified provider217*218* @throws NoSuchProviderException if the specified provider is not219* registered in the security provider list220*221* @throws NullPointerException if {@code protocol} is {@code null}222*223* @see java.security.Provider224*/225public static SSLContext getInstance(String protocol, String provider)226throws NoSuchAlgorithmException, NoSuchProviderException {227Objects.requireNonNull(protocol, "null protocol name");228GetInstance.Instance instance = GetInstance.getInstance229("SSLContext", SSLContextSpi.class, protocol, provider);230return new SSLContext((SSLContextSpi)instance.impl, instance.provider,231protocol);232}233234/**235* Returns a {@code SSLContext} object that implements the236* specified secure socket protocol.237*238* <p> A new SSLContext object encapsulating the239* SSLContextSpi implementation from the specified Provider240* object is returned. Note that the specified Provider object241* does not have to be registered in the provider list.242*243* @param protocol the standard name of the requested protocol.244* See the SSLContext section in the <a href=245* "{@docRoot}/../specs/security/standard-names.html#sslcontext-algorithms">246* Java Security Standard Algorithm Names Specification</a>247* for information about standard protocol names.248*249* @param provider an instance of the provider.250*251* @return the new {@code SSLContext} object252*253* @throws IllegalArgumentException if the provider is {@code null}254*255* @throws NoSuchAlgorithmException if a {@code SSLContextSpi}256* implementation for the specified protocol is not available257* from the specified {@code Provider} object258*259* @throws NullPointerException if {@code protocol} is {@code null}260*261* @see java.security.Provider262*/263public static SSLContext getInstance(String protocol, Provider provider)264throws NoSuchAlgorithmException {265Objects.requireNonNull(protocol, "null protocol name");266GetInstance.Instance instance = GetInstance.getInstance267("SSLContext", SSLContextSpi.class, protocol, provider);268return new SSLContext((SSLContextSpi)instance.impl, instance.provider,269protocol);270}271272/**273* Returns the protocol name of this {@code SSLContext} object.274*275* <p>This is the same name that was specified in one of the276* {@code getInstance} calls that created this277* {@code SSLContext} object.278*279* @return the protocol name of this {@code SSLContext} object.280*/281public final String getProtocol() {282return this.protocol;283}284285/**286* Returns the provider of this {@code SSLContext} object.287*288* @return the provider of this {@code SSLContext} object289*/290public final Provider getProvider() {291return this.provider;292}293294/**295* Initializes this context. Either of the first two parameters296* may be null in which case the installed security providers will297* be searched for the highest priority implementation of the298* appropriate factory. Likewise, the secure random parameter may299* be null in which case the default implementation will be used.300* <P>301* Only the first instance of a particular key and/or trust manager302* implementation type in the array is used. (For example, only303* the first javax.net.ssl.X509KeyManager in the array will be used.)304*305* @param km the sources of authentication keys or null306* @param tm the sources of peer authentication trust decisions or null307* @param random the source of randomness for this generator or null308* @throws KeyManagementException if this operation fails309*/310public final void init(KeyManager[] km, TrustManager[] tm,311SecureRandom random)312throws KeyManagementException {313contextSpi.engineInit(km, tm, random);314}315316/**317* Returns a {@code SocketFactory} object for this318* context.319*320* @return the {@code SocketFactory} object321* @throws UnsupportedOperationException if the underlying provider322* does not implement the operation.323* @throws IllegalStateException if the SSLContextImpl requires324* initialization and the {@code init()} has not been called325*/326public final SSLSocketFactory getSocketFactory() {327return contextSpi.engineGetSocketFactory();328}329330/**331* Returns a {@code ServerSocketFactory} object for332* this context.333*334* @return the {@code ServerSocketFactory} object335* @throws UnsupportedOperationException if the underlying provider336* does not implement the operation.337* @throws IllegalStateException if the SSLContextImpl requires338* initialization and the {@code init()} has not been called339*/340public final SSLServerSocketFactory getServerSocketFactory() {341return contextSpi.engineGetServerSocketFactory();342}343344/**345* Creates a new {@code SSLEngine} using this context.346* <P>347* Applications using this factory method are providing no hints348* for an internal session reuse strategy. If hints are desired,349* {@link #createSSLEngine(String, int)} should be used350* instead.351* <P>352* Some cipher suites (such as Kerberos) require remote hostname353* information, in which case this factory method should not be used.354*355* @implNote356* It is provider-specific if the returned SSLEngine uses client or357* server mode by default for the (D)TLS connection. The JDK SunJSSE358* provider implementation uses server mode by default. However, it359* is recommended to always set the desired mode explicitly by calling360* {@link SSLEngine#setUseClientMode(boolean) SSLEngine.setUseClientMode()}361* before invoking other methods of the SSLEngine.362*363* @return the {@code SSLEngine} object364* @throws UnsupportedOperationException if the underlying provider365* does not implement the operation.366* @throws IllegalStateException if the SSLContextImpl requires367* initialization and the {@code init()} has not been called368* @since 1.5369*/370public final SSLEngine createSSLEngine() {371try {372return contextSpi.engineCreateSSLEngine();373} catch (AbstractMethodError e) {374UnsupportedOperationException unsup =375new UnsupportedOperationException(376"Provider: " + getProvider() +377" doesn't support this operation");378unsup.initCause(e);379throw unsup;380}381}382383/**384* Creates a new {@code SSLEngine} using this context using385* advisory peer information.386* <P>387* Applications using this factory method are providing hints388* for an internal session reuse strategy.389* <P>390* Some cipher suites (such as Kerberos) require remote hostname391* information, in which case peerHost needs to be specified.392*393* @implNote394* It is provider-specific if the returned SSLEngine uses client or395* server mode by default for the (D)TLS connection. The JDK SunJSSE396* provider implementation uses server mode by default. However, it397* is recommended to always set the desired mode explicitly by calling398* {@link SSLEngine#setUseClientMode(boolean) SSLEngine.setUseClientMode()}399* before invoking other methods of the SSLEngine.400*401* @param peerHost the non-authoritative name of the host402* @param peerPort the non-authoritative port403* @return the new {@code SSLEngine} object404* @throws UnsupportedOperationException if the underlying provider405* does not implement the operation.406* @throws IllegalStateException if the SSLContextImpl requires407* initialization and the {@code init()} has not been called408* @since 1.5409*/410public final SSLEngine createSSLEngine(String peerHost, int peerPort) {411try {412return contextSpi.engineCreateSSLEngine(peerHost, peerPort);413} catch (AbstractMethodError e) {414UnsupportedOperationException unsup =415new UnsupportedOperationException(416"Provider: " + getProvider() +417" does not support this operation");418unsup.initCause(e);419throw unsup;420}421}422423/**424* Returns the server session context, which represents the set of425* SSL sessions available for use during the handshake phase of426* server-side SSL sockets.427* <P>428* This context may be unavailable in some environments, in which429* case this method returns null. For example, when the underlying430* SSL provider does not provide an implementation of SSLSessionContext431* interface, this method returns null. A non-null session context432* is returned otherwise.433*434* @return server session context bound to this SSL context435*/436public final SSLSessionContext getServerSessionContext() {437return contextSpi.engineGetServerSessionContext();438}439440/**441* Returns the client session context, which represents the set of442* SSL sessions available for use during the handshake phase of443* client-side SSL sockets.444* <P>445* This context may be unavailable in some environments, in which446* case this method returns null. For example, when the underlying447* SSL provider does not provide an implementation of SSLSessionContext448* interface, this method returns null. A non-null session context449* is returned otherwise.450*451* @return client session context bound to this SSL context452*/453public final SSLSessionContext getClientSessionContext() {454return contextSpi.engineGetClientSessionContext();455}456457/**458* Returns a copy of the SSLParameters indicating the default459* settings for this SSL context.460*461* <p>The parameters will always have the ciphersuites and protocols462* arrays set to non-null values.463*464* @return a copy of the SSLParameters object with the default settings465* @throws UnsupportedOperationException if the default SSL parameters466* could not be obtained.467* @since 1.6468*/469public final SSLParameters getDefaultSSLParameters() {470return contextSpi.engineGetDefaultSSLParameters();471}472473/**474* Returns a copy of the SSLParameters indicating the supported475* settings for this SSL context.476*477* <p>The parameters will always have the ciphersuites and protocols478* arrays set to non-null values.479*480* @return a copy of the SSLParameters object with the supported481* settings482* @throws UnsupportedOperationException if the supported SSL parameters483* could not be obtained.484* @since 1.6485*/486public final SSLParameters getSupportedSSLParameters() {487return contextSpi.engineGetSupportedSSLParameters();488}489490}491492493