8187443: Forest Consolidation: Move files to unified layout

Reviewed-by: darcy, ihse
This commit is contained in:
Erik Joelsson 2017-09-12 19:03:39 +02:00
parent 270fe13182
commit 3789983e89
56923 changed files with 3 additions and 15727 deletions

View file

@ -0,0 +1,160 @@
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
import com.sun.security.sasl.util.PolicyUtils;
import java.util.Map;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Client factory for EXTERNAL, CRAM-MD5, PLAIN.
*
* Requires the following callbacks to be satisfied by callback handler
* when using CRAM-MD5 or PLAIN.
* - NameCallback (to get username)
* - PasswordCallback (to get password)
*
* @author Rosanna Lee
*/
final public class ClientFactoryImpl implements SaslClientFactory {
private static final String[] myMechs = {
"EXTERNAL",
"CRAM-MD5",
"PLAIN",
};
private static final int[] mechPolicies = {
// %%% RL: Policies should actually depend on the external channel
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOACTIVE|PolicyUtils.NODICTIONARY,
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS, // CRAM-MD5
PolicyUtils.NOANONYMOUS, // PLAIN
};
private static final int EXTERNAL = 0;
private static final int CRAMMD5 = 1;
private static final int PLAIN = 2;
public ClientFactoryImpl() {
}
public SaslClient createSaslClient(String[] mechs,
String authorizationId,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
for (int i = 0; i < mechs.length; i++) {
if (mechs[i].equals(myMechs[EXTERNAL])
&& PolicyUtils.checkPolicy(mechPolicies[EXTERNAL], props)) {
return new ExternalClient(authorizationId);
} else if (mechs[i].equals(myMechs[CRAMMD5])
&& PolicyUtils.checkPolicy(mechPolicies[CRAMMD5], props)) {
Object[] uinfo = getUserInfo("CRAM-MD5", authorizationId, cbh);
// Callee responsible for clearing bytepw
return new CramMD5Client((String) uinfo[0],
(byte []) uinfo[1]);
} else if (mechs[i].equals(myMechs[PLAIN])
&& PolicyUtils.checkPolicy(mechPolicies[PLAIN], props)) {
Object[] uinfo = getUserInfo("PLAIN", authorizationId, cbh);
// Callee responsible for clearing bytepw
return new PlainClient(authorizationId,
(String) uinfo[0], (byte []) uinfo[1]);
}
}
return null;
};
public String[] getMechanismNames(Map<String,?> props) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, props);
}
/**
* Gets the authentication id and password. The
* password is converted to bytes using UTF-8 and stored in bytepw.
* The authentication id is stored in authId.
*
* @param prefix The non-null prefix to use for the prompt (e.g., mechanism
* name)
* @param authorizationId The possibly null authorization id. This is used
* as a default for the NameCallback. If null, it is not used in prompt.
* @param cbh The non-null callback handler to use.
* @return an {authid, passwd} pair
*/
private Object[] getUserInfo(String prefix, String authorizationId,
CallbackHandler cbh) throws SaslException {
if (cbh == null) {
throw new SaslException(
"Callback handler to get username/password required");
}
try {
String userPrompt = prefix + " authentication id: ";
String passwdPrompt = prefix + " password: ";
NameCallback ncb = authorizationId == null?
new NameCallback(userPrompt) :
new NameCallback(userPrompt, authorizationId);
PasswordCallback pcb = new PasswordCallback(passwdPrompt, false);
cbh.handle(new Callback[]{ncb,pcb});
char[] pw = pcb.getPassword();
byte[] bytepw;
String authId;
if (pw != null) {
bytepw = new String(pw).getBytes("UTF8");
pcb.clearPassword();
} else {
bytepw = null;
}
authId = ncb.getName();
return new Object[]{authId, bytepw};
} catch (IOException e) {
throw new SaslException("Cannot get password", e);
} catch (UnsupportedCallbackException e) {
throw new SaslException("Cannot get userid/password", e);
}
}
}

View file

@ -0,0 +1,228 @@
/*
* Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.SaslException;
import javax.security.sasl.Sasl;
// For HMAC_MD5
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* Base class for implementing CRAM-MD5 client and server mechanisms.
*
* @author Vincent Ryan
* @author Rosanna Lee
*/
abstract class CramMD5Base {
protected boolean completed = false;
protected boolean aborted = false;
protected byte[] pw;
protected CramMD5Base() {
initLogger();
}
/**
* Retrieves this mechanism's name.
*
* @return The string "CRAM-MD5".
*/
public String getMechanismName() {
return "CRAM-MD5";
}
/**
* Determines whether this mechanism has completed.
* CRAM-MD5 completes after processing one challenge from the server.
*
* @return true if has completed; false otherwise;
*/
public boolean isComplete() {
return completed;
}
/**
* Unwraps the incoming buffer. CRAM-MD5 supports no security layer.
*
* @throws SaslException If attempt to use this method.
*/
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
if (completed) {
throw new IllegalStateException(
"CRAM-MD5 supports neither integrity nor privacy");
} else {
throw new IllegalStateException(
"CRAM-MD5 authentication not completed");
}
}
/**
* Wraps the outgoing buffer. CRAM-MD5 supports no security layer.
*
* @throws SaslException If attempt to use this method.
*/
public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
if (completed) {
throw new IllegalStateException(
"CRAM-MD5 supports neither integrity nor privacy");
} else {
throw new IllegalStateException(
"CRAM-MD5 authentication not completed");
}
}
/**
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true); otherwise, a
* {@code SaslException} is thrown.
*
* @return value of property; only QOP is applicable to CRAM-MD5.
* @exception IllegalStateException if this authentication exchange has not completed
*/
public Object getNegotiatedProperty(String propName) {
if (completed) {
if (propName.equals(Sasl.QOP)) {
return "auth";
} else {
return null;
}
} else {
throw new IllegalStateException(
"CRAM-MD5 authentication not completed");
}
}
public void dispose() throws SaslException {
clearPassword();
}
protected void clearPassword() {
if (pw != null) {
// zero out password
for (int i = 0; i < pw.length; i++) {
pw[i] = (byte)0;
}
pw = null;
}
}
@SuppressWarnings("deprecation")
protected void finalize() {
clearPassword();
}
static private final int MD5_BLOCKSIZE = 64;
/**
* Hashes its input arguments according to HMAC-MD5 (RFC 2104)
* and returns the resulting digest in its ASCII representation.
*
* HMAC-MD5 function is described as follows:
*
* MD5(key XOR opad, MD5(key XOR ipad, text))
*
* where key is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* text is the data to be protected
*/
final static String HMAC_MD5(byte[] key, byte[] text)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
/* digest the key if longer than 64 bytes */
if (key.length > MD5_BLOCKSIZE) {
key = md5.digest(key);
}
byte[] ipad = new byte[MD5_BLOCKSIZE]; /* inner padding */
byte[] opad = new byte[MD5_BLOCKSIZE]; /* outer padding */
byte[] digest;
int i;
/* store key in pads */
for (i = 0; i < key.length; i++) {
ipad[i] = key[i];
opad[i] = key[i];
}
/* XOR key with pads */
for (i = 0; i < MD5_BLOCKSIZE; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
/* inner MD5 */
md5.update(ipad);
md5.update(text);
digest = md5.digest();
/* outer MD5 */
md5.update(opad);
md5.update(digest);
digest = md5.digest();
// Get character representation of digest
StringBuilder digestString = new StringBuilder();
for (i = 0; i < digest.length; i++) {
if ((digest[i] & 0x000000ff) < 0x10) {
digestString.append('0').append(Integer.toHexString(digest[i] & 0x000000ff));
} else {
digestString.append(
Integer.toHexString(digest[i] & 0x000000ff));
}
}
Arrays.fill(ipad, (byte)0);
Arrays.fill(opad, (byte)0);
ipad = null;
opad = null;
return (digestString.toString());
}
/**
* Sets logger field.
*/
private static synchronized void initLogger() {
if (logger == null) {
logger = Logger.getLogger(SASL_LOGGER_NAME);
}
}
/**
* Logger for debug messages
*/
private static final String SASL_LOGGER_NAME = "javax.security.sasl";
protected static Logger logger; // set in initLogger(); lazily loads logger
}

View file

@ -0,0 +1,130 @@
/*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Implements the CRAM-MD5 SASL client-side mechanism.
* (<A HREF="http://www.ietf.org/rfc/rfc2195.txt">RFC 2195</A>).
* CRAM-MD5 has no initial response. It receives bytes from
* the server as a challenge, which it hashes by using MD5 and the password.
* It concatenates the authentication ID with this result and returns it
* as the response to the challenge. At that point, the exchange is complete.
*
* @author Vincent Ryan
* @author Rosanna Lee
*/
final class CramMD5Client extends CramMD5Base implements SaslClient {
private String username;
/**
* Creates a SASL mechanism with client credentials that it needs
* to participate in CRAM-MD5 authentication exchange with the server.
*
* @param authID A non-null string representing the principal
* being authenticated.
*
* @param pw A non-null String or byte[]
* containing the password. If it is an array, it is first cloned.
*/
CramMD5Client(String authID, byte[] pw) throws SaslException {
if (authID == null || pw == null) {
throw new SaslException(
"CRAM-MD5: authentication ID and password must be specified");
}
username = authID;
this.pw = pw; // caller should have already cloned
}
/**
* CRAM-MD5 has no initial response.
*/
public boolean hasInitialResponse() {
return false;
}
/**
* Processes the challenge data.
*
* The server sends a challenge data using which the client must
* compute an MD5-digest with its password as the key.
*
* @param challengeData A non-null byte array containing the challenge
* data from the server.
* @return A non-null byte array containing the response to be sent to
* the server.
* @throws SaslException If platform does not have MD5 support
* @throw IllegalStateException if this method is invoked more than once.
*/
public byte[] evaluateChallenge(byte[] challengeData)
throws SaslException {
// See if we've been here before
if (completed) {
throw new IllegalStateException(
"CRAM-MD5 authentication already completed");
}
if (aborted) {
throw new IllegalStateException(
"CRAM-MD5 authentication previously aborted due to error");
}
// generate a keyed-MD5 digest from the user's password and challenge.
try {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "CRAMCLNT01:Received challenge: {0}",
new String(challengeData, "UTF8"));
}
String digest = HMAC_MD5(pw, challengeData);
// clear it when we no longer need it
clearPassword();
// response is username + " " + digest
String resp = username + " " + digest;
logger.log(Level.FINE, "CRAMCLNT02:Sending response: {0}", resp);
completed = true;
return resp.getBytes("UTF8");
} catch (java.security.NoSuchAlgorithmException e) {
aborted = true;
throw new SaslException("MD5 algorithm not available on platform", e);
} catch (java.io.UnsupportedEncodingException e) {
aborted = true;
throw new SaslException("UTF8 not available on platform", e);
}
}
}

View file

@ -0,0 +1,250 @@
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
import javax.security.auth.callback.*;
import java.util.Random;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
/**
* Implements the CRAM-MD5 SASL server-side mechanism.
* (<A HREF="http://www.ietf.org/rfc/rfc2195.txt">RFC 2195</A>).
* CRAM-MD5 has no initial response.
*
* client <---- M={random, timestamp, server-fqdn} ------- server
* client ----- {username HMAC_MD5(pw, M)} --------------> server
*
* CallbackHandler must be able to handle the following callbacks:
* - NameCallback: default name is name of user for whom to get password
* - PasswordCallback: must fill in password; if empty, no pw
* - AuthorizeCallback: must setAuthorized() and canonicalized authorization id
* - auth id == authzid, but needed to get canonicalized authzid
*
* @author Rosanna Lee
*/
final class CramMD5Server extends CramMD5Base implements SaslServer {
private String fqdn;
private byte[] challengeData = null;
private String authzid;
private CallbackHandler cbh;
/**
* Creates a CRAM-MD5 SASL server.
*
* @param protocol ignored in CRAM-MD5
* @param serverFqdn non-null, used in generating a challenge
* @param props ignored in CRAM-MD5
* @param cbh find password, authorize user
*/
CramMD5Server(String protocol, String serverFqdn, Map<String, ?> props,
CallbackHandler cbh) throws SaslException {
if (serverFqdn == null) {
throw new SaslException(
"CRAM-MD5: fully qualified server name must be specified");
}
fqdn = serverFqdn;
this.cbh = cbh;
}
/**
* Generates challenge based on response sent by client.
*
* CRAM-MD5 has no initial response.
* First call generates challenge.
* Second call verifies client response. If authentication fails, throws
* SaslException.
*
* @param responseData A non-null byte array containing the response
* data from the client.
* @return A non-null byte array containing the challenge to be sent to
* the client for the first call; null when 2nd call is successful.
* @throws SaslException If authentication fails.
*/
public byte[] evaluateResponse(byte[] responseData)
throws SaslException {
// See if we've been here before
if (completed) {
throw new IllegalStateException(
"CRAM-MD5 authentication already completed");
}
if (aborted) {
throw new IllegalStateException(
"CRAM-MD5 authentication previously aborted due to error");
}
try {
if (challengeData == null) {
if (responseData.length != 0) {
aborted = true;
throw new SaslException(
"CRAM-MD5 does not expect any initial response");
}
// Generate challenge {random, timestamp, fqdn}
Random random = new Random();
long rand = random.nextLong();
long timestamp = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
sb.append('<');
sb.append(rand);
sb.append('.');
sb.append(timestamp);
sb.append('@');
sb.append(fqdn);
sb.append('>');
String challengeStr = sb.toString();
logger.log(Level.FINE,
"CRAMSRV01:Generated challenge: {0}", challengeStr);
challengeData = challengeStr.getBytes("UTF8");
return challengeData.clone();
} else {
// Examine response to see if correctly encrypted challengeData
if(logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,
"CRAMSRV02:Received response: {0}",
new String(responseData, "UTF8"));
}
// Extract username from response
int ulen = 0;
for (int i = 0; i < responseData.length; i++) {
if (responseData[i] == ' ') {
ulen = i;
break;
}
}
if (ulen == 0) {
aborted = true;
throw new SaslException(
"CRAM-MD5: Invalid response; space missing");
}
String username = new String(responseData, 0, ulen, "UTF8");
logger.log(Level.FINE,
"CRAMSRV03:Extracted username: {0}", username);
// Get user's password
NameCallback ncb =
new NameCallback("CRAM-MD5 authentication ID: ", username);
PasswordCallback pcb =
new PasswordCallback("CRAM-MD5 password: ", false);
cbh.handle(new Callback[]{ncb,pcb});
char[] pwChars = pcb.getPassword();
if (pwChars == null || pwChars.length == 0) {
// user has no password; OK to disclose to server
aborted = true;
throw new SaslException(
"CRAM-MD5: username not found: " + username);
}
pcb.clearPassword();
String pwStr = new String(pwChars);
for (int i = 0; i < pwChars.length; i++) {
pwChars[i] = 0;
}
pw = pwStr.getBytes("UTF8");
// Generate a keyed-MD5 digest from the user's password and
// original challenge.
String digest = HMAC_MD5(pw, challengeData);
logger.log(Level.FINE,
"CRAMSRV04:Expecting digest: {0}", digest);
// clear pw when we no longer need it
clearPassword();
// Check whether digest is as expected
byte[] expectedDigest = digest.getBytes("UTF8");
int digestLen = responseData.length - ulen - 1;
if (expectedDigest.length != digestLen) {
aborted = true;
throw new SaslException("Invalid response");
}
int j = 0;
for (int i = ulen + 1; i < responseData.length ; i++) {
if (expectedDigest[j++] != responseData[i]) {
aborted = true;
throw new SaslException("Invalid response");
}
}
// All checks out, use AuthorizeCallback to canonicalize name
AuthorizeCallback acb = new AuthorizeCallback(username, username);
cbh.handle(new Callback[]{acb});
if (acb.isAuthorized()) {
authzid = acb.getAuthorizedID();
} else {
// Not authorized
aborted = true;
throw new SaslException(
"CRAM-MD5: user not authorized: " + username);
}
logger.log(Level.FINE,
"CRAMSRV05:Authorization id: {0}", authzid);
completed = true;
return null;
}
} catch (UnsupportedEncodingException e) {
aborted = true;
throw new SaslException("UTF8 not available on platform", e);
} catch (NoSuchAlgorithmException e) {
aborted = true;
throw new SaslException("MD5 algorithm not available on platform", e);
} catch (UnsupportedCallbackException e) {
aborted = true;
throw new SaslException("CRAM-MD5 authentication failed", e);
} catch (SaslException e) {
throw e; // rethrow
} catch (IOException e) {
aborted = true;
throw new SaslException("CRAM-MD5 authentication failed", e);
}
}
public String getAuthorizationID() {
if (completed) {
return authzid;
} else {
throw new IllegalStateException(
"CRAM-MD5 authentication not completed");
}
}
}

View file

