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

六眼飞鱼酱① 提交于 2019-11-29 18:03:31

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9973260/what-is-the-correct-way-to-clear-sensitive-data-from-memory-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!