Repository navigation
Expand file tree
/
Copy pathNSData_transformations.m
More file actions
executable file
·437 lines (350 loc) · 13.7 KB
/
Copy pathNSData_transformations.m
File metadata and controls
executable file
·437 lines (350 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*
* Compresses/decompresses data using zlib (see RFC 1950 and /usr/include/zlib.h)
*
* Be sure to add /usr/lib/libz.dylib to the linked frameworks, or add "-lz" to
* 'Other Linker Flags' in the 'Linker Settings' section of the target's
* 'Build Settings'
*
*/
/* NSData_transformations.m */
#import "NSData_transformations.h"
#import "NSFileManager_NV.h"
#import <CommonCrypto/CommonKeyDerivation.h>
#include "broken_md5.h"
#include <unistd.h>
#include <stdint.h>
#include <zlib.h>
#import <CommonCrypto/CommonCrypto.h>
#import <WebKit/WebKit.h>
#import <Security/Security.h>
NSData *ExecuteTransformWithInput(NSData *input, SecTransformRef transform) {
NSData *output = nil;
assert(transform);
assert(input);
if (SecTransformSetAttribute(transform, kSecTransformInputAttributeName, input, NULL))
output = (NSData *)SecTransformExecute(transform, NULL);
return [output autorelease];
}
@implementation NSData (NVUtilities)
/*
* Compress the data, default level of compression
*/
- (NSMutableData *)compressedData {
return [self compressedDataAtLevel:Z_DEFAULT_COMPRESSION];
}
/*
* Compress the data at the given compression level; stores the original data
* size at the end of the compressed data
*/
- (NSMutableData *)compressedDataAtLevel:(int)level {
NSMutableData *newData;
unsigned long bufferLength;
int zlibError;
/*
* zlib says to make sure the destination has 0.1% more + 12 bytes; last
* additional bytes to store the original size (needed for uncompress)
*/
bufferLength = ceil( (float) [self length] * 1.001 ) + 12 + sizeof( unsigned );
newData = [NSMutableData dataWithLength:bufferLength];
if( newData != nil ) {
zlibError = compress2([newData mutableBytes], &bufferLength,
[self bytes], [self length], level);
if (zlibError == Z_OK) {
// Add original size to the end of the buffer, written big-endian
// Use memcpy to avoid undefined behavior from unaligned stores
uint32_t origLenBE = NSSwapHostIntToBig((uint32_t)[self length]);
memcpy(((uint8_t *)[newData mutableBytes]) + bufferLength, &origLenBE, sizeof(origLenBE));
[newData setLength:bufferLength + sizeof(origLenBE)];
} else {
NSLog(@"error compressing: %s", zError(zlibError));
newData = nil;
}
} else
NSLog(@"error compressing: couldn't allocate memory");
return newData;
}
/*
* Decompress data
*/
- (NSMutableData *) uncompressedData {
NSMutableData *newData;
uint32_t originalSize;
unsigned long outSize;
int zlibError;
newData = nil;
if ( [self isCompressedFormat] ) {
// Read original size from the last 4 bytes (big-endian), using memcpy to avoid unaligned loads
uint32_t beSize = 0;
memcpy(&beSize, ((const uint8_t *)[self bytes]) + [self length] - sizeof(beSize), sizeof(beSize));
originalSize = NSSwapBigIntToHost(beSize);
//catch the NSInvalidArgumentException that's thrown if originalSize is too large
NS_DURING
newData = [ NSMutableData dataWithLength:originalSize ];
NS_HANDLER
if ([[localException name] isEqualToString:NSInvalidArgumentException] ) {
NSLog(@"error decompressing--bad size: %@", [localException reason]);
NS_VALUERETURN( nil, NSMutableData * );
} else
[localException raise]; // This should NEVER happen...
NS_ENDHANDLER
if( newData != nil ) {
outSize = originalSize;
zlibError = uncompress([newData mutableBytes], &outSize, [self bytes], [self length] - sizeof(unsigned));
if( zlibError != Z_OK ) {
NSLog(@"decompression failed: %s", zError(zlibError));
newData = nil;
} else if (originalSize != outSize)
NSLog(@"error decompressing: extracted size %lu does not match original of %u", outSize, originalSize);
} else
NSLog(@"error allocating memory while decompressing");
} else
NSLog(@"error decompressing: data does not seem to be compressed with zlib");
return newData;
}
/*
* Quick check of the data to avoid obviously-not-compressed data (see RFC)
*/
- (BOOL)isCompressedFormat {
const unsigned char *bytes;
bytes = [self bytes];
/*
* The checks are:
* ( *bytes & 0x0F ) == 8 : method is deflate (this is called CM compression method, in the RFC)
* ( *bytes & 0x80 ) == 0 : info must be at most seven, this makes sure the MSB is not set, otherwise it
* is at least 8 (this is called CINFO, compression info, in the RFC)
* *( (short *) bytes ) ) % 31 == 0 : the two first bytes as a whole (big endian format) must be a multiple of 31
* (this is discussed in the FCHECK in FLG, flags, section)
*/
if( ( *bytes & 0x0F ) == 8 && ( *bytes & 0x80 ) == 0 ) {
uint16_t hdr = 0;
memcpy(&hdr, bytes, sizeof(hdr)); // avoid potential unaligned short load
if (NSSwapBigShortToHost(hdr) % 31 == 0)
return YES;
}
return NO;
}
+ (NSMutableData *)randomDataOfLength:(int)len {
if (len <= 0) return [NSMutableData data];
NSMutableData *randomData = [NSMutableData dataWithLength:(NSUInteger)len];
OSStatus status = SecRandomCopyBytes(kSecRandomDefault, (size_t)len, [randomData mutableBytes]);
if (status != errSecSuccess) {
NSLog(@"SecRandomCopyBytes failed (status=%d)", (int)status);
return nil;
}
return randomData;
}
- (NSMutableData*)derivedKeyOfLength:(int)len salt:(NSData*)salt iterations:(int)count {
NSMutableData *derivedKey = [NSMutableData dataWithLength:len];
CCStatus status = CCKeyDerivationPBKDF(kCCPBKDF2,
(const char *)[self bytes], (size_t)[self length],
(const uint8_t *)[salt bytes], (size_t)[salt length],
kCCPRFHmacAlgSHA1,
(uint32_t)count,
(uint8_t *)[derivedKey mutableBytes], (size_t)len);
if (status != kCCSuccess) {
NSLog(@"CCKeyDerivationPBKDF failed (status=%d)", (int)status);
return nil;
}
return derivedKey;
}
- (unsigned long)CRC32 {
uLong crc = crc32(0L, Z_NULL, 0);
return crc32(crc, [self bytes], (uInt)[self length]);
}
- (NSData*)SHA1Digest {
unsigned char digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(self.bytes, (CC_LONG)self.length, digest);
return [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
}
- (NSData*)BrokenMD5Digest {
BrokenMD5_CTX context;
NSMutableData *digest = [NSMutableData dataWithLength:16];
BrokenMD5Init(&context);
BrokenMD5Update(&context, [self bytes], (unsigned int)[self length]);
BrokenMD5Final([digest mutableBytes], &context);
return digest;
}
- (NSData*)MD5Digest {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CC_MD5_CTX ctx;
CC_MD5_Init(&ctx);
CC_MD5_Update(&ctx, self.bytes, (CC_LONG)self.length);
unsigned char md[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(md, &ctx);
#pragma clang diagnostic pop
return [NSData dataWithBytes:md length:CC_MD5_DIGEST_LENGTH];
}
- (NSString*)pathURLFromWebArchive {
WebResource *resource = [[[[WebArchive alloc] initWithData:self] autorelease] mainResource];
NSURL *url = [resource URL];
//it's not any kind of URL we want to keep
//this is probably text from another app's internal WebKit view
if ([[url scheme] isEqualToString:@"applewebdata"] || [[url scheme] isEqualToString:@"x-msg"])
return nil;
return [url absoluteString];
}
- (NSData*)bookmarkDataFromLegacyAliasRecord {
if (![self length]) return nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CFDataRef bookmarkData = CFURLCreateBookmarkDataFromAliasRecord(kCFAllocatorDefault, (CFDataRef)self);
#pragma clang diagnostic pop
return [(NSData*)bookmarkData autorelease];
}
+ (NSData*)uncachedDataFromFile:(NSString*)filename {
return [NSData dataWithContentsOfFile:filename options:NSUncachedRead error:NULL];
}
+ (NSData*)legacyAliasDataForFileReferenceURL:(NSURL*)url {
if (![url isFileReferenceURL]) return nil;
NSURL *homeURL = [[NSFileManager defaultManager] homeDirectoryForCurrentUser];
homeURL = [[NSFileManager defaultManager] fileReferenceURLForURL:homeURL error:NULL];
if (!homeURL) return nil;
FSRef targetRef;
FSRef homeRef;
AliasHandle aliasHandle = NULL;
NSData *aliasData = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (CFURLGetFSRef((CFURLRef)url, &targetRef) &&
CFURLGetFSRef((CFURLRef)homeURL, &homeRef) &&
FSNewAlias(&homeRef, &targetRef, &aliasHandle) == noErr && aliasHandle) {
HLock((Handle)aliasHandle);
aliasData = [NSData dataWithBytes:*aliasHandle length:GetHandleSize((Handle)aliasHandle)];
HUnlock((Handle)aliasHandle);
DisposeHandle((Handle)aliasHandle);
}
#pragma clang diagnostic pop
return aliasData;
}
//yes, to do the same encoding detection we could use something like initWithContentsOfFile: or
//initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
//but those 1) require file paths and 2) the non-deprecated version is available only on 10.4
- (NSMutableString*)newStringUsingBOMReturningEncoding:(NSStringEncoding*)encoding {
NSUInteger len = [self length];
NSMutableString *string = nil;
if (len % 2 != 0 || !len) {
return nil;
}
const unichar byteOrderMark = 0xFEFF;
const unichar byteOrderMarkSwapped = 0xFFFE;
BOOL foundBOM = NO;
BOOL swapped = NO;
unsigned char *b = (unsigned char*)[self bytes];
unichar firstWord = 0;
memcpy(&firstWord, b, sizeof(firstWord)); // avoid potential unaligned unichar load
if (firstWord == byteOrderMark) {
b += sizeof(unichar);
len -= sizeof(unichar);
foundBOM = YES;
} else if (firstWord == byteOrderMarkSwapped) {
b += sizeof(unichar);
len -= sizeof(unichar);
swapped = YES;
foundBOM = YES;
} else if (len > 2 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) {
len -= 3;
b += 3;
//false because we just fixed the BOM right up there
//string = (NSString*)CFStringCreateWithBytes(kCFAllocatorDefault, b, len, kCFStringEncodingUTF8, false);
string = [[NSMutableString alloc] initWithBytes:b length:len encoding:NSUTF8StringEncoding];
if (string)
*encoding = NSUTF8StringEncoding;
return string;
}
if (foundBOM) {
unsigned char *u = (unsigned char*)malloc((size_t)len);
if (swapped) {
NSUInteger i;
for (i = 0; i < len; i += 2) {
u[i] = b[i + 1];
u[i + 1] = b[i];
}
} else {
memcpy(u, b, len);
}
string = (NSMutableString*)CFStringCreateMutableWithExternalCharactersNoCopy(NULL, (UniChar *)u, (CFIndex)len/2, (CFIndex)len/2, kCFAllocatorDefault);
if (string)
*encoding = NSUnicodeStringEncoding;
return string;
}
return nil;
}
- (NSString *)encodeBase64WithoutNewlines {
SecTransformRef const transform = SecEncodeTransformCreate(kSecBase64Encoding, NULL);
NSString *const str = [[[NSString alloc] initWithData:ExecuteTransformWithInput(self, transform) encoding:NSASCIIStringEncoding] autorelease];
CFRelease(transform);
return str;
}
@end
@implementation NSMutableData (NVCryptoRelated)
- (void)reverseBytes {
NSInteger head, tail;
unsigned char temp, *str = [self mutableBytes];
if (!str) return;
tail = (NSInteger)[self length] - 1;
for (head = 0; head < tail; ++head, --tail) {
temp = str[tail];
str[tail] = str[head];
str[head] = temp;
}
}
//extends nsmutabledata if necessary
- (void)alignForBlockSize:(int)alignedBlockSize {
NSUInteger dataBlockSize = [self length];
NSUInteger paddedDataBlockSize = 0;
if (dataBlockSize <= (NSUInteger)alignedBlockSize)
paddedDataBlockSize = alignedBlockSize;
else
paddedDataBlockSize = (NSUInteger)alignedBlockSize * ((dataBlockSize + ((NSUInteger)alignedBlockSize-1)) / (NSUInteger)alignedBlockSize);
//if malloc was used on conventional architectures, nsdata should be smart enough not to have to allocate a new block
NSInteger difference = (NSInteger)paddedDataBlockSize - (NSInteger)dataBlockSize;
if (difference > 0)
[self increaseLengthBy:(NSUInteger)difference];
}
static BOOL NVCryptAES256CBC(NSMutableData *data, CCOperation operation,
NSData *key, NSData *iv) {
BOOL encrypting = operation == kCCEncrypt;
if ([key length] != kCCKeySizeAES256) {
NSLog(@"%s key length was wrong size: %lu", encrypting ? "encryption" : "decryption",
(unsigned long)[key length]);
return NO;
}
if ([iv length] != kCCBlockSizeAES128) {
NSLog(@"initialization vector length was wrong size: %lu", (unsigned long)[iv length]);
return NO;
}
size_t bufferLength = [data length] + kCCBlockSizeAES128;
NSMutableData *buffer = [NSMutableData dataWithLength:bufferLength];
if (!buffer) return NO;
/* CommonCrypto does not validate every PKCS#7 byte when decrypting. Keep
* encryption compatible, but decrypt whole blocks and validate below. */
CCOptions options = encrypting ? kCCOptionPKCS7Padding : 0;
size_t bytesMoved = 0;
CCCryptorStatus status = CCCrypt(operation, kCCAlgorithmAES, options,
[key bytes], kCCKeySizeAES256, [iv bytes], [data bytes], [data length],
[buffer mutableBytes], bufferLength, &bytesMoved);
if (status != kCCSuccess) {
NSLog(@"Couldn't %s data (status=%d)", encrypting ? "encrypt" : "decrypt", (int)status);
return NO;
}
if (!encrypting) {
if (!bytesMoved || bytesMoved % kCCBlockSizeAES128) return NO;
const uint8_t *bytes = [buffer bytes];
uint8_t paddingLength = bytes[bytesMoved - 1];
if (!paddingLength || paddingLength > kCCBlockSizeAES128) return NO;
for (size_t i = bytesMoved - paddingLength; i < bytesMoved; i++)
if (bytes[i] != paddingLength) return NO;
bytesMoved -= paddingLength;
}
[buffer setLength:bytesMoved];
[data setData:buffer];
return YES;
}
- (BOOL)encryptAESDataWithKey:(NSData*)key iv:(NSData*)iv {
return NVCryptAES256CBC(self, kCCEncrypt, key, iv);
}
- (BOOL)decryptAESDataWithKey:(NSData*)key iv:(NSData*)iv {
return NVCryptAES256CBC(self, kCCDecrypt, key, iv);
}
@end