@ -0,0 +1,159 @@
/*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
/**
* Implements the EXTERNAL SASL client mechanism.
* (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
* The EXTERNAL mechanism returns the optional authorization ID as
* the initial response. It processes no challenges.
*
* @author Rosanna Lee
*/
final class ExternalClient implements SaslClient {
private byte[] username;
private boolean completed = false;
/**
* Constructs an External mechanism with optional authorization ID.
*
* @param authorizationID If non-null, used to specify authorization ID.
* @throws SaslException if cannot convert authorizationID into UTF-8
* representation.
*/
ExternalClient(String authorizationID) throws SaslException {
if (authorizationID != null) {
try {
username = authorizationID.getBytes("UTF8");
} catch (java.io.UnsupportedEncodingException e) {
throw new SaslException("Cannot convert " + authorizationID +
" into UTF-8", e);
}
} else {
username = new byte[0];
}
}
/**
* Retrieves this mechanism's name for initiating the "EXTERNAL" protocol
* exchange.
*
* @return The string "EXTERNAL".
*/
public String getMechanismName() {
return "EXTERNAL";
}
/**
* This mechanism has an initial response.
*/
public boolean hasInitialResponse() {
return true;
}
public void dispose() throws SaslException {
}
/**
* Processes the challenge data.
* It returns the EXTERNAL mechanism's initial response,
* which is the authorization id encoded in UTF-8.
* This is the optional information that is sent along with the SASL command.
* After this method is called, isComplete() returns true.
*
* @param challengeData Ignored.
* @return The possible empty initial response.
* @throws SaslException If authentication has already been called.
*/
public byte[] evaluateChallenge(byte[] challengeData)
throws SaslException {
if (completed) {
throw new IllegalStateException(
"EXTERNAL authentication already completed");
}
completed = true;
return username;
}
/**
* Returns whether this mechanism is complete.
* @return true if initial response has been sent; false otherwise.
*/
public boolean isComplete() {
return completed;
}
/**
* Unwraps the incoming buffer.
*
* @throws SaslException Not applicable to this mechanism.
*/
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
if (completed) {
throw new SaslException("EXTERNAL has no supported QOP");
} else {
throw new IllegalStateException(
"EXTERNAL authentication Not completed");
}
}
/**
* Wraps the outgoing buffer.
*
* @throws SaslException Not applicable to this mechanism.
*/
public byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException {
if (completed) {
throw new SaslException("EXTERNAL has no supported QOP");
} else {
throw new IllegalStateException(
"EXTERNAL authentication not completed");
}
}
/**
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true);
* otherwise, an {@code IllegalStateException} is thrown.
*
* @return null No property is applicable to this mechanism.
* @exception IllegalStateException if this authentication exchange
* has not completed
*/
public Object getNegotiatedProperty(String propName) {
if (completed) {
return null;
} else {
throw new IllegalStateException(
"EXTERNAL authentication not completed");
}
}
}

View file

@ -0,0 +1,206 @@
/*
* Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
/**
* Implements the PLAIN SASL client mechanism.
* (<A
* HREF="http://ftp.isi.edu/in-notes/rfc2595.txt">RFC 2595</A>)
*
* @author Rosanna Lee
*/
final class PlainClient implements SaslClient {
private boolean completed = false;
private byte[] pw;
private String authorizationID;
private String authenticationID;
private static byte SEP = 0; // US-ASCII <NUL>
/**
* Creates a SASL mechanism with client credentials that it needs
* to participate in Plain authentication exchange with the server.
*
* @param authorizationID A possibly null string representing the principal
* for which authorization is being granted; if null, same as
* authenticationID
* @param authenticationID A non-null string representing the principal
* being authenticated. pw is associated with this principal.
* @param pw A non-null byte[] containing the password.
*/
PlainClient(String authorizationID, String authenticationID, byte[] pw)
throws SaslException {
if (authenticationID == null || pw == null) {
throw new SaslException(
"PLAIN: authorization ID and password must be specified");
}
this.authorizationID = authorizationID;
this.authenticationID = authenticationID;
this.pw = pw; // caller should have already cloned
}
/**
* Retrieves this mechanism's name for to initiate the PLAIN protocol
* exchange.
*
* @return The string "PLAIN".
*/
public String getMechanismName() {
return "PLAIN";
}
public boolean hasInitialResponse() {
return true;
}
public void dispose() throws SaslException {
clearPassword();
}
/**
* Retrieves the initial response for the SASL command, which for
* PLAIN is the concatenation of authorization ID, authentication ID
* and password, with each component separated by the US-ASCII <NUL> byte.
*
* @param challengeData Ignored
* @return A non-null byte array containing the response to be sent to the server.
* @throws SaslException If cannot encode ids in UTF-8
* @throw IllegalStateException if authentication already completed
*/
public byte[] evaluateChallenge(byte[] challengeData) throws SaslException {
if (completed) {
throw new IllegalStateException(
"PLAIN authentication already completed");
}
completed = true;
try {
byte[] authz = (authorizationID != null)?
authorizationID.getBytes("UTF8") :
null;
byte[] auth = authenticationID.getBytes("UTF8");
byte[] answer = new byte[pw.length + auth.length + 2 +
(authz == null ? 0 : authz.length)];
int pos = 0;
if (authz != null) {
System.arraycopy(authz, 0, answer, 0, authz.length);
pos = authz.length;
}
answer[pos++] = SEP;
System.arraycopy(auth, 0, answer, pos, auth.length);
pos += auth.length;
answer[pos++] = SEP;
System.arraycopy(pw, 0, answer, pos, pw.length);
clearPassword();
return answer;
} catch (java.io.UnsupportedEncodingException e) {
throw new SaslException("Cannot get UTF-8 encoding of ids", e);
}
}
/**
* Determines whether this mechanism has completed.
* Plain completes after returning one response.
*
* @return true if has completed; false otherwise;
*/
public boolean isComplete() {
return completed;
}
/**
* Unwraps the incoming buffer.
*
* @throws SaslException Not applicable to this mechanism.
*/
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
if (completed) {
throw new SaslException(
"PLAIN supports neither integrity nor privacy");
} else {
throw new IllegalStateException("PLAIN authentication not completed");
}
}
/**
* Wraps the outgoing buffer.
*
* @throws SaslException Not applicable to this mechanism.
*/
public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
if (completed) {
throw new SaslException(
"PLAIN supports neither integrity nor privacy");
} else {
throw new IllegalStateException("PLAIN authentication not completed");
}
}
/**
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true); otherwise, a
* {@code SaslException} is thrown.
*
* @return value of property; only QOP is applicable to PLAIN.
* @exception IllegalStateException if this authentication exchange
* has not completed
*/
public Object getNegotiatedProperty(String propName) {
if (completed) {
if (propName.equals(Sasl.QOP)) {
return "auth";
} else {
return null;
}
} else {
throw new IllegalStateException("PLAIN authentication not completed");
}
}
private void clearPassword() {
if (pw != null) {
// zero out password
for (int i = 0; i < pw.length; i++) {
pw[i] = (byte)0;
}
pw = null;
}
}
@SuppressWarnings("deprecation")
protected void finalize() {
clearPassword();
}
}

View file

@ -0,0 +1,130 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidParameterException;
import java.security.ProviderException;
import static sun.security.util.SecurityConstants.PROVIDER_VER;
/**
* The SASL provider.
* Provides client support for
* - EXTERNAL
* - PLAIN
* - CRAM-MD5
* - DIGEST-MD5
* - NTLM
* And server support for
* - CRAM-MD5
* - DIGEST-MD5
* - NTLM
*/
public final class Provider extends java.security.Provider {
private static final long serialVersionUID = 8622598936488630849L;
private static final String info = "Sun SASL provider" +
"(implements client mechanisms for: " +
"DIGEST-MD5, EXTERNAL, PLAIN, CRAM-MD5, NTLM;" +
" server mechanisms for: DIGEST-MD5, CRAM-MD5, NTLM)";
private static final class ProviderService
extends java.security.Provider.Service {
ProviderService(java.security.Provider p, String type, String algo,
String cn) {
super(p, type, algo, cn, null, null);
}
@Override
public Object newInstance(Object ctrParamObj)
throws NoSuchAlgorithmException {
String type = getType();
if (ctrParamObj != null) {
throw new InvalidParameterException
("constructorParameter not used with " + type + " engines");
}
String algo = getAlgorithm();
try {
// DIGEST-MD5, NTLM uses same impl class for client and server
if (algo.equals("DIGEST-MD5")) {
return new com.sun.security.sasl.digest.FactoryImpl();
}
if (algo.equals("NTLM")) {
return new com.sun.security.sasl.ntlm.FactoryImpl();
}
if (type.equals("SaslClientFactory")) {
if (algo.equals("EXTERNAL") || algo.equals("PLAIN") ||
algo.equals("CRAM-MD5")) {
return new com.sun.security.sasl.ClientFactoryImpl();
}
} else if (type.equals("SaslServerFactory")) {
if (algo.equals("CRAM-MD5")) {
return new com.sun.security.sasl.ServerFactoryImpl();
}
}
} catch (Exception ex) {
throw new NoSuchAlgorithmException("Error constructing " +
type + " for " + algo + " using SunSASL", ex);
}
throw new ProviderException("No impl for " + algo +
" " + type);
}
}
public Provider() {
super("SunSASL", PROVIDER_VER, info);
final Provider p = this;
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
// Client mechanisms
putService(new ProviderService(p, "SaslClientFactory",
"DIGEST-MD5", "com.sun.security.sasl.digest.FactoryImpl"));
putService(new ProviderService(p, "SaslClientFactory",
"NTLM", "com.sun.security.sasl.ntlm.FactoryImpl"));
putService(new ProviderService(p, "SaslClientFactory",
"EXTERNAL", "com.sun.security.sasl.ClientFactoryImpl"));
putService(new ProviderService(p, "SaslClientFactory",
"PLAIN", "com.sun.security.sasl.ClientFactoryImpl"));
putService(new ProviderService(p, "SaslClientFactory",
"CRAM-MD5", "com.sun.security.sasl.ClientFactoryImpl"));
// Server mechanisms
putService(new ProviderService(p, "SaslServerFactory",
"CRAM-MD5", "com.sun.security.sasl.ServerFactoryImpl"));
putService(new ProviderService(p, "SaslServerFactory",
"DIGEST-MD5", "com.sun.security.sasl.digest.FactoryImpl"));
putService(new ProviderService(p, "SaslServerFactory",
"NTLM", "com.sun.security.sasl.ntlm.FactoryImpl"));
return null;
}
});
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
import com.sun.security.sasl.util.PolicyUtils;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/**
* Server factory for CRAM-MD5.
*
* Requires the following callback to be satisfied by callback handler
* when using CRAM-MD5.
* - AuthorizeCallback (to get canonicalized authzid)
*
* @author Rosanna Lee
*/
final public class ServerFactoryImpl implements SaslServerFactory {
private static final String[] myMechs = {
"CRAM-MD5", //
};
private static final int[] mechPolicies = {
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS, // CRAM-MD5
};
private static final int CRAMMD5 = 0;
public ServerFactoryImpl() {
}
public SaslServer createSaslServer(String mech,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
if (mech.equals(myMechs[CRAMMD5])
&& PolicyUtils.checkPolicy(mechPolicies[CRAMMD5], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for AuthorizeCallback required");
}
return new CramMD5Server(protocol, serverName, props, cbh);
}
return null;
};
public String[] getMechanismNames(Map<String,?> props) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, props);
}
}

View file

