UNPKG

17.7 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2013 Sam Decrock https://github.com/SamDecrock/
3 * All rights reserved.
4 *
5 * This source code is licensed under the MIT license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9var crypto = require('crypto');
10var jsmd4 = require("js-md4");
11var desjs = require("des.js");
12
13var flags = {
14 NTLM_NegotiateUnicode : 0x00000001,
15 NTLM_NegotiateOEM : 0x00000002,
16 NTLM_RequestTarget : 0x00000004,
17 NTLM_Unknown9 : 0x00000008,
18 NTLM_NegotiateSign : 0x00000010,
19 NTLM_NegotiateSeal : 0x00000020,
20 NTLM_NegotiateDatagram : 0x00000040,
21 NTLM_NegotiateLanManagerKey : 0x00000080,
22 NTLM_Unknown8 : 0x00000100,
23 NTLM_NegotiateNTLM : 0x00000200,
24 NTLM_NegotiateNTOnly : 0x00000400,
25 NTLM_Anonymous : 0x00000800,
26 NTLM_NegotiateOemDomainSupplied : 0x00001000,
27 NTLM_NegotiateOemWorkstationSupplied : 0x00002000,
28 NTLM_Unknown6 : 0x00004000,
29 NTLM_NegotiateAlwaysSign : 0x00008000,
30 NTLM_TargetTypeDomain : 0x00010000,
31 NTLM_TargetTypeServer : 0x00020000,
32 NTLM_TargetTypeShare : 0x00040000,
33 NTLM_NegotiateExtendedSecurity : 0x00080000,
34 NTLM_NegotiateIdentify : 0x00100000,
35 NTLM_Unknown5 : 0x00200000,
36 NTLM_RequestNonNTSessionKey : 0x00400000,
37 NTLM_NegotiateTargetInfo : 0x00800000,
38 NTLM_Unknown4 : 0x01000000,
39 NTLM_NegotiateVersion : 0x02000000,
40 NTLM_Unknown3 : 0x04000000,
41 NTLM_Unknown2 : 0x08000000,
42 NTLM_Unknown1 : 0x10000000,
43 NTLM_Negotiate128 : 0x20000000,
44 NTLM_NegotiateKeyExchange : 0x40000000,
45 NTLM_Negotiate56 : 0x80000000
46};
47var typeflags = {
48 NTLM_TYPE1_FLAGS : flags.NTLM_NegotiateUnicode
49 + flags.NTLM_NegotiateOEM
50 + flags.NTLM_RequestTarget
51 + flags.NTLM_NegotiateNTLM
52 + flags.NTLM_NegotiateOemDomainSupplied
53 + flags.NTLM_NegotiateOemWorkstationSupplied
54 + flags.NTLM_NegotiateAlwaysSign
55 + flags.NTLM_NegotiateExtendedSecurity
56 + flags.NTLM_NegotiateVersion
57 + flags.NTLM_Negotiate128
58 + flags.NTLM_Negotiate56,
59
60 NTLM_TYPE2_FLAGS : flags.NTLM_NegotiateUnicode
61 + flags.NTLM_RequestTarget
62 + flags.NTLM_NegotiateNTLM
63 + flags.NTLM_NegotiateAlwaysSign
64 + flags.NTLM_NegotiateExtendedSecurity
65 + flags.NTLM_NegotiateTargetInfo
66 + flags.NTLM_NegotiateVersion
67 + flags.NTLM_Negotiate128
68 + flags.NTLM_Negotiate56
69};
70
71function createType1Message(options){
72 var domain = escape(options.domain.toUpperCase());
73 var workstation = escape(options.workstation.toUpperCase());
74 var protocol = 'NTLMSSP\0';
75
76 var BODY_LENGTH = 40;
77
78 var type1flags = typeflags.NTLM_TYPE1_FLAGS;
79 if(!domain || domain === '')
80 type1flags = type1flags - flags.NTLM_NegotiateOemDomainSupplied;
81
82 var pos = 0;
83 var buf = Buffer.alloc(BODY_LENGTH + domain.length + workstation.length);
84
85
86 buf.write(protocol, pos, protocol.length); pos += protocol.length; // protocol
87 buf.writeUInt32LE(1, pos); pos += 4; // type 1
88 buf.writeUInt32LE(type1flags, pos); pos += 4; // TYPE1 flag
89
90 buf.writeUInt16LE(domain.length, pos); pos += 2; // domain length
91 buf.writeUInt16LE(domain.length, pos); pos += 2; // domain max length
92 buf.writeUInt32LE(BODY_LENGTH + workstation.length, pos); pos += 4; // domain buffer offset
93
94 buf.writeUInt16LE(workstation.length, pos); pos += 2; // workstation length
95 buf.writeUInt16LE(workstation.length, pos); pos += 2; // workstation max length
96 buf.writeUInt32LE(BODY_LENGTH, pos); pos += 4; // workstation buffer offset
97
98 buf.writeUInt8(5, pos); pos += 1; //ProductMajorVersion
99 buf.writeUInt8(1, pos); pos += 1; //ProductMinorVersion
100 buf.writeUInt16LE(2600, pos); pos += 2; //ProductBuild
101
102 buf.writeUInt8(0 , pos); pos += 1; //VersionReserved1
103 buf.writeUInt8(0 , pos); pos += 1; //VersionReserved2
104 buf.writeUInt8(0 , pos); pos += 1; //VersionReserved3
105 buf.writeUInt8(15, pos); pos += 1; //NTLMRevisionCurrent
106
107
108 // length checks is to fix issue #46 and possibly #57
109 if(workstation.length !=0) buf.write(workstation, pos, workstation.length, 'ascii'); pos += workstation.length; // workstation string
110 if(domain.length !=0) buf.write(domain , pos, domain.length , 'ascii'); pos += domain.length; // domain string
111
112 return 'NTLM ' + buf.toString('base64');
113}
114
115function parseType2Message(rawmsg, callback){
116 var match = rawmsg.match(/NTLM (.+)?/);
117 if(!match || !match[1]) {
118 callback(new Error("Couldn't find NTLM in the message type2 comming from the server"));
119 return null;
120 }
121
122 var buf = Buffer.from(match[1], 'base64');
123
124 var msg = {};
125
126 msg.signature = buf.slice(0, 8);
127 msg.type = buf.readInt16LE(8);
128
129 if(msg.type != 2) {
130 callback(new Error("Server didn't return a type 2 message"));
131 return null;
132 }
133
134 msg.targetNameLen = buf.readInt16LE(12);
135 msg.targetNameMaxLen = buf.readInt16LE(14);
136 msg.targetNameOffset = buf.readInt32LE(16);
137 msg.targetName = buf.slice(msg.targetNameOffset, msg.targetNameOffset + msg.targetNameMaxLen);
138
139 msg.negotiateFlags = buf.readInt32LE(20);
140 msg.serverChallenge = buf.slice(24, 32);
141 msg.reserved = buf.slice(32, 40);
142
143 if(msg.negotiateFlags & flags.NTLM_NegotiateTargetInfo){
144 msg.targetInfoLen = buf.readInt16LE(40);
145 msg.targetInfoMaxLen = buf.readInt16LE(42);
146 msg.targetInfoOffset = buf.readInt32LE(44);
147 msg.targetInfo = buf.slice(msg.targetInfoOffset, msg.targetInfoOffset + msg.targetInfoLen);
148 }
149 return msg;
150}
151
152function createType3Message(msg2, options){
153 var nonce = msg2.serverChallenge;
154 var username = options.username;
155 var password = options.password;
156 var lm_password = options.lm_password;
157 var nt_password = options.nt_password;
158 var negotiateFlags = msg2.negotiateFlags;
159
160 var isUnicode = negotiateFlags & flags.NTLM_NegotiateUnicode;
161 var isNegotiateExtendedSecurity = negotiateFlags & flags.NTLM_NegotiateExtendedSecurity;
162
163 var BODY_LENGTH = 72;
164
165 var domainName = escape(options.domain.toUpperCase());
166 var workstation = escape(options.workstation.toUpperCase());
167
168 var workstationBytes, domainNameBytes, usernameBytes, encryptedRandomSessionKeyBytes;
169
170 var encryptedRandomSessionKey = "";
171 if(isUnicode){
172 workstationBytes = Buffer.from(workstation, 'utf16le');
173 domainNameBytes = Buffer.from(domainName, 'utf16le');
174 usernameBytes = Buffer.from(username, 'utf16le');
175 encryptedRandomSessionKeyBytes = Buffer.from(encryptedRandomSessionKey, 'utf16le');
176 }else{
177 workstationBytes = Buffer.from(workstation, 'ascii');
178 domainNameBytes = Buffer.from(domainName, 'ascii');
179 usernameBytes = Buffer.from(username, 'ascii');
180 encryptedRandomSessionKeyBytes = Buffer.from(encryptedRandomSessionKey, 'ascii');
181 }
182
183 var lmChallengeResponse = calc_resp((lm_password!=null)?lm_password:create_LM_hashed_password_v1(password), nonce);
184 var ntChallengeResponse = calc_resp((nt_password!=null)?nt_password:create_NT_hashed_password_v1(password), nonce);
185
186 if(isNegotiateExtendedSecurity){
187 /*
188 * NTLMv2 extended security is enabled. While this technically can mean NTLMv2 extended security with NTLMv1 protocol,
189 * servers that support extended security likely also support NTLMv2, so use NTLMv2.
190 * This is also how curl implements NTLMv2 "detection".
191 * By using NTLMv2, this supports communication with servers that forbid the use of NTLMv1 (e.g. via windows policies)
192 *
193 * However, the target info is needed to construct the NTLMv2 response so if it can't be negotiated,
194 * fall back to NTLMv1 with NTLMv2 extended security.
195 */
196 var pwhash = (nt_password!=null)?nt_password:create_NT_hashed_password_v1(password);
197 var clientChallenge = "";
198 for(var i=0; i < 8; i++){
199 clientChallenge += String.fromCharCode( Math.floor(Math.random()*256) );
200 }
201 var clientChallengeBytes = Buffer.from(clientChallenge, 'ascii');
202 var challenges = msg2.targetInfo
203 ? calc_ntlmv2_resp(pwhash, username, domainName, msg2.targetInfo, nonce, clientChallengeBytes)
204 : ntlm2sr_calc_resp(pwhash, nonce, clientChallengeBytes);
205 lmChallengeResponse = challenges.lmChallengeResponse;
206 ntChallengeResponse = challenges.ntChallengeResponse;
207 }
208
209 var signature = 'NTLMSSP\0';
210
211 var pos = 0;
212 var buf = Buffer.alloc(BODY_LENGTH + domainNameBytes.length + usernameBytes.length + workstationBytes.length + lmChallengeResponse.length + ntChallengeResponse.length + encryptedRandomSessionKeyBytes.length);
213
214 buf.write(signature, pos, signature.length); pos += signature.length;
215 buf.writeUInt32LE(3, pos); pos += 4; // type 1
216
217 buf.writeUInt16LE(lmChallengeResponse.length, pos); pos += 2; // LmChallengeResponseLen
218 buf.writeUInt16LE(lmChallengeResponse.length, pos); pos += 2; // LmChallengeResponseMaxLen
219 buf.writeUInt32LE(BODY_LENGTH + domainNameBytes.length + usernameBytes.length + workstationBytes.length, pos); pos += 4; // LmChallengeResponseOffset
220
221 buf.writeUInt16LE(ntChallengeResponse.length, pos); pos += 2; // NtChallengeResponseLen
222 buf.writeUInt16LE(ntChallengeResponse.length, pos); pos += 2; // NtChallengeResponseMaxLen
223 buf.writeUInt32LE(BODY_LENGTH + domainNameBytes.length + usernameBytes.length + workstationBytes.length + lmChallengeResponse.length, pos); pos += 4; // NtChallengeResponseOffset
224
225 buf.writeUInt16LE(domainNameBytes.length, pos); pos += 2; // DomainNameLen
226 buf.writeUInt16LE(domainNameBytes.length, pos); pos += 2; // DomainNameMaxLen
227 buf.writeUInt32LE(BODY_LENGTH, pos); pos += 4; // DomainNameOffset
228
229 buf.writeUInt16LE(usernameBytes.length, pos); pos += 2; // UserNameLen
230 buf.writeUInt16LE(usernameBytes.length, pos); pos += 2; // UserNameMaxLen
231 buf.writeUInt32LE(BODY_LENGTH + domainNameBytes.length, pos); pos += 4; // UserNameOffset
232
233 buf.writeUInt16LE(workstationBytes.length, pos); pos += 2; // WorkstationLen
234 buf.writeUInt16LE(workstationBytes.length, pos); pos += 2; // WorkstationMaxLen
235 buf.writeUInt32LE(BODY_LENGTH + domainNameBytes.length + usernameBytes.length, pos); pos += 4; // WorkstationOffset
236
237 buf.writeUInt16LE(encryptedRandomSessionKeyBytes.length, pos); pos += 2; // EncryptedRandomSessionKeyLen
238 buf.writeUInt16LE(encryptedRandomSessionKeyBytes.length, pos); pos += 2; // EncryptedRandomSessionKeyMaxLen
239 buf.writeUInt32LE(BODY_LENGTH + domainNameBytes.length + usernameBytes.length + workstationBytes.length + lmChallengeResponse.length + ntChallengeResponse.length, pos); pos += 4; // EncryptedRandomSessionKeyOffset
240
241 // Fix #98
242 var flagsToWrite = isUnicode
243 ? typeflags.NTLM_TYPE2_FLAGS
244 : typeflags.NTLM_TYPE2_FLAGS - flags.NTLM_NegotiateUnicode;
245 buf.writeUInt32LE(flagsToWrite , pos); pos += 4; // NegotiateFlags
246
247 buf.writeUInt8(5, pos); pos++; // ProductMajorVersion
248 buf.writeUInt8(1, pos); pos++; // ProductMinorVersion
249 buf.writeUInt16LE(2600, pos); pos += 2; // ProductBuild
250 buf.writeUInt8(0, pos); pos++; // VersionReserved1
251 buf.writeUInt8(0, pos); pos++; // VersionReserved2
252 buf.writeUInt8(0, pos); pos++; // VersionReserved3
253 buf.writeUInt8(15, pos); pos++; // NTLMRevisionCurrent
254
255 domainNameBytes.copy(buf, pos); pos += domainNameBytes.length;
256 usernameBytes.copy(buf, pos); pos += usernameBytes.length;
257 workstationBytes.copy(buf, pos); pos += workstationBytes.length;
258 lmChallengeResponse.copy(buf, pos); pos += lmChallengeResponse.length;
259 ntChallengeResponse.copy(buf, pos); pos += ntChallengeResponse.length;
260 encryptedRandomSessionKeyBytes.copy(buf, pos); pos += encryptedRandomSessionKeyBytes.length;
261
262 return 'NTLM ' + buf.toString('base64');
263}
264
265function create_LM_hashed_password_v1(password){
266 // fix the password length to 14 bytes
267 password = password.toUpperCase();
268 var passwordBytes = Buffer.from(password, 'ascii');
269
270 var passwordBytesPadded = Buffer.alloc(14);
271 passwordBytesPadded.fill("\0");
272 var sourceEnd = 14;
273 if(passwordBytes.length < 14) sourceEnd = passwordBytes.length;
274 passwordBytes.copy(passwordBytesPadded, 0, 0, sourceEnd);
275
276 // split into 2 parts of 7 bytes:
277 var firstPart = passwordBytesPadded.slice(0,7);
278 var secondPart = passwordBytesPadded.slice(7);
279
280 function encrypt(buf){
281 var key = insertZerosEvery7Bits(buf);
282 var des = desjs.DES.create({type: 'encrypt', key: key});
283 var magicKey = Buffer.from('KGS!@#$%', 'ascii'); // page 57 in [MS-NLMP]
284 var encrypted = des.update(magicKey);
285 return Buffer.from(encrypted);
286 }
287
288 var firstPartEncrypted = encrypt(firstPart);
289 var secondPartEncrypted = encrypt(secondPart);
290
291 return Buffer.concat([firstPartEncrypted, secondPartEncrypted]);
292}
293
294function insertZerosEvery7Bits(buf){
295 var binaryArray = bytes2binaryArray(buf);
296 var newBinaryArray = [];
297 for(var i=0; i<binaryArray.length; i++){
298 newBinaryArray.push(binaryArray[i]);
299
300 if((i+1)%7 === 0){
301 newBinaryArray.push(0);
302 }
303 }
304 return binaryArray2bytes(newBinaryArray);
305}
306
307function bytes2binaryArray(buf){
308 var hex2binary = {
309 0: [0,0,0,0],
310 1: [0,0,0,1],
311 2: [0,0,1,0],
312 3: [0,0,1,1],
313 4: [0,1,0,0],
314 5: [0,1,0,1],
315 6: [0,1,1,0],
316 7: [0,1,1,1],
317 8: [1,0,0,0],
318 9: [1,0,0,1],
319 A: [1,0,1,0],
320 B: [1,0,1,1],
321 C: [1,1,0,0],
322 D: [1,1,0,1],
323 E: [1,1,1,0],
324 F: [1,1,1,1]
325 };
326
327 var hexString = buf.toString('hex').toUpperCase();
328 var array = [];
329 for(var i=0; i<hexString.length; i++){
330 var hexchar = hexString.charAt(i);
331 array = array.concat(hex2binary[hexchar]);
332 }
333 return array;
334}
335
336function binaryArray2bytes(array){
337 var binary2hex = {
338 '0000': 0,
339 '0001': 1,
340 '0010': 2,
341 '0011': 3,
342 '0100': 4,
343 '0101': 5,
344 '0110': 6,
345 '0111': 7,
346 '1000': 8,
347 '1001': 9,
348 '1010': 'A',
349 '1011': 'B',
350 '1100': 'C',
351 '1101': 'D',
352 '1110': 'E',
353 '1111': 'F'
354 };
355
356 var bufArray = [];
357
358 for(var i=0; i<array.length; i +=8 ){
359 if((i+7) > array.length)
360 break;
361
362 var binString1 = '' + array[i] + '' + array[i+1] + '' + array[i+2] + '' + array[i+3];
363 var binString2 = '' + array[i+4] + '' + array[i+5] + '' + array[i+6] + '' + array[i+7];
364 var hexchar1 = binary2hex[binString1];
365 var hexchar2 = binary2hex[binString2];
366
367 var buf = Buffer.from(hexchar1 + '' + hexchar2, 'hex');
368 bufArray.push(buf);
369 }
370
371 return Buffer.concat(bufArray);
372}
373
374function create_NT_hashed_password_v1(password){
375 var buf = Buffer.from(password, 'utf16le');
376 var md4 = jsmd4.create();
377 md4.update(buf);
378 return Buffer.from(md4.digest());
379}
380
381function calc_resp(password_hash, server_challenge){
382 // padding with zeros to make the hash 21 bytes long
383 var passHashPadded = Buffer.alloc(21);
384 passHashPadded.fill("\0");
385 password_hash.copy(passHashPadded, 0, 0, password_hash.length);
386
387 var resArray = [];
388
389 var des = desjs.DES.create({type: 'encrypt', key: insertZerosEvery7Bits(passHashPadded.slice(0,7))});
390 resArray.push( Buffer.from(des.update(server_challenge.slice(0,8))) );
391
392 des = desjs.DES.create({type: 'encrypt', key: insertZerosEvery7Bits(passHashPadded.slice(7,14))});
393 resArray.push( Buffer.from(des.update(server_challenge.slice(0,8))) );
394
395 des = desjs.DES.create({type: 'encrypt', key: insertZerosEvery7Bits(passHashPadded.slice(14,21))});
396 resArray.push( Buffer.from(des.update(server_challenge.slice(0,8))) );
397
398 return Buffer.concat(resArray);
399}
400
401function hmac_md5(key, data){
402 var hmac = crypto.createHmac('md5', key);
403 hmac.update(data);
404 return hmac.digest();
405}
406
407function ntlm2sr_calc_resp(responseKeyNT, serverChallenge, clientChallenge){
408 // padding with zeros to make the hash 16 bytes longer
409 var lmChallengeResponse = Buffer.alloc(clientChallenge.length + 16);
410 lmChallengeResponse.fill("\0");
411 clientChallenge.copy(lmChallengeResponse, 0, 0, clientChallenge.length);
412
413 var buf = Buffer.concat([serverChallenge, clientChallenge]);
414 var md5 = crypto.createHash('md5');
415 md5.update(buf);
416 var sess = md5.digest();
417 var ntChallengeResponse = calc_resp(responseKeyNT, sess.slice(0,8));
418
419 return {
420 lmChallengeResponse: lmChallengeResponse,
421 ntChallengeResponse: ntChallengeResponse
422 };
423}
424
425function calc_ntlmv2_resp(pwhash, username, domain, targetInfo, serverChallenge, clientChallenge){
426 var responseKeyNTLM = NTOWFv2(pwhash, username, domain);
427
428 var lmV2ChallengeResponse = Buffer.concat([
429 hmac_md5(responseKeyNTLM, Buffer.concat([serverChallenge, clientChallenge])),
430 clientChallenge
431 ]);
432
433 // 11644473600000 = diff between 1970 and 1601
434 var now = Date.now();
435 var timestamp = ((BigInt(now) + BigInt(11644473600000)) * BigInt(10000)); // we need BigInt to be able to write it to a buffer
436 var timestampBuffer = Buffer.alloc(8);
437 timestampBuffer.writeBigUInt64LE(timestamp);
438
439 var zero32Bit = Buffer.alloc(4, 0)
440 var temp = Buffer.concat([
441 // Version
442 Buffer.from([0x01, 0x01, 0x00, 0x00]),
443 zero32Bit,
444 timestampBuffer,
445 clientChallenge,
446 zero32Bit,
447 targetInfo,
448 zero32Bit
449 ]);
450 var proofString = hmac_md5(responseKeyNTLM, Buffer.concat([serverChallenge, temp]));
451 var ntV2ChallengeResponse = Buffer.concat([proofString, temp]);
452
453 return {
454 lmChallengeResponse: lmV2ChallengeResponse,
455 ntChallengeResponse: ntV2ChallengeResponse
456 };
457}
458
459function NTOWFv2(pwhash, user, domain){
460 return hmac_md5(pwhash, Buffer.from(user.toUpperCase() + domain, 'utf16le'));
461}
462
463exports.createType1Message = createType1Message;
464exports.parseType2Message = parseType2Message;
465exports.createType3Message = createType3Message;
466exports.create_NT_hashed_password = create_NT_hashed_password_v1;
467exports.create_LM_hashed_password = create_LM_hashed_password_v1;
468
469
470
471