1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
96 private static final String NC = "00000001";
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 }
115
116 /***
117 * Gets an ID based upon the realm and the nonce value. This ensures that requests
118 * to the same realm with different nonce values will succeed. This differentiation
119 * allows servers to request re-authentication using a fresh nonce value.
120 *
121 * @deprecated no longer used
122 */
123 public String getID() {
124
125 String id = getRealm();
126 String nonce = getParameter("nonce");
127 if (nonce != null) {
128 id += "-" + nonce;
129 }
130
131 return id;
132 }
133
134 /***
135 * Constructor for the digest authetication scheme.
136 *
137 * @param challenge authentication challenge
138 *
139 * @throws MalformedChallengeException is thrown if the authentication challenge
140 * is malformed
141 *
142 * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)}
143 * method
144 */
145 public DigestScheme(final String challenge)
146 throws MalformedChallengeException {
147 this();
148 processChallenge(challenge);
149 }
150
151 /***
152 * Processes the Digest challenge.
153 *
154 * @param challenge the challenge string
155 *
156 * @throws MalformedChallengeException is thrown if the authentication challenge
157 * is malformed
158 *
159 * @since 3.0
160 */
161 public void processChallenge(final String challenge)
162 throws MalformedChallengeException {
163 super.processChallenge(challenge);
164
165 if (getParameter("realm") == null) {
166 throw new MalformedChallengeException("missing realm in challange");
167 }
168 if (getParameter("nonce") == null) {
169 throw new MalformedChallengeException("missing nonce in challange");
170 }
171
172 boolean unsupportedQop = false;
173
174 String qop = getParameter("qop");
175 if (qop != null) {
176 StringTokenizer tok = new StringTokenizer(qop,",");
177 while (tok.hasMoreTokens()) {
178 String variant = tok.nextToken().trim();
179 if (variant.equals("auth")) {
180 qopVariant = QOP_AUTH;
181 break;
182 } else if (variant.equals("auth-int")) {
183 qopVariant = QOP_AUTH_INT;
184 } else {
185 unsupportedQop = true;
186 LOG.warn("Unsupported qop detected: "+ variant);
187 }
188 }
189 }
190
191 if (unsupportedQop && (qopVariant == QOP_MISSING)) {
192 throw new MalformedChallengeException("None of the qop methods is supported");
193 }
194
195 cnonce = createCnonce();
196 this.complete = true;
197 }
198
199 /***
200 * Tests if the Digest authentication process has been completed.
201 *
202 * @return <tt>true</tt> if Digest authorization has been processed,
203 * <tt>false</tt> otherwise.
204 *
205 * @since 3.0
206 */
207 public boolean isComplete() {
208 String s = getParameter("stale");
209 if ("true".equalsIgnoreCase(s)) {
210 return false;
211 } else {
212 return this.complete;
213 }
214 }
215
216 /***
217 * Returns textual designation of the digest authentication scheme.
218 *
219 * @return <code>digest</code>
220 */
221 public String getSchemeName() {
222 return "digest";
223 }
224
225 /***
226 * Returns <tt>false</tt>. Digest authentication scheme is request based.
227 *
228 * @return <tt>false</tt>.
229 *
230 * @since 3.0
231 */
232 public boolean isConnectionBased() {
233 return false;
234 }
235
236 /***
237 * Produces a digest authorization string for the given set of
238 * {@link Credentials}, method name and URI.
239 *
240 * @param credentials A set of credentials to be used for athentication
241 * @param method the name of the method that requires authorization.
242 * @param uri The URI for which authorization is needed.
243 *
244 * @throws InvalidCredentialsException if authentication credentials
245 * are not valid or not applicable for this authentication scheme
246 * @throws AuthenticationException if authorization string cannot
247 * be generated due to an authentication failure
248 *
249 * @return a digest authorization string
250 *
251 * @see org.apache.commons.httpclient.HttpMethod#getName()
252 * @see org.apache.commons.httpclient.HttpMethod#getPath()
253 *
254 * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
255 */
256 public String authenticate(Credentials credentials, String method, String uri)
257 throws AuthenticationException {
258
259 LOG.trace("enter DigestScheme.authenticate(Credentials, String, String)");
260
261 UsernamePasswordCredentials usernamepassword = null;
262 try {
263 usernamepassword = (UsernamePasswordCredentials) credentials;
264 } catch (ClassCastException e) {
265 throw new InvalidCredentialsException(
266 "Credentials cannot be used for digest authentication: "
267 + credentials.getClass().getName());
268 }
269 getParameters().put("methodname", method);
270 getParameters().put("uri", uri);
271 String digest = createDigest(
272 usernamepassword.getUserName(),
273 usernamepassword.getPassword());
274 return "Digest " + createDigestHeader(usernamepassword.getUserName(), digest);
275 }
276
277 /***
278 * Produces a digest authorization string for the given set of
279 * {@link Credentials}, method name and URI.
280 *
281 * @param credentials A set of credentials to be used for athentication
282 * @param method The method being authenticated
283 *
284 * @throws InvalidCredentialsException if authentication credentials
285 * are not valid or not applicable for this authentication scheme
286 * @throws AuthenticationException if authorization string cannot
287 * be generated due to an authentication failure
288 *
289 * @return a digest authorization string
290 *
291 * @since 3.0
292 */
293 public String authenticate(Credentials credentials, HttpMethod method)
294 throws AuthenticationException {
295
296 LOG.trace("enter DigestScheme.authenticate(Credentials, HttpMethod)");
297
298 UsernamePasswordCredentials usernamepassword = null;
299 try {
300 usernamepassword = (UsernamePasswordCredentials) credentials;
301 } catch (ClassCastException e) {
302 throw new InvalidCredentialsException(
303 "Credentials cannot be used for digest authentication: "
304 + credentials.getClass().getName());
305 }
306 getParameters().put("methodname", method.getName());
307 getParameters().put("uri", method.getPath());
308 String charset = getParameter("charset");
309 if (charset == null) {
310 getParameters().put("charset", method.getParams().getCredentialCharset());
311 }
312 String digest = createDigest(
313 usernamepassword.getUserName(),
314 usernamepassword.getPassword());
315 return "Digest " + createDigestHeader(usernamepassword.getUserName(),
316 digest);
317 }
318
319 /***
320 * Creates an MD5 response digest.
321 *
322 * @param uname Username
323 * @param pwd Password
324 * @param charset The credential charset
325 *
326 * @return The created digest as string. This will be the response tag's
327 * value in the Authentication HTTP header.
328 * @throws AuthenticationException when MD5 is an unsupported algorithm
329 */
330 private String createDigest(final String uname, final String pwd) throws AuthenticationException {
331
332 LOG.trace("enter DigestScheme.createDigest(String, String, Map)");
333
334 final String digAlg = "MD5";
335
336
337 String uri = getParameter("uri");
338 String realm = getParameter("realm");
339 String nonce = getParameter("nonce");
340 String qop = getParameter("qop");
341 String method = getParameter("methodname");
342 String algorithm = getParameter("algorithm");
343
344 if (algorithm == null) {
345 algorithm = "MD5";
346 }
347
348 String charset = getParameter("charset");
349 if (charset == null) {
350 charset = "ISO-8859-1";
351 }
352
353 if (qopVariant == QOP_AUTH_INT) {
354 LOG.warn("qop=auth-int is not supported");
355 throw new AuthenticationException(
356 "Unsupported qop in HTTP Digest authentication");
357 }
358
359 MessageDigest md5Helper;
360
361 try {
362 md5Helper = MessageDigest.getInstance(digAlg);
363 } catch (Exception e) {
364 throw new AuthenticationException(
365 "Unsupported algorithm in HTTP Digest authentication: "
366 + digAlg);
367 }
368
369
370 StringBuffer tmp = new StringBuffer(uname.length() + realm.length() + pwd.length() + 2);
371 tmp.append(uname);
372 tmp.append(':');
373 tmp.append(realm);
374 tmp.append(':');
375 tmp.append(pwd);
376
377 String a1 = tmp.toString();
378
379 if(algorithm.equals("MD5-sess")) {
380
381
382
383
384 String tmp2=encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
385 StringBuffer tmp3 = new StringBuffer(tmp2.length() + nonce.length() + cnonce.length() + 2);
386 tmp3.append(tmp2);
387 tmp3.append(':');
388 tmp3.append(nonce);
389 tmp3.append(':');
390 tmp3.append(cnonce);
391 a1 = tmp3.toString();
392 } else if(!algorithm.equals("MD5")) {
393 LOG.warn("Unhandled algorithm " + algorithm + " requested");
394 }
395 String md5a1 = encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
396
397 String a2 = null;
398 if (qopVariant == QOP_AUTH_INT) {
399 LOG.error("Unhandled qop auth-int");
400
401
402 } else {
403 a2 = method + ":" + uri;
404 }
405 String md5a2 = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(a2)));
406
407
408 String serverDigestValue;
409 if (qopVariant == QOP_MISSING) {
410 LOG.debug("Using null qop method");
411 StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length() + md5a2.length());
412 tmp2.append(md5a1);
413 tmp2.append(':');
414 tmp2.append(nonce);
415 tmp2.append(':');
416 tmp2.append(md5a2);
417 serverDigestValue = tmp2.toString();
418 } else {
419 if (LOG.isDebugEnabled()) {
420 LOG.debug("Using qop method " + qop);
421 }
422 String qopOption = getQopVariantString();
423 StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length()
424 + NC.length() + cnonce.length() + qopOption.length() + md5a2.length() + 5);
425 tmp2.append(md5a1);
426 tmp2.append(':');
427 tmp2.append(nonce);
428 tmp2.append(':');
429 tmp2.append(NC);
430 tmp2.append(':');
431 tmp2.append(cnonce);
432 tmp2.append(':');
433 tmp2.append(qopOption);
434 tmp2.append(':');
435 tmp2.append(md5a2);
436 serverDigestValue = tmp2.toString();
437 }
438
439 String serverDigest =
440 encode(md5Helper.digest(EncodingUtil.getAsciiBytes(serverDigestValue)));
441
442 return serverDigest;
443 }
444
445 /***
446 * Creates digest-response header as defined in RFC2617.
447 *
448 * @param uname Username
449 * @param digest The response tag's value as String.
450 *
451 * @return The digest-response as String.
452 */
453 private String createDigestHeader(final String uname, final String digest)
454 throws AuthenticationException {
455
456 LOG.trace("enter DigestScheme.createDigestHeader(String, Map, "
457 + "String)");
458
459 String uri = getParameter("uri");
460 String realm = getParameter("realm");
461 String nonce = getParameter("nonce");
462 String opaque = getParameter("opaque");
463 String response = digest;
464 String algorithm = getParameter("algorithm");
465
466 List params = new ArrayList(20);
467 params.add(new NameValuePair("username", uname));
468 params.add(new NameValuePair("realm", realm));
469 params.add(new NameValuePair("nonce", nonce));
470 params.add(new NameValuePair("uri", uri));
471 params.add(new NameValuePair("response", response));
472
473 if (qopVariant != QOP_MISSING) {
474 params.add(new NameValuePair("qop", getQopVariantString()));
475 params.add(new NameValuePair("nc", NC));
476 params.add(new NameValuePair("cnonce", this.cnonce));
477 }
478 if (algorithm != null) {
479 params.add(new NameValuePair("algorithm", algorithm));
480 }
481 if (opaque != null) {
482 params.add(new NameValuePair("opaque", opaque));
483 }
484
485 StringBuffer buffer = new StringBuffer();
486 for (int i = 0; i < params.size(); i++) {
487 NameValuePair param = (NameValuePair) params.get(i);
488 if (i > 0) {
489 buffer.append(", ");
490 }
491 boolean noQuotes = "nc".equals(param.getName()) ||
492 "qop".equals(param.getName());
493 this.formatter.setAlwaysUseQuotes(!noQuotes);
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 }