SELinuxMeter.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. htop - SELinuxMeter.c
  3. (C) 2020 htop dev team
  4. Released under the GNU GPLv2+, see the COPYING file
  5. in the source distribution for its full text.
  6. */
  7. #include "config.h" // IWYU pragma: keep
  8. #include "linux/SELinuxMeter.h"
  9. #include "CRT.h"
  10. #include <stdbool.h>
  11. #include <stdint.h>
  12. #include <stdio.h>
  13. #include <unistd.h>
  14. #include <sys/statfs.h>
  15. #include <sys/statvfs.h>
  16. #include "Object.h"
  17. #include "XUtils.h"
  18. static const int SELinuxMeter_attributes[] = {
  19. METER_TEXT,
  20. };
  21. static bool enabled = false;
  22. static bool enforcing = false;
  23. static bool hasSELinuxMount(void) {
  24. struct statfs sfbuf;
  25. int r = statfs("/sys/fs/selinux", &sfbuf);
  26. if (r != 0) {
  27. return false;
  28. }
  29. if ((uint32_t)sfbuf.f_type != /* SELINUX_MAGIC */ 0xf97cff8cU) {
  30. return false;
  31. }
  32. struct statvfs vfsbuf;
  33. r = statvfs("/sys/fs/selinux", &vfsbuf);
  34. if (r != 0 || (vfsbuf.f_flag & ST_RDONLY)) {
  35. return false;
  36. }
  37. return true;
  38. }
  39. static bool isSelinuxEnabled(void) {
  40. return hasSELinuxMount() && (0 == access("/etc/selinux/config", F_OK));
  41. }
  42. static bool isSelinuxEnforcing(void) {
  43. if (!enabled) {
  44. return false;
  45. }
  46. char buf[20];
  47. ssize_t r = xReadfile("/sys/fs/selinux/enforce", buf, sizeof(buf));
  48. if (r < 0)
  49. return false;
  50. int enforce = 0;
  51. if (sscanf(buf, "%d", &enforce) != 1) {
  52. return false;
  53. }
  54. return !!enforce;
  55. }
  56. static void SELinuxMeter_updateValues(Meter* this) {
  57. enabled = isSelinuxEnabled();
  58. enforcing = isSelinuxEnforcing();
  59. xSnprintf(this->txtBuffer, sizeof(this->txtBuffer), "%s%s", enabled ? "enabled" : "disabled", enabled ? (enforcing ? "; mode: enforcing" : "; mode: permissive") : "");
  60. }
  61. const MeterClass SELinuxMeter_class = {
  62. .super = {
  63. .extends = Class(Meter),
  64. .delete = Meter_delete,
  65. },
  66. .updateValues = SELinuxMeter_updateValues,
  67. .defaultMode = TEXT_METERMODE,
  68. .supportedModes = (1 << TEXT_METERMODE),
  69. .maxItems = 0,
  70. .total = 0.0,
  71. .attributes = SELinuxMeter_attributes,
  72. .name = "SELinux",
  73. .uiName = "SELinux",
  74. .description = "SELinux state overview",
  75. .caption = "SELinux: "
  76. };