1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/http/http_auth_handler_ntlm.h"
16 #include "base/rand_util.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/sys_string_conversions.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "net/base/net_errors.h"
21 #include "net/base/net_util.h"
22 #include "net/base/zap.h"
23 #include "net/http/des.h"
24 #include "net/http/md4.h"
28 // Based on mozilla/security/manager/ssl/src/nsNTLMAuthModule.cpp,
32 // - The IS_BIG_ENDIAN code is not tested.
33 // - Enable the logging code or just delete it.
34 // - Delete or comment out the LM code, which hasn't been tested and isn't
37 /* ***** BEGIN LICENSE BLOCK *****
38 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
40 * The contents of this file are subject to the Mozilla Public License Version
41 * 1.1 (the "License"); you may not use this file except in compliance with
42 * the License. You may obtain a copy of the License at
43 * http://www.mozilla.org/MPL/
45 * Software distributed under the License is distributed on an "AS IS" basis,
46 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
47 * for the specific language governing rights and limitations under the
50 * The Original Code is Mozilla.
52 * The Initial Developer of the Original Code is IBM Corporation.
53 * Portions created by IBM Corporation are Copyright (C) 2003
54 * IBM Corporation. All Rights Reserved.
57 * Darin Fisher <darin@meer.net>
59 * Alternatively, the contents of this file may be used under the terms of
60 * either the GNU General Public License Version 2 or later (the "GPL"), or
61 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
62 * in which case the provisions of the GPL or the LGPL are applicable instead
63 * of those above. If you wish to allow use of your version of this file only
64 * under the terms of either the GPL or the LGPL, and not to allow others to
65 * use your version of this file under the terms of the MPL, indicate your
66 * decision by deleting the provisions above and replace them with the notice
67 * and other provisions required by the GPL or the LGPL. If you do not delete
68 * the provisions above, a recipient may use your version of this file under
69 * the terms of any one of the MPL, the GPL or the LGPL.
71 * ***** END LICENSE BLOCK ***** */
73 // Discover the endianness by testing processor architecture.
74 #if defined(ARCH_CPU_X86) || defined(ARCH_CPU_X86_64)\
75 || defined(ARCH_CPU_ARMEL) || defined(ARCH_CPU_MIPSEL)
76 #define IS_LITTLE_ENDIAN 1
78 #elif defined(ARCH_CPU_MIPSEB)
79 #define IS_BIG_ENDIAN 1
80 #undef IS_LITTLE_ENDIAN
82 #error "Unknown endianness"
85 #define NTLM_LOG(x) ((void) 0)
87 //-----------------------------------------------------------------------------
88 // This file contains a cross-platform NTLM authentication implementation. It
89 // is based on documentation from: http://davenport.sourceforge.net/ntlm.html
90 //-----------------------------------------------------------------------------
93 NTLM_NegotiateUnicode = 0x00000001,
94 NTLM_NegotiateOEM = 0x00000002,
95 NTLM_RequestTarget = 0x00000004,
96 NTLM_Unknown1 = 0x00000008,
97 NTLM_NegotiateSign = 0x00000010,
98 NTLM_NegotiateSeal = 0x00000020,
99 NTLM_NegotiateDatagramStyle = 0x00000040,
100 NTLM_NegotiateLanManagerKey = 0x00000080,
101 NTLM_NegotiateNetware = 0x00000100,
102 NTLM_NegotiateNTLMKey = 0x00000200,
103 NTLM_Unknown2 = 0x00000400,
104 NTLM_Unknown3 = 0x00000800,
105 NTLM_NegotiateDomainSupplied = 0x00001000,
106 NTLM_NegotiateWorkstationSupplied = 0x00002000,
107 NTLM_NegotiateLocalCall = 0x00004000,
108 NTLM_NegotiateAlwaysSign = 0x00008000,
109 NTLM_TargetTypeDomain = 0x00010000,
110 NTLM_TargetTypeServer = 0x00020000,
111 NTLM_TargetTypeShare = 0x00040000,
112 NTLM_NegotiateNTLM2Key = 0x00080000,
113 NTLM_RequestInitResponse = 0x00100000,
114 NTLM_RequestAcceptResponse = 0x00200000,
115 NTLM_RequestNonNTSessionKey = 0x00400000,
116 NTLM_NegotiateTargetInfo = 0x00800000,
117 NTLM_Unknown4 = 0x01000000,
118 NTLM_Unknown5 = 0x02000000,
119 NTLM_Unknown6 = 0x04000000,
120 NTLM_Unknown7 = 0x08000000,
121 NTLM_Unknown8 = 0x10000000,
122 NTLM_Negotiate128 = 0x20000000,
123 NTLM_NegotiateKeyExchange = 0x40000000,
124 NTLM_Negotiate56 = 0x80000000
127 // We send these flags with our type 1 message.
129 NTLM_TYPE1_FLAGS = (NTLM_NegotiateUnicode |
132 NTLM_NegotiateNTLMKey |
133 NTLM_NegotiateAlwaysSign |
134 NTLM_NegotiateNTLM2Key)
137 static const char NTLM_SIGNATURE[] = "NTLMSSP";
138 static const char NTLM_TYPE1_MARKER[] = { 0x01, 0x00, 0x00, 0x00 };
139 static const char NTLM_TYPE2_MARKER[] = { 0x02, 0x00, 0x00, 0x00 };
140 static const char NTLM_TYPE3_MARKER[] = { 0x03, 0x00, 0x00, 0x00 };
143 NTLM_TYPE1_HEADER_LEN = 32,
144 NTLM_TYPE2_HEADER_LEN = 32,
145 NTLM_TYPE3_HEADER_LEN = 64,
154 //-----------------------------------------------------------------------------
156 // The return value of this function controls whether or not the LM hash will
157 // be included in response to a NTLM challenge.
159 // In Mozilla, this function returns the value of the boolean preference
160 // "network.ntlm.send-lm-response". By default, the preference is disabled
161 // since servers should almost never need the LM hash, and the LM hash is what
162 // makes NTLM authentication less secure. See
163 // https://bugzilla.mozilla.org/show_bug.cgi?id=250691 for further details.
165 // We just return a hardcoded false.
166 static bool SendLM() {
170 //-----------------------------------------------------------------------------
172 #define LogFlags(x) ((void) 0)
173 #define LogBuf(a, b, c) ((void) 0)
174 #define LogToken(a, b, c) ((void) 0)
176 //-----------------------------------------------------------------------------
178 // Byte order swapping.
179 #define SWAP16(x) ((((x) & 0xff) << 8) | (((x) >> 8) & 0xff))
180 #define SWAP32(x) ((SWAP16((x) & 0xffff) << 16) | (SWAP16((x) >> 16)))
182 static void* WriteBytes(void* buf, const void* data, uint32 data_len) {
183 memcpy(buf, data, data_len);
184 return static_cast<char*>(buf) + data_len;
187 static void* WriteDWORD(void* buf, uint32 dword) {
189 // NTLM uses little endian on the wire.
190 dword = SWAP32(dword);
192 return WriteBytes(buf, &dword, sizeof(dword));
195 static void* WriteSecBuf(void* buf, uint16 length, uint32 offset) {
197 length = SWAP16(length);
198 offset = SWAP32(offset);
200 buf = WriteBytes(buf, &length, sizeof(length));
201 buf = WriteBytes(buf, &length, sizeof(length));
202 buf = WriteBytes(buf, &offset, sizeof(offset));
208 * WriteUnicodeLE copies a unicode string from one buffer to another. The
209 * resulting unicode string is in little-endian format. The input string is
210 * assumed to be in the native endianness of the local machine. It is safe
211 * to pass the same buffer as both input and output, which is a handy way to
212 * convert the unicode buffer to little-endian on big-endian platforms.
214 static void* WriteUnicodeLE(void* buf, const char16* str, uint32 str_len) {
215 // Convert input string from BE to LE.
216 uint8* cursor = static_cast<uint8*>(buf);
217 const uint8* input = reinterpret_cast<const uint8*>(str);
218 for (uint32 i = 0; i < str_len; ++i, input += 2, cursor += 2) {
219 // Allow for the case where |buf == str|.
220 uint8 temp = input[0];
221 cursor[0] = input[1];
228 static uint16 ReadUint16(const uint8*& buf) {
229 uint16 x = (static_cast<uint16>(buf[0])) |
230 (static_cast<uint16>(buf[1]) << 8);
235 static uint32 ReadUint32(const uint8*& buf) {
236 uint32 x = (static_cast<uint32>(buf[0])) |
237 (static_cast<uint32>(buf[1]) << 8) |
238 (static_cast<uint32>(buf[2]) << 16) |
239 (static_cast<uint32>(buf[3]) << 24);
244 //-----------------------------------------------------------------------------
246 // LM_Hash computes the LM hash of the given password.
251 // 16-byte result buffer
253 // Note: This function is not being used because our SendLM() function always
255 static void LM_Hash(const base::string16& password, uint8* hash) {
256 static const uint8 LM_MAGIC[] = "KGS!@#$%";
258 // Convert password to OEM character set. We'll just use the native
259 // filesystem charset.
260 std::string passbuf = base::SysWideToNativeMB(UTF16ToWide(password));
261 StringToUpperASCII(&passbuf);
262 passbuf.resize(14, '\0');
265 DESMakeKey(reinterpret_cast<const uint8*>(passbuf.data()) , k1);
266 DESMakeKey(reinterpret_cast<const uint8*>(passbuf.data()) + 7, k2);
269 // Use password keys to hash LM magic string twice.
270 DESEncrypt(k1, LM_MAGIC, hash);
271 DESEncrypt(k2, LM_MAGIC, hash + 8);
274 // NTLM_Hash computes the NTLM hash of the given password.
277 // null-terminated unicode password.
279 // 16-byte result buffer
280 static void NTLM_Hash(const base::string16& password, uint8* hash) {
282 uint32 len = password.length();
285 passbuf = static_cast<uint8*>(malloc(len * 2));
286 WriteUnicodeLE(passbuf, password.data(), len);
287 weak_crypto::MD4Sum(passbuf, len * 2, hash);
289 ZapBuf(passbuf, len * 2);
292 weak_crypto::MD4Sum(reinterpret_cast<const uint8*>(password.data()),
293 password.length() * 2, hash);
297 //-----------------------------------------------------------------------------
299 // LM_Response generates the LM response given a 16-byte password hash and the
300 // challenge from the Type-2 message.
303 // 16-byte password hash
305 // 8-byte challenge from Type-2 message
307 // 24-byte buffer to contain the LM response upon return
308 static void LM_Response(const uint8* hash,
309 const uint8* challenge,
311 uint8 keybytes[21], k1[8], k2[8], k3[8];
313 memcpy(keybytes, hash, 16);
314 ZapBuf(keybytes + 16, 5);
316 DESMakeKey(keybytes , k1);
317 DESMakeKey(keybytes + 7, k2);
318 DESMakeKey(keybytes + 14, k3);
320 DESEncrypt(k1, challenge, response);
321 DESEncrypt(k2, challenge, response + 8);
322 DESEncrypt(k3, challenge, response + 16);
325 //-----------------------------------------------------------------------------
327 // Returns OK or a network error code.
328 static int GenerateType1Msg(void** out_buf, uint32* out_len) {
330 // Verify that buf_len is sufficient.
332 *out_len = NTLM_TYPE1_HEADER_LEN;
333 *out_buf = malloc(*out_len);
335 return ERR_OUT_OF_MEMORY;
338 // Write out type 1 message.
340 void* cursor = *out_buf;
343 cursor = WriteBytes(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
346 cursor = WriteBytes(cursor, NTLM_TYPE1_MARKER, sizeof(NTLM_TYPE1_MARKER));
349 cursor = WriteDWORD(cursor, NTLM_TYPE1_FLAGS);
352 // NOTE: It is common for the domain and workstation fields to be empty.
353 // This is true of Win2k clients, and my guess is that there is
354 // little utility to sending these strings before the charset has
355 // been negotiated. We follow suite -- anyways, it doesn't hurt
356 // to save some bytes on the wire ;-)
359 // 16 : supplied domain security buffer (empty)
360 cursor = WriteSecBuf(cursor, 0, 0);
362 // 24 : supplied workstation security buffer (empty)
363 cursor = WriteSecBuf(cursor, 0, 0);
369 uint32 flags; // NTLM_Xxx bitwise combination
370 uint8 challenge[8]; // 8 byte challenge
371 const void* target; // target string (type depends on flags)
372 uint32 target_len; // target length in bytes
375 // Returns OK or a network error code.
376 // TODO(wtc): This function returns ERR_UNEXPECTED when the input message is
377 // invalid. We should return a better error code.
378 static int ParseType2Msg(const void* in_buf, uint32 in_len, Type2Msg* msg) {
379 // Make sure in_buf is long enough to contain a meaningful type2 msg.
381 // 0 NTLMSSP Signature
382 // 8 NTLM Message Type
386 // 32 end of header, start of optional data blocks
388 if (in_len < NTLM_TYPE2_HEADER_LEN)
389 return ERR_UNEXPECTED;
391 const uint8* cursor = (const uint8*) in_buf;
393 // verify NTLMSSP signature
394 if (memcmp(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)) != 0)
395 return ERR_UNEXPECTED;
396 cursor += sizeof(NTLM_SIGNATURE);
398 // verify Type-2 marker
399 if (memcmp(cursor, NTLM_TYPE2_MARKER, sizeof(NTLM_TYPE2_MARKER)) != 0)
400 return ERR_UNEXPECTED;
401 cursor += sizeof(NTLM_TYPE2_MARKER);
403 // read target name security buffer
404 uint32 target_len = ReadUint16(cursor);
405 ReadUint16(cursor); // discard next 16-bit value
406 uint32 offset = ReadUint32(cursor); // get offset from in_buf
409 // Check the offset / length combo is in range of the input buffer, including
410 // integer overflow checking.
411 if (offset + target_len > offset && offset + target_len <= in_len) {
412 msg->target_len = target_len;
413 msg->target = ((const uint8*) in_buf) + offset;
417 msg->flags = ReadUint32(cursor);
420 memcpy(msg->challenge, cursor, sizeof(msg->challenge));
421 cursor += sizeof(msg->challenge);
423 NTLM_LOG(("NTLM type 2 message:\n"));
424 LogBuf("target", (const uint8*) msg->target, msg->target_len);
425 LogBuf("flags", (const uint8*) &msg->flags, 4);
426 LogFlags(msg->flags);
427 LogBuf("challenge", msg->challenge, sizeof(msg->challenge));
429 // We currently do not implement LMv2/NTLMv2 or NTLM2 responses,
430 // so we can ignore target information. We may want to enable
431 // support for these alternate mechanisms in the future.
435 static void GenerateRandom(uint8* output, size_t n) {
436 for (size_t i = 0; i < n; ++i)
437 output[i] = base::RandInt(0, 255);
440 // Returns OK or a network error code.
441 static int GenerateType3Msg(const base::string16& domain,
442 const base::string16& username,
443 const base::string16& password,
444 const std::string& hostname,
445 const void* rand_8_bytes,
450 // in_buf contains Type-2 msg (the challenge) from server.
455 rv = ParseType2Msg(in_buf, in_len, &msg);
459 bool unicode = (msg.flags & NTLM_NegotiateUnicode) != 0;
461 // Temporary buffers for unicode strings
463 base::string16 ucs_domain_buf, ucs_user_buf;
465 base::string16 ucs_host_buf;
466 // Temporary buffers for oem strings
467 std::string oem_domain_buf, oem_user_buf;
468 // Pointers and lengths for the string buffers; encoding is unicode if
469 // the "negotiate unicode" flag was set in the Type-2 message.
470 const void* domain_ptr;
471 const void* user_ptr;
472 const void* host_ptr;
473 uint32 domain_len, user_len, host_len;
480 ucs_domain_buf = domain;
481 domain_ptr = ucs_domain_buf.data();
482 domain_len = ucs_domain_buf.length() * 2;
483 WriteUnicodeLE(const_cast<void*>(domain_ptr), (const char16*) domain_ptr,
484 ucs_domain_buf.length());
486 domain_ptr = domain.data();
487 domain_len = domain.length() * 2;
490 oem_domain_buf = base::SysWideToNativeMB(UTF16ToWide(domain));
491 domain_ptr = oem_domain_buf.data();
492 domain_len = oem_domain_buf.length();
500 ucs_user_buf = username;
501 user_ptr = ucs_user_buf.data();
502 user_len = ucs_user_buf.length() * 2;
503 WriteUnicodeLE(const_cast<void*>(user_ptr), (const char16*) user_ptr,
504 ucs_user_buf.length());
506 user_ptr = username.data();
507 user_len = username.length() * 2;
510 oem_user_buf = base::SysWideToNativeMB(UTF16ToWide(username));
511 user_ptr = oem_user_buf.data();
512 user_len = oem_user_buf.length();
516 // Get workstation name (use local machine's hostname).
519 // hostname is ASCII, so we can do a simple zero-pad expansion:
520 ucs_host_buf.assign(hostname.begin(), hostname.end());
521 host_ptr = ucs_host_buf.data();
522 host_len = ucs_host_buf.length() * 2;
524 WriteUnicodeLE(const_cast<void*>(host_ptr), (const char16*) host_ptr,
525 ucs_host_buf.length());
528 host_ptr = hostname.data();
529 host_len = hostname.length();
533 // Now that we have generated all of the strings, we can allocate out_buf.
535 *out_len = NTLM_TYPE3_HEADER_LEN + host_len + domain_len + user_len +
536 LM_RESP_LEN + NTLM_RESP_LEN;
537 *out_buf = malloc(*out_len);
539 return ERR_OUT_OF_MEMORY;
542 // Next, we compute the LM and NTLM responses.
544 uint8 lm_resp[LM_RESP_LEN];
545 uint8 ntlm_resp[NTLM_RESP_LEN];
546 uint8 ntlm_hash[NTLM_HASH_LEN];
547 if (msg.flags & NTLM_NegotiateNTLM2Key) {
548 // compute NTLM2 session response
549 base::MD5Digest session_hash;
552 memcpy(lm_resp, rand_8_bytes, 8);
553 memset(lm_resp + 8, 0, LM_RESP_LEN - 8);
555 memcpy(temp, msg.challenge, 8);
556 memcpy(temp + 8, lm_resp, 8);
557 base::MD5Sum(temp, 16, &session_hash);
559 NTLM_Hash(password, ntlm_hash);
560 LM_Response(ntlm_hash, session_hash.a, ntlm_resp);
562 NTLM_Hash(password, ntlm_hash);
563 LM_Response(ntlm_hash, msg.challenge, ntlm_resp);
566 uint8 lm_hash[LM_HASH_LEN];
567 LM_Hash(password, lm_hash);
568 LM_Response(lm_hash, msg.challenge, lm_resp);
570 // According to http://davenport.sourceforge.net/ntlm.html#ntlmVersion2,
571 // the correct way to not send the LM hash is to send the NTLM hash twice
572 // in both the LM and NTLM response fields.
573 LM_Response(ntlm_hash, msg.challenge, lm_resp);
578 // Finally, we assemble the Type-3 msg :-)
580 void* cursor = *out_buf;
584 cursor = WriteBytes(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
587 cursor = WriteBytes(cursor, NTLM_TYPE3_MARKER, sizeof(NTLM_TYPE3_MARKER));
589 // 12 : LM response sec buf
590 offset = NTLM_TYPE3_HEADER_LEN + domain_len + user_len + host_len;
591 cursor = WriteSecBuf(cursor, LM_RESP_LEN, offset);
592 memcpy(static_cast<uint8*>(*out_buf) + offset, lm_resp, LM_RESP_LEN);
594 // 20 : NTLM response sec buf
595 offset += LM_RESP_LEN;
596 cursor = WriteSecBuf(cursor, NTLM_RESP_LEN, offset);
597 memcpy(static_cast<uint8*>(*out_buf) + offset, ntlm_resp, NTLM_RESP_LEN);
599 // 28 : domain name sec buf
600 offset = NTLM_TYPE3_HEADER_LEN;
601 cursor = WriteSecBuf(cursor, domain_len, offset);
602 memcpy(static_cast<uint8*>(*out_buf) + offset, domain_ptr, domain_len);
604 // 36 : user name sec buf
605 offset += domain_len;
606 cursor = WriteSecBuf(cursor, user_len, offset);
607 memcpy(static_cast<uint8*>(*out_buf) + offset, user_ptr, user_len);
609 // 44 : workstation (host) name sec buf
611 cursor = WriteSecBuf(cursor, host_len, offset);
612 memcpy(static_cast<uint8*>(*out_buf) + offset, host_ptr, host_len);
614 // 52 : session key sec buf (not used)
615 cursor = WriteSecBuf(cursor, 0, 0);
617 // 60 : negotiated flags
618 cursor = WriteDWORD(cursor, msg.flags & NTLM_TYPE1_FLAGS);
623 // NTLM authentication is specified in "NTLM Over HTTP Protocol Specification"
627 HttpAuthHandlerNTLM::GenerateRandomProc
628 HttpAuthHandlerNTLM::generate_random_proc_ = GenerateRandom;
631 HttpAuthHandlerNTLM::HostNameProc
632 HttpAuthHandlerNTLM::get_host_name_proc_ = GetHostName;
634 HttpAuthHandlerNTLM::HttpAuthHandlerNTLM() {
637 bool HttpAuthHandlerNTLM::NeedsIdentity() {
638 // This gets called for each round-trip. Only require identity on
639 // the first call (when auth_data_ is empty). On subsequent calls,
640 // we use the initially established identity.
641 return auth_data_.empty();
644 bool HttpAuthHandlerNTLM::AllowsDefaultCredentials() {
645 // Default credentials are not supported in the portable implementation of
646 // NTLM, but are supported in the SSPI implementation.
650 int HttpAuthHandlerNTLM::InitializeBeforeFirstChallenge() {
654 HttpAuthHandlerNTLM::~HttpAuthHandlerNTLM() {
659 HttpAuthHandlerNTLM::GenerateRandomProc
660 HttpAuthHandlerNTLM::SetGenerateRandomProc(
661 GenerateRandomProc proc) {
662 GenerateRandomProc old_proc = generate_random_proc_;
663 generate_random_proc_ = proc;
668 HttpAuthHandlerNTLM::HostNameProc HttpAuthHandlerNTLM::SetHostNameProc(
670 HostNameProc old_proc = get_host_name_proc_;
671 get_host_name_proc_ = proc;
675 HttpAuthHandlerNTLM::Factory::Factory() {
678 HttpAuthHandlerNTLM::Factory::~Factory() {
681 int HttpAuthHandlerNTLM::GetNextToken(const void* in_token,
684 uint32* out_token_len) {
687 // If in_token is non-null, then assume it contains a type 2 message...
689 LogToken("in-token", in_token, in_token_len);
690 std::string hostname = get_host_name_proc_();
691 if (hostname.empty())
692 return ERR_UNEXPECTED;
694 generate_random_proc_(rand_buf, 8);
695 rv = GenerateType3Msg(domain_,
696 credentials_.username(), credentials_.password(),
698 in_token, in_token_len, out_token, out_token_len);
700 rv = GenerateType1Msg(out_token, out_token_len);
704 LogToken("out-token", *out_token, *out_token_len);
709 int HttpAuthHandlerNTLM::Factory::CreateAuthHandler(
710 HttpAuth::ChallengeTokenizer* challenge,
711 HttpAuth::Target target,
714 int digest_nonce_count,
715 const BoundNetLog& net_log,
716 scoped_ptr<HttpAuthHandler>* handler) {
717 if (reason == CREATE_PREEMPTIVE)
718 return ERR_UNSUPPORTED_AUTH_SCHEME;
719 // TODO(cbentzel): Move towards model of parsing in the factory
720 // method and only constructing when valid.
721 // NOTE: Default credentials are not supported for the portable implementation
723 scoped_ptr<HttpAuthHandler> tmp_handler(new HttpAuthHandlerNTLM);
724 if (!tmp_handler->InitFromChallenge(challenge, target, origin, net_log))
725 return ERR_INVALID_RESPONSE;
726 handler->swap(tmp_handler);