2 // ========================================================================
3 // Copyright (c) 1995-2014 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.SecurityHandler;
38 import org.eclipse.jetty.security.ServerAuthException;
39 import org.eclipse.jetty.security.UserAuthentication;
40 import org.eclipse.jetty.server.Authentication;
41 import org.eclipse.jetty.server.Authentication.User;
42 import org.eclipse.jetty.server.Request;
43 import org.eclipse.jetty.server.UserIdentity;
44 import org.eclipse.jetty.util.B64Code;
45 import org.eclipse.jetty.util.QuotedStringTokenizer;
46 import org.eclipse.jetty.util.TypeUtil;
47 import org.eclipse.jetty.util.log.Log;
48 import org.eclipse.jetty.util.log.Logger;
49 import org.eclipse.jetty.util.security.Constraint;
50 import org.eclipse.jetty.util.security.Credential;
53 * @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
55 * The nonce max age in ms can be set with the {@link SecurityHandler#setInitParameter(String, String)}
56 * using the name "maxNonceAge". The nonce max count can be set with {@link SecurityHandler#setInitParameter(String, String)}
57 * using the name "maxNonceCount". When the age or count is exceeded, the nonce is considered stale.
59 public class DigestAuthenticator extends LoginAuthenticator
61 private static final Logger LOG = Log.getLogger(DigestAuthenticator.class);
62 SecureRandom _random = new SecureRandom();
63 private long _maxNonceAgeMs = 60*1000;
64 private int _maxNC=1024;
65 private ConcurrentMap<String, Nonce> _nonceMap = new ConcurrentHashMap<String, Nonce>();
66 private Queue<Nonce> _nonceQueue = new ConcurrentLinkedQueue<Nonce>();
67 private static class Nonce
73 public Nonce(String nonce, long ts, int size)
77 _seen = new BitSet(size);
80 public boolean seen(int count)
84 if (count>=_seen.size())
86 boolean s=_seen.get(count);
93 /* ------------------------------------------------------------ */
94 public DigestAuthenticator()
99 /* ------------------------------------------------------------ */
101 * @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.AuthConfiguration)
104 public void setConfiguration(AuthConfiguration configuration)
106 super.setConfiguration(configuration);
108 String mna=configuration.getInitParameter("maxNonceAge");
111 _maxNonceAgeMs=Long.valueOf(mna);
113 String mnc=configuration.getInitParameter("maxNonceCount");
116 _maxNC=Integer.valueOf(mnc);
120 /* ------------------------------------------------------------ */
121 public int getMaxNonceCount()
126 /* ------------------------------------------------------------ */
127 public void setMaxNonceCount(int maxNC)
132 /* ------------------------------------------------------------ */
133 public long getMaxNonceAge()
135 return _maxNonceAgeMs;
138 /* ------------------------------------------------------------ */
139 public synchronized void setMaxNonceAge(long maxNonceAgeInMillis)
141 _maxNonceAgeMs = maxNonceAgeInMillis;
144 /* ------------------------------------------------------------ */
146 public String getAuthMethod()
148 return Constraint.__DIGEST_AUTH;
151 /* ------------------------------------------------------------ */
153 public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
160 /* ------------------------------------------------------------ */
162 public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
165 return new DeferredAuthentication(this);
167 HttpServletRequest request = (HttpServletRequest)req;
168 HttpServletResponse response = (HttpServletResponse)res;
169 String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
173 boolean stale = false;
174 if (credentials != null)
176 if (LOG.isDebugEnabled())
177 LOG.debug("Credentials: " + credentials);
178 QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
179 final Digest digest = new Digest(request.getMethod());
183 while (tokenizer.hasMoreTokens())
185 String tok = tokenizer.nextToken();
186 char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
204 if ("username".equalsIgnoreCase(name))
205 digest.username = tok;
206 else if ("realm".equalsIgnoreCase(name))
208 else if ("nonce".equalsIgnoreCase(name))
210 else if ("nc".equalsIgnoreCase(name))
212 else if ("cnonce".equalsIgnoreCase(name))
214 else if ("qop".equalsIgnoreCase(name))
216 else if ("uri".equalsIgnoreCase(name))
218 else if ("response".equalsIgnoreCase(name))
219 digest.response = tok;
225 int n = checkNonce(digest,(Request)request);
229 //UserIdentity user = _loginService.login(digest.username,digest);
230 UserIdentity user = login(digest.username, digest, req);
233 return new UserAuthentication(getAuthMethod(),user);
241 if (!DeferredAuthentication.isDeferred(response))
243 String domain = request.getContextPath();
246 response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + _loginService.getName()
250 + newNonce((Request)request)
251 + "\", algorithm=MD5, qop=\"auth\","
252 + " stale=" + stale);
253 response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
255 return Authentication.SEND_CONTINUE;
258 return Authentication.UNAUTHENTICATED;
260 catch (IOException e)
262 throw new ServerAuthException(e);
267 /* ------------------------------------------------------------ */
268 public String newNonce(Request request)
274 byte[] nounce = new byte[24];
275 _random.nextBytes(nounce);
277 nonce = new Nonce(new String(B64Code.encode(nounce)),request.getTimeStamp(),_maxNC);
279 while (_nonceMap.putIfAbsent(nonce._nonce,nonce)!=null);
280 _nonceQueue.add(nonce);
286 * @param nstring nonce to check
288 * @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
290 /* ------------------------------------------------------------ */
291 private int checkNonce(Digest digest, Request request)
293 // firstly let's expire old nonces
294 long expired = request.getTimeStamp()-_maxNonceAgeMs;
295 Nonce nonce=_nonceQueue.peek();
296 while (nonce!=null && nonce._ts<expired)
298 _nonceQueue.remove(nonce);
299 _nonceMap.remove(nonce._nonce);
300 nonce=_nonceQueue.peek();
303 // Now check the requested nonce
306 nonce = _nonceMap.get(digest.nonce);
310 long count = Long.parseLong(digest.nc,16);
314 if (nonce.seen((int)count))
326 /* ------------------------------------------------------------ */
327 /* ------------------------------------------------------------ */
328 /* ------------------------------------------------------------ */
329 private static class Digest extends Credential
331 private static final long serialVersionUID = -2484639019549527724L;
333 String username = "";
340 String response = "";
342 /* ------------------------------------------------------------ */
348 /* ------------------------------------------------------------ */
350 public boolean check(Object credentials)
352 if (credentials instanceof char[])
353 credentials=new String((char[])credentials);
354 String password = (credentials instanceof String) ? (String) credentials : credentials.toString();
358 MessageDigest md = MessageDigest.getInstance("MD5");
360 if (credentials instanceof Credential.MD5)
362 // Credentials are already a MD5 digest - assume it's in
363 // form user:realm:password (we have no way to know since
364 // it's a digest, alright?)
365 ha1 = ((Credential.MD5) credentials).getDigest();
370 md.update(username.getBytes(StandardCharsets.ISO_8859_1));
371 md.update((byte) ':');
372 md.update(realm.getBytes(StandardCharsets.ISO_8859_1));
373 md.update((byte) ':');
374 md.update(password.getBytes(StandardCharsets.ISO_8859_1));
379 md.update(method.getBytes(StandardCharsets.ISO_8859_1));
380 md.update((byte) ':');
381 md.update(uri.getBytes(StandardCharsets.ISO_8859_1));
382 byte[] ha2 = md.digest();
385 // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
386 // nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
388 // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
391 md.update(TypeUtil.toString(ha1, 16).getBytes(StandardCharsets.ISO_8859_1));
392 md.update((byte) ':');
393 md.update(nonce.getBytes(StandardCharsets.ISO_8859_1));
394 md.update((byte) ':');
395 md.update(nc.getBytes(StandardCharsets.ISO_8859_1));
396 md.update((byte) ':');
397 md.update(cnonce.getBytes(StandardCharsets.ISO_8859_1));
398 md.update((byte) ':');
399 md.update(qop.getBytes(StandardCharsets.ISO_8859_1));
400 md.update((byte) ':');
401 md.update(TypeUtil.toString(ha2, 16).getBytes(StandardCharsets.ISO_8859_1));
402 byte[] digest = md.digest();
405 return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response));
416 public String toString()
418 return username + "," + response;