Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to clear sensitive data from memory in iOS?

I want to clear sensitive data from memory in my iOS app. In Windows I used to use SecureZeroMemory. Now, in iOS, I use plain old memset, but I'm a little worried the compiler might optimize it: https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/771-BSI.html

code snippet:

 NSData *someSensitiveData;
 memset((void *)someSensitiveData.bytes, 0, someSensitiveData.length);
like image 279
HyBRiD Avatar asked Apr 02 '12 08:04

HyBRiD


1 Answers

Paraphrasing 771-BSI (link see OP):

A way to avoid having the memset call optimized out by the compiler is to access the buffer again after the memset call in a way that would force the compiler not to optimize the location. This can be achieved by

*(volatile char*)buffer = *(volatile char*)buffer;

after the memset() call.

In fact, you could write a secure_memset() function

void* secure_memset(void *v, int c, size_t n) {
    volatile char *p = v;
    while (n--) *p++ = c;
    return v;
}

(Code taken from 771-BSI. Thanks to Daniel Trebbien for pointing out for a possible defect of the previous code proposal.)

Why does volatile prevent optimization? See https://stackoverflow.com/a/3604588/220060

UPDATE Please also read Sensitive Data In Memory because if you have an adversary on your iOS system, your are already more or less screwed even before he tries to read that memory. In a summary SecureZeroMemory() or secure_memset() do not really help.

like image 187
nalply Avatar answered Nov 15 '22 14:11

nalply