Seccomp.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. // sigaction() siginfo_t SIG_UNBLOCK
  16. #define _POSIX_C_SOURCE 199309L
  17. #include "util/Seccomp.h"
  18. #include "util/Bits.h"
  19. #include "util/ArchInfo.h"
  20. // getpriority()
  21. #include <sys/resource.h>
  22. #include <signal.h>
  23. #include <sys/prctl.h>
  24. #include <errno.h>
  25. #include <linux/filter.h>
  26. #include <linux/seccomp.h>
  27. #include <linux/audit.h>
  28. #include <linux/netlink.h>
  29. #include <sys/syscall.h>
  30. #include <sys/socket.h>
  31. #include <sys/ioctl.h>
  32. #include <stddef.h>
  33. #include <stdio.h>
  34. #include <string.h>
  35. /**
  36. * A unique number which is returned as errno by getpriority(), a syscall we never use
  37. * this will be used by Seccomp_isWorking() to detect that the filter has been properly installed.
  38. */
  39. #define IS_WORKING_ERRNO 3333
  40. /**
  41. * Accessing the SIGSYS siginfo depends on the fields being defined by the libc.
  42. * Older libc do not yet include the needed definitions and accessor macros.
  43. * Work around that by falling back to si_value.sival_int which works on some
  44. * but not all architectures.
  45. */
  46. #if defined(si_syscall)
  47. # define GET_SYSCALL_NUM(si) ((si)->si_syscall)
  48. #else
  49. # warning "your libc doesn't define SIGSYS signal info! Try build witch Seccomp_NO=1"
  50. # define GET_SYSCALL_NUM(si) ((si)->si_value.sival_int)
  51. #endif
  52. static void catchViolation(int sig, siginfo_t* si, void* threadContext)
  53. {
  54. printf("Attempted banned syscall number [%d] see doc/Seccomp.md for more information\n",
  55. GET_SYSCALL_NUM(si));
  56. Assert_failure("Disallowed Syscall");
  57. }
  58. struct Filter {
  59. int label;
  60. int jt;
  61. int jf;
  62. struct sock_filter sf;
  63. };
  64. static struct sock_fprog* compile(struct Filter* input, int inputLen, struct Allocator* alloc)
  65. {
  66. // compute gotos
  67. int totalOut = 0;
  68. for (int i = inputLen-1; i >= 0; i--) {
  69. struct Filter* a = &input[i];
  70. if (a->label == 0) {
  71. // check for unresolved gotos...
  72. Assert_true(a->jt == 0 && a->jf == 0);
  73. totalOut++;
  74. continue;
  75. }
  76. int diff = 0;
  77. for (int j = i-1; j >= 0; j--) {
  78. struct Filter* b = &input[j];
  79. if (b->label != 0) { continue; }
  80. if (b->jt == a->label) {
  81. b->sf.jt = diff;
  82. b->jt = 0;
  83. }
  84. if (b->jf == a->label) {
  85. b->sf.jf = diff;
  86. b->jf = 0;
  87. }
  88. diff++;
  89. }
  90. }
  91. // copy into output filter array...
  92. struct sock_filter* sf = Allocator_calloc(alloc, sizeof(struct sock_filter), totalOut);
  93. int outI = 0;
  94. for (int i = 0; i < inputLen; i++) {
  95. if (input[i].label == 0) {
  96. Bits_memcpy(&sf[outI++], &input[i].sf, sizeof(struct sock_filter));
  97. }
  98. Assert_true(outI <= totalOut);
  99. Assert_true(i != inputLen-1 || outI == totalOut);
  100. }
  101. struct sock_fprog* out = Allocator_malloc(alloc, sizeof(struct sock_fprog));
  102. out->len = (unsigned short) totalOut;
  103. out->filter = sf;
  104. return out;
  105. }
  106. #define RET_TRAP 0x00030000u
  107. #define RET_ERRNO(x) (0x00050000u | ((x) & 0x0000ffffu))
  108. #define RET_SUCCESS 0x7fff0000u
  109. static struct sock_fprog* mkFilter(struct Allocator* alloc, struct Except* eh)
  110. {
  111. // Adding exceptions to the syscall filter:
  112. //
  113. // echo '#include <sys/syscall.h>' | gcc -E -dM - | grep 'define __NR_' | sort
  114. // for the full list of system calls with syscall numbers (different per ABI)
  115. //
  116. // If gdb traps out it will look like this:
  117. //
  118. // Program received signal SIGSYS, Bad system call.
  119. // [Switching to Thread 0x7ffff7fdd740 (LWP 14673)]
  120. // 0x00007ffff74d1caa in mmap64 () at ../sysdeps/unix/syscall-template.S:81
  121. // 81 ../sysdeps/unix/syscall-template.S: No such file or directory.
  122. //
  123. // %eax should contain the system call number (on different ABIs YMMV)
  124. //
  125. // (gdb) print $eax
  126. // $1 = 9
  127. // (gdb)
  128. //
  129. // Consult your syscall table from the above gcc command...
  130. //
  131. // #define __NR_mmap 9
  132. //
  133. // Then add:
  134. //
  135. // IFEQ(__NR_mmap, success),
  136. //
  137. // And add a comment documenting where you needed that syscall :)
  138. #define STMT(code, val) { .sf = BPF_STMT(code, val) }
  139. #define JMPK(type, not, input, label) { \
  140. .sf = BPF_JUMP(BPF_JMP+(type)+BPF_K, (input), 0, 0), \
  141. .jt = (!(not) ? (label) : 0), \
  142. .jf = ((not) ? (label) : 0) \
  143. }
  144. // Create a label for jumps, the label must be represented by a non-zero integer.
  145. #define LABEL(lbl) { .label = (lbl) }
  146. // Load offset into the register
  147. #define LOAD(offset) STMT(BPF_LD+BPF_W+BPF_ABS, (offset))
  148. // Return constant value
  149. #define RET(val) STMT(BPF_RET+BPF_K, (val))
  150. // If-equal if the currently loaded value equals input, jump to label.
  151. #define IFEQ(input, label) JMPK(BPF_JEQ, 0, (input), (label))
  152. // If-not-equal if the currently loaded value is not equal to input, jump to label.
  153. #define IFNE(input, label) JMPK(BPF_JEQ, 1, (input), (label))
  154. // If-greater-than
  155. #define IFGT(input, label) JMPK(BPF_JGT, 0, (input), (label))
  156. // If-greater-than-or-equal-to
  157. #define IFGE(input, label) JMPK(BPF_JGE, 0, (input), (label))
  158. // If-less-than
  159. #define IFLT(input, label) JMPK(BPF_JGE, 1, (input), (label))
  160. // If-less-than-or-equal-to
  161. #define IFLE(input, label) JMPK(BPF_JGT, 1, (input), (label))
  162. // labels are integers so they must be predefined
  163. int success = 1;
  164. int fail = 2;
  165. int unmaskOnly = 3;
  166. int isworking = 4;
  167. int socket = 5;
  168. int ioctl_setip = 6;
  169. int bind_netlink = 7;
  170. uint32_t auditArch = ArchInfo_getAuditArch();
  171. struct Filter seccompFilter[] = {
  172. LOAD(offsetof(struct seccomp_data, arch)),
  173. IFNE(auditArch, fail),
  174. // Get the syscall num.
  175. LOAD(offsetof(struct seccomp_data, nr)),
  176. // udp
  177. #ifdef __NR_sendmsg
  178. IFEQ(__NR_sendmsg, success),
  179. #endif
  180. #ifdef __NR_recvmsg
  181. IFEQ(__NR_recvmsg, success),
  182. #endif
  183. // ETHInterface
  184. #ifdef __NR_sendto
  185. IFEQ(__NR_sendto, success),
  186. #endif
  187. #ifdef __NR_recvfrom
  188. IFEQ(__NR_recvfrom, success),
  189. #endif
  190. #ifdef __NR_socketcall
  191. // 32-bit: recvmsg is a socketcall
  192. IFEQ(__NR_socketcall, success),
  193. #endif
  194. // libuv
  195. IFEQ(__NR_epoll_ctl, success),
  196. #ifdef __NR_epoll_wait
  197. IFEQ(__NR_epoll_wait, success),
  198. #endif
  199. #ifdef __NR_epoll_pwait
  200. IFEQ(__NR_epoll_pwait, success),
  201. #endif
  202. // gettimeofday is required on some architectures
  203. #ifdef __NR_gettimeofday
  204. IFEQ(__NR_gettimeofday, success),
  205. #endif
  206. // TUN (and logging)
  207. IFEQ(__NR_write, success),
  208. IFEQ(__NR_read, success),
  209. // readv and writev are used by some libc (musl)
  210. #ifdef __NR_readv
  211. IFEQ(__NR_readv, success),
  212. #endif
  213. #ifdef __NR_writev
  214. IFEQ(__NR_writev, success),
  215. #endif
  216. // modern librt reads a read-only mapped section of kernel space which contains the time
  217. // older versions need system calls for getting the time.
  218. // i686 glibc-2.18's time() uses __NR_time
  219. // Raspberry Pi and BeagleBone Black don't provide __NR_time
  220. IFEQ(__NR_clock_gettime, success),
  221. #ifdef __NR_time
  222. IFEQ(__NR_time, success),
  223. #endif
  224. // malloc()
  225. IFEQ(__NR_brk, success),
  226. // abort()
  227. IFEQ(__NR_gettid, success),
  228. IFEQ(__NR_tgkill, success),
  229. IFEQ(__NR_rt_sigprocmask, unmaskOnly),
  230. // exit()
  231. IFEQ(__NR_exit_group, success),
  232. // Seccomp_isWorking()
  233. IFEQ(__NR_getpriority, isworking),
  234. // Securiy_checkPermissions() -> canOpenFiles()
  235. IFEQ(__NR_dup, success),
  236. IFEQ(__NR_close, success),
  237. // Security_checkPermissions() -> getMaxMem()
  238. // x86/ARM use ugetrlimit and mmap2
  239. // ARM does not even have __NR_getrlimit or __NR_mmap defined
  240. // and AMD64 does not have __NR_ugetrlimit or __NR_mmap2 defined
  241. #ifdef __NR_getrlimit
  242. IFEQ(__NR_getrlimit, success),
  243. #endif
  244. #ifdef __NR_ugetrlimit
  245. IFEQ(__NR_ugetrlimit, success),
  246. #endif
  247. #ifdef __NR_mmap
  248. IFEQ(__NR_mmap, success),
  249. #endif
  250. #ifdef __NR_mmap2
  251. IFEQ(__NR_mmap2, success),
  252. #endif
  253. IFEQ(__NR_munmap, success),
  254. // printf()
  255. IFEQ(__NR_fstat, success),
  256. #ifdef __NR_fstat64
  257. IFEQ(__NR_fstat64, success),
  258. #endif
  259. // for setting IP addresses
  260. // socketForIfName()
  261. // and ETHInterface_listDevices
  262. #ifdef __NR_socket
  263. IFEQ(__NR_socket, socket),
  264. #endif
  265. IFEQ(__NR_ioctl, ioctl_setip),
  266. // Security_checkPermissions
  267. IFEQ(__NR_getuid, success),
  268. // Security_nofiles
  269. IFEQ(__NR_setrlimit, success),
  270. // for ETHInterface_listDevices (netlinkk)
  271. #ifdef __NR_bind
  272. IFEQ(__NR_bind, bind_netlink),
  273. #endif
  274. #ifdef __NR_getsockname
  275. IFEQ(__NR_getsockname, success),
  276. #endif
  277. RET(SECCOMP_RET_TRAP),
  278. LABEL(socket),
  279. LOAD(offsetof(struct seccomp_data, args[1])),
  280. IFEQ(SOCK_DGRAM, success),
  281. LOAD(offsetof(struct seccomp_data, args[0])),
  282. IFEQ(AF_NETLINK, success),
  283. RET(SECCOMP_RET_TRAP),
  284. LABEL(ioctl_setip),
  285. LOAD(offsetof(struct seccomp_data, args[1])),
  286. IFEQ(SIOCGIFINDEX, success),
  287. IFEQ(SIOCGIFFLAGS, success),
  288. IFEQ(SIOCSIFFLAGS, success),
  289. IFEQ(SIOCSIFADDR, success),
  290. IFEQ(SIOCSIFNETMASK, success),
  291. IFEQ(SIOCSIFMTU, success),
  292. RET(SECCOMP_RET_TRAP),
  293. LABEL(bind_netlink),
  294. LOAD(offsetof(struct seccomp_data, args[2])),
  295. // Filter NETLINK by size of address.
  296. // Most importantly INET and INET6
  297. // are differnt.
  298. IFEQ(sizeof(struct sockaddr_nl), success),
  299. RET(SECCOMP_RET_TRAP),
  300. // We allow sigprocmask to *unmask* signals but we don't allow it to mask them.
  301. LABEL(unmaskOnly),
  302. LOAD(offsetof(struct seccomp_data, args[0])),
  303. IFEQ(SIG_UNBLOCK, success),
  304. RET(SECCOMP_RET_TRAP),
  305. LABEL(isworking),
  306. RET(RET_ERRNO(IS_WORKING_ERRNO)),
  307. LABEL(fail),
  308. RET(SECCOMP_RET_TRAP),
  309. LABEL(success),
  310. RET(SECCOMP_RET_ALLOW),
  311. };
  312. return compile(seccompFilter, sizeof(seccompFilter)/sizeof(seccompFilter[0]), alloc);
  313. }
  314. static void installFilter(struct sock_fprog* filter, struct Log* logger, struct Except* eh)
  315. {
  316. struct sigaction sa = { .sa_sigaction = catchViolation, .sa_flags = SA_SIGINFO };
  317. if (sigaction(SIGSYS, &sa, NULL)) {
  318. Log_warn(logger, "sigaction(SIGSYS) -> [%s]\n", strerror(errno));
  319. }
  320. if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1) {
  321. // don't worry about it.
  322. Log_warn(logger, "prctl(PR_SET_NO_NEW_PRIVS) -> [%s]\n", strerror(errno));
  323. }
  324. if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, filter) == -1) {
  325. Except_throw(eh, "prctl(PR_SET_SECCOMP) -> [%s]\n", strerror(errno));
  326. }
  327. }
  328. void Seccomp_dropPermissions(struct Allocator* tempAlloc, struct Log* logger, struct Except* eh)
  329. {
  330. struct sock_fprog* filter = mkFilter(tempAlloc, eh);
  331. installFilter(filter, logger, eh);
  332. if (!Seccomp_isWorking()) {
  333. Except_throw(eh, "Seccomp filter not installed properly, Seccomp_isWorking() -> false");
  334. }
  335. }
  336. int Seccomp_isWorking()
  337. {
  338. errno = 0;
  339. // If seccomp is not working, this will fail setting errno to EINVAL
  340. long ret = getpriority(1000, 1);
  341. int err = errno;
  342. // Inside of the kernel, it seems to check whether the errno return is sane
  343. // and if it is not, it treates it as a return value, IS_WORKING_ERRNO (3333) is very unique so
  344. // we'll check for either case just in case this changes.
  345. return (ret == -1 && err == IS_WORKING_ERRNO) || (ret == -IS_WORKING_ERRNO && err == 0);
  346. }
  347. int Seccomp_exists()
  348. {
  349. return 1;
  350. }