Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/javax/security/sasl/Sasl.java
38918 views
/*1* Copyright (c) 1999, 2019, 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.security.sasl;2627import javax.security.auth.callback.CallbackHandler;28import java.security.AccessController;29import java.security.PrivilegedAction;30import java.util.ArrayList;31import java.util.Enumeration;32import java.util.Iterator;33import java.util.List;34import java.util.Map;35import java.util.Set;36import java.util.HashSet;37import java.util.Collections;38import java.security.Provider;39import java.security.Security;40import java.util.logging.Level;41import java.util.logging.Logger;4243/**44* A static class for creating SASL clients and servers.45*<p>46* This class defines the policy of how to locate, load, and instantiate47* SASL clients and servers.48*<p>49* For example, an application or library gets a SASL client by doing50* something like:51*<blockquote><pre>52* SaslClient sc = Sasl.createSaslClient(mechanisms,53* authorizationId, protocol, serverName, props, callbackHandler);54*</pre></blockquote>55* It can then proceed to use the instance to create an authentication connection.56*<p>57* Similarly, a server gets a SASL server by using code that looks as follows:58*<blockquote><pre>59* SaslServer ss = Sasl.createSaslServer(mechanism,60* protocol, serverName, props, callbackHandler);61*</pre></blockquote>62*63* @since 1.564*65* @author Rosanna Lee66* @author Rob Weltman67*/68public class Sasl {6970private static List<String> disabledMechanisms = new ArrayList<>();7172static {73String prop = AccessController.doPrivileged(74(PrivilegedAction<String>)75() -> Security.getProperty("jdk.sasl.disabledMechanisms"));7677if (prop != null) {78for (String s : prop.split("\\s*,\\s*")) {79if (!s.isEmpty()) {80disabledMechanisms.add(s);81}82}83}84}8586private static final String SASL_LOGGER_NAME = "javax.security.sasl";8788/**89* Logger for debug messages90*/91private static final Logger logger = Logger.getLogger(SASL_LOGGER_NAME);9293// Cannot create one of these94private Sasl() {95}9697/**98* The name of a property that specifies the quality-of-protection to use.99* The property contains a comma-separated, ordered list100* of quality-of-protection values that the101* client or server is willing to support. A qop value is one of102* <ul>103* <li>{@code "auth"} - authentication only</li>104* <li>{@code "auth-int"} - authentication plus integrity protection</li>105* <li>{@code "auth-conf"} - authentication plus integrity and confidentiality106* protection</li>107* </ul>108*109* The order of the list specifies the preference order of the client or110* server. If this property is absent, the default qop is {@code "auth"}.111* The value of this constant is {@code "javax.security.sasl.qop"}.112*/113public static final String QOP = "javax.security.sasl.qop";114115/**116* The name of a property that specifies the cipher strength to use.117* The property contains a comma-separated, ordered list118* of cipher strength values that119* the client or server is willing to support. A strength value is one of120* <ul>121* <li>{@code "low"}</li>122* <li>{@code "medium"}</li>123* <li>{@code "high"}</li>124* </ul>125* The order of the list specifies the preference order of the client or126* server. An implementation should allow configuration of the meaning127* of these values. An application may use the Java Cryptography128* Extension (JCE) with JCE-aware mechanisms to control the selection of129* cipher suites that match the strength values.130* <BR>131* If this property is absent, the default strength is132* {@code "high,medium,low"}.133* The value of this constant is {@code "javax.security.sasl.strength"}.134*/135public static final String STRENGTH = "javax.security.sasl.strength";136137/**138* The name of a property that specifies whether the139* server must authenticate to the client. The property contains140* {@code "true"} if the server must141* authenticate the to client; {@code "false"} otherwise.142* The default is {@code "false"}.143* <br>The value of this constant is144* {@code "javax.security.sasl.server.authentication"}.145*/146public static final String SERVER_AUTH =147"javax.security.sasl.server.authentication";148149/**150* The name of a property that specifies the bound server name for151* an unbound server. A server is created as an unbound server by setting152* the {@code serverName} argument in {@link #createSaslServer} as null.153* The property contains the bound host name after the authentication154* exchange has completed. It is only available on the server side.155* <br>The value of this constant is156* {@code "javax.security.sasl.bound.server.name"}.157*/158public static final String BOUND_SERVER_NAME =159"javax.security.sasl.bound.server.name";160161/**162* The name of a property that specifies the maximum size of the receive163* buffer in bytes of {@code SaslClient}/{@code SaslServer}.164* The property contains the string representation of an integer.165* <br>If this property is absent, the default size166* is defined by the mechanism.167* <br>The value of this constant is {@code "javax.security.sasl.maxbuffer"}.168*/169public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer";170171/**172* The name of a property that specifies the maximum size of the raw send173* buffer in bytes of {@code SaslClient}/{@code SaslServer}.174* The property contains the string representation of an integer.175* The value of this property is negotiated between the client and server176* during the authentication exchange.177* <br>The value of this constant is {@code "javax.security.sasl.rawsendsize"}.178*/179public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize";180181/**182* The name of a property that specifies whether to reuse previously183* authenticated session information. The property contains "true" if the184* mechanism implementation may attempt to reuse previously authenticated185* session information; it contains "false" if the implementation must186* not reuse previously authenticated session information. A setting of187* "true" serves only as a hint: it does not necessarily entail actual188* reuse because reuse might not be possible due to a number of reasons,189* including, but not limited to, lack of mechanism support for reuse,190* expiration of reusable information, and the peer's refusal to support191* reuse.192*193* The property's default value is "false". The value of this constant194* is "javax.security.sasl.reuse".195*196* Note that all other parameters and properties required to create a197* SASL client/server instance must be provided regardless of whether198* this property has been supplied. That is, you cannot supply any less199* information in anticipation of reuse.200*201* Mechanism implementations that support reuse might allow customization202* of its implementation, for factors such as cache size, timeouts, and203* criteria for reusability. Such customizations are204* implementation-dependent.205*/206public static final String REUSE = "javax.security.sasl.reuse";207208/**209* The name of a property that specifies210* whether mechanisms susceptible to simple plain passive attacks (e.g.,211* "PLAIN") are not permitted. The property212* contains {@code "true"} if such mechanisms are not permitted;213* {@code "false"} if such mechanisms are permitted.214* The default is {@code "false"}.215* <br>The value of this constant is216* {@code "javax.security.sasl.policy.noplaintext"}.217*/218public static final String POLICY_NOPLAINTEXT =219"javax.security.sasl.policy.noplaintext";220221/**222* The name of a property that specifies whether223* mechanisms susceptible to active (non-dictionary) attacks224* are not permitted.225* The property contains {@code "true"}226* if mechanisms susceptible to active attacks227* are not permitted; {@code "false"} if such mechanisms are permitted.228* The default is {@code "false"}.229* <br>The value of this constant is230* {@code "javax.security.sasl.policy.noactive"}.231*/232public static final String POLICY_NOACTIVE =233"javax.security.sasl.policy.noactive";234235/**236* The name of a property that specifies whether237* mechanisms susceptible to passive dictionary attacks are not permitted.238* The property contains {@code "true"}239* if mechanisms susceptible to dictionary attacks are not permitted;240* {@code "false"} if such mechanisms are permitted.241* The default is {@code "false"}.242*<br>243* The value of this constant is244* {@code "javax.security.sasl.policy.nodictionary"}.245*/246public static final String POLICY_NODICTIONARY =247"javax.security.sasl.policy.nodictionary";248249/**250* The name of a property that specifies whether mechanisms that accept251* anonymous login are not permitted. The property contains {@code "true"}252* if mechanisms that accept anonymous login are not permitted;253* {@code "false"}254* if such mechanisms are permitted. The default is {@code "false"}.255*<br>256* The value of this constant is257* {@code "javax.security.sasl.policy.noanonymous"}.258*/259public static final String POLICY_NOANONYMOUS =260"javax.security.sasl.policy.noanonymous";261262/**263* The name of a property that specifies whether mechanisms that implement264* forward secrecy between sessions are required. Forward secrecy265* means that breaking into one session will not automatically266* provide information for breaking into future sessions.267* The property268* contains {@code "true"} if mechanisms that implement forward secrecy269* between sessions are required; {@code "false"} if such mechanisms270* are not required. The default is {@code "false"}.271*<br>272* The value of this constant is273* {@code "javax.security.sasl.policy.forward"}.274*/275public static final String POLICY_FORWARD_SECRECY =276"javax.security.sasl.policy.forward";277278/**279* The name of a property that specifies whether280* mechanisms that pass client credentials are required. The property281* contains {@code "true"} if mechanisms that pass282* client credentials are required; {@code "false"}283* if such mechanisms are not required. The default is {@code "false"}.284*<br>285* The value of this constant is286* {@code "javax.security.sasl.policy.credentials"}.287*/288public static final String POLICY_PASS_CREDENTIALS =289"javax.security.sasl.policy.credentials";290291/**292* The name of a property that specifies the credentials to use.293* The property contains a mechanism-specific Java credential object.294* Mechanism implementations may examine the value of this property295* to determine whether it is a class that they support.296* The property may be used to supply credentials to a mechanism that297* supports delegated authentication.298*<br>299* The value of this constant is300* {@code "javax.security.sasl.credentials"}.301*/302public static final String CREDENTIALS = "javax.security.sasl.credentials";303304/**305* Creates a {@code SaslClient} using the parameters supplied.306*307* This method uses the308<a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>, described in the309* "Java Cryptography Architecture API Specification & Reference", for310* locating and selecting a {@code SaslClient} implementation.311*312* First, it313* obtains an ordered list of {@code SaslClientFactory} instances from314* the registered security providers for the "SaslClientFactory" service315* and the specified SASL mechanism(s). It then invokes316* {@code createSaslClient()} on each factory instance on the list317* until one produces a non-null {@code SaslClient} instance. It returns318* the non-null {@code SaslClient} instance, or null if the search fails319* to produce a non-null {@code SaslClient} instance.320*<p>321* A security provider for SaslClientFactory registers with the322* JCA Security Provider Framework keys of the form <br>323* {@code SaslClientFactory.}<em>{@code mechanism_name}</em>324* <br>325* and values that are class names of implementations of326* {@code javax.security.sasl.SaslClientFactory}.327*328* For example, a provider that contains a factory class,329* {@code com.wiz.sasl.digest.ClientFactory}, that supports the330* "DIGEST-MD5" mechanism would register the following entry with the JCA:331* {@code SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory}332*<p>333* See the334* "Java Cryptography Architecture API Specification & Reference"335* for information about how to install and configure security service336* providers.337* <p>338* If a mechanism is listed in the {@code jdk.sasl.disabledMechanisms}339* security property, it will be ignored and won't be negotiated.340*341* @param mechanisms The non-null list of mechanism names to try. Each is the342* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").343* @param authorizationId The possibly null protocol-dependent344* identification to be used for authorization.345* If null or empty, the server derives an authorization346* ID from the client's authentication credentials.347* When the SASL authentication completes successfully,348* the specified entity is granted access.349*350* @param protocol The non-null string name of the protocol for which351* the authentication is being performed (e.g., "ldap").352*353* @param serverName The non-null fully-qualified host name of the server354* to authenticate to.355*356* @param props The possibly null set of properties used to357* select the SASL mechanism and to configure the authentication358* exchange of the selected mechanism.359* For example, if {@code props} contains the360* {@code Sasl.POLICY_NOPLAINTEXT} property with the value361* {@code "true"}, then the selected362* SASL mechanism must not be susceptible to simple plain passive attacks.363* In addition to the standard properties declared in this class,364* other, possibly mechanism-specific, properties can be included.365* Properties not relevant to the selected mechanism are ignored,366* including any map entries with non-String keys.367*368* @param cbh The possibly null callback handler to used by the SASL369* mechanisms to get further information from the application/library370* to complete the authentication. For example, a SASL mechanism might371* require the authentication ID, password and realm from the caller.372* The authentication ID is requested by using a {@code NameCallback}.373* The password is requested by using a {@code PasswordCallback}.374* The realm is requested by using a {@code RealmChoiceCallback} if there is a list375* of realms to choose from, and by using a {@code RealmCallback} if376* the realm must be entered.377*378*@return A possibly null {@code SaslClient} created using the parameters379* supplied. If null, cannot find a {@code SaslClientFactory}380* that will produce one.381*@exception SaslException If cannot create a {@code SaslClient} because382* of an error.383*/384public static SaslClient createSaslClient(385String[] mechanisms,386String authorizationId,387String protocol,388String serverName,389Map<String,?> props,390CallbackHandler cbh) throws SaslException {391392SaslClient mech = null;393SaslClientFactory fac;394String className;395String mechName;396397for (int i = 0; i < mechanisms.length; i++) {398if ((mechName=mechanisms[i]) == null) {399throw new NullPointerException(400"Mechanism name cannot be null");401} else if (mechName.length() == 0) {402continue;403} else if (isDisabled(mechName)) {404logger.log(Level.FINE,405"Disabled " + mechName + " mechanism ignored");406continue;407}408String mechFilter = "SaslClientFactory." + mechName;409Provider[] provs = Security.getProviders(mechFilter);410for (int j = 0; provs != null && j < provs.length; j++) {411className = provs[j].getProperty(mechFilter);412if (className == null) {413// Case is ignored414continue;415}416417fac = (SaslClientFactory) loadFactory(provs[j], className);418if (fac != null) {419mech = fac.createSaslClient(420new String[]{mechanisms[i]}, authorizationId,421protocol, serverName, props, cbh);422if (mech != null) {423return mech;424}425}426}427}428429return null;430}431432private static Object loadFactory(Provider p, String className)433throws SaslException {434try {435/*436* Load the implementation class with the same class loader437* that was used to load the provider.438* In order to get the class loader of a class, the439* caller's class loader must be the same as or an ancestor of440* the class loader being returned. Otherwise, the caller must441* have "getClassLoader" permission, or a SecurityException442* will be thrown.443*/444ClassLoader cl = p.getClass().getClassLoader();445Class<?> implClass;446implClass = Class.forName(className, true, cl);447return implClass.newInstance();448} catch (ClassNotFoundException e) {449throw new SaslException("Cannot load class " + className, e);450} catch (InstantiationException e) {451throw new SaslException("Cannot instantiate class " + className, e);452} catch (IllegalAccessException e) {453throw new SaslException("Cannot access class " + className, e);454} catch (SecurityException e) {455throw new SaslException("Cannot access class " + className, e);456}457}458459460/**461* Creates a {@code SaslServer} for the specified mechanism.462*463* This method uses the464<a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>,465* described in the466* "Java Cryptography Architecture API Specification & Reference", for467* locating and selecting a {@code SaslServer} implementation.468*469* First, it470* obtains an ordered list of {@code SaslServerFactory} instances from471* the registered security providers for the "SaslServerFactory" service472* and the specified mechanism. It then invokes473* {@code createSaslServer()} on each factory instance on the list474* until one produces a non-null {@code SaslServer} instance. It returns475* the non-null {@code SaslServer} instance, or null if the search fails476* to produce a non-null {@code SaslServer} instance.477*<p>478* A security provider for SaslServerFactory registers with the479* JCA Security Provider Framework keys of the form <br>480* {@code SaslServerFactory.}<em>{@code mechanism_name}</em>481* <br>482* and values that are class names of implementations of483* {@code javax.security.sasl.SaslServerFactory}.484*485* For example, a provider that contains a factory class,486* {@code com.wiz.sasl.digest.ServerFactory}, that supports the487* "DIGEST-MD5" mechanism would register the following entry with the JCA:488* {@code SaslServerFactory.DIGEST-MD5 com.wiz.sasl.digest.ServerFactory}489*<p>490* See the491* "Java Cryptography Architecture API Specification & Reference"492* for information about how to install and configure security493* service providers.494* <p>495* If {@code mechanism} is listed in the {@code jdk.sasl.disabledMechanisms}496* security property, it will be ignored and this method returns {@code null}.497*498* @param mechanism The non-null mechanism name. It must be an499* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").500* @param protocol The non-null string name of the protocol for which501* the authentication is being performed (e.g., "ldap").502* @param serverName The fully qualified host name of the server, or null503* if the server is not bound to any specific host name. If the mechanism504* does not allow an unbound server, a {@code SaslException} will505* be thrown.506* @param props The possibly null set of properties used to507* select the SASL mechanism and to configure the authentication508* exchange of the selected mechanism.509* For example, if {@code props} contains the510* {@code Sasl.POLICY_NOPLAINTEXT} property with the value511* {@code "true"}, then the selected512* SASL mechanism must not be susceptible to simple plain passive attacks.513* In addition to the standard properties declared in this class,514* other, possibly mechanism-specific, properties can be included.515* Properties not relevant to the selected mechanism are ignored,516* including any map entries with non-String keys.517*518* @param cbh The possibly null callback handler to used by the SASL519* mechanisms to get further information from the application/library520* to complete the authentication. For example, a SASL mechanism might521* require the authentication ID, password and realm from the caller.522* The authentication ID is requested by using a {@code NameCallback}.523* The password is requested by using a {@code PasswordCallback}.524* The realm is requested by using a {@code RealmChoiceCallback} if there is a list525* of realms to choose from, and by using a {@code RealmCallback} if526* the realm must be entered.527*528*@return A possibly null {@code SaslServer} created using the parameters529* supplied. If null, cannot find a {@code SaslServerFactory}530* that will produce one.531*@exception SaslException If cannot create a {@code SaslServer} because532* of an error.533**/534public static SaslServer535createSaslServer(String mechanism,536String protocol,537String serverName,538Map<String,?> props,539javax.security.auth.callback.CallbackHandler cbh)540throws SaslException {541542SaslServer mech = null;543SaslServerFactory fac;544String className;545546if (mechanism == null) {547throw new NullPointerException("Mechanism name cannot be null");548} else if (mechanism.length() == 0) {549return null;550} else if (isDisabled(mechanism)) {551logger.log(Level.FINE,552"Disabled " + mechanism + " mechanism ignored");553return null;554}555556String mechFilter = "SaslServerFactory." + mechanism;557Provider[] provs = Security.getProviders(mechFilter);558for (int j = 0; provs != null && j < provs.length; j++) {559className = provs[j].getProperty(mechFilter);560if (className == null) {561throw new SaslException("Provider does not support " +562mechFilter);563}564fac = (SaslServerFactory) loadFactory(provs[j], className);565if (fac != null) {566mech = fac.createSaslServer(567mechanism, protocol, serverName, props, cbh);568if (mech != null) {569return mech;570}571}572}573574return null;575}576577/**578* Gets an enumeration of known factories for producing {@code SaslClient}.579* This method uses the same algorithm for locating factories as580* {@code createSaslClient()}.581* @return A non-null enumeration of known factories for producing582* {@code SaslClient}.583* @see #createSaslClient584*/585public static Enumeration<SaslClientFactory> getSaslClientFactories() {586Set<Object> facs = getFactories("SaslClientFactory");587final Iterator<Object> iter = facs.iterator();588return new Enumeration<SaslClientFactory>() {589public boolean hasMoreElements() {590return iter.hasNext();591}592public SaslClientFactory nextElement() {593return (SaslClientFactory)iter.next();594}595};596}597598/**599* Gets an enumeration of known factories for producing {@code SaslServer}.600* This method uses the same algorithm for locating factories as601* {@code createSaslServer()}.602* @return A non-null enumeration of known factories for producing603* {@code SaslServer}.604* @see #createSaslServer605*/606public static Enumeration<SaslServerFactory> getSaslServerFactories() {607Set<Object> facs = getFactories("SaslServerFactory");608final Iterator<Object> iter = facs.iterator();609return new Enumeration<SaslServerFactory>() {610public boolean hasMoreElements() {611return iter.hasNext();612}613public SaslServerFactory nextElement() {614return (SaslServerFactory)iter.next();615}616};617}618619private static Set<Object> getFactories(String serviceName) {620HashSet<Object> result = new HashSet<Object>();621622if ((serviceName == null) || (serviceName.length() == 0) ||623(serviceName.endsWith("."))) {624return result;625}626627628Provider[] providers = Security.getProviders();629HashSet<String> classes = new HashSet<String>();630Object fac;631632for (int i = 0; i < providers.length; i++) {633classes.clear();634635// Check the keys for each provider.636for (Enumeration<Object> e = providers[i].keys(); e.hasMoreElements(); ) {637String currentKey = (String)e.nextElement();638if (currentKey.startsWith(serviceName)) {639// We should skip the currentKey if it contains a640// whitespace. The reason is: such an entry in the641// provider property contains attributes for the642// implementation of an algorithm. We are only interested643// in entries which lead to the implementation644// classes.645if (currentKey.indexOf(" ") < 0) {646String className = providers[i].getProperty(currentKey);647if (!classes.contains(className)) {648classes.add(className);649try {650fac = loadFactory(providers[i], className);651if (fac != null) {652result.add(fac);653}654}catch (Exception ignore) {655}656}657}658}659}660}661return Collections.unmodifiableSet(result);662}663664private static boolean isDisabled(String name) {665return disabledMechanisms.contains(name);666}667}668669670