简体   繁体   English

在Linux中使用C的零RAM

[英]Zero RAM using C in Linux

How can I zero unused RAM in Linux for security purposes ? 为了安全起见,如何在Linux中将未使用的RAM归零? I wrote this simple C program but I do not know if the RAM called by malloc will be reused at the next loop or if new RAM will be used. 我写了这个简单的C程序,但是我不知道malloc调用的RAM是否将在下一个循环中重用,或者是否将使用新的RAM。 Hopefully, after a few minutes the entire RAM will have been zeroed. 希望几分钟后,整个RAM将被清零。

#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char *a = NULL; // declare variable

    while(1) // infinite loop
    {
        a = malloc(524288); // half a MB
        memset(a, 0, 524288); // zero
        free(a); // free

        sleep(1); // sleep for 1 second
    }
}

Linux already has a kernel process that is zeroing memory using idle cycles so it will have memory ready to hand to processes that request it. Linux已经有一个内核进程,该进程使用空闲周期将内存清零,因此它将准备好处理请求它的进程的内存。

Your loop may or may not zero different memory depending on the particular malloc implementation. 您的循环可能会或可能不会将不同的内存归零,具体取决于特定的malloc实现。 If you really want to write a process like you describe, look into using sbrk directly to ensure you're cycling memory in and out of your process. 如果您真的想编写一个像您描述的那样的进程,请直接使用sbrk来确保您将内存循环到进程之外。 I bet if you check you'll find every byte given to you by sbrk is already zero, though. 我敢打赌,如果您检查一下,就会发现sbrk给您的每个字节已经为零。

You can't zero system RAM. 您不能将系统RAM调零。 The system owns it. 系统拥有它。 If you want to run a system which zeros the RAM then you need to write your own OS! 如果要运行将RAM归零的系统,则需要编写自己的OS!

As long as you never access uninitialized memory, you don't have to worry about what someone else left behind. 只要您从不访问未初始化的内存,就不必担心别人留下了什么。 As long as you never free memory before zeroing it out, you don't have to worry about what you have left behind. 只要您在将内存清零之前从不释放内存,就不必担心遗忘了什么。

I think you need to write a kernel module to actually do this reliably. 我认为您需要编写一个内核模块才能真正可靠地执行此操作。 And then you still could only zero unused pages. 然后您仍然只能将未使用的页面归零。 Note that pages that were used by other processes will be cleared automatically by the kernel on allocation. 注意,其他进程使用的页面将在分配时由内核自动清除。

What are you trying to do? 你想做什么? Avoid cold boot attacks? 避免冷启动攻击?

Typically, on my system (2.6.36) I can free all the unused (but allocated) memory by just doing a while(1) malloc(); 通常,在我的系统(2.6.36)上,我可以通过执行while(1)malloc()释放所有未使用(但已分配)的内存; loop, and killing it when it stops allocating memory. 循环,并在停止分配内存时将其杀死。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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