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

前端 未结 2 526
粉色の甜心
粉色の甜心 2021-01-02 03:45

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 compi

相关标签:
2条回答
  • 2021-01-02 04:22

    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.

    0 讨论(0)
  • 2021-01-02 04:35

    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.

    0 讨论(0)
提交回复
热议问题