feat(jdk8): move files to new folder to avoid resources compiled.
This commit is contained in:
160
jdkSrc/jdk8/com/sun/security/sasl/ClientFactoryImpl.java
Normal file
160
jdkSrc/jdk8/com/sun/security/sasl/ClientFactoryImpl.java
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
228
jdkSrc/jdk8/com/sun/security/sasl/CramMD5Base.java
Normal file
228
jdkSrc/jdk8/com/sun/security/sasl/CramMD5Base.java
Normal file
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
* Copyright (c) 2003, 2019, 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 {@codeisComplete()} returns true); otherwise, a
|
||||
* {@codeSaslException} 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;
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
StringBuffer digestString = new StringBuffer();
|
||||
|
||||
for (i = 0; i < digest.length; i++) {
|
||||
if ((digest[i] & 0x000000ff) < 0x10) {
|
||||
digestString.append("0" +
|
||||
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
|
||||
}
|
||||
130
jdkSrc/jdk8/com/sun/security/sasl/CramMD5Client.java
Normal file
130
jdkSrc/jdk8/com/sun/security/sasl/CramMD5Client.java
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
250
jdkSrc/jdk8/com/sun/security/sasl/CramMD5Server.java
Normal file
250
jdkSrc/jdk8/com/sun/security/sasl/CramMD5Server.java
Normal 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();
|
||||
|
||||
StringBuffer buf = new StringBuffer();
|
||||
buf.append('<');
|
||||
buf.append(rand);
|
||||
buf.append('.');
|
||||
buf.append(timestamp);
|
||||
buf.append('@');
|
||||
buf.append(fqdn);
|
||||
buf.append('>');
|
||||
String challengeStr = buf.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");
|
||||
}
|
||||
}
|
||||
}
|
||||
159
jdkSrc/jdk8/com/sun/security/sasl/ExternalClient.java
Normal file
159
jdkSrc/jdk8/com/sun/security/sasl/ExternalClient.java
Normal file
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Copyright (c) 1999, 2019, 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, a
|
||||
* {@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");
|
||||
}
|
||||
}
|
||||
}
|
||||
205
jdkSrc/jdk8/com/sun/security/sasl/PlainClient.java
Normal file
205
jdkSrc/jdk8/com/sun/security/sasl/PlainClient.java
Normal file
@@ -0,0 +1,205 @@
|
||||
/*
|
||||
* Copyright (c) 2000, 2019, 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 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;
|
||||
}
|
||||
}
|
||||
|
||||
protected void finalize() {
|
||||
clearPassword();
|
||||
}
|
||||
}
|
||||
88
jdkSrc/jdk8/com/sun/security/sasl/Provider.java
Normal file
88
jdkSrc/jdk8/com/sun/security/sasl/Provider.java
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* 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 com.sun.security.sasl;
|
||||
|
||||
import java.security.AccessController;
|
||||
import java.security.PrivilegedAction;
|
||||
|
||||
/**
|
||||
* The SASL provider.
|
||||
* Provides client support for
|
||||
* - EXTERNAL
|
||||
* - PLAIN
|
||||
* - CRAM-MD5
|
||||
* - DIGEST-MD5
|
||||
* - GSSAPI/Kerberos v5
|
||||
* - NTLM
|
||||
* And server support for
|
||||
* - CRAM-MD5
|
||||
* - DIGEST-MD5
|
||||
* - GSSAPI/Kerberos v5
|
||||
* - 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, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5, NTLM;" +
|
||||
" server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5, NTLM)";
|
||||
|
||||
public Provider() {
|
||||
super("SunSASL", 1.8d, info);
|
||||
|
||||
AccessController.doPrivileged(new PrivilegedAction<Void>() {
|
||||
public Void run() {
|
||||
// Client mechanisms
|
||||
put("SaslClientFactory.DIGEST-MD5",
|
||||
"com.sun.security.sasl.digest.FactoryImpl");
|
||||
put("SaslClientFactory.NTLM",
|
||||
"com.sun.security.sasl.ntlm.FactoryImpl");
|
||||
put("SaslClientFactory.GSSAPI",
|
||||
"com.sun.security.sasl.gsskerb.FactoryImpl");
|
||||
|
||||
put("SaslClientFactory.EXTERNAL",
|
||||
"com.sun.security.sasl.ClientFactoryImpl");
|
||||
put("SaslClientFactory.PLAIN",
|
||||
"com.sun.security.sasl.ClientFactoryImpl");
|
||||
put("SaslClientFactory.CRAM-MD5",
|
||||
"com.sun.security.sasl.ClientFactoryImpl");
|
||||
|
||||
// Server mechanisms
|
||||
put("SaslServerFactory.CRAM-MD5",
|
||||
"com.sun.security.sasl.ServerFactoryImpl");
|
||||
put("SaslServerFactory.GSSAPI",
|
||||
"com.sun.security.sasl.gsskerb.FactoryImpl");
|
||||
put("SaslServerFactory.DIGEST-MD5",
|
||||
"com.sun.security.sasl.digest.FactoryImpl");
|
||||
put("SaslServerFactory.NTLM",
|
||||
"com.sun.security.sasl.ntlm.FactoryImpl");
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
78
jdkSrc/jdk8/com/sun/security/sasl/ServerFactoryImpl.java
Normal file
78
jdkSrc/jdk8/com/sun/security/sasl/ServerFactoryImpl.java
Normal 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);
|
||||
}
|
||||
}
|
||||
1626
jdkSrc/jdk8/com/sun/security/sasl/digest/DigestMD5Base.java
Normal file
1626
jdkSrc/jdk8/com/sun/security/sasl/digest/DigestMD5Base.java
Normal file
File diff suppressed because it is too large
Load Diff
700
jdkSrc/jdk8/com/sun/security/sasl/digest/DigestMD5Client.java
Normal file
700
jdkSrc/jdk8/com/sun/security/sasl/digest/DigestMD5Client.java
Normal file
@@ -0,0 +1,700 @@
|
||||
/*
|
||||
* Copyright (c) 2000, 2019, 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}",
|
||||
new Integer(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
|
||||
* @returns {@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;
|
||||
}
|
||||
}
|
||||
}
|
||||
724
jdkSrc/jdk8/com/sun/security/sasl/digest/DigestMD5Server.java
Normal file
724
jdkSrc/jdk8/com/sun/security/sasl/digest/DigestMD5Server.java
Normal 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();
|
||||
StringBuffer buf = new StringBuffer();
|
||||
|
||||
// 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 (buf.length() > 0) {
|
||||
buf.append(',');
|
||||
}
|
||||
buf.append(CIPHER_TOKENS[i]);
|
||||
}
|
||||
}
|
||||
supportedCiphers = buf.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");
|
||||
}
|
||||
}
|
||||
}
|
||||
123
jdkSrc/jdk8/com/sun/security/sasl/digest/FactoryImpl.java
Normal file
123
jdkSrc/jdk8/com/sun/security/sasl/digest/FactoryImpl.java
Normal 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);
|
||||
}
|
||||
}
|
||||
57
jdkSrc/jdk8/com/sun/security/sasl/digest/SecurityCtx.java
Normal file
57
jdkSrc/jdk8/com/sun/security/sasl/digest/SecurityCtx.java
Normal 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;
|
||||
}
|
||||
97
jdkSrc/jdk8/com/sun/security/sasl/gsskerb/FactoryImpl.java
Normal file
97
jdkSrc/jdk8/com/sun/security/sasl/gsskerb/FactoryImpl.java
Normal file
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* 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.gsskerb;
|
||||
|
||||
import javax.security.sasl.*;
|
||||
import com.sun.security.sasl.util.PolicyUtils;
|
||||
|
||||
import java.util.Map;
|
||||
import javax.security.auth.callback.CallbackHandler;
|
||||
|
||||
/**
|
||||
* Client/server factory for GSSAPI (Kerberos V5) SASL client/server mechs.
|
||||
* See GssKrb5Client/GssKrb5Server for input requirements.
|
||||
*
|
||||
* @author Rosanna Lee
|
||||
*/
|
||||
public final class FactoryImpl implements SaslClientFactory, SaslServerFactory {
|
||||
private static final String myMechs[] = {
|
||||
"GSSAPI"};
|
||||
|
||||
private static final int mechPolicies[] = {
|
||||
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS|PolicyUtils.NOACTIVE
|
||||
};
|
||||
|
||||
private static final int GSS_KERB_V5 = 0;
|
||||
|
||||
public FactoryImpl() {
|
||||
}
|
||||
|
||||
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[GSS_KERB_V5])
|
||||
&& PolicyUtils.checkPolicy(mechPolicies[GSS_KERB_V5], props)) {
|
||||
return new GssKrb5Client(
|
||||
authorizationId,
|
||||
protocol,
|
||||
serverName,
|
||||
props,
|
||||
cbh);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
public SaslServer createSaslServer(String mech,
|
||||
String protocol,
|
||||
String serverName,
|
||||
Map<String,?> props,
|
||||
CallbackHandler cbh) throws SaslException {
|
||||
if (mech.equals(myMechs[GSS_KERB_V5])
|
||||
&& PolicyUtils.checkPolicy(mechPolicies[GSS_KERB_V5], props)) {
|
||||
if (cbh == null) {
|
||||
throw new SaslException(
|
||||
"Callback handler with support for AuthorizeCallback required");
|
||||
}
|
||||
return new GssKrb5Server(
|
||||
protocol,
|
||||
serverName,
|
||||
props,
|
||||
cbh);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
public String[] getMechanismNames(Map<String,?> props) {
|
||||
return PolicyUtils.filterMechs(myMechs, mechPolicies, props);
|
||||
}
|
||||
}
|
||||
151
jdkSrc/jdk8/com/sun/security/sasl/gsskerb/GssKrb5Base.java
Normal file
151
jdkSrc/jdk8/com/sun/security/sasl/gsskerb/GssKrb5Base.java
Normal file
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Copyright (c) 2003, 2019, 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.gsskerb;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import javax.security.sasl.*;
|
||||
import com.sun.security.sasl.util.AbstractSaslImpl;
|
||||
import org.ietf.jgss.*;
|
||||
|
||||
abstract class GssKrb5Base extends AbstractSaslImpl {
|
||||
|
||||
private static final String KRB5_OID_STR = "1.2.840.113554.1.2.2";
|
||||
protected static Oid KRB5_OID;
|
||||
protected static final byte[] EMPTY = new byte[0];
|
||||
|
||||
static {
|
||||
try {
|
||||
KRB5_OID = new Oid(KRB5_OID_STR);
|
||||
} catch (GSSException ignore) {}
|
||||
}
|
||||
|
||||
protected GSSContext secCtx = null;
|
||||
protected static final int JGSS_QOP = 0; // unrelated to SASL QOP mask
|
||||
|
||||
protected GssKrb5Base(Map<String, ?> props, String className)
|
||||
throws SaslException {
|
||||
super(props, className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves this mechanism's name.
|
||||
*
|
||||
* @return The string "GSSAPI".
|
||||
*/
|
||||
public String getMechanismName() {
|
||||
return "GSSAPI";
|
||||
}
|
||||
|
||||
public byte[] unwrap(byte[] incoming, int start, int len)
|
||||
throws SaslException {
|
||||
if (!completed) {
|
||||
throw new IllegalStateException("GSSAPI authentication not completed");
|
||||
}
|
||||
|
||||
// integrity will be true if either privacy or integrity negotiated
|
||||
if (!integrity) {
|
||||
throw new IllegalStateException("No security layer negotiated");
|
||||
}
|
||||
|
||||
try {
|
||||
MessageProp msgProp = new MessageProp(JGSS_QOP, false);
|
||||
byte[] answer = secCtx.unwrap(incoming, start, len, msgProp);
|
||||
if (privacy && !msgProp.getPrivacy()) {
|
||||
throw new SaslException("Privacy not protected");
|
||||
}
|
||||
checkMessageProp("", msgProp);
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
traceOutput(myClassName, "KRB501:Unwrap", "incoming: ",
|
||||
incoming, start, len);
|
||||
traceOutput(myClassName, "KRB502:Unwrap", "unwrapped: ",
|
||||
answer, 0, answer.length);
|
||||
}
|
||||
return answer;
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("Problems unwrapping SASL buffer", e);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] wrap(byte[] outgoing, int start, int len) throws SaslException {
|
||||
if (!completed) {
|
||||
throw new IllegalStateException("GSSAPI authentication not completed");
|
||||
}
|
||||
|
||||
// integrity will be true if either privacy or integrity negotiated
|
||||
if (!integrity) {
|
||||
throw new IllegalStateException("No security layer negotiated");
|
||||
}
|
||||
|
||||
// Generate GSS token
|
||||
try {
|
||||
MessageProp msgProp = new MessageProp(JGSS_QOP, privacy);
|
||||
byte[] answer = secCtx.wrap(outgoing, start, len, msgProp);
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
traceOutput(myClassName, "KRB503:Wrap", "outgoing: ",
|
||||
outgoing, start, len);
|
||||
traceOutput(myClassName, "KRB504:Wrap", "wrapped: ",
|
||||
answer, 0, answer.length);
|
||||
}
|
||||
return answer;
|
||||
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("Problem performing GSS wrap", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void dispose() throws SaslException {
|
||||
if (secCtx != null) {
|
||||
try {
|
||||
secCtx.dispose();
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("Problem disposing GSS context", e);
|
||||
}
|
||||
secCtx = null;
|
||||
}
|
||||
}
|
||||
|
||||
protected void finalize() throws Throwable {
|
||||
dispose();
|
||||
}
|
||||
|
||||
void checkMessageProp(String label, MessageProp msgProp)
|
||||
throws SaslException {
|
||||
if (msgProp.isDuplicateToken()) {
|
||||
throw new SaslException(label + "Duplicate token");
|
||||
}
|
||||
if (msgProp.isGapToken()) {
|
||||
throw new SaslException(label + "Gap token");
|
||||
}
|
||||
if (msgProp.isOldToken()) {
|
||||
throw new SaslException(label + "Old token");
|
||||
}
|
||||
if (msgProp.isUnseqToken()) {
|
||||
throw new SaslException(label + "Token not in sequence");
|
||||
}
|
||||
}
|
||||
}
|
||||
331
jdkSrc/jdk8/com/sun/security/sasl/gsskerb/GssKrb5Client.java
Normal file
331
jdkSrc/jdk8/com/sun/security/sasl/gsskerb/GssKrb5Client.java
Normal file
@@ -0,0 +1,331 @@
|
||||
/*
|
||||
* Copyright (c) 2000, 2019, 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.gsskerb;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import javax.security.sasl.*;
|
||||
|
||||
// JAAS
|
||||
import javax.security.auth.callback.CallbackHandler;
|
||||
|
||||
// JGSS
|
||||
import org.ietf.jgss.*;
|
||||
|
||||
/**
|
||||
* Implements the GSSAPI SASL client mechanism for Kerberos V5.
|
||||
* (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>,
|
||||
* <a HREF="http://www.ietf.org/internet-drafts/draft-ietf-cat-sasl-gssapi-04.txt">draft-ietf-cat-sasl-gssapi-04.txt</a>).
|
||||
* It uses the Java Bindings for GSSAPI
|
||||
* (<A HREF="http://www.ietf.org/rfc/rfc2853.txt">RFC 2853</A>)
|
||||
* for getting GSSAPI/Kerberos V5 support.
|
||||
*
|
||||
* The client/server interactions are:
|
||||
* C0: bind (GSSAPI, initial response)
|
||||
* S0: sasl-bind-in-progress, challenge 1 (output of accept_sec_context or [])
|
||||
* C1: bind (GSSAPI, response 1 (output of init_sec_context or []))
|
||||
* S1: sasl-bind-in-progress challenge 2 (security layer, server max recv size)
|
||||
* C2: bind (GSSAPI, response 2 (security layer, client max recv size, authzid))
|
||||
* S2: bind success response
|
||||
*
|
||||
* Expects the client's credentials to be supplied from the
|
||||
* javax.security.sasl.credentials property or from the thread's Subject.
|
||||
* Otherwise the underlying KRB5 mech will attempt to acquire Kerberos creds
|
||||
* by logging into Kerberos (via default TextCallbackHandler).
|
||||
* These creds will be used for exchange with server.
|
||||
*
|
||||
* Required callbacks: none.
|
||||
*
|
||||
* 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.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)
|
||||
*
|
||||
* javax.security.sasl.server.authentication
|
||||
* - "true" means require mutual authentication; default is "false"
|
||||
*
|
||||
* javax.security.sasl.credentials
|
||||
* - an {@link org.ietf.jgss.GSSCredential} used for delegated authentication.
|
||||
*
|
||||
* @author Rosanna Lee
|
||||
*/
|
||||
|
||||
final class GssKrb5Client extends GssKrb5Base implements SaslClient {
|
||||
// ---------------- Constants -----------------
|
||||
private static final String MY_CLASS_NAME = GssKrb5Client.class.getName();
|
||||
|
||||
private boolean finalHandshake = false;
|
||||
private boolean mutual = false; // default false
|
||||
private byte[] authzID;
|
||||
|
||||
/**
|
||||
* Creates a SASL mechanism with client credentials that it needs
|
||||
* to participate in GSS-API/Kerberos v5 authentication exchange
|
||||
* with the server.
|
||||
*/
|
||||
GssKrb5Client(String authzID, String protocol, String serverName,
|
||||
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
|
||||
|
||||
super(props, MY_CLASS_NAME);
|
||||
|
||||
String service = protocol + "@" + serverName;
|
||||
logger.log(Level.FINE, "KRB5CLNT01:Requesting service name: {0}",
|
||||
service);
|
||||
|
||||
try {
|
||||
GSSManager mgr = GSSManager.getInstance();
|
||||
|
||||
// Create the name for the requested service entity for Krb5 mech
|
||||
GSSName acceptorName = mgr.createName(service,
|
||||
GSSName.NT_HOSTBASED_SERVICE, KRB5_OID);
|
||||
|
||||
// Parse properties to check for supplied credentials
|
||||
GSSCredential credentials = null;
|
||||
if (props != null) {
|
||||
Object prop = props.get(Sasl.CREDENTIALS);
|
||||
if (prop != null && prop instanceof GSSCredential) {
|
||||
credentials = (GSSCredential) prop;
|
||||
logger.log(Level.FINE,
|
||||
"KRB5CLNT01:Using the credentials supplied in " +
|
||||
"javax.security.sasl.credentials");
|
||||
}
|
||||
}
|
||||
|
||||
// Create a context using credentials for Krb5 mech
|
||||
secCtx = mgr.createContext(acceptorName,
|
||||
KRB5_OID, /* mechanism */
|
||||
credentials, /* credentials */
|
||||
GSSContext.INDEFINITE_LIFETIME);
|
||||
|
||||
// Request credential delegation when credentials have been supplied
|
||||
if (credentials != null) {
|
||||
secCtx.requestCredDeleg(true);
|
||||
}
|
||||
|
||||
// Parse properties to set desired context options
|
||||
if (props != null) {
|
||||
// Mutual authentication
|
||||
String prop = (String)props.get(Sasl.SERVER_AUTH);
|
||||
if (prop != null) {
|
||||
mutual = "true".equalsIgnoreCase(prop);
|
||||
}
|
||||
}
|
||||
secCtx.requestMutualAuth(mutual);
|
||||
|
||||
// Always specify potential need for integrity and confidentiality
|
||||
// Decision will be made during final handshake
|
||||
secCtx.requestConf(true);
|
||||
secCtx.requestInteg(true);
|
||||
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("Failure to initialize security context", e);
|
||||
}
|
||||
|
||||
if (authzID != null && authzID.length() > 0) {
|
||||
try {
|
||||
this.authzID = authzID.getBytes("UTF8");
|
||||
} catch (IOException e) {
|
||||
throw new SaslException("Cannot encode authorization ID", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasInitialResponse() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes the challenge data.
|
||||
*
|
||||
* The server sends a challenge data using which the client must
|
||||
* process using GSS_Init_sec_context.
|
||||
* As per RFC 2222, when GSS_S_COMPLETE is returned, we do
|
||||
* an extra handshake to determine the negotiated security protection
|
||||
* and buffer sizes.
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
public byte[] evaluateChallenge(byte[] challengeData) throws SaslException {
|
||||
if (completed) {
|
||||
throw new IllegalStateException(
|
||||
"GSSAPI authentication already complete");
|
||||
}
|
||||
|
||||
if (finalHandshake) {
|
||||
return doFinalHandshake(challengeData);
|
||||
} else {
|
||||
|
||||
// Security context not established yet; continue with init
|
||||
|
||||
try {
|
||||
byte[] gssOutToken = secCtx.initSecContext(challengeData,
|
||||
0, challengeData.length);
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "evaluteChallenge",
|
||||
"KRB5CLNT02:Challenge: [raw]", challengeData);
|
||||
traceOutput(MY_CLASS_NAME, "evaluateChallenge",
|
||||
"KRB5CLNT03:Response: [after initSecCtx]", gssOutToken);
|
||||
}
|
||||
|
||||
if (secCtx.isEstablished()) {
|
||||
finalHandshake = true;
|
||||
if (gssOutToken == null) {
|
||||
// RFC 2222 7.2.1: Client responds with no data
|
||||
return EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
return gssOutToken;
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("GSS initiate failed", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] doFinalHandshake(byte[] challengeData) throws SaslException {
|
||||
try {
|
||||
// Security context already established. challengeData
|
||||
// should contain security layers and server's maximum buffer size
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "doFinalHandshake",
|
||||
"KRB5CLNT04:Challenge [raw]:", challengeData);
|
||||
}
|
||||
|
||||
if (challengeData.length == 0) {
|
||||
// Received S0, should return []
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
// Received S1 (security layer, server max recv size)
|
||||
|
||||
MessageProp msgProp = new MessageProp(false);
|
||||
byte[] gssOutToken = secCtx.unwrap(challengeData, 0,
|
||||
challengeData.length, msgProp);
|
||||
checkMessageProp("Handshake failure: ", msgProp);
|
||||
|
||||
// First octet is a bit-mask specifying the protections
|
||||
// supported by the server
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "doFinalHandshake",
|
||||
"KRB5CLNT05:Challenge [unwrapped]:", gssOutToken);
|
||||
}
|
||||
logger.log(Level.FINE, "KRB5CLNT06:Server protections: {0}",
|
||||
new Byte(gssOutToken[0]));
|
||||
}
|
||||
|
||||
// Client selects preferred protection
|
||||
// qop is ordered list of qop values
|
||||
byte selectedQop = findPreferredMask(gssOutToken[0], qop);
|
||||
if (selectedQop == 0) {
|
||||
throw new SaslException(
|
||||
"No common protection layer between client and server");
|
||||
}
|
||||
|
||||
if ((selectedQop&PRIVACY_PROTECTION) != 0) {
|
||||
privacy = true;
|
||||
integrity = true;
|
||||
} else if ((selectedQop&INTEGRITY_ONLY_PROTECTION) != 0) {
|
||||
integrity = true;
|
||||
}
|
||||
|
||||
// 2nd-4th octets specifies maximum buffer size expected by
|
||||
// server (in network byte order)
|
||||
int srvMaxBufSize = networkByteOrderToInt(gssOutToken, 1, 3);
|
||||
|
||||
// Determine the max send buffer size based on what the
|
||||
// server is able to receive and our specified max
|
||||
sendMaxBufSize = (sendMaxBufSize == 0) ? srvMaxBufSize :
|
||||
Math.min(sendMaxBufSize, srvMaxBufSize);
|
||||
|
||||
// Update context to limit size of returned buffer
|
||||
rawSendSize = secCtx.getWrapSizeLimit(JGSS_QOP, privacy,
|
||||
sendMaxBufSize);
|
||||
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE,
|
||||
"KRB5CLNT07:Client max recv size: {0}; server max recv size: {1}; rawSendSize: {2}",
|
||||
new Object[] {new Integer(recvMaxBufSize),
|
||||
new Integer(srvMaxBufSize),
|
||||
new Integer(rawSendSize)});
|
||||
}
|
||||
|
||||
// Construct negotiated security layers and client's max
|
||||
// receive buffer size and authzID
|
||||
int len = 4;
|
||||
if (authzID != null) {
|
||||
len += authzID.length;
|
||||
}
|
||||
|
||||
byte[] gssInToken = new byte[len];
|
||||
gssInToken[0] = selectedQop;
|
||||
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE,
|
||||
"KRB5CLNT08:Selected protection: {0}; privacy: {1}; integrity: {2}",
|
||||
new Object[]{new Byte(selectedQop),
|
||||
Boolean.valueOf(privacy),
|
||||
Boolean.valueOf(integrity)});
|
||||
}
|
||||
|
||||
intToNetworkByteOrder(recvMaxBufSize, gssInToken, 1, 3);
|
||||
if (authzID != null) {
|
||||
// copy authorization id
|
||||
System.arraycopy(authzID, 0, gssInToken, 4, authzID.length);
|
||||
logger.log(Level.FINE, "KRB5CLNT09:Authzid: {0}", authzID);
|
||||
}
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "doFinalHandshake",
|
||||
"KRB5CLNT10:Response [raw]", gssInToken);
|
||||
}
|
||||
|
||||
gssOutToken = secCtx.wrap(gssInToken,
|
||||
0, gssInToken.length,
|
||||
new MessageProp(0 /* qop */, false /* privacy */));
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "doFinalHandshake",
|
||||
"KRB5CLNT11:Response [after wrap]", gssOutToken);
|
||||
}
|
||||
|
||||
completed = true; // server authenticated
|
||||
|
||||
return gssOutToken;
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("Final handshake failed", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
367
jdkSrc/jdk8/com/sun/security/sasl/gsskerb/GssKrb5Server.java
Normal file
367
jdkSrc/jdk8/com/sun/security/sasl/gsskerb/GssKrb5Server.java
Normal file
@@ -0,0 +1,367 @@
|
||||
/*
|
||||
* Copyright (c) 2000, 2019, 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.gsskerb;
|
||||
|
||||
import javax.security.sasl.*;
|
||||
import java.io.*;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
|
||||
// JAAS
|
||||
import javax.security.auth.callback.*;
|
||||
|
||||
// JGSS
|
||||
import org.ietf.jgss.*;
|
||||
|
||||
/**
|
||||
* Implements the GSSAPI SASL server mechanism for Kerberos V5.
|
||||
* (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>,
|
||||
* <a HREF="http://www.ietf.org/internet-drafts/draft-ietf-cat-sasl-gssapi-00.txt">draft-ietf-cat-sasl-gssapi-00.txt</a>).
|
||||
*
|
||||
* Expects thread's Subject to contain server's Kerberos credentials
|
||||
* - If not, underlying KRB5 mech will attempt to acquire Kerberos creds
|
||||
* by logging into Kerberos (via default TextCallbackHandler).
|
||||
* - These creds will be used for exchange with client.
|
||||
*
|
||||
* Required callbacks:
|
||||
* - AuthorizeCallback
|
||||
* handler must verify that authid/authzids are allowed and set
|
||||
* authorized ID to be the canonicalized authzid (if applicable).
|
||||
*
|
||||
* 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.maxbuf
|
||||
* - max receive buffer size; default is 65536
|
||||
* javax.security.sasl.sendmaxbuffer
|
||||
* - max send buffer size; default is 65536; (min with client max recv size)
|
||||
*
|
||||
* @author Rosanna Lee
|
||||
*/
|
||||
final class GssKrb5Server extends GssKrb5Base implements SaslServer {
|
||||
private static final String MY_CLASS_NAME = GssKrb5Server.class.getName();
|
||||
|
||||
private int handshakeStage = 0;
|
||||
private String peer;
|
||||
private String me;
|
||||
private String authzid;
|
||||
private CallbackHandler cbh;
|
||||
|
||||
// When serverName is null, the server will be unbound. We need to save and
|
||||
// check the protocol name after the context is established. This value
|
||||
// will be null if serverName is not null.
|
||||
private final String protocolSaved;
|
||||
/**
|
||||
* Creates a SASL mechanism with server credentials that it needs
|
||||
* to participate in GSS-API/Kerberos v5 authentication exchange
|
||||
* with the client.
|
||||
*/
|
||||
GssKrb5Server(String protocol, String serverName,
|
||||
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
|
||||
|
||||
super(props, MY_CLASS_NAME);
|
||||
|
||||
this.cbh = cbh;
|
||||
|
||||
String service;
|
||||
if (serverName == null) {
|
||||
protocolSaved = protocol;
|
||||
service = null;
|
||||
} else {
|
||||
protocolSaved = null;
|
||||
service = protocol + "@" + serverName;
|
||||
}
|
||||
|
||||
logger.log(Level.FINE, "KRB5SRV01:Using service name: {0}", service);
|
||||
|
||||
try {
|
||||
GSSManager mgr = GSSManager.getInstance();
|
||||
|
||||
// Create the name for the requested service entity for Krb5 mech
|
||||
GSSName serviceName = service == null ? null:
|
||||
mgr.createName(service, GSSName.NT_HOSTBASED_SERVICE, KRB5_OID);
|
||||
|
||||
GSSCredential cred = mgr.createCredential(serviceName,
|
||||
GSSCredential.INDEFINITE_LIFETIME,
|
||||
KRB5_OID, GSSCredential.ACCEPT_ONLY);
|
||||
|
||||
// Create a context using the server's credentials
|
||||
secCtx = mgr.createContext(cred);
|
||||
|
||||
if ((allQop&INTEGRITY_ONLY_PROTECTION) != 0) {
|
||||
// Might need integrity
|
||||
secCtx.requestInteg(true);
|
||||
}
|
||||
|
||||
if ((allQop&PRIVACY_PROTECTION) != 0) {
|
||||
// Might need privacy
|
||||
secCtx.requestConf(true);
|
||||
}
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("Failure to initialize security context", e);
|
||||
}
|
||||
logger.log(Level.FINE, "KRB5SRV02:Initialization complete");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Processes the response data.
|
||||
*
|
||||
* The client sends response data to which the server must
|
||||
* process using GSS_accept_sec_context.
|
||||
* As per RFC 2222, the GSS authenication completes (GSS_S_COMPLETE)
|
||||
* we do an extra hand shake to determine the negotiated security protection
|
||||
* and buffer sizes.
|
||||
*
|
||||
* @param responseData A non-null but possible empty byte array containing the
|
||||
* response data from the client.
|
||||
* @return A non-null byte array containing the challenge to be
|
||||
* sent to the client, or null when no more data is to be sent.
|
||||
*/
|
||||
public byte[] evaluateResponse(byte[] responseData) throws SaslException {
|
||||
if (completed) {
|
||||
throw new SaslException(
|
||||
"SASL authentication already complete");
|
||||
}
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "evaluateResponse",
|
||||
"KRB5SRV03:Response [raw]:", responseData);
|
||||
}
|
||||
|
||||
switch (handshakeStage) {
|
||||
case 1:
|
||||
return doHandshake1(responseData);
|
||||
|
||||
case 2:
|
||||
return doHandshake2(responseData);
|
||||
|
||||
default:
|
||||
// Security context not established yet; continue with accept
|
||||
|
||||
try {
|
||||
byte[] gssOutToken = secCtx.acceptSecContext(responseData,
|
||||
0, responseData.length);
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "evaluateResponse",
|
||||
"KRB5SRV04:Challenge: [after acceptSecCtx]", gssOutToken);
|
||||
}
|
||||
|
||||
if (secCtx.isEstablished()) {
|
||||
handshakeStage = 1;
|
||||
|
||||
peer = secCtx.getSrcName().toString();
|
||||
me = secCtx.getTargName().toString();
|
||||
|
||||
logger.log(Level.FINE,
|
||||
"KRB5SRV05:Peer name is : {0}, my name is : {1}",
|
||||
new Object[]{peer, me});
|
||||
|
||||
// me might take the form of proto@host or proto/host
|
||||
if (protocolSaved != null &&
|
||||
!protocolSaved.equalsIgnoreCase(me.split("[/@]")[0])) {
|
||||
throw new SaslException(
|
||||
"GSS context targ name protocol error: " + me);
|
||||
}
|
||||
|
||||
if (gssOutToken == null) {
|
||||
return doHandshake1(EMPTY);
|
||||
}
|
||||
}
|
||||
|
||||
return gssOutToken;
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("GSS initiate failed", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] doHandshake1(byte[] responseData) throws SaslException {
|
||||
try {
|
||||
// Security context already established. responseData
|
||||
// should contain no data
|
||||
if (responseData != null && responseData.length > 0) {
|
||||
throw new SaslException(
|
||||
"Handshake expecting no response data from server");
|
||||
}
|
||||
|
||||
// Construct 4 octets of data:
|
||||
// First octet contains bitmask specifying protections supported
|
||||
// 2nd-4th octets contains max receive buffer of server
|
||||
|
||||
byte[] gssInToken = new byte[4];
|
||||
gssInToken[0] = allQop;
|
||||
intToNetworkByteOrder(recvMaxBufSize, gssInToken, 1, 3);
|
||||
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE,
|
||||
"KRB5SRV06:Supported protections: {0}; recv max buf size: {1}",
|
||||
new Object[]{new Byte(allQop),
|
||||
new Integer(recvMaxBufSize)});
|
||||
}
|
||||
|
||||
handshakeStage = 2; // progress to next stage
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "doHandshake1",
|
||||
"KRB5SRV07:Challenge [raw]", gssInToken);
|
||||
}
|
||||
|
||||
byte[] gssOutToken = secCtx.wrap(gssInToken, 0, gssInToken.length,
|
||||
new MessageProp(0 /* gop */, false /* privacy */));
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "doHandshake1",
|
||||
"KRB5SRV08:Challenge [after wrap]", gssOutToken);
|
||||
}
|
||||
return gssOutToken;
|
||||
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("Problem wrapping handshake1", e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] doHandshake2(byte[] responseData) throws SaslException {
|
||||
try {
|
||||
// Expecting 4 octets from client selected protection
|
||||
// and client's receive buffer size
|
||||
MessageProp msgProp = new MessageProp(false);
|
||||
byte[] gssOutToken = secCtx.unwrap(responseData, 0,
|
||||
responseData.length, msgProp);
|
||||
checkMessageProp("Handshake failure: ", msgProp);
|
||||
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
traceOutput(MY_CLASS_NAME, "doHandshake2",
|
||||
"KRB5SRV09:Response [after unwrap]", gssOutToken);
|
||||
}
|
||||
|
||||
// First octet is a bit-mask specifying the selected protection
|
||||
byte selectedQop = gssOutToken[0];
|
||||
if ((selectedQop&allQop) == 0) {
|
||||
throw new SaslException("Client selected unsupported protection: "
|
||||
+ selectedQop);
|
||||
}
|
||||
if ((selectedQop&PRIVACY_PROTECTION) != 0) {
|
||||
privacy = true;
|
||||
integrity = true;
|
||||
} else if ((selectedQop&INTEGRITY_ONLY_PROTECTION) != 0) {
|
||||
integrity = true;
|
||||
}
|
||||
|
||||
// 2nd-4th octets specifies maximum buffer size expected by
|
||||
// client (in network byte order). This is the server's send
|
||||
// buffer maximum.
|
||||
int clntMaxBufSize = networkByteOrderToInt(gssOutToken, 1, 3);
|
||||
|
||||
// Determine the max send buffer size based on what the
|
||||
// client is able to receive and our specified max
|
||||
sendMaxBufSize = (sendMaxBufSize == 0) ? clntMaxBufSize :
|
||||
Math.min(sendMaxBufSize, clntMaxBufSize);
|
||||
|
||||
// Update context to limit size of returned buffer
|
||||
rawSendSize = secCtx.getWrapSizeLimit(JGSS_QOP, privacy,
|
||||
sendMaxBufSize);
|
||||
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE,
|
||||
"KRB5SRV10:Selected protection: {0}; privacy: {1}; integrity: {2}",
|
||||
new Object[]{new Byte(selectedQop),
|
||||
Boolean.valueOf(privacy),
|
||||
Boolean.valueOf(integrity)});
|
||||
logger.log(Level.FINE,
|
||||
"KRB5SRV11:Client max recv size: {0}; server max send size: {1}; rawSendSize: {2}",
|
||||
new Object[] {new Integer(clntMaxBufSize),
|
||||
new Integer(sendMaxBufSize),
|
||||
new Integer(rawSendSize)});
|
||||
}
|
||||
|
||||
// Get authorization identity, if any
|
||||
if (gssOutToken.length > 4) {
|
||||
try {
|
||||
authzid = new String(gssOutToken, 4,
|
||||
gssOutToken.length - 4, "UTF-8");
|
||||
} catch (UnsupportedEncodingException uee) {
|
||||
throw new SaslException ("Cannot decode authzid", uee);
|
||||
}
|
||||
} else {
|
||||
authzid = peer;
|
||||
}
|
||||
logger.log(Level.FINE, "KRB5SRV12:Authzid: {0}", authzid);
|
||||
|
||||
AuthorizeCallback acb = new AuthorizeCallback(peer, authzid);
|
||||
|
||||
// In Kerberos, realm is embedded in peer name
|
||||
cbh.handle(new Callback[] {acb});
|
||||
if (acb.isAuthorized()) {
|
||||
authzid = acb.getAuthorizedID();
|
||||
completed = true;
|
||||
} else {
|
||||
// Authorization failed
|
||||
throw new SaslException(peer +
|
||||
" is not authorized to connect as " + authzid);
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (GSSException e) {
|
||||
throw new SaslException("Final handshake step failed", e);
|
||||
} catch (IOException e) {
|
||||
throw new SaslException("Problem with callback handler", e);
|
||||
} catch (UnsupportedCallbackException e) {
|
||||
throw new SaslException("Problem with callback handler", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String getAuthorizationID() {
|
||||
if (completed) {
|
||||
return authzid;
|
||||
} else {
|
||||
throw new IllegalStateException("Authentication incomplete");
|
||||
}
|
||||
}
|
||||
|
||||
public Object getNegotiatedProperty(String propName) {
|
||||
if (!completed) {
|
||||
throw new IllegalStateException("Authentication incomplete");
|
||||
}
|
||||
|
||||
Object result;
|
||||
switch (propName) {
|
||||
case Sasl.BOUND_SERVER_NAME:
|
||||
try {
|
||||
// me might take the form of proto@host or proto/host
|
||||
result = me.split("[/@]")[1];
|
||||
} catch (Exception e) {
|
||||
result = null;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
result = super.getNegotiatedProperty(propName);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
125
jdkSrc/jdk8/com/sun/security/sasl/ntlm/FactoryImpl.java
Normal file
125
jdkSrc/jdk8/com/sun/security/sasl/ntlm/FactoryImpl.java
Normal 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);
|
||||
}
|
||||
}
|
||||
243
jdkSrc/jdk8/com/sun/security/sasl/ntlm/NTLMClient.java
Normal file
243
jdkSrc/jdk8/com/sun/security/sasl/ntlm/NTLMClient.java
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
240
jdkSrc/jdk8/com/sun/security/sasl/ntlm/NTLMServer.java
Normal file
240
jdkSrc/jdk8/com/sun/security/sasl/ntlm/NTLMServer.java
Normal 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;
|
||||
}
|
||||
}
|
||||
365
jdkSrc/jdk8/com/sun/security/sasl/util/AbstractSaslImpl.java
Normal file
365
jdkSrc/jdk8/com/sun/security/sasl/util/AbstractSaslImpl.java
Normal 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.misc.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}", new Byte(allQop));
|
||||
|
||||
if (qop.length > 0) {
|
||||
StringBuffer qopbuf = new StringBuffer();
|
||||
for (int i = 0; i < qop.length; i++) {
|
||||
qopbuf.append(Byte.toString(qop[i]));
|
||||
qopbuf.append(' ');
|
||||
}
|
||||
logger.logp(Level.FINE, myClassName, "constructor",
|
||||
"SASLIMPL03:Preferred qops : {0}", qopbuf.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) {
|
||||
StringBuffer strbuf = new StringBuffer();
|
||||
for (int i = 0; i < strength.length; i++) {
|
||||
strbuf.append(Byte.toString(strength[i]));
|
||||
strbuf.append(' ');
|
||||
}
|
||||
logger.logp(Level.FINE, myClassName, "constructor",
|
||||
"SASLIMPL05:Cipher strengths: {0}", strbuf.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, new Integer(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};
|
||||
}
|
||||
117
jdkSrc/jdk8/com/sun/security/sasl/util/PolicyUtils.java
Normal file
117
jdkSrc/jdk8/com/sun/security/sasl/util/PolicyUtils.java
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user