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