001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 *
019 */
020package org.apache.mina.proxy.handlers.http.ntlm;
021
022import java.security.Key;
023import java.security.MessageDigest;
024
025import javax.crypto.Cipher;
026import javax.crypto.spec.SecretKeySpec;
027
028/**
029 * NTLMResponses.java - Calculates the various Type 3 responses. Needs an MD4,
030 * MD5 and DES crypto provider (Please note that default provider doesn't
031 * provide MD4).
032 * 
033 * Copyright (c) 2003 Eric Glass Permission to use, copy, modify, and distribute
034 * this document for any purpose and without any fee is hereby granted, provided
035 * that the above copyright notice and this list of conditions appear in all
036 * copies.
037 * 
038 * @see <a href="http://curl.haxx.se/rfc/ntlm.html">NTLM RFC</a>
039 * 
040 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
041 * @since MINA 2.0.0-M3
042 */
043public class NTLMResponses {
044
045    // LAN Manager magic constant used in LM Response calculation
046    public static final byte[] LM_HASH_MAGIC_CONSTANT =
047            new byte[]{ 'K', 'G', 'S', '!', '@', '#', '$', '%' };
048
049    /**
050     * Calculates the LM Response for the given challenge, using the specified
051     * password.
052     *
053     * @param password The user's password.
054     * @param challenge The Type 2 challenge from the server.
055     *
056     * @return The LM Response.
057     * @throws Exception If something went wrong
058     */
059    public static byte[] getLMResponse(String password, byte[] challenge) throws Exception {
060        byte[] lmHash = lmHash(password);
061        return lmResponse(lmHash, challenge);
062    }
063
064    /**
065     * Calculates the NTLM Response for the given challenge, using the
066     * specified password.
067     *
068     * @param password The user's password.
069     * @param challenge The Type 2 challenge from the server.
070     *
071     * @return The NTLM Response.
072     * @throws Exception If something went wrong
073     */
074    public static byte[] getNTLMResponse(String password, byte[] challenge) throws Exception {
075        byte[] ntlmHash = ntlmHash(password);
076        return lmResponse(ntlmHash, challenge);
077    }
078
079    /**
080     * Calculates the NTLMv2 Response for the given challenge, using the
081     * specified authentication target, username, password, target information
082     * block, and client nonce.
083     *
084     * @param target The authentication target (i.e., domain).
085     * @param user The username.
086     * @param password The user's password.
087     * @param targetInformation The target information block from the Type 2
088     * message.
089     * @param challenge The Type 2 challenge from the server.
090     * @param clientNonce The random 8-byte client nonce.
091     *
092     * @return The NTLMv2 Response.
093     * @throws Exception If something went wrong
094     */
095    public static byte[] getNTLMv2Response(String target, String user, String password, byte[] targetInformation,
096            byte[] challenge, byte[] clientNonce) throws Exception {
097
098        return getNTLMv2Response(target, user, password, targetInformation, challenge, clientNonce,
099                System.currentTimeMillis());
100    }
101
102    /**
103     * Calculates the NTLMv2 Response for the given challenge, using the
104     * specified authentication target, username, password, target information
105     * block, and client nonce.
106     *
107     * @param target The authentication target (i.e., domain).
108     * @param user The username.
109     * @param password The user's password.
110     * @param targetInformation The target information block from the Type 2
111     * message.
112     * @param challenge The Type 2 challenge from the server.
113     * @param clientNonce The random 8-byte client nonce.
114     * @param time The time stamp.
115     *
116     * @return The NTLMv2 Response.
117     * @throws Exception If something went wrong
118     */
119    public static byte[] getNTLMv2Response(String target, String user, String password, byte[] targetInformation,
120            byte[] challenge, byte[] clientNonce, long time) throws Exception {
121        byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
122        byte[] blob = createBlob(targetInformation, clientNonce, time);
123        return lmv2Response(ntlmv2Hash, blob, challenge);
124    }
125
126    /**
127     * Calculates the LMv2 Response for the given challenge, using the
128     * specified authentication target, username, password, and client
129     * challenge.
130     *
131     * @param target The authentication target (i.e., domain).
132     * @param user The username.
133     * @param password The user's password.
134     * @param challenge The Type 2 challenge from the server.
135     * @param clientNonce The random 8-byte client nonce.
136     *
137     * @return The LMv2 Response.
138     * @throws Exception If something went wrong
139     */
140    public static byte[] getLMv2Response(String target, String user, String password, byte[] challenge,
141            byte[] clientNonce) throws Exception {
142        byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
143        return lmv2Response(ntlmv2Hash, clientNonce, challenge);
144    }
145
146    /**
147     * Calculates the NTLM2 Session Response for the given challenge, using the
148     * specified password and client nonce.
149     *
150     * @param password The user's password.
151     * @param challenge The Type 2 challenge from the server.
152     * @param clientNonce The random 8-byte client nonce.
153     *
154     * @return The NTLM2 Session Response.  This is placed in the NTLM
155     * response field of the Type 3 message; the LM response field contains
156     * the client nonce, null-padded to 24 bytes.
157     * @throws Exception If something went wrong
158     */
159    public static byte[] getNTLM2SessionResponse(String password, byte[] challenge, byte[] clientNonce)
160            throws Exception {
161        byte[] ntlmHash = ntlmHash(password);
162        MessageDigest md5 = MessageDigest.getInstance("MD5");
163        md5.update(challenge);
164        md5.update(clientNonce);
165        byte[] sessionHash = new byte[8];
166        System.arraycopy(md5.digest(), 0, sessionHash, 0, 8);
167        return lmResponse(ntlmHash, sessionHash);
168    }
169
170    /**
171     * Creates the LM Hash of the user's password.
172     *
173     * @param password The password.
174     *
175     * @return The LM Hash of the given password, used in the calculation
176     * of the LM Response.
177     */
178    private static byte[] lmHash(String password) throws Exception {
179        byte[] oemPassword = password.toUpperCase().getBytes("US-ASCII");
180        int length = Math.min(oemPassword.length, 14);
181        byte[] keyBytes = new byte[14];
182        System.arraycopy(oemPassword, 0, keyBytes, 0, length);
183        Key lowKey = createDESKey(keyBytes, 0);
184        Key highKey = createDESKey(keyBytes, 7);
185        Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
186        des.init(Cipher.ENCRYPT_MODE, lowKey);
187        byte[] lowHash = des.doFinal(LM_HASH_MAGIC_CONSTANT);
188        des.init(Cipher.ENCRYPT_MODE, highKey);
189        byte[] highHash = des.doFinal(LM_HASH_MAGIC_CONSTANT);
190        byte[] lmHash = new byte[16];
191        System.arraycopy(lowHash, 0, lmHash, 0, 8);
192        System.arraycopy(highHash, 0, lmHash, 8, 8);
193        return lmHash;
194    }
195
196    /**
197     * Creates the NTLM Hash of the user's password.
198     *
199     * @param password The password.
200     *
201     * @return The NTLM Hash of the given password, used in the calculation
202     * of the NTLM Response and the NTLMv2 and LMv2 Hashes.
203     */
204    private static byte[] ntlmHash(String password) throws Exception {
205        byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
206        MessageDigest md4 = MessageDigest.getInstance("MD4");
207        return md4.digest(unicodePassword);
208    }
209
210    /**
211     * Creates the NTLMv2 Hash of the user's password.
212     *
213     * @param target The authentication target (i.e., domain).
214     * @param user The username.
215     * @param password The password.
216     *
217     * @return The NTLMv2 Hash, used in the calculation of the NTLMv2
218     * and LMv2 Responses.
219     */
220    private static byte[] ntlmv2Hash(String target, String user, String password) throws Exception {
221        byte[] ntlmHash = ntlmHash(password);
222        String identity = user.toUpperCase() + target;
223        return hmacMD5(identity.getBytes("UnicodeLittleUnmarked"), ntlmHash);
224    }
225
226    /**
227     * Creates the LM Response from the given hash and Type 2 challenge.
228     *
229     * @param hash The LM or NTLM Hash.
230     * @param challenge The server challenge from the Type 2 message.
231     *
232     * @return The response (either LM or NTLM, depending on the provided
233     * hash).
234     */
235    private static byte[] lmResponse(byte[] hash, byte[] challenge) throws Exception {
236        byte[] keyBytes = new byte[21];
237        System.arraycopy(hash, 0, keyBytes, 0, 16);
238        Key lowKey = createDESKey(keyBytes, 0);
239        Key middleKey = createDESKey(keyBytes, 7);
240        Key highKey = createDESKey(keyBytes, 14);
241        Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
242        des.init(Cipher.ENCRYPT_MODE, lowKey);
243        byte[] lowResponse = des.doFinal(challenge);
244        des.init(Cipher.ENCRYPT_MODE, middleKey);
245        byte[] middleResponse = des.doFinal(challenge);
246        des.init(Cipher.ENCRYPT_MODE, highKey);
247        byte[] highResponse = des.doFinal(challenge);
248        byte[] lmResponse = new byte[24];
249        System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
250        System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
251        System.arraycopy(highResponse, 0, lmResponse, 16, 8);
252        return lmResponse;
253    }
254
255    /**
256     * Creates the LMv2 Response from the given hash, client data, and
257     * Type 2 challenge.
258     *
259     * @param hash The NTLMv2 Hash.
260     * @param clientData The client data (blob or client nonce).
261     * @param challenge The server challenge from the Type 2 message.
262     *
263     * @return The response (either NTLMv2 or LMv2, depending on the
264     * client data).
265     */
266    private static byte[] lmv2Response(byte[] hash, byte[] clientData, byte[] challenge) throws Exception {
267        byte[] data = new byte[challenge.length + clientData.length];
268        System.arraycopy(challenge, 0, data, 0, challenge.length);
269        System.arraycopy(clientData, 0, data, challenge.length, clientData.length);
270        byte[] mac = hmacMD5(data, hash);
271        byte[] lmv2Response = new byte[mac.length + clientData.length];
272        System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
273        System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length);
274        return lmv2Response;
275    }
276
277    /**
278     * Creates the NTLMv2 blob from the given target information block and
279     * client nonce.
280     *
281     * @param targetInformation The target information block from the Type 2
282     * message.
283     * @param clientNonce The random 8-byte client nonce.
284     * @param time the time stamp.
285     *
286     * @return The blob, used in the calculation of the NTLMv2 Response.
287     */
288    private static byte[] createBlob(byte[] targetInformation, byte[] clientNonce, long time) {
289        byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 };
290        byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
291        byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
292        byte[] unknown2 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
293        time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
294        time *= 10000; // tenths of a microsecond.
295        // convert to little-endian byte array.
296        byte[] timestamp = new byte[8];
297        for (int i = 0; i < 8; i++) {
298            timestamp[i] = (byte) time;
299            time >>>= 8;
300        }
301        byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + clientNonce.length
302                               + unknown1.length + targetInformation.length + unknown2.length];
303        int offset = 0;
304        System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
305        offset += blobSignature.length;
306        System.arraycopy(reserved, 0, blob, offset, reserved.length);
307        offset += reserved.length;
308        System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
309        offset += timestamp.length;
310        System.arraycopy(clientNonce, 0, blob, offset, clientNonce.length);
311        offset += clientNonce.length;
312        System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
313        offset += unknown1.length;
314        System.arraycopy(targetInformation, 0, blob, offset, targetInformation.length);
315        offset += targetInformation.length;
316        System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
317        return blob;
318    }
319
320    /**
321     * Calculates the HMAC-MD5 hash of the given data using the specified
322     * hashing key.
323     *
324     * @param data The data for which the hash will be calculated.
325     * @param key The hashing key.
326     *
327     * @return The HMAC-MD5 hash of the given data.
328     * @throws Exception If something went wrong
329     */
330    public static byte[] hmacMD5(byte[] data, byte[] key) throws Exception {
331        byte[] ipad = new byte[64];
332        byte[] opad = new byte[64];
333
334        // Stores key in pads and XOR it with ipad and opad values
335        for (int i = 0; i < 64; i++) {
336            if (i < key.length) {
337                ipad[i] = (byte) (key[i] ^ 0x36);
338                opad[i] = (byte) (key[i] ^ 0x5c);
339            } else {
340                ipad[i] = 0x36;
341                opad[i] = 0x5c;
342            }
343        }
344
345        byte[] content = new byte[data.length + 64];
346        System.arraycopy(ipad, 0, content, 0, 64);
347        System.arraycopy(data, 0, content, 64, data.length);
348        MessageDigest md5 = MessageDigest.getInstance("MD5");
349        data = md5.digest(content);
350        content = new byte[data.length + 64];
351        System.arraycopy(opad, 0, content, 0, 64);
352        System.arraycopy(data, 0, content, 64, data.length);
353        return md5.digest(content);
354    }
355
356    /**
357     * Creates a DES encryption key from the given key material.
358     *
359     * @param bytes A byte array containing the DES key material.
360     * @param offset The offset in the given byte array at which
361     * the 7-byte key material starts.
362     *
363     * @return A DES encryption key created from the key material
364     * starting at the specified offset in the given byte array.
365     */
366    private static Key createDESKey(byte[] bytes, int offset) {
367        byte[] keyBytes = new byte[7];
368        System.arraycopy(bytes, offset, keyBytes, 0, 7);
369        byte[] material = new byte[8];
370        material[0] = keyBytes[0];
371        material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
372        material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
373        material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
374        material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
375        material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
376        material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
377        material[7] = (byte) (keyBytes[6] << 1);
378        oddParity(material);
379        return new SecretKeySpec(material, "DES");
380    }
381
382    /**
383     * Applies odd parity to the given byte array.
384     *
385     * @param bytes The data whose parity bits are to be adjusted for
386     * odd parity.
387     */
388    private static void oddParity(byte[] bytes) {
389        for (int i = 0; i < bytes.length; i++) {
390            byte b = bytes[i];
391            boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0;
392            if (needsParity) {
393                bytes[i] |= (byte) 0x01;
394            } else {
395                bytes[i] &= (byte) 0xfe;
396            }
397        }
398    }
399}