View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.http.impl.auth;
28  
29  import java.io.IOException;
30  import java.nio.charset.Charset;
31  import java.security.MessageDigest;
32  import java.security.SecureRandom;
33  import java.util.ArrayList;
34  import java.util.Formatter;
35  import java.util.HashSet;
36  import java.util.List;
37  import java.util.Locale;
38  import java.util.Set;
39  import java.util.StringTokenizer;
40  
41  import org.apache.http.Consts;
42  import org.apache.http.Header;
43  import org.apache.http.HttpEntity;
44  import org.apache.http.HttpEntityEnclosingRequest;
45  import org.apache.http.HttpRequest;
46  import org.apache.http.annotation.NotThreadSafe;
47  import org.apache.http.auth.AUTH;
48  import org.apache.http.auth.AuthenticationException;
49  import org.apache.http.auth.ChallengeState;
50  import org.apache.http.auth.Credentials;
51  import org.apache.http.auth.MalformedChallengeException;
52  import org.apache.http.message.BasicHeaderValueFormatter;
53  import org.apache.http.message.BasicNameValuePair;
54  import org.apache.http.message.BufferedHeader;
55  import org.apache.http.protocol.BasicHttpContext;
56  import org.apache.http.protocol.HttpContext;
57  import org.apache.http.util.Args;
58  import org.apache.http.util.CharArrayBuffer;
59  import org.apache.http.util.EncodingUtils;
60  
61  /**
62   * Digest authentication scheme as defined in RFC 2617.
63   * Both MD5 (default) and MD5-sess are supported.
64   * Currently only qop=auth or no qop is supported. qop=auth-int
65   * is unsupported. If auth and auth-int are provided, auth is
66   * used.
67   * <p>
68   * Since the digest username is included as clear text in the generated
69   * Authentication header, the charset of the username must be compatible
70   * with the HTTP element charset used by the connection.
71   * </p>
72   *
73   * @since 4.0
74   */
75  @NotThreadSafe
76  public class DigestScheme extends RFC2617Scheme {
77  
78      private static final long serialVersionUID = 3883908186234566916L;
79  
80      /**
81       * Hexa values used when creating 32 character long digest in HTTP DigestScheme
82       * in case of authentication.
83       *
84       * @see #encode(byte[])
85       */
86      private static final char[] HEXADECIMAL = {
87          '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
88          'e', 'f'
89      };
90  
91      /** Whether the digest authentication process is complete */
92      private boolean complete;
93  
94      private static final int QOP_UNKNOWN = -1;
95      private static final int QOP_MISSING = 0;
96      private static final int QOP_AUTH_INT = 1;
97      private static final int QOP_AUTH = 2;
98  
99      private String lastNonce;
100     private long nounceCount;
101     private String cnonce;
102     private String a1;
103     private String a2;
104 
105     /**
106      * @since 4.3
107      */
108     public DigestScheme(final Charset credentialsCharset) {
109         super(credentialsCharset);
110         this.complete = false;
111     }
112 
113     /**
114      * Creates an instance of {@code DigestScheme} with the given challenge
115      * state.
116      *
117      * @since 4.2
118      *
119      * @deprecated (4.3) do not use.
120      */
121     @Deprecated
122     public DigestScheme(final ChallengeState challengeState) {
123         super(challengeState);
124     }
125 
126     public DigestScheme() {
127         this(Consts.ASCII);
128     }
129 
130     /**
131      * Processes the Digest challenge.
132      *
133      * @param header the challenge header
134      *
135      * @throws MalformedChallengeException is thrown if the authentication challenge
136      * is malformed
137      */
138     @Override
139     public void processChallenge(
140             final Header header) throws MalformedChallengeException {
141         super.processChallenge(header);
142         this.complete = true;
143     }
144 
145     /**
146      * Tests if the Digest authentication process has been completed.
147      *
148      * @return {@code true} if Digest authorization has been processed,
149      *   {@code false} otherwise.
150      */
151     @Override
152     public boolean isComplete() {
153         final String s = getParameter("stale");
154         if ("true".equalsIgnoreCase(s)) {
155             return false;
156         } else {
157             return this.complete;
158         }
159     }
160 
161     /**
162      * Returns textual designation of the digest authentication scheme.
163      *
164      * @return {@code digest}
165      */
166     @Override
167     public String getSchemeName() {
168         return "digest";
169     }
170 
171     /**
172      * Returns {@code false}. Digest authentication scheme is request based.
173      *
174      * @return {@code false}.
175      */
176     @Override
177     public boolean isConnectionBased() {
178         return false;
179     }
180 
181     public void overrideParamter(final String name, final String value) {
182         getParameters().put(name, value);
183     }
184 
185     /**
186      * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate(
187      *   Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
188      */
189     @Override
190     @Deprecated
191     public Header authenticate(
192             final Credentials credentials, final HttpRequest request) throws AuthenticationException {
193         return authenticate(credentials, request, new BasicHttpContext());
194     }
195 
196     /**
197      * Produces a digest authorization string for the given set of
198      * {@link Credentials}, method name and URI.
199      *
200      * @param credentials A set of credentials to be used for athentication
201      * @param request    The request being authenticated
202      *
203      * @throws org.apache.http.auth.InvalidCredentialsException if authentication credentials
204      *         are not valid or not applicable for this authentication scheme
205      * @throws AuthenticationException if authorization string cannot
206      *   be generated due to an authentication failure
207      *
208      * @return a digest authorization string
209      */
210     @Override
211     public Header authenticate(
212             final Credentials credentials,
213             final HttpRequest request,
214             final HttpContext context) throws AuthenticationException {
215 
216         Args.notNull(credentials, "Credentials");
217         Args.notNull(request, "HTTP request");
218         if (getParameter("realm") == null) {
219             throw new AuthenticationException("missing realm in challenge");
220         }
221         if (getParameter("nonce") == null) {
222             throw new AuthenticationException("missing nonce in challenge");
223         }
224         // Add method name and request-URI to the parameter map
225         getParameters().put("methodname", request.getRequestLine().getMethod());
226         getParameters().put("uri", request.getRequestLine().getUri());
227         final String charset = getParameter("charset");
228         if (charset == null) {
229             getParameters().put("charset", getCredentialsCharset(request));
230         }
231         return createDigestHeader(credentials, request);
232     }
233 
234     private static MessageDigest createMessageDigest(
235             final String digAlg) throws UnsupportedDigestAlgorithmException {
236         try {
237             return MessageDigest.getInstance(digAlg);
238         } catch (final Exception e) {
239             throw new UnsupportedDigestAlgorithmException(
240               "Unsupported algorithm in HTTP Digest authentication: "
241                + digAlg);
242         }
243     }
244 
245     /**
246      * Creates digest-response header as defined in RFC2617.
247      *
248      * @param credentials User credentials
249      *
250      * @return The digest-response as String.
251      */
252     private Header createDigestHeader(
253             final Credentials credentials,
254             final HttpRequest request) throws AuthenticationException {
255         final String uri = getParameter("uri");
256         final String realm = getParameter("realm");
257         final String nonce = getParameter("nonce");
258         final String opaque = getParameter("opaque");
259         final String method = getParameter("methodname");
260         String algorithm = getParameter("algorithm");
261         // If an algorithm is not specified, default to MD5.
262         if (algorithm == null) {
263             algorithm = "MD5";
264         }
265 
266         final Set<String> qopset = new HashSet<String>(8);
267         int qop = QOP_UNKNOWN;
268         final String qoplist = getParameter("qop");
269         if (qoplist != null) {
270             final StringTokenizer tok = new StringTokenizer(qoplist, ",");
271             while (tok.hasMoreTokens()) {
272                 final String variant = tok.nextToken().trim();
273                 qopset.add(variant.toLowerCase(Locale.ROOT));
274             }
275             if (request instanceof HttpEntityEnclosingRequest && qopset.contains("auth-int")) {
276                 qop = QOP_AUTH_INT;
277             } else if (qopset.contains("auth")) {
278                 qop = QOP_AUTH;
279             }
280         } else {
281             qop = QOP_MISSING;
282         }
283 
284         if (qop == QOP_UNKNOWN) {
285             throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
286         }
287 
288         String charset = getParameter("charset");
289         if (charset == null) {
290             charset = "ISO-8859-1";
291         }
292 
293         String digAlg = algorithm;
294         if (digAlg.equalsIgnoreCase("MD5-sess")) {
295             digAlg = "MD5";
296         }
297 
298         final MessageDigest digester;
299         try {
300             digester = createMessageDigest(digAlg);
301         } catch (final UnsupportedDigestAlgorithmException ex) {
302             throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg);
303         }
304 
305         final String uname = credentials.getUserPrincipal().getName();
306         final String pwd = credentials.getPassword();
307 
308         if (nonce.equals(this.lastNonce)) {
309             nounceCount++;
310         } else {
311             nounceCount = 1;
312             cnonce = null;
313             lastNonce = nonce;
314         }
315         final StringBuilder sb = new StringBuilder(256);
316         final Formatter formatter = new Formatter(sb, Locale.US);
317         formatter.format("%08x", Long.valueOf(nounceCount));
318         formatter.close();
319         final String nc = sb.toString();
320 
321         if (cnonce == null) {
322             cnonce = createCnonce();
323         }
324 
325         a1 = null;
326         a2 = null;
327         // 3.2.2.2: Calculating digest
328         if (algorithm.equalsIgnoreCase("MD5-sess")) {
329             // H( unq(username-value) ":" unq(realm-value) ":" passwd )
330             //      ":" unq(nonce-value)
331             //      ":" unq(cnonce-value)
332 
333             // calculated one per session
334             sb.setLength(0);
335             sb.append(uname).append(':').append(realm).append(':').append(pwd);
336             final String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset)));
337             sb.setLength(0);
338             sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
339             a1 = sb.toString();
340         } else {
341             // unq(username-value) ":" unq(realm-value) ":" passwd
342             sb.setLength(0);
343             sb.append(uname).append(':').append(realm).append(':').append(pwd);
344             a1 = sb.toString();
345         }
346 
347         final String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));
348 
349         if (qop == QOP_AUTH) {
350             // Method ":" digest-uri-value
351             a2 = method + ':' + uri;
352         } else if (qop == QOP_AUTH_INT) {
353             // Method ":" digest-uri-value ":" H(entity-body)
354             HttpEntity entity = null;
355             if (request instanceof HttpEntityEnclosingRequest) {
356                 entity = ((HttpEntityEnclosingRequest) request).getEntity();
357             }
358             if (entity != null && !entity.isRepeatable()) {
359                 // If the entity is not repeatable, try falling back onto QOP_AUTH
360                 if (qopset.contains("auth")) {
361                     qop = QOP_AUTH;
362                     a2 = method + ':' + uri;
363                 } else {
364                     throw new AuthenticationException("Qop auth-int cannot be used with " +
365                             "a non-repeatable entity");
366                 }
367             } else {
368                 final HttpEntityDigester entityDigester = new HttpEntityDigester(digester);
369                 try {
370                     if (entity != null) {
371                         entity.writeTo(entityDigester);
372                     }
373                     entityDigester.close();
374                 } catch (final IOException ex) {
375                     throw new AuthenticationException("I/O error reading entity content", ex);
376                 }
377                 a2 = method + ':' + uri + ':' + encode(entityDigester.getDigest());
378             }
379         } else {
380             a2 = method + ':' + uri;
381         }
382 
383         final String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset)));
384 
385         // 3.2.2.1
386 
387         final String digestValue;
388         if (qop == QOP_MISSING) {
389             sb.setLength(0);
390             sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);
391             digestValue = sb.toString();
392         } else {
393             sb.setLength(0);
394             sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':')
395                 .append(cnonce).append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth")
396                 .append(':').append(hasha2);
397             digestValue = sb.toString();
398         }
399 
400         final String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue)));
401 
402         final CharArrayBuffer buffer = new CharArrayBuffer(128);
403         if (isProxy()) {
404             buffer.append(AUTH.PROXY_AUTH_RESP);
405         } else {
406             buffer.append(AUTH.WWW_AUTH_RESP);
407         }
408         buffer.append(": Digest ");
409 
410         final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
411         params.add(new BasicNameValuePair("username", uname));
412         params.add(new BasicNameValuePair("realm", realm));
413         params.add(new BasicNameValuePair("nonce", nonce));
414         params.add(new BasicNameValuePair("uri", uri));
415         params.add(new BasicNameValuePair("response", digest));
416 
417         if (qop != QOP_MISSING) {
418             params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth"));
419             params.add(new BasicNameValuePair("nc", nc));
420             params.add(new BasicNameValuePair("cnonce", cnonce));
421         }
422         // algorithm cannot be null here
423         params.add(new BasicNameValuePair("algorithm", algorithm));
424         if (opaque != null) {
425             params.add(new BasicNameValuePair("opaque", opaque));
426         }
427 
428         for (int i = 0; i < params.size(); i++) {
429             final BasicNameValuePair param = params.get(i);
430             if (i > 0) {
431                 buffer.append(", ");
432             }
433             final String name = param.getName();
434             final boolean noQuotes = ("nc".equals(name) || "qop".equals(name)
435                     || "algorithm".equals(name));
436             BasicHeaderValueFormatter.INSTANCE.formatNameValuePair(buffer, param, !noQuotes);
437         }
438         return new BufferedHeader(buffer);
439     }
440 
441     String getCnonce() {
442         return cnonce;
443     }
444 
445     String getA1() {
446         return a1;
447     }
448 
449     String getA2() {
450         return a2;
451     }
452 
453     /**
454      * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long
455      * <CODE>String</CODE> according to RFC 2617.
456      *
457      * @param binaryData array containing the digest
458      * @return encoded MD5, or <CODE>null</CODE> if encoding failed
459      */
460     static String encode(final byte[] binaryData) {
461         final int n = binaryData.length;
462         final char[] buffer = new char[n * 2];
463         for (int i = 0; i < n; i++) {
464             final int low = (binaryData[i] & 0x0f);
465             final int high = ((binaryData[i] & 0xf0) >> 4);
466             buffer[i * 2] = HEXADECIMAL[high];
467             buffer[(i * 2) + 1] = HEXADECIMAL[low];
468         }
469 
470         return new String(buffer);
471     }
472 
473 
474     /**
475      * Creates a random cnonce value based on the current time.
476      *
477      * @return The cnonce value as String.
478      */
479     public static String createCnonce() {
480         final SecureRandom rnd = new SecureRandom();
481         final byte[] tmp = new byte[8];
482         rnd.nextBytes(tmp);
483         return encode(tmp);
484     }
485 
486     @Override
487     public String toString() {
488         final StringBuilder builder = new StringBuilder();
489         builder.append("DIGEST [complete=").append(complete)
490                 .append(", nonce=").append(lastNonce)
491                 .append(", nc=").append(nounceCount)
492                 .append("]");
493         return builder.toString();
494     }
495 
496 }