2 // ========================================================================
3 // Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.security.authentication;
21 import java.io.IOException;
22 import java.nio.charset.StandardCharsets;
23 import java.security.MessageDigest;
24 import java.security.SecureRandom;
25 import java.util.BitSet;
26 import java.util.Queue;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentLinkedQueue;
29 import java.util.concurrent.ConcurrentMap;
31 import javax.servlet.ServletRequest;
32 import javax.servlet.ServletResponse;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
36 import org.eclipse.jetty.http.HttpHeader;
37 import org.eclipse.jetty.security.ServerAuthException;
38 import org.eclipse.jetty.security.UserAuthentication;
39 import org.eclipse.jetty.server.Authentication;
40 import org.eclipse.jetty.server.Authentication.User;
41 import org.eclipse.jetty.server.Request;
42 import org.eclipse.jetty.server.UserIdentity;
43 import org.eclipse.jetty.util.B64Code;
44 import org.eclipse.jetty.util.QuotedStringTokenizer;
45 import org.eclipse.jetty.util.TypeUtil;
46 import org.eclipse.jetty.util.log.Log;
47 import org.eclipse.jetty.util.log.Logger;
48 import org.eclipse.jetty.util.security.Constraint;
49 import org.eclipse.jetty.util.security.Credential;
52 * @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
54 * The nonce max age in ms can be set with the {@link SecurityHandler#setInitParameter(String, String)}
55 * using the name "maxNonceAge". The nonce max count can be set with {@link SecurityHandler#setInitParameter(String, String)}
56 * using the name "maxNonceCount". When the age or count is exceeded, the nonce is considered stale.
58 public class DigestAuthenticator extends LoginAuthenticator
60 private static final Logger LOG = Log.getLogger(DigestAuthenticator.class);
61 SecureRandom _random = new SecureRandom();
62 private long _maxNonceAgeMs = 60*1000;
63 private int _maxNC=1024;
64 private ConcurrentMap<String, Nonce> _nonceMap = new ConcurrentHashMap<String, Nonce>();
65 private Queue<Nonce> _nonceQueue = new ConcurrentLinkedQueue<Nonce>();
66 private static class Nonce
72 public Nonce(String nonce, long ts, int size)
76 _seen = new BitSet(size);
79 public boolean seen(int count)
83 if (count>=_seen.size())
85 boolean s=_seen.get(count);
92 /* ------------------------------------------------------------ */
93 public DigestAuthenticator()
98 /* ------------------------------------------------------------ */
100 * @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.AuthConfiguration)
103 public void setConfiguration(AuthConfiguration configuration)
105 super.setConfiguration(configuration);
107 String mna=configuration.getInitParameter("maxNonceAge");
110 _maxNonceAgeMs=Long.valueOf(mna);
112 String mnc=configuration.getInitParameter("maxNonceCount");
115 _maxNC=Integer.valueOf(mnc);
119 /* ------------------------------------------------------------ */
120 public int getMaxNonceCount()
125 /* ------------------------------------------------------------ */
126 public void setMaxNonceCount(int maxNC)
131 /* ------------------------------------------------------------ */
132 public long getMaxNonceAge()
134 return _maxNonceAgeMs;
137 /* ------------------------------------------------------------ */
138 public synchronized void setMaxNonceAge(long maxNonceAgeInMillis)
140 _maxNonceAgeMs = maxNonceAgeInMillis;
143 /* ------------------------------------------------------------ */
145 public String getAuthMethod()
147 return Constraint.__DIGEST_AUTH;
150 /* ------------------------------------------------------------ */
152 public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
159 /* ------------------------------------------------------------ */
161 public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
164 return new DeferredAuthentication(this);
166 HttpServletRequest request = (HttpServletRequest)req;
167 HttpServletResponse response = (HttpServletResponse)res;
168 String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
172 boolean stale = false;
173 if (credentials != null)
175 if (LOG.isDebugEnabled())
176 LOG.debug("Credentials: " + credentials);
177 QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
178 final Digest digest = new Digest(request.getMethod());
182 while (tokenizer.hasMoreTokens())
184 String tok = tokenizer.nextToken();
185 char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
203 if ("username".equalsIgnoreCase(name))
204 digest.username = tok;
205 else if ("realm".equalsIgnoreCase(name))
207 else if ("nonce".equalsIgnoreCase(name))
209 else if ("nc".equalsIgnoreCase(name))
211 else if ("cnonce".equalsIgnoreCase(name))
213 else if ("qop".equalsIgnoreCase(name))
215 else if ("uri".equalsIgnoreCase(name))
217 else if ("response".equalsIgnoreCase(name))
218 digest.response = tok;
224 int n = checkNonce(digest,(Request)request);
228 //UserIdentity user = _loginService.login(digest.username,digest);
229 UserIdentity user = login(digest.username, digest, req);
232 return new UserAuthentication(getAuthMethod(),user);
240 if (!DeferredAuthentication.isDeferred(response))
242 String domain = request.getContextPath();
245 response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + _loginService.getName()
249 + newNonce((Request)request)
250 + "\", algorithm=MD5, qop=\"auth\","
251 + " stale=" + stale);
252 response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
254 return Authentication.SEND_CONTINUE;
257 return Authentication.UNAUTHENTICATED;
259 catch (IOException e)
261 throw new ServerAuthException(e);
266 /* ------------------------------------------------------------ */
267 public String newNonce(Request request)
273 byte[] nounce = new byte[24];
274 _random.nextBytes(nounce);
276 nonce = new Nonce(new String(B64Code.encode(nounce)),request.getTimeStamp(),_maxNC);
278 while (_nonceMap.putIfAbsent(nonce._nonce,nonce)!=null);
279 _nonceQueue.add(nonce);
285 * @param nstring nonce to check
287 * @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
289 /* ------------------------------------------------------------ */
290 private int checkNonce(Digest digest, Request request)
292 // firstly let's expire old nonces
293 long expired = request.getTimeStamp()-_maxNonceAgeMs;
294 Nonce nonce=_nonceQueue.peek();
295 while (nonce!=null && nonce._ts<expired)
297 _nonceQueue.remove(nonce);
298 _nonceMap.remove(nonce._nonce);
299 nonce=_nonceQueue.peek();
302 // Now check the requested nonce
305 nonce = _nonceMap.get(digest.nonce);
309 long count = Long.parseLong(digest.nc,16);
313 if (nonce.seen((int)count))
325 /* ------------------------------------------------------------ */
326 /* ------------------------------------------------------------ */
327 /* ------------------------------------------------------------ */
328 private static class Digest extends Credential
330 private static final long serialVersionUID = -2484639019549527724L;
332 String username = "";
339 String response = "";
341 /* ------------------------------------------------------------ */
347 /* ------------------------------------------------------------ */
349 public boolean check(Object credentials)
351 if (credentials instanceof char[])
352 credentials=new String((char[])credentials);
353 String password = (credentials instanceof String) ? (String) credentials : credentials.toString();
357 MessageDigest md = MessageDigest.getInstance("MD5");
359 if (credentials instanceof Credential.MD5)
361 // Credentials are already a MD5 digest - assume it's in
362 // form user:realm:password (we have no way to know since
363 // it's a digest, alright?)
364 ha1 = ((Credential.MD5) credentials).getDigest();
369 md.update(username.getBytes(StandardCharsets.ISO_8859_1));
370 md.update((byte) ':');
371 md.update(realm.getBytes(StandardCharsets.ISO_8859_1));
372 md.update((byte) ':');
373 md.update(password.getBytes(StandardCharsets.ISO_8859_1));
378 md.update(method.getBytes(StandardCharsets.ISO_8859_1));
379 md.update((byte) ':');
380 md.update(uri.getBytes(StandardCharsets.ISO_8859_1));
381 byte[] ha2 = md.digest();
384 // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
385 // nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
387 // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
390 md.update(TypeUtil.toString(ha1, 16).getBytes(StandardCharsets.ISO_8859_1));
391 md.update((byte) ':');
392 md.update(nonce.getBytes(StandardCharsets.ISO_8859_1));
393 md.update((byte) ':');
394 md.update(nc.getBytes(StandardCharsets.ISO_8859_1));
395 md.update((byte) ':');
396 md.update(cnonce.getBytes(StandardCharsets.ISO_8859_1));
397 md.update((byte) ':');
398 md.update(qop.getBytes(StandardCharsets.ISO_8859_1));
399 md.update((byte) ':');
400 md.update(TypeUtil.toString(ha2, 16).getBytes(StandardCharsets.ISO_8859_1));
401 byte[] digest = md.digest();
404 return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response));
415 public String toString()
417 return username + "," + response;