View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 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.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.security.authentication;
20  
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;
30  
31  import javax.servlet.ServletRequest;
32  import javax.servlet.ServletResponse;
33  import javax.servlet.http.HttpServletRequest;
34  import javax.servlet.http.HttpServletResponse;
35  
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.StringUtil;
47  import org.eclipse.jetty.util.TypeUtil;
48  import org.eclipse.jetty.util.log.Log;
49  import org.eclipse.jetty.util.log.Logger;
50  import org.eclipse.jetty.util.security.Constraint;
51  import org.eclipse.jetty.util.security.Credential;
52  
53  /**
54   * @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
55   *
56   * The nonce max age in ms can be set with the {@link SecurityHandler#setInitParameter(String, String)}
57   * using the name "maxNonceAge".  The nonce max count can be set with {@link SecurityHandler#setInitParameter(String, String)}
58   * using the name "maxNonceCount".  When the age or count is exceeded, the nonce is considered stale.
59   */
60  public class DigestAuthenticator extends LoginAuthenticator
61  {
62      private static final Logger LOG = Log.getLogger(DigestAuthenticator.class);
63      SecureRandom _random = new SecureRandom();
64      private long _maxNonceAgeMs = 60*1000;
65      private int _maxNC=1024;
66      private ConcurrentMap<String, Nonce> _nonceMap = new ConcurrentHashMap<String, Nonce>();
67      private Queue<Nonce> _nonceQueue = new ConcurrentLinkedQueue<Nonce>();
68      private static class Nonce
69      {
70          final String _nonce;
71          final long _ts;
72          final BitSet _seen; 
73  
74          public Nonce(String nonce, long ts, int size)
75          {
76              _nonce=nonce;
77              _ts=ts;
78              _seen = new BitSet(size);
79          }
80  
81          public boolean seen(int count)
82          {
83              synchronized (this)
84              {
85                  if (count>=_seen.size())
86                      return true;
87                  boolean s=_seen.get(count);
88                  _seen.set(count);
89                  return s;
90              }
91          }
92      }
93  
94      /* ------------------------------------------------------------ */
95      public DigestAuthenticator()
96      {
97          super();
98      }
99  
100     /* ------------------------------------------------------------ */
101     /**
102      * @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.AuthConfiguration)
103      */
104     @Override
105     public void setConfiguration(AuthConfiguration configuration)
106     {
107         super.setConfiguration(configuration);
108 
109         String mna=configuration.getInitParameter("maxNonceAge");
110         if (mna!=null)
111         {
112             _maxNonceAgeMs=Long.valueOf(mna);
113         }
114         String mnc=configuration.getInitParameter("maxNonceCount");
115         if (mnc!=null)
116         {
117             _maxNC=Integer.valueOf(mnc);
118         }
119     }
120 
121     /* ------------------------------------------------------------ */
122     public int getMaxNonceCount()
123     {
124         return _maxNC;
125     }
126 
127     /* ------------------------------------------------------------ */
128     public void setMaxNonceCount(int maxNC)
129     {
130         _maxNC = maxNC;
131     }
132 
133     /* ------------------------------------------------------------ */
134     public long getMaxNonceAge()
135     {
136         return _maxNonceAgeMs;
137     }
138 
139     /* ------------------------------------------------------------ */
140     public synchronized void setMaxNonceAge(long maxNonceAgeInMillis)
141     {
142         _maxNonceAgeMs = maxNonceAgeInMillis;
143     }
144 
145     /* ------------------------------------------------------------ */
146     @Override
147     public String getAuthMethod()
148     {
149         return Constraint.__DIGEST_AUTH;
150     }
151 
152     /* ------------------------------------------------------------ */
153     @Override
154     public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
155     {
156         return true;
157     }
158     
159 
160 
161     /* ------------------------------------------------------------ */
162     @Override
163     public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
164     {
165         if (!mandatory)
166             return new DeferredAuthentication(this);
167 
168         HttpServletRequest request = (HttpServletRequest)req;
169         HttpServletResponse response = (HttpServletResponse)res;
170         String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
171 
172         try
173         {
174             boolean stale = false;
175             if (credentials != null)
176             {
177                 if (LOG.isDebugEnabled())
178                     LOG.debug("Credentials: " + credentials);
179                 QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
180                 final Digest digest = new Digest(request.getMethod());
181                 String last = null;
182                 String name = null;
183 
184                 while (tokenizer.hasMoreTokens())
185                 {
186                     String tok = tokenizer.nextToken();
187                     char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
188 
189                     switch (c)
190                     {
191                         case '=':
192                             name = last;
193                             last = tok;
194                             break;
195                         case ',':
196                             name = null;
197                             break;
198                         case ' ':
199                             break;
200 
201                         default:
202                             last = tok;
203                             if (name != null)
204                             {
205                                 if ("username".equalsIgnoreCase(name))
206                                     digest.username = tok;
207                                 else if ("realm".equalsIgnoreCase(name))
208                                     digest.realm = tok;
209                                 else if ("nonce".equalsIgnoreCase(name))
210                                     digest.nonce = tok;
211                                 else if ("nc".equalsIgnoreCase(name))
212                                     digest.nc = tok;
213                                 else if ("cnonce".equalsIgnoreCase(name))
214                                     digest.cnonce = tok;
215                                 else if ("qop".equalsIgnoreCase(name))
216                                     digest.qop = tok;
217                                 else if ("uri".equalsIgnoreCase(name))
218                                     digest.uri = tok;
219                                 else if ("response".equalsIgnoreCase(name))
220                                     digest.response = tok;
221                                 name=null;
222                             }
223                     }
224                 }
225 
226                 int n = checkNonce(digest,(Request)request);
227 
228                 if (n > 0)
229                 {
230                     //UserIdentity user = _loginService.login(digest.username,digest);
231                     UserIdentity user = login(digest.username, digest, req);
232                     if (user!=null)
233                     {
234                         return new UserAuthentication(getAuthMethod(),user);
235                     }
236                 }
237                 else if (n == 0)
238                     stale = true;
239 
240             }
241 
242             if (!DeferredAuthentication.isDeferred(response))
243             {
244                 String domain = request.getContextPath();
245                 if (domain == null)
246                     domain = "/";
247                 response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + _loginService.getName()
248                         + "\", domain=\""
249                         + domain
250                         + "\", nonce=\""
251                         + newNonce((Request)request)
252                         + "\", algorithm=MD5, qop=\"auth\","
253                         + " stale=" + stale);
254                 response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
255 
256                 return Authentication.SEND_CONTINUE;
257             }
258 
259             return Authentication.UNAUTHENTICATED;
260         }
261         catch (IOException e)
262         {
263             throw new ServerAuthException(e);
264         }
265 
266     }
267 
268     /* ------------------------------------------------------------ */
269     public String newNonce(Request request)
270     {
271         Nonce nonce;
272 
273         do
274         {
275             byte[] nounce = new byte[24];
276             _random.nextBytes(nounce);
277 
278             nonce = new Nonce(new String(B64Code.encode(nounce)),request.getTimeStamp(),_maxNC);
279         }
280         while (_nonceMap.putIfAbsent(nonce._nonce,nonce)!=null);
281         _nonceQueue.add(nonce);
282 
283         return nonce._nonce;
284     }
285 
286     /**
287      * @param nstring nonce to check
288      * @param request
289      * @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
290      */
291     /* ------------------------------------------------------------ */
292     private int checkNonce(Digest digest, Request request)
293     {
294         // firstly let's expire old nonces
295         long expired = request.getTimeStamp()-_maxNonceAgeMs;
296         Nonce nonce=_nonceQueue.peek();
297         while (nonce!=null && nonce._ts<expired)
298         {
299             _nonceQueue.remove(nonce);
300             _nonceMap.remove(nonce._nonce);
301             nonce=_nonceQueue.peek();
302         }
303 
304         // Now check the requested nonce
305         try
306         {
307             nonce = _nonceMap.get(digest.nonce);
308             if (nonce==null)
309                 return 0;
310 
311             long count = Long.parseLong(digest.nc,16);
312             if (count>=_maxNC)
313                 return 0;
314             
315             if (nonce.seen((int)count))
316                 return -1;
317 
318             return 1;
319         }
320         catch (Exception e)
321         {
322             LOG.ignore(e);
323         }
324         return -1;
325     }
326 
327     /* ------------------------------------------------------------ */
328     /* ------------------------------------------------------------ */
329     /* ------------------------------------------------------------ */
330     private static class Digest extends Credential
331     {
332         private static final long serialVersionUID = -2484639019549527724L;
333         final String method;
334         String username = "";
335         String realm = "";
336         String nonce = "";
337         String nc = "";
338         String cnonce = "";
339         String qop = "";
340         String uri = "";
341         String response = "";
342 
343         /* ------------------------------------------------------------ */
344         Digest(String m)
345         {
346             method = m;
347         }
348 
349         /* ------------------------------------------------------------ */
350         @Override
351         public boolean check(Object credentials)
352         {
353             if (credentials instanceof char[])
354                 credentials=new String((char[])credentials);
355             String password = (credentials instanceof String) ? (String) credentials : credentials.toString();
356 
357             try
358             {
359                 MessageDigest md = MessageDigest.getInstance("MD5");
360                 byte[] ha1;
361                 if (credentials instanceof Credential.MD5)
362                 {
363                     // Credentials are already a MD5 digest - assume it's in
364                     // form user:realm:password (we have no way to know since
365                     // it's a digest, alright?)
366                     ha1 = ((Credential.MD5) credentials).getDigest();
367                 }
368                 else
369                 {
370                     // calc A1 digest
371                     md.update(username.getBytes(StandardCharsets.ISO_8859_1));
372                     md.update((byte) ':');
373                     md.update(realm.getBytes(StandardCharsets.ISO_8859_1));
374                     md.update((byte) ':');
375                     md.update(password.getBytes(StandardCharsets.ISO_8859_1));
376                     ha1 = md.digest();
377                 }
378                 // calc A2 digest
379                 md.reset();
380                 md.update(method.getBytes(StandardCharsets.ISO_8859_1));
381                 md.update((byte) ':');
382                 md.update(uri.getBytes(StandardCharsets.ISO_8859_1));
383                 byte[] ha2 = md.digest();
384 
385                 // calc digest
386                 // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
387                 // nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
388                 // <">
389                 // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
390                 // ) > <">
391 
392                 md.update(TypeUtil.toString(ha1, 16).getBytes(StandardCharsets.ISO_8859_1));
393                 md.update((byte) ':');
394                 md.update(nonce.getBytes(StandardCharsets.ISO_8859_1));
395                 md.update((byte) ':');
396                 md.update(nc.getBytes(StandardCharsets.ISO_8859_1));
397                 md.update((byte) ':');
398                 md.update(cnonce.getBytes(StandardCharsets.ISO_8859_1));
399                 md.update((byte) ':');
400                 md.update(qop.getBytes(StandardCharsets.ISO_8859_1));
401                 md.update((byte) ':');
402                 md.update(TypeUtil.toString(ha2, 16).getBytes(StandardCharsets.ISO_8859_1));
403                 byte[] digest = md.digest();
404 
405                 // check digest
406                 return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response));
407             }
408             catch (Exception e)
409             {
410                 LOG.warn(e);
411             }
412 
413             return false;
414         }
415 
416         @Override
417         public String toString()
418         {
419             return username + "," + response;
420         }
421     }
422 }