summaryrefslogtreecommitdiffstats
path: root/linux/SELinuxMeter.c
blob: c35cb686f1cac992bf6758944bcc0bd3eb5209b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
htop - SELinuxMeter.c
(C) 2020 htop dev team
Released under the GNU GPLv2+, see the COPYING file
in the source distribution for its full text.
*/

#include "linux/SELinuxMeter.h"

#include "CRT.h"

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/statfs.h>
#include <sys/statvfs.h>

#include "Object.h"
#include "XUtils.h"


static const int SELinuxMeter_attributes[] = {
   METER_TEXT,
};

static bool enabled = false;
static bool enforcing = false;

static bool hasSELinuxMount(void) {
   struct statfs sfbuf;
   int r = statfs("/sys/fs/selinux", &sfbuf);
   if (r != 0) {
      return false;
   }

   if ((uint32_t)sfbuf.f_type != /* SELINUX_MAGIC */ 0xf97cff8cU) {
      return false;
   }

   struct statvfs vfsbuf;
   r = statvfs("/sys/fs/selinux", &vfsbuf);
   if (r != 0 || (vfsbuf.f_flag & ST_RDONLY)) {
      return false;
   }

   return true;
}

static bool isSelinuxEnabled(void) {
   return hasSELinuxMount() && (0 == access("/etc/selinux/config", F_OK));
}

static bool isSelinuxEnforcing(void) {
   if (!enabled) {
      return false;
   }

   char buf[20];
   ssize_t r = xReadfile("/sys/fs/selinux/enforce", buf, sizeof(buf));
   if (r < 0)
      return false;

   int enforce = 0;
   if (sscanf(buf, "%d", &enforce) != 1) {
      return false;
   }

   return !!enforce;
}

static void SELinuxMeter_updateValues(Meter* this) {
   enabled = isSelinuxEnabled();
   enforcing = isSelinuxEnforcing();

   xSnprintf(this->txtBuffer, sizeof(this->txtBuffer), "%s%s", enabled ? "enabled" : "disabled", enabled ? (enforcing ? "; mode: enforcing" : "; mode: permissive") : "");
}

const MeterClass SELinuxMeter_class = {
   .super = {
      .extends = Class(Meter),
      .delete = Meter_delete,
   },
   .updateValues = SELinuxMeter_updateValues,
   .defaultMode = TEXT_METERMODE,
   .maxItems = 0,
   .total = 100.0,
   .attributes = SELinuxMeter_attributes,
   .name = "SELinux",
   .uiName = "SELinux",
   .description = "SELinux state overview",
   .caption = "SELinux: "
};