View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.proxy.handlers.http.digest;
21  
22  import java.io.UnsupportedEncodingException;
23  import java.security.MessageDigest;
24  import java.security.NoSuchAlgorithmException;
25  import java.util.HashMap;
26  
27  import javax.security.sasl.AuthenticationException;
28  
29  import org.apache.mina.core.session.IoSession;
30  import org.apache.mina.proxy.session.ProxyIoSession;
31  import org.apache.mina.proxy.utils.ByteUtilities;
32  import org.apache.mina.proxy.utils.StringUtilities;
33  
34  /**
35   * DigestUtilities.java - A class supporting the HTTP DIGEST authentication (see RFC 2617).
36   * 
37   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
38   * @since MINA 2.0.0-M3
39   */
40  public class DigestUtilities {
41  
42      public final static String SESSION_HA1 = DigestUtilities.class + ".SessionHA1";
43  
44      private static MessageDigest md5;
45  
46      static {
47          // Initialize secure random generator 
48          try {
49              md5 = MessageDigest.getInstance("MD5");
50          } catch (NoSuchAlgorithmException e) {
51              throw new RuntimeException(e);
52          }
53      }
54  
55      /**
56       * The supported qualities of protections.
57       */
58      public final static String[] SUPPORTED_QOPS = new String[] { "auth", "auth-int" };
59  
60      /**
61       * Computes the response to the DIGEST challenge.
62       * 
63       * @param session the current session
64       * @param map the map holding the directives sent by the proxy
65       * @param method the HTTP verb
66       * @param pwd the password
67       * @param charsetName the name of the charset used for the challenge
68       * @param body the html body to be hashed for integrity calculations
69       * @return The response
70       * @throws AuthenticationException if we weren't able to find a directive value in the map
71       * @throws UnsupportedEncodingException If we weren't able to encode to ISO 8859_1 the username or realm,
72       * or if we weren't able to encode the charsetName
73       */
74      public static String computeResponseValue(IoSession session, HashMap<String, String> map, String method,
75              String pwd, String charsetName, String body) throws AuthenticationException, UnsupportedEncodingException{
76  
77          byte[] hA1;
78          StringBuilder sb;
79          boolean isMD5Sess = "md5-sess".equalsIgnoreCase(StringUtilities.getDirectiveValue(map, "algorithm", false));
80  
81          if (!isMD5Sess || (session.getAttribute(SESSION_HA1) == null)) {
82              // Build A1
83              sb = new StringBuilder();
84              sb.append(StringUtilities.stringTo8859_1(StringUtilities.getDirectiveValue(map, "username", true))).append(
85                      ':');
86  
87              String realm = StringUtilities.stringTo8859_1(StringUtilities.getDirectiveValue(map, "realm", false));
88              
89              if (realm != null) {
90                  sb.append(realm);
91              }
92  
93              sb.append(':').append(pwd);
94  
95              if (isMD5Sess) {
96                  byte[] prehA1;
97                  
98                  synchronized (md5) {
99                      md5.reset();
100                     prehA1 = md5.digest(sb.toString().getBytes(charsetName));
101                 }
102 
103                 sb = new StringBuilder();
104                 sb.append(ByteUtilities.asHex(prehA1));
105                 sb.append(':').append(
106                         StringUtilities.stringTo8859_1(StringUtilities.getDirectiveValue(map, "nonce", true)));
107                 sb.append(':').append(
108                         StringUtilities.stringTo8859_1(StringUtilities.getDirectiveValue(map, "cnonce", true)));
109 
110                 synchronized (md5) {
111                     md5.reset();
112                     hA1 = md5.digest(sb.toString().getBytes(charsetName));
113                 }
114 
115                 session.setAttribute(SESSION_HA1, hA1);
116             } else {
117                 synchronized (md5) {
118                     md5.reset();
119                     hA1 = md5.digest(sb.toString().getBytes(charsetName));
120                 }
121             }
122         } else {
123             hA1 = (byte[]) session.getAttribute(SESSION_HA1);
124         }
125 
126         sb = new StringBuilder(method);
127         sb.append(':');
128         sb.append(StringUtilities.getDirectiveValue(map, "uri", false));
129 
130         String qop = StringUtilities.getDirectiveValue(map, "qop", false);
131         
132         if ("auth-int".equalsIgnoreCase(qop)) {
133             ProxyIoSession proxyIoSession = (ProxyIoSession) session.getAttribute(ProxyIoSession.PROXY_SESSION);
134             byte[] hEntity;
135 
136             synchronized (md5) {
137                 md5.reset();
138                 hEntity = md5.digest(body.getBytes(proxyIoSession.getCharsetName()));
139             }
140             
141             sb.append(':').append(hEntity);
142         }
143 
144         byte[] hA2;
145         synchronized (md5) {
146             md5.reset();
147             hA2 = md5.digest(sb.toString().getBytes(charsetName));
148         }
149 
150         sb = new StringBuilder();
151         sb.append(ByteUtilities.asHex(hA1));
152         sb.append(':').append(StringUtilities.getDirectiveValue(map, "nonce", true));
153         sb.append(":00000001:");
154 
155         sb.append(StringUtilities.getDirectiveValue(map, "cnonce", true));
156         sb.append(':').append(qop).append(':');
157         sb.append(ByteUtilities.asHex(hA2));
158 
159         byte[] hFinal;
160         
161         synchronized (md5) {
162             md5.reset();
163             hFinal = md5.digest(sb.toString().getBytes(charsetName));
164         }
165 
166         return ByteUtilities.asHex(hFinal);
167     }
168 }