Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / net / http / http_auth_handler_ntlm_portable.cc
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.
4
5 #include "net/http/http_auth_handler_ntlm.h"
6
7 #include <stdlib.h>
8 // For gethostname
9 #if defined(OS_POSIX)
10 #include <unistd.h>
11 #elif defined(OS_WIN)
12 #include <winsock2.h>
13 #endif
14
15 #include "base/md5.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"
25
26 namespace net {
27
28 // Based on mozilla/security/manager/ssl/src/nsNTLMAuthModule.cpp,
29 // CVS rev. 1.14.
30 //
31 // TODO(wtc):
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
35 //   being used.
36
37 /* ***** BEGIN LICENSE BLOCK *****
38  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
39  *
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/
44  *
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
48  * License.
49  *
50  * The Original Code is Mozilla.
51  *
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.
55  *
56  * Contributor(s):
57  *   Darin Fisher <darin@meer.net>
58  *
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.
70  *
71  * ***** END LICENSE BLOCK ***** */
72
73 #if defined(ARCH_CPU_LITTLE_ENDIAN)
74 #define IS_LITTLE_ENDIAN 1
75 #undef  IS_BIG_ENDIAN
76 #elif defined(ARCH_CPU_BIG_ENDIAN)
77 #define IS_BIG_ENDIAN 1
78 #undef  IS_LITTLE_ENDIAN
79 #else
80 #error "Unknown endianness"
81 #endif
82
83 #define NTLM_LOG(x) ((void) 0)
84
85 //-----------------------------------------------------------------------------
86 // This file contains a cross-platform NTLM authentication implementation. It
87 // is based on documentation from: http://davenport.sourceforge.net/ntlm.html
88 //-----------------------------------------------------------------------------
89
90 enum {
91   NTLM_NegotiateUnicode             = 0x00000001,
92   NTLM_NegotiateOEM                 = 0x00000002,
93   NTLM_RequestTarget                = 0x00000004,
94   NTLM_Unknown1                     = 0x00000008,
95   NTLM_NegotiateSign                = 0x00000010,
96   NTLM_NegotiateSeal                = 0x00000020,
97   NTLM_NegotiateDatagramStyle       = 0x00000040,
98   NTLM_NegotiateLanManagerKey       = 0x00000080,
99   NTLM_NegotiateNetware             = 0x00000100,
100   NTLM_NegotiateNTLMKey             = 0x00000200,
101   NTLM_Unknown2                     = 0x00000400,
102   NTLM_Unknown3                     = 0x00000800,
103   NTLM_NegotiateDomainSupplied      = 0x00001000,
104   NTLM_NegotiateWorkstationSupplied = 0x00002000,
105   NTLM_NegotiateLocalCall           = 0x00004000,
106   NTLM_NegotiateAlwaysSign          = 0x00008000,
107   NTLM_TargetTypeDomain             = 0x00010000,
108   NTLM_TargetTypeServer             = 0x00020000,
109   NTLM_TargetTypeShare              = 0x00040000,
110   NTLM_NegotiateNTLM2Key            = 0x00080000,
111   NTLM_RequestInitResponse          = 0x00100000,
112   NTLM_RequestAcceptResponse        = 0x00200000,
113   NTLM_RequestNonNTSessionKey       = 0x00400000,
114   NTLM_NegotiateTargetInfo          = 0x00800000,
115   NTLM_Unknown4                     = 0x01000000,
116   NTLM_Unknown5                     = 0x02000000,
117   NTLM_Unknown6                     = 0x04000000,
118   NTLM_Unknown7                     = 0x08000000,
119   NTLM_Unknown8                     = 0x10000000,
120   NTLM_Negotiate128                 = 0x20000000,
121   NTLM_NegotiateKeyExchange         = 0x40000000,
122   NTLM_Negotiate56                  = 0x80000000
123 };
124
125 // We send these flags with our type 1 message.
126 enum {
127   NTLM_TYPE1_FLAGS = (NTLM_NegotiateUnicode |
128                       NTLM_NegotiateOEM |
129                       NTLM_RequestTarget |
130                       NTLM_NegotiateNTLMKey |
131                       NTLM_NegotiateAlwaysSign |
132                       NTLM_NegotiateNTLM2Key)
133 };
134
135 static const char NTLM_SIGNATURE[] = "NTLMSSP";
136 static const char NTLM_TYPE1_MARKER[] = { 0x01, 0x00, 0x00, 0x00 };
137 static const char NTLM_TYPE2_MARKER[] = { 0x02, 0x00, 0x00, 0x00 };
138 static const char NTLM_TYPE3_MARKER[] = { 0x03, 0x00, 0x00, 0x00 };
139
140 enum {
141   NTLM_TYPE1_HEADER_LEN = 32,
142   NTLM_TYPE2_HEADER_LEN = 32,
143   NTLM_TYPE3_HEADER_LEN = 64,
144
145   LM_HASH_LEN = 16,
146   LM_RESP_LEN = 24,
147
148   NTLM_HASH_LEN = 16,
149   NTLM_RESP_LEN = 24
150 };
151
152 //-----------------------------------------------------------------------------
153
154 // The return value of this function controls whether or not the LM hash will
155 // be included in response to a NTLM challenge.
156 //
157 // In Mozilla, this function returns the value of the boolean preference
158 // "network.ntlm.send-lm-response".  By default, the preference is disabled
159 // since servers should almost never need the LM hash, and the LM hash is what
160 // makes NTLM authentication less secure.  See
161 // https://bugzilla.mozilla.org/show_bug.cgi?id=250691 for further details.
162 //
163 // We just return a hardcoded false.
164 static bool SendLM() {
165   return false;
166 }
167
168 //-----------------------------------------------------------------------------
169
170 #define LogFlags(x) ((void) 0)
171 #define LogBuf(a, b, c) ((void) 0)
172 #define LogToken(a, b, c) ((void) 0)
173
174 //-----------------------------------------------------------------------------
175
176 // Byte order swapping.
177 #define SWAP16(x) ((((x) & 0xff) << 8) | (((x) >> 8) & 0xff))
178 #define SWAP32(x) ((SWAP16((x) & 0xffff) << 16) | (SWAP16((x) >> 16)))
179
180 static void* WriteBytes(void* buf, const void* data, uint32 data_len) {
181   memcpy(buf, data, data_len);
182   return static_cast<char*>(buf) + data_len;
183 }
184
185 static void* WriteDWORD(void* buf, uint32 dword) {
186 #ifdef IS_BIG_ENDIAN
187   // NTLM uses little endian on the wire.
188   dword = SWAP32(dword);
189 #endif
190   return WriteBytes(buf, &dword, sizeof(dword));
191 }
192
193 static void* WriteSecBuf(void* buf, uint16 length, uint32 offset) {
194 #ifdef IS_BIG_ENDIAN
195   length = SWAP16(length);
196   offset = SWAP32(offset);
197 #endif
198   buf = WriteBytes(buf, &length, sizeof(length));
199   buf = WriteBytes(buf, &length, sizeof(length));
200   buf = WriteBytes(buf, &offset, sizeof(offset));
201   return buf;
202 }
203
204 #ifdef IS_BIG_ENDIAN
205 /**
206  * WriteUnicodeLE copies a unicode string from one buffer to another.  The
207  * resulting unicode string is in little-endian format.  The input string is
208  * assumed to be in the native endianness of the local machine.  It is safe
209  * to pass the same buffer as both input and output, which is a handy way to
210  * convert the unicode buffer to little-endian on big-endian platforms.
211  */
212 static void* WriteUnicodeLE(
213     void* buf, const base::char16* str, uint32 str_len) {
214   // Convert input string from BE to LE.
215   uint8* cursor = static_cast<uint8*>(buf);
216   const uint8* input  = reinterpret_cast<const uint8*>(str);
217   for (uint32 i = 0; i < str_len; ++i, input += 2, cursor += 2) {
218     // Allow for the case where |buf == str|.
219     uint8 temp = input[0];
220     cursor[0] = input[1];
221     cursor[1] = temp;
222   }
223   return buf;
224 }
225 #endif
226
227 static uint16 ReadUint16(const uint8*& buf) {
228   uint16 x = (static_cast<uint16>(buf[0]))      |
229              (static_cast<uint16>(buf[1]) << 8);
230   buf += sizeof(x);
231   return x;
232 }
233
234 static uint32 ReadUint32(const uint8*& buf) {
235   uint32 x = (static_cast<uint32>(buf[0]))       |
236              (static_cast<uint32>(buf[1]) << 8)  |
237              (static_cast<uint32>(buf[2]) << 16) |
238              (static_cast<uint32>(buf[3]) << 24);
239   buf += sizeof(x);
240   return x;
241 }
242
243 //-----------------------------------------------------------------------------
244
245 // LM_Hash computes the LM hash of the given password.
246 //
247 // param password
248 //       unicode password.
249 // param hash
250 //       16-byte result buffer
251 //
252 // Note: This function is not being used because our SendLM() function always
253 // returns false.
254 static void LM_Hash(const base::string16& password, uint8* hash) {
255   static const uint8 LM_MAGIC[] = "KGS!@#$%";
256
257   // Convert password to OEM character set.  We'll just use the native
258   // filesystem charset.
259   std::string passbuf = base::SysWideToNativeMB(base::UTF16ToWide(password));
260   StringToUpperASCII(&passbuf);
261   passbuf.resize(14, '\0');
262
263   uint8 k1[8], k2[8];
264   DESMakeKey(reinterpret_cast<const uint8*>(passbuf.data())    , k1);
265   DESMakeKey(reinterpret_cast<const uint8*>(passbuf.data()) + 7, k2);
266   ZapString(&passbuf);
267
268   // Use password keys to hash LM magic string twice.
269   DESEncrypt(k1, LM_MAGIC, hash);
270   DESEncrypt(k2, LM_MAGIC, hash + 8);
271 }
272
273 // NTLM_Hash computes the NTLM hash of the given password.
274 //
275 // param password
276 //       null-terminated unicode password.
277 // param hash
278 //       16-byte result buffer
279 static void NTLM_Hash(const base::string16& password, uint8* hash) {
280 #ifdef IS_BIG_ENDIAN
281   uint32 len = password.length();
282   uint8* passbuf;
283
284   passbuf = static_cast<uint8*>(malloc(len * 2));
285   WriteUnicodeLE(passbuf, password.data(), len);
286   weak_crypto::MD4Sum(passbuf, len * 2, hash);
287
288   ZapBuf(passbuf, len * 2);
289   free(passbuf);
290 #else
291   weak_crypto::MD4Sum(reinterpret_cast<const uint8*>(password.data()),
292                       password.length() * 2, hash);
293 #endif
294 }
295
296 //-----------------------------------------------------------------------------
297
298 // LM_Response generates the LM response given a 16-byte password hash and the
299 // challenge from the Type-2 message.
300 //
301 // param hash
302 //       16-byte password hash
303 // param challenge
304 //       8-byte challenge from Type-2 message
305 // param response
306 //       24-byte buffer to contain the LM response upon return
307 static void LM_Response(const uint8* hash,
308                         const uint8* challenge,
309                         uint8* response) {
310   uint8 keybytes[21], k1[8], k2[8], k3[8];
311
312   memcpy(keybytes, hash, 16);
313   ZapBuf(keybytes + 16, 5);
314
315   DESMakeKey(keybytes     , k1);
316   DESMakeKey(keybytes +  7, k2);
317   DESMakeKey(keybytes + 14, k3);
318
319   DESEncrypt(k1, challenge, response);
320   DESEncrypt(k2, challenge, response + 8);
321   DESEncrypt(k3, challenge, response + 16);
322 }
323
324 //-----------------------------------------------------------------------------
325
326 // Returns OK or a network error code.
327 static int GenerateType1Msg(void** out_buf, uint32* out_len) {
328   //
329   // Verify that buf_len is sufficient.
330   //
331   *out_len = NTLM_TYPE1_HEADER_LEN;
332   *out_buf = malloc(*out_len);
333   if (!*out_buf)
334     return ERR_OUT_OF_MEMORY;
335
336   //
337   // Write out type 1 message.
338   //
339   void* cursor = *out_buf;
340
341   // 0 : signature
342   cursor = WriteBytes(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
343
344   // 8 : marker
345   cursor = WriteBytes(cursor, NTLM_TYPE1_MARKER, sizeof(NTLM_TYPE1_MARKER));
346
347   // 12 : flags
348   cursor = WriteDWORD(cursor, NTLM_TYPE1_FLAGS);
349
350   //
351   // NOTE: It is common for the domain and workstation fields to be empty.
352   //       This is true of Win2k clients, and my guess is that there is
353   //       little utility to sending these strings before the charset has
354   //       been negotiated.  We follow suite -- anyways, it doesn't hurt
355   //       to save some bytes on the wire ;-)
356   //
357
358   // 16 : supplied domain security buffer (empty)
359   cursor = WriteSecBuf(cursor, 0, 0);
360
361   // 24 : supplied workstation security buffer (empty)
362   cursor = WriteSecBuf(cursor, 0, 0);
363
364   return OK;
365 }
366
367 struct Type2Msg {
368   uint32      flags;         // NTLM_Xxx bitwise combination
369   uint8       challenge[8];  // 8 byte challenge
370   const void* target;        // target string (type depends on flags)
371   uint32      target_len;    // target length in bytes
372 };
373
374 // Returns OK or a network error code.
375 // TODO(wtc): This function returns ERR_UNEXPECTED when the input message is
376 // invalid.  We should return a better error code.
377 static int ParseType2Msg(const void* in_buf, uint32 in_len, Type2Msg* msg) {
378   // Make sure in_buf is long enough to contain a meaningful type2 msg.
379   //
380   // 0  NTLMSSP Signature
381   // 8  NTLM Message Type
382   // 12 Target Name
383   // 20 Flags
384   // 24 Challenge
385   // 32 end of header, start of optional data blocks
386   //
387   if (in_len < NTLM_TYPE2_HEADER_LEN)
388     return ERR_UNEXPECTED;
389
390   const uint8* cursor = (const uint8*) in_buf;
391
392   // verify NTLMSSP signature
393   if (memcmp(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)) != 0)
394     return ERR_UNEXPECTED;
395   cursor += sizeof(NTLM_SIGNATURE);
396
397   // verify Type-2 marker
398   if (memcmp(cursor, NTLM_TYPE2_MARKER, sizeof(NTLM_TYPE2_MARKER)) != 0)
399     return ERR_UNEXPECTED;
400   cursor += sizeof(NTLM_TYPE2_MARKER);
401
402   // read target name security buffer
403   uint32 target_len = ReadUint16(cursor);
404   ReadUint16(cursor);  // discard next 16-bit value
405   uint32 offset = ReadUint32(cursor);  // get offset from in_buf
406   msg->target_len = 0;
407   msg->target = NULL;
408   // Check the offset / length combo is in range of the input buffer, including
409   // integer overflow checking.
410   if (offset + target_len > offset && offset + target_len <= in_len) {
411     msg->target_len = target_len;
412     msg->target = ((const uint8*) in_buf) + offset;
413   }
414
415   // read flags
416   msg->flags = ReadUint32(cursor);
417
418   // read challenge
419   memcpy(msg->challenge, cursor, sizeof(msg->challenge));
420   cursor += sizeof(msg->challenge);
421
422   NTLM_LOG(("NTLM type 2 message:\n"));
423   LogBuf("target", (const uint8*) msg->target, msg->target_len);
424   LogBuf("flags", (const uint8*) &msg->flags, 4);
425   LogFlags(msg->flags);
426   LogBuf("challenge", msg->challenge, sizeof(msg->challenge));
427
428   // We currently do not implement LMv2/NTLMv2 or NTLM2 responses,
429   // so we can ignore target information.  We may want to enable
430   // support for these alternate mechanisms in the future.
431   return OK;
432 }
433
434 static void GenerateRandom(uint8* output, size_t n) {
435   for (size_t i = 0; i < n; ++i)
436     output[i] = base::RandInt(0, 255);
437 }
438
439 // Returns OK or a network error code.
440 static int GenerateType3Msg(const base::string16& domain,
441                             const base::string16& username,
442                             const base::string16& password,
443                             const std::string& hostname,
444                             const void* rand_8_bytes,
445                             const void* in_buf,
446                             uint32 in_len,
447                             void** out_buf,
448                             uint32* out_len) {
449   // in_buf contains Type-2 msg (the challenge) from server.
450
451   int rv;
452   Type2Msg msg;
453
454   rv = ParseType2Msg(in_buf, in_len, &msg);
455   if (rv != OK)
456     return rv;
457
458   bool unicode = (msg.flags & NTLM_NegotiateUnicode) != 0;
459
460   // Temporary buffers for unicode strings
461 #ifdef IS_BIG_ENDIAN
462   base::string16 ucs_domain_buf, ucs_user_buf;
463 #endif
464   base::string16 ucs_host_buf;
465   // Temporary buffers for oem strings
466   std::string oem_domain_buf, oem_user_buf;
467   // Pointers and lengths for the string buffers; encoding is unicode if
468   // the "negotiate unicode" flag was set in the Type-2 message.
469   const void* domain_ptr;
470   const void* user_ptr;
471   const void* host_ptr;
472   uint32 domain_len, user_len, host_len;
473
474   //
475   // Get domain name.
476   //
477   if (unicode) {
478 #ifdef IS_BIG_ENDIAN
479     ucs_domain_buf = domain;
480     domain_ptr = ucs_domain_buf.data();
481     domain_len = ucs_domain_buf.length() * 2;
482     WriteUnicodeLE(const_cast<void*>(domain_ptr),
483                    (const base::char16*) domain_ptr,
484                    ucs_domain_buf.length());
485 #else
486     domain_ptr = domain.data();
487     domain_len = domain.length() * 2;
488 #endif
489   } else {
490     oem_domain_buf = base::SysWideToNativeMB(base::UTF16ToWide(domain));
491     domain_ptr = oem_domain_buf.data();
492     domain_len = oem_domain_buf.length();
493   }
494
495   //
496   // Get user name.
497   //
498   if (unicode) {
499 #ifdef IS_BIG_ENDIAN
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 base::char16*) user_ptr,
504                    ucs_user_buf.length());
505 #else
506     user_ptr = username.data();
507     user_len = username.length() * 2;
508 #endif
509   } else {
510     oem_user_buf = base::SysWideToNativeMB(base::UTF16ToWide(username));
511     user_ptr = oem_user_buf.data();
512     user_len = oem_user_buf.length();
513   }
514
515   //
516   // Get workstation name (use local machine's hostname).
517   //
518   if (unicode) {
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;
523 #ifdef IS_BIG_ENDIAN
524     WriteUnicodeLE(const_cast<void*>(host_ptr), (const base::char16*) host_ptr,
525                    ucs_host_buf.length());
526 #endif
527   } else {
528     host_ptr = hostname.data();
529     host_len = hostname.length();
530   }
531
532   //
533   // Now that we have generated all of the strings, we can allocate out_buf.
534   //
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);
538   if (!*out_buf)
539     return ERR_OUT_OF_MEMORY;
540
541   //
542   // Next, we compute the LM and NTLM responses.
543   //
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;
550     uint8 temp[16];
551
552     memcpy(lm_resp, rand_8_bytes, 8);
553     memset(lm_resp + 8, 0, LM_RESP_LEN - 8);
554
555     memcpy(temp, msg.challenge, 8);
556     memcpy(temp + 8, lm_resp, 8);
557     base::MD5Sum(temp, 16, &session_hash);
558
559     NTLM_Hash(password, ntlm_hash);
560     LM_Response(ntlm_hash, session_hash.a, ntlm_resp);
561   } else {
562     NTLM_Hash(password, ntlm_hash);
563     LM_Response(ntlm_hash, msg.challenge, ntlm_resp);
564
565     if (SendLM()) {
566       uint8 lm_hash[LM_HASH_LEN];
567       LM_Hash(password, lm_hash);
568       LM_Response(lm_hash, msg.challenge, lm_resp);
569     } else {
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);
574     }
575   }
576
577   //
578   // Finally, we assemble the Type-3 msg :-)
579   //
580   void* cursor = *out_buf;
581   uint32 offset;
582
583   // 0 : signature
584   cursor = WriteBytes(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
585
586   // 8 : marker
587   cursor = WriteBytes(cursor, NTLM_TYPE3_MARKER, sizeof(NTLM_TYPE3_MARKER));
588
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);
593
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);
598
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);
603
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);
608
609   // 44 : workstation (host) name sec buf
610   offset += user_len;
611   cursor = WriteSecBuf(cursor, host_len, offset);
612   memcpy(static_cast<uint8*>(*out_buf) + offset, host_ptr, host_len);
613
614   // 52 : session key sec buf (not used)
615   cursor = WriteSecBuf(cursor, 0, 0);
616
617   // 60 : negotiated flags
618   cursor = WriteDWORD(cursor, msg.flags & NTLM_TYPE1_FLAGS);
619
620   return OK;
621 }
622
623 // NTLM authentication is specified in "NTLM Over HTTP Protocol Specification"
624 // [MS-NTHT].
625
626 // static
627 HttpAuthHandlerNTLM::GenerateRandomProc
628 HttpAuthHandlerNTLM::generate_random_proc_ = GenerateRandom;
629
630 // static
631 HttpAuthHandlerNTLM::HostNameProc
632 HttpAuthHandlerNTLM::get_host_name_proc_ = GetHostName;
633
634 HttpAuthHandlerNTLM::HttpAuthHandlerNTLM() {
635 }
636
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();
642 }
643
644 bool HttpAuthHandlerNTLM::AllowsDefaultCredentials() {
645   // Default credentials are not supported in the portable implementation of
646   // NTLM, but are supported in the SSPI implementation.
647   return false;
648 }
649
650 int HttpAuthHandlerNTLM::InitializeBeforeFirstChallenge() {
651   return OK;
652 }
653
654 HttpAuthHandlerNTLM::~HttpAuthHandlerNTLM() {
655   credentials_.Zap();
656 }
657
658 // static
659 HttpAuthHandlerNTLM::GenerateRandomProc
660 HttpAuthHandlerNTLM::SetGenerateRandomProc(
661     GenerateRandomProc proc) {
662   GenerateRandomProc old_proc = generate_random_proc_;
663   generate_random_proc_ = proc;
664   return old_proc;
665 }
666
667 // static
668 HttpAuthHandlerNTLM::HostNameProc HttpAuthHandlerNTLM::SetHostNameProc(
669     HostNameProc proc) {
670   HostNameProc old_proc = get_host_name_proc_;
671   get_host_name_proc_ = proc;
672   return old_proc;
673 }
674
675 HttpAuthHandlerNTLM::Factory::Factory() {
676 }
677
678 HttpAuthHandlerNTLM::Factory::~Factory() {
679 }
680
681 int HttpAuthHandlerNTLM::GetNextToken(const void* in_token,
682                                       uint32 in_token_len,
683                                       void** out_token,
684                                       uint32* out_token_len) {
685   int rv = 0;
686
687   // If in_token is non-null, then assume it contains a type 2 message...
688   if (in_token) {
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;
693     uint8 rand_buf[8];
694     generate_random_proc_(rand_buf, 8);
695     rv = GenerateType3Msg(domain_,
696                           credentials_.username(), credentials_.password(),
697                           hostname, rand_buf,
698                           in_token, in_token_len, out_token, out_token_len);
699   } else {
700     rv = GenerateType1Msg(out_token, out_token_len);
701   }
702
703   if (rv == OK)
704     LogToken("out-token", *out_token, *out_token_len);
705
706   return rv;
707 }
708
709 int HttpAuthHandlerNTLM::Factory::CreateAuthHandler(
710     HttpAuth::ChallengeTokenizer* challenge,
711     HttpAuth::Target target,
712     const GURL& origin,
713     CreateReason reason,
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
722   // of NTLM.
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);
727   return OK;
728 }
729
730 }  // namespace net