我正在为我的大学局域网上进行类似 ACM-ICPC 的比赛做一名在线评委。为此,我要求法官可能足够安全,以防止恶意程序在我的服务器上执行。(这样的程序的一个例子是)
int main(){
while(1) fork();
}
让我们调用这个程序的可执行文件testcode。
这个程序会导致我运行法官的服务器冻结。显然我不希望这种情况发生。所以为了防止我尝试使用 ptrace。我想出了以下代码:(让我们调用这个代码监视器的可执行文件)
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/user.h>
#include <sys/syscall.h>
#include <sys/reg.h>
#include<stdio.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/user.h>
#include <sys/syscall.h>
#include <sys/reg.h>
#include<stdio.h>
#include<signal.h>
#include<sys/prctl.h>
#include<stdlib.h>
#define NOBANNEDSYS 40
int bannedsys[50]={2,14,12,15,26,37,38,39,39,40,41,42,46,47,48,49,50,60,61,63,72,83,88,120,102,182,183,190};
int main(int argc,char **argv) {
int insyscall=0;
if(argc!=2) {
fprintf(stderr,"Usage: %s <prog name> ",argv[0]);
exit(-1);
}
int status = 0;
int syscall_n = 0;
int entering = 1;
int amp;
struct user_regs_struct regs;
int pid = fork();
if ( !pid ) {
prctl(PR_SET_PDEATHSIG, SIGKILL);
ptrace( PTRACE_TRACEME, 0, 0, 0 );
execlp( argv[1],argv[1], 0 );
}
else {
//ptrace( PTRACE_SINGLESTEP ,pid, 0, 0 );
// ptrace( PTRACE_SYSCALL, pid, 0, 0 );
while (1) {
wait( &);
if ( WIFEXITED( amp ) ) break;
//ptrace( PTRACE_SINGLESTEP ,pid, 0, 0 );
if(insyscall==0){
ptrace( PTRACE_GETREGS, pid, 0,®s );
int i=0;
for(i=0;i<NOBANNEDSYS;i++) if(regs.orig_eax==bannedsys[i]) { kill(pid,SIGKILL);
printf("%d killed due to illegal system call\n",pid);
abort();
}
insyscall=1;
}
else insyscall=0;
// ptrace(PTRACE_CONT,pid,0,0);
// wait(&);
ptrace( PTRACE_SYSCALL, pid, 0, 0 );
// puts("Here");
//ptrace(PTRACE_CONT, pid, 0, 0);
}
}
return 0;
}
此代码在阻止可能导致问题的系统调用方面效果很好。但是当要监视的代码包含循环中的 fork 调用(如测试代码)时,机器会因为颠簸而冻结。我可以弄清楚的原因是原始进程被杀死根据监控代码,它的孩子幸存下来并继续携带叉形炸弹。如何修复监控代码,使其可以成功部署?
PS:可移植性不是问题。我正在寻找一个Linux特定的答案。
编辑:在调用 exec 之前,我使用 setrlimit 将子进程的最大数量设置为 0。到目前为止,这似乎是一个很好的解决方案。尽管如果监视器代码中仍然存在漏洞,很高兴听到社区的消息。