Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to replace malloc on iOS?

I'd like to use a custom malloc and free for some allocations in an iOS app, including those made by classes like NSMutableData.

  • Is this possible?
  • If so, how do I do it?

What I'd actually like to do is zero out certain data after I've used it, in order to guarantee forward security (in case the device is lost or stolen) as much as possible. If there's an easier way to do this that doesn't involve replacing malloc then that's great.

I believe I need to replace malloc in order to do this because the sensitive data is stored in the keychain --- and I have no option other than to use NSDictionary, NSString and NSData in order to access this data (I can't even use the mutable versions).

like image 447
James Avatar asked May 03 '11 14:05

James


3 Answers

Instead of overwriting generic memory management functions you can use custom allocators on the sensitive objects.

The keychain services API is written in C and uses Core Foundation objects, like CFDictionary, CFData and CFString. While it's true that these objects are "toll free" bridged to their Objective-C counterparts and are usually interchangeable they have some abilities not available from Objective-C. One of these features is using custom allocators.

CFDictionaryCreate for example takes an argument of type CFAllocatorRef which, in turn, can be created using CFAllocatorCreate. The allocator holds pointers to functions for allocation and deallocation, among others. You can use custom functions to overwrite the sensible data.

like image 104
Nikolai Ruhe Avatar answered Oct 13 '22 02:10

Nikolai Ruhe


Why do you need to go so low-level about it? I'd just overwrite the data in the NSMutableData instance with zeroes instead. If you really need to mess with malloc - I'd probably write a category on NSObject and override the memory-handling functions.

like image 41
iceydee Avatar answered Oct 13 '22 00:10

iceydee


Disclaimer: I have no iOS experience, but I understand that it uses GCC. Assuming that is correct...

I have done this, albeit with GCC on the PlayStation3. I don't know how much of this is transferable to your case. I used the GCC objcopy utility with --weaken-symbol. (You may need to use nm to list the symbols in your library.

Once you've "weakened" the library's malloc, you just write your own, which is then used instead of the original when linked (rather than giving you a link error). To delegate to the original you may have to give it another name somehow (can't remember -- presumably doable with one of the binutils or else there's both a malloc and a _malloc in the library -- sorry, it's been a while.)

Hope that helps.

like image 29
Martin Stone Avatar answered Oct 13 '22 00:10

Martin Stone