@ -0,0 +1,700 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.digest;
import java.security.NoSuchAlgorithmException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.logging.Level;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* An implementation of the DIGEST-MD5
* (<a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>) SASL
* (<a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>) mechanism.
*
* The DIGEST-MD5 SASL mechanism specifies two modes of authentication.
* - Initial Authentication
* - Subsequent Authentication - optional, (currently unsupported)
*
* Required callbacks:
* - RealmChoiceCallback
* shows user list of realms server has offered; handler must choose one
* from list
* - RealmCallback
* shows user the only realm server has offered or none; handler must
* enter realm to use
* - NameCallback
* handler must enter username to use for authentication
* - PasswordCallback
* handler must enter password for username to use for authentication
*
* Environment properties that affect behavior of implementation:
*
* javax.security.sasl.qop
* quality of protection; list of auth, auth-int, auth-conf; default is "auth"
* javax.security.sasl.strength
* auth-conf strength; list of high, medium, low; default is highest
* available on platform ["high,medium,low"].
* high means des3 or rc4 (128); medium des or rc4-56; low is rc4-40;
* choice of cipher depends on its availablility on platform
* javax.security.sasl.maxbuf
* max receive buffer size; default is 65536
* javax.security.sasl.sendmaxbuffer
* max send buffer size; default is 65536; (min with server max recv size)
*
* com.sun.security.sasl.digest.cipher
* name a specific cipher to use; setting must be compatible with the
* setting of the javax.security.sasl.strength property.
*
* @see <a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>
* - Simple Authentication and Security Layer (SASL)
* @see <a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>
* - Using Digest Authentication as a SASL Mechanism
* @see <a href="http://java.sun.com/products/jce">Java(TM)
* Cryptography Extension 1.2.1 (JCE)</a>
* @see <a href="http://java.sun.com/products/jaas">Java(TM)
* Authentication and Authorization Service (JAAS)</a>
*
* @author Jonathan Bruce
* @author Rosanna Lee
*/
final class DigestMD5Client extends DigestMD5Base implements SaslClient {
private static final String MY_CLASS_NAME = DigestMD5Client.class.getName();
// Property for specifying cipher explicitly
private static final String CIPHER_PROPERTY =
"com.sun.security.sasl.digest.cipher";
/* Directives encountered in challenges sent by the server. */
private static final String[] DIRECTIVE_KEY = {
"realm", // >= 0 times
"qop", // atmost once; default is "auth"
"algorithm", // exactly once
"nonce", // exactly once
"maxbuf", // atmost once; default is 65536
"charset", // atmost once; default is ISO 8859-1
"cipher", // exactly once if qop is "auth-conf"
"rspauth", // exactly once in 2nd challenge
"stale", // atmost once for in subsequent auth (not supported)
};
/* Indices into DIRECTIVE_KEY */
private static final int REALM = 0;
private static final int QOP = 1;
private static final int ALGORITHM = 2;
private static final int NONCE = 3;
private static final int MAXBUF = 4;
private static final int CHARSET = 5;
private static final int CIPHER = 6;
private static final int RESPONSE_AUTH = 7;
private static final int STALE = 8;
private int nonceCount; // number of times nonce has been used/seen
/* User-supplied/generated information */
private String specifiedCipher; // cipher explicitly requested by user
private byte[] cnonce; // client generated nonce
private String username;
private char[] passwd;
private byte[] authzidBytes; // byte repr of authzid
/**
* Constructor for DIGEST-MD5 mechanism.
*
* @param authzid A non-null String representing the principal
* for which authorization is being granted..
* @param digestURI A non-null String representing detailing the
* combined protocol and host being used for authentication.
* @param props The possibly null properties to be used by the SASL
* mechanism to configure the authentication exchange.
* @param cbh The non-null CallbackHanlder object for callbacks
* @throws SaslException if no authentication ID or password is supplied
*/
DigestMD5Client(String authzid, String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
super(props, MY_CLASS_NAME, 2, protocol + "/" + serverName, cbh);
// authzID can only be encoded in UTF8 - RFC 2222
if (authzid != null) {
this.authzid = authzid;
try {
authzidBytes = authzid.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
throw new SaslException(
"DIGEST-MD5: Error encoding authzid value into UTF-8", e);
}
}
if (props != null) {
specifiedCipher = (String)props.get(CIPHER_PROPERTY);
logger.log(Level.FINE, "DIGEST60:Explicitly specified cipher: {0}",
specifiedCipher);
}
}
/**
* DIGEST-MD5 has no initial response
*
* @return false
*/
public boolean hasInitialResponse() {
return false;
}
/**
* Process the challenge data.
*
* The server sends a digest-challenge which the client must reply to
* in a digest-response. When the authentication is complete, the
* completed field is set to true.
*
* @param challengeData A non-null byte array containing the challenge
* data from the server.
* @return A possibly null byte array containing the response to
* be sent to the server.
*
* @throws SaslException If the platform does not have MD5 digest support
* or if the server sends an invalid challenge.
*/
public byte[] evaluateChallenge(byte[] challengeData) throws SaslException {
if (challengeData.length > MAX_CHALLENGE_LENGTH) {
throw new SaslException(
"DIGEST-MD5: Invalid digest-challenge length. Got: " +
challengeData.length + " Expected < " + MAX_CHALLENGE_LENGTH);
}
/* Extract and process digest-challenge */
byte[][] challengeVal;
switch (step) {
case 2:
/* Process server's first challenge (from Step 1) */
/* Get realm, qop, maxbuf, charset, algorithm, cipher, nonce
directives */
List<byte[]> realmChoices = new ArrayList<byte[]>(3);
challengeVal = parseDirectives(challengeData, DIRECTIVE_KEY,
realmChoices, REALM);
try {
processChallenge(challengeVal, realmChoices);
checkQopSupport(challengeVal[QOP], challengeVal[CIPHER]);
++step;
return generateClientResponse(challengeVal[CHARSET]);
} catch (SaslException e) {
step = 0;
clearPassword();
throw e; // rethrow
} catch (IOException e) {
step = 0;
clearPassword();
throw new SaslException("DIGEST-MD5: Error generating " +
"digest response-value", e);
}
case 3:
try {
/* Process server's step 3 (server response to digest response) */
/* Get rspauth directive */
challengeVal = parseDirectives(challengeData, DIRECTIVE_KEY,
null, REALM);
validateResponseValue(challengeVal[RESPONSE_AUTH]);
/* Initialize SecurityCtx implementation */
if (integrity && privacy) {
secCtx = new DigestPrivacy(true /* client */);
} else if (integrity) {
secCtx = new DigestIntegrity(true /* client */);
}
return null; // Mechanism has completed.
} finally {
clearPassword();
step = 0; // Set to invalid state
completed = true;
}
default:
// No other possible state
throw new SaslException("DIGEST-MD5: Client at illegal state");
}
}
/**
* Record information from the challengeVal array into variables/fields.
* Check directive values that are multi-valued and ensure that mandatory
* directives not missing from the digest-challenge.
*
* @throws SaslException if a sasl is a the mechanism cannot
* correcly handle a callbacks or if a violation in the
* digest challenge format is detected.
*/
private void processChallenge(byte[][] challengeVal, List<byte[]> realmChoices)
throws SaslException, UnsupportedEncodingException {
/* CHARSET: optional atmost once */
if (challengeVal[CHARSET] != null) {
if (!"utf-8".equals(new String(challengeVal[CHARSET], encoding))) {
throw new SaslException("DIGEST-MD5: digest-challenge format " +
"violation. Unrecognised charset value: " +
new String(challengeVal[CHARSET]));
} else {
encoding = "UTF8";
useUTF8 = true;
}
}
/* ALGORITHM: required exactly once */
if (challengeVal[ALGORITHM] == null) {
throw new SaslException("DIGEST-MD5: Digest-challenge format " +
"violation: algorithm directive missing");
} else if (!"md5-sess".equals(new String(challengeVal[ALGORITHM], encoding))) {
throw new SaslException("DIGEST-MD5: Digest-challenge format " +
"violation. Invalid value for 'algorithm' directive: " +
challengeVal[ALGORITHM]);
}
/* NONCE: required exactly once */
if (challengeVal[NONCE] == null) {
throw new SaslException("DIGEST-MD5: Digest-challenge format " +
"violation: nonce directive missing");
} else {
nonce = challengeVal[NONCE];
}
try {
/* REALM: optional, if multiple, stored in realmChoices */
String[] realmTokens = null;
if (challengeVal[REALM] != null) {
if (realmChoices == null || realmChoices.size() <= 1) {
// Only one realm specified
negotiatedRealm = new String(challengeVal[REALM], encoding);
} else {
realmTokens = new String[realmChoices.size()];
for (int i = 0; i < realmTokens.length; i++) {
realmTokens[i] =
new String(realmChoices.get(i), encoding);
}
}
}
NameCallback ncb = authzid == null ?
new NameCallback("DIGEST-MD5 authentication ID: ") :
new NameCallback("DIGEST-MD5 authentication ID: ", authzid);
PasswordCallback pcb =
new PasswordCallback("DIGEST-MD5 password: ", false);
if (realmTokens == null) {
// Server specified <= 1 realm
// If 0, RFC 2831: the client SHOULD solicit a realm from the user.
RealmCallback tcb =
(negotiatedRealm == null? new RealmCallback("DIGEST-MD5 realm: ") :
new RealmCallback("DIGEST-MD5 realm: ", negotiatedRealm));
cbh.handle(new Callback[] {tcb, ncb, pcb});
/* Acquire realm from RealmCallback */
negotiatedRealm = tcb.getText();
if (negotiatedRealm == null) {
negotiatedRealm = "";
}
} else {
RealmChoiceCallback ccb = new RealmChoiceCallback(
"DIGEST-MD5 realm: ",
realmTokens,
0, false);
cbh.handle(new Callback[] {ccb, ncb, pcb});
// Acquire realm from RealmChoiceCallback
int[] selected = ccb.getSelectedIndexes();
if (selected == null
|| selected[0] < 0
|| selected[0] >= realmTokens.length) {
throw new SaslException("DIGEST-MD5: Invalid realm chosen");
}
negotiatedRealm = realmTokens[selected[0]];
}
passwd = pcb.getPassword();
pcb.clearPassword();
username = ncb.getName();
} catch (SaslException se) {
throw se;
} catch (UnsupportedCallbackException e) {
throw new SaslException("DIGEST-MD5: Cannot perform callback to " +
"acquire realm, authentication ID or password", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: Error acquiring realm, authentication ID or password", e);
}
if (username == null || passwd == null) {
throw new SaslException(
"DIGEST-MD5: authentication ID and password must be specified");
}
/* MAXBUF: optional atmost once */
int srvMaxBufSize =
(challengeVal[MAXBUF] == null) ? DEFAULT_MAXBUF
: Integer.parseInt(new String(challengeVal[MAXBUF], encoding));
sendMaxBufSize =
(sendMaxBufSize == 0) ? srvMaxBufSize
: Math.min(sendMaxBufSize, srvMaxBufSize);
}
/**
* Parses the 'qop' directive. If 'auth-conf' is specified by
* the client and offered as a QOP option by the server, then a check
* is client-side supported ciphers is performed.
*
* @throws IOException
*/
private void checkQopSupport(byte[] qopInChallenge, byte[] ciphersInChallenge)
throws IOException {
/* QOP: optional; if multiple, merged earlier */
String qopOptions;
if (qopInChallenge == null) {
qopOptions = "auth";
} else {
qopOptions = new String(qopInChallenge, encoding);
}
// process
String[] serverQopTokens = new String[3];
byte[] serverQop = parseQop(qopOptions, serverQopTokens,
true /* ignore unrecognized tokens */);
byte serverAllQop = combineMasks(serverQop);
switch (findPreferredMask(serverAllQop, qop)) {
case 0:
throw new SaslException("DIGEST-MD5: No common protection " +
"layer between client and server");
case NO_PROTECTION:
negotiatedQop = "auth";
// buffer sizes not applicable
break;
case INTEGRITY_ONLY_PROTECTION:
negotiatedQop = "auth-int";
integrity = true;
rawSendSize = sendMaxBufSize - 16;
break;
case PRIVACY_PROTECTION:
negotiatedQop = "auth-conf";
privacy = integrity = true;
rawSendSize = sendMaxBufSize - 26;
checkStrengthSupport(ciphersInChallenge);
break;
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "DIGEST61:Raw send size: {0}",
rawSendSize);
}
}
/**
* Processes the 'cipher' digest-challenge directive. This allows the
* mechanism to check for client-side support against the list of
* supported ciphers send by the server. If no match is found,
* the mechanism aborts.
*
* @throws SaslException If an error is encountered in processing
* the cipher digest-challenge directive or if no client-side
* support is found.
*/
private void checkStrengthSupport(byte[] ciphersInChallenge)
throws IOException {
/* CIPHER: required exactly once if qop=auth-conf */
if (ciphersInChallenge == null) {
throw new SaslException("DIGEST-MD5: server did not specify " +
"cipher to use for 'auth-conf'");
}
// First determine ciphers that server supports
String cipherOptions = new String(ciphersInChallenge, encoding);
StringTokenizer parser = new StringTokenizer(cipherOptions, ", \t\n");
int tokenCount = parser.countTokens();
String token = null;
byte[] serverCiphers = { UNSET,
UNSET,
UNSET,
UNSET,
UNSET };
String[] serverCipherStrs = new String[serverCiphers.length];
// Parse ciphers in challenge; mark each that server supports
for (int i = 0; i < tokenCount; i++) {
token = parser.nextToken();
for (int j = 0; j < CIPHER_TOKENS.length; j++) {
if (token.equals(CIPHER_TOKENS[j])) {
serverCiphers[j] |= CIPHER_MASKS[j];
serverCipherStrs[j] = token; // keep for replay to server
logger.log(Level.FINE, "DIGEST62:Server supports {0}", token);
}
}
}
// Determine which ciphers are available on client
byte[] clntCiphers = getPlatformCiphers();
// Take intersection of server and client supported ciphers
byte inter = 0;
for (int i = 0; i < serverCiphers.length; i++) {
serverCiphers[i] &= clntCiphers[i];
inter |= serverCiphers[i];
}
if (inter == UNSET) {
throw new SaslException(
"DIGEST-MD5: Client supports none of these cipher suites: " +
cipherOptions);
}
// now have a clear picture of user / client; client / server
// cipher options. Leverage strength array against what is
// supported to choose a cipher.
negotiatedCipher = findCipherAndStrength(serverCiphers, serverCipherStrs);
if (negotiatedCipher == null) {
throw new SaslException("DIGEST-MD5: Unable to negotiate " +
"a strength level for 'auth-conf'");
}
logger.log(Level.FINE, "DIGEST63:Cipher suite: {0}", negotiatedCipher);
}
/**
* Steps through the ordered 'strength' array, and compares it with
* the 'supportedCiphers' array. The cipher returned represents
* the best possible cipher based on the strength preference and the
* available ciphers on both the server and client environments.
*
* @param tokens The array of cipher tokens sent by server
* @return The agreed cipher.
*/
private String findCipherAndStrength(byte[] supportedCiphers,
String[] tokens) {
byte s;
for (int i = 0; i < strength.length; i++) {
if ((s=strength[i]) != 0) {
for (int j = 0; j < supportedCiphers.length; j++) {
// If user explicitly requested cipher, then it
// must be the one we choose
if (s == supportedCiphers[j] &&
(specifiedCipher == null ||
specifiedCipher.equals(tokens[j]))) {
switch (s) {
case HIGH_STRENGTH:
negotiatedStrength = "high";
break;
case MEDIUM_STRENGTH:
negotiatedStrength = "medium";
break;
case LOW_STRENGTH:
negotiatedStrength = "low";
break;
}
return tokens[j];
}
}
}
}
return null; // none found
}
/**
* Returns digest-response suitable for an initial authentication.
*
* The following are qdstr-val (quoted string values) as per RFC 2831,
* which means that any embedded quotes must be escaped.
* realm-value
* nonce-value
* username-value
* cnonce-value
* authzid-value
* @return {@code digest-response} in a byte array
* @throws SaslException if there is an error generating the
* response value or the cnonce value.
*/
private byte[] generateClientResponse(byte[] charset) throws IOException {
ByteArrayOutputStream digestResp = new ByteArrayOutputStream();
if (useUTF8) {
digestResp.write("charset=".getBytes(encoding));
digestResp.write(charset);
digestResp.write(',');
}
digestResp.write(("username=\"" +
quotedStringValue(username) + "\",").getBytes(encoding));
if (negotiatedRealm.length() > 0) {
digestResp.write(("realm=\"" +
quotedStringValue(negotiatedRealm) + "\",").getBytes(encoding));
}
digestResp.write("nonce=\"".getBytes(encoding));
writeQuotedStringValue(digestResp, nonce);
digestResp.write('"');
digestResp.write(',');
nonceCount = getNonceCount(nonce);
digestResp.write(("nc=" +
nonceCountToHex(nonceCount) + ",").getBytes(encoding));
cnonce = generateNonce();
digestResp.write("cnonce=\"".getBytes(encoding));
writeQuotedStringValue(digestResp, cnonce);
digestResp.write("\",".getBytes(encoding));
digestResp.write(("digest-uri=\"" + digestUri + "\",").getBytes(encoding));
digestResp.write("maxbuf=".getBytes(encoding));
digestResp.write(String.valueOf(recvMaxBufSize).getBytes(encoding));
digestResp.write(',');
try {
digestResp.write("response=".getBytes(encoding));
digestResp.write(generateResponseValue("AUTHENTICATE",
digestUri, negotiatedQop, username,
negotiatedRealm, passwd, nonce, cnonce,
nonceCount, authzidBytes));
digestResp.write(',');
} catch (Exception e) {
throw new SaslException(
"DIGEST-MD5: Error generating response value", e);
}
digestResp.write(("qop=" + negotiatedQop).getBytes(encoding));
if (negotiatedCipher != null) {
digestResp.write((",cipher=\"" + negotiatedCipher + "\"").getBytes(encoding));
}
if (authzidBytes != null) {
digestResp.write(",authzid=\"".getBytes(encoding));
writeQuotedStringValue(digestResp, authzidBytes);
digestResp.write("\"".getBytes(encoding));
}
if (digestResp.size() > MAX_RESPONSE_LENGTH) {
throw new SaslException ("DIGEST-MD5: digest-response size too " +
"large. Length: " + digestResp.size());
}
return digestResp.toByteArray();
}
/**
* From RFC 2831, Section 2.1.3: Step Three
* [Server] sends a message formatted as follows:
* response-auth = "rspauth" "=" response-value
* where response-value is calculated as above, using the values sent in
* step two, except that if qop is "auth", then A2 is
*
* A2 = { ":", digest-uri-value }
*
* And if qop is "auth-int" or "auth-conf" then A2 is
*
* A2 = { ":", digest-uri-value, ":00000000000000000000000000000000" }
*/
private void validateResponseValue(byte[] fromServer) throws SaslException {
if (fromServer == null) {
throw new SaslException("DIGEST-MD5: Authenication failed. " +
"Expecting 'rspauth' authentication success message");
}
try {
byte[] expected = generateResponseValue("",
digestUri, negotiatedQop, username, negotiatedRealm,
passwd, nonce, cnonce, nonceCount, authzidBytes);
if (!Arrays.equals(expected, fromServer)) {
/* Server's rspauth value does not match */
throw new SaslException(
"Server's rspauth value does not match what client expects");
}
} catch (NoSuchAlgorithmException e) {
throw new SaslException(
"Problem generating response value for verification", e);
} catch (IOException e) {
throw new SaslException(
"Problem generating response value for verification", e);
}
}
/**
* Returns the number of requests (including current request)
* that the client has sent in response to nonceValue.
* This is 1 the first time nonceValue is seen.
*
* We don't cache nonce values seen, and we don't support subsequent
* authentication, so the value is always 1.
*/
private static int getNonceCount(byte[] nonceValue) {
return 1;
}
private void clearPassword() {
if (passwd != null) {
for (int i = 0; i < passwd.length; i++) {
passwd[i] = 0;
}
passwd = null;
}
}
}

View file

