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.ntlm;
21  
22  import java.security.Key;
23  import java.security.MessageDigest;
24  
25  import javax.crypto.Cipher;
26  import javax.crypto.spec.SecretKeySpec;
27  
28  /**
29   * NTLMResponses.java - Calculates the various Type 3 responses. Needs an MD4,
30   * MD5 and DES crypto provider (Please note that default provider doesn't
31   * provide MD4).
32   * 
33   * Copyright (c) 2003 Eric Glass Permission to use, copy, modify, and distribute
34   * this document for any purpose and without any fee is hereby granted, provided
35   * that the above copyright notice and this list of conditions appear in all
36   * copies.
37   * 
38   * @see <a href="http://curl.haxx.se/rfc/ntlm.html">NTLM RFC</a>
39   * 
40   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
41   * @since MINA 2.0.0-M3
42   */
43  public class NTLMResponses {
44  
45      // LAN Manager magic constant used in LM Response calculation
46      public static final byte[] LM_HASH_MAGIC_CONSTANT =
47              new byte[]{ 'K', 'G', 'S', '!', '@', '#', '$', '%' };
48  
49      /**
50       * Calculates the LM Response for the given challenge, using the specified
51       * password.
52       *
53       * @param password The user's password.
54       * @param challenge The Type 2 challenge from the server.
55       *
56       * @return The LM Response.
57       */
58      public static byte[] getLMResponse(String password, byte[] challenge) throws Exception {
59          byte[] lmHash = lmHash(password);
60          return lmResponse(lmHash, challenge);
61      }
62  
63      /**
64       * Calculates the NTLM Response for the given challenge, using the
65       * specified password.
66       *
67       * @param password The user's password.
68       * @param challenge The Type 2 challenge from the server.
69       *
70       * @return The NTLM Response.
71       */
72      public static byte[] getNTLMResponse(String password, byte[] challenge) throws Exception {
73          byte[] ntlmHash = ntlmHash(password);
74          return lmResponse(ntlmHash, challenge);
75      }
76  
77      /**
78       * Calculates the NTLMv2 Response for the given challenge, using the
79       * specified authentication target, username, password, target information
80       * block, and client nonce.
81       *
82       * @param target The authentication target (i.e., domain).
83       * @param user The username.
84       * @param password The user's password.
85       * @param targetInformation The target information block from the Type 2
86       * message.
87       * @param challenge The Type 2 challenge from the server.
88       * @param clientNonce The random 8-byte client nonce.
89       *
90       * @return The NTLMv2 Response.
91       */
92      public static byte[] getNTLMv2Response(String target, String user, String password, byte[] targetInformation,
93              byte[] challenge, byte[] clientNonce) throws Exception {
94  
95          return getNTLMv2Response(target, user, password, targetInformation, challenge, clientNonce,
96                  System.currentTimeMillis());
97      }
98  
99      /**
100      * Calculates the NTLMv2 Response for the given challenge, using the
101      * specified authentication target, username, password, target information
102      * block, and client nonce.
103      *
104      * @param target The authentication target (i.e., domain).
105      * @param user The username.
106      * @param password The user's password.
107      * @param targetInformation The target information block from the Type 2
108      * message.
109      * @param challenge The Type 2 challenge from the server.
110      * @param clientNonce The random 8-byte client nonce.
111      * @param time The time stamp.
112      *
113      * @return The NTLMv2 Response.
114      */
115     public static byte[] getNTLMv2Response(String target, String user, String password, byte[] targetInformation,
116             byte[] challenge, byte[] clientNonce, long time) throws Exception {
117         byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
118         byte[] blob = createBlob(targetInformation, clientNonce, time);
119         return lmv2Response(ntlmv2Hash, blob, challenge);
120     }
121 
122     /**
123      * Calculates the LMv2 Response for the given challenge, using the
124      * specified authentication target, username, password, and client
125      * challenge.
126      *
127      * @param target The authentication target (i.e., domain).
128      * @param user The username.
129      * @param password The user's password.
130      * @param challenge The Type 2 challenge from the server.
131      * @param clientNonce The random 8-byte client nonce.
132      *
133      * @return The LMv2 Response.
134      */
135     public static byte[] getLMv2Response(String target, String user, String password, byte[] challenge,
136             byte[] clientNonce) throws Exception {
137         byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
138         return lmv2Response(ntlmv2Hash, clientNonce, challenge);
139     }
140 
141     /**
142      * Calculates the NTLM2 Session Response for the given challenge, using the
143      * specified password and client nonce.
144      *
145      * @param password The user's password.
146      * @param challenge The Type 2 challenge from the server.
147      * @param clientNonce The random 8-byte client nonce.
148      *
149      * @return The NTLM2 Session Response.  This is placed in the NTLM
150      * response field of the Type 3 message; the LM response field contains
151      * the client nonce, null-padded to 24 bytes.
152      */
153     public static byte[] getNTLM2SessionResponse(String password, byte[] challenge, byte[] clientNonce)
154             throws Exception {
155         byte[] ntlmHash = ntlmHash(password);
156         MessageDigest md5 = MessageDigest.getInstance("MD5");
157         md5.update(challenge);
158         md5.update(clientNonce);
159         byte[] sessionHash = new byte[8];
160         System.arraycopy(md5.digest(), 0, sessionHash, 0, 8);
161         return lmResponse(ntlmHash, sessionHash);
162     }
163 
164     /**
165      * Creates the LM Hash of the user's password.
166      *
167      * @param password The password.
168      *
169      * @return The LM Hash of the given password, used in the calculation
170      * of the LM Response.
171      */
172     private static byte[] lmHash(String password) throws Exception {
173         byte[] oemPassword = password.toUpperCase().getBytes("US-ASCII");
174         int length = Math.min(oemPassword.length, 14);
175         byte[] keyBytes = new byte[14];
176         System.arraycopy(oemPassword, 0, keyBytes, 0, length);
177         Key lowKey = createDESKey(keyBytes, 0);
178         Key highKey = createDESKey(keyBytes, 7);
179         Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
180         des.init(Cipher.ENCRYPT_MODE, lowKey);
181         byte[] lowHash = des.doFinal(LM_HASH_MAGIC_CONSTANT);
182         des.init(Cipher.ENCRYPT_MODE, highKey);
183         byte[] highHash = des.doFinal(LM_HASH_MAGIC_CONSTANT);
184         byte[] lmHash = new byte[16];
185         System.arraycopy(lowHash, 0, lmHash, 0, 8);
186         System.arraycopy(highHash, 0, lmHash, 8, 8);
187         return lmHash;
188     }
189 
190     /**
191      * Creates the NTLM Hash of the user's password.
192      *
193      * @param password The password.
194      *
195      * @return The NTLM Hash of the given password, used in the calculation
196      * of the NTLM Response and the NTLMv2 and LMv2 Hashes.
197      */
198     private static byte[] ntlmHash(String password) throws Exception {
199         byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
200         MessageDigest md4 = MessageDigest.getInstance("MD4");
201         return md4.digest(unicodePassword);
202     }
203 
204     /**
205      * Creates the NTLMv2 Hash of the user's password.
206      *
207      * @param target The authentication target (i.e., domain).
208      * @param user The username.
209      * @param password The password.
210      *
211      * @return The NTLMv2 Hash, used in the calculation of the NTLMv2
212      * and LMv2 Responses.
213      */
214     private static byte[] ntlmv2Hash(String target, String user, String password) throws Exception {
215         byte[] ntlmHash = ntlmHash(password);
216         String identity = user.toUpperCase() + target;
217         return hmacMD5(identity.getBytes("UnicodeLittleUnmarked"), ntlmHash);
218     }
219 
220     /**
221      * Creates the LM Response from the given hash and Type 2 challenge.
222      *
223      * @param hash The LM or NTLM Hash.
224      * @param challenge The server challenge from the Type 2 message.
225      *
226      * @return The response (either LM or NTLM, depending on the provided
227      * hash).
228      */
229     private static byte[] lmResponse(byte[] hash, byte[] challenge) throws Exception {
230         byte[] keyBytes = new byte[21];
231         System.arraycopy(hash, 0, keyBytes, 0, 16);
232         Key lowKey = createDESKey(keyBytes, 0);
233         Key middleKey = createDESKey(keyBytes, 7);
234         Key highKey = createDESKey(keyBytes, 14);
235         Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
236         des.init(Cipher.ENCRYPT_MODE, lowKey);
237         byte[] lowResponse = des.doFinal(challenge);
238         des.init(Cipher.ENCRYPT_MODE, middleKey);
239         byte[] middleResponse = des.doFinal(challenge);
240         des.init(Cipher.ENCRYPT_MODE, highKey);
241         byte[] highResponse = des.doFinal(challenge);
242         byte[] lmResponse = new byte[24];
243         System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
244         System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
245         System.arraycopy(highResponse, 0, lmResponse, 16, 8);
246         return lmResponse;
247     }
248 
249     /**
250      * Creates the LMv2 Response from the given hash, client data, and
251      * Type 2 challenge.
252      *
253      * @param hash The NTLMv2 Hash.
254      * @param clientData The client data (blob or client nonce).
255      * @param challenge The server challenge from the Type 2 message.
256      *
257      * @return The response (either NTLMv2 or LMv2, depending on the
258      * client data).
259      */
260     private static byte[] lmv2Response(byte[] hash, byte[] clientData, byte[] challenge) throws Exception {
261         byte[] data = new byte[challenge.length + clientData.length];
262         System.arraycopy(challenge, 0, data, 0, challenge.length);
263         System.arraycopy(clientData, 0, data, challenge.length, clientData.length);
264         byte[] mac = hmacMD5(data, hash);
265         byte[] lmv2Response = new byte[mac.length + clientData.length];
266         System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
267         System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length);
268         return lmv2Response;
269     }
270 
271     /**
272      * Creates the NTLMv2 blob from the given target information block and
273      * client nonce.
274      *
275      * @param targetInformation The target information block from the Type 2
276      * message.
277      * @param clientNonce The random 8-byte client nonce.
278      * @param time the time stamp.
279      *
280      * @return The blob, used in the calculation of the NTLMv2 Response.
281      */
282     private static byte[] createBlob(byte[] targetInformation, byte[] clientNonce, long time) {
283         byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 };
284         byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
285         byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
286         byte[] unknown2 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
287         time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
288         time *= 10000; // tenths of a microsecond.
289         // convert to little-endian byte array.
290         byte[] timestamp = new byte[8];
291         for (int i = 0; i < 8; i++) {
292             timestamp[i] = (byte) time;
293             time >>>= 8;
294         }
295         byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + clientNonce.length
296                                + unknown1.length + targetInformation.length + unknown2.length];
297         int offset = 0;
298         System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
299         offset += blobSignature.length;
300         System.arraycopy(reserved, 0, blob, offset, reserved.length);
301         offset += reserved.length;
302         System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
303         offset += timestamp.length;
304         System.arraycopy(clientNonce, 0, blob, offset, clientNonce.length);
305         offset += clientNonce.length;
306         System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
307         offset += unknown1.length;
308         System.arraycopy(targetInformation, 0, blob, offset, targetInformation.length);
309         offset += targetInformation.length;
310         System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
311         return blob;
312     }
313 
314     /**
315      * Calculates the HMAC-MD5 hash of the given data using the specified
316      * hashing key.
317      *
318      * @param data The data for which the hash will be calculated.
319      * @param key The hashing key.
320      *
321      * @return The HMAC-MD5 hash of the given data.
322      */
323     public static byte[] hmacMD5(byte[] data, byte[] key) throws Exception {
324         byte[] ipad = new byte[64];
325         byte[] opad = new byte[64];
326 
327         // Stores key in pads and XOR it with ipad and opad values
328         for (int i = 0; i < 64; i++) {
329             if (i < key.length) {
330                 ipad[i] = (byte) (key[i] ^ 0x36);
331                 opad[i] = (byte) (key[i] ^ 0x5c);
332             } else {
333                 ipad[i] = 0x36;
334                 opad[i] = 0x5c;
335             }
336         }
337 
338         byte[] content = new byte[data.length + 64];
339         System.arraycopy(ipad, 0, content, 0, 64);
340         System.arraycopy(data, 0, content, 64, data.length);
341         MessageDigest md5 = MessageDigest.getInstance("MD5");
342         data = md5.digest(content);
343         content = new byte[data.length + 64];
344         System.arraycopy(opad, 0, content, 0, 64);
345         System.arraycopy(data, 0, content, 64, data.length);
346         return md5.digest(content);
347     }
348 
349     /**
350      * Creates a DES encryption key from the given key material.
351      *
352      * @param bytes A byte array containing the DES key material.
353      * @param offset The offset in the given byte array at which
354      * the 7-byte key material starts.
355      *
356      * @return A DES encryption key created from the key material
357      * starting at the specified offset in the given byte array.
358      */
359     private static Key createDESKey(byte[] bytes, int offset) {
360         byte[] keyBytes = new byte[7];
361         System.arraycopy(bytes, offset, keyBytes, 0, 7);
362         byte[] material = new byte[8];
363         material[0] = keyBytes[0];
364         material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
365         material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
366         material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
367         material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
368         material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
369         material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
370         material[7] = (byte) (keyBytes[6] << 1);
371         oddParity(material);
372         return new SecretKeySpec(material, "DES");
373     }
374 
375     /**
376      * Applies odd parity to the given byte array.
377      *
378      * @param bytes The data whose parity bits are to be adjusted for
379      * odd parity.
380      */
381     private static void oddParity(byte[] bytes) {
382         for (int i = 0; i < bytes.length; i++) {
383             byte b = bytes[i];
384             boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0;
385             if (needsParity) {
386                 bytes[i] |= (byte) 0x01;
387             } else {
388                 bytes[i] &= (byte) 0xfe;
389             }
390         }
391     }
392 }