summaryrefslogtreecommitdiff
path: root/python/runner/sandbox.c
blob: b822997ddd4705dbf888fa730aeb7036f562dc2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* CodeQ: an online programming tutor.
   Copyright (C) 2015 UL FRI

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */

#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
	if (argc < 3) {
		fprintf(stderr, "usage: %s USERNAME FILE [ARGS...]\n", argv[0]);
		return 1;
	}

	// initialize arguments for the sandboxed command
	char** args = malloc((argc-1) * sizeof(char*));
	int i;
	for (i = 0; i < argc-2; i++)
		args[i] = argv[i+2];
	args[argc-2] = (char*)0;

	// switch user (requires root or "setcap cap_setuid,cap_setgid+ep")
	char const* username = argv[1];
	struct passwd const* pw = getpwnam(username);
	if (!pw) {
		fprintf(stderr, "no such user: %s\n", username);
		return 1;
	}
	int ret = 0;
	if ((ret = setgid(pw->pw_gid)) != 0)
		fprintf(stderr, "setgid returned %d\n", ret);
	if ((ret = setuid(pw->pw_uid)) != 0)
		fprintf(stderr, "setuid returned %d\n", ret);

	// limit CPU time to 1 second
	struct rlimit const cpu_limit = { .rlim_cur = 1, .rlim_max = 1 };
	if ((ret = setrlimit(RLIMIT_CPU, &cpu_limit)) != 0)
		fprintf(stderr, "setrlimit(CPU) returned %d\n", ret);

	// don't allow writing files of any size
	struct rlimit const fsize_limit = { .rlim_cur = 0, .rlim_max = 0 };
	if ((ret = setrlimit(RLIMIT_FSIZE, &fsize_limit)) != 0)
		fprintf(stderr, "setrlimit(FSIZE) returned %d\n", ret);

	// there will be no fork
	struct rlimit const nproc_limit = { .rlim_cur = 0, .rlim_max = 0 };
	if ((ret = setrlimit(RLIMIT_NPROC, &nproc_limit)) != 0)
		fprintf(stderr, "setrlimit(NPROC) returned %d\n", ret);

	return execvp(args[0], args);
}