@ -0,0 +1,724 @@
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.digest;
import java.security.NoSuchAlgorithmException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.logging.Level;
import javax.security.sasl.*;
import javax.security.auth.callback.*;
/**
* An implementation of the DIGEST-MD5 server SASL mechanism.
* (<a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>)
* <p>
* The DIGEST-MD5 SASL mechanism specifies two modes of authentication.
* <ul><li>Initial Authentication
* <li>Subsequent Authentication - optional, (currently not supported)
* </ul>
*
* Required callbacks:
* - RealmCallback
* used as key by handler to fetch password
* - NameCallback
* used as key by handler to fetch password
* - PasswordCallback
* handler must enter password for username/realm supplied
* - AuthorizeCallback
* handler must verify that authid/authzids are allowed and set
* authorized ID to be the canonicalized authzid (if applicable).
*
* Environment properties that affect the implementation:
* javax.security.sasl.qop:
* specifies list of qops; default is "auth"; typically, caller should set
* this to "auth, auth-int, auth-conf".
* javax.security.sasl.strength
* specifies low/medium/high strength of encryption; default is all available
* ciphers [high,medium,low]; high means des3 or rc4 (128); medium des or
* rc4-56; low is rc4-40.
* javax.security.sasl.maxbuf
* specifies max receive buf size; default is 65536
* javax.security.sasl.sendmaxbuffer
* specifies max send buf size; default is 65536 (min of this and client's max
* recv size)
*
* com.sun.security.sasl.digest.utf8:
* "true" means to use UTF-8 charset; "false" to use ISO-8859-1 encoding;
* default is "true".
* com.sun.security.sasl.digest.realm:
* space-separated list of realms; default is server name (fqdn parameter)
*
* @author Rosanna Lee
*/
final class DigestMD5Server extends DigestMD5Base implements SaslServer {
private static final String MY_CLASS_NAME = DigestMD5Server.class.getName();
private static final String UTF8_DIRECTIVE = "charset=utf-8,";
private static final String ALGORITHM_DIRECTIVE = "algorithm=md5-sess";
/*
* Always expect nonce count value to be 1 because we support only
* initial authentication.
*/
private static final int NONCE_COUNT_VALUE = 1;
/* "true" means use UTF8; "false" ISO 8859-1; default is "true" */
private static final String UTF8_PROPERTY =
"com.sun.security.sasl.digest.utf8";
/* List of space-separated realms used for authentication */
private static final String REALM_PROPERTY =
"com.sun.security.sasl.digest.realm";
/* Directives encountered in responses sent by the client. */
private static final String[] DIRECTIVE_KEY = {
"username", // exactly once
"realm", // exactly once if sent by server
"nonce", // exactly once
"cnonce", // exactly once
"nonce-count", // atmost once; default is 00000001
"qop", // atmost once; default is "auth"
"digest-uri", // atmost once; (default?)
"response", // exactly once
"maxbuf", // atmost once; default is 65536
"charset", // atmost once; default is ISO-8859-1
"cipher", // exactly once if qop is "auth-conf"
"authzid", // atmost once; default is none
"auth-param", // >= 0 times (ignored)
};
/* Indices into DIRECTIVE_KEY */
private static final int USERNAME = 0;
private static final int REALM = 1;
private static final int NONCE = 2;
private static final int CNONCE = 3;
private static final int NONCE_COUNT = 4;
private static final int QOP = 5;
private static final int DIGEST_URI = 6;
private static final int RESPONSE = 7;
private static final int MAXBUF = 8;
private static final int CHARSET = 9;
private static final int CIPHER = 10;
private static final int AUTHZID = 11;
private static final int AUTH_PARAM = 12;
/* Server-generated/supplied information */
private String specifiedQops;
private byte[] myCiphers;
private List<String> serverRealms;
DigestMD5Server(String protocol, String serverName, Map<String, ?> props,
CallbackHandler cbh) throws SaslException {
super(props, MY_CLASS_NAME, 1,
protocol + "/" + (serverName==null?"*":serverName),
cbh);
serverRealms = new ArrayList<String>();
useUTF8 = true; // default
if (props != null) {
specifiedQops = (String) props.get(Sasl.QOP);
if ("false".equals((String) props.get(UTF8_PROPERTY))) {
useUTF8 = false;
logger.log(Level.FINE, "DIGEST80:Server supports ISO-Latin-1");
}
String realms = (String) props.get(REALM_PROPERTY);
if (realms != null) {
StringTokenizer parser = new StringTokenizer(realms, ", \t\n");
int tokenCount = parser.countTokens();
String token = null;
for (int i = 0; i < tokenCount; i++) {
token = parser.nextToken();
logger.log(Level.FINE, "DIGEST81:Server supports realm {0}",
token);
serverRealms.add(token);
}
}
}
encoding = (useUTF8 ? "UTF8" : "8859_1");
// By default, use server name as realm
if (serverRealms.isEmpty()) {
if (serverName == null) {
throw new SaslException(
"A realm must be provided in props or serverName");
} else {
serverRealms.add(serverName);
}
}
}
public byte[] evaluateResponse(byte[] response) throws SaslException {
if (response.length > MAX_RESPONSE_LENGTH) {
throw new SaslException(
"DIGEST-MD5: Invalid digest response length. Got: " +
response.length + " Expected < " + MAX_RESPONSE_LENGTH);
}
byte[] challenge;
switch (step) {
case 1:
if (response.length != 0) {
throw new SaslException(
"DIGEST-MD5 must not have an initial response");
}
/* Generate first challenge */
String supportedCiphers = null;
if ((allQop&PRIVACY_PROTECTION) != 0) {
myCiphers = getPlatformCiphers();
StringBuilder sb = new StringBuilder();
// myCipher[i] is a byte that indicates whether CIPHER_TOKENS[i]
// is supported
for (int i = 0; i < CIPHER_TOKENS.length; i++) {
if (myCiphers[i] != 0) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(CIPHER_TOKENS[i]);
}
}
supportedCiphers = sb.toString();
}
try {
challenge = generateChallenge(serverRealms, specifiedQops,
supportedCiphers);
step = 3;
return challenge;
} catch (UnsupportedEncodingException e) {
throw new SaslException(
"DIGEST-MD5: Error encoding challenge", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: Error generating challenge", e);
}
// Step 2 is performed by client
case 3:
/* Validates client's response and generate challenge:
* response-auth = "rspauth" "=" response-value
*/
try {
byte[][] responseVal = parseDirectives(response, DIRECTIVE_KEY,
null, REALM);
challenge = validateClientResponse(responseVal);
} catch (SaslException e) {
throw e;
} catch (UnsupportedEncodingException e) {
throw new SaslException(
"DIGEST-MD5: Error validating client response", e);
} finally {
step = 0; // Set to invalid state
}
completed = true;
/* Initialize SecurityCtx implementation */
if (integrity && privacy) {
secCtx = new DigestPrivacy(false /* not client */);
} else if (integrity) {
secCtx = new DigestIntegrity(false /* not client */);
}
return challenge;
default:
// No other possible state
throw new SaslException("DIGEST-MD5: Server at illegal state");
}
}
/**
* Generates challenge to be sent to client.
* digest-challenge =
* 1#( realm | nonce | qop-options | stale | maxbuf | charset
* algorithm | cipher-opts | auth-param )
*
* realm = "realm" "=" <"> realm-value <">
* realm-value = qdstr-val
* nonce = "nonce" "=" <"> nonce-value <">
* nonce-value = qdstr-val
* qop-options = "qop" "=" <"> qop-list <">
* qop-list = 1#qop-value
* qop-value = "auth" | "auth-int" | "auth-conf" |
* token
* stale = "stale" "=" "true"
* maxbuf = "maxbuf" "=" maxbuf-value
* maxbuf-value = 1*DIGIT
* charset = "charset" "=" "utf-8"
* algorithm = "algorithm" "=" "md5-sess"
* cipher-opts = "cipher" "=" <"> 1#cipher-value <">
* cipher-value = "3des" | "des" | "rc4-40" | "rc4" |
* "rc4-56" | token
* auth-param = token "=" ( token | quoted-string )
*/
private byte[] generateChallenge(List<String> realms, String qopStr,
String cipherStr) throws UnsupportedEncodingException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Realms (>= 0)
for (int i = 0; realms != null && i < realms.size(); i++) {
out.write("realm=\"".getBytes(encoding));
writeQuotedStringValue(out, realms.get(i).getBytes(encoding));
out.write('"');
out.write(',');
}
// Nonce - required (1)
out.write(("nonce=\"").getBytes(encoding));
nonce = generateNonce();
writeQuotedStringValue(out, nonce);
out.write('"');
out.write(',');
// QOP - optional (1) [default: auth]
// qop="auth,auth-conf,auth-int"
if (qopStr != null) {
out.write(("qop=\"").getBytes(encoding));
// Check for quotes in case of non-standard qop options
writeQuotedStringValue(out, qopStr.getBytes(encoding));
out.write('"');
out.write(',');
}
// maxbuf - optional (1) [default: 65536]
if (recvMaxBufSize != DEFAULT_MAXBUF) {
out.write(("maxbuf=\"" + recvMaxBufSize + "\",").getBytes(encoding));
}
// charset - optional (1) [default: ISO 8859_1]
if (useUTF8) {
out.write(UTF8_DIRECTIVE.getBytes(encoding));
}
if (cipherStr != null) {
out.write("cipher=\"".getBytes(encoding));
// Check for quotes in case of custom ciphers
writeQuotedStringValue(out, cipherStr.getBytes(encoding));
out.write('"');
out.write(',');
}
// algorithm - required (1)
out.write(ALGORITHM_DIRECTIVE.getBytes(encoding));
return out.toByteArray();
}
/**
* Validates client's response.
* digest-response = 1#( username | realm | nonce | cnonce |
* nonce-count | qop | digest-uri | response |
* maxbuf | charset | cipher | authzid |
* auth-param )
*
* username = "username" "=" <"> username-value <">
* username-value = qdstr-val
* cnonce = "cnonce" "=" <"> cnonce-value <">
* cnonce-value = qdstr-val
* nonce-count = "nc" "=" nc-value
* nc-value = 8LHEX
* qop = "qop" "=" qop-value
* digest-uri = "digest-uri" "=" <"> digest-uri-value <">
* digest-uri-value = serv-type "/" host [ "/" serv-name ]
* serv-type = 1*ALPHA
* host = 1*( ALPHA | DIGIT | "-" | "." )
* serv-name = host
* response = "response" "=" response-value
* response-value = 32LHEX
* LHEX = "0" | "1" | "2" | "3" |
* "4" | "5" | "6" | "7" |
* "8" | "9" | "a" | "b" |
* "c" | "d" | "e" | "f"
* cipher = "cipher" "=" cipher-value
* authzid = "authzid" "=" <"> authzid-value <">
* authzid-value = qdstr-val
* sets:
* negotiatedQop
* negotiatedCipher
* negotiatedRealm
* negotiatedStrength
* digestUri (checked and set to clients to account for case diffs)
* sendMaxBufSize
* authzid (gotten from callback)
* @return response-value ('rspauth') for client to validate
*/
private byte[] validateClientResponse(byte[][] responseVal)
throws SaslException, UnsupportedEncodingException {
/* CHARSET: optional atmost once */
if (responseVal[CHARSET] != null) {
// The client should send this directive only if the server has
// indicated it supports UTF-8.
if (!useUTF8 ||
!"utf-8".equals(new String(responseVal[CHARSET], encoding))) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Incompatible charset value: " +
new String(responseVal[CHARSET]));
}
}
// maxbuf: atmost once
int clntMaxBufSize =
(responseVal[MAXBUF] == null) ? DEFAULT_MAXBUF
: Integer.parseInt(new String(responseVal[MAXBUF], encoding));
// Max send buf size is min of client's max recv buf size and
// server's max send buf size
sendMaxBufSize = ((sendMaxBufSize == 0) ? clntMaxBufSize :
Math.min(sendMaxBufSize, clntMaxBufSize));
/* username: exactly once */
String username;
if (responseVal[USERNAME] != null) {
username = new String(responseVal[USERNAME], encoding);
logger.log(Level.FINE, "DIGEST82:Username: {0}", username);
} else {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Missing username.");
}
/* realm: exactly once if sent by server */
negotiatedRealm = ((responseVal[REALM] != null) ?
new String(responseVal[REALM], encoding) : "");
logger.log(Level.FINE, "DIGEST83:Client negotiated realm: {0}",
negotiatedRealm);
if (!serverRealms.contains(negotiatedRealm)) {
// Server had sent at least one realm
// Check that response is one of these
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Nonexistent realm: " + negotiatedRealm);
}
// Else, client specified realm was one of server's or server had none
/* nonce: exactly once */
if (responseVal[NONCE] == null) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Missing nonce.");
}
byte[] nonceFromClient = responseVal[NONCE];
if (!Arrays.equals(nonceFromClient, nonce)) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Mismatched nonce.");
}
/* cnonce: exactly once */
if (responseVal[CNONCE] == null) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Missing cnonce.");
}
byte[] cnonce = responseVal[CNONCE];
/* nonce-count: atmost once */
if (responseVal[NONCE_COUNT] != null &&
NONCE_COUNT_VALUE != Integer.parseInt(
new String(responseVal[NONCE_COUNT], encoding), 16)) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Nonce count does not match: " +
new String(responseVal[NONCE_COUNT]));
}
/* qop: atmost once; default is "auth" */
negotiatedQop = ((responseVal[QOP] != null) ?
new String(responseVal[QOP], encoding) : "auth");
logger.log(Level.FINE, "DIGEST84:Client negotiated qop: {0}",
negotiatedQop);
// Check that QOP is one sent by server
byte cQop;
switch (negotiatedQop) {
case "auth":
cQop = NO_PROTECTION;
break;
case "auth-int":
cQop = INTEGRITY_ONLY_PROTECTION;
integrity = true;
rawSendSize = sendMaxBufSize - 16;
break;
case "auth-conf":
cQop = PRIVACY_PROTECTION;
integrity = privacy = true;
rawSendSize = sendMaxBufSize - 26;
break;
default:
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Invalid QOP: " + negotiatedQop);
}
if ((cQop&allQop) == 0) {
throw new SaslException("DIGEST-MD5: server does not support " +
" qop: " + negotiatedQop);
}
if (privacy) {
negotiatedCipher = ((responseVal[CIPHER] != null) ?
new String(responseVal[CIPHER], encoding) : null);
if (negotiatedCipher == null) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. No cipher specified.");
}
int foundCipher = -1;
logger.log(Level.FINE, "DIGEST85:Client negotiated cipher: {0}",
negotiatedCipher);
// Check that cipher is one that we offered
for (int j = 0; j < CIPHER_TOKENS.length; j++) {
if (negotiatedCipher.equals(CIPHER_TOKENS[j]) &&
myCiphers[j] != 0) {
foundCipher = j;
break;
}
}
if (foundCipher == -1) {
throw new SaslException("DIGEST-MD5: server does not " +
"support cipher: " + negotiatedCipher);
}
// Set negotiatedStrength
if ((CIPHER_MASKS[foundCipher]&HIGH_STRENGTH) != 0) {
negotiatedStrength = "high";
} else if ((CIPHER_MASKS[foundCipher]&MEDIUM_STRENGTH) != 0) {
negotiatedStrength = "medium";
} else {
// assume default low
negotiatedStrength = "low";
}
logger.log(Level.FINE, "DIGEST86:Negotiated strength: {0}",
negotiatedStrength);
}
// atmost once
String digestUriFromResponse = ((responseVal[DIGEST_URI]) != null ?
new String(responseVal[DIGEST_URI], encoding) : null);
if (digestUriFromResponse != null) {
logger.log(Level.FINE, "DIGEST87:digest URI: {0}",
digestUriFromResponse);
}
// serv-type "/" host [ "/" serv-name ]
// e.g.: smtp/mail3.example.com/example.com
// e.g.: ftp/ftp.example.com
// e.g.: ldap/ldapserver.example.com
// host should match one of service's configured service names
// Check against digest URI that mech was created with
if (uriMatches(digestUri, digestUriFromResponse)) {
digestUri = digestUriFromResponse; // account for case-sensitive diffs
} else {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Mismatched URI: " + digestUriFromResponse +
"; expecting: " + digestUri);
}
// response: exactly once
byte[] responseFromClient = responseVal[RESPONSE];
if (responseFromClient == null) {
throw new SaslException("DIGEST-MD5: digest response format " +
" violation. Missing response.");
}
// authzid: atmost once
byte[] authzidBytes;
String authzidFromClient = ((authzidBytes=responseVal[AUTHZID]) != null?
new String(authzidBytes, encoding) : username);
if (authzidBytes != null) {
logger.log(Level.FINE, "DIGEST88:Authzid: {0}",
new String(authzidBytes));
}
// Ignore auth-param
// Get password need to generate verifying response
char[] passwd;
try {
// Realm and Name callbacks are used to provide info
RealmCallback rcb = new RealmCallback("DIGEST-MD5 realm: ",
negotiatedRealm);
NameCallback ncb = new NameCallback("DIGEST-MD5 authentication ID: ",
username);
// PasswordCallback is used to collect info
PasswordCallback pcb =
new PasswordCallback("DIGEST-MD5 password: ", false);
cbh.handle(new Callback[] {rcb, ncb, pcb});
passwd = pcb.getPassword();
pcb.clearPassword();
} catch (UnsupportedCallbackException e) {
throw new SaslException(
"DIGEST-MD5: Cannot perform callback to acquire password", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: IO error acquiring password", e);
}
if (passwd == null) {
throw new SaslException(
"DIGEST-MD5: cannot acquire password for " + username +
" in realm : " + negotiatedRealm);
}
try {
// Validate response value sent by client
byte[] expectedResponse;
try {
expectedResponse = generateResponseValue("AUTHENTICATE",
digestUri, negotiatedQop, username, negotiatedRealm,
passwd, nonce /* use own nonce */,
cnonce, NONCE_COUNT_VALUE, authzidBytes);
} catch (NoSuchAlgorithmException e) {
throw new SaslException(
"DIGEST-MD5: problem duplicating client response", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: problem duplicating client response", e);
}
if (!Arrays.equals(responseFromClient, expectedResponse)) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Mismatched response.");
}
// Ensure that authzid mapping is OK
try {
AuthorizeCallback acb =
new AuthorizeCallback(username, authzidFromClient);
cbh.handle(new Callback[]{acb});
if (acb.isAuthorized()) {
authzid = acb.getAuthorizedID();
} else {
throw new SaslException("DIGEST-MD5: " + username +
" is not authorized to act as " + authzidFromClient);
}
} catch (SaslException e) {
throw e;
} catch (UnsupportedCallbackException e) {
throw new SaslException(
"DIGEST-MD5: Cannot perform callback to check authzid", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: IO error checking authzid", e);
}
return generateResponseAuth(username, passwd, cnonce,
NONCE_COUNT_VALUE, authzidBytes);
} finally {
// Clear password
for (int i = 0; i < passwd.length; i++) {
passwd[i] = 0;
}
}
}
private static boolean uriMatches(String thisUri, String incomingUri) {
// Full match
if (thisUri.equalsIgnoreCase(incomingUri)) {
return true;
}
// Unbound match
if (thisUri.endsWith("/*")) {
int protoAndSlash = thisUri.length() - 1;
String thisProtoAndSlash = thisUri.substring(0, protoAndSlash);
String incomingProtoAndSlash = incomingUri.substring(0, protoAndSlash);
return thisProtoAndSlash.equalsIgnoreCase(incomingProtoAndSlash);
}
return false;
}
/**
* Server sends a message formatted as follows:
* response-auth = "rspauth" "=" response-value
* where response-value is calculated as above, using the values sent in
* step two, except that if qop is "auth", then A2 is
*
* A2 = { ":", digest-uri-value }
*
* And if qop is "auth-int" or "auth-conf" then A2 is
*
* A2 = { ":", digest-uri-value, ":00000000000000000000000000000000" }
*
* Clears password afterwards.
*/
private byte[] generateResponseAuth(String username, char[] passwd,
byte[] cnonce, int nonceCount, byte[] authzidBytes) throws SaslException {
// Construct response value
try {
byte[] responseValue = generateResponseValue("",
digestUri, negotiatedQop, username, negotiatedRealm,
passwd, nonce, cnonce, nonceCount, authzidBytes);
byte[] challenge = new byte[responseValue.length + 8];
System.arraycopy("rspauth=".getBytes(encoding), 0, challenge, 0, 8);
System.arraycopy(responseValue, 0, challenge, 8,
responseValue.length );
return challenge;
} catch (NoSuchAlgorithmException e) {
throw new SaslException("DIGEST-MD5: problem generating response", e);
} catch (IOException e) {
throw new SaslException("DIGEST-MD5: problem generating response", e);
}
}
public String getAuthorizationID() {
if (completed) {
return authzid;
} else {
throw new IllegalStateException(
"DIGEST-MD5 server negotiation not complete");
}
}
}

View file

