简体   繁体   中英

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);

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.

The problem is NSData is immutable and you do not have control over what happens. If the buffer is controlled by you, you could use dataWithBytesNoCopy:length: and NSData will act as a wrapper. When finished you could memset your buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM