View Javadoc

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/DigestScheme.java,v 1.22 2004/12/30 11:01:27 oglueck Exp $
3    * $Revision: 188828 $
4    * $Date: 2005-06-07 13:35:20 -0400 (Tue, 07 Jun 2005) $
5    *
6    * ====================================================================
7    *
8    *  Copyright 2002-2004 The Apache Software Foundation
9    *
10   *  Licensed under the Apache License, Version 2.0 (the "License");
11   *  you may not use this file except in compliance with the License.
12   *  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.auth;
31  
32  import java.security.MessageDigest;
33  import java.security.NoSuchAlgorithmException;
34  import java.util.ArrayList;
35  import java.util.List;
36  import java.util.StringTokenizer;
37  
38  import org.apache.commons.httpclient.Credentials;
39  import org.apache.commons.httpclient.HttpClientError;
40  import org.apache.commons.httpclient.HttpMethod;
41  import org.apache.commons.httpclient.NameValuePair;
42  import org.apache.commons.httpclient.UsernamePasswordCredentials;
43  import org.apache.commons.httpclient.util.EncodingUtil;
44  import org.apache.commons.httpclient.util.ParameterFormatter;
45  import org.apache.commons.logging.Log;
46  import org.apache.commons.logging.LogFactory;
47  
48  /***
49   * <p>
50   * Digest authentication scheme as defined in RFC 2617.
51   * Both MD5 (default) and MD5-sess are supported.
52   * Currently only qop=auth or no qop is supported. qop=auth-int
53   * is unsupported. If auth and auth-int are provided, auth is
54   * used.
55   * </p>
56   * <p>
57   * Credential charset is configured via the 
58   * {@link org.apache.commons.httpclient.params.HttpMethodParams#CREDENTIAL_CHARSET credential
59   * charset} parameter.  Since the digest username is included as clear text in the generated 
60   * Authentication header, the charset of the username must be compatible with the 
61   * {@link org.apache.commons.httpclient.params.HttpMethodParams#HTTP_ELEMENT_CHARSET http element 
62   * charset}.
63   * </p>
64   * TODO: make class more stateful regarding repeated authentication requests
65   * 
66   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
67   * @author Rodney Waldhoff
68   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
69   * @author Ortwin Gl?ck
70   * @author Sean C. Sullivan
71   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
72   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
73   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
74   */
75  
76  public class DigestScheme extends RFC2617Scheme {
77      
78      /*** Log object for this class. */
79      private static final Log LOG = LogFactory.getLog(DigestScheme.class);
80  
81      /***
82       * Hexa values used when creating 32 character long digest in HTTP DigestScheme
83       * in case of authentication.
84       * 
85       * @see #encode(byte[])
86       */
87      private static final char[] HEXADECIMAL = {
88          '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 
89          'e', 'f'
90      };
91      
92      /*** Whether the digest authentication process is complete */
93      private boolean complete;
94      
95      //TODO: supply a real nonce-count, currently a server will interprete a repeated request as a replay  
96      private static final String NC = "00000001"; //nonce-count is always 1
97      private static final int QOP_MISSING = 0;
98      private static final int QOP_AUTH_INT = 1;
99      private static final int QOP_AUTH = 2;
100 
101     private int qopVariant = QOP_MISSING;
102     private String cnonce;
103 
104     private final ParameterFormatter formatter;
105     /***
106      * Default constructor for the digest authetication scheme.
107      * 
108      * @since 3.0
109      */
110     public DigestScheme() {
111         super();
112         this.complete = false;
113         this.formatter = new ParameterFormatter();
114         this.formatter.setAlwaysUseQuotes(true);
115     }
116 
117     /***
118      * Gets an ID based upon the realm and the nonce value.  This ensures that requests
119      * to the same realm with different nonce values will succeed.  This differentiation
120      * allows servers to request re-authentication using a fresh nonce value.
121      * 
122      * @deprecated no longer used
123      */
124     public String getID() {
125         
126         String id = getRealm();
127         String nonce = getParameter("nonce");
128         if (nonce != null) {
129             id += "-" + nonce;
130         }
131         
132         return id;
133     }
134 
135     /***
136      * Constructor for the digest authetication scheme.
137      * 
138      * @param challenge authentication challenge
139      * 
140      * @throws MalformedChallengeException is thrown if the authentication challenge
141      * is malformed
142      * 
143      * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} 
144      *             method
145      */
146     public DigestScheme(final String challenge) 
147       throws MalformedChallengeException {
148         this();
149         processChallenge(challenge);
150     }
151 
152     /***
153      * Processes the Digest challenge.
154      *  
155      * @param challenge the challenge string
156      * 
157      * @throws MalformedChallengeException is thrown if the authentication challenge
158      * is malformed
159      * 
160      * @since 3.0
161      */
162     public void processChallenge(final String challenge) 
163       throws MalformedChallengeException {
164         super.processChallenge(challenge);
165         
166         if (getParameter("realm") == null) {
167             throw new MalformedChallengeException("missing realm in challange");
168         }
169         if (getParameter("nonce") == null) {
170             throw new MalformedChallengeException("missing nonce in challange");   
171         }
172         
173         boolean unsupportedQop = false;
174         // qop parsing
175         String qop = getParameter("qop");
176         if (qop != null) {
177             StringTokenizer tok = new StringTokenizer(qop,",");
178             while (tok.hasMoreTokens()) {
179                 String variant = tok.nextToken().trim();
180                 if (variant.equals("auth")) {
181                     qopVariant = QOP_AUTH;
182                     break; //that's our favourite, because auth-int is unsupported
183                 } else if (variant.equals("auth-int")) {
184                     qopVariant = QOP_AUTH_INT;               
185                 } else {
186                     unsupportedQop = true;
187                     LOG.warn("Unsupported qop detected: "+ variant);   
188                 }     
189             }
190         }        
191         
192         if (unsupportedQop && (qopVariant == QOP_MISSING)) {
193             throw new MalformedChallengeException("None of the qop methods is supported");   
194         }
195         
196         cnonce = createCnonce();   
197         this.complete = true;
198     }
199 
200     /***
201      * Tests if the Digest authentication process has been completed.
202      * 
203      * @return <tt>true</tt> if Digest authorization has been processed,
204      *   <tt>false</tt> otherwise.
205      * 
206      * @since 3.0
207      */
208     public boolean isComplete() {
209         String s = getParameter("stale");
210         if ("true".equalsIgnoreCase(s)) {
211             return false;
212         } else {
213             return this.complete;
214         }
215     }
216 
217     /***
218      * Returns textual designation of the digest authentication scheme.
219      * 
220      * @return <code>digest</code>
221      */
222     public String getSchemeName() {
223         return "digest";
224     }
225 
226     /***
227      * Returns <tt>false</tt>. Digest authentication scheme is request based.
228      * 
229      * @return <tt>false</tt>.
230      * 
231      * @since 3.0
232      */
233     public boolean isConnectionBased() {
234         return false;    
235     }
236 
237     /***
238      * Produces a digest authorization string for the given set of 
239      * {@link Credentials}, method name and URI.
240      * 
241      * @param credentials A set of credentials to be used for athentication
242      * @param method the name of the method that requires authorization. 
243      * @param uri The URI for which authorization is needed. 
244      * 
245      * @throws InvalidCredentialsException if authentication credentials
246      *         are not valid or not applicable for this authentication scheme
247      * @throws AuthenticationException if authorization string cannot 
248      *   be generated due to an authentication failure
249      * 
250      * @return a digest authorization string
251      * 
252      * @see org.apache.commons.httpclient.HttpMethod#getName()
253      * @see org.apache.commons.httpclient.HttpMethod#getPath()
254      * 
255      * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
256      */
257     public String authenticate(Credentials credentials, String method, String uri)
258       throws AuthenticationException {
259 
260         LOG.trace("enter DigestScheme.authenticate(Credentials, String, String)");
261 
262         UsernamePasswordCredentials usernamepassword = null;
263         try {
264             usernamepassword = (UsernamePasswordCredentials) credentials;
265         } catch (ClassCastException e) {
266             throw new InvalidCredentialsException(
267              "Credentials cannot be used for digest authentication: " 
268               + credentials.getClass().getName());
269         }
270         getParameters().put("methodname", method);
271         getParameters().put("uri", uri);
272         String digest = createDigest(
273             usernamepassword.getUserName(),
274             usernamepassword.getPassword());
275         return "Digest " + createDigestHeader(usernamepassword.getUserName(), digest);
276     }
277 
278     /***
279      * Produces a digest authorization string for the given set of 
280      * {@link Credentials}, method name and URI.
281      * 
282      * @param credentials A set of credentials to be used for athentication
283      * @param method The method being authenticated
284      * 
285      * @throws InvalidCredentialsException if authentication credentials
286      *         are not valid or not applicable for this authentication scheme
287      * @throws AuthenticationException if authorization string cannot 
288      *   be generated due to an authentication failure
289      * 
290      * @return a digest authorization string
291      * 
292      * @since 3.0
293      */
294     public String authenticate(Credentials credentials, HttpMethod method)
295     throws AuthenticationException {
296 
297         LOG.trace("enter DigestScheme.authenticate(Credentials, HttpMethod)");
298 
299         UsernamePasswordCredentials usernamepassword = null;
300         try {
301             usernamepassword = (UsernamePasswordCredentials) credentials;
302         } catch (ClassCastException e) {
303             throw new InvalidCredentialsException(
304                     "Credentials cannot be used for digest authentication: " 
305                     + credentials.getClass().getName());
306         }
307         getParameters().put("methodname", method.getName());
308         getParameters().put("uri", method.getPath());
309         String charset = getParameter("charset");
310         if (charset == null) {
311             getParameters().put("charset", method.getParams().getCredentialCharset());
312         }
313         String digest = createDigest(
314             usernamepassword.getUserName(),
315             usernamepassword.getPassword());
316         return "Digest " + createDigestHeader(usernamepassword.getUserName(),
317                 digest);
318     }
319     
320     /***
321      * Creates an MD5 response digest.
322      * 
323      * @param uname Username
324      * @param pwd Password
325      * @param charset The credential charset
326      * 
327      * @return The created digest as string. This will be the response tag's
328      *         value in the Authentication HTTP header.
329      * @throws AuthenticationException when MD5 is an unsupported algorithm
330      */
331     private String createDigest(final String uname, final String pwd) throws AuthenticationException {
332 
333         LOG.trace("enter DigestScheme.createDigest(String, String, Map)");
334 
335         final String digAlg = "MD5";
336 
337         // Collecting required tokens
338         String uri = getParameter("uri");
339         String realm = getParameter("realm");
340         String nonce = getParameter("nonce");
341         String qop = getParameter("qop");
342         String method = getParameter("methodname");
343         String algorithm = getParameter("algorithm");
344         // If an algorithm is not specified, default to MD5.
345         if (algorithm == null) {
346             algorithm = "MD5";
347         }
348         // If an charset is not specified, default to ISO-8859-1.
349         String charset = getParameter("charset");
350         if (charset == null) {
351             charset = "ISO-8859-1";
352         }
353 
354         if (qopVariant == QOP_AUTH_INT) {
355             LOG.warn("qop=auth-int is not supported");
356             throw new AuthenticationException(
357                 "Unsupported qop in HTTP Digest authentication");   
358         }
359 
360         MessageDigest md5Helper;
361 
362         try {
363             md5Helper = MessageDigest.getInstance(digAlg);
364         } catch (Exception e) {
365             throw new AuthenticationException(
366               "Unsupported algorithm in HTTP Digest authentication: "
367                + digAlg);
368         }
369 
370         // 3.2.2.2: Calculating digest
371         StringBuffer tmp = new StringBuffer(uname.length() + realm.length() + pwd.length() + 2);
372         tmp.append(uname);
373         tmp.append(':');
374         tmp.append(realm);
375         tmp.append(':');
376         tmp.append(pwd);
377         // unq(username-value) ":" unq(realm-value) ":" passwd
378         String a1 = tmp.toString();
379         //a1 is suitable for MD5 algorithm
380         if(algorithm.equals("MD5-sess")) {
381             // H( unq(username-value) ":" unq(realm-value) ":" passwd )
382             //      ":" unq(nonce-value)
383             //      ":" unq(cnonce-value)
384 
385             String tmp2=encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
386             StringBuffer tmp3 = new StringBuffer(tmp2.length() + nonce.length() + cnonce.length() + 2);
387             tmp3.append(tmp2);
388             tmp3.append(':');
389             tmp3.append(nonce);
390             tmp3.append(':');
391             tmp3.append(cnonce);
392             a1 = tmp3.toString();
393         } else if(!algorithm.equals("MD5")) {
394             LOG.warn("Unhandled algorithm " + algorithm + " requested");
395         }
396         String md5a1 = encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
397 
398         String a2 = null;
399         if (qopVariant == QOP_AUTH_INT) {
400             LOG.error("Unhandled qop auth-int");
401             //we do not have access to the entity-body or its hash
402             //TODO: add Method ":" digest-uri-value ":" H(entity-body)      
403         } else {
404             a2 = method + ":" + uri;
405         }
406         String md5a2 = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(a2)));
407 
408         // 3.2.2.1
409         String serverDigestValue;
410         if (qopVariant == QOP_MISSING) {
411             LOG.debug("Using null qop method");
412             StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length() + md5a2.length());
413             tmp2.append(md5a1);
414             tmp2.append(':');
415             tmp2.append(nonce);
416             tmp2.append(':');
417             tmp2.append(md5a2);
418             serverDigestValue = tmp2.toString();
419         } else {
420             if (LOG.isDebugEnabled()) {
421                 LOG.debug("Using qop method " + qop);
422             }
423             String qopOption = getQopVariantString();
424             StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length()
425                 + NC.length() + cnonce.length() + qopOption.length() + md5a2.length() + 5);
426             tmp2.append(md5a1);
427             tmp2.append(':');
428             tmp2.append(nonce);
429             tmp2.append(':');
430             tmp2.append(NC);
431             tmp2.append(':');
432             tmp2.append(cnonce);
433             tmp2.append(':');
434             tmp2.append(qopOption);
435             tmp2.append(':');
436             tmp2.append(md5a2); 
437             serverDigestValue = tmp2.toString();
438         }
439 
440         String serverDigest =
441             encode(md5Helper.digest(EncodingUtil.getAsciiBytes(serverDigestValue)));
442 
443         return serverDigest;
444     }
445 
446     /***
447      * Creates digest-response header as defined in RFC2617.
448      * 
449      * @param uname Username
450      * @param digest The response tag's value as String.
451      * 
452      * @return The digest-response as String.
453      */
454     private String createDigestHeader(final String uname, final String digest) 
455         throws AuthenticationException {
456 
457         LOG.trace("enter DigestScheme.createDigestHeader(String, Map, "
458             + "String)");
459 
460         String uri = getParameter("uri");
461         String realm = getParameter("realm");
462         String nonce = getParameter("nonce");
463         String nc = getParameter("nc");
464         String opaque = getParameter("opaque");
465         String response = digest;
466         String qop = getParameter("qop");
467         String algorithm = getParameter("algorithm");
468 
469         List params = new ArrayList(20);
470         params.add(new NameValuePair("username", uname));
471         params.add(new NameValuePair("realm", realm));
472         params.add(new NameValuePair("nonce", nonce));
473         params.add(new NameValuePair("uri", uri));
474         params.add(new NameValuePair("response", response));
475         
476         if (qopVariant != QOP_MISSING) {
477             params.add(new NameValuePair("qop", getQopVariantString()));
478             params.add(new NameValuePair("nc", NC));
479             params.add(new NameValuePair("cnonce", this.cnonce));
480         }
481         if (algorithm != null) {
482             params.add(new NameValuePair("algorithm", algorithm));
483         }    
484         if (opaque != null) {
485             params.add(new NameValuePair("opaque", opaque));
486         }
487 
488         StringBuffer buffer = new StringBuffer();
489         for (int i = 0; i < params.size(); i++) {
490             NameValuePair param = (NameValuePair) params.get(i);
491             if (i > 0) {
492                 buffer.append(", ");
493             }
494             this.formatter.format(buffer, param);
495         }
496         return buffer.toString();
497     }
498 
499     private String getQopVariantString() {
500         String qopOption;
501         if (qopVariant == QOP_AUTH_INT) {
502             qopOption = "auth-int";   
503         } else {
504             qopOption = "auth";
505         }
506         return qopOption;            
507     }
508 
509     /***
510      * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long 
511      * <CODE>String</CODE> according to RFC 2617.
512      * 
513      * @param binaryData array containing the digest
514      * @return encoded MD5, or <CODE>null</CODE> if encoding failed
515      */
516     private static String encode(byte[] binaryData) {
517         LOG.trace("enter DigestScheme.encode(byte[])");
518 
519         if (binaryData.length != 16) {
520             return null;
521         } 
522 
523         char[] buffer = new char[32];
524         for (int i = 0; i < 16; i++) {
525             int low = (int) (binaryData[i] & 0x0f);
526             int high = (int) ((binaryData[i] & 0xf0) >> 4);
527             buffer[i * 2] = HEXADECIMAL[high];
528             buffer[(i * 2) + 1] = HEXADECIMAL[low];
529         }
530 
531         return new String(buffer);
532     }
533 
534 
535     /***
536      * Creates a random cnonce value based on the current time.
537      * 
538      * @return The cnonce value as String.
539      * @throws HttpClientError if MD5 algorithm is not supported.
540      */
541     public static String createCnonce() {
542         LOG.trace("enter DigestScheme.createCnonce()");
543 
544         String cnonce;
545         final String digAlg = "MD5";
546         MessageDigest md5Helper;
547 
548         try {
549             md5Helper = MessageDigest.getInstance(digAlg);
550         } catch (NoSuchAlgorithmException e) {
551             throw new HttpClientError(
552               "Unsupported algorithm in HTTP Digest authentication: "
553                + digAlg);
554         }
555 
556         cnonce = Long.toString(System.currentTimeMillis());
557         cnonce = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(cnonce)));
558 
559         return cnonce;
560     }
561 }