@ -0,0 +1,123 @@
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.digest;
import java.util.Map;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import com.sun.security.sasl.util.PolicyUtils;
/**
* Client and server factory for DIGEST-MD5 SASL client/server mechanisms.
* See DigestMD5Client and DigestMD5Server for input requirements.
*
* @author Jonathan Bruce
* @author Rosanna Lee
*/
public final class FactoryImpl implements SaslClientFactory,
SaslServerFactory{
private static final String[] myMechs = { "DIGEST-MD5" };
private static final int DIGEST_MD5 = 0;
private static final int[] mechPolicies = {
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS};
/**
* Empty constructor.
*/
public FactoryImpl() {
}
/**
* Returns a new instance of the DIGEST-MD5 SASL client mechanism.
*
* @throws SaslException If there is an error creating the DigestMD5
* SASL client.
* @return a new SaslClient; otherwise null if unsuccessful.
*/
public SaslClient createSaslClient(String[] mechs,
String authorizationId, String protocol, String serverName,
Map<String,?> props, CallbackHandler cbh)
throws SaslException {
for (int i=0; i<mechs.length; i++) {
if (mechs[i].equals(myMechs[DIGEST_MD5]) &&
PolicyUtils.checkPolicy(mechPolicies[DIGEST_MD5], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for RealmChoiceCallback, " +
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new DigestMD5Client(authorizationId,
protocol, serverName, props, cbh);
}
}
return null;
}
/**
* Returns a new instance of the DIGEST-MD5 SASL server mechanism.
*
* @throws SaslException If there is an error creating the DigestMD5
* SASL server.
* @return a new SaslServer; otherwise null if unsuccessful.
*/
public SaslServer createSaslServer(String mech,
String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
throws SaslException {
if (mech.equals(myMechs[DIGEST_MD5]) &&
PolicyUtils.checkPolicy(mechPolicies[DIGEST_MD5], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for AuthorizeCallback, "+
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new DigestMD5Server(protocol, serverName, props, cbh);
}
return null;
}
/**
* Returns the authentication mechanisms that this factory can produce.
*
* @return String[] {"DigestMD5"} if policies in env match those of this
* factory.
*/
public String[] getMechanismNames(Map<String,?> env) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, env);
}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.digest;
import javax.security.sasl.SaslException;
/**
* Interface used for classes implementing integrity checking and privacy
* for DIGEST-MD5 SASL mechanism implementation.
*
* @see <a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>
* - Using Digest Authentication as a SASL Mechanism
*
* @author Jonathan Bruce
*/
interface SecurityCtx {
/**
* Wrap out-going message and return wrapped message
*
* @throws SaslException
*/
byte[] wrap(byte[] dest, int start, int len)
throws SaslException;
/**
* Unwrap incoming message and return original message
*
* @throws SaslException
*/
byte[] unwrap(byte[] outgoing, int start, int len)
throws SaslException;
}

View file

@ -0,0 +1,125 @@
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.ntlm;
import java.util.Map;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import com.sun.security.sasl.util.PolicyUtils;
/**
* Client and server factory for NTLM SASL client/server mechanisms.
* See NTLMClient and NTLMServer for input requirements.
*
* @since 1.7
*/
public final class FactoryImpl implements SaslClientFactory,
SaslServerFactory{
private static final String[] myMechs = { "NTLM" };
private static final int[] mechPolicies = {
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS
};
/**
* Empty constructor.
*/
public FactoryImpl() {
}
/**
* Returns a new instance of the NTLM SASL client mechanism.
* Argument checks are performed in SaslClient's constructor.
* @return a new SaslClient; otherwise null if unsuccessful.
* @throws SaslException If there is an error creating the NTLM
* SASL client.
*/
public SaslClient createSaslClient(String[] mechs,
String authorizationId, String protocol, String serverName,
Map<String,?> props, CallbackHandler cbh)
throws SaslException {
for (int i=0; i<mechs.length; i++) {
if (mechs[i].equals("NTLM") &&
PolicyUtils.checkPolicy(mechPolicies[0], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for " +
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new NTLMClient(mechs[i], authorizationId,
protocol, serverName, props, cbh);
}
}
return null;
}
/**
* Returns a new instance of the NTLM SASL server mechanism.
* Argument checks are performed in SaslServer's constructor.
* @return a new SaslServer; otherwise null if unsuccessful.
* @throws SaslException If there is an error creating the NTLM
* SASL server.
*/
public SaslServer createSaslServer(String mech,
String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
throws SaslException {
if (mech.equals("NTLM") &&
PolicyUtils.checkPolicy(mechPolicies[0], props)) {
if (props != null) {
String qop = (String)props.get(Sasl.QOP);
if (qop != null && !qop.equals("auth")) {
throw new SaslException("NTLM only support auth");
}
}
if (cbh == null) {
throw new SaslException(
"Callback handler with support for " +
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new NTLMServer(mech, protocol, serverName, props, cbh);
}
return null;
}
/**
* Returns the authentication mechanisms that this factory can produce.
*
* @return String[] {"NTLM"} if policies in env match those of this
* factory.
*/
public String[] getMechanismNames(Map<String,?> env) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, env);
}
}

View file

@ -0,0 +1,243 @@
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.ntlm;
import com.sun.security.ntlm.Client;
import com.sun.security.ntlm.NTLMException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Random;
import javax.security.auth.callback.Callback;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Required callbacks:
* - RealmCallback
* handle can provide domain info for authentication, optional
* - NameCallback
* handler must enter username to use for authentication
* - PasswordCallback
* handler must enter password for username to use for authentication
*
* Environment properties that affect behavior of implementation:
*
* javax.security.sasl.qop
* String, quality of protection; only "auth" is accepted, default "auth"
*
* com.sun.security.sasl.ntlm.version
* String, name a specific version to use; can be:
* LM/NTLM: Original NTLM v1
* LM: Original NTLM v1, LM only
* NTLM: Original NTLM v1, NTLM only
* NTLM2: NTLM v1 with Client Challenge
* LMv2/NTLMv2: NTLM v2
* LMv2: NTLM v2, LM only
* NTLMv2: NTLM v2, NTLM only
* If not specified, use system property "ntlm.version". If
* still not specified, use default value "LMv2/NTLMv2".
*
* com.sun.security.sasl.ntlm.random
* java.util.Random, the nonce source to be used in NTLM v2 or NTLM v1 with
* Client Challenge. Default null, an internal java.util.Random object
* will be used
*
* Negotiated Properties:
*
* javax.security.sasl.qop
* Always "auth"
*
* com.sun.security.sasl.html.domain
* The domain for the user, provided by the server
*
* @see <a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>
* - Simple Authentication and Security Layer (SASL)
*
*/
final class NTLMClient implements SaslClient {
private static final String NTLM_VERSION =
"com.sun.security.sasl.ntlm.version";
private static final String NTLM_RANDOM =
"com.sun.security.sasl.ntlm.random";
private final static String NTLM_DOMAIN =
"com.sun.security.sasl.ntlm.domain";
private final static String NTLM_HOSTNAME =
"com.sun.security.sasl.ntlm.hostname";
private final Client client;
private final String mech;
private final Random random;
private int step = 0; // 0-start,1-nego,2-auth,3-done
/**
* @param mech non-null
* @param authorizationId can be null or empty and ignored
* @param protocol non-null for Sasl, useless for NTLM
* @param serverName non-null for Sasl, but can be null for NTLM
* @param props can be null
* @param cbh can be null for Sasl, already null-checked in factory
* @throws SaslException
*/
NTLMClient(String mech, String authzid, String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
this.mech = mech;
String version = null;
Random rtmp = null;
String hostname = null;
if (props != null) {
String qop = (String)props.get(Sasl.QOP);
if (qop != null && !qop.equals("auth")) {
throw new SaslException("NTLM only support auth");
}
version = (String)props.get(NTLM_VERSION);
rtmp = (Random)props.get(NTLM_RANDOM);
hostname = (String)props.get(NTLM_HOSTNAME);
}
this.random = rtmp != null ? rtmp : new Random();
if (version == null) {
version = System.getProperty("ntlm.version");
}
RealmCallback dcb = (serverName != null && !serverName.isEmpty())?
new RealmCallback("Realm: ", serverName) :
new RealmCallback("Realm: ");
NameCallback ncb = (authzid != null && !authzid.isEmpty()) ?
new NameCallback("User name: ", authzid) :
new NameCallback("User name: ");
PasswordCallback pcb =
new PasswordCallback("Password: ", false);
try {
cbh.handle(new Callback[] {dcb, ncb, pcb});
} catch (UnsupportedCallbackException e) {
throw new SaslException("NTLM: Cannot perform callback to " +
"acquire realm, username or password", e);
} catch (IOException e) {
throw new SaslException(
"NTLM: Error acquiring realm, username or password", e);
}
if (hostname == null) {
try {
hostname = InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
hostname = "localhost";
}
}
try {
String name = ncb.getName();
if (name == null) {
name = authzid;
}
String domain = dcb.getText();
if (domain == null) {
domain = serverName;
}
client = new Client(version, hostname,
name,
domain,
pcb.getPassword());
} catch (NTLMException ne) {
throw new SaslException(
"NTLM: client creation failure", ne);
}
}
@Override
public String getMechanismName() {
return mech;
}
@Override
public boolean isComplete() {
return step >= 2;
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
throw new IllegalStateException("Not supported.");
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException {
throw new IllegalStateException("Not supported.");
}
@Override
public Object getNegotiatedProperty(String propName) {
if (!isComplete()) {
throw new IllegalStateException("authentication not complete");
}
switch (propName) {
case Sasl.QOP:
return "auth";
case NTLM_DOMAIN:
return client.getDomain();
default:
return null;
}
}
@Override
public void dispose() throws SaslException {
client.dispose();
}
@Override
public boolean hasInitialResponse() {
return true;
}
@Override
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
step++;
if (step == 1) {
return client.type1();
} else {
try {
byte[] nonce = new byte[8];
random.nextBytes(nonce);
return client.type3(challenge, nonce);
} catch (NTLMException ex) {
throw new SaslException("Type3 creation failed", ex);
}
}
}
}

View file

@ -0,0 +1,240 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.ntlm;
import com.sun.security.ntlm.NTLMException;
import com.sun.security.ntlm.Server;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.Random;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.*;
/**
* Required callbacks:
* - RealmCallback
* used as key by handler to fetch password, optional
* - NameCallback
* used as key by handler to fetch password
* - PasswordCallback
* handler must enter password for username/realm supplied
*
* Environment properties that affect the implementation:
*
* javax.security.sasl.qop
* String, quality of protection; only "auth" is accepted, default "auth"
*
* com.sun.security.sasl.ntlm.version
* String, name a specific version to accept:
* LM/NTLM: Original NTLM v1
* LM: Original NTLM v1, LM only
* NTLM: Original NTLM v1, NTLM only
* NTLM2: NTLM v1 with Client Challenge
* LMv2/NTLMv2: NTLM v2
* LMv2: NTLM v2, LM only
* NTLMv2: NTLM v2, NTLM only
* If not specified, use system property "ntlm.version". If also
* not specified, all versions are accepted.
*
* com.sun.security.sasl.ntlm.domain
* String, the domain of the server, default is server name (fqdn parameter)
*
* com.sun.security.sasl.ntlm.random
* java.util.Random, the nonce source. Default null, an internal
* java.util.Random object will be used
*
* Negotiated Properties:
*
* javax.security.sasl.qop
* Always "auth"
*
* com.sun.security.sasl.ntlm.hostname
* The hostname for the user, provided by the client
*
*/
final class NTLMServer implements SaslServer {
private final static String NTLM_VERSION =
"com.sun.security.sasl.ntlm.version";
private final static String NTLM_DOMAIN =
"com.sun.security.sasl.ntlm.domain";
private final static String NTLM_HOSTNAME =
"com.sun.security.sasl.ntlm.hostname";
private static final String NTLM_RANDOM =
"com.sun.security.sasl.ntlm.random";
private final Random random;
private final Server server;
private byte[] nonce;
private int step = 0;
private String authzId;
private final String mech;
private String hostname;
private String target;
/**
* @param mech not null
* @param protocol not null for Sasl, ignored in NTLM
* @param serverName not null for Sasl, can be null in NTLM. If non-null,
* might be used as domain if not provided in props
* @param props can be null
* @param cbh can be null for Sasl, already null-checked in factory
* @throws SaslException
*/
NTLMServer(String mech, String protocol, String serverName,
Map<String, ?> props, final CallbackHandler cbh)
throws SaslException {
this.mech = mech;
String version = null;
String domain = null;
Random rtmp = null;
if (props != null) {
domain = (String) props.get(NTLM_DOMAIN);
version = (String)props.get(NTLM_VERSION);
rtmp = (Random)props.get(NTLM_RANDOM);
}
random = rtmp != null ? rtmp : new Random();
if (version == null) {
version = System.getProperty("ntlm.version");
}
if (domain == null) {
domain = serverName;
}
if (domain == null) {
throw new SaslException("Domain must be provided as"
+ " the serverName argument or in props");
}
try {
server = new Server(version, domain) {
public char[] getPassword(String ntdomain, String username) {
try {
RealmCallback rcb =
(ntdomain == null || ntdomain.isEmpty())
? new RealmCallback("Domain: ")
: new RealmCallback("Domain: ", ntdomain);
NameCallback ncb = new NameCallback(
"Name: ", username);
PasswordCallback pcb = new PasswordCallback(
"Password: ", false);
cbh.handle(new Callback[] { rcb, ncb, pcb });
char[] passwd = pcb.getPassword();
pcb.clearPassword();
return passwd;
} catch (IOException ioe) {
return null;
} catch (UnsupportedCallbackException uce) {
return null;
}
}
};
} catch (NTLMException ne) {
throw new SaslException(
"NTLM: server creation failure", ne);
}
nonce = new byte[8];
}
@Override
public String getMechanismName() {
return mech;
}
@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
try {
step++;
if (step == 1) {
random.nextBytes(nonce);
return server.type2(response, nonce);
} else {
String[] out = server.verify(response, nonce);
authzId = out[0];
hostname = out[1];
target = out[2];
return null;
}
} catch (NTLMException ex) {
throw new SaslException("NTLM: generate response failure", ex);
}
}
@Override
public boolean isComplete() {
return step >= 2;
}
@Override
public String getAuthorizationID() {
if (!isComplete()) {
throw new IllegalStateException("authentication not complete");
}
return authzId;
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
throw new IllegalStateException("Not supported yet.");
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException {
throw new IllegalStateException("Not supported yet.");
}
@Override
public Object getNegotiatedProperty(String propName) {
if (!isComplete()) {
throw new IllegalStateException("authentication not complete");
}
switch (propName) {
case Sasl.QOP:
return "auth";
case Sasl.BOUND_SERVER_NAME:
return target;
case NTLM_HOSTNAME:
return hostname;
default:
return null;
}
}
@Override
public void dispose() throws SaslException {
return;
}
}

View file

@ -0,0 +1,365 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.util;
import javax.security.sasl.*;
import java.io.*;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import java.util.logging.Level;
import sun.security.util.HexDumpEncoder;
/**
* The base class used by client and server implementations of SASL
* mechanisms to process properties passed in the props argument
* and strings with the same format (e.g., used in digest-md5).
*
* Also contains utilities for doing int to network-byte-order
* transformations.
*
* @author Rosanna Lee
*/
public abstract class AbstractSaslImpl {
protected boolean completed = false;
protected boolean privacy = false;
protected boolean integrity = false;
protected byte[] qop; // ordered list of qops
protected byte allQop; // a mask indicating which QOPs are requested
protected byte[] strength; // ordered list of cipher strengths
// These are relevant only when privacy or integray have been negotiated
protected int sendMaxBufSize = 0; // specified by peer but can override
protected int recvMaxBufSize = 65536; // optionally specified by self
protected int rawSendSize; // derived from sendMaxBufSize
protected String myClassName;
protected AbstractSaslImpl(Map<String, ?> props, String className)
throws SaslException {
myClassName = className;
// Parse properties to set desired context options
if (props != null) {
String prop;
// "auth", "auth-int", "auth-conf"
qop = parseQop(prop=(String)props.get(Sasl.QOP));
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL01:Preferred qop property: {0}", prop);
allQop = combineMasks(qop);
if (logger.isLoggable(Level.FINE)) {
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL02:Preferred qop mask: {0}", allQop);
if (qop.length > 0) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < qop.length; i++) {
str.append(Byte.toString(qop[i]));
str.append(' ');
}
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL03:Preferred qops : {0}", str.toString());
}
}
// "low", "medium", "high"
strength = parseStrength(prop=(String)props.get(Sasl.STRENGTH));
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL04:Preferred strength property: {0}", prop);
if (logger.isLoggable(Level.FINE) && strength.length > 0) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < strength.length; i++) {
str.append(Byte.toString(strength[i]));
str.append(' ');
}
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL05:Cipher strengths: {0}", str.toString());
}
// Max receive buffer size
prop = (String)props.get(Sasl.MAX_BUFFER);
if (prop != null) {
try {
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL06:Max receive buffer size: {0}", prop);
recvMaxBufSize = Integer.parseInt(prop);
} catch (NumberFormatException e) {
throw new SaslException(
"Property must be string representation of integer: " +
Sasl.MAX_BUFFER);
}
}
// Max send buffer size
prop = (String)props.get(MAX_SEND_BUF);
if (prop != null) {
try {
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL07:Max send buffer size: {0}", prop);
sendMaxBufSize = Integer.parseInt(prop);
} catch (NumberFormatException e) {
throw new SaslException(
"Property must be string representation of integer: " +
MAX_SEND_BUF);
}
}
} else {
qop = DEFAULT_QOP;
allQop = NO_PROTECTION;
strength = STRENGTH_MASKS;
}
}
/**
* Determines whether this mechanism has completed.
*
* @return true if has completed; false otherwise;
*/
public boolean isComplete() {
return completed;
}
/**
* Retrieves the negotiated property.
* @exception IllegalStateException if this authentication exchange has
* not completed
*/
public Object getNegotiatedProperty(String propName) {
if (!completed) {
throw new IllegalStateException("SASL authentication not completed");
}
switch (propName) {
case Sasl.QOP:
if (privacy) {
return "auth-conf";
} else if (integrity) {
return "auth-int";
} else {
return "auth";
}
case Sasl.MAX_BUFFER:
return Integer.toString(recvMaxBufSize);
case Sasl.RAW_SEND_SIZE:
return Integer.toString(rawSendSize);
case MAX_SEND_BUF:
return Integer.toString(sendMaxBufSize);
default:
return null;
}
}
protected static final byte combineMasks(byte[] in) {
byte answer = 0;
for (int i = 0; i < in.length; i++) {
answer |= in[i];
}
return answer;
}
protected static final byte findPreferredMask(byte pref, byte[] in) {
for (int i = 0; i < in.length; i++) {
if ((in[i]&pref) != 0) {
return in[i];
}
}
return (byte)0;
}
private static final byte[] parseQop(String qop) throws SaslException {
return parseQop(qop, null, false);
}
protected static final byte[] parseQop(String qop, String[] saveTokens,
boolean ignore) throws SaslException {
if (qop == null) {
return DEFAULT_QOP; // default
}
return parseProp(Sasl.QOP, qop, QOP_TOKENS, QOP_MASKS, saveTokens, ignore);
}
private static final byte[] parseStrength(String strength)
throws SaslException {
if (strength == null) {
return DEFAULT_STRENGTH; // default
}
return parseProp(Sasl.STRENGTH, strength, STRENGTH_TOKENS,
STRENGTH_MASKS, null, false);
}
private static final byte[] parseProp(String propName, String propVal,
String[] vals, byte[] masks, String[] tokens, boolean ignore)
throws SaslException {
StringTokenizer parser = new StringTokenizer(propVal, ", \t\n");
String token;
byte[] answer = new byte[vals.length];
int i = 0;
boolean found;
while (parser.hasMoreTokens() && i < answer.length) {
token = parser.nextToken();
found = false;
for (int j = 0; !found && j < vals.length; j++) {
if (token.equalsIgnoreCase(vals[j])) {
found = true;
answer[i++] = masks[j];
if (tokens != null) {
tokens[j] = token; // save what was parsed
}
}
}
if (!found && !ignore) {
throw new SaslException(
"Invalid token in " + propName + ": " + propVal);
}
}
// Initialize rest of array with 0
for (int j = i; j < answer.length; j++) {
answer[j] = 0;
}
return answer;
}
/**
* Outputs a byte array. Can be null.
*/
protected static final void traceOutput(String srcClass, String srcMethod,
String traceTag, byte[] output) {
traceOutput(srcClass, srcMethod, traceTag, output, 0,
output == null ? 0 : output.length);
}
protected static final void traceOutput(String srcClass, String srcMethod,
String traceTag, byte[] output, int offset, int len) {
try {
int origlen = len;
Level lev;
if (!logger.isLoggable(Level.FINEST)) {
len = Math.min(16, len);
lev = Level.FINER;
} else {
lev = Level.FINEST;
}
String content;
if (output != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream(len);
new HexDumpEncoder().encodeBuffer(
new ByteArrayInputStream(output, offset, len), out);
content = out.toString();
} else {
content = "NULL";
}
// Message id supplied by caller as part of traceTag
logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}",
new Object[] {traceTag, origlen, content});
} catch (Exception e) {
logger.logp(Level.WARNING, srcClass, srcMethod,
"SASLIMPL09:Error generating trace output: {0}", e);
}
}
/**
* Returns the integer represented by 4 bytes in network byte order.
*/
protected static final int networkByteOrderToInt(byte[] buf, int start,
int count) {
if (count > 4) {
throw new IllegalArgumentException("Cannot handle more than 4 bytes");
}
int answer = 0;
for (int i = 0; i < count; i++) {
answer <<= 8;
answer |= ((int)buf[start+i] & 0xff);
}
return answer;
}
/**
* Encodes an integer into 4 bytes in network byte order in the buffer
* supplied.
*/
protected static final void intToNetworkByteOrder(int num, byte[] buf,
int start, int count) {
if (count > 4) {
throw new IllegalArgumentException("Cannot handle more than 4 bytes");
}
for (int i = count-1; i >= 0; i--) {
buf[start+i] = (byte)(num & 0xff);
num >>>= 8;
}
}
// ---------------- Constants -----------------
private static final String SASL_LOGGER_NAME = "javax.security.sasl";
protected static final String MAX_SEND_BUF = "javax.security.sasl.sendmaxbuffer";
/**
* Logger for debug messages
*/
protected static final Logger logger = Logger.getLogger(SASL_LOGGER_NAME);
// default 0 (no protection); 1 (integrity only)
protected static final byte NO_PROTECTION = (byte)1;
protected static final byte INTEGRITY_ONLY_PROTECTION = (byte)2;
protected static final byte PRIVACY_PROTECTION = (byte)4;
protected static final byte LOW_STRENGTH = (byte)1;
protected static final byte MEDIUM_STRENGTH = (byte)2;
protected static final byte HIGH_STRENGTH = (byte)4;
private static final byte[] DEFAULT_QOP = new byte[]{NO_PROTECTION};
private static final String[] QOP_TOKENS = {"auth-conf",
"auth-int",
"auth"};
private static final byte[] QOP_MASKS = {PRIVACY_PROTECTION,
INTEGRITY_ONLY_PROTECTION,
NO_PROTECTION};
private static final byte[] DEFAULT_STRENGTH = new byte[]{
HIGH_STRENGTH, MEDIUM_STRENGTH, LOW_STRENGTH};
private static final String[] STRENGTH_TOKENS = {"low",
"medium",
"high"};
private static final byte[] STRENGTH_MASKS = {LOW_STRENGTH,
MEDIUM_STRENGTH,
HIGH_STRENGTH};
}

