]> git.saurik.com Git - apple/security.git/blob - ntlm/ntlmBlobPriv.c
Security-58286.200.222.tar.gz
[apple/security.git] / ntlm / ntlmBlobPriv.c
1 /*
2 * Copyright (c) 2000-2004,2006-2008,2010-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /*
25 * ntlmBlobPriv.c - Private routines used by NtlmGenerator module.
26 */
27
28 #include "ntlmBlobPriv.h"
29 #include <Security/SecBase.h>
30
31 #include <sys/types.h>
32 #include <sys/uio.h>
33 #include <unistd.h>
34 #include <sys/param.h>
35 #include <stdlib.h>
36 #include <stdint.h>
37 #include <assert.h>
38 #include <fcntl.h>
39 #include <ctype.h>
40 #include <strings.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>
48
49 #if DEBUG_FIXED_CHALLENGE
50 /* Fixed 64-bit timestamp for sourceforge test vectors */
51 static unsigned char dbgStamp[] =
52 {
53 0x00, 0x90, 0xd3, 0x36, 0xb7, 0x34, 0xc3, 0x01
54 };
55 #endif /* DEBUG_FIXED_CHALLENGE */
56
57 // MARK: -
58 // MARK: Encode/Decode Routines
59
60 /* write a 64-bit word, little endian */
61 void appendUint64(
62 CFMutableDataRef buf,
63 uint64_t word)
64 {
65 #if 1
66 unsigned char cb[8];
67 OSWriteLittleInt64(cb, 0, word);
68 CFDataAppendBytes(buf, cb, 8);
69 #else
70 /* This is an alternate implementation which may or may not be faster than
71 the above. */
72 CFIndex offset = CFDataGetLength(buf);
73 UInt8 *bytes = CFDataGetMutableBytePtr(buf);
74 CFDataIncreaseLength(buf, 8);
75 OSWriteLittleInt64(bytes, offset, word);
76 #endif
77 }
78
79 /* write a 32-bit word, little endian */
80 void appendUint32(
81 CFMutableDataRef buf,
82 uint32_t word)
83 {
84 #if 1
85 unsigned char cb[4];
86 OSWriteLittleInt32(cb, 0, word);
87 CFDataAppendBytes(buf, cb, 4);
88 #else
89 /* This is an alternate implementation which may or may not be faster than
90 the above. */
91 CFIndex offset = CFDataGetLength(buf);
92 UInt8 *bytes = CFDataGetMutableBytePtr(buf);
93 CFDataIncreaseLength(buf, 4);
94 OSWriteLittleInt32(bytes, offset, word);
95 #endif
96 }
97
98 /* write a 16-bit word, little endian */
99 void appendUint16(
100 CFMutableDataRef buf,
101 uint16_t word)
102 {
103 unsigned char cb[2];
104 OSWriteLittleInt16(cb, 0, word);
105 CFDataAppendBytes(buf, cb, 2);
106 }
107
108 /*
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().
112 */
113 void appendSecBuf(
114 CFMutableDataRef buf,
115 uint16_t len,
116 CFIndex *offsetIndex)
117 {
118 #if 1
119 unsigned char cb[8];
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 */
125 #else
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 */
130 #endif
131 }
132
133 /*
134 * Update a security buffer's offset to be the current end of data in a CFData.
135 */
136 void secBufOffset(
137 CFMutableDataRef buf,
138 CFIndex offsetIndex) /* obtained from appendSecBuf() */
139 {
140 CFIndex currPos = CFDataGetLength(buf);
141 unsigned char cb[4];
142 OSWriteLittleInt32(cb, 0, (uint32_t)currPos);
143 CFRange range = {offsetIndex, 4};
144 CFDataReplaceBytes(buf, range, cb, 4);
145 }
146
147 /*
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.
151 */
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 */
158 {
159 assert(cp >= bufStart);
160
161 uint16_t secBufLen = OSReadLittleInt16(cp, 0);
162 /* skip length we just parsed plus alloc size, which we don't use */
163 cp += 4;
164 uint32_t offset = OSReadLittleInt32(cp, 0);
165 if((offset + secBufLen) > bufLen) {
166 dprintf("ntlmParseSecBuffer: buf overflow\n");
167 return NTLM_ERR_PARSE_ERR;
168 }
169 *data = bufStart + offset;
170 *dataLen = secBufLen;
171 return errSecSuccess;
172 }
173
174 // MARK: -
175 // MARK: CFString Converters
176
177 /*
178 * Convert CFString to little-endian unicode.
179 */
180 OSStatus ntlmStringToLE(
181 CFStringRef pwd,
182 unsigned char **ucode, // mallocd and RETURNED
183 unsigned *ucodeLen) // RETURNED
184 {
185 CFIndex len = CFStringGetLength(pwd);
186 if (len > NTLM_MAX_STRING_LEN)
187 return errSecAllocate;
188 unsigned char *data = (unsigned char *)malloc(len * 2);
189 if (data == NULL)
190 return errSecAllocate;
191 unsigned char *cp = data;
192
193 CFIndex dex;
194 for(dex=0; dex<len; dex++) {
195 UniChar uc = CFStringGetCharacterAtIndex(pwd, dex);
196 *cp++ = uc & 0xff;
197 *cp++ = uc >> 8;
198 }
199 *ucode = data;
200 *ucodeLen = (unsigned)(len * 2);
201
202 return errSecSuccess;
203 }
204
205 /*
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
208 * appropriately.
209 */
210 OSStatus ntlmStringFlatten(
211 CFStringRef str,
212 bool unicode,
213 unsigned char **flat, // mallocd and RETURNED
214 unsigned *flatLen) // RETURNED
215 {
216 if(unicode) {
217 /* convert to little-endian unicode */
218 return ntlmStringToLE(str, flat, flatLen);
219 }
220 else {
221 /* convert to ASCII C string */
222 CFIndex strLen = CFStringGetLength(str);
223 if (strLen > NTLM_MAX_STRING_LEN)
224 return errSecAllocate;
225
226 char *cStr = (char *)malloc(strLen + 1);
227 if(cStr == NULL) {
228 return errSecAllocate;
229 }
230 if(CFStringGetCString(str, cStr, strLen + 1, kCFStringEncodingASCII)) {
231 *flat = (unsigned char *)cStr;
232 *flatLen = (unsigned)strLen;
233 return errSecSuccess;
234 }
235
236 /*
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.
239 */
240 dprintf("ntlmStringFlatten: ASCII password conversion failed; trying UTF8\n");
241 free(cStr);
242
243 CFDataRef dataFromString = CFStringCreateExternalRepresentation(NULL, str, kCFStringEncodingUTF8, 0);
244 if(dataFromString) {
245 *flatLen = (unsigned)CFDataGetLength(dataFromString);
246 *flat = malloc(*flatLen);
247 if (*flat == NULL) {
248 CFRelease(dataFromString);
249 return errSecAllocate;
250 }
251 memcpy(*flat, CFDataGetBytePtr(dataFromString), *flatLen);
252 CFReleaseNull(dataFromString);
253 return errSecSuccess;
254 }
255 dprintf("lmPasswordHash: UTF8 password conversion failed\n");
256 CFReleaseNull(dataFromString);
257 return NTLM_ERR_PARSE_ERR;
258 }
259 }
260
261 // MARK: -
262 // MARK: Machine Dependent Cruft
263
264 /* random number generator */
265 void ntlmRand(
266 unsigned len,
267 void *buf) /* allocated by caller, random data RETURNED */
268 {
269 int status;
270 status=SecRandomCopyBytes(kSecRandomDefault, len, buf);
271 (void)status; // Prevent warning
272 }
273
274 /* Obtain host name in appropriate encoding */
275 OSStatus ntlmHostName(
276 bool unicode,
277 unsigned char **flat, // mallocd and RETURNED
278 unsigned *flatLen) // RETURNED
279 {
280 char hostname[] = "WORKSTATION";
281 size_t len = strlen(hostname);
282 if(unicode) {
283 /* quickie "little endian unicode" conversion */
284 *flat = (unsigned char *)malloc(len * 2);
285 unsigned char *cp = *flat;
286 size_t dex;
287 for(dex=0; dex<len; dex++) {
288 *cp++ = hostname[dex];
289 *cp++ = 0;
290 }
291 *flatLen = (unsigned)len * 2;
292 return errSecSuccess;
293 }
294 else {
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;
300 }
301 }
302
303 /*
304 * Append 64-bit little-endiam timestamp to a CFData. Time is relative to
305 * January 1 1601, in tenths of a microsecond.
306 */
307
308 CFGiblisGetSingleton(CFAbsoluteTime, ntlmGetBasis, ntlmBasisAbsoluteTime, ^{
309 *ntlmBasisAbsoluteTime = CFAbsoluteTimeForGregorianZuluDay(1601, 1, 1);
310 });
311
312 void ntlmAppendTimestamp(
313 CFMutableDataRef ntlmV2Blob)
314 {
315 #if DEBUG_FIXED_CHALLENGE
316 /* Fixed 64-bit timestamp for sourceforge test vectors */
317 CFDataAppendBytes(ntlmV2Blob, dbgStamp, 8);
318 #else
319
320 CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
321
322 /* elapsed := time in seconds since basis */
323 CFTimeInterval elapsed = nowTime - ntlmGetBasis();
324 /* now in tenths of microseconds */
325 elapsed *= 10000000.0;
326
327 appendUint64(ntlmV2Blob, (uint64_t)elapsed);
328 #endif
329 }
330
331 // MARK: -
332 // MARK: Crypto
333
334 /* MD4 and MD5 hash */
335 #define NTLM_DIGEST_LENGTH 16
336 void md4Hash(
337 const unsigned char *data,
338 unsigned dataLen,
339 unsigned char *digest) // caller-supplied, NTLM_DIGEST_LENGTH */
340 {
341 CC_MD4_CTX ctx;
342 CC_MD4_Init(&ctx);
343 CC_MD4_Update(&ctx, data, dataLen);
344 CC_MD4_Final(digest, &ctx);
345 }
346
347 void md5Hash(
348 const unsigned char *data,
349 unsigned dataLen,
350 unsigned char *digest) // caller-supplied, NTLM_DIGEST_LENGTH */
351 {
352 CC_MD5_CTX ctx;
353 CC_MD5_Init(&ctx);
354 CC_MD5_Update(&ctx, data, dataLen);
355 CC_MD5_Final(digest, &ctx);
356 }
357
358 /*
359 * Given 7 bytes, create 8-byte DES key. Our implementation ignores the
360 * parity bit (lsb), which simplifies this somewhat.
361 */
362 void ntlmMakeDesKey(
363 const unsigned char *inKey, // 7 bytes
364 unsigned char *outKey) // 8 bytes
365 {
366 outKey[0] = inKey[0] & 0xfe;
367 outKey[1] = ((inKey[0] << 7) | (inKey[1] >> 1)) & 0xfe;
368 outKey[2] = ((inKey[1] << 6) | (inKey[2] >> 2)) & 0xfe;
369 outKey[3] = ((inKey[2] << 5) | (inKey[3] >> 3)) & 0xfe;
370 outKey[4] = ((inKey[3] << 4) | (inKey[4] >> 4)) & 0xfe;
371 outKey[5] = ((inKey[4] << 3) | (inKey[5] >> 5)) & 0xfe;
372 outKey[6] = ((inKey[5] << 2) | (inKey[6] >> 6)) & 0xfe;
373 outKey[7] = (inKey[6] << 1) & 0xfe;
374 }
375
376 /*
377 * single block DES encrypt.
378 * This would really benefit from a DES implementation in CommonCrypto.
379 */
380 OSStatus ntlmDesCrypt(
381 const unsigned char *key, // 8 bytes
382 const unsigned char *inData, // 8 bytes
383 unsigned char *outData) // 8 bytes
384 {
385 size_t data_moved;
386 return CCCrypt(kCCEncrypt, kCCAlgorithmDES, 0, key, kCCKeySizeDES,
387 NULL /*no iv, 1 block*/, inData, 1 * kCCBlockSizeDES, outData,
388 1 * kCCBlockSizeDES, &data_moved);
389 }
390
391 /*
392 * HMAC/MD5.
393 */
394 OSStatus ntlmHmacMD5(
395 const unsigned char *key,
396 unsigned keyLen,
397 const unsigned char *inData,
398 unsigned inDataLen,
399 unsigned char *mac) // caller provided, NTLM_DIGEST_LENGTH
400 {
401 CCHmacContext hmac_md5_context;
402
403 CCHmacInit(&hmac_md5_context, kCCHmacAlgMD5, key, keyLen);
404 CCHmacUpdate(&hmac_md5_context, inData, inDataLen);
405 CCHmacFinal(&hmac_md5_context, mac);
406
407 return errSecSuccess;
408 }
409
410 // MARK: -
411 // MARK: NTLM password and digest munging
412
413
414 /*
415 * Calculate NTLM password hash (MD4 on a unicode password).
416 */
417 OSStatus ntlmPasswordHash(
418 CFStringRef pwd,
419 unsigned char *digest) // caller-supplied, NTLM_DIGEST_LENGTH
420 {
421 OSStatus res;
422 unsigned char *data;
423 unsigned len;
424
425 /* convert to little-endian unicode */
426 res = ntlmStringToLE(pwd, &data, &len);
427 if (res)
428 return res;
429 /* md4 hash of that */
430 md4Hash(data, len, digest);
431 free(data);
432
433 return 0;
434 }
435
436 /*
437 * NTLM response: DES encrypt the challenge (or session hash) with three
438 * different keys derived from the password hash. Result is concatenation
439 * of three DES encrypts.
440 */
441 #define ALL_KEYS_LENGTH (3 * DES_RAW_KEY_SIZE)
442 OSStatus lmv2Response(
443 const unsigned char *digest, // NTLM_DIGEST_LENGTH bytes
444 const unsigned char *ptext, // challenge or session hash
445 unsigned char *ntlmResp) // caller-supplied NTLM_LM_RESPONSE_LEN
446 {
447 unsigned char allKeys[ALL_KEYS_LENGTH];
448 unsigned char key1[DES_KEY_SIZE], key2[DES_KEY_SIZE], key3[DES_KEY_SIZE];
449 OSStatus ortn;
450
451 memmove(allKeys, digest, NTLM_DIGEST_LENGTH);
452 memset(allKeys + NTLM_DIGEST_LENGTH, 0, ALL_KEYS_LENGTH - NTLM_DIGEST_LENGTH);
453 ntlmMakeDesKey(allKeys, key1);
454 ntlmMakeDesKey(allKeys + DES_RAW_KEY_SIZE, key2);
455 ntlmMakeDesKey(allKeys + (2 * DES_RAW_KEY_SIZE), key3);
456 ortn = ntlmDesCrypt(key1, ptext, ntlmResp);
457 if(ortn == errSecSuccess) {
458 ortn = ntlmDesCrypt(key2, ptext, ntlmResp + DES_BLOCK_SIZE);
459 }
460 if(ortn == errSecSuccess) {
461 ortn = ntlmDesCrypt(key3, ptext, ntlmResp + (2 * DES_BLOCK_SIZE));
462 }
463 return ortn;
464 }
465