f3b8b130f18ac00b1dc626292687750f16a6627f
[platform/upstream/cmake.git] / Utilities / cmcurl / lib / curl_ntlm_core.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "curl_setup.h"
24
25 #if defined(USE_CURL_NTLM_CORE)
26
27 /*
28  * NTLM details:
29  *
30  * https://davenport.sourceforge.io/ntlm.html
31  * https://www.innovation.ch/java/ntlm.html
32  */
33
34 /* Please keep the SSL backend-specific #if branches in this order:
35
36    1. USE_OPENSSL
37    2. USE_GNUTLS
38    3. USE_NSS
39    4. USE_MBEDTLS
40    5. USE_SECTRANSP
41    6. USE_OS400CRYPTO
42    7. USE_WIN32_CRYPTO
43
44    This ensures that:
45    - the same SSL branch gets activated throughout this source
46      file even if multiple backends are enabled at the same time.
47    - OpenSSL and NSS have higher priority than Windows Crypt, due
48      to issues with the latter supporting NTLM2Session responses
49      in NTLM type-3 messages.
50  */
51
52 #if defined(USE_OPENSSL)
53   #include <openssl/opensslconf.h>
54   #if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_DEPRECATED_3_0)
55     #define USE_OPENSSL_DES
56   #endif
57 #endif
58
59 #if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL)
60
61 #ifdef USE_WOLFSSL
62 #include <wolfssl/options.h>
63 #endif
64
65 #  include <openssl/des.h>
66 #  include <openssl/md5.h>
67 #  include <openssl/ssl.h>
68 #  include <openssl/rand.h>
69 #  if (defined(OPENSSL_VERSION_NUMBER) && \
70        (OPENSSL_VERSION_NUMBER < 0x00907001L)) && !defined(USE_WOLFSSL)
71 #    define DES_key_schedule des_key_schedule
72 #    define DES_cblock des_cblock
73 #    define DES_set_odd_parity des_set_odd_parity
74 #    define DES_set_key des_set_key
75 #    define DES_ecb_encrypt des_ecb_encrypt
76 #    define DESKEY(x) x
77 #    define DESKEYARG(x) x
78 #  else
79 #    define DESKEYARG(x) *x
80 #    define DESKEY(x) &x
81 #  endif
82
83 #elif defined(USE_GNUTLS)
84
85 #  include <nettle/des.h>
86
87 #elif defined(USE_NSS)
88
89 #  include <nss.h>
90 #  include <pk11pub.h>
91 #  include <hasht.h>
92
93 #elif defined(USE_MBEDTLS)
94
95 #  include <mbedtls/des.h>
96
97 #elif defined(USE_SECTRANSP)
98
99 #  include <CommonCrypto/CommonCryptor.h>
100 #  include <CommonCrypto/CommonDigest.h>
101
102 #elif defined(USE_OS400CRYPTO)
103 #  include "cipher.mih"  /* mih/cipher */
104 #elif defined(USE_WIN32_CRYPTO)
105 #  include <wincrypt.h>
106 #else
107 #  error "Can't compile NTLM support without a crypto library with DES."
108 #endif
109
110 #include "urldata.h"
111 #include "strcase.h"
112 #include "curl_ntlm_core.h"
113 #include "curl_md5.h"
114 #include "curl_hmac.h"
115 #include "warnless.h"
116 #include "curl_endian.h"
117 #include "curl_des.h"
118 #include "curl_md4.h"
119 /* The last 3 #include files should be in this order */
120 #include "curl_printf.h"
121 #include "curl_memory.h"
122 #include "memdebug.h"
123
124 #define NTLMv2_BLOB_SIGNATURE "\x01\x01\x00\x00"
125 #define NTLMv2_BLOB_LEN       (44 -16 + ntlm->target_info_len + 4)
126
127 /*
128 * Turns a 56-bit key into being 64-bit wide.
129 */
130 static void extend_key_56_to_64(const unsigned char *key_56, char *key)
131 {
132   key[0] = key_56[0];
133   key[1] = (unsigned char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1));
134   key[2] = (unsigned char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2));
135   key[3] = (unsigned char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3));
136   key[4] = (unsigned char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4));
137   key[5] = (unsigned char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5));
138   key[6] = (unsigned char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6));
139   key[7] = (unsigned char) ((key_56[6] << 1) & 0xFF);
140 }
141
142 #if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL)
143 /*
144  * Turns a 56 bit key into the 64 bit, odd parity key and sets the key.  The
145  * key schedule ks is also set.
146  */
147 static void setup_des_key(const unsigned char *key_56,
148                           DES_key_schedule DESKEYARG(ks))
149 {
150   DES_cblock key;
151
152   /* Expand the 56-bit key to 64-bits */
153   extend_key_56_to_64(key_56, (char *) &key);
154
155   /* Set the key parity to odd */
156   DES_set_odd_parity(&key);
157
158   /* Set the key */
159   DES_set_key_unchecked(&key, ks);
160 }
161
162 #elif defined(USE_GNUTLS)
163
164 static void setup_des_key(const unsigned char *key_56,
165                           struct des_ctx *des)
166 {
167   char key[8];
168
169   /* Expand the 56-bit key to 64-bits */
170   extend_key_56_to_64(key_56, key);
171
172   /* Set the key parity to odd */
173   Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
174
175   /* Set the key */
176   des_set_key(des, (const uint8_t *) key);
177 }
178
179 #elif defined(USE_NSS)
180
181 /*
182  * Expands a 56 bit key KEY_56 to 64 bit and encrypts 64 bit of data, using
183  * the expanded key.  The caller is responsible for giving 64 bit of valid
184  * data is IN and (at least) 64 bit large buffer as OUT.
185  */
186 static bool encrypt_des(const unsigned char *in, unsigned char *out,
187                         const unsigned char *key_56)
188 {
189   const CK_MECHANISM_TYPE mech = CKM_DES_ECB; /* DES cipher in ECB mode */
190   char key[8];                                /* expanded 64 bit key */
191   SECItem key_item;
192   PK11SymKey *symkey = NULL;
193   SECItem *param = NULL;
194   PK11Context *ctx = NULL;
195   int out_len;                                /* not used, required by NSS */
196   bool rv = FALSE;
197
198   /* use internal slot for DES encryption (requires NSS to be initialized) */
199   PK11SlotInfo *slot = PK11_GetInternalKeySlot();
200   if(!slot)
201     return FALSE;
202
203   /* Expand the 56-bit key to 64-bits */
204   extend_key_56_to_64(key_56, key);
205
206   /* Set the key parity to odd */
207   Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
208
209   /* Import the key */
210   key_item.data = (unsigned char *)key;
211   key_item.len = sizeof(key);
212   symkey = PK11_ImportSymKey(slot, mech, PK11_OriginUnwrap, CKA_ENCRYPT,
213                              &key_item, NULL);
214   if(!symkey)
215     goto fail;
216
217   /* Create the DES encryption context */
218   param = PK11_ParamFromIV(mech, /* no IV in ECB mode */ NULL);
219   if(!param)
220     goto fail;
221   ctx = PK11_CreateContextBySymKey(mech, CKA_ENCRYPT, symkey, param);
222   if(!ctx)
223     goto fail;
224
225   /* Perform the encryption */
226   if(SECSuccess == PK11_CipherOp(ctx, out, &out_len, /* outbuflen */ 8,
227                                  (unsigned char *)in, /* inbuflen */ 8)
228       && SECSuccess == PK11_Finalize(ctx))
229     rv = /* all OK */ TRUE;
230
231 fail:
232   /* cleanup */
233   if(ctx)
234     PK11_DestroyContext(ctx, PR_TRUE);
235   if(symkey)
236     PK11_FreeSymKey(symkey);
237   if(param)
238     SECITEM_FreeItem(param, PR_TRUE);
239   PK11_FreeSlot(slot);
240   return rv;
241 }
242
243 #elif defined(USE_MBEDTLS)
244
245 static bool encrypt_des(const unsigned char *in, unsigned char *out,
246                         const unsigned char *key_56)
247 {
248   mbedtls_des_context ctx;
249   char key[8];
250
251   /* Expand the 56-bit key to 64-bits */
252   extend_key_56_to_64(key_56, key);
253
254   /* Set the key parity to odd */
255   mbedtls_des_key_set_parity((unsigned char *) key);
256
257   /* Perform the encryption */
258   mbedtls_des_init(&ctx);
259   mbedtls_des_setkey_enc(&ctx, (unsigned char *) key);
260   return mbedtls_des_crypt_ecb(&ctx, in, out) == 0;
261 }
262
263 #elif defined(USE_SECTRANSP)
264
265 static bool encrypt_des(const unsigned char *in, unsigned char *out,
266                         const unsigned char *key_56)
267 {
268   char key[8];
269   size_t out_len;
270   CCCryptorStatus err;
271
272   /* Expand the 56-bit key to 64-bits */
273   extend_key_56_to_64(key_56, key);
274
275   /* Set the key parity to odd */
276   Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
277
278   /* Perform the encryption */
279   err = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode, key,
280                 kCCKeySizeDES, NULL, in, 8 /* inbuflen */, out,
281                 8 /* outbuflen */, &out_len);
282
283   return err == kCCSuccess;
284 }
285
286 #elif defined(USE_OS400CRYPTO)
287
288 static bool encrypt_des(const unsigned char *in, unsigned char *out,
289                         const unsigned char *key_56)
290 {
291   char key[8];
292   _CIPHER_Control_T ctl;
293
294   /* Setup the cipher control structure */
295   ctl.Func_ID = ENCRYPT_ONLY;
296   ctl.Data_Len = sizeof(key);
297
298   /* Expand the 56-bit key to 64-bits */
299   extend_key_56_to_64(key_56, ctl.Crypto_Key);
300
301   /* Set the key parity to odd */
302   Curl_des_set_odd_parity((unsigned char *) ctl.Crypto_Key, ctl.Data_Len);
303
304   /* Perform the encryption */
305   _CIPHER((_SPCPTR *) &out, &ctl, (_SPCPTR *) &in);
306
307   return TRUE;
308 }
309
310 #elif defined(USE_WIN32_CRYPTO)
311
312 static bool encrypt_des(const unsigned char *in, unsigned char *out,
313                         const unsigned char *key_56)
314 {
315   HCRYPTPROV hprov;
316   HCRYPTKEY hkey;
317   struct {
318     BLOBHEADER hdr;
319     unsigned int len;
320     char key[8];
321   } blob;
322   DWORD len = 8;
323
324   /* Acquire the crypto provider */
325   if(!CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_FULL,
326                           CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
327     return FALSE;
328
329   /* Setup the key blob structure */
330   memset(&blob, 0, sizeof(blob));
331   blob.hdr.bType = PLAINTEXTKEYBLOB;
332   blob.hdr.bVersion = 2;
333   blob.hdr.aiKeyAlg = CALG_DES;
334   blob.len = sizeof(blob.key);
335
336   /* Expand the 56-bit key to 64-bits */
337   extend_key_56_to_64(key_56, blob.key);
338
339   /* Set the key parity to odd */
340   Curl_des_set_odd_parity((unsigned char *) blob.key, sizeof(blob.key));
341
342   /* Import the key */
343   if(!CryptImportKey(hprov, (BYTE *) &blob, sizeof(blob), 0, 0, &hkey)) {
344     CryptReleaseContext(hprov, 0);
345
346     return FALSE;
347   }
348
349   memcpy(out, in, 8);
350
351   /* Perform the encryption */
352   CryptEncrypt(hkey, 0, FALSE, 0, out, &len, len);
353
354   CryptDestroyKey(hkey);
355   CryptReleaseContext(hprov, 0);
356
357   return TRUE;
358 }
359
360 #endif /* defined(USE_WIN32_CRYPTO) */
361
362  /*
363   * takes a 21 byte array and treats it as 3 56-bit DES keys. The
364   * 8 byte plaintext is encrypted with each key and the resulting 24
365   * bytes are stored in the results array.
366   */
367 void Curl_ntlm_core_lm_resp(const unsigned char *keys,
368                             const unsigned char *plaintext,
369                             unsigned char *results)
370 {
371 #if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL)
372   DES_key_schedule ks;
373
374   setup_des_key(keys, DESKEY(ks));
375   DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) results,
376                   DESKEY(ks), DES_ENCRYPT);
377
378   setup_des_key(keys + 7, DESKEY(ks));
379   DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 8),
380                   DESKEY(ks), DES_ENCRYPT);
381
382   setup_des_key(keys + 14, DESKEY(ks));
383   DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 16),
384                   DESKEY(ks), DES_ENCRYPT);
385 #elif defined(USE_GNUTLS)
386   struct des_ctx des;
387   setup_des_key(keys, &des);
388   des_encrypt(&des, 8, results, plaintext);
389   setup_des_key(keys + 7, &des);
390   des_encrypt(&des, 8, results + 8, plaintext);
391   setup_des_key(keys + 14, &des);
392   des_encrypt(&des, 8, results + 16, plaintext);
393 #elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \
394   || defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
395   encrypt_des(plaintext, results, keys);
396   encrypt_des(plaintext, results + 8, keys + 7);
397   encrypt_des(plaintext, results + 16, keys + 14);
398 #endif
399 }
400
401 /*
402  * Set up lanmanager hashed password
403  */
404 CURLcode Curl_ntlm_core_mk_lm_hash(const char *password,
405                                    unsigned char *lmbuffer /* 21 bytes */)
406 {
407   unsigned char pw[14];
408   static const unsigned char magic[] = {
409     0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 /* i.e. KGS!@#$% */
410   };
411   size_t len = CURLMIN(strlen(password), 14);
412
413   Curl_strntoupper((char *)pw, password, len);
414   memset(&pw[len], 0, 14 - len);
415
416   {
417     /* Create LanManager hashed password. */
418
419 #if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL)
420     DES_key_schedule ks;
421
422     setup_des_key(pw, DESKEY(ks));
423     DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)lmbuffer,
424                     DESKEY(ks), DES_ENCRYPT);
425
426     setup_des_key(pw + 7, DESKEY(ks));
427     DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)(lmbuffer + 8),
428                     DESKEY(ks), DES_ENCRYPT);
429 #elif defined(USE_GNUTLS)
430     struct des_ctx des;
431     setup_des_key(pw, &des);
432     des_encrypt(&des, 8, lmbuffer, magic);
433     setup_des_key(pw + 7, &des);
434     des_encrypt(&des, 8, lmbuffer + 8, magic);
435 #elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \
436   || defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
437     encrypt_des(magic, lmbuffer, pw);
438     encrypt_des(magic, lmbuffer + 8, pw + 7);
439 #endif
440
441     memset(lmbuffer + 16, 0, 21 - 16);
442   }
443
444   return CURLE_OK;
445 }
446
447 static void ascii_to_unicode_le(unsigned char *dest, const char *src,
448                                 size_t srclen)
449 {
450   size_t i;
451   for(i = 0; i < srclen; i++) {
452     dest[2 * i] = (unsigned char)src[i];
453     dest[2 * i + 1] = '\0';
454   }
455 }
456
457 #if !defined(USE_WINDOWS_SSPI)
458
459 static void ascii_uppercase_to_unicode_le(unsigned char *dest,
460                                           const char *src, size_t srclen)
461 {
462   size_t i;
463   for(i = 0; i < srclen; i++) {
464     dest[2 * i] = (unsigned char)(Curl_raw_toupper(src[i]));
465     dest[2 * i + 1] = '\0';
466   }
467 }
468
469 #endif /* !USE_WINDOWS_SSPI */
470
471 /*
472  * Set up nt hashed passwords
473  * @unittest: 1600
474  */
475 CURLcode Curl_ntlm_core_mk_nt_hash(const char *password,
476                                    unsigned char *ntbuffer /* 21 bytes */)
477 {
478   size_t len = strlen(password);
479   unsigned char *pw;
480   if(len > SIZE_T_MAX/2) /* avoid integer overflow */
481     return CURLE_OUT_OF_MEMORY;
482   pw = len ? malloc(len * 2) : (unsigned char *)strdup("");
483   if(!pw)
484     return CURLE_OUT_OF_MEMORY;
485
486   ascii_to_unicode_le(pw, password, len);
487
488   /* Create NT hashed password. */
489   Curl_md4it(ntbuffer, pw, 2 * len);
490   memset(ntbuffer + 16, 0, 21 - 16);
491
492   free(pw);
493
494   return CURLE_OK;
495 }
496
497 #if !defined(USE_WINDOWS_SSPI)
498
499 /* Timestamp in tenths of a microsecond since January 1, 1601 00:00:00 UTC. */
500 struct ms_filetime {
501   unsigned int dwLowDateTime;
502   unsigned int dwHighDateTime;
503 };
504
505 /* Convert a time_t to an MS FILETIME (MS-DTYP section 2.3.3). */
506 static void time2filetime(struct ms_filetime *ft, time_t t)
507 {
508 #if SIZEOF_TIME_T > 4
509   t = (t + CURL_OFF_T_C(11644473600)) * 10000000;
510   ft->dwLowDateTime = (unsigned int) (t & 0xFFFFFFFF);
511   ft->dwHighDateTime = (unsigned int) (t >> 32);
512 #else
513   unsigned int r, s;
514   unsigned int i;
515
516   ft->dwLowDateTime = t & 0xFFFFFFFF;
517   ft->dwHighDateTime = 0;
518
519 # ifndef HAVE_TIME_T_UNSIGNED
520   /* Extend sign if needed. */
521   if(ft->dwLowDateTime & 0x80000000)
522     ft->dwHighDateTime = ~0;
523 # endif
524
525   /* Bias seconds to Jan 1, 1601.
526      134774 days = 11644473600 seconds = 0x2B6109100 */
527   r = ft->dwLowDateTime;
528   ft->dwLowDateTime = (ft->dwLowDateTime + 0xB6109100U) & 0xFFFFFFFF;
529   ft->dwHighDateTime += ft->dwLowDateTime < r? 0x03: 0x02;
530
531   /* Convert to tenths of microseconds. */
532   ft->dwHighDateTime *= 10000000;
533   i = 32;
534   do {
535     i -= 8;
536     s = ((ft->dwLowDateTime >> i) & 0xFF) * (10000000 - 1);
537     r = (s << i) & 0xFFFFFFFF;
538     s >>= 1;   /* Split shift to avoid width overflow. */
539     s >>= 31 - i;
540     ft->dwLowDateTime = (ft->dwLowDateTime + r) & 0xFFFFFFFF;
541     if(ft->dwLowDateTime < r)
542       s++;
543     ft->dwHighDateTime += s;
544   } while(i);
545   ft->dwHighDateTime &= 0xFFFFFFFF;
546 #endif
547 }
548
549 /* This creates the NTLMv2 hash by using NTLM hash as the key and Unicode
550  * (uppercase UserName + Domain) as the data
551  */
552 CURLcode Curl_ntlm_core_mk_ntlmv2_hash(const char *user, size_t userlen,
553                                        const char *domain, size_t domlen,
554                                        unsigned char *ntlmhash,
555                                        unsigned char *ntlmv2hash)
556 {
557   /* Unicode representation */
558   size_t identity_len;
559   unsigned char *identity;
560   CURLcode result = CURLE_OK;
561
562   if((userlen > CURL_MAX_INPUT_LENGTH) || (domlen > CURL_MAX_INPUT_LENGTH))
563     return CURLE_OUT_OF_MEMORY;
564
565   identity_len = (userlen + domlen) * 2;
566   identity = malloc(identity_len + 1);
567
568   if(!identity)
569     return CURLE_OUT_OF_MEMORY;
570
571   ascii_uppercase_to_unicode_le(identity, user, userlen);
572   ascii_to_unicode_le(identity + (userlen << 1), domain, domlen);
573
574   result = Curl_hmacit(Curl_HMAC_MD5, ntlmhash, 16, identity, identity_len,
575                        ntlmv2hash);
576   free(identity);
577
578   return result;
579 }
580
581 /*
582  * Curl_ntlm_core_mk_ntlmv2_resp()
583  *
584  * This creates the NTLMv2 response as set in the ntlm type-3 message.
585  *
586  * Parameters:
587  *
588  * ntlmv2hash       [in] - The ntlmv2 hash (16 bytes)
589  * challenge_client [in] - The client nonce (8 bytes)
590  * ntlm             [in] - The ntlm data struct being used to read TargetInfo
591                            and Server challenge received in the type-2 message
592  * ntresp          [out] - The address where a pointer to newly allocated
593  *                         memory holding the NTLMv2 response.
594  * ntresp_len      [out] - The length of the output message.
595  *
596  * Returns CURLE_OK on success.
597  */
598 CURLcode Curl_ntlm_core_mk_ntlmv2_resp(unsigned char *ntlmv2hash,
599                                        unsigned char *challenge_client,
600                                        struct ntlmdata *ntlm,
601                                        unsigned char **ntresp,
602                                        unsigned int *ntresp_len)
603 {
604 /* NTLMv2 response structure :
605 ------------------------------------------------------------------------------
606 0     HMAC MD5         16 bytes
607 ------BLOB--------------------------------------------------------------------
608 16    Signature        0x01010000
609 20    Reserved         long (0x00000000)
610 24    Timestamp        LE, 64-bit signed value representing the number of
611                        tenths of a microsecond since January 1, 1601.
612 32    Client Nonce     8 bytes
613 40    Unknown          4 bytes
614 44    Target Info      N bytes (from the type-2 message)
615 44+N  Unknown          4 bytes
616 ------------------------------------------------------------------------------
617 */
618
619   unsigned int len = 0;
620   unsigned char *ptr = NULL;
621   unsigned char hmac_output[HMAC_MD5_LENGTH];
622   struct ms_filetime tw;
623
624   CURLcode result = CURLE_OK;
625
626   /* Calculate the timestamp */
627 #ifdef DEBUGBUILD
628   char *force_timestamp = getenv("CURL_FORCETIME");
629   if(force_timestamp)
630     time2filetime(&tw, (time_t) 0);
631   else
632 #endif
633     time2filetime(&tw, time(NULL));
634
635   /* Calculate the response len */
636   len = HMAC_MD5_LENGTH + NTLMv2_BLOB_LEN;
637
638   /* Allocate the response */
639   ptr = calloc(1, len);
640   if(!ptr)
641     return CURLE_OUT_OF_MEMORY;
642
643   /* Create the BLOB structure */
644   msnprintf((char *)ptr + HMAC_MD5_LENGTH, NTLMv2_BLOB_LEN,
645             "%c%c%c%c"           /* NTLMv2_BLOB_SIGNATURE */
646             "%c%c%c%c"           /* Reserved = 0 */
647             "%c%c%c%c%c%c%c%c",  /* Timestamp */
648             NTLMv2_BLOB_SIGNATURE[0], NTLMv2_BLOB_SIGNATURE[1],
649             NTLMv2_BLOB_SIGNATURE[2], NTLMv2_BLOB_SIGNATURE[3],
650             0, 0, 0, 0,
651             LONGQUARTET(tw.dwLowDateTime), LONGQUARTET(tw.dwHighDateTime));
652
653   memcpy(ptr + 32, challenge_client, 8);
654   memcpy(ptr + 44, ntlm->target_info, ntlm->target_info_len);
655
656   /* Concatenate the Type 2 challenge with the BLOB and do HMAC MD5 */
657   memcpy(ptr + 8, &ntlm->nonce[0], 8);
658   result = Curl_hmacit(Curl_HMAC_MD5, ntlmv2hash, HMAC_MD5_LENGTH, ptr + 8,
659                     NTLMv2_BLOB_LEN + 8, hmac_output);
660   if(result) {
661     free(ptr);
662     return result;
663   }
664
665   /* Concatenate the HMAC MD5 output  with the BLOB */
666   memcpy(ptr, hmac_output, HMAC_MD5_LENGTH);
667
668   /* Return the response */
669   *ntresp = ptr;
670   *ntresp_len = len;
671
672   return result;
673 }
674
675 /*
676  * Curl_ntlm_core_mk_lmv2_resp()
677  *
678  * This creates the LMv2 response as used in the ntlm type-3 message.
679  *
680  * Parameters:
681  *
682  * ntlmv2hash        [in] - The ntlmv2 hash (16 bytes)
683  * challenge_client  [in] - The client nonce (8 bytes)
684  * challenge_client  [in] - The server challenge (8 bytes)
685  * lmresp           [out] - The LMv2 response (24 bytes)
686  *
687  * Returns CURLE_OK on success.
688  */
689 CURLcode  Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash,
690                                       unsigned char *challenge_client,
691                                       unsigned char *challenge_server,
692                                       unsigned char *lmresp)
693 {
694   unsigned char data[16];
695   unsigned char hmac_output[16];
696   CURLcode result = CURLE_OK;
697
698   memcpy(&data[0], challenge_server, 8);
699   memcpy(&data[8], challenge_client, 8);
700
701   result = Curl_hmacit(Curl_HMAC_MD5, ntlmv2hash, 16, &data[0], 16,
702                        hmac_output);
703   if(result)
704     return result;
705
706   /* Concatenate the HMAC MD5 output  with the client nonce */
707   memcpy(lmresp, hmac_output, 16);
708   memcpy(lmresp + 16, challenge_client, 8);
709
710   return result;
711 }
712
713 #endif /* !USE_WINDOWS_SSPI */
714
715 #endif /* USE_CURL_NTLM_CORE */