View file

@ -0,0 +1,117 @@
/*
* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.util;
import javax.security.sasl.Sasl;
import java.util.Map;
/**
* Static class that contains utilities for dealing with Java SASL
* security policy-related properties.
*
* @author Rosanna Lee
*/
final public class PolicyUtils {
// Can't create one of these
private PolicyUtils() {
}
public final static int NOPLAINTEXT = 0x0001;
public final static int NOACTIVE = 0x0002;
public final static int NODICTIONARY = 0x0004;
public final static int FORWARD_SECRECY = 0x0008;
public final static int NOANONYMOUS = 0x0010;
public final static int PASS_CREDENTIALS = 0x0200;
/**
* Determines whether a mechanism's characteristics, as defined in flags,
* fits the security policy properties found in props.
* @param flags The mechanism's security characteristics
* @param props The security policy properties to check
* @return true if passes; false if fails
*/
public static boolean checkPolicy(int flags, Map<String, ?> props) {
if (props == null) {
return true;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOPLAINTEXT))
&& (flags&NOPLAINTEXT) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOACTIVE))
&& (flags&NOACTIVE) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NODICTIONARY))
&& (flags&NODICTIONARY) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOANONYMOUS))
&& (flags&NOANONYMOUS) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_FORWARD_SECRECY))
&& (flags&FORWARD_SECRECY) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_PASS_CREDENTIALS))
&& (flags&PASS_CREDENTIALS) == 0) {
return false;
}
return true;
}
/**
* Given a list of mechanisms and their characteristics, select the
* subset that conforms to the policies defined in props.
* Useful for SaslXXXFactory.getMechanismNames(props) implementations.
*
*/
public static String[] filterMechs(String[] mechs, int[] policies,
Map<String, ?> props) {
if (props == null) {
return mechs.clone();
}
boolean[] passed = new boolean[mechs.length];
int count = 0;
for (int i = 0; i< mechs.length; i++) {
if (passed[i] = checkPolicy(policies[i], props)) {
++count;
}
}
String[] answer = new String[count];
for (int i = 0, j=0; i< mechs.length; i++) {
if (passed[i]) {
answer[j++] = mechs[i];
}
}
return answer;
}
}

View file

@ -0,0 +1,83 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
/**
* This exception is thrown by a SASL mechanism implementation
* to indicate that the SASL
* exchange has failed due to reasons related to authentication, such as
* an invalid identity, passphrase, or key.
* <p>
* Note that the lack of an AuthenticationException does not mean that
* the failure was not due to an authentication error. A SASL mechanism
* implementation might throw the more general SaslException instead of
* AuthenticationException if it is unable to determine the nature
* of the failure, or if does not want to disclose the nature of
* the failure, for example, due to security reasons.
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class AuthenticationException extends SaslException {
/**
* Constructs a new instance of {@code AuthenticationException}.
* The root exception and the detailed message are null.
*/
public AuthenticationException () {
super();
}
/**
* Constructs a new instance of {@code AuthenticationException}
* with a detailed message.
* The root exception is null.
* @param detail A possibly null string containing details of the exception.
*
* @see java.lang.Throwable#getMessage
*/
public AuthenticationException (String detail) {
super(detail);
}
/**
* Constructs a new instance of {@code AuthenticationException} with a detailed message
* and a root exception.
*
* @param detail A possibly null string containing details of the exception.
* @param ex A possibly null root exception that caused this exception.
*
* @see java.lang.Throwable#getMessage
* @see #getCause
*/
public AuthenticationException (String detail, Throwable ex) {
super(detail, ex);
}
/** Use serialVersionUID from JSR 28 RI for interoperability */
private static final long serialVersionUID = -3579708765071815007L;
}

View file

@ -0,0 +1,145 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import javax.security.auth.callback.Callback;
/**
* This callback is used by {@code SaslServer} to determine whether
* one entity (identified by an authenticated authentication id)
* can act on
* behalf of another entity (identified by an authorization id).
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class AuthorizeCallback implements Callback, java.io.Serializable {
/**
* The (authenticated) authentication id to check.
* @serial
*/
private String authenticationID;
/**
* The authorization id to check.
* @serial
*/
private String authorizationID;
/**
* The id of the authorized entity. If null, the id of
* the authorized entity is authorizationID.
* @serial
*/
private String authorizedID;
/**
* A flag indicating whether the authentication id is allowed to
* act on behalf of the authorization id.
* @serial
*/
private boolean authorized;
/**
* Constructs an instance of {@code AuthorizeCallback}.
*
* @param authnID The (authenticated) authentication id.
* @param authzID The authorization id.
*/
public AuthorizeCallback(String authnID, String authzID) {
authenticationID = authnID;
authorizationID = authzID;
}
/**
* Returns the authentication id to check.
* @return The authentication id to check.
*/
public String getAuthenticationID() {
return authenticationID;
}
/**
* Returns the authorization id to check.
* @return The authentication id to check.
*/
public String getAuthorizationID() {
return authorizationID;
}
/**
* Determines whether the authentication id is allowed to
* act on behalf of the authorization id.
*
* @return {@code true} if authorization is allowed; {@code false} otherwise
* @see #setAuthorized(boolean)
* @see #getAuthorizedID()
*/
public boolean isAuthorized() {
return authorized;
}
/**
* Sets whether the authorization is allowed.
* @param ok {@code true} if authorization is allowed; {@code false} otherwise
* @see #isAuthorized
* @see #setAuthorizedID(java.lang.String)
*/
public void setAuthorized(boolean ok) {
authorized = ok;
}
/**
* Returns the id of the authorized user.
* @return The id of the authorized user. {@code null} means the
* authorization failed.
* @see #setAuthorized(boolean)
* @see #setAuthorizedID(java.lang.String)
*/
public String getAuthorizedID() {
if (!authorized) {
return null;
}
return (authorizedID == null) ? authorizationID : authorizedID;
}
/**
* Sets the id of the authorized entity. Called by handler only when the id
* is different from getAuthorizationID(). For example, the id
* might need to be canonicalized for the environment in which it
* will be used.
* @param id The id of the authorized user.
* @see #setAuthorized(boolean)
* @see #getAuthorizedID
*/
public void setAuthorizedID(String id) {
authorizedID = id;
}
private static final long serialVersionUID = -2353344186490470805L;
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import javax.security.auth.callback.TextInputCallback;
/**
* This callback is used by {@code SaslClient} and {@code SaslServer}
* to retrieve realm information.
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class RealmCallback extends TextInputCallback {
/**
* Constructs a {@code RealmCallback} with a prompt.
*
* @param prompt The non-null prompt to use to request the realm information.
* @throws IllegalArgumentException If {@code prompt} is null or
* the empty string.
*/
public RealmCallback(String prompt) {
super(prompt);
}
/**
* Constructs a {@code RealmCallback} with a prompt and default
* realm information.
*
* @param prompt The non-null prompt to use to request the realm information.
* @param defaultRealmInfo The non-null default realm information to use.
* @throws IllegalArgumentException If {@code prompt} is null or
* the empty string,
* or if {@code defaultRealm} is empty or null.
*/
public RealmCallback(String prompt, String defaultRealmInfo) {
super(prompt, defaultRealmInfo);
}
private static final long serialVersionUID = -4342673378785456908L;
}

View file

@ -0,0 +1,62 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import javax.security.auth.callback.ChoiceCallback;
/**
* This callback is used by {@code SaslClient} and {@code SaslServer}
* to obtain a realm given a list of realm choices.
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class RealmChoiceCallback extends ChoiceCallback {
/**
* Constructs a {@code RealmChoiceCallback} with a prompt, a list of
* choices and a default choice.
*
* @param prompt the non-null prompt to use to request the realm.
* @param choices the non-null list of realms to choose from.
* @param defaultChoice the choice to be used as the default choice
* when the list of choices is displayed. It is an index into
* the {@code choices} array.
* @param multiple true if multiple choices allowed; false otherwise
* @throws IllegalArgumentException If {@code prompt} is null or the empty string,
* if {@code choices} has a length of 0, if any element from
* {@code choices} is null or empty, or if {@code defaultChoice}
* does not fall within the array boundary of {@code choices}
*/
public RealmChoiceCallback(String prompt, String[]choices,
int defaultChoice, boolean multiple) {
super(prompt, choices, defaultChoice, multiple);
}
private static final long serialVersionUID = -8588141348846281332L;
}

View file

