- add sources.
[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 // 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
77 #undef  IS_BIG_ENDIAN
78 #elif defined(ARCH_CPU_MIPSEB)
79 #define IS_BIG_ENDIAN 1
80 #undef  IS_LITTLE_ENDIAN
81 #else
82 #error "Unknown endianness"
83 #endif
84
85 #define NTLM_LOG(x) ((void) 0)
86
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 //-----------------------------------------------------------------------------
91
92 enum {
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
125 };
126
127 // We send these flags with our type 1 message.
128 enum {
129   NTLM_TYPE1_FLAGS = (NTLM_NegotiateUnicode |
130                       NTLM_NegotiateOEM |
131                       NTLM_RequestTarget |
132                       NTLM_NegotiateNTLMKey |
133                       NTLM_NegotiateAlwaysSign |
134                       NTLM_NegotiateNTLM2Key)
135 };
136
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 };
141
142 enum {
143   NTLM_TYPE1_HEADER_LEN = 32,
144   NTLM_TYPE2_HEADER_LEN = 32,
145   NTLM_TYPE3_HEADER_LEN = 64,
146
147   LM_HASH_LEN = 16,
148   LM_RESP_LEN = 24,
149
150   NTLM_HASH_LEN = 16,
151   NTLM_RESP_LEN = 24
152 };
153
154 //-----------------------------------------------------------------------------
155
156 // The return value of this function controls whether or not the LM hash will
157 // be included in response to a NTLM challenge.
158 //
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.
164 //
165 // We just return a hardcoded false.
166 static bool SendLM() {
167   return false;
168 }
169
170 //-----------------------------------------------------------------------------
171
172 #define LogFlags(x) ((void) 0)
173 #define LogBuf(a, b, c) ((void) 0)
174 #define LogToken(a, b, c) ((void) 0)
175
176 //-----------------------------------------------------------------------------
177
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)))
181
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;
185 }
186
187 static void* WriteDWORD(void* buf, uint32 dword) {
188 #ifdef IS_BIG_ENDIAN
189   // NTLM uses little endian on the wire.
190   dword = SWAP32(dword);
191 #endif
192   return WriteBytes(buf, &dword, sizeof(dword));
193 }
194
195 static void* WriteSecBuf(void* buf, uint16 length, uint32 offset) {
196 #ifdef IS_BIG_ENDIAN
197   length = SWAP16(length);
198   offset = SWAP32(offset);
199 #endif
200   buf = WriteBytes(buf, &length, sizeof(length));
201   buf = WriteBytes(buf, &length, sizeof(length));
202   buf = WriteBytes(buf, &offset, sizeof(offset));
203   return buf;
204 }
205
206 #ifdef IS_BIG_ENDIAN
207 /**
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.
213  */
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];
222     cursor[1] = temp;
223   }
224   return buf;
225 }
226 #endif
227
228 static uint16 ReadUint16(const uint8*& buf) {
229   uint16 x = (static_cast<uint16>(buf[0]))      |
230              (static_cast<uint16>(buf[1]) << 8);
231   buf += sizeof(x);
232   return x;
233 }
234
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);
240   buf += sizeof(x);
241   return x;
242 }
243
244 //-----------------------------------------------------------------------------
245
246 // LM_Hash computes the LM hash of the given password.
247 //
248 // param password
249 //       unicode password.
250 // param hash
251 //       16-byte result buffer
252 //
253 // Note: This function is not being used because our SendLM() function always
254 // returns false.
255 static void LM_Hash(const base::string16& password, uint8* hash) {
256   static const uint8 LM_MAGIC[] = "KGS!@#$%";
257
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');
263
264   uint8 k1[8], k2[8];
265   DESMakeKey(reinterpret_cast<const uint8*>(passbuf.data())    , k1);
266   DESMakeKey(reinterpret_cast<const uint8*>(passbuf.data()) + 7, k2);
267   ZapString(&passbuf);
268
269   // Use password keys to hash LM magic string twice.
270   DESEncrypt(k1, LM_MAGIC, hash);
271   DESEncrypt(k2, LM_MAGIC, hash + 8);
272 }
273
274 // NTLM_Hash computes the NTLM hash of the given password.
275 //
276 // param password
277 //       null-terminated unicode password.
278 // param hash
279 //       16-byte result buffer
280 static void NTLM_Hash(const base::string16& password, uint8* hash) {
281 #ifdef IS_BIG_ENDIAN
282   uint32 len = password.length();
283   uint8* passbuf;
284
285   passbuf = static_cast<uint8*>(malloc(len * 2));
286   WriteUnicodeLE(passbuf, password.data(), len);
287   weak_crypto::MD4Sum(passbuf, len * 2, hash);
288
289   ZapBuf(passbuf, len * 2);
290   free(passbuf);
291 #else
292   weak_crypto::MD4Sum(reinterpret_cast<const uint8*>(password.data()),
293                       password.length() * 2, hash);
294 #endif
295 }
296
297 //-----------------------------------------------------------------------------
298
299 // LM_Response generates the LM response given a 16-byte password hash and the
300 // challenge from the Type-2 message.
301 //
302 // param hash
303 //       16-byte password hash
304 // param challenge
305 //       8-byte challenge from Type-2 message
306 // param response
307 //       24-byte buffer to contain the LM response upon return
308 static void LM_Response(const uint8* hash,
309                         const uint8* challenge,
310                         uint8* response) {
311   uint8 keybytes[21], k1[8], k2[8], k3[8];
312
313   memcpy(keybytes, hash, 16);
314   ZapBuf(keybytes + 16, 5);
315
316   DESMakeKey(keybytes     , k1);
317   DESMakeKey(keybytes +  7, k2);
318   DESMakeKey(keybytes + 14, k3);
319
320   DESEncrypt(k1, challenge, response);
321   DESEncrypt(k2, challenge, response + 8);
322   DESEncrypt(k3, challenge, response + 16);
323 }
324
325 //-----------------------------------------------------------------------------
326
327 // Returns OK or a network error code.
328 static int GenerateType1Msg(void** out_buf, uint32* out_len) {
329   //
330   // Verify that buf_len is sufficient.
331   //
332   *out_len = NTLM_TYPE1_HEADER_LEN;
333   *out_buf = malloc(*out_len);
334   if (!*out_buf)
335     return ERR_OUT_OF_MEMORY;
336
337   //
338   // Write out type 1 message.
339   //
340   void* cursor = *out_buf;
341
342   // 0 : signature
343   cursor = WriteBytes(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
344
345   // 8 : marker
346   cursor = WriteBytes(cursor, NTLM_TYPE1_MARKER, sizeof(NTLM_TYPE1_MARKER));
347
348   // 12 : flags
349   cursor = WriteDWORD(cursor, NTLM_TYPE1_FLAGS);
350
351   //
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 ;-)
357   //
358
359   // 16 : supplied domain security buffer (empty)
360   cursor = WriteSecBuf(cursor, 0, 0);
361
362   // 24 : supplied workstation security buffer (empty)
363   cursor = WriteSecBuf(cursor, 0, 0);
364
365   return OK;
366 }
367
368 struct Type2Msg {
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
373 };
374
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.
380   //
381   // 0  NTLMSSP Signature
382   // 8  NTLM Message Type
383   // 12 Target Name
384   // 20 Flags
385   // 24 Challenge
386   // 32 end of header, start of optional data blocks
387   //
388   if (in_len < NTLM_TYPE2_HEADER_LEN)
389     return ERR_UNEXPECTED;
390
391   const uint8* cursor = (const uint8*) in_buf;
392
393   // verify NTLMSSP signature
394   if (memcmp(cursor, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)) != 0)
395     return ERR_UNEXPECTED;
396   cursor += sizeof(NTLM_SIGNATURE);
397
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);
402
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
407   msg->target_len = 0;
408   msg->target = NULL;
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;
414   }
415
416   // read flags
417   msg->flags = ReadUint32(cursor);
418
419   // read challenge
420   memcpy(msg->challenge, cursor, sizeof(msg->challenge));
421   cursor += sizeof(msg->challenge);
422
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));
428
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.
432   return OK;
433 }
434
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);
438 }
439
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,
446                             const void* in_buf,
447                             uint32 in_len,
448                             void** out_buf,
449                             uint32* out_len) {
450   // in_buf contains Type-2 msg (the challenge) from server.
451
452   int rv;
453   Type2Msg msg;
454
455   rv = ParseType2Msg(in_buf, in_len, &msg);
456   if (rv != OK)
457     return rv;
458
459   bool unicode = (msg.flags & NTLM_NegotiateUnicode) != 0;
460
461   // Temporary buffers for unicode strings
462 #ifdef IS_BIG_ENDIAN
463   base::string16 ucs_domain_buf, ucs_user_buf;
464 #endif
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;
474
475   //
476   // Get domain name.
477   //
478   if (unicode) {
479 #ifdef IS_BIG_ENDIAN
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());
485 #else
486     domain_ptr = domain.data();
487     domain_len = domain.length() * 2;
488 #endif
489   } else {
490     oem_domain_buf = base::SysWideToNativeMB(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 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(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 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