char *ld_preload=getenv("LD_PRELOAD"); if(ld_preload != NULL){ fprintf(stderr,"\033[31mError: please unset $LD_PRELOAD before running this program or use su -c `COMMAND` to run.\033[0m\n"); exit(1); }
权限检查:
容器需要以特权创建,否则会运行失败。 解决方法:
1 2 3 4
if (getuid() != 0){ fprintf(stderr,"\033[31mError: this program should be run with root privileges !\033[0m\n"); exit(1); }
容器目录存在检查:
容器目录不存在会导致chroot()函数失败,检查方法:
1 2 3 4 5 6 7
DIR *direxist; if((direxist=opendir(container_dir)) == NULL){ fprintf(stderr,"\033[31mError: container directory does not exist !\033[0m\n"); exit(1); }else{ closedir(direxist); }
all : cc -lcap -O3 -z noexecstack -z now -fstack-protector-all -fPIE -pie container.c -o container strip container no : cc -lcap container.c -o container static : cc -static -ffunction-sections -fdata-sections -Wl,--gc-sections -lcap -O3 -z noexecstack -z now -fstack-protector-all -fPIE container.c -o container strip container staticfail : cc -static -ffunction-sections -fdata-sections -Wl,--gc-sections -lcap -O3 -z noexecstack -z now -fstack-protector-all -fPIE container.c -o container ./libcap.a strip container install :all install -m 777 container ${PREFIX}/bin/container clean : rm container||true rm libcap.a||true help : @printf "\033[1;38;2;254;228;208mUsage:\n" @echo " make all :compile" @echo " make install :make all and install container to \$$PREFIX" @echo " make static :static compile" @echo " make staticfail :static compile,fix errors" @echo " make no :compile without optimizations" @echo " make clean :clean" @echo "Dependent libraries:" @echo " libc-client-static,libcap-static" @printf "If you got errors like \`undefined symbol: cap_drop_bound\` or \`undefined reference to \`cap_set_flag' when using static compile,please copy your \`libcap.a\` into current directory and use \`make staticfail\` instead\n\033[0m"
intmain(int argc,char **argv){ if (getuid() != 0){ fprintf(stderr,"\033[31mError: this program should be run with root privileges !\033[0m\n"); exit(1); } if (argc <= 1){ fprintf(stderr,"\033[31mError: too few arguments !\033[0m\n"); exit(1); } char *ld_preload=getenv("LD_PRELOAD"); if(ld_preload != NULL){ fprintf(stderr,"\033[31mError: please unset $LD_PRELOAD before running this program or use su -c `COMMAND` to run.\033[0m\n"); exit(1); } char *container_dir=argv[1]; char *login[1024]={0}; if (argc==2){ login[0]="/bin/su"; login[1]="-"; login[2]=NULL; }else{ int login_arg=0; for (int arg=2;arg<argc;arg++){ login_arg=arg-2; login[login_arg]=argv[arg]; } login_arg+=1; login[login_arg]=NULL; } DIR *direxist; if((direxist=opendir(container_dir)) == NULL){ fprintf(stderr,"\033[31mError: container directory does not exist !\033[0m\n"); exit(1); }else{ closedir(direxist); } chroot(container_dir); if (execv(login[0],login) == -1){ fprintf(stderr,"\033[31mFailed to execute `/bin/su`\n"); fprintf(stderr,"execv() returned: %d\n",errno); fprintf(stderr,"error reason: %s\033[0m\n",strerror(errno)); exit(1); } }