1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
45
46
47
48 @SuppressWarnings("unused")
49 final class DavMailNTLMEngineImpl implements NTLMEngine {
50
51 static final Logger LOGGER = Logger.getLogger("davmail.http.DavMailNTLMEngineImpl");
52
53
54 private static final Charset UNICODE_LITTLE_UNMARKED = StandardCharsets.UTF_16LE;
55
56 private static final Charset DEFAULT_CHARSET = Consts.ASCII;
57
58
59
60
61
62
63 static final int FLAG_REQUEST_UNICODE_ENCODING = 0x00000001;
64 static final int FLAG_REQUEST_OEM_ENCODING = 0x00000002;
65 static final int FLAG_REQUEST_TARGET = 0x00000004;
66 static final int FLAG_REQUEST_SIGN = 0x00000010;
67 static final int FLAG_REQUEST_SEAL = 0x00000020;
68 static final int FLAG_REQUEST_LAN_MANAGER_KEY = 0x00000080;
69 static final int FLAG_REQUEST_NTLMv1 = 0x00000200;
70 static final int FLAG_DOMAIN_PRESENT = 0x00001000;
71 static final int FLAG_WORKSTATION_PRESENT = 0x00002000;
72 static final int FLAG_REQUEST_ALWAYS_SIGN = 0x00008000;
73 static final int FLAG_REQUEST_NTLM2_SESSION = 0x00080000;
74 static final int FLAG_REQUEST_VERSION = 0x02000000;
75 static final int FLAG_TARGETINFO_PRESENT = 0x00800000;
76 static final int FLAG_REQUEST_128BIT_KEY_EXCH = 0x20000000;
77 static final int FLAG_REQUEST_EXPLICIT_KEY_EXCH = 0x40000000;
78 static final int FLAG_REQUEST_56BIT_ENCRYPTION = 0x80000000;
79
80
81
82 static final int MSV_AV_EOL = 0x0000;
83 static final int MSV_AV_NB_COMPUTER_NAME = 0x0001;
84 static final int MSV_AV_NB_DOMAIN_NAME = 0x0002;
85 static final int MSV_AV_DNS_COMPUTER_NAME = 0x0003;
86 static final int MSV_AV_DNS_DOMAIN_NAME = 0x0004;
87 static final int MSV_AV_DNS_TREE_NAME = 0x0005;
88 static final int MSV_AV_FLAGS = 0x0006;
89 static final int MSV_AV_TIMESTAMP = 0x0007;
90 static final int MSV_AV_SINGLE_HOST = 0x0008;
91 static final int MSV_AV_TARGET_NAME = 0x0009;
92 static final int MSV_AV_CHANNEL_BINDINGS = 0x000A;
93
94 static final int MSV_AV_FLAGS_ACCOUNT_AUTH_CONSTAINED = 0x00000001;
95 static final int MSV_AV_FLAGS_MIC = 0x00000002;
96 static final int MSV_AV_FLAGS_UNTRUSTED_TARGET_SPN = 0x00000004;
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
109 private static final byte[] SIGNATURE = getNullTerminatedAsciiString("NTLMSSP");
110
111
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
131
132
133 public void setPeerServerCertificate(Certificate peerServerCertificate) {
134 this.peerServerCertificate = peerServerCertificate;
135 }
136
137
138
139
140
141
142
143
144
145
146
147
148 static String getType1Message(final String host, final String domain) {
149
150 return TYPE_1_MESSAGE;
151 }
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
235 private static byte[] makeRandomChallenge() {
236 final byte[] rval = new byte[8];
237 RNG.nextBytes(rval);
238 return rval;
239 }
240
241
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
260 protected byte[] clientChallenge;
261 protected byte[] clientChallenge2;
262 protected byte[] secondaryKey;
263 protected byte[] timestamp;
264
265
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
313 public byte[] getClientChallenge() {
314 if (clientChallenge == null) {
315 clientChallenge = makeRandomChallenge();
316 }
317 return clientChallenge;
318 }
319
320
321 public byte[] getClientChallenge2() {
322 if (clientChallenge2 == null) {
323 clientChallenge2 = makeRandomChallenge();
324 }
325 return clientChallenge2;
326 }
327
328
329 public byte[] getSecondaryKey() {
330 if (secondaryKey == null) {
331 secondaryKey = makeSecondaryKey();
332 }
333 return secondaryKey;
334 }
335
336
337 public byte[] getLMHash()
338 throws NTLMEngineException {
339 if (lmHash == null) {
340 lmHash = lmHash(password);
341 }
342 return lmHash;
343 }
344
345
346 public byte[] getLMResponse()
347 throws NTLMEngineException {
348 if (lmResponse == null) {
349 lmResponse = lmResponse(getLMHash(), challenge);
350 }
351 return lmResponse;
352 }
353
354
355 public byte[] getNTLMHash() {
356 if (ntlmHash == null) {
357 ntlmHash = ntlmHash(password);
358 }
359 return ntlmHash;
360 }
361
362
363 public byte[] getNTLMResponse()
364 throws NTLMEngineException {
365 if (ntlmResponse == null) {
366 ntlmResponse = lmResponse(getNTLMHash(), challenge);
367 }
368 return ntlmResponse;
369 }
370
371
372 public byte[] getLMv2Hash()
373 throws NTLMEngineException {
374 if (lmv2Hash == null) {
375 lmv2Hash = lmv2Hash(domain, user, getNTLMHash());
376 }
377 return lmv2Hash;
378 }
379
380
381 public byte[] getNTLMv2Hash()
382 throws NTLMEngineException {
383 if (ntlmv2Hash == null) {
384 ntlmv2Hash = ntlmv2Hash(domain, user, getNTLMHash());
385 }
386 return ntlmv2Hash;
387 }
388
389
390 public byte[] getTimestamp() {
391 if (timestamp == null) {
392 long time = this.currentTime;
393 time += 11644473600000L;
394 time *= 10000;
395
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
406 public byte[] getNTLMv2Blob() {
407 if (ntlmv2Blob == null) {
408 ntlmv2Blob = createBlob(getClientChallenge2(), targetInformation, getTimestamp());
409 }
410 return ntlmv2Blob;
411 }
412
413
414 public byte[] getNTLMv2Response()
415 throws NTLMEngineException {
416 if (ntlmv2Response == null) {
417 ntlmv2Response = lmv2Response(getNTLMv2Hash(), challenge, getNTLMv2Blob());
418 }
419 return ntlmv2Response;
420 }
421
422
423 public byte[] getLMv2Response()
424 throws NTLMEngineException {
425 if (lmv2Response == null) {
426 lmv2Response = lmv2Response(getLMv2Hash(), challenge, getClientChallenge());
427 }
428 return lmv2Response;
429 }
430
431
432 public byte[] getNTLM2SessionResponse()
433 throws NTLMEngineException {
434 if (ntlm2SessionResponse == null) {
435 ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(), challenge, getClientChallenge());
436 }
437 return ntlm2SessionResponse;
438 }
439
440
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
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
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
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
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
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
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
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
548
549
550
551
552
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
574
575
576
577
578
579
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
606
607
608
609
610
611
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
622
623
624
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
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
639
640
641
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
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
655
656
657
658
659
660
661
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
689
690
691
692
693
694
695
696
697
698
699
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
727
728
729
730
731
732
733
734
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
763
764
765
766
767
768
769
770
771
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
791
792
793
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
810
811
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
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
833 private static String convertHost(final String host) {
834 return stripDotSuffix(host);
835 }
836
837
838 private static String convertDomain(final String domain) {
839 return stripDotSuffix(domain);
840 }
841
842
843 static class NTLMMessage {
844
845 protected byte[] messageContents = null;
846
847
848 protected int currentOutputPosition = 0;
849
850
851 NTLMMessage() {
852 }
853
854
855 NTLMMessage(final String messageBody, final int expectedType) throws NTLMEngineException {
856 this(Base64.decodeBase64(messageBody.getBytes(DEFAULT_CHARSET)), expectedType);
857 }
858
859
860 NTLMMessage(final byte[] message, final int expectedType) throws NTLMEngineException {
861 messageContents = message;
862
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
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
887
888
889 protected int getPreambleLength() {
890 return SIGNATURE.length + 4;
891 }
892
893
894 protected int getMessageLength() {
895 return currentOutputPosition;
896 }
897
898
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
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
915 protected int readUShort(final int position) {
916 return DavMailNTLMEngineImpl.readUShort(messageContents, position);
917 }
918
919
920 protected int readULong(final int position) {
921 return DavMailNTLMEngineImpl.readULong(messageContents, position);
922 }
923
924
925 protected byte[] readSecurityBuffer(final int position) {
926 return DavMailNTLMEngineImpl.readSecurityBuffer(messageContents, position);
927 }
928
929
930
931
932
933
934
935
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
946
947
948
949
950 protected void addByte(final byte b) {
951 messageContents[currentOutputPosition] = b;
952 currentOutputPosition++;
953 }
954
955
956
957
958
959
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
972 protected void addUShort(final int value) {
973 addByte((byte) (value & 0xff));
974 addByte((byte) (value >> 8 & 0xff));
975 }
976
977
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
987
988
989
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
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
1029 final String unqualifiedHost = convertHost(host);
1030
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
1049
1050
1051
1052
1053 FLAG_REQUEST_NTLMv1 |
1054 FLAG_REQUEST_NTLM2_SESSION |
1055
1056
1057 FLAG_REQUEST_VERSION |
1058
1059
1060 FLAG_REQUEST_ALWAYS_SIGN |
1061
1062 FLAG_REQUEST_SIGN |
1063
1064
1065 FLAG_REQUEST_128BIT_KEY_EXCH |
1066 FLAG_REQUEST_56BIT_ENCRYPTION |
1067
1068
1069 FLAG_REQUEST_UNICODE_ENCODING;
1070
1071 }
1072
1073
1074
1075
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
1089
1090 final int finalLength = 32 + 8 + hostBytesLength + domainBytesLength;
1091
1092
1093
1094 prepareResponse(finalLength, 1);
1095
1096
1097 addULong(flags);
1098
1099
1100 addUShort(domainBytesLength);
1101 addUShort(domainBytesLength);
1102
1103
1104 addULong(hostBytesLength + 32 + 8);
1105
1106
1107 addUShort(hostBytesLength);
1108 addUShort(hostBytesLength);
1109
1110
1111 addULong(32 + 8);
1112
1113
1114 addUShort(0x0105);
1115
1116 addULong(2600);
1117
1118 addUShort(0x0f00);
1119
1120
1121 if (hostBytes != null) {
1122 addBytes(hostBytes);
1123 }
1124
1125 if (domainBytes != null) {
1126 addBytes(domainBytes);
1127 }
1128 }
1129
1130 }
1131
1132
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
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161 challenge = new byte[8];
1162 readBytes(challenge, 24);
1163
1164 flags = super.readULong(20);
1165
1166
1167 target = null;
1168
1169
1170
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
1179 targetInfo = null;
1180
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
1190 byte[] getChallenge() {
1191 return challenge;
1192 }
1193
1194
1195 String getTarget() {
1196 return target;
1197 }
1198
1199
1200 byte[] getTargetInfo() {
1201 return targetInfo;
1202 }
1203
1204
1205 int getFlags() {
1206 return flags;
1207 }
1208
1209 }
1210
1211
1212 static class Type3Message extends DavMailNTLMEngineImpl.NTLMMessage {
1213
1214 protected final byte[] type1Message;
1215 protected final byte[] type2Message;
1216
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
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
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
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
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
1291 this.type2Flags = type2Flags;
1292 this.type1Message = type1Message;
1293 this.type2Message = type2Message;
1294
1295
1296 final String unqualifiedHost = convertHost(host);
1297
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
1311 final DavMailNTLMEngineImpl.CipherGen gen = new DavMailNTLMEngineImpl.CipherGen(currentTime,
1312 unqualifiedDomain,
1313 user,
1314 password,
1315 nonce,
1316 target,
1317 responseTargetInformation);
1318
1319
1320
1321 byte[] userSessionKey;
1322 try {
1323
1324
1325 if (((type2Flags & FLAG_TARGETINFO_PRESENT) != 0) &&
1326 targetInformation != null && target != null) {
1327
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
1337 if ((type2Flags & FLAG_REQUEST_NTLM2_SESSION) != 0) {
1338
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
1358
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
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
1415 final int lmRespOffset = 72 +
1416 (computeMic ? 16 : 0);
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
1425 prepareResponse(finalLength, 3);
1426
1427
1428 addUShort(lmRespLen);
1429 addUShort(lmRespLen);
1430
1431
1432 addULong(lmRespOffset);
1433
1434
1435 addUShort(ntRespLen);
1436 addUShort(ntRespLen);
1437
1438
1439 addULong(ntRespOffset);
1440
1441
1442 addUShort(domainLen);
1443 addUShort(domainLen);
1444
1445
1446 addULong(domainOffset);
1447
1448
1449 addUShort(userLen);
1450 addUShort(userLen);
1451
1452
1453 addULong(userOffset);
1454
1455
1456 addUShort(hostLen);
1457 addUShort(hostLen);
1458
1459
1460 addULong(hostOffset);
1461
1462
1463 addUShort(sessionKeyLen);
1464 addUShort(sessionKeyLen);
1465
1466
1467 addULong(sessionKeyOffset);
1468
1469
1470 addULong(
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497 type2Flags
1498 );
1499
1500
1501 addUShort(0x0105);
1502
1503 addULong(2600);
1504
1505 addUShort(0x0f00);
1506
1507 int micPosition = -1;
1508 if (computeMic) {
1509 micPosition = currentOutputPosition;
1510 currentOutputPosition += 16;
1511 }
1512
1513
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
1524
1525 if (computeMic) {
1526
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
1538
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;
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
1613
1614
1615
1616
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
1631
1632
1633 int curBufferPos = (int) (count & 63L);
1634 int inputIndex = 0;
1635 while (input.length - inputIndex + curBufferPos >= dataBuffer.length) {
1636
1637
1638
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
1648
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
1658
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
1663
1664 postBytes[0] = (byte) 0x80;
1665
1666 for (int i = 0; i < 8; i++) {
1667 postBytes[padLen + i] = (byte) ((count * 8) >>> (8 * i));
1668 }
1669
1670
1671 update(postBytes);
1672
1673
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
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
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
1779
1780
1781 private static class HMACMD5 {
1782 protected final byte[] ipad;
1783 protected final byte[] opad;
1784 @SuppressWarnings("java:S9428")
1785 protected final MessageDigest md5;
1786
1787 HMACMD5(final byte[] input) {
1788 byte[] key = input;
1789 md5 = getMD5();
1790
1791
1792 ipad = new byte[64];
1793 opad = new byte[64];
1794
1795 int keyLength = key.length;
1796 if (keyLength > 64) {
1797
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
1815 md5.reset();
1816 md5.update(ipad);
1817
1818 }
1819
1820
1821 byte[] getOutput() {
1822 final byte[] digest = md5.digest();
1823 md5.update(opad);
1824 return md5.digest(digest);
1825 }
1826
1827
1828 void update(final byte[] input) {
1829 md5.update(input);
1830 }
1831
1832
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
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
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 }