如果你在Linux终端中执行”:(){ :|:& };:“,你的计算机会立即崩溃,甚至不用使用root权限。这个字符串就是所谓的fork炸弹。
“:(){ :|:& };:”实际上是一段shell脚本,在理解它之前,我们先来看一下shell脚本函数是怎么定义的:
function_name()
{
some command
}
“:(){ :|:& };:”中的”:(){ }”实际上定义了一个叫”:”的函数,”:|:&”代表执行“:”函数并放入后台,实际上是fork了两个进程(”:|:“),“;:”指定要递归的执行这个函数。系统崩溃是因为线程数过多,系统资源耗尽所致。
fork炸弹并非Linux专有,Windows也有同样的问题。下面用C语言实现了简单的fork炸弹:
#include
int main(int argc, char* argv[])
{
while(1)
fork();
return 0;
}
说了这么多fork炸弹,怎么防止它呢?
防止fork炸弹攻击
fork炸弹的原理是创建N多进程,耗尽系统资源。而且更坏的是fork炸弹根本不需要root权限。
为了保护系统,防止fork炸弹,你需要限制每个用户能创建的最大进程数。大概限制在每个用户1000-4000个进程。
要想限制进程数,你需要使用/etc/security/limits.conf文件。
文件里详细说明了怎么使用。
# /etc/security/limits.conf
#
#Each line describes a limit for a user in the form:
#
#
#
#Where:
# can be:
# - a user name
# - a group name, with @group syntax
# - the wildcard *, for default entry
# - the wildcard %, can be also used with %group syntax,
# for maxlogin limit
# - NOTE: group and wildcard limits are not applied to root.
# To apply a limit to the root user, must be
# the literal username root.
#
# can have the two values:
# - "soft" for enforcing the soft limits
# - "hard" for enforcing hard limits
#
# can be one of the following:
# - core - limits the core file size (KB)
# - data - max data size (KB)
# - fsize - maximum filesize (KB)
# - memlock - max locked-in-memory address space (KB)
# - nofile - max number of open files
# - rss - max resident set size (KB)
# - stack - max stack size (KB)
# - cpu - max CPU time (MIN)
# - nproc - max number of processes
# - as - address space limit (KB)
# - maxlogins - max number of logins for this user
# - maxsyslogins - max number of logins on the system
# - priority - the priority to run user process with
# - locks - max number of file locks the user can hold
# - sigpending - max number of pending signals
# - msgqueue - max memory used by POSIX message queues (bytes)
# - nice - max nice priority allowed to raise to values: [-20, 19]
# - rtprio - max realtime priority
# - chroot - change root to directory (Debian-specific)
#
#
#
#* soft core 0
#root hard core 100000
#* hard rss 10000
#@student hard nproc 20
#@faculty soft nproc 20
#@faculty hard nproc 50
#ftp hard nproc 0
#ftp - chroot /ftp
#@student - maxlogins 4
# End of file
在文件尾加入:
snown_1 hard proc 2000
...
上面代码限制snown_1用户最多创建2000个进程。保存文件,重启系统生效。
如果fork炸弹脚本已经运行,使用如下命令结束所有fork出的进程:
$ exec killall -9 script_name