2 * Copyright (c) 2000-2004,2006-2008,2010-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 * ntlmBlobPriv.c - Private routines used by NtlmGenerator module.
28 #include "ntlmBlobPriv.h"
29 #include <Security/SecBase.h>
31 #include <sys/types.h>
34 #include <sys/param.h>
41 #include <CommonCrypto/CommonDigest.h>
42 #include <CommonCrypto/CommonCryptor.h>
43 #include <CommonCrypto/CommonHMAC.h>
44 #include <CoreFoundation/CFDate.h>
45 #include <Security/SecFramework.h>
46 #include <Security/SecRandom.h>
47 #include <utilities/SecCFWrappers.h>
49 #if DEBUG_FIXED_CHALLENGE
50 /* Fixed 64-bit timestamp for sourceforge test vectors */
51 static unsigned char dbgStamp
[] =
53 0x00, 0x90, 0xd3, 0x36, 0xb7, 0x34, 0xc3, 0x01
55 #endif /* DEBUG_FIXED_CHALLENGE */
58 // MARK: Encode/Decode Routines
60 /* write a 64-bit word, little endian */
67 OSWriteLittleInt64(cb
, 0, word
);
68 CFDataAppendBytes(buf
, cb
, 8);
70 /* This is an alternate implementation which may or may not be faster than
72 CFIndex offset
= CFDataGetLength(buf
);
73 UInt8
*bytes
= CFDataGetMutableBytePtr(buf
);
74 CFDataIncreaseLength(buf
, 8);
75 OSWriteLittleInt64(bytes
, offset
, word
);
79 /* write a 32-bit word, little endian */
86 OSWriteLittleInt32(cb
, 0, word
);
87 CFDataAppendBytes(buf
, cb
, 4);
89 /* This is an alternate implementation which may or may not be faster than
91 CFIndex offset
= CFDataGetLength(buf
);
92 UInt8
*bytes
= CFDataGetMutableBytePtr(buf
);
93 CFDataIncreaseLength(buf
, 4);
94 OSWriteLittleInt32(bytes
, offset
, word
);
98 /* write a 16-bit word, little endian */
100 CFMutableDataRef buf
,
104 OSWriteLittleInt16(cb
, 0, word
);
105 CFDataAppendBytes(buf
, cb
, 2);
109 * Write a security buffer, providing the index into the CFData at which
110 * this security buffer's offset is located. Just before the actual data is written,
111 * go back and update the offset with the start of that data using secBufOffset().
114 CFMutableDataRef buf
,
116 CFIndex
*offsetIndex
)
120 OSWriteLittleInt16(cb
, 0, len
); /* buffer length */
121 OSWriteLittleInt16(cb
, 2, len
); /* buffer allocated size */
122 OSWriteLittleInt32(cb
, 4, 0); /* offset is empty for now */
123 CFDataAppendBytes(buf
, cb
, 8);
124 *offsetIndex
= CFDataGetLength(buf
) - 4; /* offset will go here */
126 appendUint16(buf
, len
); /* buffer length */
127 appendUint16(buf
, len
); /* buffer allocated size */
128 *offsetIndex
= CFDataGetLength(buf
); /* offset will go here */
129 appendUint32(buf
, 0); /* but it's empty for now */
134 * Update a security buffer's offset to be the current end of data in a CFData.
137 CFMutableDataRef buf
,
138 CFIndex offsetIndex
) /* obtained from appendSecBuf() */
140 CFIndex currPos
= CFDataGetLength(buf
);
142 OSWriteLittleInt32(cb
, 0, (uint32_t)currPos
);
143 CFRange range
= {offsetIndex
, 4};
144 CFDataReplaceBytes(buf
, range
, cb
, 4);
148 * Parse/validate a security buffer. Verifies that supplied offset/length don't go
149 * past end of avaialble data. Returns ptr to actual data and its length. Returns
150 * NTLM_ERR_PARSE_ERR on bogus values.
152 OSStatus
ntlmParseSecBuffer(
153 const unsigned char *cp
, /* start of security buffer */
154 const unsigned char *bufStart
, /* start of whole msg buffer */
155 unsigned bufLen
, /* # of valid bytes starting at bufStart */
156 const unsigned char **data
, /* RETURNED, start of actual data */
157 uint16_t *dataLen
) /* RETURNED, length of actual data */
159 assert(cp
>= bufStart
);
161 uint16_t secBufLen
= OSReadLittleInt16(cp
, 0);
162 /* skip length we just parsed plus alloc size, which we don't use */
164 uint32_t offset
= OSReadLittleInt32(cp
, 0);
165 if((offset
+ secBufLen
) > bufLen
) {
166 dprintf("ntlmParseSecBuffer: buf overflow\n");
167 return NTLM_ERR_PARSE_ERR
;
169 *data
= bufStart
+ offset
;
170 *dataLen
= secBufLen
;
171 return errSecSuccess
;
175 // MARK: CFString Converters
178 * Convert CFString to little-endian unicode.
180 OSStatus
ntlmStringToLE(
182 unsigned char **ucode
, // mallocd and RETURNED
183 unsigned *ucodeLen
) // RETURNED
185 CFIndex len
= CFStringGetLength(pwd
);
186 if (len
> NTLM_MAX_STRING_LEN
)
187 return errSecAllocate
;
188 unsigned char *data
= (unsigned char *)malloc(len
* 2);
190 return errSecAllocate
;
191 unsigned char *cp
= data
;
194 for(dex
=0; dex
<len
; dex
++) {
195 UniChar uc
= CFStringGetCharacterAtIndex(pwd
, dex
);
200 *ucodeLen
= (unsigned)(len
* 2);
202 return errSecSuccess
;
206 * Convert a CFStringRef into a mallocd array of chars suitable for the specified
207 * encoding. This might return an error if the string can't be converted
210 OSStatus
ntlmStringFlatten(
213 unsigned char **flat
, // mallocd and RETURNED
214 unsigned *flatLen
) // RETURNED
217 /* convert to little-endian unicode */
218 return ntlmStringToLE(str
, flat
, flatLen
);
221 /* convert to ASCII C string */
222 CFIndex strLen
= CFStringGetLength(str
);
223 if (strLen
> NTLM_MAX_STRING_LEN
)
224 return errSecAllocate
;
226 char *cStr
= (char *)malloc(strLen
+ 1);
228 return errSecAllocate
;
230 if(CFStringGetCString(str
, cStr
, strLen
+ 1, kCFStringEncodingASCII
)) {
231 *flat
= (unsigned char *)cStr
;
232 *flatLen
= (unsigned)strLen
;
233 return errSecSuccess
;
237 * Well that didn't work. Try UTF8 - I don't know how a MS would behave if
238 * this portion of auth (only used for the LM response) didn't work.
240 dprintf("ntlmStringFlatten: ASCII password conversion failed; trying UTF8\n");
243 CFDataRef dataFromString
= CFStringCreateExternalRepresentation(NULL
, str
, kCFStringEncodingUTF8
, 0);
245 *flatLen
= (unsigned)CFDataGetLength(dataFromString
);
246 *flat
= malloc(*flatLen
);
248 CFRelease(dataFromString
);
249 return errSecAllocate
;
251 memcpy(*flat
, CFDataGetBytePtr(dataFromString
), *flatLen
);
252 CFReleaseNull(dataFromString
);
253 return errSecSuccess
;
255 dprintf("lmPasswordHash: UTF8 password conversion failed\n");
256 CFReleaseNull(dataFromString
);
257 return NTLM_ERR_PARSE_ERR
;
262 // MARK: Machine Dependent Cruft
264 /* random number generator */
267 void *buf
) /* allocated by caller, random data RETURNED */
270 status
=SecRandomCopyBytes(kSecRandomDefault
, len
, buf
);
271 (void)status
; // Prevent warning
274 /* Obtain host name in appropriate encoding */
275 OSStatus
ntlmHostName(
277 unsigned char **flat
, // mallocd and RETURNED
278 unsigned *flatLen
) // RETURNED
280 char hostname
[] = "WORKSTATION";
281 size_t len
= strlen(hostname
);
283 /* quickie "little endian unicode" conversion */
284 *flat
= (unsigned char *)malloc(len
* 2);
285 unsigned char *cp
= *flat
;
287 for(dex
=0; dex
<len
; dex
++) {
288 *cp
++ = hostname
[dex
];
291 *flatLen
= (unsigned)len
* 2;
292 return errSecSuccess
;
295 *flat
= (unsigned char *)malloc(len
+1);
296 *flatLen
= (unsigned)len
;
297 memmove(*flat
, hostname
, len
);
298 flat
[len
] = NULL
; // ensure null terminator
299 return errSecSuccess
;
304 * Append 64-bit little-endiam timestamp to a CFData. Time is relative to
305 * January 1 1601, in tenths of a microsecond.
308 CFGiblisGetSingleton(CFAbsoluteTime
, ntlmGetBasis
, ntlmBasisAbsoluteTime
, ^{
309 *ntlmBasisAbsoluteTime
= CFAbsoluteTimeForGregorianZuluDay(1601, 1, 1);
312 void ntlmAppendTimestamp(
313 CFMutableDataRef ntlmV2Blob
)
315 #if DEBUG_FIXED_CHALLENGE
316 /* Fixed 64-bit timestamp for sourceforge test vectors */
317 CFDataAppendBytes(ntlmV2Blob
, dbgStamp
, 8);
320 CFAbsoluteTime nowTime
= CFAbsoluteTimeGetCurrent();
322 /* elapsed := time in seconds since basis */
323 CFTimeInterval elapsed
= nowTime
- ntlmGetBasis();
324 /* now in tenths of microseconds */
325 elapsed
*= 10000000.0;
327 appendUint64(ntlmV2Blob
, (uint64_t)elapsed
);
334 /* MD4 and MD5 hash */
335 #define NTLM_DIGEST_LENGTH 16
337 const unsigned char *data
,
339 unsigned char *digest
) // caller-supplied, NTLM_DIGEST_LENGTH */
341 #pragma clang diagnostic push
342 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
345 CC_MD4_Update(&ctx
, data
, dataLen
);
346 CC_MD4_Final(digest
, &ctx
);
347 #pragma clang diagnostic pop
351 const unsigned char *data
,
353 unsigned char *digest
) // caller-supplied, NTLM_DIGEST_LENGTH */
355 #pragma clang diagnostic push
356 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
359 CC_MD5_Update(&ctx
, data
, dataLen
);
360 CC_MD5_Final(digest
, &ctx
);
361 #pragma clang diagnostic pop
365 * Given 7 bytes, create 8-byte DES key. Our implementation ignores the
366 * parity bit (lsb), which simplifies this somewhat.
369 const unsigned char *inKey
, // 7 bytes
370 unsigned char *outKey
) // 8 bytes
372 outKey
[0] = inKey
[0] & 0xfe;
373 outKey
[1] = ((inKey
[0] << 7) | (inKey
[1] >> 1)) & 0xfe;
374 outKey
[2] = ((inKey
[1] << 6) | (inKey
[2] >> 2)) & 0xfe;
375 outKey
[3] = ((inKey
[2] << 5) | (inKey
[3] >> 3)) & 0xfe;
376 outKey
[4] = ((inKey
[3] << 4) | (inKey
[4] >> 4)) & 0xfe;
377 outKey
[5] = ((inKey
[4] << 3) | (inKey
[5] >> 5)) & 0xfe;
378 outKey
[6] = ((inKey
[5] << 2) | (inKey
[6] >> 6)) & 0xfe;
379 outKey
[7] = (inKey
[6] << 1) & 0xfe;
383 * single block DES encrypt.
384 * This would really benefit from a DES implementation in CommonCrypto.
386 OSStatus
ntlmDesCrypt(
387 const unsigned char *key
, // 8 bytes
388 const unsigned char *inData
, // 8 bytes
389 unsigned char *outData
) // 8 bytes
392 return CCCrypt(kCCEncrypt
, kCCAlgorithmDES
, 0, key
, kCCKeySizeDES
,
393 NULL
/*no iv, 1 block*/, inData
, 1 * kCCBlockSizeDES
, outData
,
394 1 * kCCBlockSizeDES
, &data_moved
);
400 OSStatus
ntlmHmacMD5(
401 const unsigned char *key
,
403 const unsigned char *inData
,
405 unsigned char *mac
) // caller provided, NTLM_DIGEST_LENGTH
407 CCHmacContext hmac_md5_context
;
409 CCHmacInit(&hmac_md5_context
, kCCHmacAlgMD5
, key
, keyLen
);
410 CCHmacUpdate(&hmac_md5_context
, inData
, inDataLen
);
411 CCHmacFinal(&hmac_md5_context
, mac
);
413 return errSecSuccess
;
417 // MARK: NTLM password and digest munging
421 * Calculate NTLM password hash (MD4 on a unicode password).
423 OSStatus
ntlmPasswordHash(
425 unsigned char *digest
) // caller-supplied, NTLM_DIGEST_LENGTH
431 /* convert to little-endian unicode */
432 res
= ntlmStringToLE(pwd
, &data
, &len
);
435 /* md4 hash of that */
436 md4Hash(data
, len
, digest
);
443 * NTLM response: DES encrypt the challenge (or session hash) with three
444 * different keys derived from the password hash. Result is concatenation
445 * of three DES encrypts.
447 #define ALL_KEYS_LENGTH (3 * DES_RAW_KEY_SIZE)
448 OSStatus
lmv2Response(
449 const unsigned char *digest
, // NTLM_DIGEST_LENGTH bytes
450 const unsigned char *ptext
, // challenge or session hash
451 unsigned char *ntlmResp
) // caller-supplied NTLM_LM_RESPONSE_LEN
453 unsigned char allKeys
[ALL_KEYS_LENGTH
];
454 unsigned char key1
[DES_KEY_SIZE
], key2
[DES_KEY_SIZE
], key3
[DES_KEY_SIZE
];
457 memmove(allKeys
, digest
, NTLM_DIGEST_LENGTH
);
458 memset(allKeys
+ NTLM_DIGEST_LENGTH
, 0, ALL_KEYS_LENGTH
- NTLM_DIGEST_LENGTH
);
459 ntlmMakeDesKey(allKeys
, key1
);
460 ntlmMakeDesKey(allKeys
+ DES_RAW_KEY_SIZE
, key2
);
461 ntlmMakeDesKey(allKeys
+ (2 * DES_RAW_KEY_SIZE
), key3
);
462 ortn
= ntlmDesCrypt(key1
, ptext
, ntlmResp
);
463 if(ortn
== errSecSuccess
) {
464 ortn
= ntlmDesCrypt(key2
, ptext
, ntlmResp
+ DES_BLOCK_SIZE
);
466 if(ortn
== errSecSuccess
) {
467 ortn
= ntlmDesCrypt(key3
, ptext
, ntlmResp
+ (2 * DES_BLOCK_SIZE
));