Search code examples
iosobjective-cnsstringnsdatamemset

OBJ-C wipe NSData content before nullifying it


For security reasons we need Always to wipe sensitive data from memory. Usually it is not something that i see done in IOS but for apps and need extended security it is very important.

The Data that Usually needs to be wiped if NSData and NSString objects (pointing to nil does not wipe the data and it is a security breach)

I've managed to wipe my NSStrings with the code below (When password is NSString):

unsigned char *charPass;
if (password != nil) {
    charPass = (unsigned char*) CFStringGetCStringPtr((CFStringRef) password, CFStringGetSystemEncoding());
    memset(charPass, 0, [password length]);
    password = nil;
}
  • Big remark on this implementation: You HAVE to check for NULL before calling the charPass or it might crash. There is NO guarantee that CFStringGetCStringPtr will return a value!

When password is NSData It suppose to be even more strait forward and the code bellow suppose to work:

memset([password bytes], 0, [password length]);

But this gives me a compilation error:

No matching function for call to 'memset'

I can't find a workaround to point to the password address and wipe the bytes over there like I did with the string (bytes method should let me do just that from what I understand but it doesn't compile for some reason that I cant figure out)

Any one has an idea for this?

10x


Solution

  • While I cannot speak for the actual safety of doing this, your problem is that NSData's bytes method returns a const void *

    https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc

    You can cast it to a void * if you want by

    memset((void *)[password bytes], 0, [password length]);
    

    If you use a NSMutableData, you won't have to do this.