Path: blob/master/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Server.java
41161 views
/*1* Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package com.sun.security.sasl;2627import java.io.IOException;28import java.security.NoSuchAlgorithmException;29import java.util.logging.Level;30import java.util.Map;31import java.util.Random;32import javax.security.sasl.*;33import javax.security.auth.callback.*;3435import static java.nio.charset.StandardCharsets.UTF_8;3637/**38* Implements the CRAM-MD5 SASL server-side mechanism.39* (<A HREF="http://www.ietf.org/rfc/rfc2195.txt">RFC 2195</A>).40* CRAM-MD5 has no initial response.41*42* client <---- M={random, timestamp, server-fqdn} ------- server43* client ----- {username HMAC_MD5(pw, M)} --------------> server44*45* CallbackHandler must be able to handle the following callbacks:46* - NameCallback: default name is name of user for whom to get password47* - PasswordCallback: must fill in password; if empty, no pw48* - AuthorizeCallback: must setAuthorized() and canonicalized authorization id49* - auth id == authzid, but needed to get canonicalized authzid50*51* @author Rosanna Lee52*/53final class CramMD5Server extends CramMD5Base implements SaslServer {54private String fqdn;55private byte[] challengeData = null;56private String authzid;57private CallbackHandler cbh;5859/**60* Creates a CRAM-MD5 SASL server.61*62* @param protocol ignored in CRAM-MD563* @param serverFqdn non-null, used in generating a challenge64* @param props ignored in CRAM-MD565* @param cbh find password, authorize user66*/67CramMD5Server(String protocol, String serverFqdn, Map<String, ?> props,68CallbackHandler cbh) throws SaslException {69if (serverFqdn == null) {70throw new SaslException(71"CRAM-MD5: fully qualified server name must be specified");72}7374fqdn = serverFqdn;75this.cbh = cbh;76}7778/**79* Generates challenge based on response sent by client.80*81* CRAM-MD5 has no initial response.82* First call generates challenge.83* Second call verifies client response. If authentication fails, throws84* SaslException.85*86* @param responseData A non-null byte array containing the response87* data from the client.88* @return A non-null byte array containing the challenge to be sent to89* the client for the first call; null when 2nd call is successful.90* @throws SaslException If authentication fails.91*/92public byte[] evaluateResponse(byte[] responseData)93throws SaslException {9495// See if we've been here before96if (completed) {97throw new IllegalStateException(98"CRAM-MD5 authentication already completed");99}100101if (aborted) {102throw new IllegalStateException(103"CRAM-MD5 authentication previously aborted due to error");104}105106try {107if (challengeData == null) {108if (responseData.length != 0) {109aborted = true;110throw new SaslException(111"CRAM-MD5 does not expect any initial response");112}113114// Generate challenge {random, timestamp, fqdn}115Random random = new Random();116long rand = random.nextLong();117long timestamp = System.currentTimeMillis();118119StringBuilder sb = new StringBuilder();120sb.append('<');121sb.append(rand);122sb.append('.');123sb.append(timestamp);124sb.append('@');125sb.append(fqdn);126sb.append('>');127String challengeStr = sb.toString();128129logger.log(Level.FINE,130"CRAMSRV01:Generated challenge: {0}", challengeStr);131132challengeData = challengeStr.getBytes(UTF_8);133return challengeData.clone();134135} else {136// Examine response to see if correctly encrypted challengeData137if(logger.isLoggable(Level.FINE)) {138logger.log(Level.FINE,139"CRAMSRV02:Received response: {0}",140new String(responseData, UTF_8));141}142143// Extract username from response144int ulen = 0;145for (int i = 0; i < responseData.length; i++) {146if (responseData[i] == ' ') {147ulen = i;148break;149}150}151if (ulen == 0) {152aborted = true;153throw new SaslException(154"CRAM-MD5: Invalid response; space missing");155}156String username = new String(responseData, 0, ulen, UTF_8);157158logger.log(Level.FINE,159"CRAMSRV03:Extracted username: {0}", username);160161// Get user's password162NameCallback ncb =163new NameCallback("CRAM-MD5 authentication ID: ", username);164PasswordCallback pcb =165new PasswordCallback("CRAM-MD5 password: ", false);166cbh.handle(new Callback[]{ncb,pcb});167char[] pwChars = pcb.getPassword();168if (pwChars == null || pwChars.length == 0) {169// user has no password; OK to disclose to server170aborted = true;171throw new SaslException(172"CRAM-MD5: username not found: " + username);173}174pcb.clearPassword();175String pwStr = new String(pwChars);176for (int i = 0; i < pwChars.length; i++) {177pwChars[i] = 0;178}179pw = pwStr.getBytes(UTF_8);180181// Generate a keyed-MD5 digest from the user's password and182// original challenge.183String digest = HMAC_MD5(pw, challengeData);184185logger.log(Level.FINE,186"CRAMSRV04:Expecting digest: {0}", digest);187188// clear pw when we no longer need it189clearPassword();190191// Check whether digest is as expected192byte[] expectedDigest = digest.getBytes(UTF_8);193int digestLen = responseData.length - ulen - 1;194if (expectedDigest.length != digestLen) {195aborted = true;196throw new SaslException("Invalid response");197}198int j = 0;199for (int i = ulen + 1; i < responseData.length ; i++) {200if (expectedDigest[j++] != responseData[i]) {201aborted = true;202throw new SaslException("Invalid response");203}204}205206// All checks out, use AuthorizeCallback to canonicalize name207AuthorizeCallback acb = new AuthorizeCallback(username, username);208cbh.handle(new Callback[]{acb});209if (acb.isAuthorized()) {210authzid = acb.getAuthorizedID();211} else {212// Not authorized213aborted = true;214throw new SaslException(215"CRAM-MD5: user not authorized: " + username);216}217218logger.log(Level.FINE,219"CRAMSRV05:Authorization id: {0}", authzid);220221completed = true;222return null;223}224} catch (NoSuchAlgorithmException e) {225aborted = true;226throw new SaslException("MD5 algorithm not available on platform", e);227} catch (UnsupportedCallbackException e) {228aborted = true;229throw new SaslException("CRAM-MD5 authentication failed", e);230} catch (SaslException e) {231throw e; // rethrow232} catch (IOException e) {233aborted = true;234throw new SaslException("CRAM-MD5 authentication failed", e);235}236}237238public String getAuthorizationID() {239if (completed) {240return authzid;241} else {242throw new IllegalStateException(243"CRAM-MD5 authentication not completed");244}245}246}247248249