336443 Check nonce count is increasing

This commit is contained in:
Greg Wilkins 2011-09-20 17:04:01 +10:00
parent dacb8962f0
commit 57bd9f3bce
2 changed files with 83 additions and 86 deletions

View File

@ -23,13 +23,14 @@ import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService; import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService; import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator; import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.security.authentication.DigestAuthenticator;
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Server;
public class SecuredHelloHandler public class SecuredHelloHandler
{ {
public static void main(String[] args) throws Exception public static void main(String[] args) throws Exception
{ {
Server server = new Server(0); Server server = new Server(8080);
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties"); LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService); server.addBean(loginService);
@ -51,7 +52,7 @@ public class SecuredHelloHandler
knownRoles.add("admin"); knownRoles.add("admin");
security.setConstraintMappings(Collections.singletonList(mapping), knownRoles); security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
security.setAuthenticator(new BasicAuthenticator()); security.setAuthenticator(new DigestAuthenticator());
security.setLoginService(loginService); security.setLoginService(loginService);
security.setStrict(false); security.setStrict(false);

View File

@ -15,6 +15,12 @@ package org.eclipse.jetty.security.authentication;
import java.io.IOException; import java.io.IOException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
@ -42,17 +48,29 @@ import org.eclipse.jetty.util.log.Logger;
/** /**
* @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $ * @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
* *
* The nonce max age can be set with the {@link SecurityHandler#setInitParameter(String, String)} * The nonce max age in ms can be set with the {@link SecurityHandler#setInitParameter(String, String)}
* using the name "maxNonceAge" * using the name "maxNonceAge"
*/ */
public class DigestAuthenticator extends LoginAuthenticator public class DigestAuthenticator extends LoginAuthenticator
{ {
private static final Logger LOG = Log.getLogger(DigestAuthenticator.class); private static final Logger LOG = Log.getLogger(DigestAuthenticator.class);
SecureRandom _random = new SecureRandom();
private long _maxNonceAgeMs = 60*1000;
private ConcurrentMap<String, Nonce> _nonceCount = new ConcurrentHashMap<String, Nonce>();
private Queue<Nonce> _nonceQueue = new ConcurrentLinkedQueue<Nonce>();
private static class Nonce
{
final String _nonce;
final long _ts;
AtomicInteger _nc=new AtomicInteger();
public Nonce(String nonce, long ts)
{
_nonce=nonce;
_ts=ts;
}
}
protected long _maxNonceAge = 0; /* ------------------------------------------------------------ */
protected long _nonceSecret = this.hashCode() ^ System.currentTimeMillis();
protected boolean _useStale = false;
public DigestAuthenticator() public DigestAuthenticator()
{ {
super(); super();
@ -69,19 +87,22 @@ public class DigestAuthenticator extends LoginAuthenticator
String mna=configuration.getInitParameter("maxNonceAge"); String mna=configuration.getInitParameter("maxNonceAge");
if (mna!=null) if (mna!=null)
_maxNonceAge=Long.valueOf(mna); _maxNonceAgeMs=Long.valueOf(mna);
} }
/* ------------------------------------------------------------ */
public String getAuthMethod() public String getAuthMethod()
{ {
return Constraint.__DIGEST_AUTH; return Constraint.__DIGEST_AUTH;
} }
/* ------------------------------------------------------------ */
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
{ {
return true; return true;
} }
/* ------------------------------------------------------------ */
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{ {
if (!mandatory) if (!mandatory)
@ -144,7 +165,7 @@ public class DigestAuthenticator extends LoginAuthenticator
} }
} }
int n = checkNonce(digest.nonce, (Request)request); int n = checkNonce(digest,(Request)request);
if (n > 0) if (n > 0)
{ {
@ -171,7 +192,7 @@ public class DigestAuthenticator extends LoginAuthenticator
+ "\", nonce=\"" + "\", nonce=\""
+ newNonce((Request)request) + newNonce((Request)request)
+ "\", algorithm=MD5, qop=\"auth\"" + "\", algorithm=MD5, qop=\"auth\""
+ (_useStale ? (" stale=" + stale) : "")); + " stale=" + stale);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED); response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return Authentication.SEND_CONTINUE; return Authentication.SEND_CONTINUE;
@ -186,87 +207,59 @@ public class DigestAuthenticator extends LoginAuthenticator
} }
/* ------------------------------------------------------------ */
public String newNonce(Request request) public String newNonce(Request request)
{ {
long ts=request.getTimeStamp(); Nonce nonce;
long sk = _nonceSecret;
do
byte[] nounce = new byte[24];
for (int i = 0; i < 8; i++)
{ {
nounce[i] = (byte) (ts & 0xff); byte[] nounce = new byte[24];
ts = ts >> 8; _random.nextBytes(nounce);
nounce[8 + i] = (byte) (sk & 0xff);
sk = sk >> 8;
}
byte[] hash = null; nonce = new Nonce(new String(B64Code.encode(nounce)),request.getTimeStamp());
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(nounce, 0, 16);
hash = md.digest();
} }
catch (Exception e) while (_nonceCount.putIfAbsent(nonce._nonce,nonce)!=null);
{ _nonceQueue.add(nonce);
LOG.warn(e);
} return nonce._nonce;
for (int i = 0; i < hash.length; i++)
{
nounce[8 + i] = hash[i];
if (i == 23) break;
}
return new String(B64Code.encode(nounce));
} }
/** /**
* @param nonce nonce to check * @param nstring nonce to check
* @param request * @param request
* @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce * @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
*/ */
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private int checkNonce(String nonce, Request request) private int checkNonce(Digest digest, Request request)
{ {
// firstly let's expire old nonces
long expired = request.getTimeStamp()-_maxNonceAgeMs;
Nonce nonce=_nonceQueue.peek();
while (nonce!=null && nonce._ts<expired)
{
_nonceQueue.remove();
_nonceCount.remove(nonce._nonce);
nonce=_nonceQueue.peek();
}
try try
{ {
byte[] n = B64Code.decode(nonce.toCharArray()); nonce = _nonceCount.get(digest.nonce);
if (n.length != 24) return -1; if (nonce==null)
return 0;
long ts = 0;
long sk = _nonceSecret; long count = Long.parseLong(digest.nc,16);
byte[] n2 = new byte[16]; if (count>Integer.MAX_VALUE)
System.arraycopy(n, 0, n2, 0, 8); return 0;
for (int i = 0; i < 8; i++) int old=nonce._nc.get();
{ while (!nonce._nc.compareAndSet(old,(int)count))
n2[8 + i] = (byte) (sk & 0xff); old=nonce._nc.get();
sk = sk >> 8; if (count<=old)
ts = (ts << 8) + (0xff & (long) n[7 - i]); return -1;
}
long age = request.getTimeStamp() - ts;
if (LOG.isDebugEnabled()) LOG.debug("age=" + age);
byte[] hash = null;
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(n2, 0, 16);
hash = md.digest();
}
catch (Exception e)
{
LOG.warn(e);
}
for (int i = 0; i < 16; i++)
if (n[i + 8] != hash[i]) return -1;
if (_maxNonceAge > 0 && (age < 0 || age > _maxNonceAge)) return 0; // stale
return 1; return 1;
} }
catch (Exception e) catch (Exception e)
@ -276,18 +269,21 @@ public class DigestAuthenticator extends LoginAuthenticator
return -1; return -1;
} }
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private static class Digest extends Credential private static class Digest extends Credential
{ {
private static final long serialVersionUID = -2484639019549527724L; private static final long serialVersionUID = -2484639019549527724L;
String method = null; String method = "";
String username = null; String username = "";
String realm = null; String realm = "";
String nonce = null; String nonce = "";
String nc = null; String nc = "";
String cnonce = null; String cnonce = "";
String qop = null; String qop = "";
String uri = null; String uri = "";
String response = null; String response = "";
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
Digest(String m) Digest(String m)