strict_rwx.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Module strict rwx
  4. *
  5. * Copyright (C) 2015 Rusty Russell
  6. */
  7. #include <linux/module.h>
  8. #include <linux/mm.h>
  9. #include <linux/vmalloc.h>
  10. #include <linux/set_memory.h>
  11. #include "internal.h"
  12. static int module_set_memory(const struct module *mod, enum mod_mem_type type,
  13. int (*set_memory)(unsigned long start, int num_pages))
  14. {
  15. const struct module_memory *mod_mem = &mod->mem[type];
  16. if (!mod_mem->base)
  17. return 0;
  18. set_vm_flush_reset_perms(mod_mem->base);
  19. return set_memory((unsigned long)mod_mem->base, mod_mem->size >> PAGE_SHIFT);
  20. }
  21. /*
  22. * Since some arches are moving towards PAGE_KERNEL module allocations instead
  23. * of PAGE_KERNEL_EXEC, keep module_enable_x() independent of
  24. * CONFIG_STRICT_MODULE_RWX because they are needed regardless of whether we
  25. * are strict.
  26. */
  27. int module_enable_text_rox(const struct module *mod)
  28. {
  29. for_class_mod_mem_type(type, text) {
  30. int ret;
  31. if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
  32. ret = module_set_memory(mod, type, set_memory_rox);
  33. else
  34. ret = module_set_memory(mod, type, set_memory_x);
  35. if (ret)
  36. return ret;
  37. }
  38. return 0;
  39. }
  40. int module_enable_rodata_ro(const struct module *mod, bool after_init)
  41. {
  42. int ret;
  43. if (!IS_ENABLED(CONFIG_STRICT_MODULE_RWX) || !rodata_enabled)
  44. return 0;
  45. ret = module_set_memory(mod, MOD_RODATA, set_memory_ro);
  46. if (ret)
  47. return ret;
  48. ret = module_set_memory(mod, MOD_INIT_RODATA, set_memory_ro);
  49. if (ret)
  50. return ret;
  51. if (after_init)
  52. return module_set_memory(mod, MOD_RO_AFTER_INIT, set_memory_ro);
  53. return 0;
  54. }
  55. int module_enable_data_nx(const struct module *mod)
  56. {
  57. if (!IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
  58. return 0;
  59. for_class_mod_mem_type(type, data) {
  60. int ret = module_set_memory(mod, type, set_memory_nx);
  61. if (ret)
  62. return ret;
  63. }
  64. return 0;
  65. }
  66. int module_enforce_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
  67. char *secstrings, struct module *mod)
  68. {
  69. const unsigned long shf_wx = SHF_WRITE | SHF_EXECINSTR;
  70. int i;
  71. if (!IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
  72. return 0;
  73. for (i = 0; i < hdr->e_shnum; i++) {
  74. if ((sechdrs[i].sh_flags & shf_wx) == shf_wx) {
  75. pr_err("%s: section %s (index %d) has invalid WRITE|EXEC flags\n",
  76. mod->name, secstrings + sechdrs[i].sh_name, i);
  77. return -ENOEXEC;
  78. }
  79. }
  80. return 0;
  81. }