Path: blob/master/src/java.security.sasl/share/classes/javax/security/sasl/Sasl.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.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.InvalidParameterException;39import java.security.NoSuchAlgorithmException;40import java.security.Provider;41import java.security.Provider.Service;42import java.security.Security;43import java.util.logging.Level;44import java.util.logging.Logger;4546/**47* A static class for creating SASL clients and servers.48*<p>49* This class defines the policy of how to locate, load, and instantiate50* SASL clients and servers.51*<p>52* For example, an application or library gets a SASL client by doing53* something like:54*<blockquote><pre>55* SaslClient sc = Sasl.createSaslClient(mechanisms,56* authorizationId, protocol, serverName, props, callbackHandler);57*</pre></blockquote>58* It can then proceed to use the instance to create an authentication connection.59*<p>60* Similarly, a server gets a SASL server by using code that looks as follows:61*<blockquote><pre>62* SaslServer ss = Sasl.createSaslServer(mechanism,63* protocol, serverName, props, callbackHandler);64*</pre></blockquote>65*66* @since 1.567*68* @author Rosanna Lee69* @author Rob Weltman70*/71public class Sasl {7273private static List<String> disabledMechanisms = new ArrayList<>();7475static {76@SuppressWarnings("removal")77String prop = AccessController.doPrivileged(78(PrivilegedAction<String>)79() -> Security.getProperty("jdk.sasl.disabledMechanisms"));8081if (prop != null) {82for (String s : prop.split("\\s*,\\s*")) {83if (!s.isEmpty()) {84disabledMechanisms.add(s);85}86}87}88}8990private static final String SASL_LOGGER_NAME = "javax.security.sasl";9192/**93* Logger for debug messages94*/95private static final Logger logger = Logger.getLogger(SASL_LOGGER_NAME);9697// Cannot create one of these98private Sasl() {99}100101/**102* The name of a property that specifies the quality-of-protection to use.103* The property contains a comma-separated, ordered list104* of quality-of-protection values that the105* client or server is willing to support. A qop value is one of106* <ul>107* <li>{@code "auth"} - authentication only</li>108* <li>{@code "auth-int"} - authentication plus integrity protection</li>109* <li>{@code "auth-conf"} - authentication plus integrity and confidentiality110* protection</li>111* </ul>112*113* The order of the list specifies the preference order of the client or114* server. If this property is absent, the default qop is {@code "auth"}.115* The value of this constant is {@code "javax.security.sasl.qop"}.116*/117public static final String QOP = "javax.security.sasl.qop";118119/**120* The name of a property that specifies the cipher strength to use.121* The property contains a comma-separated, ordered list122* of cipher strength values that123* the client or server is willing to support. A strength value is one of124* <ul>125* <li>{@code "low"}</li>126* <li>{@code "medium"}</li>127* <li>{@code "high"}</li>128* </ul>129* The order of the list specifies the preference order of the client or130* server. An implementation should allow configuration of the meaning131* of these values. An application may use the Java Cryptography132* Extension (JCE) with JCE-aware mechanisms to control the selection of133* cipher suites that match the strength values.134* <BR>135* If this property is absent, the default strength is136* {@code "high,medium,low"}.137* The value of this constant is {@code "javax.security.sasl.strength"}.138*/139public static final String STRENGTH = "javax.security.sasl.strength";140141/**142* The name of a property that specifies whether the143* server must authenticate to the client. The property contains144* {@code "true"} if the server must145* authenticate the to client; {@code "false"} otherwise.146* The default is {@code "false"}.147* <br>The value of this constant is148* {@code "javax.security.sasl.server.authentication"}.149*/150public static final String SERVER_AUTH =151"javax.security.sasl.server.authentication";152153/**154* The name of a property that specifies the bound server name for155* an unbound server. A server is created as an unbound server by setting156* the {@code serverName} argument in {@link #createSaslServer} as null.157* The property contains the bound host name after the authentication158* exchange has completed. It is only available on the server side.159* <br>The value of this constant is160* {@code "javax.security.sasl.bound.server.name"}.161*/162public static final String BOUND_SERVER_NAME =163"javax.security.sasl.bound.server.name";164165/**166* The name of a property that specifies the maximum size of the receive167* buffer in bytes of {@code SaslClient}/{@code SaslServer}.168* The property contains the string representation of an integer.169* <br>If this property is absent, the default size170* is defined by the mechanism.171* <br>The value of this constant is {@code "javax.security.sasl.maxbuffer"}.172*/173public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer";174175/**176* The name of a property that specifies the maximum size of the raw send177* buffer in bytes of {@code SaslClient}/{@code SaslServer}.178* The property contains the string representation of an integer.179* The value of this property is negotiated between the client and server180* during the authentication exchange.181* <br>The value of this constant is {@code "javax.security.sasl.rawsendsize"}.182*/183public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize";184185/**186* The name of a property that specifies whether to reuse previously187* authenticated session information. The property contains "true" if the188* mechanism implementation may attempt to reuse previously authenticated189* session information; it contains "false" if the implementation must190* not reuse previously authenticated session information. A setting of191* "true" serves only as a hint: it does not necessarily entail actual192* reuse because reuse might not be possible due to a number of reasons,193* including, but not limited to, lack of mechanism support for reuse,194* expiration of reusable information, and the peer's refusal to support195* reuse.196*197* The property's default value is "false". The value of this constant198* is "javax.security.sasl.reuse".199*200* Note that all other parameters and properties required to create a201* SASL client/server instance must be provided regardless of whether202* this property has been supplied. That is, you cannot supply any less203* information in anticipation of reuse.204*205* Mechanism implementations that support reuse might allow customization206* of its implementation, for factors such as cache size, timeouts, and207* criteria for reusability. Such customizations are208* implementation-dependent.209*/210public static final String REUSE = "javax.security.sasl.reuse";211212/**213* The name of a property that specifies214* whether mechanisms susceptible to simple plain passive attacks (e.g.,215* "PLAIN") are not permitted. The property216* contains {@code "true"} if such mechanisms are not permitted;217* {@code "false"} if such mechanisms are permitted.218* The default is {@code "false"}.219* <br>The value of this constant is220* {@code "javax.security.sasl.policy.noplaintext"}.221*/222public static final String POLICY_NOPLAINTEXT =223"javax.security.sasl.policy.noplaintext";224225/**226* The name of a property that specifies whether227* mechanisms susceptible to active (non-dictionary) attacks228* are not permitted.229* The property contains {@code "true"}230* if mechanisms susceptible to active attacks231* are not permitted; {@code "false"} if such mechanisms are permitted.232* The default is {@code "false"}.233* <br>The value of this constant is234* {@code "javax.security.sasl.policy.noactive"}.235*/236public static final String POLICY_NOACTIVE =237"javax.security.sasl.policy.noactive";238239/**240* The name of a property that specifies whether241* mechanisms susceptible to passive dictionary attacks are not permitted.242* The property contains {@code "true"}243* if mechanisms susceptible to dictionary attacks are not permitted;244* {@code "false"} if such mechanisms are permitted.245* The default is {@code "false"}.246*<br>247* The value of this constant is248* {@code "javax.security.sasl.policy.nodictionary"}.249*/250public static final String POLICY_NODICTIONARY =251"javax.security.sasl.policy.nodictionary";252253/**254* The name of a property that specifies whether mechanisms that accept255* anonymous login are not permitted. The property contains {@code "true"}256* if mechanisms that accept anonymous login are not permitted;257* {@code "false"}258* if such mechanisms are permitted. The default is {@code "false"}.259*<br>260* The value of this constant is261* {@code "javax.security.sasl.policy.noanonymous"}.262*/263public static final String POLICY_NOANONYMOUS =264"javax.security.sasl.policy.noanonymous";265266/**267* The name of a property that specifies whether mechanisms that implement268* forward secrecy between sessions are required. Forward secrecy269* means that breaking into one session will not automatically270* provide information for breaking into future sessions.271* The property272* contains {@code "true"} if mechanisms that implement forward secrecy273* between sessions are required; {@code "false"} if such mechanisms274* are not required. The default is {@code "false"}.275*<br>276* The value of this constant is277* {@code "javax.security.sasl.policy.forward"}.278*/279public static final String POLICY_FORWARD_SECRECY =280"javax.security.sasl.policy.forward";281282/**283* The name of a property that specifies whether284* mechanisms that pass client credentials are required. The property285* contains {@code "true"} if mechanisms that pass286* client credentials are required; {@code "false"}287* if such mechanisms are not required. The default is {@code "false"}.288*<br>289* The value of this constant is290* {@code "javax.security.sasl.policy.credentials"}.291*/292public static final String POLICY_PASS_CREDENTIALS =293"javax.security.sasl.policy.credentials";294295/**296* The name of a property that specifies the credentials to use.297* The property contains a mechanism-specific Java credential object.298* Mechanism implementations may examine the value of this property299* to determine whether it is a class that they support.300* The property may be used to supply credentials to a mechanism that301* supports delegated authentication.302*<br>303* The value of this constant is304* {@code "javax.security.sasl.credentials"}.305*/306public static final String CREDENTIALS = "javax.security.sasl.credentials";307308/**309* Creates a {@code SaslClient} using the parameters supplied.310*311* This method uses the312* {@extLink security_guide_jca JCA Security Provider Framework},313* described in the314* "Java Cryptography Architecture (JCA) Reference Guide", for315* locating and selecting a {@code SaslClient} implementation.316*317* First, it318* obtains an ordered list of {@code SaslClientFactory} instances from319* the registered security providers for the "SaslClientFactory" service320* and the specified SASL mechanism(s). It then invokes321* {@code createSaslClient()} on each factory instance on the list322* until one produces a non-null {@code SaslClient} instance. It returns323* the non-null {@code SaslClient} instance, or null if the search fails324* to produce a non-null {@code SaslClient} instance.325*<p>326* A security provider for SaslClientFactory registers with the327* JCA Security Provider Framework keys of the form <br>328* {@code SaslClientFactory.}<em>{@code mechanism_name}</em>329* <br>330* and values that are class names of implementations of331* {@code javax.security.sasl.SaslClientFactory}.332*333* For example, a provider that contains a factory class,334* {@code com.wiz.sasl.digest.ClientFactory}, that supports the335* "DIGEST-MD5" mechanism would register the following entry with the JCA:336* {@code SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory}337*<p>338* See the339* "Java Cryptography Architecture API Specification & Reference"340* for information about how to install and configure security service341* providers.342*343* @implNote344* The JDK Reference Implementation additionally uses the345* {@code jdk.security.provider.preferred}346* {@link Security#getProperty(String) Security} property to determine347* the preferred provider order for the specified algorithm. This348* may be different than the order of providers returned by349* {@link Security#getProviders() Security.getProviders()}.350* <p>351* If a mechanism is listed in the {@code jdk.sasl.disabledMechanisms}352* security property, it will be ignored and won't be negotiated.353*354* @param mechanisms The non-null list of mechanism names to try. Each is the355* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").356* @param authorizationId The possibly null protocol-dependent357* identification to be used for authorization.358* If null or empty, the server derives an authorization359* ID from the client's authentication credentials.360* When the SASL authentication completes successfully,361* the specified entity is granted access.362*363* @param protocol The non-null string name of the protocol for which364* the authentication is being performed (e.g., "ldap").365*366* @param serverName The non-null fully-qualified host name of the server367* to authenticate to.368*369* @param props The possibly null set of properties used to370* select the SASL mechanism and to configure the authentication371* exchange of the selected mechanism.372* For example, if {@code props} contains the373* {@code Sasl.POLICY_NOPLAINTEXT} property with the value374* {@code "true"}, then the selected375* SASL mechanism must not be susceptible to simple plain passive attacks.376* In addition to the standard properties declared in this class,377* other, possibly mechanism-specific, properties can be included.378* Properties not relevant to the selected mechanism are ignored,379* including any map entries with non-String keys.380*381* @param cbh The possibly null callback handler to used by the SASL382* mechanisms to get further information from the application/library383* to complete the authentication. For example, a SASL mechanism might384* require the authentication ID, password and realm from the caller.385* The authentication ID is requested by using a {@code NameCallback}.386* The password is requested by using a {@code PasswordCallback}.387* The realm is requested by using a {@code RealmChoiceCallback} if there is a list388* of realms to choose from, and by using a {@code RealmCallback} if389* the realm must be entered.390*391*@return A possibly null {@code SaslClient} created using the parameters392* supplied. If null, cannot find a {@code SaslClientFactory}393* that will produce one.394*@exception SaslException If cannot create a {@code SaslClient} because395* of an error.396*/397public static SaslClient createSaslClient(398String[] mechanisms,399String authorizationId,400String protocol,401String serverName,402Map<String,?> props,403CallbackHandler cbh) throws SaslException {404405SaslClient mech = null;406SaslClientFactory fac;407Service service;408String mechName;409410for (int i = 0; i < mechanisms.length; i++) {411if ((mechName=mechanisms[i]) == null) {412throw new NullPointerException(413"Mechanism name cannot be null");414} else if (mechName.length() == 0) {415continue;416} else if (isDisabled(mechName)) {417logger.log(Level.FINE,418"Disabled " + mechName + " mechanism ignored");419continue;420}421String type = "SaslClientFactory";422Provider[] provs = Security.getProviders(type + "." + mechName);423if (provs != null) {424for (Provider p : provs) {425service = p.getService(type, mechName);426if (service == null) {427// no such service exists428continue;429}430431fac = (SaslClientFactory) loadFactory(service);432if (fac != null) {433mech = fac.createSaslClient(434new String[]{mechanisms[i]}, authorizationId,435protocol, serverName, props, cbh);436if (mech != null) {437return mech;438}439}440}441}442}443return null;444}445446private static Object loadFactory(Service service)447throws SaslException {448try {449/*450* Load the implementation class with the same class loader451* that was used to load the provider.452* In order to get the class loader of a class, the453* caller's class loader must be the same as or an ancestor of454* the class loader being returned. Otherwise, the caller must455* have "getClassLoader" permission, or a SecurityException456* will be thrown.457*/458return service.newInstance(null);459} catch (InvalidParameterException | NoSuchAlgorithmException e) {460throw new SaslException("Cannot instantiate service " + service, e);461}462}463464465/**466* Creates a {@code SaslServer} for the specified mechanism.467*468* This method uses the469* {@extLink security_guide_jca JCA Security Provider Framework},470* described in the471* "Java Cryptography Architecture (JCA) Reference Guide", for472* locating and selecting a {@code SaslClient} implementation.473*474* First, it475* obtains an ordered list of {@code SaslServerFactory} instances from476* the registered security providers for the "SaslServerFactory" service477* and the specified mechanism. It then invokes478* {@code createSaslServer()} on each factory instance on the list479* until one produces a non-null {@code SaslServer} instance. It returns480* the non-null {@code SaslServer} instance, or null if the search fails481* to produce a non-null {@code SaslServer} instance.482*<p>483* A security provider for SaslServerFactory registers with the484* JCA Security Provider Framework keys of the form <br>485* {@code SaslServerFactory.}<em>{@code mechanism_name}</em>486* <br>487* and values that are class names of implementations of488* {@code javax.security.sasl.SaslServerFactory}.489*490* For example, a provider that contains a factory class,491* {@code com.wiz.sasl.digest.ServerFactory}, that supports the492* "DIGEST-MD5" mechanism would register the following entry with the JCA:493* {@code SaslServerFactory.DIGEST-MD5 com.wiz.sasl.digest.ServerFactory}494*<p>495* See the496* "Java Cryptography Architecture API Specification & Reference"497* for information about how to install and configure security498* service providers.499*500* @implNote501* The JDK Reference Implementation additionally uses the502* {@code jdk.security.provider.preferred}503* {@link Security#getProperty(String) Security} property to determine504* the preferred provider order for the specified algorithm. This505* may be different than the order of providers returned by506* {@link Security#getProviders() Security.getProviders()}.507* <p>508* If {@code mechanism} is listed in the {@code jdk.sasl.disabledMechanisms}509* security property, it will be ignored and this method returns {@code null}.510*511* @param mechanism The non-null mechanism name. It must be an512* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").513* @param protocol The non-null string name of the protocol for which514* the authentication is being performed (e.g., "ldap").515* @param serverName The fully qualified host name of the server, or null516* if the server is not bound to any specific host name. If the mechanism517* does not allow an unbound server, a {@code SaslException} will518* be thrown.519* @param props The possibly null set of properties used to520* select the SASL mechanism and to configure the authentication521* exchange of the selected mechanism.522* For example, if {@code props} contains the523* {@code Sasl.POLICY_NOPLAINTEXT} property with the value524* {@code "true"}, then the selected525* SASL mechanism must not be susceptible to simple plain passive attacks.526* In addition to the standard properties declared in this class,527* other, possibly mechanism-specific, properties can be included.528* Properties not relevant to the selected mechanism are ignored,529* including any map entries with non-String keys.530*531* @param cbh The possibly null callback handler to used by the SASL532* mechanisms to get further information from the application/library533* to complete the authentication. For example, a SASL mechanism might534* require the authentication ID, password and realm from the caller.535* The authentication ID is requested by using a {@code NameCallback}.536* The password is requested by using a {@code PasswordCallback}.537* The realm is requested by using a {@code RealmChoiceCallback} if there is a list538* of realms to choose from, and by using a {@code RealmCallback} if539* the realm must be entered.540*541*@return A possibly null {@code SaslServer} created using the parameters542* supplied. If null, cannot find a {@code SaslServerFactory}543* that will produce one.544*@exception SaslException If cannot create a {@code SaslServer} because545* of an error.546**/547public static SaslServer548createSaslServer(String mechanism,549String protocol,550String serverName,551Map<String,?> props,552javax.security.auth.callback.CallbackHandler cbh)553throws SaslException {554555SaslServer mech = null;556SaslServerFactory fac;557Service service;558559if (mechanism == null) {560throw new NullPointerException("Mechanism name cannot be null");561} else if (mechanism.length() == 0) {562return null;563} else if (isDisabled(mechanism)) {564logger.log(Level.FINE,565"Disabled " + mechanism + " mechanism ignored");566return null;567}568569String type = "SaslServerFactory";570Provider[] provs = Security.getProviders(type + "." + mechanism);571if (provs != null) {572for (Provider p : provs) {573service = p.getService(type, mechanism);574if (service == null) {575throw new SaslException("Provider does not support " +576mechanism + " " + type);577}578fac = (SaslServerFactory) loadFactory(service);579if (fac != null) {580mech = fac.createSaslServer(581mechanism, protocol, serverName, props, cbh);582if (mech != null) {583return mech;584}585}586}587}588return null;589}590591/**592* Gets an enumeration of known factories for producing {@code SaslClient}.593* This method uses the same algorithm for locating factories as594* {@code createSaslClient()}.595* @return A non-null enumeration of known factories for producing596* {@code SaslClient}.597* @see #createSaslClient598*/599public static Enumeration<SaslClientFactory> getSaslClientFactories() {600Set<Object> facs = getFactories("SaslClientFactory");601final Iterator<Object> iter = facs.iterator();602return new Enumeration<SaslClientFactory>() {603public boolean hasMoreElements() {604return iter.hasNext();605}606public SaslClientFactory nextElement() {607return (SaslClientFactory)iter.next();608}609};610}611612/**613* Gets an enumeration of known factories for producing {@code SaslServer}.614* This method uses the same algorithm for locating factories as615* {@code createSaslServer()}.616* @return A non-null enumeration of known factories for producing617* {@code SaslServer}.618* @see #createSaslServer619*/620public static Enumeration<SaslServerFactory> getSaslServerFactories() {621Set<Object> facs = getFactories("SaslServerFactory");622final Iterator<Object> iter = facs.iterator();623return new Enumeration<SaslServerFactory>() {624public boolean hasMoreElements() {625return iter.hasNext();626}627public SaslServerFactory nextElement() {628return (SaslServerFactory)iter.next();629}630};631}632633private static Set<Object> getFactories(String serviceName) {634HashSet<Object> result = new HashSet<Object>();635636if ((serviceName == null) || (serviceName.length() == 0) ||637(serviceName.endsWith("."))) {638return result;639}640641Provider[] provs = Security.getProviders();642Object fac;643644for (Provider p : provs) {645646Iterator<Service> iter = p.getServices().iterator();647while (iter.hasNext()) {648Service s = iter.next();649if (s.getType().equals(serviceName)) {650try {651fac = loadFactory(s);652if (fac != null) {653result.add(fac);654}655} catch (Exception ignore) {656}657}658}659}660return Collections.unmodifiableSet(result);661}662663private static boolean isDisabled(String name) {664return disabledMechanisms.contains(name);665}666}667668669