1use std::num::NonZeroU32;
6use zerocopy::{Immutable, IntoBytes};
7
8#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, IntoBytes, Immutable)]
10pub struct SecurityId(pub NonZeroU32);
11
12#[repr(u64)]
16pub enum ReferenceInitialSid {
17 Kernel = 1,
18 Security = 2,
19 Unlabeled = 3,
20 _Fs = 4,
21 File = 5,
22 _Port = 9,
23 _Netif = 10,
24 _Netmsg = 11,
25 _Node = 12,
26 _Sysctl = 17,
27 Devnull = 27,
28
29 FirstUnused,
32}
33
34#[macro_export]
35macro_rules! initial_sid_enum {
36 ($(#[$meta:meta])* $name:ident {
37 $($(#[$variant_meta:meta])* $variant:ident ($variant_name: literal)),*,
38 }) => {
39 $(#[$meta])*
40 pub enum $name {
41 $($(#[$variant_meta])* $variant = ReferenceInitialSid::$variant as isize),*
42 }
43
44 impl $name {
45 pub fn all_variants() -> &'static [Self] {
46 &[
47 $($name::$variant),*
48 ]
49 }
50
51 pub fn name(&self) -> &'static str {
52 match self {
53 $($name::$variant => $variant_name),*
54 }
55 }
56 }
57 }
58}
59
60initial_sid_enum! {
61#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
64 InitialSid {
65 Devnull("devnull"),
67 File("file"),
68 Kernel("kernel"),
69 Security("security"),
70 Unlabeled("unlabeled"),
71 }
73}
74
75impl From<InitialSid> for SecurityId {
76 fn from(initial_sid: InitialSid) -> Self {
77 Self(NonZeroU32::new(initial_sid as u32).unwrap())
81 }
82}
83
84#[derive(Clone, Debug, PartialEq)]
86pub struct TaskAttrs {
87 pub current_sid: SecurityId,
89
90 pub exec_sid: Option<SecurityId>,
92
93 pub fscreate_sid: Option<SecurityId>,
95
96 pub keycreate_sid: Option<SecurityId>,
98
99 pub previous_sid: SecurityId,
101
102 pub sockcreate_sid: Option<SecurityId>,
104
105 pub internal_operation: bool,
108}
109
110impl TaskAttrs {
111 pub fn for_kernel() -> Self {
113 Self::for_sid(InitialSid::Kernel.into())
114 }
115
116 pub fn for_selinux_disabled() -> Self {
118 Self::for_sid(InitialSid::Unlabeled.into())
119 }
120
121 pub fn for_sid(sid: SecurityId) -> Self {
123 Self::for_transition(sid, sid)
124 }
125
126 pub fn for_transition(new_sid: SecurityId, old_sid: SecurityId) -> Self {
128 Self {
129 current_sid: new_sid,
130 previous_sid: old_sid,
131 exec_sid: None,
132 fscreate_sid: None,
133 keycreate_sid: None,
134 sockcreate_sid: None,
135 internal_operation: false,
136 }
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 #[test]
145 fn task_alloc_for_kernel() {
146 let for_kernel = TaskAttrs::for_kernel();
147 assert_eq!(for_kernel.current_sid, InitialSid::Kernel.into());
148 assert_eq!(for_kernel.previous_sid, for_kernel.current_sid);
149 assert_eq!(for_kernel.exec_sid, None);
150 assert_eq!(for_kernel.fscreate_sid, None);
151 assert_eq!(for_kernel.keycreate_sid, None);
152 assert_eq!(for_kernel.sockcreate_sid, None);
153 }
154}