@ -0,0 +1,619 @@
/*
* Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import javax.security.auth.callback.CallbackHandler;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;
/**
* A static class for creating SASL clients and servers.
*<p>
* This class defines the policy of how to locate, load, and instantiate
* SASL clients and servers.
*<p>
* For example, an application or library gets a SASL client by doing
* something like:
*<blockquote><pre>
* SaslClient sc = Sasl.createSaslClient(mechanisms,
* authorizationId, protocol, serverName, props, callbackHandler);
*</pre></blockquote>
* It can then proceed to use the instance to create an authentication connection.
*<p>
* Similarly, a server gets a SASL server by using code that looks as follows:
*<blockquote><pre>
* SaslServer ss = Sasl.createSaslServer(mechanism,
* protocol, serverName, props, callbackHandler);
*</pre></blockquote>
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class Sasl {
// Cannot create one of these
private Sasl() {
}
/**
* The name of a property that specifies the quality-of-protection to use.
* The property contains a comma-separated, ordered list
* of quality-of-protection values that the
* client or server is willing to support. A qop value is one of
* <ul>
* <li>{@code "auth"} - authentication only</li>
* <li>{@code "auth-int"} - authentication plus integrity protection</li>
* <li>{@code "auth-conf"} - authentication plus integrity and confidentiality
* protection</li>
* </ul>
*
* The order of the list specifies the preference order of the client or
* server. If this property is absent, the default qop is {@code "auth"}.
* The value of this constant is {@code "javax.security.sasl.qop"}.
*/
public static final String QOP = "javax.security.sasl.qop";
/**
* The name of a property that specifies the cipher strength to use.
* The property contains a comma-separated, ordered list
* of cipher strength values that
* the client or server is willing to support. A strength value is one of
* <ul>
* <li>{@code "low"}</li>
* <li>{@code "medium"}</li>
* <li>{@code "high"}</li>
* </ul>
* The order of the list specifies the preference order of the client or
* server. An implementation should allow configuration of the meaning
* of these values. An application may use the Java Cryptography
* Extension (JCE) with JCE-aware mechanisms to control the selection of
* cipher suites that match the strength values.
* <BR>
* If this property is absent, the default strength is
* {@code "high,medium,low"}.
* The value of this constant is {@code "javax.security.sasl.strength"}.
*/
public static final String STRENGTH = "javax.security.sasl.strength";
/**
* The name of a property that specifies whether the
* server must authenticate to the client. The property contains
* {@code "true"} if the server must
* authenticate the to client; {@code "false"} otherwise.
* The default is {@code "false"}.
* <br>The value of this constant is
* {@code "javax.security.sasl.server.authentication"}.
*/
public static final String SERVER_AUTH =
"javax.security.sasl.server.authentication";
/**
* The name of a property that specifies the bound server name for
* an unbound server. A server is created as an unbound server by setting
* the {@code serverName} argument in {@link #createSaslServer} as null.
* The property contains the bound host name after the authentication
* exchange has completed. It is only available on the server side.
* <br>The value of this constant is
* {@code "javax.security.sasl.bound.server.name"}.
*/
public static final String BOUND_SERVER_NAME =
"javax.security.sasl.bound.server.name";
/**
* The name of a property that specifies the maximum size of the receive
* buffer in bytes of {@code SaslClient}/{@code SaslServer}.
* The property contains the string representation of an integer.
* <br>If this property is absent, the default size
* is defined by the mechanism.
* <br>The value of this constant is {@code "javax.security.sasl.maxbuffer"}.
*/
public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer";
/**
* The name of a property that specifies the maximum size of the raw send
* buffer in bytes of {@code SaslClient}/{@code SaslServer}.
* The property contains the string representation of an integer.
* The value of this property is negotiated between the client and server
* during the authentication exchange.
* <br>The value of this constant is {@code "javax.security.sasl.rawsendsize"}.
*/
public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize";
/**
* The name of a property that specifies whether to reuse previously
* authenticated session information. The property contains "true" if the
* mechanism implementation may attempt to reuse previously authenticated
* session information; it contains "false" if the implementation must
* not reuse previously authenticated session information. A setting of
* "true" serves only as a hint: it does not necessarily entail actual
* reuse because reuse might not be possible due to a number of reasons,
* including, but not limited to, lack of mechanism support for reuse,
* expiration of reusable information, and the peer's refusal to support
* reuse.
*
* The property's default value is "false". The value of this constant
* is "javax.security.sasl.reuse".
*
* Note that all other parameters and properties required to create a
* SASL client/server instance must be provided regardless of whether
* this property has been supplied. That is, you cannot supply any less
* information in anticipation of reuse.
*
* Mechanism implementations that support reuse might allow customization
* of its implementation, for factors such as cache size, timeouts, and
* criteria for reusability. Such customizations are
* implementation-dependent.
*/
public static final String REUSE = "javax.security.sasl.reuse";
/**
* The name of a property that specifies
* whether mechanisms susceptible to simple plain passive attacks (e.g.,
* "PLAIN") are not permitted. The property
* contains {@code "true"} if such mechanisms are not permitted;
* {@code "false"} if such mechanisms are permitted.
* The default is {@code "false"}.
* <br>The value of this constant is
* {@code "javax.security.sasl.policy.noplaintext"}.
*/
public static final String POLICY_NOPLAINTEXT =
"javax.security.sasl.policy.noplaintext";
/**
* The name of a property that specifies whether
* mechanisms susceptible to active (non-dictionary) attacks
* are not permitted.
* The property contains {@code "true"}
* if mechanisms susceptible to active attacks
* are not permitted; {@code "false"} if such mechanisms are permitted.
* The default is {@code "false"}.
* <br>The value of this constant is
* {@code "javax.security.sasl.policy.noactive"}.
*/
public static final String POLICY_NOACTIVE =
"javax.security.sasl.policy.noactive";
/**
* The name of a property that specifies whether
* mechanisms susceptible to passive dictionary attacks are not permitted.
* The property contains {@code "true"}
* if mechanisms susceptible to dictionary attacks are not permitted;
* {@code "false"} if such mechanisms are permitted.
* The default is {@code "false"}.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.policy.nodictionary"}.
*/
public static final String POLICY_NODICTIONARY =
"javax.security.sasl.policy.nodictionary";
/**
* The name of a property that specifies whether mechanisms that accept
* anonymous login are not permitted. The property contains {@code "true"}
* if mechanisms that accept anonymous login are not permitted;
* {@code "false"}
* if such mechanisms are permitted. The default is {@code "false"}.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.policy.noanonymous"}.
*/
public static final String POLICY_NOANONYMOUS =
"javax.security.sasl.policy.noanonymous";
/**
* The name of a property that specifies whether mechanisms that implement
* forward secrecy between sessions are required. Forward secrecy
* means that breaking into one session will not automatically
* provide information for breaking into future sessions.
* The property
* contains {@code "true"} if mechanisms that implement forward secrecy
* between sessions are required; {@code "false"} if such mechanisms
* are not required. The default is {@code "false"}.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.policy.forward"}.
*/
public static final String POLICY_FORWARD_SECRECY =
"javax.security.sasl.policy.forward";
/**
* The name of a property that specifies whether
* mechanisms that pass client credentials are required. The property
* contains {@code "true"} if mechanisms that pass
* client credentials are required; {@code "false"}
* if such mechanisms are not required. The default is {@code "false"}.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.policy.credentials"}.
*/
public static final String POLICY_PASS_CREDENTIALS =
"javax.security.sasl.policy.credentials";
/**
* The name of a property that specifies the credentials to use.
* The property contains a mechanism-specific Java credential object.
* Mechanism implementations may examine the value of this property
* to determine whether it is a class that they support.
* The property may be used to supply credentials to a mechanism that
* supports delegated authentication.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.credentials"}.
*/
public static final String CREDENTIALS = "javax.security.sasl.credentials";
/**
* Creates a {@code SaslClient} using the parameters supplied.
*
* This method uses the
* {@extLink security_guide_jca JCA Security Provider Framework},
* described in the
* "Java Cryptography Architecture (JCA) Reference Guide", for
* locating and selecting a {@code SaslClient} implementation.
*
* First, it
* obtains an ordered list of {@code SaslClientFactory} instances from
* the registered security providers for the "SaslClientFactory" service
* and the specified SASL mechanism(s). It then invokes
* {@code createSaslClient()} on each factory instance on the list
* until one produces a non-null {@code SaslClient} instance. It returns
* the non-null {@code SaslClient} instance, or null if the search fails
* to produce a non-null {@code SaslClient} instance.
*<p>
* A security provider for SaslClientFactory registers with the
* JCA Security Provider Framework keys of the form <br>
* {@code SaslClientFactory.}<em>{@code mechanism_name}</em>
* <br>
* and values that are class names of implementations of
* {@code javax.security.sasl.SaslClientFactory}.
*
* For example, a provider that contains a factory class,
* {@code com.wiz.sasl.digest.ClientFactory}, that supports the
* "DIGEST-MD5" mechanism would register the following entry with the JCA:
* {@code SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory}
*<p>
* See the
* "Java Cryptography Architecture API Specification &amp; Reference"
* for information about how to install and configure security service
* providers.
*
* @implNote
* The JDK Reference Implementation additionally uses the
* {@code jdk.security.provider.preferred}
* {@link Security#getProperty(String) Security} property to determine
* the preferred provider order for the specified algorithm. This
* may be different than the order of providers returned by
* {@link Security#getProviders() Security.getProviders()}.
*
* @param mechanisms The non-null list of mechanism names to try. Each is the
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param authorizationId The possibly null protocol-dependent
* identification to be used for authorization.
* If null or empty, the server derives an authorization
* ID from the client's authentication credentials.
* When the SASL authentication completes successfully,
* the specified entity is granted access.
*
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
*
* @param serverName The non-null fully-qualified host name of the server
* to authenticate to.
*
* @param props The possibly null set of properties used to
* select the SASL mechanism and to configure the authentication
* exchange of the selected mechanism.
* For example, if {@code props} contains the
* {@code Sasl.POLICY_NOPLAINTEXT} property with the value
* {@code "true"}, then the selected
* SASL mechanism must not be susceptible to simple plain passive attacks.
* In addition to the standard properties declared in this class,
* other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a {@code NameCallback}.
* The password is requested by using a {@code PasswordCallback}.
* The realm is requested by using a {@code RealmChoiceCallback} if there is a list
* of realms to choose from, and by using a {@code RealmCallback} if
* the realm must be entered.
*
*@return A possibly null {@code SaslClient} created using the parameters
* supplied. If null, cannot find a {@code SaslClientFactory}
* that will produce one.
*@exception SaslException If cannot create a {@code SaslClient} because
* of an error.
*/
public static SaslClient createSaslClient(
String[] mechanisms,
String authorizationId,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
SaslClient mech = null;
SaslClientFactory fac;
Service service;
String mechName;
for (int i = 0; i < mechanisms.length; i++) {
if ((mechName=mechanisms[i]) == null) {
throw new NullPointerException(
"Mechanism name cannot be null");
} else if (mechName.length() == 0) {
continue;
}
String type = "SaslClientFactory";
Provider[] provs = Security.getProviders(type + "." + mechName);
if (provs != null) {
for (Provider p : provs) {
service = p.getService(type, mechName);
if (service == null) {
// no such service exists
continue;
}
fac = (SaslClientFactory) loadFactory(service);
if (fac != null) {
mech = fac.createSaslClient(
new String[]{mechanisms[i]}, authorizationId,
protocol, serverName, props, cbh);
if (mech != null) {
return mech;
}
}
}
}
}
return null;
}
private static Object loadFactory(Service service)
throws SaslException {
try {
/*
* Load the implementation class with the same class loader
* that was used to load the provider.
* In order to get the class loader of a class, the
* caller's class loader must be the same as or an ancestor of
* the class loader being returned. Otherwise, the caller must
* have "getClassLoader" permission, or a SecurityException
* will be thrown.
*/
return service.newInstance(null);
} catch (InvalidParameterException | NoSuchAlgorithmException e) {
throw new SaslException("Cannot instantiate service " + service, e);
}
}
/**
* Creates a {@code SaslServer} for the specified mechanism.
*
* This method uses the
* {@extLink security_guide_jca JCA Security Provider Framework},
* described in the
* "Java Cryptography Architecture (JCA) Reference Guide", for
* locating and selecting a {@code SaslClient} implementation.
*
* First, it
* obtains an ordered list of {@code SaslServerFactory} instances from
* the registered security providers for the "SaslServerFactory" service
* and the specified mechanism. It then invokes
* {@code createSaslServer()} on each factory instance on the list
* until one produces a non-null {@code SaslServer} instance. It returns
* the non-null {@code SaslServer} instance, or null if the search fails
* to produce a non-null {@code SaslServer} instance.
*<p>
* A security provider for SaslServerFactory registers with the
* JCA Security Provider Framework keys of the form <br>
* {@code SaslServerFactory.}<em>{@code mechanism_name}</em>
* <br>
* and values that are class names of implementations of
* {@code javax.security.sasl.SaslServerFactory}.
*
* For example, a provider that contains a factory class,
* {@code com.wiz.sasl.digest.ServerFactory}, that supports the
* "DIGEST-MD5" mechanism would register the following entry with the JCA:
* {@code SaslServerFactory.DIGEST-MD5 com.wiz.sasl.digest.ServerFactory}
*<p>
* See the
* "Java Cryptography Architecture API Specification &amp; Reference"
* for information about how to install and configure security
* service providers.
*
* @implNote
* The JDK Reference Implementation additionally uses the
* {@code jdk.security.provider.preferred}
* {@link Security#getProperty(String) Security} property to determine
* the preferred provider order for the specified algorithm. This
* may be different than the order of providers returned by
* {@link Security#getProviders() Security.getProviders()}.
*
* @param mechanism The non-null mechanism name. It must be an
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
* @param serverName The fully qualified host name of the server, or null
* if the server is not bound to any specific host name. If the mechanism
* does not allow an unbound server, a {@code SaslException} will
* be thrown.
* @param props The possibly null set of properties used to
* select the SASL mechanism and to configure the authentication
* exchange of the selected mechanism.
* For example, if {@code props} contains the
* {@code Sasl.POLICY_NOPLAINTEXT} property with the value
* {@code "true"}, then the selected
* SASL mechanism must not be susceptible to simple plain passive attacks.
* In addition to the standard properties declared in this class,
* other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a {@code NameCallback}.
* The password is requested by using a {@code PasswordCallback}.
* The realm is requested by using a {@code RealmChoiceCallback} if there is a list
* of realms to choose from, and by using a {@code RealmCallback} if
* the realm must be entered.
*
*@return A possibly null {@code SaslServer} created using the parameters
* supplied. If null, cannot find a {@code SaslServerFactory}
* that will produce one.
*@exception SaslException If cannot create a {@code SaslServer} because
* of an error.
**/
public static SaslServer
createSaslServer(String mechanism,
String protocol,
String serverName,
Map<String,?> props,
javax.security.auth.callback.CallbackHandler cbh)
throws SaslException {
SaslServer mech = null;
SaslServerFactory fac;
Service service;
if (mechanism == null) {
throw new NullPointerException("Mechanism name cannot be null");
} else if (mechanism.length() == 0) {
return null;
}
String type = "SaslServerFactory";
Provider[] provs = Security.getProviders(type + "." + mechanism);
if (provs != null) {
for (Provider p : provs) {
service = p.getService(type, mechanism);
if (service == null) {
throw new SaslException("Provider does not support " +
mechanism + " " + type);
}
fac = (SaslServerFactory) loadFactory(service);
if (fac != null) {
mech = fac.createSaslServer(
mechanism, protocol, serverName, props, cbh);
if (mech != null) {
return mech;
}
}
}
}
return null;
}
/**
* Gets an enumeration of known factories for producing {@code SaslClient}.
* This method uses the same algorithm for locating factories as
* {@code createSaslClient()}.
* @return A non-null enumeration of known factories for producing
* {@code SaslClient}.
* @see #createSaslClient
*/
public static Enumeration<SaslClientFactory> getSaslClientFactories() {
Set<Object> facs = getFactories("SaslClientFactory");
final Iterator<Object> iter = facs.iterator();
return new Enumeration<SaslClientFactory>() {
public boolean hasMoreElements() {
return iter.hasNext();
}
public SaslClientFactory nextElement() {
return (SaslClientFactory)iter.next();
}
};
}
/**
* Gets an enumeration of known factories for producing {@code SaslServer}.
* This method uses the same algorithm for locating factories as
* {@code createSaslServer()}.
* @return A non-null enumeration of known factories for producing
* {@code SaslServer}.
* @see #createSaslServer
*/
public static Enumeration<SaslServerFactory> getSaslServerFactories() {
Set<Object> facs = getFactories("SaslServerFactory");
final Iterator<Object> iter = facs.iterator();
return new Enumeration<SaslServerFactory>() {
public boolean hasMoreElements() {
return iter.hasNext();
}
public SaslServerFactory nextElement() {
return (SaslServerFactory)iter.next();
}
};
}
private static Set<Object> getFactories(String serviceName) {
HashSet<Object> result = new HashSet<Object>();
if ((serviceName == null) || (serviceName.length() == 0) ||
(serviceName.endsWith("."))) {
return result;
}
Provider[] provs = Security.getProviders();
Object fac;
for (Provider p : provs) {
Iterator<Service> iter = p.getServices().iterator();
while (iter.hasNext()) {
Service s = iter.next();
if (s.getType().equals(serviceName)) {
try {
fac = loadFactory(s);
if (fac != null) {
result.add(fac);
}
} catch (Exception ignore) {
}
}
}
}
return Collections.unmodifiableSet(result);
}
}

View file

@ -0,0 +1,229 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
/**
* Performs SASL authentication as a client.
*<p>
* A protocol library such as one for LDAP gets an instance of this
* class in order to perform authentication defined by a specific SASL
* mechanism. Invoking methods on the {@code SaslClient} instance
* process challenges and create responses according to the SASL
* mechanism implemented by the {@code SaslClient}.
* As the authentication proceeds, the instance
* encapsulates the state of a SASL client's authentication exchange.
*<p>
* Here's an example of how an LDAP library might use a {@code SaslClient}.
* It first gets an instance of a {@code SaslClient}:
*<blockquote><pre>{@code
* SaslClient sc = Sasl.createSaslClient(mechanisms,
* authorizationId, protocol, serverName, props, callbackHandler);
*}</pre></blockquote>
* It can then proceed to use the client for authentication.
* For example, an LDAP library might use the client as follows:
*<blockquote><pre>{@code
* // Get initial response and send to server
* byte[] response = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) :
* null);
* LdapResult res = ldap.sendBindRequest(dn, sc.getName(), response);
* while (!sc.isComplete() &&
* (res.status == SASL_BIND_IN_PROGRESS || res.status == SUCCESS)) {
* response = sc.evaluateChallenge(res.getBytes());
* if (res.status == SUCCESS) {
* // we're done; don't expect to send another BIND
* if (response != null) {
* throw new SaslException(
* "Protocol error: attempting to send response after completion");
* }
* break;
* }
* res = ldap.sendBindRequest(dn, sc.getName(), response);
* }
* if (sc.isComplete() && res.status == SUCCESS) {
* String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
* if (qop != null
* && (qop.equalsIgnoreCase("auth-int")
* || qop.equalsIgnoreCase("auth-conf"))) {
*
* // Use SaslClient.wrap() and SaslClient.unwrap() for future
* // communication with server
* ldap.in = new SecureInputStream(sc, ldap.in);
* ldap.out = new SecureOutputStream(sc, ldap.out);
* }
* }
*}</pre></blockquote>
*
* If the mechanism has an initial response, the library invokes
* {@code evaluateChallenge()} with an empty
* challenge and to get initial response.
* Protocols such as IMAP4, which do not include an initial response with
* their first authentication command to the server, initiates the
* authentication without first calling {@code hasInitialResponse()}
* or {@code evaluateChallenge()}.
* When the server responds to the command, it sends an initial challenge.
* For a SASL mechanism in which the client sends data first, the server should
* have issued a challenge with no data. This will then result in a call
* (on the client) to {@code evaluateChallenge()} with an empty challenge.
*
* @since 1.5
*
* @see Sasl
* @see SaslClientFactory
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public abstract interface SaslClient {
/**
* Returns the IANA-registered mechanism name of this SASL client.
* (e.g. "CRAM-MD5", "GSSAPI").
* @return A non-null string representing the IANA-registered mechanism name.
*/
public abstract String getMechanismName();
/**
* Determines whether this mechanism has an optional initial response.
* If true, caller should call {@code evaluateChallenge()} with an
* empty array to get the initial response.
*
* @return true if this mechanism has an initial response.
*/
public abstract boolean hasInitialResponse();
/**
* Evaluates the challenge data and generates a response.
* If a challenge is received from the server during the authentication
* process, this method is called to prepare an appropriate next
* response to submit to the server.
*
* @param challenge The non-null challenge sent from the server.
* The challenge array may have zero length.
*
* @return The possibly null response to send to the server.
* It is null if the challenge accompanied a "SUCCESS" status and the challenge
* only contains data for the client to update its state and no response
* needs to be sent to the server. The response is a zero-length byte
* array if the client is to send a response with no data.
* @exception SaslException If an error occurred while processing
* the challenge or generating a response.
*/
public abstract byte[] evaluateChallenge(byte[] challenge)
throws SaslException;
/**
* Determines whether the authentication exchange has completed.
* This method may be called at any time, but typically, it
* will not be called until the caller has received indication
* from the server
* (in a protocol-specific manner) that the exchange has completed.
*
* @return true if the authentication exchange has completed; false otherwise.
*/
public abstract boolean isComplete();
/**
* Unwraps a byte array received from the server.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true) and only if
* the authentication exchange has negotiated integrity and/or privacy
* as the quality of protection; otherwise, an
* {@code IllegalStateException} is thrown.
*<p>
* {@code incoming} is the contents of the SASL buffer as defined in RFC 2222
* without the leading four octet field that represents the length.
* {@code offset} and {@code len} specify the portion of {@code incoming}
* to use.
*
* @param incoming A non-null byte array containing the encoded bytes
* from the server.
* @param offset The starting position at {@code incoming} of the bytes to use.
* @param len The number of bytes from {@code incoming} to use.
* @return A non-null byte array containing the decoded bytes.
* @exception SaslException if {@code incoming} cannot be successfully
* unwrapped.
* @exception IllegalStateException if the authentication exchange has
* not completed, or if the negotiated quality of protection
* has neither integrity nor privacy.
*/
public abstract byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException;
/**
* Wraps a byte array to be sent to the server.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true) and only if
* the authentication exchange has negotiated integrity and/or privacy
* as the quality of protection; otherwise, an
* {@code IllegalStateException} is thrown.
*<p>
* The result of this method will make up the contents of the SASL buffer
* as defined in RFC 2222 without the leading four octet field that
* represents the length.
* {@code offset} and {@code len} specify the portion of {@code outgoing}
* to use.
*
* @param outgoing A non-null byte array containing the bytes to encode.
* @param offset The starting position at {@code outgoing} of the bytes to use.
* @param len The number of bytes from {@code outgoing} to use.
* @return A non-null byte array containing the encoded bytes.
* @exception SaslException if {@code outgoing} cannot be successfully
* wrapped.
* @exception IllegalStateException if the authentication exchange has
* not completed, or if the negotiated quality of protection
* has neither integrity nor privacy.
*/
public abstract byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException;
/**
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true); otherwise, an
* {@code IllegalStateException} is thrown.
* <p>
* The {@link Sasl} class includes several well-known property names
* (For example, {@link Sasl#QOP}). A SASL provider can support other
* properties which are specific to the vendor and/or a mechanism.
*
* @param propName The non-null property name.
* @return The value of the negotiated property. If null, the property was
* not negotiated or is not applicable to this mechanism.
* @exception IllegalStateException if this authentication exchange
* has not completed
*/
public abstract Object getNegotiatedProperty(String propName);
/**
* Disposes of any system resources or security-sensitive information
* the SaslClient might be using. Invoking this method invalidates
* the SaslClient instance. This method is idempotent.
* @throws SaslException If a problem was encountered while disposing
* the resources.
*/
public abstract void dispose() throws SaslException;
}

