logo

utils

~/.local/bin tools and git-hooks git clone https://hacktivis.me/git/utils.git

chroot.c (1259B)


  1. // Collection of Unix tools, comparable to coreutils
  2. // SPDX-FileCopyrightText: 2017-2023 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #define _DEFAULT_SOURCE // chroot
  6. #include <assert.h> // assert
  7. #include <errno.h> // errno
  8. #include <stdbool.h> // false
  9. #include <stdio.h> // fprintf, perror
  10. #include <stdlib.h> // getenv
  11. #include <unistd.h> // chroot, execl, execv
  12. int
  13. main(int argc, char *argv[])
  14. {
  15. if(argc < 2)
  16. {
  17. fprintf(stderr, "chroot: Needs arguments\n");
  18. fprintf(stderr, "Usage: chroot <newroot> [command [args ...]]\n");
  19. return 125;
  20. }
  21. if(chroot(argv[1]) < 0)
  22. {
  23. perror("chroot");
  24. return 125;
  25. }
  26. if(chdir("/") < 0)
  27. {
  28. perror("chdir");
  29. return 125;
  30. }
  31. int ret = 0;
  32. errno = 0;
  33. if(argc == 2)
  34. {
  35. char *shell = getenv("SHELL");
  36. if(shell == NULL) shell = "/bin/sh";
  37. /* flawfinder: ignore. No restrictions on commands is intended */
  38. ret = execlp(shell, shell, "-i", NULL);
  39. }
  40. else
  41. {
  42. argv += 2;
  43. /* flawfinder: ignore. No restrictions on commands is intended */
  44. ret = execvp(argv[0], argv);
  45. }
  46. if(ret != 0)
  47. {
  48. perror("chroot: exec");
  49. if(errno == ENOENT) return 127;
  50. return 126;
  51. }
  52. assert(false);
  53. }