001: /*
002: * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
003: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004: *
005: * This code is free software; you can redistribute it and/or modify it
006: * under the terms of the GNU General Public License version 2 only, as
007: * published by the Free Software Foundation. Sun designates this
008: * particular file as subject to the "Classpath" exception as provided
009: * by Sun in the LICENSE file that accompanied this code.
010: *
011: * This code is distributed in the hope that it will be useful, but WITHOUT
012: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014: * version 2 for more details (a copy is included in the LICENSE file that
015: * accompanied this code).
016: *
017: * You should have received a copy of the GNU General Public License version
018: * 2 along with this work; if not, write to the Free Software Foundation,
019: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020: *
021: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022: * CA 95054 USA or visit www.sun.com if you need additional information or
023: * have any questions.
024: */
025:
026: package com.sun.security.sasl;
027:
028: import javax.security.sasl.*;
029: import javax.security.auth.callback.*;
030: import java.util.Random;
031: import java.util.Map;
032: import java.io.IOException;
033: import java.io.UnsupportedEncodingException;
034: import java.security.NoSuchAlgorithmException;
035:
036: import java.util.logging.Logger;
037: import java.util.logging.Level;
038:
039: /**
040: * Implements the CRAM-MD5 SASL server-side mechanism.
041: * (<A HREF="ftp://ftp.isi.edu/in-notes/rfc2195.txt">RFC 2195</A>).
042: * CRAM-MD5 has no initial response.
043: *
044: * client <---- M={random, timestamp, server-fqdn} ------- server
045: * client ----- {username HMAC_MD5(pw, M)} --------------> server
046: *
047: * CallbackHandler must be able to handle the following callbacks:
048: * - NameCallback: default name is name of user for whom to get password
049: * - PasswordCallback: must fill in password; if empty, no pw
050: * - AuthorizeCallback: must setAuthorized() and canonicalized authorization id
051: * - auth id == authzid, but needed to get canonicalized authzid
052: *
053: * @author Rosanna Lee
054: */
055: final class CramMD5Server extends CramMD5Base implements SaslServer {
056: private String fqdn;
057: private byte[] challengeData = null;
058: private String authzid;
059: private CallbackHandler cbh;
060:
061: /**
062: * Creates a SASL mechanism with client credentials that it needs
063: * to participate in CRAM-MD5 authentication exchange with the server.
064: *
065: * @param authID A non-null string representing the principal
066: * being authenticated.
067: *
068: * @param pw A non-null String or byte[]
069: * containing the password. If it is an array, it is first cloned.
070: */
071: CramMD5Server(String protocol, String serverFqdn, Map props,
072: CallbackHandler cbh) throws SaslException {
073: if (serverFqdn == null) {
074: throw new SaslException(
075: "CRAM-MD5: fully qualified server name must be specified");
076: }
077:
078: fqdn = serverFqdn;
079: this .cbh = cbh;
080: }
081:
082: /**
083: * Generates challenge based on response sent by client.
084: *
085: * CRAM-MD5 has no initial response.
086: * First call generates challenge.
087: * Second call verifies client response. If authentication fails, throws
088: * SaslException.
089: *
090: * @param responseData A non-null byte array containing the response
091: * data from the client.
092: * @return A non-null byte array containing the challenge to be sent to
093: * the client for the first call; null when 2nd call is successful.
094: * @throws SaslException If authentication fails.
095: */
096: public byte[] evaluateResponse(byte[] responseData)
097: throws SaslException {
098:
099: // See if we've been here before
100: if (completed) {
101: throw new IllegalStateException(
102: "CRAM-MD5 authentication already completed");
103: }
104:
105: if (aborted) {
106: throw new IllegalStateException(
107: "CRAM-MD5 authentication previously aborted due to error");
108: }
109:
110: try {
111: if (challengeData == null) {
112: if (responseData.length != 0) {
113: aborted = true;
114: throw new SaslException(
115: "CRAM-MD5 does not expect any initial response");
116: }
117:
118: // Generate challenge {random, timestamp, fqdn}
119: Random random = new Random();
120: long rand = random.nextLong();
121: long timestamp = System.currentTimeMillis();
122:
123: StringBuffer buf = new StringBuffer();
124: buf.append('<');
125: buf.append(rand);
126: buf.append('.');
127: buf.append(timestamp);
128: buf.append('@');
129: buf.append(fqdn);
130: buf.append('>');
131: String challengeStr = buf.toString();
132:
133: logger.log(Level.FINE,
134: "CRAMSRV01:Generated challenge: {0}",
135: challengeStr);
136:
137: challengeData = challengeStr.getBytes("UTF8");
138: return (byte[]) challengeData.clone();
139:
140: } else {
141: // Examine response to see if correctly encrypted challengeData
142: if (logger.isLoggable(Level.FINE)) {
143: logger.log(Level.FINE,
144: "CRAMSRV02:Received response: {0}",
145: new String(responseData, "UTF8"));
146: }
147:
148: // Extract username from response
149: int ulen = 0;
150: for (int i = 0; i < responseData.length; i++) {
151: if (responseData[i] == ' ') {
152: ulen = i;
153: break;
154: }
155: }
156: if (ulen == 0) {
157: aborted = true;
158: throw new SaslException(
159: "CRAM-MD5: Invalid response; space missing");
160: }
161: String username = new String(responseData, 0, ulen,
162: "UTF8");
163:
164: logger.log(Level.FINE,
165: "CRAMSRV03:Extracted username: {0}", username);
166:
167: // Get user's password
168: NameCallback ncb = new NameCallback(
169: "CRAM-MD5 authentication ID: ", username);
170: PasswordCallback pcb = new PasswordCallback(
171: "CRAM-MD5 password: ", false);
172: cbh.handle(new Callback[] { ncb, pcb });
173: char pwChars[] = pcb.getPassword();
174: if (pwChars == null || pwChars.length == 0) {
175: // user has no password; OK to disclose to server
176: aborted = true;
177: throw new SaslException(
178: "CRAM-MD5: username not found: " + username);
179: }
180: pcb.clearPassword();
181: String pwStr = new String(pwChars);
182: for (int i = 0; i < pwChars.length; i++) {
183: pwChars[i] = 0;
184: }
185: pw = pwStr.getBytes("UTF8");
186:
187: // Generate a keyed-MD5 digest from the user's password and
188: // original challenge.
189: String digest = HMAC_MD5(pw, challengeData);
190:
191: logger.log(Level.FINE,
192: "CRAMSRV04:Expecting digest: {0}", digest);
193:
194: // clear pw when we no longer need it
195: clearPassword();
196:
197: // Check whether digest is as expected
198: byte[] expectedDigest = digest.getBytes("UTF8");
199: int digestLen = responseData.length - ulen - 1;
200: if (expectedDigest.length != digestLen) {
201: aborted = true;
202: throw new SaslException("Invalid response");
203: }
204: int j = 0;
205: for (int i = ulen + 1; i < responseData.length; i++) {
206: if (expectedDigest[j++] != responseData[i]) {
207: aborted = true;
208: throw new SaslException("Invalid response");
209: }
210: }
211:
212: // All checks out, use AuthorizeCallback to canonicalize name
213: AuthorizeCallback acb = new AuthorizeCallback(username,
214: username);
215: cbh.handle(new Callback[] { acb });
216: if (acb.isAuthorized()) {
217: authzid = acb.getAuthorizedID();
218: } else {
219: // Not authorized
220: aborted = true;
221: throw new SaslException(
222: "CRAM-MD5: user not authorized: "
223: + username);
224: }
225:
226: logger.log(Level.FINE,
227: "CRAMSRV05:Authorization id: {0}", authzid);
228:
229: completed = true;
230: return null;
231: }
232: } catch (UnsupportedEncodingException e) {
233: aborted = true;
234: throw new SaslException("UTF8 not available on platform", e);
235: } catch (NoSuchAlgorithmException e) {
236: aborted = true;
237: throw new SaslException(
238: "MD5 algorithm not available on platform", e);
239: } catch (UnsupportedCallbackException e) {
240: aborted = true;
241: throw new SaslException("CRAM-MD5 authentication failed", e);
242: } catch (SaslException e) {
243: throw e; // rethrow
244: } catch (IOException e) {
245: aborted = true;
246: throw new SaslException("CRAM-MD5 authentication failed", e);
247: }
248: }
249:
250: public String getAuthorizationID() {
251: if (completed) {
252: return authzid;
253: } else {
254: throw new IllegalStateException(
255: "CRAM-MD5 authentication not completed");
256: }
257: }
258: }
|