View file

@ -0,0 +1,112 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/**
* An interface for creating instances of {@code SaslClient}.
* A class that implements this interface
* must be thread-safe and handle multiple simultaneous
* requests. It must also have a public constructor that accepts no
* argument.
*<p>
* This interface is not normally accessed directly by a client, which will use the
* {@code Sasl} static methods
* instead. However, a particular environment may provide and install a
* new or different {@code SaslClientFactory}.
*
* @since 1.5
*
* @see SaslClient
* @see Sasl
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public abstract interface SaslClientFactory {
/**
* Creates a SaslClient using the parameters supplied.
*
* @param mechanisms The non-null list of mechanism names to try. Each is the
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param authorizationId The possibly null protocol-dependent
* identification to be used for authorization.
* If null or empty, the server derives an authorization
* ID from the client's authentication credentials.
* When the SASL authentication completes successfully,
* the specified entity is granted access.
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
* @param serverName The non-null fully qualified host name
* of the server to authenticate to.
* @param props The possibly null set of properties used to select the SASL
* mechanism and to configure the authentication exchange of the selected
* mechanism. See the {@code Sasl} class for a list of standard properties.
* Other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a {@code NameCallback}.
* The password is requested by using a {@code PasswordCallback}.
* The realm is requested by using a {@code RealmChoiceCallback} if there is a list
* of realms to choose from, and by using a {@code RealmCallback} if
* the realm must be entered.
*
*@return A possibly null {@code SaslClient} created using the parameters
* supplied. If null, this factory cannot produce a {@code SaslClient}
* using the parameters supplied.
*@exception SaslException If cannot create a {@code SaslClient} because
* of an error.
*/
public abstract SaslClient createSaslClient(
String[] mechanisms,
String authorizationId,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException;
/**
* Returns an array of names of mechanisms that match the specified
* mechanism selection policies.
* @param props The possibly null set of properties used to specify the
* security policy of the SASL mechanisms. For example, if {@code props}
* contains the {@code Sasl.POLICY_NOPLAINTEXT} property with the value
* {@code "true"}, then the factory must not return any SASL mechanisms
* that are susceptible to simple plain passive attacks.
* See the {@code Sasl} class for a complete list of policy properties.
* Non-policy related properties, if present in {@code props}, are ignored,
* including any map entries with non-String keys.
* @return A non-null array containing a IANA-registered SASL mechanism names.
*/
public abstract String[] getMechanismNames(Map<String,?> props);
}

View file

@ -0,0 +1,129 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import java.io.IOException;
/**
* This class represents an error that has occurred when using SASL.
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class SaslException extends IOException {
/**
* The possibly null root cause exception.
* @serial
*/
// Required for serialization interoperability with JSR 28
private Throwable _exception;
/**
* Constructs a new instance of {@code SaslException}.
* The root exception and the detailed message are null.
*/
public SaslException () {
super();
}
/**
* Constructs a new instance of {@code SaslException} with a detailed message.
* The root exception is null.
* @param detail A possibly null string containing details of the exception.
*
* @see java.lang.Throwable#getMessage
*/
public SaslException (String detail) {
super(detail);
}
/**
* Constructs a new instance of {@code SaslException} with a detailed message
* and a root exception.
* For example, a SaslException might result from a problem with
* the callback handler, which might throw a NoSuchCallbackException if
* it does not support the requested callback, or throw an IOException
* if it had problems obtaining data for the callback. The
* SaslException's root exception would be then be the exception thrown
* by the callback handler.
*
* @param detail A possibly null string containing details of the exception.
* @param ex A possibly null root exception that caused this exception.
*
* @see java.lang.Throwable#getMessage
* @see #getCause
*/
public SaslException (String detail, Throwable ex) {
super(detail);
if (ex != null) {
initCause(ex);
}
}
/*
* Override Throwable.getCause() to ensure deserialized object from
* JSR 28 would return same value for getCause() (i.e., _exception).
*/
public Throwable getCause() {
return _exception;
}
/*
* Override Throwable.initCause() to match getCause() by updating
* _exception as well.
*/
public Throwable initCause(Throwable cause) {
super.initCause(cause);
_exception = cause;
return this;
}
/**
* Returns the string representation of this exception.
* The string representation contains
* this exception's class name, its detailed message, and if
* it has a root exception, the string representation of the root
* exception. This string representation
* is meant for debugging and not meant to be interpreted
* programmatically.
* @return The non-null string representation of this exception.
* @see java.lang.Throwable#getMessage
*/
// Override Throwable.toString() to conform to JSR 28
public String toString() {
String answer = super.toString();
if (_exception != null && _exception != this) {
answer += " [Caused by " + _exception.toString() + "]";
}
return answer;
}
/** Use serialVersionUID from JSR 28 RI for interoperability */
private static final long serialVersionUID = 4579784287983423626L;
}

View file

@ -0,0 +1,220 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
/**
* Performs SASL authentication as a server.
*<p>
* A server such an LDAP server gets an instance of this
* class in order to perform authentication defined by a specific SASL
* mechanism. Invoking methods on the {@code SaslServer} instance
* generates challenges according to the SASL
* mechanism implemented by the {@code SaslServer}.
* As the authentication proceeds, the instance
* encapsulates the state of a SASL server's authentication exchange.
*<p>
* Here's an example of how an LDAP server might use a {@code SaslServer}.
* It first gets an instance of a {@code SaslServer} for the SASL mechanism
* requested by the client:
*<blockquote><pre>
* SaslServer ss = Sasl.createSaslServer(mechanism,
* "ldap", myFQDN, props, callbackHandler);
*</pre></blockquote>
* It can then proceed to use the server for authentication.
* For example, suppose the LDAP server received an LDAP BIND request
* containing the name of the SASL mechanism and an (optional) initial
* response. It then might use the server as follows:
*<blockquote><pre>{@code
* while (!ss.isComplete()) {
* try {
* byte[] challenge = ss.evaluateResponse(response);
* if (ss.isComplete()) {
* status = ldap.sendBindResponse(mechanism, challenge, SUCCESS);
* } else {
* status = ldap.sendBindResponse(mechanism, challenge,
SASL_BIND_IN_PROGRESS);
* response = ldap.readBindRequest();
* }
* } catch (SaslException e) {
* status = ldap.sendErrorResponse(e);
* break;
* }
* }
* if (ss.isComplete() && status == SUCCESS) {
* String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
* if (qop != null
* && (qop.equalsIgnoreCase("auth-int")
* || qop.equalsIgnoreCase("auth-conf"))) {
*
* // Use SaslServer.wrap() and SaslServer.unwrap() for future
* // communication with client
* ldap.in = new SecureInputStream(ss, ldap.in);
* ldap.out = new SecureOutputStream(ss, ldap.out);
* }
* }
*}</pre></blockquote>
*
* @since 1.5
*
* @see Sasl
* @see SaslServerFactory
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public abstract interface SaslServer {
/**
* Returns the IANA-registered mechanism name of this SASL server.
* (e.g. "CRAM-MD5", "GSSAPI").
* @return A non-null string representing the IANA-registered mechanism name.
*/
public abstract String getMechanismName();
/**
* Evaluates the response data and generates a challenge.
*
* If a response is received from the client during the authentication
* process, this method is called to prepare an appropriate next
* challenge to submit to the client. The challenge is null if the
* authentication has succeeded and no more challenge data is to be sent
* to the client. It is non-null if the authentication must be continued
* by sending a challenge to the client, or if the authentication has
* succeeded but challenge data needs to be processed by the client.
* {@code isComplete()} should be called
* after each call to {@code evaluateResponse()},to determine if any further
* response is needed from the client.
*
* @param response The non-null (but possibly empty) response sent
* by the client.
*
* @return The possibly null challenge to send to the client.
* It is null if the authentication has succeeded and there is
* no more challenge data to be sent to the client.
* @exception SaslException If an error occurred while processing
* the response or generating a challenge.
*/
public abstract byte[] evaluateResponse(byte[] response)
throws SaslException;
/**
* Determines whether the authentication exchange has completed.
* This method is typically called after each invocation of
* {@code evaluateResponse()} to determine whether the
* authentication has completed successfully or should be continued.
* @return true if the authentication exchange has completed; false otherwise.
*/
public abstract boolean isComplete();
/**
* Reports the authorization ID in effect for the client of this
* session.
* This method can only be called if isComplete() returns true.
* @return The authorization ID of the client.
* @exception IllegalStateException if this authentication session has not completed
*/
public String getAuthorizationID();
/**
* Unwraps a byte array received from the client.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true) and only if
* the authentication exchange has negotiated integrity and/or privacy
* as the quality of protection; otherwise,
* an {@code IllegalStateException} is thrown.
*<p>
* {@code incoming} is the contents of the SASL buffer as defined in RFC 2222
* without the leading four octet field that represents the length.
* {@code offset} and {@code len} specify the portion of {@code incoming}
* to use.
*
* @param incoming A non-null byte array containing the encoded bytes
* from the client.
* @param offset The starting position at {@code incoming} of the bytes to use.
* @param len The number of bytes from {@code incoming} to use.
* @return A non-null byte array containing the decoded bytes.
* @exception SaslException if {@code incoming} cannot be successfully
* unwrapped.
* @exception IllegalStateException if the authentication exchange has
* not completed, or if the negotiated quality of protection
* has neither integrity nor privacy
*/
public abstract byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException;
/**
* Wraps a byte array to be sent to the client.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true) and only if
* the authentication exchange has negotiated integrity and/or privacy
* as the quality of protection; otherwise, a {@code SaslException} is thrown.
*<p>
* The result of this method
* will make up the contents of the SASL buffer as defined in RFC 2222
* without the leading four octet field that represents the length.
* {@code offset} and {@code len} specify the portion of {@code outgoing}
* to use.
*
* @param outgoing A non-null byte array containing the bytes to encode.
* @param offset The starting position at {@code outgoing} of the bytes to use.
* @param len The number of bytes from {@code outgoing} to use.
* @return A non-null byte array containing the encoded bytes.
* @exception SaslException if {@code outgoing} cannot be successfully
* wrapped.
* @exception IllegalStateException if the authentication exchange has
* not completed, or if the negotiated quality of protection has
* neither integrity nor privacy.
*/
public abstract byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException;
/**
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true); otherwise, an
* {@code IllegalStateException} is thrown.
* <p>
* The {@link Sasl} class includes several well-known property names
* (For example, {@link Sasl#QOP}). A SASL provider can support other
* properties which are specific to the vendor and/or a mechanism.
*
* @param propName the property
* @return The value of the negotiated property. If null, the property was
* not negotiated or is not applicable to this mechanism.
* @exception IllegalStateException if this authentication exchange has not completed
*/
public abstract Object getNegotiatedProperty(String propName);
/**
* Disposes of any system resources or security-sensitive information
* the SaslServer might be using. Invoking this method invalidates
* the SaslServer instance. This method is idempotent.
* @throws SaslException If a problem was encountered while disposing
* the resources.
*/
public abstract void dispose() throws SaslException;
}

View file

@ -0,0 +1,111 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/**
* An interface for creating instances of {@code SaslServer}.
* A class that implements this interface
* must be thread-safe and handle multiple simultaneous
* requests. It must also have a public constructor that accepts no
* argument.
*<p>
* This interface is not normally accessed directly by a server, which will use the
* {@code Sasl} static methods
* instead. However, a particular environment may provide and install a
* new or different {@code SaslServerFactory}.
*
* @since 1.5
*
* @see SaslServer
* @see Sasl
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public abstract interface SaslServerFactory {
/**
* Creates a {@code SaslServer} using the parameters supplied.
* It returns null
* if no {@code SaslServer} can be created using the parameters supplied.
* Throws {@code SaslException} if it cannot create a {@code SaslServer}
* because of an error.
*
* @param mechanism The non-null
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
* @param serverName The fully qualified host name of the server to
* authenticate to, or null if the server is not bound to any specific host
* name. If the mechanism does not allow an unbound server, a
* {@code SaslException} will be thrown.
* @param props The possibly null set of properties used to select the SASL
* mechanism and to configure the authentication exchange of the selected
* mechanism. See the {@code Sasl} class for a list of standard properties.
* Other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a {@code NameCallback}.
* The password is requested by using a {@code PasswordCallback}.
* The realm is requested by using a {@code RealmChoiceCallback} if there is a list
* of realms to choose from, and by using a {@code RealmCallback} if
* the realm must be entered.
*
*@return A possibly null {@code SaslServer} created using the parameters
* supplied. If null, this factory cannot produce a {@code SaslServer}
* using the parameters supplied.
*@exception SaslException If cannot create a {@code SaslServer} because
* of an error.
*/
public abstract SaslServer createSaslServer(
String mechanism,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException;
/**
* Returns an array of names of mechanisms that match the specified
* mechanism selection policies.
* @param props The possibly null set of properties used to specify the
* security policy of the SASL mechanisms. For example, if {@code props}
* contains the {@code Sasl.POLICY_NOPLAINTEXT} property with the value
* {@code "true"}, then the factory must not return any SASL mechanisms
* that are susceptible to simple plain passive attacks.
* See the {@code Sasl} class for a complete list of policy properties.
* Non-policy related properties, if present in {@code props}, are ignored,
* including any map entries with non-String keys.
* @return A non-null array containing a IANA-registered SASL mechanism names.
*/
public abstract String[] getMechanismNames(Map<String,?> props);
}

View file

@ -0,0 +1,103 @@
/*
* Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Contains class and interfaces for supporting SASL.
*
* This package defines classes and interfaces for SASL mechanisms.
* It is used by developers to add authentication support for
* connection-based protocols that use SASL.
*
* <h3>SASL Overview</h3>
*
* Simple Authentication and Security Layer (SASL) specifies a
* challenge-response protocol in which data is exchanged between the
* client and the server for the purposes of
* authentication and (optional) establishment of a security layer on
* which to carry on subsequent communications. It is used with
* connection-based protocols such as LDAPv3 or IMAPv4. SASL is
* described in
* <A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>.
*
*
* There are various <em>mechanisms</em> defined for SASL.
* Each mechanism defines the data that must be exchanged between the
* client and server in order for the authentication to succeed.
* This data exchange required for a particular mechanism is referred to
* to as its <em>protocol profile</em>.
* The following are some examples of mechanisms that have been defined by
* the Internet standards community.
* <ul>
* <li>DIGEST-MD5 (<A HREF="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>).
* This mechanism defines how HTTP Digest Authentication can be used as a SASL
* mechanism.
* <li>Anonymous (<A HREF="http://www.ietf.org/rfc/rfc2245.txt">RFC 2245</a>).
* This mechanism is anonymous authentication in which no credentials are
* necessary.
* <li>External (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
* This mechanism obtains authentication information
* from an external source (such as TLS or IPsec).
* <li>S/Key (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
* This mechanism uses the MD4 digest algorithm to exchange data based on
* a shared secret.
* <li>GSSAPI (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
* This mechanism uses the
* <A HREF="http://www.ietf.org/rfc/rfc2078.txt">GSSAPI</A>
* for obtaining authentication information.
* </ul>
*
* Some of these mechanisms provide both authentication and establishment
* of a security layer, others only authentication. Anonymous and
* S/Key do not provide for any security layers. GSSAPI and DIGEST-MD5
* allow negotiation of the security layer. For External, the
* security layer is determined by the external protocol.
*
* <h3>Usage</h3>
*
* Users of this API are typically developers who produce
* client library implementations for connection-based protocols,
* such as LDAPv3 and IMAPv4,
* and developers who write servers (such as LDAP servers and IMAP servers).
* Developers who write client libraries use the
* {@code SaslClient} and {@code SaslClientFactory} interfaces.
* Developers who write servers use the
* {@code SaslServer} and {@code SaslServerFactory} interfaces.
*
* Among these two groups of users, each can be further divided into two groups:
* those who <em>produce</em> the SASL mechanisms and those
* who <em>use</em> the SASL mechanisms.
* The producers of SASL mechanisms need to provide implementations
* for these interfaces, while users of the SASL mechanisms use
* the APIs in this package to access those implementations.
*
* <h2>Related Documentation</h2>
*
* Please refer to the
* {@extLink security_guide_sasl Java SASL Programming Guide}
* for information on how to use this API.
*
* @since 1.5
*/
package javax.security.sasl;

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Defines Java support for the IETF Simple Authentication and Security Layer
* (SASL).
* <P>
* This module also contains SASL mechanisms including DIGEST-MD5,
* CRAM-MD5, and NTLM.
*
* @moduleGraph
* @since 9
*/
module java.security.sasl {
requires java.logging;
exports javax.security.sasl;
exports com.sun.security.sasl.util to
jdk.security.jgss;
provides java.security.Provider with
com.sun.security.sasl.Provider;
}