SEC-1132: Moved TextUtils to web module and StringSplit utils into Digest authentication package (as they aren't used elsewhere).

This commit is contained in:
Luke Taylor
2009-04-25 08:04:26 +00:00
parent a76cbee4bc
commit 1454cbb78e
11 changed files with 227 additions and 304 deletions

View File

@@ -21,8 +21,8 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.util.TextUtils;
import org.springframework.security.web.FilterChainOrder;
import org.springframework.security.web.util.TextEscapeUtils;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
@@ -88,7 +88,7 @@ public class AuthenticationProcessingFilter extends AbstractProcessingFilter {
HttpSession session = request.getSession(false);
if (session != null || getAllowSessionCreation()) {
request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextUtils.escapeEntities(username));
request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextEscapeUtils.escapeEntities(username));
}
// Allow subclasses to set the "details" property

View File

@@ -0,0 +1,191 @@
package org.springframework.security.web.authentication.www;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
abstract class DigestAuthUtils {
private static final String[] EMPTY_STRING_ARRAY = new String[0];
public final static String encodePasswordInA1Format(String username, String realm, String password) {
String a1 = username + ":" + realm + ":" + password;
String a1Md5 = new String(DigestUtils.md5Hex(a1));
return a1Md5;
}
final static String[] splitIgnoringQuotes(String str, char separatorChar) {
if (str == null) {
return null;
}
int len = str.length();
if (len == 0) {
return EMPTY_STRING_ARRAY;
}
List<String> list = new ArrayList<String>();
int i = 0;
int start = 0;
boolean match = false;
while (i < len) {
if (str.charAt(i) == '"') {
i++;
while (i < len) {
if (str.charAt(i) == '"') {
i++;
break;
}
i++;
}
match = true;
continue;
}
if (str.charAt(i) == separatorChar) {
if (match) {
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
if (match) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
/**
* Computes the <code>response</code> portion of a Digest authentication header. Both the server and user
* agent should compute the <code>response</code> independently. Provided as a static method to simplify the
* coding of user agents.
*
* @param passwordAlreadyEncoded true if the password argument is already encoded in the correct format. False if
* it is plain text.
* @param username the user's login name.
* @param realm the name of the realm.
* @param password the user's password in plaintext or ready-encoded.
* @param httpMethod the HTTP request method (GET, POST etc.)
* @param uri the request URI.
* @param qop the qop directive, or null if not set.
* @param nonce the nonce supplied by the server
* @param nc the "nonce-count" as defined in RFC 2617.
* @param cnonce opaque string supplied by the client when qop is set.
* @return the MD5 of the digest authentication response, encoded in hex
* @throws IllegalArgumentException if the supplied qop value is unsupported.
*/
final static String generateDigest(boolean passwordAlreadyEncoded, String username, String realm, String password,
String httpMethod, String uri, String qop, String nonce, String nc, String cnonce)
throws IllegalArgumentException {
String a1Md5 = null;
String a2 = httpMethod + ":" + uri;
String a2Md5 = new String(DigestUtils.md5Hex(a2));
if (passwordAlreadyEncoded) {
a1Md5 = password;
} else {
a1Md5 = DigestAuthUtils.encodePasswordInA1Format(username, realm, password);
}
String digest;
if (qop == null) {
// as per RFC 2069 compliant clients (also reaffirmed by RFC 2617)
digest = a1Md5 + ":" + nonce + ":" + a2Md5;
} else if ("auth".equals(qop)) {
// As per RFC 2617 compliant clients
digest = a1Md5 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2Md5;
} else {
throw new IllegalArgumentException("This method does not support a qop: '" + qop + "'");
}
String digestMd5 = new String(DigestUtils.md5Hex(digest));
return digestMd5;
}
/**
* Takes an array of <code>String</code>s, and for each element removes any instances of
* <code>removeCharacter</code>, and splits the element based on the <code>delimiter</code>. A <code>Map</code> is
* then generated, with the left of the delimiter providing the key, and the right of the delimiter providing the
* value.<p>Will trim both the key and value before adding to the <code>Map</code>.</p>
*
* @param array the array to process
* @param delimiter to split each element using (typically the equals symbol)
* @param removeCharacters one or more characters to remove from each element prior to attempting the split
* operation (typically the quotation mark symbol) or <code>null</code> if no removal should occur
* @return a <code>Map</code> representing the array contents, or <code>null</code> if the array to process was
* null or empty
*/
final static Map<String, String> splitEachArrayElementAndCreateMap(String[] array, String delimiter, String removeCharacters) {
if ((array == null) || (array.length == 0)) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < array.length; i++) {
String postRemove;
if (removeCharacters == null) {
postRemove = array[i];
} else {
postRemove = StringUtils.replace(array[i], removeCharacters, "");
}
String[] splitThisArrayElement = split(postRemove, delimiter);
if (splitThisArrayElement == null) {
continue;
}
map.put(splitThisArrayElement[0].trim(), splitThisArrayElement[1].trim());
}
return map;
}
/**
* Splits a <code>String</code> at the first instance of the delimiter.<p>Does not include the delimiter in
* the response.</p>
*
* @param toSplit the string to split
* @param delimiter to split the string up with
* @return a two element array with index 0 being before the delimiter, and index 1 being after the delimiter
* (neither element includes the delimiter)
* @throws IllegalArgumentException if an argument was invalid
*/
final static String[] split(String toSplit, String delimiter) {
Assert.hasLength(toSplit, "Cannot split a null or empty string");
Assert.hasLength(delimiter, "Cannot use a null or empty delimiter to split a string");
if (delimiter.length() != 1) {
throw new IllegalArgumentException("Delimiter can only be one character in length");
}
int offset = toSplit.indexOf(delimiter);
if (offset < 0) {
return null;
}
String beforeDelimiter = toSplit.substring(0, offset);
String afterDelimiter = toSplit.substring(offset + 1);
return new String[]{beforeDelimiter, afterDelimiter};
}
}

View File

@@ -44,7 +44,6 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.security.util.StringSplitUtils;
import org.springframework.security.web.FilterChainOrder;
import org.springframework.security.web.SpringSecurityFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
@@ -81,6 +80,7 @@ import org.springframework.util.StringUtils;
public class DigestProcessingFilter extends SpringSecurityFilter implements Filter, InitializingBean, MessageSourceAware {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(DigestProcessingFilter.class);
//~ Instance fields ================================================================================================
@@ -110,17 +110,17 @@ public class DigestProcessingFilter extends SpringSecurityFilter implements Filt
if ((header != null) && header.startsWith("Digest ")) {
String section212response = header.substring(7);
String[] headerEntries = StringSplitUtils.splitIgnoringQuotes(section212response, ',');
Map<String,String> headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
String[] headerEntries = DigestAuthUtils.splitIgnoringQuotes(section212response, ',');
Map<String,String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
String username = (String) headerMap.get("username");
String realm = (String) headerMap.get("realm");
String nonce = (String) headerMap.get("nonce");
String uri = (String) headerMap.get("uri");
String responseDigest = (String) headerMap.get("response");
String qop = (String) headerMap.get("qop"); // RFC 2617 extension
String nc = (String) headerMap.get("nc"); // RFC 2617 extension
String cnonce = (String) headerMap.get("cnonce"); // RFC 2617 extension
String username = headerMap.get("username");
String realm = headerMap.get("realm");
String nonce = headerMap.get("nonce");
String uri = headerMap.get("uri");
String responseDigest = headerMap.get("response");
String qop = headerMap.get("qop"); // RFC 2617 extension
String nc = headerMap.get("nc"); // RFC 2617 extension
String cnonce = headerMap.get("cnonce"); // RFC 2617 extension
// Check all required parameters were supplied (ie RFC 2069)
if ((username == null) || (realm == null) || (nonce == null) || (uri == null) || (response == null)) {
@@ -241,8 +241,8 @@ public class DigestProcessingFilter extends SpringSecurityFilter implements Filt
String serverDigestMd5;
// Don't catch IllegalArgumentException (already checked validity)
serverDigestMd5 = generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(),
((HttpServletRequest) request).getMethod(), uri, qop, nonce, nc, cnonce);
serverDigestMd5 = DigestAuthUtils.generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(),
request.getMethod(), uri, qop, nonce, nc, cnonce);
// If digest is incorrect, try refreshing from backend and recomputing
if (!serverDigestMd5.equals(responseDigest) && !loadedFromDao) {
@@ -263,8 +263,8 @@ public class DigestProcessingFilter extends SpringSecurityFilter implements Filt
userCache.putUserInCache(user);
// Don't catch IllegalArgumentException (already checked validity)
serverDigestMd5 = generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(),
((HttpServletRequest) request).getMethod(), uri, qop, nonce, nc, cnonce);
serverDigestMd5 = DigestAuthUtils.generateDigest(passwordAlreadyEncoded, username, realm, user.getPassword(),
request.getMethod(), uri, qop, nonce, nc, cnonce);
}
// If digest is still incorrect, definitely reject authentication attempt
@@ -277,7 +277,6 @@ public class DigestProcessingFilter extends SpringSecurityFilter implements Filt
fail(request, response,
new BadCredentialsException(messages.getMessage("DigestProcessingFilter.incorrectResponse",
"Incorrect response")));
return;
}
@@ -309,13 +308,6 @@ public class DigestProcessingFilter extends SpringSecurityFilter implements Filt
chain.doFilter(request, response);
}
public static String encodePasswordInA1Format(String username, String realm, String password) {
String a1 = username + ":" + realm + ":" + password;
String a1Md5 = new String(DigestUtils.md5Hex(a1));
return a1Md5;
}
private void fail(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(null);
@@ -327,55 +319,6 @@ public class DigestProcessingFilter extends SpringSecurityFilter implements Filt
authenticationEntryPoint.commence(request, response, failed);
}
/**
* Computes the <code>response</code> portion of a Digest authentication header. Both the server and user
* agent should compute the <code>response</code> independently. Provided as a static method to simplify the
* coding of user agents.
*
* @param passwordAlreadyEncoded true if the password argument is already encoded in the correct format. False if
* it is plain text.
* @param username the user's login name.
* @param realm the name of the realm.
* @param password the user's password in plaintext or ready-encoded.
* @param httpMethod the HTTP request method (GET, POST etc.)
* @param uri the request URI.
* @param qop the qop directive, or null if not set.
* @param nonce the nonce supplied by the server
* @param nc the "nonce-count" as defined in RFC 2617.
* @param cnonce opaque string supplied by the client when qop is set.
* @return the MD5 of the digest authentication response, encoded in hex
* @throws IllegalArgumentException if the supplied qop value is unsupported.
*/
public static String generateDigest(boolean passwordAlreadyEncoded, String username, String realm, String password,
String httpMethod, String uri, String qop, String nonce, String nc, String cnonce)
throws IllegalArgumentException {
String a1Md5 = null;
String a2 = httpMethod + ":" + uri;
String a2Md5 = new String(DigestUtils.md5Hex(a2));
if (passwordAlreadyEncoded) {
a1Md5 = password;
} else {
a1Md5 = encodePasswordInA1Format(username, realm, password);
}
String digest;
if (qop == null) {
// as per RFC 2069 compliant clients (also reaffirmed by RFC 2617)
digest = a1Md5 + ":" + nonce + ":" + a2Md5;
} else if ("auth".equals(qop)) {
// As per RFC 2617 compliant clients
digest = a1Md5 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2Md5;
} else {
throw new IllegalArgumentException("This method does not support a qop: '" + qop + "'");
}
String digestMd5 = new String(DigestUtils.md5Hex(digest));
return digestMd5;
}
public DigestProcessingFilterEntryPoint getAuthenticationEntryPoint() {
return authenticationEntryPoint;
}

View File

@@ -0,0 +1,39 @@
package org.springframework.security.web.util;
/**
* Utility for escaping characters in HTML strings.
*
* @author Luke Taylor
* @version $Id$
*/
public abstract class TextEscapeUtils {
public final static String escapeEntities(String s) {
if (s == null || s.length() == 0) {
return s;
}
StringBuffer sb = new StringBuffer();
for (int i=0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '<') {
sb.append("&lt;");
} else if (c == '>') {
sb.append("&gt;");
} else if (c == '"') {
sb.append("&#034;");
} else if (c == '\'') {
sb.append("&#039;");
} else if (c == '&') {
sb.append("&amp;");
} else {
sb.append(c);
}
}
return sb.toString();
}
}