在 Linux 中使用 C 实现零 RAM
出于安全目的,如何将 Linux 中未使用的 RAM 归零?我编写了这个简单的 C 程序,但我不知道 malloc 调用的 RAM 是否会在下一个循环中重用,或者是否会使用新的 RAM。希望几分钟后整个 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
}
}
How can I zero unused RAM in Linux for security purposes ? 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. Hopefully, after a few minutes the entire RAM will have been zeroed.
#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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Linux 已经有一个内核进程,它使用空闲周期将内存清零,因此它将有内存可供请求它的进程使用。
您的循环可能会也可能不会将不同的内存归零,具体取决于特定的
malloc
实现。如果您确实想编写一个像您所描述的那样的流程,请考虑直接使用 sbrk 以确保您在流程中循环内存。不过,我敢打赌,如果您检查一下,您会发现sbrk
给您的每个字节都已经为零。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.
Your loop may or may not zero different memory depending on the particular
malloc
implementation. If you really want to write a process like you describe, look into usingsbrk
directly to ensure you're cycling memory in and out of your process. I bet if you check you'll find every byte given to you bysbrk
is already zero, though.您无法将系统 RAM 清零。系统拥有它。如果您想运行一个将 RAM 归零的系统,那么您需要编写自己的操作系统!
You can't zero system RAM. The system owns it. If you want to run a system which zeros the RAM then you need to write your own OS!
我认为您需要编写一个内核模块才能真正可靠地完成此操作。然后你仍然只能将未使用的页面归零。请注意,其他进程使用的页面将在分配时由内核自动清除。
你想做什么?避免冷启动攻击?
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?
只要您从不访问未初始化的内存,您就不必担心其他人留下的内容。只要您在将内存清零之前从未释放过内存,就不必担心留下的内容。
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.
通常,在我的系统(2.6.36)上,我只需执行 while(1) malloc(); 即可释放所有未使用(但已分配)的内存;循环,并在停止分配内存时杀死它。
Typically, on my system (2.6.36) I can free all the unused (but allocated) memory by just doing a while(1) malloc(); loop, and killing it when it stops allocating memory.