重构seccomp部分

This commit is contained in:
LiYang 2016-10-07 17:06:55 +08:00
parent 87719790b3
commit 191b4bda0d
18 changed files with 57 additions and 231 deletions

View File

@ -9,17 +9,9 @@ set(CMAKE_C_FLAGS "${BASE_CMAKE_C_FLAGS}")
# make judger lib
file(GLOB SOURCE "src/*.c")
file(GLOB SOURCE "src/*.c" "src/rules/*.c")
add_library(judger SHARED ${SOURCE})
target_link_libraries(judger pthread dl)
target_link_libraries(judger pthread seccomp)
# make language seccomp rules
file(GLOB RULE_SOURCE src/rules/*)
foreach(lang_rule_path ${RULE_SOURCE})
file(RELATIVE_PATH lang_name ${CMAKE_CURRENT_SOURCE_DIR}/src/rules ${lang_rule_path})
add_library("rule_${lang_name}" SHARED "${lang_rule_path}/rule.c")
target_link_libraries("rule_${lang_name}" seccomp)
endforeach(lang_rule_path src/rules)
install(DIRECTORY output/ DESTINATION /usr/lib/judger)

View File

@ -16,7 +16,7 @@ static PyObject *judger_run(PyObject *self, PyObject *args, PyObject *kwargs) {
struct config _config;
struct result _result = {0, 0, 0, 0, 0, 0, 0};
PyObject *args_list, *env_list, *rule_path, *args_iter, *env_iter, *next;
PyObject *args_list, *env_list, *rule_name, *args_iter, *env_iter, *next;
int count = 0;
@ -24,14 +24,14 @@ static PyObject *judger_run(PyObject *self, PyObject *args, PyObject *kwargs) {
"max_process_number", "max_output_size",
"exe_path", "input_path", "output_path",
"error_path", "args", "env", "log_path",
"seccomp_rule_so_path", "uid", "gid", NULL};
"seccomp_rule_name", "uid", "gid", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iililssssOOsOii", kwargs_list,
&(_config.max_cpu_time), &(_config.max_real_time), &(_config.max_memory),
&(_config.max_process_number), &(_config.max_output_size),
&(_config.exe_path), &(_config.input_path), &(_config.output_path),
&(_config.error_path), &args_list, &env_list, &(_config.log_path),
&rule_path, &(_config.uid), &(_config.gid))) {
&rule_name, &(_config.uid), &(_config.gid))) {
RaiseValueError("Invalid args and kwargs");
}
@ -82,14 +82,14 @@ static PyObject *judger_run(PyObject *self, PyObject *args, PyObject *kwargs) {
// Py_DECREF(env_list);
// Py_DECREF(env_iter);
if (PyString_Check(rule_path)) {
_config.seccomp_rule_so_path = PyString_AsString(rule_path);
if (PyString_Check(rule_name)) {
_config.seccomp_rule_name = PyString_AsString(rule_name);
// Py_DECREF(rule_path);
}
else {
if (rule_path == Py_None) {
if (rule_name == Py_None) {
// Py_DECREF(rule_path);
_config.seccomp_rule_so_path = NULL;
_config.seccomp_rule_name = NULL;
}
else {
// fixme decref

View File

@ -19,6 +19,7 @@
#include "runner.h"
#include "child.h"
#include "logger.h"
#include "rules/seccomp_rules.h"
#include "killer.h"
@ -132,19 +133,17 @@ int child_process(void *args) {
}
// load seccomp so
if (_config->seccomp_rule_so_path != NULL) {
void *handler = dlopen(_config->seccomp_rule_so_path, RTLD_LAZY);
int (*load_seccomp)(void *, struct config *);
if (!handler) {
LOG_FATAL(log_fp, "seccomp failed, %s", dlerror());
if (_config->seccomp_rule_name != NULL) {
if (strcmp("c_cpp", _config->seccomp_rule_name) == 0) {
if (c_cpp_seccomp_rules(_config) != SUCCESS) {
CHILD_ERROR_EXIT(LOAD_SECCOMP_FAILED);
}
}
// other rules
else {
// rule does not exist
CHILD_ERROR_EXIT(LOAD_SECCOMP_FAILED);
}
load_seccomp = dlsym(handler, "load_seccomp");
if (load_seccomp(handler, _config) != 0) {
CHILD_ERROR_EXIT(LOAD_SECCOMP_FAILED);
}
dlclose(handler);
}
execve(_config->exe_path, _config->args, _config->env);

View File

@ -1,10 +1,10 @@
#include <stdio.h>
#include <seccomp.h>
#include "../../runner.h"
#include "../runner.h"
int load_seccomp(void *dl_handler, struct config *_config) {
int c_cpp_seccomp(struct config *_config) {
int syscalls_whitelist[] = {SCMP_SYS(read), SCMP_SYS(fstat),
SCMP_SYS(mmap), SCMP_SYS(mprotect),
SCMP_SYS(munmap), SCMP_SYS(open),
@ -33,9 +33,9 @@ int load_seccomp(void *dl_handler, struct config *_config) {
return LOAD_SECCOMP_FAILED;
}
// mmap can write file, 5th args is fd
if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(mmap), 1, SCMP_A5(SCMP_CMP_LE, 2)) != 0) {
return LOAD_SECCOMP_FAILED;
}
//if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(mmap), 1, SCMP_A5(SCMP_CMP_LE, 2)) != 0) {
// return LOAD_SECCOMP_FAILED;
//}
if (seccomp_load(ctx) != 0) {
return LOAD_SECCOMP_FAILED;
}

View File

@ -0,0 +1,7 @@
#ifndef JUDGER_SECCOMP_RULES_H
#define JUDGER_SECCOMP_RULES_H
#include "../runner.h"
int c_cpp_seccomp_rules(struct config *_config);
#endif //JUDGER_SECCOMP_RULES_H

View File

@ -19,7 +19,7 @@
#include "child.h"
#include "logger.h"
#define STACK_SIZE (2 * 1024 * 1024)
#define STACK_SIZE (32 * 1024 * 1024)
void init_result(struct result *_result) {
_result->error = SUCCESS;

View File

@ -49,7 +49,7 @@ struct config {
char *args[256];
char *env[256];
char *log_path;
char *seccomp_rule_so_path;
char *seccomp_rule_name;
uid_t uid;
gid_t gid;
};

View File

@ -3,8 +3,6 @@ import _judger
from unittest import TestCase, main
from testcase.integration.test import IntegrationTest
from testcase.c_cpp.test import C_CPPJudgeTestCase
from testcase.seccomp.test import SeccompTest
ver = _judger.VERSION
print "Judger version %d.%d.%d" % ((ver >> 16) & 0xff, (ver >> 8) & 0xff, ver & 0xff)

View File

@ -1,7 +0,0 @@
# coding=utf-8
from unittest import TestCase
class PythonJudgeTestCase(TestCase):
def test_firest(self):
self.assertTrue(1==1)

View File

@ -29,7 +29,7 @@ class BaseTestCase(TestCase):
flags = " "
if extra_flags:
flags += " ".join(extra_flags)
cmd = ("gcc {0} -g -O0 -o {1}" + flags).format(os.path.join(path, src_name), exe_path)
cmd = ("gcc {0} -g -O0 -static -o {1}" + flags).format(os.path.join(path, src_name), exe_path)
if os.system(cmd):
raise AssertionError("compile error, cmd: {0}".format(cmd))
return exe_path

View File

@ -1,28 +0,0 @@
# coding=utf-8
import os
import _judger
import signal
from unittest import TestCase
from .. import base
class C_CPPJudgeTestCase(base.BaseTestCase):
def setUp(self):
self.workspace = self.init_workspace("c_cpp")
self.config = {"max_cpu_time": 1000,
"max_real_time": 3000,
"max_memory": 1024 * 1024 * 1024,
"max_process_number": 10,
"max_output_size": 1024 * 1024,
"exe_path": "/bin/ls",
"input_path": "/dev/null",
"output_path": "/dev/null",
"error_path": "/dev/null",
"args": [],
"env": ["env=judger_test", "test=judger"],
"log_path": "judger_test.log",
"seccomp_rule_so_path": "/usr/lib/judger/librule_c_cpp.so",
"uid": 0,
"gid": 0}
print "Running", self._testMethodName

View File

@ -3,7 +3,6 @@
int main()
{
sin(1.0);
printf("sin");
printf("abs %d", abs(-1024));
return 0;
}

View File

@ -11,7 +11,7 @@ class IntegrationTest(base.BaseTestCase):
print "Running", self._testMethodName
self.config = {"max_cpu_time": 1000,
"max_real_time": 3000,
"max_memory": 1024 * 1024 * 1024,
"max_memory": 1024 * 1024 * 128,
"max_process_number": 10,
"max_output_size": 1024 * 1024,
"exe_path": "/bin/ls",
@ -21,7 +21,7 @@ class IntegrationTest(base.BaseTestCase):
"args": [],
"env": ["env=judger_test", "test=judger"],
"log_path": "judger_test.log",
"seccomp_rule_so_path": None,
"seccomp_rule_name": None,
"uid": 0,
"gid": 0}
self.workspace = self.init_workspace("integration")
@ -43,14 +43,14 @@ class IntegrationTest(base.BaseTestCase):
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args="12344", env=["a=b"], log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
with self.assertRaisesRegexp(ValueError, "args must be a list"):
_judger.run(max_cpu_time=1000, max_real_time=2000, max_memory=1000000000,
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args={"k": "v"}, env=["a=b"], log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
def test_args_item_must_be_string(self):
with self.assertRaisesRegexp(ValueError, "arg item must be a string"):
@ -58,21 +58,21 @@ class IntegrationTest(base.BaseTestCase):
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args=["1234", 1234], env=["a=b"], log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
with self.assertRaisesRegexp(ValueError, "arg item must be a string"):
_judger.run(max_cpu_time=1000, max_real_time=2000, max_memory=1000000000,
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args=["1234", None], env=["a=b"], log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
with self.assertRaisesRegexp(ValueError, "arg item must be a string"):
_judger.run(max_cpu_time=1000, max_real_time=2000, max_memory=1000000000,
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args=[u"哈哈哈"], env=["a=b"], log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
def test_env_must_be_list(self):
with self.assertRaisesRegexp(ValueError, "env must be a list"):
@ -80,14 +80,14 @@ class IntegrationTest(base.BaseTestCase):
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args=["1234"], env="1234", log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
with self.assertRaisesRegexp(ValueError, "env must be a list"):
_judger.run(max_cpu_time=1000, max_real_time=2000, max_memory=1000000000,
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args=["1234"], env={"k": "v"}, log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
def test_env_item_must_be_string(self):
with self.assertRaisesRegexp(ValueError, "env item must be a string"):
@ -95,34 +95,34 @@ class IntegrationTest(base.BaseTestCase):
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args=["1234"], env=["1234", 1234], log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
with self.assertRaisesRegexp(ValueError, "env item must be a string"):
_judger.run(max_cpu_time=1000, max_real_time=2000, max_memory=1000000000,
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args=["1234"], env=["a=b", None], log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
with self.assertRaisesRegexp(ValueError, "env item must be a string"):
_judger.run(max_cpu_time=1000, max_real_time=2000, max_memory=1000000000,
max_process_number=200, max_output_size=10000, exe_path="1.out",
input_path="1.in", output_path="1.out", error_path="1.out",
args=["1234"], env=[u"哈哈哈"], log_path="1.log",
seccomp_rule_so_path="1.so", uid=0, gid=0)
seccomp_rule_name="1.so", uid=0, gid=0)
def test_seccomp_rule_can_be_none(self):
_judger.run(max_cpu_time=1000, max_real_time=2000, max_memory=1000000000,
max_process_number=200, max_output_size=10000, exe_path="/bin/ls",
input_path="/dev/null", output_path="/dev/null", error_path="/dev/null",
args=["12344"], env=["a=b"], log_path="/dev/null",
seccomp_rule_so_path="/usr/lib/judger/librule_c_cpp.so", uid=0, gid=0)
seccomp_rule_name="c_cpp", uid=0, gid=0)
_judger.run(max_cpu_time=1000, max_real_time=2000, max_memory=1000000000,
max_process_number=200, max_output_size=10000, exe_path="/bin/ls",
input_path="/dev/null", output_path="/dev/null", error_path="/dev/null",
args=["12344"], env=["a=b"], log_path="/dev/null",
seccomp_rule_so_path=None, uid=0, gid=0)
seccomp_rule_name=None, uid=0, gid=0)
def test_normal(self):
config = self.config
@ -134,6 +134,13 @@ class IntegrationTest(base.BaseTestCase):
self.assertEqual(result["result"], _judger.RESULT_SUCCESS)
self.assertEqual(output, self.output_content(config["output_path"]))
config["exe_path"] = self._compile_c("math.c")
config["input_path"] = "/dev/null"
config["output_path"] = config["error_path"] = self.output_path()
result = _judger.run(**config)
self.assertEqual(result["result"], _judger.RESULT_SUCCESS)
self.assertEqual("abs 1024", self.output_content(config["output_path"]))
def test_args(self):
config = self.config
config["exe_path"] = self._compile_c("args.c")
@ -257,6 +264,7 @@ class IntegrationTest(base.BaseTestCase):
def test_cpp_meta(self):
config = self.config
config["exe_path"] = "/usr/bin/g++"
config["max_memory"] = 1024 * 1024 * 1024
config["args"] = [os.path.join(os.path.dirname(os.path.abspath(__file__)), "cpp_meta.cpp"),
"-o", os.path.join(self.workspace, "cpp_meta")]
result = _judger.run(**config)

View File

@ -1,95 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
int main(int argc, const char *argv[])
{
const char *text = "Hello world";
/* Open a file for writing.
* - Creating the file if it doesn't exist.
* - Truncating it to 0 size if it already exists. (not really needed)
*
* Note: "O_WRONLY" mode is not sufficient when mmaping.
*/
const char *filepath = "/tmp/mmapped.bin";
size_t i;
int fd = open(filepath, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
if (fd == -1)
{
perror("Error opening file for writing");
exit(EXIT_FAILURE);
}
// Stretch the file size to the size of the (mmapped) array of char
size_t textsize = strlen(text) + 1; // + \0 null character
if (lseek(fd, textsize-1, SEEK_SET) == -1)
{
close(fd);
perror("Error calling lseek() to 'stretch' the file");
exit(EXIT_FAILURE);
}
/* Something needs to be written at the end of the file to
* have the file actually have the new size.
* Just writing an empty string at the current file position will do.
*
* Note:
* - The current position in the file is at the end of the stretched
* file due to the call to lseek().
* - An empty string is actually a single '\0' character, so a zero-byte
* will be written at the last byte of the file.
*/
if (write(fd, "", 1) == -1)
{
close(fd);
perror("Error writing last byte of the file");
exit(EXIT_FAILURE);
}
// Now the file is ready to be mmapped.
char *map = mmap(0, textsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED)
{
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
for (i = 0; i < textsize; i++)
{
printf("Writing character %c at %zu\n", text[i], i);
map[i] = text[i];
}
// Write it now to disk
if (msync(map, textsize, MS_SYNC) == -1)
{
perror("Could not sync the file to disk");
}
// Don't forget to free the mmapped memory
if (munmap(map, textsize) == -1)
{
close(fd);
perror("Error un-mmapping the file");
exit(EXIT_FAILURE);
}
// Un-mmaping doesn't close the file, so we still need to do that.
close(fd);
return 0;
}

View File

@ -1,47 +0,0 @@
# coding=utf-8
import _judger
import signal
import os
from .. import base
class SeccompTest(base.BaseTestCase):
def setUp(self):
print "Running", self._testMethodName
self.config = {"max_cpu_time": 1000,
"max_real_time": 3000,
"max_memory": 1024 * 1024 * 1024,
"max_process_number": 10,
"max_output_size": 1024 * 1024,
"exe_path": "/bin/ls",
"input_path": "/dev/null",
"output_path": "/dev/null",
"error_path": "/dev/null",
"args": [],
"env": ["env=judger_test", "test=judger"],
"log_path": "judger_test.log",
"seccomp_rule_so_path": None,
"uid": 0,
"gid": 0}
self.workspace = self.init_workspace("seccomp")
def _compile_c(self, src_name, extra_flags=None):
return super(SeccompTest, self)._compile_c("seccomp/" + src_name, extra_flags)
def test_mmap_write_file(self):
config = self.config
config["exe_path"] = self._compile_c("mmap.c")
config["seccomp_rule_so_path"] = "/usr/lib/judger/librule_c_cpp.so"
result = _judger.run(**config)
self.assertEqual(result["result"], _judger.RESULT_RUNTIME_ERROR)
self.assertEqual(result["signal"], 31)
def test_math(self):
config = self.config
config["exe_path"] = self._compile_c("math.c", extra_flags=["-lm"])
config["seccomp_rule_so_path"] = "/usr/lib/judger/librule_c_cpp.so"
config["output_path"] = self.output_path()
result = _judger.run(**config)
self.assertEqual(result["result"], _judger.RESULT_SUCCESS)
self.assertEqual("sin", self.output_content(config["output_path"]))