sandboxer.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. // SPDX-License-Identifier: BSD-3-Clause
  2. /*
  3. * Simple Landlock sandbox manager able to execute a process restricted by
  4. * user-defined file system and network access control policies.
  5. *
  6. * Copyright © 2017-2020 Mickaël Salaün <mic@digikod.net>
  7. * Copyright © 2020 ANSSI
  8. */
  9. #define _GNU_SOURCE
  10. #define __SANE_USERSPACE_TYPES__
  11. #include <arpa/inet.h>
  12. #include <errno.h>
  13. #include <fcntl.h>
  14. #include <linux/landlock.h>
  15. #include <linux/socket.h>
  16. #include <stddef.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <sys/prctl.h>
  21. #include <sys/stat.h>
  22. #include <sys/syscall.h>
  23. #include <unistd.h>
  24. #include <stdbool.h>
  25. #if defined(__GLIBC__)
  26. #include <linux/prctl.h>
  27. #endif
  28. #ifndef landlock_create_ruleset
  29. static inline int
  30. landlock_create_ruleset(const struct landlock_ruleset_attr *const attr,
  31. const size_t size, const __u32 flags)
  32. {
  33. return syscall(__NR_landlock_create_ruleset, attr, size, flags);
  34. }
  35. #endif
  36. #ifndef landlock_add_rule
  37. static inline int landlock_add_rule(const int ruleset_fd,
  38. const enum landlock_rule_type rule_type,
  39. const void *const rule_attr,
  40. const __u32 flags)
  41. {
  42. return syscall(__NR_landlock_add_rule, ruleset_fd, rule_type, rule_attr,
  43. flags);
  44. }
  45. #endif
  46. #ifndef landlock_restrict_self
  47. static inline int landlock_restrict_self(const int ruleset_fd,
  48. const __u32 flags)
  49. {
  50. return syscall(__NR_landlock_restrict_self, ruleset_fd, flags);
  51. }
  52. #endif
  53. #define ENV_FS_RO_NAME "LL_FS_RO"
  54. #define ENV_FS_RW_NAME "LL_FS_RW"
  55. #define ENV_TCP_BIND_NAME "LL_TCP_BIND"
  56. #define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT"
  57. #define ENV_SCOPED_NAME "LL_SCOPED"
  58. #define ENV_FORCE_LOG_NAME "LL_FORCE_LOG"
  59. #define ENV_DELIMITER ":"
  60. static int str2num(const char *numstr, __u64 *num_dst)
  61. {
  62. char *endptr = NULL;
  63. int err = 0;
  64. __u64 num;
  65. errno = 0;
  66. num = strtoull(numstr, &endptr, 10);
  67. if (errno != 0)
  68. err = errno;
  69. /* Was the string empty, or not entirely parsed successfully? */
  70. else if ((*numstr == '\0') || (*endptr != '\0'))
  71. err = EINVAL;
  72. else
  73. *num_dst = num;
  74. return err;
  75. }
  76. static int parse_path(char *env_path, const char ***const path_list)
  77. {
  78. int i, num_paths = 0;
  79. if (env_path) {
  80. num_paths++;
  81. for (i = 0; env_path[i]; i++) {
  82. if (env_path[i] == ENV_DELIMITER[0])
  83. num_paths++;
  84. }
  85. }
  86. *path_list = malloc(num_paths * sizeof(**path_list));
  87. if (!*path_list)
  88. return -1;
  89. for (i = 0; i < num_paths; i++)
  90. (*path_list)[i] = strsep(&env_path, ENV_DELIMITER);
  91. return num_paths;
  92. }
  93. /* clang-format off */
  94. #define ACCESS_FILE ( \
  95. LANDLOCK_ACCESS_FS_EXECUTE | \
  96. LANDLOCK_ACCESS_FS_WRITE_FILE | \
  97. LANDLOCK_ACCESS_FS_READ_FILE | \
  98. LANDLOCK_ACCESS_FS_TRUNCATE | \
  99. LANDLOCK_ACCESS_FS_IOCTL_DEV)
  100. /* clang-format on */
  101. static int populate_ruleset_fs(const char *const env_var, const int ruleset_fd,
  102. const __u64 allowed_access)
  103. {
  104. int num_paths, i, ret = 1;
  105. char *env_path_name;
  106. const char **path_list = NULL;
  107. struct landlock_path_beneath_attr path_beneath = {
  108. .parent_fd = -1,
  109. };
  110. env_path_name = getenv(env_var);
  111. if (!env_path_name) {
  112. /* Prevents users to forget a setting. */
  113. fprintf(stderr, "Missing environment variable %s\n", env_var);
  114. return 1;
  115. }
  116. env_path_name = strdup(env_path_name);
  117. unsetenv(env_var);
  118. num_paths = parse_path(env_path_name, &path_list);
  119. if (num_paths < 0) {
  120. fprintf(stderr, "Failed to allocate memory\n");
  121. goto out_free_name;
  122. }
  123. if (num_paths == 1 && path_list[0][0] == '\0') {
  124. /*
  125. * Allows to not use all possible restrictions (e.g. use
  126. * LL_FS_RO without LL_FS_RW).
  127. */
  128. ret = 0;
  129. goto out_free_name;
  130. }
  131. for (i = 0; i < num_paths; i++) {
  132. struct stat statbuf;
  133. path_beneath.parent_fd = open(path_list[i], O_PATH | O_CLOEXEC);
  134. if (path_beneath.parent_fd < 0) {
  135. fprintf(stderr, "Failed to open \"%s\": %s\n",
  136. path_list[i], strerror(errno));
  137. continue;
  138. }
  139. if (fstat(path_beneath.parent_fd, &statbuf)) {
  140. fprintf(stderr, "Failed to stat \"%s\": %s\n",
  141. path_list[i], strerror(errno));
  142. close(path_beneath.parent_fd);
  143. goto out_free_name;
  144. }
  145. path_beneath.allowed_access = allowed_access;
  146. if (!S_ISDIR(statbuf.st_mode))
  147. path_beneath.allowed_access &= ACCESS_FILE;
  148. if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
  149. &path_beneath, 0)) {
  150. fprintf(stderr,
  151. "Failed to update the ruleset with \"%s\": %s\n",
  152. path_list[i], strerror(errno));
  153. close(path_beneath.parent_fd);
  154. goto out_free_name;
  155. }
  156. close(path_beneath.parent_fd);
  157. }
  158. ret = 0;
  159. out_free_name:
  160. free(path_list);
  161. free(env_path_name);
  162. return ret;
  163. }
  164. static int populate_ruleset_net(const char *const env_var, const int ruleset_fd,
  165. const __u64 allowed_access)
  166. {
  167. int ret = 1;
  168. char *env_port_name, *env_port_name_next, *strport;
  169. struct landlock_net_port_attr net_port = {
  170. .allowed_access = allowed_access,
  171. };
  172. env_port_name = getenv(env_var);
  173. if (!env_port_name)
  174. return 0;
  175. env_port_name = strdup(env_port_name);
  176. unsetenv(env_var);
  177. env_port_name_next = env_port_name;
  178. while ((strport = strsep(&env_port_name_next, ENV_DELIMITER))) {
  179. __u64 port;
  180. if (strcmp(strport, "") == 0)
  181. continue;
  182. if (str2num(strport, &port)) {
  183. fprintf(stderr, "Failed to parse port at \"%s\"\n",
  184. strport);
  185. goto out_free_name;
  186. }
  187. net_port.port = port;
  188. if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
  189. &net_port, 0)) {
  190. fprintf(stderr,
  191. "Failed to update the ruleset with port \"%llu\": %s\n",
  192. net_port.port, strerror(errno));
  193. goto out_free_name;
  194. }
  195. }
  196. ret = 0;
  197. out_free_name:
  198. free(env_port_name);
  199. return ret;
  200. }
  201. /* Returns true on error, false otherwise. */
  202. static bool check_ruleset_scope(const char *const env_var,
  203. struct landlock_ruleset_attr *ruleset_attr)
  204. {
  205. char *env_type_scope, *env_type_scope_next, *ipc_scoping_name;
  206. bool error = false;
  207. bool abstract_scoping = false;
  208. bool signal_scoping = false;
  209. /* Scoping is not supported by Landlock ABI */
  210. if (!(ruleset_attr->scoped &
  211. (LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL)))
  212. goto out_unset;
  213. env_type_scope = getenv(env_var);
  214. /* Scoping is not supported by the user */
  215. if (!env_type_scope || strcmp("", env_type_scope) == 0)
  216. goto out_unset;
  217. env_type_scope = strdup(env_type_scope);
  218. env_type_scope_next = env_type_scope;
  219. while ((ipc_scoping_name =
  220. strsep(&env_type_scope_next, ENV_DELIMITER))) {
  221. if (strcmp("a", ipc_scoping_name) == 0 && !abstract_scoping) {
  222. abstract_scoping = true;
  223. } else if (strcmp("s", ipc_scoping_name) == 0 &&
  224. !signal_scoping) {
  225. signal_scoping = true;
  226. } else {
  227. fprintf(stderr, "Unknown or duplicate scope \"%s\"\n",
  228. ipc_scoping_name);
  229. error = true;
  230. goto out_free_name;
  231. }
  232. }
  233. out_free_name:
  234. free(env_type_scope);
  235. out_unset:
  236. if (!abstract_scoping)
  237. ruleset_attr->scoped &= ~LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET;
  238. if (!signal_scoping)
  239. ruleset_attr->scoped &= ~LANDLOCK_SCOPE_SIGNAL;
  240. unsetenv(env_var);
  241. return error;
  242. }
  243. /* clang-format off */
  244. #define ACCESS_FS_ROUGHLY_READ ( \
  245. LANDLOCK_ACCESS_FS_EXECUTE | \
  246. LANDLOCK_ACCESS_FS_READ_FILE | \
  247. LANDLOCK_ACCESS_FS_READ_DIR)
  248. #define ACCESS_FS_ROUGHLY_WRITE ( \
  249. LANDLOCK_ACCESS_FS_WRITE_FILE | \
  250. LANDLOCK_ACCESS_FS_REMOVE_DIR | \
  251. LANDLOCK_ACCESS_FS_REMOVE_FILE | \
  252. LANDLOCK_ACCESS_FS_MAKE_CHAR | \
  253. LANDLOCK_ACCESS_FS_MAKE_DIR | \
  254. LANDLOCK_ACCESS_FS_MAKE_REG | \
  255. LANDLOCK_ACCESS_FS_MAKE_SOCK | \
  256. LANDLOCK_ACCESS_FS_MAKE_FIFO | \
  257. LANDLOCK_ACCESS_FS_MAKE_BLOCK | \
  258. LANDLOCK_ACCESS_FS_MAKE_SYM | \
  259. LANDLOCK_ACCESS_FS_REFER | \
  260. LANDLOCK_ACCESS_FS_TRUNCATE | \
  261. LANDLOCK_ACCESS_FS_IOCTL_DEV)
  262. /* clang-format on */
  263. #define LANDLOCK_ABI_LAST 8
  264. #define XSTR(s) #s
  265. #define STR(s) XSTR(s)
  266. /* clang-format off */
  267. static const char help[] =
  268. "usage: " ENV_FS_RO_NAME "=\"...\" " ENV_FS_RW_NAME "=\"...\" "
  269. "[other environment variables] %1$s <cmd> [args]...\n"
  270. "\n"
  271. "Execute the given command in a restricted environment.\n"
  272. "Multi-valued settings (lists of ports, paths, scopes) are colon-delimited.\n"
  273. "\n"
  274. "Mandatory settings:\n"
  275. "* " ENV_FS_RO_NAME ": paths allowed to be used in a read-only way\n"
  276. "* " ENV_FS_RW_NAME ": paths allowed to be used in a read-write way\n"
  277. "\n"
  278. "Optional settings (when not set, their associated access check "
  279. "is always allowed, which is different from an empty string which "
  280. "means an empty list):\n"
  281. "* " ENV_TCP_BIND_NAME ": ports allowed to bind (server)\n"
  282. "* " ENV_TCP_CONNECT_NAME ": ports allowed to connect (client)\n"
  283. "* " ENV_SCOPED_NAME ": actions denied on the outside of the landlock domain\n"
  284. " - \"a\" to restrict opening abstract unix sockets\n"
  285. " - \"s\" to restrict sending signals\n"
  286. "\n"
  287. "A sandboxer should not log denied access requests to avoid spamming logs, "
  288. "but to test audit we can set " ENV_FORCE_LOG_NAME "=1\n"
  289. "\n"
  290. "Example:\n"
  291. ENV_FS_RO_NAME "=\"${PATH}:/lib:/usr:/proc:/etc:/dev/urandom\" "
  292. ENV_FS_RW_NAME "=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" "
  293. ENV_TCP_BIND_NAME "=\"9418\" "
  294. ENV_TCP_CONNECT_NAME "=\"80:443\" "
  295. ENV_SCOPED_NAME "=\"a:s\" "
  296. "%1$s bash -i\n"
  297. "\n"
  298. "This sandboxer can use Landlock features up to ABI version "
  299. STR(LANDLOCK_ABI_LAST) ".\n";
  300. /* clang-format on */
  301. int main(const int argc, char *const argv[], char *const *const envp)
  302. {
  303. const char *cmd_path;
  304. char *const *cmd_argv;
  305. int ruleset_fd, abi;
  306. char *env_port_name, *env_force_log;
  307. __u64 access_fs_ro = ACCESS_FS_ROUGHLY_READ,
  308. access_fs_rw = ACCESS_FS_ROUGHLY_READ | ACCESS_FS_ROUGHLY_WRITE;
  309. struct landlock_ruleset_attr ruleset_attr = {
  310. .handled_access_fs = access_fs_rw,
  311. .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
  312. LANDLOCK_ACCESS_NET_CONNECT_TCP,
  313. .scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
  314. LANDLOCK_SCOPE_SIGNAL,
  315. };
  316. int supported_restrict_flags = LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON;
  317. int set_restrict_flags = 0;
  318. if (argc < 2) {
  319. fprintf(stderr, help, argv[0]);
  320. return 1;
  321. }
  322. abi = landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
  323. if (abi < 0) {
  324. const int err = errno;
  325. perror("Failed to check Landlock compatibility");
  326. switch (err) {
  327. case ENOSYS:
  328. fprintf(stderr,
  329. "Hint: Landlock is not supported by the current kernel. "
  330. "To support it, build the kernel with "
  331. "CONFIG_SECURITY_LANDLOCK=y and prepend "
  332. "\"landlock,\" to the content of CONFIG_LSM.\n");
  333. break;
  334. case EOPNOTSUPP:
  335. fprintf(stderr,
  336. "Hint: Landlock is currently disabled. "
  337. "It can be enabled in the kernel configuration by "
  338. "prepending \"landlock,\" to the content of CONFIG_LSM, "
  339. "or at boot time by setting the same content to the "
  340. "\"lsm\" kernel parameter.\n");
  341. break;
  342. }
  343. return 1;
  344. }
  345. /* Best-effort security. */
  346. switch (abi) {
  347. case 1:
  348. /*
  349. * Removes LANDLOCK_ACCESS_FS_REFER for ABI < 2
  350. *
  351. * Note: The "refer" operations (file renaming and linking
  352. * across different directories) are always forbidden when using
  353. * Landlock with ABI 1.
  354. *
  355. * If only ABI 1 is available, this sandboxer knowingly forbids
  356. * refer operations.
  357. *
  358. * If a program *needs* to do refer operations after enabling
  359. * Landlock, it can not use Landlock at ABI level 1. To be
  360. * compatible with different kernel versions, such programs
  361. * should then fall back to not restrict themselves at all if
  362. * the running kernel only supports ABI 1.
  363. */
  364. ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_REFER;
  365. __attribute__((fallthrough));
  366. case 2:
  367. /* Removes LANDLOCK_ACCESS_FS_TRUNCATE for ABI < 3 */
  368. ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_TRUNCATE;
  369. __attribute__((fallthrough));
  370. case 3:
  371. /* Removes network support for ABI < 4 */
  372. ruleset_attr.handled_access_net &=
  373. ~(LANDLOCK_ACCESS_NET_BIND_TCP |
  374. LANDLOCK_ACCESS_NET_CONNECT_TCP);
  375. __attribute__((fallthrough));
  376. case 4:
  377. /* Removes LANDLOCK_ACCESS_FS_IOCTL_DEV for ABI < 5 */
  378. ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_IOCTL_DEV;
  379. __attribute__((fallthrough));
  380. case 5:
  381. /* Removes LANDLOCK_SCOPE_* for ABI < 6 */
  382. ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
  383. LANDLOCK_SCOPE_SIGNAL);
  384. __attribute__((fallthrough));
  385. case 6:
  386. /* Removes LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON for ABI < 7 */
  387. supported_restrict_flags &=
  388. ~LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON;
  389. __attribute__((fallthrough));
  390. case 7:
  391. /* Must be printed for any ABI < LANDLOCK_ABI_LAST. */
  392. fprintf(stderr,
  393. "Hint: You should update the running kernel "
  394. "to leverage Landlock features "
  395. "provided by ABI version %d (instead of %d).\n",
  396. LANDLOCK_ABI_LAST, abi);
  397. __attribute__((fallthrough));
  398. case LANDLOCK_ABI_LAST:
  399. break;
  400. default:
  401. fprintf(stderr,
  402. "Hint: You should update this sandboxer "
  403. "to leverage Landlock features "
  404. "provided by ABI version %d (instead of %d).\n",
  405. abi, LANDLOCK_ABI_LAST);
  406. }
  407. access_fs_ro &= ruleset_attr.handled_access_fs;
  408. access_fs_rw &= ruleset_attr.handled_access_fs;
  409. /* Removes bind access attribute if not supported by a user. */
  410. env_port_name = getenv(ENV_TCP_BIND_NAME);
  411. if (!env_port_name) {
  412. ruleset_attr.handled_access_net &=
  413. ~LANDLOCK_ACCESS_NET_BIND_TCP;
  414. }
  415. /* Removes connect access attribute if not supported by a user. */
  416. env_port_name = getenv(ENV_TCP_CONNECT_NAME);
  417. if (!env_port_name) {
  418. ruleset_attr.handled_access_net &=
  419. ~LANDLOCK_ACCESS_NET_CONNECT_TCP;
  420. }
  421. if (check_ruleset_scope(ENV_SCOPED_NAME, &ruleset_attr))
  422. return 1;
  423. /* Enables optional logs. */
  424. env_force_log = getenv(ENV_FORCE_LOG_NAME);
  425. if (env_force_log) {
  426. if (strcmp(env_force_log, "1") != 0) {
  427. fprintf(stderr, "Unknown value for " ENV_FORCE_LOG_NAME
  428. " (only \"1\" is handled)\n");
  429. return 1;
  430. }
  431. if (!(supported_restrict_flags &
  432. LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON)) {
  433. fprintf(stderr,
  434. "Audit logs not supported by current kernel\n");
  435. return 1;
  436. }
  437. set_restrict_flags |= LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON;
  438. unsetenv(ENV_FORCE_LOG_NAME);
  439. }
  440. ruleset_fd =
  441. landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
  442. if (ruleset_fd < 0) {
  443. perror("Failed to create a ruleset");
  444. return 1;
  445. }
  446. if (populate_ruleset_fs(ENV_FS_RO_NAME, ruleset_fd, access_fs_ro)) {
  447. goto err_close_ruleset;
  448. }
  449. if (populate_ruleset_fs(ENV_FS_RW_NAME, ruleset_fd, access_fs_rw)) {
  450. goto err_close_ruleset;
  451. }
  452. if (populate_ruleset_net(ENV_TCP_BIND_NAME, ruleset_fd,
  453. LANDLOCK_ACCESS_NET_BIND_TCP)) {
  454. goto err_close_ruleset;
  455. }
  456. if (populate_ruleset_net(ENV_TCP_CONNECT_NAME, ruleset_fd,
  457. LANDLOCK_ACCESS_NET_CONNECT_TCP)) {
  458. goto err_close_ruleset;
  459. }
  460. if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
  461. perror("Failed to restrict privileges");
  462. goto err_close_ruleset;
  463. }
  464. if (landlock_restrict_self(ruleset_fd, set_restrict_flags)) {
  465. perror("Failed to enforce ruleset");
  466. goto err_close_ruleset;
  467. }
  468. close(ruleset_fd);
  469. cmd_path = argv[1];
  470. cmd_argv = argv + 1;
  471. fprintf(stderr, "Executing the sandboxed command...\n");
  472. execvpe(cmd_path, cmd_argv, envp);
  473. fprintf(stderr, "Failed to execute \"%s\": %s\n", cmd_path,
  474. strerror(errno));
  475. fprintf(stderr, "Hint: access to the binary, the interpreter or "
  476. "shared libraries may be denied.\n");
  477. return 1;
  478. err_close_ruleset:
  479. close(ruleset_fd);
  480. return 1;
  481. }