View Javadoc
1   /*
2    * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
3    * Copyright (C) 2010  Mickael Guessant
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18   */
19  
20  package davmail.http;
21  
22  
23  import org.apache.commons.codec.binary.Base64;
24  import org.apache.http.Consts;
25  import org.apache.http.impl.auth.NTLMEngine;
26  import org.apache.http.impl.auth.NTLMEngineException;
27  import org.apache.log4j.Logger;
28  
29  import javax.crypto.Cipher;
30  import javax.crypto.spec.SecretKeySpec;
31  import java.nio.charset.Charset;
32  import java.nio.charset.StandardCharsets;
33  import java.security.Key;
34  import java.security.MessageDigest;
35  import java.security.NoSuchAlgorithmException;
36  import java.security.SecureRandom;
37  import java.security.cert.Certificate;
38  import java.security.cert.CertificateEncodingException;
39  import java.security.cert.X509Certificate;
40  import java.util.Arrays;
41  import java.util.Locale;
42  
43  /**
44   * Provides an implementation for NTLMv1, NTLMv2, and NTLM2 Session forms of the NTLM
45   * authentication protocol.
46   * Duplicate code from NTLMEngineImpl to implement channel binding
47   */
48  @SuppressWarnings("unused")
49  final class DavMailNTLMEngineImpl implements NTLMEngine {
50  
51      static final Logger LOGGER = Logger.getLogger("davmail.http.DavMailNTLMEngineImpl");
52  
53      /** Unicode encoding */
54      private static final Charset UNICODE_LITTLE_UNMARKED = StandardCharsets.UTF_16LE;
55      /** Character encoding */
56      private static final Charset DEFAULT_CHARSET = Consts.ASCII;
57  
58      // Flags we use; descriptions according to:
59      // http://davenport.sourceforge.net/ntlm.html
60      // and
61      // http://msdn.microsoft.com/en-us/library/cc236650%28v=prot.20%29.aspx
62      // [MS-NLMP] section 2.2.2.5
63      static final int FLAG_REQUEST_UNICODE_ENCODING = 0x00000001;      // Unicode string encoding requested
64      static final int FLAG_REQUEST_OEM_ENCODING = 0x00000002;      // OEM string encoding requested
65      static final int FLAG_REQUEST_TARGET = 0x00000004;                      // Requests target field
66      static final int FLAG_REQUEST_SIGN = 0x00000010;  // Requests all messages have a signature attached, in NEGOTIATE message.
67      static final int FLAG_REQUEST_SEAL = 0x00000020;  // Request key exchange for message confidentiality in NEGOTIATE message.  MUST be used in conjunction with 56BIT.
68      static final int FLAG_REQUEST_LAN_MANAGER_KEY = 0x00000080;    // Request Lan Manager key instead of user session key
69      static final int FLAG_REQUEST_NTLMv1 = 0x00000200; // Request NTLMv1 security.  MUST be set in NEGOTIATE and CHALLENGE both
70      static final int FLAG_DOMAIN_PRESENT = 0x00001000;        // Domain is present in message
71      static final int FLAG_WORKSTATION_PRESENT = 0x00002000;   // Workstation is present in message
72      static final int FLAG_REQUEST_ALWAYS_SIGN = 0x00008000;   // Requests a signature block on all messages.  Overridden by REQUEST_SIGN and REQUEST_SEAL.
73      static final int FLAG_REQUEST_NTLM2_SESSION = 0x00080000; // From server in challenge, requesting NTLM2 session security
74      static final int FLAG_REQUEST_VERSION = 0x02000000;       // Request protocol version
75      static final int FLAG_TARGETINFO_PRESENT = 0x00800000;    // From server in challenge message, indicating targetinfo is present
76      static final int FLAG_REQUEST_128BIT_KEY_EXCH = 0x20000000; // Request explicit 128-bit key exchange
77      static final int FLAG_REQUEST_EXPLICIT_KEY_EXCH = 0x40000000;     // Request explicit key exchange
78      static final int FLAG_REQUEST_56BIT_ENCRYPTION = 0x80000000;      // Must be used in conjunction with SEAL
79  
80      // Attribute-value identifiers (AvId)
81      // according to [MS-NLMP] section 2.2.2.1
82      static final int MSV_AV_EOL = 0x0000; // Indicates that this is the last AV_PAIR in the list.
83      static final int MSV_AV_NB_COMPUTER_NAME = 0x0001; // The server's NetBIOS computer name.
84      static final int MSV_AV_NB_DOMAIN_NAME = 0x0002; // The server's NetBIOS domain name.
85      static final int MSV_AV_DNS_COMPUTER_NAME = 0x0003; // The fully qualified domain name (FQDN) of the computer.
86      static final int MSV_AV_DNS_DOMAIN_NAME = 0x0004; // The FQDN of the domain.
87      static final int MSV_AV_DNS_TREE_NAME = 0x0005; // The FQDN of the forest.
88      static final int MSV_AV_FLAGS = 0x0006; // A 32-bit value indicating server or client configuration.
89      static final int MSV_AV_TIMESTAMP = 0x0007; // server local time
90      static final int MSV_AV_SINGLE_HOST = 0x0008; // A Single_Host_Data structure.
91      static final int MSV_AV_TARGET_NAME = 0x0009; // The SPN of the target server.
92      static final int MSV_AV_CHANNEL_BINDINGS = 0x000A; // A channel bindings hash.
93  
94      static final int MSV_AV_FLAGS_ACCOUNT_AUTH_CONSTAINED = 0x00000001; // Indicates to the client that the account authentication is constrained.
95      static final int MSV_AV_FLAGS_MIC = 0x00000002; // Indicates that the client is providing message integrity in the MIC field in the AUTHENTICATE_MESSAGE.
96      static final int MSV_AV_FLAGS_UNTRUSTED_TARGET_SPN = 0x00000004; // Indicates that the client is providing a target SPN generated from an untrusted source.
97  
98      private static final SecureRandom RNG;
99  
100     static {
101         try {
102             RNG = java.security.SecureRandom.getInstance("SHA1PRNG");
103         } catch (final NoSuchAlgorithmException e) {
104             throw new RuntimeException(e.getMessage(), e);
105         }
106     }
107 
108     /** The signature string as bytes in the default encoding */
109     private static final byte[] SIGNATURE = getNullTerminatedAsciiString("NTLMSSP");
110 
111     // prefix for GSS API channel binding
112     private static final byte[] MAGIC_TLS_SERVER_ENDPOINT = "tls-server-end-point:".getBytes(Consts.ASCII);
113 
114     private static byte[] getNullTerminatedAsciiString(final String source) {
115         final byte[] bytesWithoutNull = source.getBytes(Consts.ASCII);
116         final byte[] target = new byte[bytesWithoutNull.length + 1];
117         System.arraycopy(bytesWithoutNull, 0, target, 0, bytesWithoutNull.length);
118         target[bytesWithoutNull.length] = (byte) 0x00;
119         return target;
120     }
121 
122     private static final String TYPE_1_MESSAGE = new DavMailNTLMEngineImpl.Type1Message().getResponse();
123 
124     Certificate peerServerCertificate = null;
125 
126     DavMailNTLMEngineImpl() {
127     }
128 
129     /**
130      * Store connection certificate for channel binding implementation.
131      * @param peerServerCertificate certificate
132      */
133     public void setPeerServerCertificate(Certificate peerServerCertificate) {
134         this.peerServerCertificate = peerServerCertificate;
135     }
136 
137     /**
138      * Creates the first message (type 1 message) in the NTLM authentication
139      * sequence. This message includes the user name, domain and host for the
140      * authentication session.
141      *
142      * @param host
143      *            the computer name of the host requesting authentication.
144      * @param domain
145      *            The domain to authenticate with.
146      * @return String the message to add to the HTTP request header.
147      */
148     static String getType1Message(final String host, final String domain) {
149         // For compatibility reason do not include domain and host in type 1 message
150         return TYPE_1_MESSAGE;
151     }
152 
153     /**
154      * Creates the type 3 message using the given server nonce. The type 3
155      * message includes all the information for authentication, host, domain,
156      * username and the result of encrypting the nonce sent by the server using
157      * the user's password as the key.
158      *
159      * @param user
160      *            The user name. This should not include the domain name.
161      * @param password
162      *            The password.
163      * @param host
164      *            The host that is originating the authentication request.
165      * @param domain
166      *            The domain to authenticate within.
167      * @param nonce
168      *            the 8 byte array the server sent.
169      * @return The type 3 message.
170      * @throws NTLMEngineException
171      *             If {link #Type3Message(String, String, String, String, byte[], int, String, byte[])} fails.
172      */
173     static String getType3Message(final String user, final String password, final String host, final String domain,
174                                   final byte[] nonce, final int type2Flags, final String target, final byte[] targetInformation)
175             throws NTLMEngineException {
176         return new DavMailNTLMEngineImpl.Type3Message(domain, host, user, password, nonce, type2Flags, target,
177                 targetInformation).getResponse();
178     }
179 
180     /**
181      * Creates the type 3 message using the given server nonce. The type 3
182      * message includes all the information for authentication, host, domain,
183      * username and the result of encrypting the nonce sent by the server using
184      * the user's password as the key.
185      *
186      * @param user
187      *            The user name. This should not include the domain name.
188      * @param password
189      *            The password.
190      * @param host
191      *            The host that is originating the authentication request.
192      * @param domain
193      *            The domain to authenticate within.
194      * @param nonce
195      *            the 8 byte array the server sent.
196      * @return The type 3 message.
197      * @throws NTLMEngineException
198      *             If {link #Type3Message(String, String, String, String, byte[], int, String, byte[], Certificate, byte[], byte[])} fails.
199      */
200     static String getType3Message(final String user, final String password, final String host, final String domain,
201                                   final byte[] nonce, final int type2Flags, final String target, final byte[] targetInformation,
202                                   final Certificate peerServerCertificate, final byte[] type1Message, final byte[] type2Message)
203             throws NTLMEngineException {
204         return new Type3Message(domain, host, user, password, nonce, type2Flags, target,
205                 targetInformation, peerServerCertificate, type1Message, type2Message).getResponse();
206     }
207 
208     private static int readULong(final byte[] src, final int index) {
209         if (src.length < index + 4) {
210             return 0;
211         }
212         return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8)
213                 | ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24);
214     }
215 
216     private static int readUShort(final byte[] src, final int index) {
217         if (src.length < index + 2) {
218             return 0;
219         }
220         return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8);
221     }
222 
223     private static byte[] readSecurityBuffer(final byte[] src, final int index) {
224         final int length = readUShort(src, index);
225         final int offset = readULong(src, index + 4);
226         if (src.length < offset + length) {
227             return new byte[length];
228         }
229         final byte[] buffer = new byte[length];
230         System.arraycopy(src, offset, buffer, 0, length);
231         return buffer;
232     }
233 
234     /** Calculate a challenge block */
235     private static byte[] makeRandomChallenge() {
236         final byte[] rval = new byte[8];
237         RNG.nextBytes(rval);
238         return rval;
239     }
240 
241     /** Calculate a 16-byte secondary key */
242     private static byte[] makeSecondaryKey() {
243         final byte[] rval = new byte[16];
244         RNG.nextBytes(rval);
245         return rval;
246     }
247 
248     protected static class CipherGen {
249 
250         protected final long currentTime;
251 
252         protected final String domain;
253         protected final String user;
254         protected final String password;
255         protected final byte[] challenge;
256         protected final String target;
257         protected final byte[] targetInformation;
258 
259         // Information we can generate but may be passed in (for testing)
260         protected byte[] clientChallenge;
261         protected byte[] clientChallenge2;
262         protected byte[] secondaryKey;
263         protected byte[] timestamp;
264 
265         // Stuff we always generate
266         protected byte[] lmHash = null;
267         protected byte[] lmResponse = null;
268         protected byte[] ntlmHash = null;
269         protected byte[] ntlmResponse = null;
270         protected byte[] ntlmv2Hash = null;
271         protected byte[] lmv2Hash = null;
272         protected byte[] lmv2Response = null;
273         protected byte[] ntlmv2Blob = null;
274         protected byte[] ntlmv2Response = null;
275         protected byte[] ntlm2SessionResponse = null;
276         protected byte[] lm2SessionResponse = null;
277         protected byte[] lmUserSessionKey = null;
278         protected byte[] ntlmUserSessionKey = null;
279         protected byte[] ntlmv2UserSessionKey = null;
280         protected byte[] ntlm2SessionResponseUserSessionKey = null;
281         protected byte[] lanManagerSessionKey = null;
282 
283         public CipherGen(final long currentTime,
284                          final String domain, final String user, final String password,
285                          final byte[] challenge, final String target, final byte[] targetInformation,
286                          final byte[] clientChallenge, final byte[] clientChallenge2,
287                          final byte[] secondaryKey, final byte[] timestamp) {
288             this.currentTime = currentTime;
289 
290             this.domain = domain;
291             this.target = target;
292             this.user = user;
293             this.password = password;
294             this.challenge = challenge;
295             this.targetInformation = targetInformation;
296             this.clientChallenge = clientChallenge;
297             this.clientChallenge2 = clientChallenge2;
298             this.secondaryKey = secondaryKey;
299             this.timestamp = timestamp;
300         }
301 
302         public CipherGen(final long currentTime,
303                          final String domain,
304                          final String user,
305                          final String password,
306                          final byte[] challenge,
307                          final String target,
308                          final byte[] targetInformation) {
309             this(currentTime, domain, user, password, challenge, target, targetInformation, null, null, null, null);
310         }
311 
312         /** Calculate and return client challenge */
313         public byte[] getClientChallenge() {
314             if (clientChallenge == null) {
315                 clientChallenge = makeRandomChallenge();
316             }
317             return clientChallenge;
318         }
319 
320         /** Calculate and return second client challenge */
321         public byte[] getClientChallenge2() {
322             if (clientChallenge2 == null) {
323                 clientChallenge2 = makeRandomChallenge();
324             }
325             return clientChallenge2;
326         }
327 
328         /** Calculate and return random secondary key */
329         public byte[] getSecondaryKey() {
330             if (secondaryKey == null) {
331                 secondaryKey = makeSecondaryKey();
332             }
333             return secondaryKey;
334         }
335 
336         /** Calculate and return the LMHash */
337         public byte[] getLMHash()
338                 throws NTLMEngineException {
339             if (lmHash == null) {
340                 lmHash = lmHash(password);
341             }
342             return lmHash;
343         }
344 
345         /** Calculate and return the LMResponse */
346         public byte[] getLMResponse()
347                 throws NTLMEngineException {
348             if (lmResponse == null) {
349                 lmResponse = lmResponse(getLMHash(), challenge);
350             }
351             return lmResponse;
352         }
353 
354         /** Calculate and return the NTLMHash */
355         public byte[] getNTLMHash() {
356             if (ntlmHash == null) {
357                 ntlmHash = ntlmHash(password);
358             }
359             return ntlmHash;
360         }
361 
362         /** Calculate and return the NTLMResponse */
363         public byte[] getNTLMResponse()
364                 throws NTLMEngineException {
365             if (ntlmResponse == null) {
366                 ntlmResponse = lmResponse(getNTLMHash(), challenge);
367             }
368             return ntlmResponse;
369         }
370 
371         /** Calculate the LMv2 hash */
372         public byte[] getLMv2Hash()
373                 throws NTLMEngineException {
374             if (lmv2Hash == null) {
375                 lmv2Hash = lmv2Hash(domain, user, getNTLMHash());
376             }
377             return lmv2Hash;
378         }
379 
380         /** Calculate the NTLMv2 hash */
381         public byte[] getNTLMv2Hash()
382                 throws NTLMEngineException {
383             if (ntlmv2Hash == null) {
384                 ntlmv2Hash = ntlmv2Hash(domain, user, getNTLMHash());
385             }
386             return ntlmv2Hash;
387         }
388 
389         /** Calculate a timestamp */
390         public byte[] getTimestamp() {
391             if (timestamp == null) {
392                 long time = this.currentTime;
393                 time += 11644473600000L; // milliseconds from January 1, 1601 -> epoch.
394                 time *= 10000; // tenths of a microsecond.
395                 // convert to little-endian byte array.
396                 timestamp = new byte[8];
397                 for (int i = 0; i < 8; i++) {
398                     timestamp[i] = (byte) time;
399                     time >>>= 8;
400                 }
401             }
402             return timestamp;
403         }
404 
405         /** Calculate the NTLMv2Blob */
406         public byte[] getNTLMv2Blob() {
407             if (ntlmv2Blob == null) {
408                 ntlmv2Blob = createBlob(getClientChallenge2(), targetInformation, getTimestamp());
409             }
410             return ntlmv2Blob;
411         }
412 
413         /** Calculate the NTLMv2Response */
414         public byte[] getNTLMv2Response()
415                 throws NTLMEngineException {
416             if (ntlmv2Response == null) {
417                 ntlmv2Response = lmv2Response(getNTLMv2Hash(), challenge, getNTLMv2Blob());
418             }
419             return ntlmv2Response;
420         }
421 
422         /** Calculate the LMv2Response */
423         public byte[] getLMv2Response()
424                 throws NTLMEngineException {
425             if (lmv2Response == null) {
426                 lmv2Response = lmv2Response(getLMv2Hash(), challenge, getClientChallenge());
427             }
428             return lmv2Response;
429         }
430 
431         /** Get NTLM2SessionResponse */
432         public byte[] getNTLM2SessionResponse()
433                 throws NTLMEngineException {
434             if (ntlm2SessionResponse == null) {
435                 ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(), challenge, getClientChallenge());
436             }
437             return ntlm2SessionResponse;
438         }
439 
440         /** Calculate and return LM2 session response */
441         public byte[] getLM2SessionResponse() {
442             if (lm2SessionResponse == null) {
443                 final byte[] clntChallenge = getClientChallenge();
444                 lm2SessionResponse = new byte[24];
445                 System.arraycopy(clntChallenge, 0, lm2SessionResponse, 0, clntChallenge.length);
446                 Arrays.fill(lm2SessionResponse, clntChallenge.length, lm2SessionResponse.length, (byte) 0x00);
447             }
448             return lm2SessionResponse;
449         }
450 
451         /** Get LMUserSessionKey */
452         public byte[] getLMUserSessionKey()
453                 throws NTLMEngineException {
454             if (lmUserSessionKey == null) {
455                 lmUserSessionKey = new byte[16];
456                 System.arraycopy(getLMHash(), 0, lmUserSessionKey, 0, 8);
457                 Arrays.fill(lmUserSessionKey, 8, 16, (byte) 0x00);
458             }
459             return lmUserSessionKey;
460         }
461 
462         /** Get NTLMUserSessionKey */
463         public byte[] getNTLMUserSessionKey()
464                 throws NTLMEngineException {
465             if (ntlmUserSessionKey == null) {
466                 final DavMailNTLMEngineImpl.MD4 md4 = new DavMailNTLMEngineImpl.MD4();
467                 md4.update(getNTLMHash());
468                 ntlmUserSessionKey = md4.getOutput();
469             }
470             return ntlmUserSessionKey;
471         }
472 
473         /** GetNTLMv2UserSessionKey */
474         public byte[] getNTLMv2UserSessionKey()
475                 throws NTLMEngineException {
476             if (ntlmv2UserSessionKey == null) {
477                 final byte[] ntlmv2hash = getNTLMv2Hash();
478                 final byte[] truncatedResponse = new byte[16];
479                 System.arraycopy(getNTLMv2Response(), 0, truncatedResponse, 0, 16);
480                 ntlmv2UserSessionKey = hmacMD5(truncatedResponse, ntlmv2hash);
481             }
482             return ntlmv2UserSessionKey;
483         }
484 
485         /** Get NTLM2SessionResponseUserSessionKey */
486         public byte[] getNTLM2SessionResponseUserSessionKey()
487                 throws NTLMEngineException {
488             if (ntlm2SessionResponseUserSessionKey == null) {
489                 final byte[] ntlm2SessionResponseNonce = getLM2SessionResponse();
490                 final byte[] sessionNonce = new byte[challenge.length + ntlm2SessionResponseNonce.length];
491                 System.arraycopy(challenge, 0, sessionNonce, 0, challenge.length);
492                 System.arraycopy(ntlm2SessionResponseNonce, 0, sessionNonce, challenge.length, ntlm2SessionResponseNonce.length);
493                 ntlm2SessionResponseUserSessionKey = hmacMD5(sessionNonce, getNTLMUserSessionKey());
494             }
495             return ntlm2SessionResponseUserSessionKey;
496         }
497 
498         /** Get LAN Manager session key */
499         public byte[] getLanManagerSessionKey()
500                 throws NTLMEngineException {
501             if (lanManagerSessionKey == null) {
502                 try {
503                     final byte[] keyBytes = new byte[14];
504                     System.arraycopy(getLMHash(), 0, keyBytes, 0, 8);
505                     Arrays.fill(keyBytes, 8, keyBytes.length, (byte) 0xbd);
506                     final Key lowKey = createDESKey(keyBytes, 0);
507                     final Key highKey = createDESKey(keyBytes, 7);
508                     final byte[] truncatedResponse = new byte[8];
509                     System.arraycopy(getLMResponse(), 0, truncatedResponse, 0, truncatedResponse.length);
510                     Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
511                     des.init(Cipher.ENCRYPT_MODE, lowKey);
512                     final byte[] lowPart = des.doFinal(truncatedResponse);
513                     des = Cipher.getInstance("DES/ECB/NoPadding");
514                     des.init(Cipher.ENCRYPT_MODE, highKey);
515                     final byte[] highPart = des.doFinal(truncatedResponse);
516                     lanManagerSessionKey = new byte[16];
517                     System.arraycopy(lowPart, 0, lanManagerSessionKey, 0, lowPart.length);
518                     System.arraycopy(highPart, 0, lanManagerSessionKey, lowPart.length, highPart.length);
519                 } catch (final Exception e) {
520                     throw new NTLMEngineException(e.getMessage(), e);
521                 }
522             }
523             return lanManagerSessionKey;
524         }
525     }
526 
527     /** Calculates HMAC-MD5 */
528     static byte[] hmacMD5(final byte[] value, final byte[] key) {
529         final DavMailNTLMEngineImpl.HMACMD5 hmacMD5 = new DavMailNTLMEngineImpl.HMACMD5(key);
530         hmacMD5.update(value);
531         return hmacMD5.getOutput();
532     }
533 
534     /** Calculates RC4 */
535     static byte[] RC4(final byte[] value, final byte[] key)
536             throws NTLMEngineException {
537         try {
538             final Cipher rc4 = Cipher.getInstance("RC4");
539             rc4.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "RC4"));
540             return rc4.doFinal(value);
541         } catch (final Exception e) {
542             throw new NTLMEngineException(e.getMessage(), e);
543         }
544     }
545 
546     /**
547      * Calculates the NTLM2 Session Response for the given challenge, using the
548      * specified password and client challenge.
549      *
550      * @return The NTLM2 Session Response. This is placed in the NTLM response
551      *         field of the Type 3 message; the LM response field contains the
552      *         client challenge, null-padded to 24 bytes.
553      */
554     static byte[] ntlm2SessionResponse(final byte[] ntlmHash, final byte[] challenge,
555                                        final byte[] clientChallenge) throws NTLMEngineException {
556         try {
557             final MessageDigest md5 = getMD5();
558             md5.update(challenge);
559             md5.update(clientChallenge);
560             final byte[] digest = md5.digest();
561 
562             final byte[] sessionHash = new byte[8];
563             System.arraycopy(digest, 0, sessionHash, 0, 8);
564             return lmResponse(ntlmHash, sessionHash);
565         } catch (final NTLMEngineException e) {
566             throw e;
567         } catch (final Exception e) {
568             throw new NTLMEngineException(e.getMessage(), e);
569         }
570     }
571 
572     /**
573      * Creates the LM Hash of the user's password.
574      *
575      * @param password
576      *            The password.
577      *
578      * @return The LM Hash of the given password, used in the calculation of the
579      *         LM Response.
580      */
581     private static byte[] lmHash(final String password) throws NTLMEngineException {
582         try {
583             final byte[] oemPassword = password.toUpperCase(Locale.ROOT).getBytes(Consts.ASCII);
584             final int length = Math.min(oemPassword.length, 14);
585             final byte[] keyBytes = new byte[14];
586             System.arraycopy(oemPassword, 0, keyBytes, 0, length);
587             final Key lowKey = createDESKey(keyBytes, 0);
588             final Key highKey = createDESKey(keyBytes, 7);
589             final byte[] magicConstant = "KGS!@#$%".getBytes(Consts.ASCII);
590             final Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
591             des.init(Cipher.ENCRYPT_MODE, lowKey);
592             final byte[] lowHash = des.doFinal(magicConstant);
593             des.init(Cipher.ENCRYPT_MODE, highKey);
594             final byte[] highHash = des.doFinal(magicConstant);
595             final byte[] lmHash = new byte[16];
596             System.arraycopy(lowHash, 0, lmHash, 0, 8);
597             System.arraycopy(highHash, 0, lmHash, 8, 8);
598             return lmHash;
599         } catch (final Exception e) {
600             throw new NTLMEngineException(e.getMessage(), e);
601         }
602     }
603 
604     /**
605      * Creates the NTLM Hash of the user's password.
606      *
607      * @param password
608      *            The password.
609      *
610      * @return The NTLM Hash of the given password, used in the calculation of
611      *         the NTLM Response and the NTLMv2 and LMv2 Hashes.
612      */
613     private static byte[] ntlmHash(final String password) {
614         final byte[] unicodePassword = password.getBytes(UNICODE_LITTLE_UNMARKED);
615         final DavMailNTLMEngineImpl.MD4 md4 = new DavMailNTLMEngineImpl.MD4();
616         md4.update(unicodePassword);
617         return md4.getOutput();
618     }
619 
620     /**
621      * Creates the LMv2 Hash of the user's password.
622      *
623      * @return The LMv2 Hash, used in the calculation of the NTLMv2 and LMv2
624      *         Responses.
625      */
626     private static byte[] lmv2Hash(final String domain, final String user, final byte[] ntlmHash)
627             throws NTLMEngineException {
628         final DavMailNTLMEngineImpl.HMACMD5 hmacMD5 = new DavMailNTLMEngineImpl.HMACMD5(ntlmHash);
629         // Upper case username, upper case domain!
630         hmacMD5.update(user.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED));
631         if (domain != null) {
632             hmacMD5.update(domain.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED));
633         }
634         return hmacMD5.getOutput();
635     }
636 
637     /**
638      * Creates the NTLMv2 Hash of the user's password.
639      *
640      * @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2
641      *         Responses.
642      */
643     private static byte[] ntlmv2Hash(final String domain, final String user, final byte[] ntlmHash) {
644         final DavMailNTLMEngineImpl.HMACMD5 hmacMD5 = new DavMailNTLMEngineImpl.HMACMD5(ntlmHash);
645         // Upper case username, mixed case target!!
646         hmacMD5.update(user.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED));
647         if (domain != null) {
648             hmacMD5.update(domain.getBytes(UNICODE_LITTLE_UNMARKED));
649         }
650         return hmacMD5.getOutput();
651     }
652 
653     /**
654      * Creates the LM Response from the given hash and Type 2 challenge.
655      *
656      * @param hash
657      *            The LM or NTLM Hash.
658      * @param challenge
659      *            The server challenge from the Type 2 message.
660      *
661      * @return The response (either LM or NTLM, depending on the provided hash).
662      */
663     private static byte[] lmResponse(final byte[] hash, final byte[] challenge) throws NTLMEngineException {
664         try {
665             final byte[] keyBytes = new byte[21];
666             System.arraycopy(hash, 0, keyBytes, 0, 16);
667             final Key lowKey = createDESKey(keyBytes, 0);
668             final Key middleKey = createDESKey(keyBytes, 7);
669             final Key highKey = createDESKey(keyBytes, 14);
670             final Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
671             des.init(Cipher.ENCRYPT_MODE, lowKey);
672             final byte[] lowResponse = des.doFinal(challenge);
673             des.init(Cipher.ENCRYPT_MODE, middleKey);
674             final byte[] middleResponse = des.doFinal(challenge);
675             des.init(Cipher.ENCRYPT_MODE, highKey);
676             final byte[] highResponse = des.doFinal(challenge);
677             final byte[] lmResponse = new byte[24];
678             System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
679             System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
680             System.arraycopy(highResponse, 0, lmResponse, 16, 8);
681             return lmResponse;
682         } catch (final Exception e) {
683             throw new NTLMEngineException(e.getMessage(), e);
684         }
685     }
686 
687     /**
688      * Creates the LMv2 Response from the given hash, client data, and Type 2
689      * challenge.
690      *
691      * @param hash
692      *            The NTLMv2 Hash.
693      * @param clientData
694      *            The client data (blob or client challenge).
695      * @param challenge
696      *            The server challenge from the Type 2 message.
697      *
698      * @return The response (either NTLMv2 or LMv2, depending on the client
699      *         data).
700      */
701     private static byte[] lmv2Response(final byte[] hash, final byte[] challenge, final byte[] clientData) {
702         final DavMailNTLMEngineImpl.HMACMD5 hmacMD5 = new DavMailNTLMEngineImpl.HMACMD5(hash);
703         hmacMD5.update(challenge);
704         hmacMD5.update(clientData);
705         final byte[] mac = hmacMD5.getOutput();
706         final byte[] lmv2Response = new byte[mac.length + clientData.length];
707         System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
708         System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length);
709         return lmv2Response;
710     }
711 
712     private static byte[] encodeLong(final int value) {
713         final byte[] enc = new byte[4];
714         encodeLong(enc, 0, value);
715         return enc;
716     }
717 
718     private static void encodeLong(final byte[] buf, final int offset, final int value) {
719         buf[offset    ] = (byte) (value & 0xff);
720         buf[offset + 1] = (byte) (value >> 8 & 0xff);
721         buf[offset + 2] = (byte) (value >> 16 & 0xff);
722         buf[offset + 3] = (byte) (value >> 24 & 0xff);
723     }
724 
725     /**
726      * Creates the NTLMv2 blob from the given target information block and
727      * client challenge.
728      *
729      * @param targetInformation
730      *            The target information block from the Type 2 message.
731      * @param clientChallenge
732      *            The random 8-byte client challenge.
733      *
734      * @return The blob, used in the calculation of the NTLMv2 Response.
735      */
736     private static byte[] createBlob(final byte[] clientChallenge, final byte[] targetInformation, final byte[] timestamp) {
737         final byte[] blobSignature = new byte[]{(byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00};
738         final byte[] reserved = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
739         final byte[] unknown1 = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
740         final byte[] unknown2 = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
741         final byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + 8
742                 + unknown1.length + targetInformation.length + unknown2.length];
743         int offset = 0;
744         System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
745         offset += blobSignature.length;
746         System.arraycopy(reserved, 0, blob, offset, reserved.length);
747         offset += reserved.length;
748         System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
749         offset += timestamp.length;
750         System.arraycopy(clientChallenge, 0, blob, offset, 8);
751         offset += 8;
752         System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
753         offset += unknown1.length;
754         System.arraycopy(targetInformation, 0, blob, offset, targetInformation.length);
755         offset += targetInformation.length;
756         System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
757         offset += unknown2.length;
758         return blob;
759     }
760 
761     /**
762      * Creates a DES encryption key from the given key material.
763      *
764      * @param bytes
765      *            A byte array containing the DES key material.
766      * @param offset
767      *            The offset in the given byte array at which the 7-byte key
768      *            material starts.
769      *
770      * @return A DES encryption key created from the key material starting at
771      *         the specified offset in the given byte array.
772      */
773     private static Key createDESKey(final byte[] bytes, final int offset) {
774         final byte[] keyBytes = new byte[7];
775         System.arraycopy(bytes, offset, keyBytes, 0, 7);
776         final byte[] material = new byte[8];
777         material[0] = keyBytes[0];
778         material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
779         material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
780         material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
781         material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
782         material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
783         material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
784         material[7] = (byte) (keyBytes[6] << 1);
785         oddParity(material);
786         return new SecretKeySpec(material, "DES");
787     }
788 
789     /**
790      * Applies odd parity to the given byte array.
791      *
792      * @param bytes
793      *            The data whose parity bits are to be adjusted for odd parity.
794      */
795     private static void oddParity(final byte[] bytes) {
796         for (int i = 0; i < bytes.length; i++) {
797             final byte b = bytes[i];
798             final boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3)
799                     ^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0;
800             if (needsParity) {
801                 bytes[i] |= (byte) 0x01;
802             } else {
803                 bytes[i] &= (byte) 0xfe;
804             }
805         }
806     }
807 
808     /**
809      * Find the character set based on the flags.
810      * @param flags is the flags.
811      * @return the character set.
812      */
813     private static Charset getCharset(final int flags) {
814         if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0) {
815             return DEFAULT_CHARSET;
816         }
817         return UNICODE_LITTLE_UNMARKED;
818     }
819 
820     /** Strip dot suffix from a name */
821     private static String stripDotSuffix(final String value) {
822         if (value == null) {
823             return null;
824         }
825         final int index = value.indexOf('.');
826         if (index != -1) {
827             return value.substring(0, index);
828         }
829         return value;
830     }
831 
832     /** Convert host to standard form */
833     private static String convertHost(final String host) {
834         return stripDotSuffix(host);
835     }
836 
837     /** Convert domain to standard form */
838     private static String convertDomain(final String domain) {
839         return stripDotSuffix(domain);
840     }
841 
842     /** NTLM message generation, base class */
843     static class NTLMMessage {
844         /** The current response */
845         protected byte[] messageContents = null;
846 
847         /** The current output position */
848         protected int currentOutputPosition = 0;
849 
850         /** Constructor to use when message contents are not yet known */
851         NTLMMessage() {
852         }
853 
854         /** Constructor taking a string */
855         NTLMMessage(final String messageBody, final int expectedType) throws NTLMEngineException {
856             this(Base64.decodeBase64(messageBody.getBytes(DEFAULT_CHARSET)), expectedType);
857         }
858 
859         /** Constructor to use when message bytes are known */
860         NTLMMessage(final byte[] message, final int expectedType) throws NTLMEngineException {
861             messageContents = message;
862             // Look for NTLM message
863             if (messageContents.length < SIGNATURE.length) {
864                 throw new NTLMEngineException("NTLM message decoding error - packet too short");
865             }
866             int i = 0;
867             while (i < SIGNATURE.length) {
868                 if (messageContents[i] != SIGNATURE[i]) {
869                     throw new NTLMEngineException(
870                             "NTLM message expected - instead got unrecognized bytes");
871                 }
872                 i++;
873             }
874 
875             // Check to be sure there's a type 2 message indicator next
876             final int type = readULong(SIGNATURE.length);
877             if (type != expectedType) {
878                 throw new NTLMEngineException("NTLM type " + expectedType
879                         + " message expected - instead got type " + type);
880             }
881 
882             currentOutputPosition = messageContents.length;
883         }
884 
885         /**
886          * Get the length of the signature and flags, so calculations can adjust
887          * offsets accordingly.
888          */
889         protected int getPreambleLength() {
890             return SIGNATURE.length + 4;
891         }
892 
893         /** Get the message length */
894         protected int getMessageLength() {
895             return currentOutputPosition;
896         }
897 
898         /** Read a byte from a position within the message buffer */
899         protected byte readByte(final int position) throws NTLMEngineException {
900             if (messageContents.length < position + 1) {
901                 throw new NTLMEngineException("NTLM: Message too short");
902             }
903             return messageContents[position];
904         }
905 
906         /** Read a bunch of bytes from a position in the message buffer */
907         protected void readBytes(final byte[] buffer, final int position) throws NTLMEngineException {
908             if (messageContents.length < position + buffer.length) {
909                 throw new NTLMEngineException("NTLM: Message too short");
910             }
911             System.arraycopy(messageContents, position, buffer, 0, buffer.length);
912         }
913 
914         /** Read a ushort from a position within the message buffer */
915         protected int readUShort(final int position) {
916             return DavMailNTLMEngineImpl.readUShort(messageContents, position);
917         }
918 
919         /** Read a ulong from a position within the message buffer */
920         protected int readULong(final int position) {
921             return DavMailNTLMEngineImpl.readULong(messageContents, position);
922         }
923 
924         /** Read a security buffer from a position within the message buffer */
925         protected byte[] readSecurityBuffer(final int position) {
926             return DavMailNTLMEngineImpl.readSecurityBuffer(messageContents, position);
927         }
928 
929         /**
930          * Prepares the object to create a response of the given length.
931          *
932          * @param maxlength
933          *            the maximum length of the response to prepare,
934          *            including the type and the signature (which this method
935          *            adds).
936          */
937         protected void prepareResponse(final int maxlength, final int messageType) {
938             messageContents = new byte[maxlength];
939             currentOutputPosition = 0;
940             addBytes(SIGNATURE);
941             addULong(messageType);
942         }
943 
944         /**
945          * Adds the given byte to the response.
946          *
947          * @param b
948          *            the byte to add.
949          */
950         protected void addByte(final byte b) {
951             messageContents[currentOutputPosition] = b;
952             currentOutputPosition++;
953         }
954 
955         /**
956          * Adds the given bytes to the response.
957          *
958          * @param bytes
959          *            the bytes to add.
960          */
961         protected void addBytes(final byte[] bytes) {
962             if (bytes == null) {
963                 return;
964             }
965             for (final byte b : bytes) {
966                 messageContents[currentOutputPosition] = b;
967                 currentOutputPosition++;
968             }
969         }
970 
971         /** Adds a USHORT to the response */
972         protected void addUShort(final int value) {
973             addByte((byte) (value & 0xff));
974             addByte((byte) (value >> 8 & 0xff));
975         }
976 
977         /** Adds a ULong to the response */
978         protected void addULong(final int value) {
979             addByte((byte) (value & 0xff));
980             addByte((byte) (value >> 8 & 0xff));
981             addByte((byte) (value >> 16 & 0xff));
982             addByte((byte) (value >> 24 & 0xff));
983         }
984 
985         /**
986          * Returns the response that has been generated after shrinking the
987          * array if required and base64 encodes the response.
988          *
989          * @return The response as above.
990          */
991         public String getResponse() {
992             return new String(Base64.encodeBase64(getBytes()), Consts.ASCII);
993         }
994 
995         public byte[] getBytes() {
996             if (messageContents == null) {
997                 buildMessage();
998             }
999 
1000             if (messageContents.length > currentOutputPosition) {
1001                 final byte[] tmp = new byte[currentOutputPosition];
1002                 System.arraycopy(messageContents, 0, tmp, 0, currentOutputPosition);
1003                 messageContents = tmp;
1004             }
1005             return messageContents;
1006         }
1007 
1008         protected void buildMessage() {
1009             throw new RuntimeException("Message builder not implemented for " + getClass().getName());
1010         }
1011     }
1012 
1013     /** Type 1 message assembly class */
1014     static class Type1Message extends DavMailNTLMEngineImpl.NTLMMessage {
1015 
1016         private final byte[] hostBytes;
1017         private final byte[] domainBytes;
1018         private final int flags;
1019 
1020         Type1Message(final String domain, final String host) {
1021             this(domain, host, null);
1022         }
1023 
1024         Type1Message(final String domain, final String host, final Integer flags) {
1025             super();
1026             this.flags = ((flags == null) ? getDefaultFlags() : flags);
1027 
1028             // Strip off domain name from the host!
1029             final String unqualifiedHost = convertHost(host);
1030             // Use only the base domain name!
1031             final String unqualifiedDomain = convertDomain(domain);
1032 
1033             hostBytes = unqualifiedHost != null ?
1034                     unqualifiedHost.getBytes(UNICODE_LITTLE_UNMARKED) : null;
1035             domainBytes = unqualifiedDomain != null ?
1036                     unqualifiedDomain.toUpperCase(Locale.ROOT).getBytes(UNICODE_LITTLE_UNMARKED) : null;
1037         }
1038 
1039         Type1Message() {
1040             super();
1041             hostBytes = null;
1042             domainBytes = null;
1043             flags = getDefaultFlags();
1044         }
1045 
1046         private int getDefaultFlags() {
1047             return
1048                     //FLAG_WORKSTATION_PRESENT |
1049                     //FLAG_DOMAIN_PRESENT |
1050 
1051                     // Required flags
1052                     //FLAG_REQUEST_LAN_MANAGER_KEY |
1053                     FLAG_REQUEST_NTLMv1 |
1054                             FLAG_REQUEST_NTLM2_SESSION |
1055 
1056                             // Protocol version request
1057                             FLAG_REQUEST_VERSION |
1058 
1059                             // Recommended privacy settings
1060                             FLAG_REQUEST_ALWAYS_SIGN |
1061                             //FLAG_REQUEST_SEAL |
1062                             FLAG_REQUEST_SIGN | // for channel binding
1063 
1064                             // These must be set according to documentation, based on use of SEAL above
1065                             FLAG_REQUEST_128BIT_KEY_EXCH |
1066                             FLAG_REQUEST_56BIT_ENCRYPTION |
1067                             //FLAG_REQUEST_EXPLICIT_KEY_EXCH |
1068 
1069                             FLAG_REQUEST_UNICODE_ENCODING;
1070 
1071         }
1072 
1073         /**
1074          * Getting the response involves building the message before returning
1075          * it
1076          */
1077         @Override
1078         protected void buildMessage() {
1079             int domainBytesLength = 0;
1080             if (domainBytes != null) {
1081                 domainBytesLength = domainBytes.length;
1082             }
1083             int hostBytesLength = 0;
1084             if (hostBytes != null) {
1085                 hostBytesLength = hostBytes.length;
1086             }
1087 
1088             // Now, build the message. Calculate its length first, including
1089             // signature or type.
1090             final int finalLength = 32 + 8 + hostBytesLength + domainBytesLength;
1091 
1092             // Set up the response. This will initialize the signature, message
1093             // type, and flags.
1094             prepareResponse(finalLength, 1);
1095 
1096             // Flags. These are the complete set of flags we support.
1097             addULong(flags);
1098 
1099             // Domain length (two times).
1100             addUShort(domainBytesLength);
1101             addUShort(domainBytesLength);
1102 
1103             // Domain offset.
1104             addULong(hostBytesLength + 32 + 8);
1105 
1106             // Host length (two times).
1107             addUShort(hostBytesLength);
1108             addUShort(hostBytesLength);
1109 
1110             // Host offset (always 32 + 8).
1111             addULong(32 + 8);
1112 
1113             // Version
1114             addUShort(0x0105);
1115             // Build
1116             addULong(2600);
1117             // NTLM revision
1118             addUShort(0x0f00);
1119 
1120             // Host (workstation) String.
1121             if (hostBytes != null) {
1122                 addBytes(hostBytes);
1123             }
1124             // Domain String.
1125             if (domainBytes != null) {
1126                 addBytes(domainBytes);
1127             }
1128         }
1129 
1130     }
1131 
1132     /** Type 2 message class */
1133     static class Type2Message extends NTLMMessage {
1134         protected final byte[] challenge;
1135         protected String target;
1136         protected byte[] targetInfo;
1137         protected final int flags;
1138 
1139         Type2Message(final String messageBody) throws NTLMEngineException {
1140             this(Base64.decodeBase64(messageBody.getBytes(DEFAULT_CHARSET)));
1141         }
1142 
1143         Type2Message(final byte[] message) throws NTLMEngineException {
1144             super(message, 2);
1145 
1146             // Type 2 message is laid out as follows:
1147             // First 8 bytes: NTLMSSP[0]
1148             // Next 4 bytes: Ulong, value 2
1149             // Next 8 bytes, starting at offset 12: target field (2 ushort lengths, 1 ulong offset)
1150             // Next 4 bytes, starting at offset 20: Flags, e.g. 0x22890235
1151             // Next 8 bytes, starting at offset 24: Challenge
1152             // Next 8 bytes, starting at offset 32: ??? (8 bytes of zeros)
1153             // Next 8 bytes, starting at offset 40: targetinfo field (2 ushort lengths, 1 ulong offset)
1154             // Next 2 bytes, major/minor version number (e.g. 0x05 0x02)
1155             // Next 8 bytes, build number
1156             // Next 2 bytes, protocol version number (e.g. 0x00 0x0f)
1157             // Next, various text fields, and a ushort of value 0 at the end
1158 
1159             // Parse out the rest of the info we need from the message
1160             // The nonce is the 8 bytes starting from the byte in position 24.
1161             challenge = new byte[8];
1162             readBytes(challenge, 24);
1163 
1164             flags = super.readULong(20);
1165 
1166             // Do the target!
1167             target = null;
1168             // The TARGET_DESIRED flag is said to not have understood semantics
1169             // in Type2 messages, so use the length of the packet to decide
1170             // how to proceed instead
1171             if (getMessageLength() >= 12 + 8) {
1172                 final byte[] bytes = super.readSecurityBuffer(12);
1173                 if (bytes.length != 0) {
1174                     target = new String(bytes, getCharset(flags));
1175                 }
1176             }
1177 
1178             // Do the target info!
1179             targetInfo = null;
1180             // TARGET_DESIRED flag cannot be relied on, so use packet length
1181             if (getMessageLength() >= 40 + 8) {
1182                 final byte[] bytes = super.readSecurityBuffer(40);
1183                 if (bytes.length != 0) {
1184                     targetInfo = bytes;
1185                 }
1186             }
1187         }
1188 
1189         /** Retrieve the challenge */
1190         byte[] getChallenge() {
1191             return challenge;
1192         }
1193 
1194         /** Retrieve the target */
1195         String getTarget() {
1196             return target;
1197         }
1198 
1199         /** Retrieve the target info */
1200         byte[] getTargetInfo() {
1201             return targetInfo;
1202         }
1203 
1204         /** Retrieve the response flags */
1205         int getFlags() {
1206             return flags;
1207         }
1208 
1209     }
1210 
1211     /** Type 3 message assembly class */
1212     static class Type3Message extends DavMailNTLMEngineImpl.NTLMMessage {
1213         // For mic computation
1214         protected final byte[] type1Message;
1215         protected final byte[] type2Message;
1216         // Response flags from the type2 message
1217         protected final int type2Flags;
1218 
1219         protected final byte[] domainBytes;
1220         protected final byte[] hostBytes;
1221         protected final byte[] userBytes;
1222 
1223         protected byte[] lmResp;
1224         protected byte[] ntResp;
1225         protected final byte[] sessionKey;
1226         protected final byte[] exportedSessionKey;
1227 
1228         protected final boolean computeMic;
1229 
1230         /** More primitive constructor: don't include cert or previous messages.
1231          */
1232         Type3Message(final String domain,
1233                      final String host,
1234                      final String user,
1235                      final String password,
1236                      final byte[] nonce,
1237                      final int type2Flags,
1238                      final String target,
1239                      final byte[] targetInformation)
1240                 throws NTLMEngineException {
1241             this(domain, host, user, password, nonce, type2Flags, target, targetInformation, null, null, null);
1242         }
1243 
1244         /** More primitive constructor: don't include cert or previous messages.
1245          */
1246         Type3Message(final long currentTime,
1247                      final String domain,
1248                      final String host,
1249                      final String user,
1250                      final String password,
1251                      final byte[] nonce,
1252                      final int type2Flags,
1253                      final String target,
1254                      final byte[] targetInformation)
1255                 throws NTLMEngineException {
1256             this(currentTime, domain, host, user, password, nonce, type2Flags, target, targetInformation, null, null, null);
1257         }
1258 
1259         /** Constructor. Pass the arguments we will need */
1260         Type3Message(final String domain,
1261                      final String host,
1262                      final String user,
1263                      final String password,
1264                      final byte[] nonce,
1265                      final int type2Flags,
1266                      final String target,
1267                      final byte[] targetInformation,
1268                      final Certificate peerServerCertificate,
1269                      final byte[] type1Message,
1270                      final byte[] type2Message)
1271                 throws NTLMEngineException {
1272             this(System.currentTimeMillis(), domain, host, user, password, nonce, type2Flags, target, targetInformation, peerServerCertificate, type1Message, type2Message);
1273         }
1274 
1275         /** Constructor. Pass the arguments we will need */
1276         Type3Message(final long currentTime,
1277                      final String domain,
1278                      final String host,
1279                      final String user,
1280                      final String password,
1281                      final byte[] nonce,
1282                      final int type2Flags,
1283                      final String target,
1284                      final byte[] targetInformation,
1285                      final Certificate peerServerCertificate,
1286                      final byte[] type1Message,
1287                      final byte[] type2Message)
1288                 throws NTLMEngineException {
1289 
1290             // Save the flags
1291             this.type2Flags = type2Flags;
1292             this.type1Message = type1Message;
1293             this.type2Message = type2Message;
1294 
1295             // Strip off domain name from the host!
1296             final String unqualifiedHost = convertHost(host);
1297             // Use only the base domain name!
1298             final String unqualifiedDomain = convertDomain(domain);
1299 
1300             byte[] responseTargetInformation = targetInformation;
1301             if (peerServerCertificate != null) {
1302                 responseTargetInformation = addGssMicAvsToTargetInfo(targetInformation, peerServerCertificate);
1303                 computeMic = true;
1304                 LOGGER.debug("Included certificate info for channel binding subject:"+((X509Certificate)peerServerCertificate).getSubjectX500Principal());
1305             } else {
1306                 computeMic = false;
1307                 LOGGER.debug("Certificate info not available for channel binding");
1308             }
1309 
1310             // Create a cipher generator class.  Use domain BEFORE it gets modified!
1311             final DavMailNTLMEngineImpl.CipherGen gen = new DavMailNTLMEngineImpl.CipherGen(currentTime,
1312                     unqualifiedDomain,
1313                     user,
1314                     password,
1315                     nonce,
1316                     target,
1317                     responseTargetInformation);
1318 
1319             // Use the new code to calculate the responses, including v2 if that
1320             // seems warranted.
1321             byte[] userSessionKey;
1322             try {
1323                 // This conditional may not work on Windows Server 2008 R2 and above, where it has not yet
1324                 // been tested
1325                 if (((type2Flags & FLAG_TARGETINFO_PRESENT) != 0) &&
1326                         targetInformation != null && target != null) {
1327                     // NTLMv2
1328                     ntResp = gen.getNTLMv2Response();
1329                     lmResp = gen.getLMv2Response();
1330                     if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
1331                         userSessionKey = gen.getLanManagerSessionKey();
1332                     } else {
1333                         userSessionKey = gen.getNTLMv2UserSessionKey();
1334                     }
1335                 } else {
1336                     // NTLMv1
1337                     if ((type2Flags & FLAG_REQUEST_NTLM2_SESSION) != 0) {
1338                         // NTLM2 session stuff is requested
1339                         ntResp = gen.getNTLM2SessionResponse();
1340                         lmResp = gen.getLM2SessionResponse();
1341                         if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
1342                             userSessionKey = gen.getLanManagerSessionKey();
1343                         } else {
1344                             userSessionKey = gen.getNTLM2SessionResponseUserSessionKey();
1345                         }
1346                     } else {
1347                         ntResp = gen.getNTLMResponse();
1348                         lmResp = gen.getLMResponse();
1349                         if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
1350                             userSessionKey = gen.getLanManagerSessionKey();
1351                         } else {
1352                             userSessionKey = gen.getNTLMUserSessionKey();
1353                         }
1354                     }
1355                 }
1356             } catch (final NTLMEngineException e) {
1357                 // This likely means we couldn't find the MD4 hash algorithm -
1358                 // fail back to just using LM
1359                 ntResp = new byte[0];
1360                 lmResp = gen.getLMResponse();
1361                 if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
1362                     userSessionKey = gen.getLanManagerSessionKey();
1363                 } else {
1364                     userSessionKey = gen.getLMUserSessionKey();
1365                 }
1366             }
1367 
1368             if ((type2Flags & FLAG_REQUEST_SIGN) != 0) {
1369                 if ((type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) != 0) {
1370                     exportedSessionKey = gen.getSecondaryKey();
1371                     sessionKey = RC4(exportedSessionKey, userSessionKey);
1372                 } else {
1373                     sessionKey = userSessionKey;
1374                     exportedSessionKey = sessionKey;
1375                 }
1376             } else {
1377                 if (computeMic) {
1378                     throw new NTLMEngineException("Cannot sign/seal: no exported session key");
1379                 }
1380                 sessionKey = null;
1381                 exportedSessionKey = null;
1382             }
1383             final Charset charset = getCharset(type2Flags);
1384             hostBytes = unqualifiedHost != null ? unqualifiedHost.getBytes(charset) : null;
1385             domainBytes = unqualifiedDomain != null ? unqualifiedDomain
1386                     .toUpperCase(Locale.ROOT).getBytes(charset) : null;
1387             userBytes = user.getBytes(charset);
1388         }
1389 
1390         public byte[] getEncryptedRandomSessionKey() {
1391             return sessionKey;
1392         }
1393 
1394         public byte[] getExportedSessionKey() {
1395             return exportedSessionKey;
1396         }
1397 
1398         /** Assemble the response */
1399         @Override
1400         protected void buildMessage() {
1401             final int ntRespLen = ntResp.length;
1402             final int lmRespLen = lmResp.length;
1403 
1404             final int domainLen = domainBytes != null ? domainBytes.length : 0;
1405             final int hostLen = hostBytes != null ? hostBytes.length : 0;
1406             final int userLen = userBytes.length;
1407             final int sessionKeyLen;
1408             if (sessionKey != null) {
1409                 sessionKeyLen = sessionKey.length;
1410             } else {
1411                 sessionKeyLen = 0;
1412             }
1413 
1414             // Calculate the layout within the packet
1415             final int lmRespOffset = 72 + // allocate space for the version
1416                     (computeMic ? 16 : 0); // and MIC
1417             final int ntRespOffset = lmRespOffset + lmRespLen;
1418             final int domainOffset = ntRespOffset + ntRespLen;
1419             final int userOffset = domainOffset + domainLen;
1420             final int hostOffset = userOffset + userLen;
1421             final int sessionKeyOffset = hostOffset + hostLen;
1422             final int finalLength = sessionKeyOffset + sessionKeyLen;
1423 
1424             // Start the response. Length includes signature and type
1425             prepareResponse(finalLength, 3);
1426 
1427             // LM Resp Length (twice)
1428             addUShort(lmRespLen);
1429             addUShort(lmRespLen);
1430 
1431             // LM Resp Offset
1432             addULong(lmRespOffset);
1433 
1434             // NT Resp Length (twice)
1435             addUShort(ntRespLen);
1436             addUShort(ntRespLen);
1437 
1438             // NT Resp Offset
1439             addULong(ntRespOffset);
1440 
1441             // Domain length (twice)
1442             addUShort(domainLen);
1443             addUShort(domainLen);
1444 
1445             // Domain offset.
1446             addULong(domainOffset);
1447 
1448             // User Length (twice)
1449             addUShort(userLen);
1450             addUShort(userLen);
1451 
1452             // User offset
1453             addULong(userOffset);
1454 
1455             // Host length (twice)
1456             addUShort(hostLen);
1457             addUShort(hostLen);
1458 
1459             // Host offset
1460             addULong(hostOffset);
1461 
1462             // Session key length (twice)
1463             addUShort(sessionKeyLen);
1464             addUShort(sessionKeyLen);
1465 
1466             // Session key offset
1467             addULong(sessionKeyOffset);
1468 
1469             // Flags.
1470             addULong(
1471                     /*
1472                     //FLAG_WORKSTATION_PRESENT |
1473                     //FLAG_DOMAIN_PRESENT |
1474 
1475                     // Required flags
1476                     (type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) |
1477                     (type2Flags & FLAG_REQUEST_NTLMv1) |
1478                     (type2Flags & FLAG_REQUEST_NTLM2_SESSION) |
1479 
1480                     // Protocol version request
1481                     FLAG_REQUEST_VERSION |
1482 
1483                     // Recommended privacy settings
1484                     (type2Flags & FLAG_REQUEST_ALWAYS_SIGN) |
1485                     (type2Flags & FLAG_REQUEST_SEAL) |
1486                     (type2Flags & FLAG_REQUEST_SIGN) |
1487 
1488                     // These must be set according to documentation, based on use of SEAL above
1489                     (type2Flags & FLAG_REQUEST_128BIT_KEY_EXCH) |
1490                     (type2Flags & FLAG_REQUEST_56BIT_ENCRYPTION) |
1491                     (type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) |
1492 
1493                     (type2Flags & FLAG_TARGETINFO_PRESENT) |
1494                     (type2Flags & FLAG_REQUEST_UNICODE_ENCODING) |
1495                     (type2Flags & FLAG_REQUEST_TARGET)
1496                         */
1497                     type2Flags
1498             );
1499 
1500             // Version
1501             addUShort(0x0105);
1502             // Build
1503             addULong(2600);
1504             // NTLM revision
1505             addUShort(0x0f00);
1506 
1507             int micPosition = -1;
1508             if (computeMic) {
1509                 micPosition = currentOutputPosition;
1510                 currentOutputPosition += 16;
1511             }
1512 
1513             // Add the actual data
1514             addBytes(lmResp);
1515             addBytes(ntResp);
1516             addBytes(domainBytes);
1517             addBytes(userBytes);
1518             addBytes(hostBytes);
1519             if (sessionKey != null) {
1520                 addBytes(sessionKey);
1521             }
1522 
1523             // Write the mic back into its slot in the message
1524 
1525             if (computeMic) {
1526                 // Computation of message integrity code (MIC) as specified in [MS-NLMP] section 3.2.5.1.2.
1527                 final DavMailNTLMEngineImpl.HMACMD5 hmacMD5 = new HMACMD5(exportedSessionKey);
1528                 hmacMD5.update(type1Message);
1529                 hmacMD5.update(type2Message);
1530                 hmacMD5.update(messageContents);
1531                 final byte[] mic = hmacMD5.getOutput();
1532                 System.arraycopy(mic, 0, messageContents, micPosition, mic.length);
1533             }
1534         }
1535 
1536         /**
1537          * Add GSS channel binding hash and MIC flag to the targetInfo.
1538          * Looks like this is needed if we want to use exported session key for GSS wrapping.
1539          */
1540         private byte[] addGssMicAvsToTargetInfo(final byte[] originalTargetInfo,
1541                                                 final Certificate peerServerCertificate) throws NTLMEngineException {
1542             final byte[] newTargetInfo = new byte[originalTargetInfo.length + 8 + 20];
1543             final int appendLength = originalTargetInfo.length - 4; // last tag is MSV_AV_EOL, do not copy that
1544             System.arraycopy(originalTargetInfo, 0, newTargetInfo, 0, appendLength);
1545             writeUShort(newTargetInfo, MSV_AV_FLAGS, appendLength);
1546             writeUShort(newTargetInfo, 4, appendLength + 2);
1547             writeULong(newTargetInfo, MSV_AV_FLAGS_MIC, appendLength + 4);
1548             writeUShort(newTargetInfo, MSV_AV_CHANNEL_BINDINGS, appendLength + 8);
1549             writeUShort(newTargetInfo, 16, appendLength + 10);
1550 
1551             final byte[] channelBindingsHash;
1552             try {
1553                 final byte[] certBytes = peerServerCertificate.getEncoded();
1554                 final MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
1555                 final byte[] certHashBytes = sha256.digest(certBytes);
1556                 final byte[] channelBindingStruct = new byte[16 + 4 + MAGIC_TLS_SERVER_ENDPOINT.length
1557                         + certHashBytes.length];
1558                 writeULong(channelBindingStruct, 0x00000035, 16);
1559                 System.arraycopy(MAGIC_TLS_SERVER_ENDPOINT, 0, channelBindingStruct, 20,
1560                         MAGIC_TLS_SERVER_ENDPOINT.length);
1561                 System.arraycopy(certHashBytes, 0, channelBindingStruct, 20 + MAGIC_TLS_SERVER_ENDPOINT.length,
1562                         certHashBytes.length);
1563                 final MessageDigest md5 = getMD5();
1564                 channelBindingsHash = md5.digest(channelBindingStruct);
1565             } catch (CertificateEncodingException | NoSuchAlgorithmException e) {
1566                 throw new NTLMEngineException(e.getMessage(), e);
1567             }
1568 
1569             System.arraycopy(channelBindingsHash, 0, newTargetInfo, appendLength + 12, 16);
1570             return newTargetInfo;
1571         }
1572 
1573     }
1574 
1575     static void writeUShort(final byte[] buffer, final int value, final int offset) {
1576         buffer[offset] = (byte) (value & 0xff);
1577         buffer[offset + 1] = (byte) (value >> 8 & 0xff);
1578     }
1579 
1580     static void writeULong(final byte[] buffer, final int value, final int offset) {
1581         buffer[offset] = (byte) (value & 0xff);
1582         buffer[offset + 1] = (byte) (value >> 8 & 0xff);
1583         buffer[offset + 2] = (byte) (value >> 16 & 0xff);
1584         buffer[offset + 3] = (byte) (value >> 24 & 0xff);
1585     }
1586 
1587     static int F(final int x, final int y, final int z) {
1588         return ((x & y) | (~x & z));
1589     }
1590 
1591     static int G(final int x, final int y, final int z) {
1592         return ((x & y) | (x & z) | (y & z));
1593     }
1594 
1595     static int H(final int x, final int y, final int z) {
1596         return (x ^ y ^ z);
1597     }
1598 
1599     static int rotintlft(final int val, final int numbits) {
1600         return ((val << numbits) | (val >>> (32 - numbits)));
1601     }
1602 
1603     static MessageDigest getMD5() {
1604         try {
1605             return MessageDigest.getInstance("MD5");
1606         } catch (final NoSuchAlgorithmException ex) {
1607             throw new RuntimeException("MD5 message digest doesn't seem to exist - fatal error: " + ex.getMessage(), ex);
1608         }
1609     }
1610 
1611     /**
1612      * Cryptography support - MD4. The following class was based loosely on the
1613      * RFC and on code found at http://www.cs.umd.edu/~harry/jotp/src/md.java.
1614      * Code correctness was verified by looking at MD4.java from the jcifs
1615      * library (http://jcifs.samba.org). It was massaged extensively to the
1616      * final form found here by Karl Wright (kwright@metacarta.com).
1617      */
1618     static class MD4 {
1619         protected int A = 0x67452301;
1620         protected int B = 0xefcdab89;
1621         protected int C = 0x98badcfe;
1622         protected int D = 0x10325476;
1623         protected long count = 0L;
1624         protected final byte[] dataBuffer = new byte[64];
1625 
1626         MD4() {
1627         }
1628 
1629         void update(final byte[] input) {
1630             // We always deal with 512 bits at a time. Correspondingly, there is
1631             // a buffer 64 bytes long that we write data into until it gets
1632             // full.
1633             int curBufferPos = (int) (count & 63L);
1634             int inputIndex = 0;
1635             while (input.length - inputIndex + curBufferPos >= dataBuffer.length) {
1636                 // We have enough data to do the next step. Do a partial copy
1637                 // and a transform, updating inputIndex and curBufferPos
1638                 // accordingly
1639                 final int transferAmt = dataBuffer.length - curBufferPos;
1640                 System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
1641                 count += transferAmt;
1642                 curBufferPos = 0;
1643                 inputIndex += transferAmt;
1644                 processBuffer();
1645             }
1646 
1647             // If there's anything left, copy it into the buffer and leave it.
1648             // We know there's not enough left to process.
1649             if (inputIndex < input.length) {
1650                 final int transferAmt = input.length - inputIndex;
1651                 System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
1652                 count += transferAmt;
1653             }
1654         }
1655 
1656         byte[] getOutput() {
1657             // Feed pad/length data into engine. This must round out the input
1658             // to a multiple of 512 bits.
1659             final int bufferIndex = (int) (count & 63L);
1660             final int padLen = (bufferIndex < 56) ? (56 - bufferIndex) : (120 - bufferIndex);
1661             final byte[] postBytes = new byte[padLen + 8];
1662             // Leading 0x80, specified amount of zero padding, then length in
1663             // bits.
1664             postBytes[0] = (byte) 0x80;
1665             // Fill out the last 8 bytes with the length
1666             for (int i = 0; i < 8; i++) {
1667                 postBytes[padLen + i] = (byte) ((count * 8) >>> (8 * i));
1668             }
1669 
1670             // Update the engine
1671             update(postBytes);
1672 
1673             // Calculate final result
1674             final byte[] result = new byte[16];
1675             writeULong(result, A, 0);
1676             writeULong(result, B, 4);
1677             writeULong(result, C, 8);
1678             writeULong(result, D, 12);
1679             return result;
1680         }
1681 
1682         protected void processBuffer() {
1683             // Convert current buffer to 16 ulongs
1684             final int[] d = new int[16];
1685 
1686             for (int i = 0; i < 16; i++) {
1687                 d[i] = (dataBuffer[i * 4] & 0xff) + ((dataBuffer[i * 4 + 1] & 0xff) << 8)
1688                         + ((dataBuffer[i * 4 + 2] & 0xff) << 16)
1689                         + ((dataBuffer[i * 4 + 3] & 0xff) << 24);
1690             }
1691 
1692             // Do a round of processing
1693             final int AA = A;
1694             final int BB = B;
1695             final int CC = C;
1696             final int DD = D;
1697             round1(d);
1698             round2(d);
1699             round3(d);
1700             A += AA;
1701             B += BB;
1702             C += CC;
1703             D += DD;
1704 
1705         }
1706 
1707         protected void round1(final int[] d) {
1708             A = rotintlft((A + F(B, C, D) + d[0]), 3);
1709             D = rotintlft((D + F(A, B, C) + d[1]), 7);
1710             C = rotintlft((C + F(D, A, B) + d[2]), 11);
1711             B = rotintlft((B + F(C, D, A) + d[3]), 19);
1712 
1713             A = rotintlft((A + F(B, C, D) + d[4]), 3);
1714             D = rotintlft((D + F(A, B, C) + d[5]), 7);
1715             C = rotintlft((C + F(D, A, B) + d[6]), 11);
1716             B = rotintlft((B + F(C, D, A) + d[7]), 19);
1717 
1718             A = rotintlft((A + F(B, C, D) + d[8]), 3);
1719             D = rotintlft((D + F(A, B, C) + d[9]), 7);
1720             C = rotintlft((C + F(D, A, B) + d[10]), 11);
1721             B = rotintlft((B + F(C, D, A) + d[11]), 19);
1722 
1723             A = rotintlft((A + F(B, C, D) + d[12]), 3);
1724             D = rotintlft((D + F(A, B, C) + d[13]), 7);
1725             C = rotintlft((C + F(D, A, B) + d[14]), 11);
1726             B = rotintlft((B + F(C, D, A) + d[15]), 19);
1727         }
1728 
1729         protected void round2(final int[] d) {
1730             A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3);
1731             D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5);
1732             C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9);
1733             B = rotintlft((B + G(C, D, A) + d[12] + 0x5a827999), 13);
1734 
1735             A = rotintlft((A + G(B, C, D) + d[1] + 0x5a827999), 3);
1736             D = rotintlft((D + G(A, B, C) + d[5] + 0x5a827999), 5);
1737             C = rotintlft((C + G(D, A, B) + d[9] + 0x5a827999), 9);
1738             B = rotintlft((B + G(C, D, A) + d[13] + 0x5a827999), 13);
1739 
1740             A = rotintlft((A + G(B, C, D) + d[2] + 0x5a827999), 3);
1741             D = rotintlft((D + G(A, B, C) + d[6] + 0x5a827999), 5);
1742             C = rotintlft((C + G(D, A, B) + d[10] + 0x5a827999), 9);
1743             B = rotintlft((B + G(C, D, A) + d[14] + 0x5a827999), 13);
1744 
1745             A = rotintlft((A + G(B, C, D) + d[3] + 0x5a827999), 3);
1746             D = rotintlft((D + G(A, B, C) + d[7] + 0x5a827999), 5);
1747             C = rotintlft((C + G(D, A, B) + d[11] + 0x5a827999), 9);
1748             B = rotintlft((B + G(C, D, A) + d[15] + 0x5a827999), 13);
1749 
1750         }
1751 
1752         protected void round3(final int[] d) {
1753             A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3);
1754             D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9);
1755             C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11);
1756             B = rotintlft((B + H(C, D, A) + d[12] + 0x6ed9eba1), 15);
1757 
1758             A = rotintlft((A + H(B, C, D) + d[2] + 0x6ed9eba1), 3);
1759             D = rotintlft((D + H(A, B, C) + d[10] + 0x6ed9eba1), 9);
1760             C = rotintlft((C + H(D, A, B) + d[6] + 0x6ed9eba1), 11);
1761             B = rotintlft((B + H(C, D, A) + d[14] + 0x6ed9eba1), 15);
1762 
1763             A = rotintlft((A + H(B, C, D) + d[1] + 0x6ed9eba1), 3);
1764             D = rotintlft((D + H(A, B, C) + d[9] + 0x6ed9eba1), 9);
1765             C = rotintlft((C + H(D, A, B) + d[5] + 0x6ed9eba1), 11);
1766             B = rotintlft((B + H(C, D, A) + d[13] + 0x6ed9eba1), 15);
1767 
1768             A = rotintlft((A + H(B, C, D) + d[3] + 0x6ed9eba1), 3);
1769             D = rotintlft((D + H(A, B, C) + d[11] + 0x6ed9eba1), 9);
1770             C = rotintlft((C + H(D, A, B) + d[7] + 0x6ed9eba1), 11);
1771             B = rotintlft((B + H(C, D, A) + d[15] + 0x6ed9eba1), 15);
1772 
1773         }
1774 
1775     }
1776 
1777     /**
1778      * Cryptography support - HMACMD5 - algorithmically based on various web
1779      * resources by Karl Wright
1780      */
1781     private static class HMACMD5 {
1782         protected final byte[] ipad;
1783         protected final byte[] opad;
1784         @SuppressWarnings("java:S9428") // HMACMD5 instances are short-lived and never shared across threads
1785         protected final MessageDigest md5;
1786 
1787         HMACMD5(final byte[] input) {
1788             byte[] key = input;
1789             md5 = getMD5();
1790 
1791             // Initialize the pad buffers with the key
1792             ipad = new byte[64];
1793             opad = new byte[64];
1794 
1795             int keyLength = key.length;
1796             if (keyLength > 64) {
1797                 // Use MD5 of the key instead, as described in RFC 2104
1798                 md5.update(key);
1799                 key = md5.digest();
1800                 keyLength = key.length;
1801             }
1802             int i = 0;
1803             while (i < keyLength) {
1804                 ipad[i] = (byte) (key[i] ^ (byte) 0x36);
1805                 opad[i] = (byte) (key[i] ^ (byte) 0x5c);
1806                 i++;
1807             }
1808             while (i < 64) {
1809                 ipad[i] = (byte) 0x36;
1810                 opad[i] = (byte) 0x5c;
1811                 i++;
1812             }
1813 
1814             // Very important: processChallenge the digest with the ipad buffer
1815             md5.reset();
1816             md5.update(ipad);
1817 
1818         }
1819 
1820         /** Grab the current digest. This is the "answer". */
1821         byte[] getOutput() {
1822             final byte[] digest = md5.digest();
1823             md5.update(opad);
1824             return md5.digest(digest);
1825         }
1826 
1827         /** Update by adding a complete array */
1828         void update(final byte[] input) {
1829             md5.update(input);
1830         }
1831 
1832         /** Update the algorithm */
1833         void update(final byte[] input, final int offset, final int length) {
1834             md5.update(input, offset, length);
1835         }
1836 
1837     }
1838 
1839     @Override
1840     public String generateType1Msg(
1841             final String domain,
1842             final String workstation) {
1843         LOGGER.debug("generateType1Msg domain='" + domain + "' workstation='" + workstation + "'");
1844         LOGGER.debug(NTLMMessageDecoder.decode(TYPE_1_MESSAGE));
1845         // Type 1 message is a constant without domain and workstation
1846         return TYPE_1_MESSAGE;
1847     }
1848 
1849     @Override
1850     public String generateType3Msg(
1851             final String username,
1852             final String password,
1853             final String domain,
1854             final String workstation,
1855             final String challenge) throws NTLMEngineException {
1856 
1857         // need to retrieve raw type 1 and 2 message and connection certificate for channel binding implementation
1858         byte[] type1MessageBytes = new Type1Message().getBytes();
1859         byte[] type2MessageBytes = Base64.decodeBase64(challenge.getBytes(DEFAULT_CHARSET));
1860         if (LOGGER.isDebugEnabled()) {
1861             LOGGER.debug(NTLMMessageDecoder.decode(challenge));
1862         }
1863 
1864         final DavMailNTLMEngineImpl.Type2Message t2m = new DavMailNTLMEngineImpl.Type2Message(challenge);
1865 
1866         LOGGER.debug("generateType3Msg type2Flags=" + t2m.getFlags() + " target='" + t2m.getTarget() + "' username='" + username + "' domain='" + domain + "' workstation='" + workstation + "'");
1867 
1868         String type3Message = getType3Message(
1869                 username,
1870                 password,
1871                 workstation,
1872                 domain,
1873                 t2m.getChallenge(),
1874                 t2m.getFlags(),
1875                 t2m.getTarget(),
1876                 t2m.getTargetInfo(),
1877                 peerServerCertificate,
1878                 type1MessageBytes,
1879                 type2MessageBytes);
1880         if (LOGGER.isDebugEnabled()) {
1881             LOGGER.debug(NTLMMessageDecoder.decode(type3Message));
1882         }
1883         return type3Message;
1884     }
1885 
1886 }