[英]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. 我想在我的iOS应用程序中清除内存中的敏感数据。 In Windows I used to use SecureZeroMemory. 在Windows中我曾经使用过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 现在,在iOS中,我使用普通的旧memset,但我有点担心编译器可能会优化它: 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): 释义771-BSI(链接见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. 避免编译器优化的memset调用的一种方法是在memset调用之后再次访问缓冲区,这会强制编译器不优化位置。 This can be achieved by 这可以通过以下方式实现
*(volatile char*)buffer = *(volatile char*)buffer;
after the memset()
call. 在memset()
调用之后。
In fact, you could write a secure_memset()
function 实际上,您可以编写secure_memset()
函数
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.) (代码取自771-BSI。感谢Daniel Trebbien指出前一个代码提案可能存在的缺陷。)
Why does volatile
prevent optimization? 为什么volatile
阻止优化? See https://stackoverflow.com/a/3604588/220060 请参阅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. 更新请同时阅读内存中的敏感数据,因为如果您的iOS系统上有对手,即使在他尝试读取内存之前,您已经或多或少地被搞砸了。 In a summary SecureZeroMemory() or secure_memset() do not really help. 总结SecureZeroMemory()或secure_memset()并没有真正帮助。
The problem is NSData is immutable and you do not have control over what happens. 问题是NSData是不可变的,你无法控制发生的事情。 If the buffer is controlled by you, you could use dataWithBytesNoCopy:length: and NSData will act as a wrapper. 如果缓冲区由您控制,则可以使用dataWithBytesNoCopy:length:并且NSData将充当包装器。 When finished you could memset your buffer. 完成后,您可以设置缓冲区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.