1pub mod arrays;
6pub mod error;
7pub mod index;
8pub mod metadata;
9pub mod parsed_policy;
10pub mod parser;
11pub mod view;
12
13mod constraints;
14mod extensible_bitmap;
15mod security_context;
16mod symbols;
17
18pub use arrays::{FsUseType, XpermsBitmap};
19pub use index::FsUseLabelAndType;
20pub use parser::PolicyCursor;
21pub use security_context::{SecurityContext, SecurityContextError};
22
23use crate::{ClassPermission, KernelClass, NullessByteStr, ObjectClass, PolicyCap};
24use index::PolicyIndex;
25use metadata::HandleUnknown;
26use parsed_policy::ParsedPolicy;
27use parser::PolicyData;
28use symbols::{find_class_by_name, find_common_symbol_by_name_bytes};
29
30use anyhow::Context as _;
31use std::fmt::{Debug, Display, LowerHex};
32use std::num::{NonZeroU8, NonZeroU32};
33use std::ops::Deref;
34use std::str::FromStr;
35use std::sync::Arc;
36use zerocopy::{
37 FromBytes, Immutable, KnownLayout, Ref, SplitByteSlice, Unaligned, little_endian as le,
38};
39
40#[derive(Copy, Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
42pub struct UserId(NonZeroU32);
43
44#[derive(Copy, Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
46pub struct RoleId(NonZeroU32);
47
48#[derive(Copy, Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
50pub struct TypeId(NonZeroU32);
51
52#[derive(Copy, Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
54pub struct SensitivityId(NonZeroU32);
55
56#[derive(Copy, Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
58pub struct CategoryId(NonZeroU32);
59
60#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
63pub struct ClassId(NonZeroU32);
64
65impl ClassId {
66 pub fn new(id: NonZeroU32) -> Self {
68 Self(id)
69 }
70}
71
72impl Into<u32> for ClassId {
73 fn into(self) -> u32 {
74 self.0.into()
75 }
76}
77
78#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
80pub struct ClassPermissionId(NonZeroU8);
81
82impl Display for ClassPermissionId {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 write!(f, "{}", self.0)
85 }
86}
87
88#[derive(Debug, Clone, PartialEq)]
93pub struct AccessDecision {
94 pub allow: AccessVector,
95 pub auditallow: AccessVector,
96 pub auditdeny: AccessVector,
97 pub flags: u32,
98
99 pub todo_bug: Option<NonZeroU32>,
102}
103
104impl Default for AccessDecision {
105 fn default() -> Self {
106 Self::allow(AccessVector::NONE)
107 }
108}
109
110impl AccessDecision {
111 pub(super) const fn allow(allow: AccessVector) -> Self {
114 Self {
115 allow,
116 auditallow: AccessVector::NONE,
117 auditdeny: AccessVector::ALL,
118 flags: 0,
119 todo_bug: None,
120 }
121 }
122}
123
124pub(super) const SELINUX_AVD_FLAGS_PERMISSIVE: u32 = 1;
126
127#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
130pub struct AccessVector(u32);
131
132impl AccessVector {
133 pub const NONE: AccessVector = AccessVector(0);
134 pub const ALL: AccessVector = AccessVector(std::u32::MAX);
135
136 pub(super) fn from_class_permission_id(id: ClassPermissionId) -> Self {
137 Self((1 as u32) << (id.0.get() - 1))
138 }
139}
140
141impl From<u32> for AccessVector {
142 fn from(x: u32) -> Self {
143 Self(x)
144 }
145}
146
147impl Into<u32> for AccessVector {
148 fn into(self) -> u32 {
149 self.0
150 }
151}
152
153impl Debug for AccessVector {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 write!(f, "AccessVector({:0>8x})", self)
156 }
157}
158
159impl FromStr for AccessVector {
160 type Err = <u32 as FromStr>::Err;
161
162 fn from_str(value: &str) -> Result<Self, Self::Err> {
163 Ok(AccessVector(u32::from_str_radix(value, 16)?))
165 }
166}
167
168impl LowerHex for AccessVector {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 LowerHex::fmt(&self.0, f)
171 }
172}
173
174impl std::ops::BitAnd for AccessVector {
175 type Output = Self;
176
177 fn bitand(self, rhs: Self) -> Self::Output {
178 AccessVector(self.0 & rhs.0)
179 }
180}
181
182impl std::ops::BitOr for AccessVector {
183 type Output = Self;
184
185 fn bitor(self, rhs: Self) -> Self::Output {
186 AccessVector(self.0 | rhs.0)
187 }
188}
189
190impl std::ops::BitAndAssign for AccessVector {
191 fn bitand_assign(&mut self, rhs: Self) {
192 self.0 &= rhs.0
193 }
194}
195
196impl std::ops::BitOrAssign for AccessVector {
197 fn bitor_assign(&mut self, rhs: Self) {
198 self.0 |= rhs.0
199 }
200}
201
202impl std::ops::SubAssign for AccessVector {
203 fn sub_assign(&mut self, rhs: Self) {
204 self.0 = self.0 ^ (self.0 & rhs.0);
205 }
206}
207
208impl std::ops::Sub for AccessVector {
209 type Output = Self;
210
211 fn sub(self, rhs: Self) -> Self::Output {
212 AccessVector(self.0 ^ (self.0 & rhs.0))
213 }
214}
215
216impl std::ops::Not for AccessVector {
217 type Output = Self;
218
219 fn not(self) -> Self {
220 AccessVector(!self.0)
221 }
222}
223
224#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
227pub enum XpermsKind {
228 Ioctl,
229 Nlmsg,
230}
231
232#[derive(Debug, Clone, PartialEq)]
237pub struct XpermsAccessDecision {
238 pub allow: XpermsBitmap,
239 pub auditallow: XpermsBitmap,
240 pub auditdeny: XpermsBitmap,
241}
242
243impl XpermsAccessDecision {
244 pub const DENY_ALL: Self = Self {
245 allow: XpermsBitmap::NONE,
246 auditallow: XpermsBitmap::NONE,
247 auditdeny: XpermsBitmap::ALL,
248 };
249 pub const ALLOW_ALL: Self = Self {
250 allow: XpermsBitmap::ALL,
251 auditallow: XpermsBitmap::NONE,
252 auditdeny: XpermsBitmap::ALL,
253 };
254}
255
256pub fn parse_policy_by_value(binary_policy: Vec<u8>) -> Result<Unvalidated, anyhow::Error> {
265 let policy_data = Arc::new(binary_policy);
266 let policy = ParsedPolicy::parse(policy_data).context("parsing policy")?;
267 Ok(Unvalidated(policy))
268}
269
270pub struct ClassInfo {
272 pub class_name: Box<[u8]>,
274 pub class_id: ClassId,
276}
277
278#[derive(Debug)]
279pub struct Policy(PolicyIndex);
280
281impl Policy {
282 pub fn policy_version(&self) -> u32 {
284 self.0.parsed_policy().policy_version()
285 }
286
287 pub fn binary(&self) -> &PolicyData {
288 &self.0.parsed_policy().data
289 }
290
291 pub fn handle_unknown(&self) -> HandleUnknown {
294 self.0.parsed_policy().handle_unknown()
295 }
296
297 pub fn conditional_booleans<'a>(&'a self) -> Vec<(&'a [u8], bool)> {
298 self.0
299 .parsed_policy()
300 .conditional_booleans()
301 .iter()
302 .map(|boolean| (boolean.data.as_slice(), boolean.metadata.active()))
303 .collect()
304 }
305
306 pub fn classes(&self) -> Vec<ClassInfo> {
308 self.0
309 .parsed_policy()
310 .classes()
311 .into_iter()
312 .map(|class| ClassInfo {
313 class_name: Box::<[u8]>::from(class.name_bytes()),
314 class_id: class.id(),
315 })
316 .collect()
317 }
318
319 pub(super) fn type_id_by_name(&self, name: &str) -> Option<TypeId> {
321 self.0.parsed_policy().type_id_by_name(name)
322 }
323
324 pub fn find_class_permissions_by_name(
329 &self,
330 class_name: &str,
331 ) -> Result<Vec<(ClassPermissionId, Vec<u8>)>, ()> {
332 let classes = self.0.parsed_policy().classes();
333 let class = find_class_by_name(&classes, class_name).ok_or(())?;
334 let owned_permissions = class.permissions();
335
336 let mut result: Vec<_> = owned_permissions
337 .iter()
338 .map(|permission| (permission.id(), permission.name_bytes().to_vec()))
339 .collect();
340
341 if class.common_name_bytes().is_empty() {
343 return Ok(result);
344 }
345
346 let common_symbol_permissions = find_common_symbol_by_name_bytes(
347 self.0.parsed_policy().common_symbols(),
348 class.common_name_bytes(),
349 )
350 .ok_or(())?
351 .permissions();
352
353 result.append(
354 &mut common_symbol_permissions
355 .iter()
356 .map(|permission| (permission.id(), permission.name_bytes().to_vec()))
357 .collect(),
358 );
359
360 Ok(result)
361 }
362
363 pub fn fs_use_label_and_type(&self, fs_type: NullessByteStr<'_>) -> Option<FsUseLabelAndType> {
366 self.0.fs_use_label_and_type(fs_type)
367 }
368
369 pub fn genfscon_label_for_fs_and_path(
372 &self,
373 fs_type: NullessByteStr<'_>,
374 node_path: NullessByteStr<'_>,
375 class_id: Option<KernelClass>,
376 ) -> Option<SecurityContext> {
377 self.0.genfscon_label_for_fs_and_path(fs_type, node_path, class_id)
378 }
379
380 pub fn initial_context(&self, id: crate::InitialSid) -> security_context::SecurityContext {
383 self.0.initial_context(id)
384 }
385
386 pub fn parse_security_context(
388 &self,
389 security_context: NullessByteStr<'_>,
390 ) -> Result<security_context::SecurityContext, security_context::SecurityContextError> {
391 security_context::SecurityContext::parse(&self.0, security_context)
392 }
393
394 pub fn validate_security_context(
396 &self,
397 security_context: &SecurityContext,
398 ) -> Result<(), SecurityContextError> {
399 security_context.validate(&self.0)
400 }
401
402 pub fn serialize_security_context(&self, security_context: &SecurityContext) -> Vec<u8> {
404 security_context.serialize(&self.0)
405 }
406
407 pub fn compute_create_context_with_name(
415 &self,
416 source: &SecurityContext,
417 target: &SecurityContext,
418 class: impl Into<ObjectClass>,
419 name: NullessByteStr<'_>,
420 ) -> Option<SecurityContext> {
421 self.0.compute_create_context_with_name(source, target, class.into(), name)
422 }
423
424 pub fn compute_create_context(
442 &self,
443 source: &SecurityContext,
444 target: &SecurityContext,
445 class: impl Into<ObjectClass>,
446 ) -> SecurityContext {
447 self.0.compute_create_context(source, target, class.into())
448 }
449
450 pub fn compute_access_decision(
460 &self,
461 source_context: &SecurityContext,
462 target_context: &SecurityContext,
463 object_class: impl Into<ObjectClass>,
464 ) -> AccessDecision {
465 if let Some(target_class) = self.0.class(object_class.into()) {
466 self.0.parsed_policy().compute_access_decision(
467 source_context,
468 target_context,
469 &target_class,
470 )
471 } else {
472 let mut decision = AccessDecision::allow(AccessVector::NONE);
473 if self.is_permissive(source_context.type_()) {
474 decision.flags |= SELINUX_AVD_FLAGS_PERMISSIVE;
475 }
476 decision
477 }
478 }
479
480 pub fn compute_xperms_access_decision(
484 &self,
485 xperms_kind: XpermsKind,
486 source_context: &SecurityContext,
487 target_context: &SecurityContext,
488 object_class: impl Into<ObjectClass>,
489 xperms_prefix: u8,
490 ) -> XpermsAccessDecision {
491 if let Some(target_class) = self.0.class(object_class.into()) {
492 self.0.parsed_policy().compute_xperms_access_decision(
493 xperms_kind,
494 source_context,
495 target_context,
496 &target_class,
497 xperms_prefix,
498 )
499 } else {
500 XpermsAccessDecision::DENY_ALL
501 }
502 }
503
504 pub fn is_bounded_by(&self, bounded_type: TypeId, parent_type: TypeId) -> bool {
505 self.0.parsed_policy().type_(bounded_type).bounded_by() == Some(parent_type)
506 }
507
508 pub fn is_permissive(&self, type_: TypeId) -> bool {
510 self.0.parsed_policy().permissive_types().is_set(type_.0.get())
511 }
512
513 pub fn has_policycap(&self, policy_cap: PolicyCap) -> bool {
515 self.0.parsed_policy().has_policycap(policy_cap)
516 }
517}
518
519impl AccessVectorComputer for Policy {
520 fn access_decision_to_kernel_access_decision(
521 &self,
522 class: KernelClass,
523 av: AccessDecision,
524 ) -> KernelAccessDecision {
525 let mut kernel_allow;
526 let mut kernel_audit;
527 if self.0.parsed_policy().handle_unknown() == HandleUnknown::Allow {
530 kernel_allow = 0xffffffffu32;
532 kernel_audit = 0u32;
533 } else {
534 kernel_allow = 0u32;
536 kernel_audit = 0xffffffffu32;
537 }
538
539 let decision_allow = av.allow;
540 let decision_audit = (av.allow & av.auditallow) | (!av.allow & av.auditdeny);
541 for permission in class.permissions() {
542 if let Some(permission_access_vector) =
543 self.0.kernel_permission_to_access_vector(permission.clone())
544 {
545 let bit = 1 << permission.id();
548 let allow = decision_allow & permission_access_vector == permission_access_vector;
549 let audit = decision_audit & permission_access_vector == permission_access_vector;
550 kernel_allow = (kernel_allow & !bit) | ((allow as u32) << permission.id());
551 kernel_audit = (kernel_audit & !bit) | ((audit as u32) << permission.id());
552 }
553 }
554 KernelAccessDecision {
555 allow: AccessVector::from(kernel_allow),
556 audit: AccessVector::from(kernel_audit),
557 flags: av.flags,
558 todo_bug: av.todo_bug,
559 }
560 }
561}
562
563pub struct Unvalidated(ParsedPolicy);
565
566impl Unvalidated {
567 pub fn validate(self) -> Result<Policy, anyhow::Error> {
568 self.0.validate().context("validating parsed policy")?;
569 let index = PolicyIndex::new(self.0).context("building index")?;
570 Ok(Policy(index))
571 }
572}
573
574#[derive(Clone, Copy, Debug, PartialEq, Eq)]
575pub struct KernelAccessDecision {
576 pub allow: AccessVector,
577 pub audit: AccessVector,
578 pub flags: u32,
579 pub todo_bug: Option<NonZeroU32>,
580}
581
582pub trait AccessVectorComputer {
585 fn access_decision_to_kernel_access_decision(
592 &self,
593 class: KernelClass,
594 av: AccessDecision,
595 ) -> KernelAccessDecision;
596}
597
598pub trait Parse: Sized {
600 type Error: Into<anyhow::Error>;
603
604 fn parse<'a>(bytes: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error>;
607}
608
609pub(super) struct PolicyValidationContext {
611 #[allow(unused)]
613 pub(super) data: PolicyData,
614}
615
616pub(super) trait Validate {
618 type Error: Into<anyhow::Error>;
621
622 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error>;
624}
625
626pub(super) trait ValidateArray<M, D> {
627 type Error: Into<anyhow::Error>;
630
631 fn validate_array(
633 context: &PolicyValidationContext,
634 metadata: &M,
635 items: &[D],
636 ) -> Result<(), Self::Error>;
637}
638
639pub(super) trait Counted {
641 fn count(&self) -> u32;
643}
644
645impl<T: Validate> Validate for Option<T> {
646 type Error = <T as Validate>::Error;
647
648 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
649 match self {
650 Some(value) => value.validate(context),
651 None => Ok(()),
652 }
653 }
654}
655
656impl<T: Validate> Validate for Vec<T> {
657 type Error = <T as Validate>::Error;
658
659 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
660 for item in self {
661 item.validate(context)?;
662 }
663 Ok(())
664 }
665}
666
667impl Validate for le::U32 {
668 type Error = anyhow::Error;
669
670 fn validate(&self, _context: &PolicyValidationContext) -> Result<(), Self::Error> {
673 Ok(())
674 }
675}
676
677impl Validate for u8 {
678 type Error = anyhow::Error;
679
680 fn validate(&self, _context: &PolicyValidationContext) -> Result<(), Self::Error> {
683 Ok(())
684 }
685}
686
687impl<B: SplitByteSlice, T: Validate + FromBytes + KnownLayout + Immutable> Validate for Ref<B, T> {
688 type Error = <T as Validate>::Error;
689
690 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
691 self.deref().validate(context)
692 }
693}
694
695impl<B: SplitByteSlice, T: Counted + FromBytes + KnownLayout + Immutable> Counted for Ref<B, T> {
696 fn count(&self) -> u32 {
697 self.deref().count()
698 }
699}
700
701#[derive(Clone, Debug, PartialEq)]
703struct Array<M, T> {
704 metadata: M,
705 data: Vec<T>,
706}
707
708impl<M: Counted + Parse, T: Parse> Parse for Array<M, T> {
709 type Error = anyhow::Error;
712
713 fn parse<'a>(bytes: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error> {
715 let tail = bytes;
716
717 let (metadata, tail) = M::parse(tail).map_err(Into::<anyhow::Error>::into)?;
718
719 let count = metadata.count() as usize;
720 let mut data = Vec::with_capacity(count);
721 let mut cur_tail = tail;
722 for _ in 0..count {
723 let (item, next_tail) = T::parse(cur_tail).map_err(Into::<anyhow::Error>::into)?;
724 data.push(item);
725 cur_tail = next_tail;
726 }
727 let tail = cur_tail;
728
729 let array = Self { metadata, data };
730
731 Ok((array, tail))
732 }
733}
734
735impl<T: Clone + Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned> Parse for T {
736 type Error = anyhow::Error;
737
738 fn parse<'a>(bytes: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error> {
739 bytes.parse::<T>().map_err(anyhow::Error::from)
740 }
741}
742
743macro_rules! array_type {
747 ($type_name:ident, $metadata_type:ty, $data_type:ty, $metadata_type_name:expr, $data_type_name:expr) => {
748 #[doc = "An [`Array`] with [`"]
749 #[doc = $metadata_type_name]
750 #[doc = "`] metadata and [`"]
751 #[doc = $data_type_name]
752 #[doc = "`] data items."]
753 #[derive(Debug, PartialEq)]
754 pub(super) struct $type_name(super::Array<$metadata_type, $data_type>);
755
756 impl std::ops::Deref for $type_name {
757 type Target = super::Array<$metadata_type, $data_type>;
758
759 fn deref(&self) -> &Self::Target {
760 &self.0
761 }
762 }
763
764 impl super::Parse for $type_name
765 where
766 super::Array<$metadata_type, $data_type>: super::Parse,
767 {
768 type Error = <Array<$metadata_type, $data_type> as super::Parse>::Error;
769
770 fn parse<'a>(bytes: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error> {
771 let (array, tail) = Array::<$metadata_type, $data_type>::parse(bytes)?;
772 Ok((Self(array), tail))
773 }
774 }
775 };
776
777 ($type_name:ident, $metadata_type:ty, $data_type:ty) => {
778 array_type!(
779 $type_name,
780 $metadata_type,
781 $data_type,
782 stringify!($metadata_type),
783 stringify!($data_type)
784 );
785 };
786}
787
788pub(super) use array_type;
789
790macro_rules! array_type_validate_deref_both {
791 ($type_name:ident) => {
792 impl Validate for $type_name {
793 type Error = anyhow::Error;
794
795 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
796 let metadata = &self.metadata;
797 metadata.validate(context)?;
798
799 self.data.validate(context).map_err(Into::<anyhow::Error>::into)?;
800
801 Self::validate_array(context, metadata, &self.data)
802 .map_err(Into::<anyhow::Error>::into)
803 }
804 }
805 };
806}
807
808pub(super) use array_type_validate_deref_both;
809
810macro_rules! array_type_validate_deref_data {
811 ($type_name:ident) => {
812 impl Validate for $type_name {
813 type Error = anyhow::Error;
814
815 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
816 let metadata = &self.metadata;
817 metadata.validate(context)?;
818
819 self.data.validate(context).map_err(Into::<anyhow::Error>::into)?;
820
821 Self::validate_array(context, metadata, &self.data)
822 }
823 }
824 };
825}
826
827pub(super) use array_type_validate_deref_data;
828
829macro_rules! array_type_validate_deref_metadata_data_vec {
830 ($type_name:ident) => {
831 impl Validate for $type_name {
832 type Error = anyhow::Error;
833
834 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
835 let metadata = &self.metadata;
836 metadata.validate(context)?;
837
838 self.data.validate(context).map_err(Into::<anyhow::Error>::into)?;
839
840 Self::validate_array(context, metadata, self.data.as_slice())
841 }
842 }
843 };
844}
845
846pub(super) use array_type_validate_deref_metadata_data_vec;
847
848macro_rules! array_type_validate_deref_none_data_vec {
849 ($type_name:ident) => {
850 impl Validate for $type_name {
851 type Error = anyhow::Error;
852
853 fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
854 let metadata = &self.metadata;
855 metadata.validate(context)?;
856
857 self.data.validate(context).map_err(Into::<anyhow::Error>::into)?;
858
859 Self::validate_array(context, metadata, self.data.as_slice())
860 }
861 }
862 };
863}
864
865pub(super) use array_type_validate_deref_none_data_vec;
866
867#[cfg(test)]
868pub(super) mod testing {
869 use super::error::{ParseError, ValidateError};
870
871 pub(super) fn as_parse_error(error: anyhow::Error) -> ParseError {
873 error.downcast::<ParseError>().expect("parse error")
874 }
875
876 pub(super) fn as_validate_error(error: anyhow::Error) -> ValidateError {
878 error.downcast::<ValidateError>().expect("validate error")
879 }
880}
881
882#[cfg(test)]
883pub(super) mod tests {
884 use super::arrays::XpermsBitmap;
885 use super::metadata::HandleUnknown;
886 use super::security_context::SecurityContext;
887 use super::symbols::find_class_by_name;
888 use super::{
889 AccessVector, Policy, TypeId, XpermsAccessDecision, XpermsKind, parse_policy_by_value,
890 };
891 use crate::{FileClass, InitialSid, KernelClass};
892
893 use anyhow::Context as _;
894 use serde::Deserialize;
895 use std::ops::{Deref, Shl};
896 use zerocopy::little_endian as le;
897
898 fn is_explicitly_allowed(
906 policy: &Policy,
907 source_type: TypeId,
908 target_type: TypeId,
909 target_class: &str,
910 permission: &str,
911 ) -> bool {
912 let classes = policy.0.parsed_policy().classes();
913 let class = classes
914 .iter()
915 .find(|class| class.name_bytes() == target_class.as_bytes())
916 .expect("class not found");
917 let class_permissions = policy
918 .find_class_permissions_by_name(target_class)
919 .expect("class permissions not found");
920 let (permission_id, _) = class_permissions
921 .iter()
922 .find(|(_, name)| permission.as_bytes() == name)
923 .expect("permission not found");
924 let permission_bit = AccessVector::from_class_permission_id(*permission_id);
925 let access_decision =
926 policy.0.parsed_policy().compute_explicitly_allowed(source_type, target_type, class);
927 permission_bit == access_decision.allow & permission_bit
928 }
929
930 #[derive(Debug, Deserialize)]
931 struct Expectations {
932 expected_policy_version: u32,
933 expected_handle_unknown: LocalHandleUnknown,
934 }
935
936 #[derive(Debug, Deserialize, PartialEq)]
937 #[serde(rename_all = "snake_case")]
938 enum LocalHandleUnknown {
939 Deny,
940 Reject,
941 Allow,
942 }
943
944 impl PartialEq<HandleUnknown> for LocalHandleUnknown {
945 fn eq(&self, other: &HandleUnknown) -> bool {
946 match self {
947 LocalHandleUnknown::Deny => *other == HandleUnknown::Deny,
948 LocalHandleUnknown::Reject => *other == HandleUnknown::Reject,
949 LocalHandleUnknown::Allow => *other == HandleUnknown::Allow,
950 }
951 }
952 }
953
954 fn xperms_bitmap_from_elements(elements: &[u8]) -> XpermsBitmap {
957 let mut bitmap = [le::U32::ZERO; 8];
958 for element in elements {
959 let block_index = (*element as usize) / 32;
960 let bit_index = ((*element as usize) % 32) as u32;
961 let bitmask = le::U32::new(1).shl(bit_index);
962 bitmap[block_index] = bitmap[block_index] | bitmask;
963 }
964 XpermsBitmap::new(bitmap)
965 }
966
967 #[test]
968 fn known_policies() {
969 let policies_and_expectations = [
970 [
971 b"testdata/policies/emulator".to_vec(),
972 include_bytes!("../../testdata/policies/emulator").to_vec(),
973 include_bytes!("../../testdata/expectations/emulator").to_vec(),
974 ],
975 [
976 b"testdata/policies/selinux_testsuite".to_vec(),
977 include_bytes!("../../testdata/policies/selinux_testsuite").to_vec(),
978 include_bytes!("../../testdata/expectations/selinux_testsuite").to_vec(),
979 ],
980 ];
981
982 for [policy_path, policy_bytes, expectations_bytes] in policies_and_expectations {
983 let expectations = serde_json5::from_reader::<_, Expectations>(
984 &mut std::io::Cursor::new(expectations_bytes),
985 )
986 .expect("deserialize expectations");
987
988 let unvalidated_policy =
991 parse_policy_by_value(policy_bytes.clone()).expect("parse policy");
992
993 let policy = unvalidated_policy
994 .validate()
995 .with_context(|| {
996 format!(
997 "policy path: {:?}",
998 std::str::from_utf8(policy_path.as_slice()).unwrap()
999 )
1000 })
1001 .expect("validate policy");
1002
1003 assert_eq!(expectations.expected_policy_version, policy.policy_version());
1004 assert_eq!(expectations.expected_handle_unknown, policy.handle_unknown());
1005
1006 let binary_policy = policy.binary().clone();
1008 assert_eq!(&policy_bytes, binary_policy.deref());
1009 }
1010 }
1011
1012 #[test]
1013 fn policy_lookup() {
1014 let policy_bytes = include_bytes!("../../testdata/policies/selinux_testsuite");
1015 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1016 let policy = policy.validate().expect("validate selinux testsuite policy");
1017
1018 let unconfined_t = policy.type_id_by_name("unconfined_t").expect("look up type id");
1019
1020 assert!(is_explicitly_allowed(&policy, unconfined_t, unconfined_t, "process", "fork",));
1021 }
1022
1023 #[test]
1024 fn initial_contexts() {
1025 let policy_bytes =
1026 include_bytes!("../../testdata/micro_policies/multiple_levels_and_categories_policy");
1027 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1028 let policy = policy.validate().expect("validate policy");
1029
1030 let kernel_context = policy.initial_context(InitialSid::Kernel);
1031 assert_eq!(
1032 policy.serialize_security_context(&kernel_context),
1033 b"user0:object_r:type0:s0:c0-s1:c0.c2,c4"
1034 )
1035 }
1036
1037 #[test]
1038 fn explicit_allow_type_type() {
1039 let policy_bytes =
1040 include_bytes!("../../testdata/micro_policies/allow_a_t_b_t_class0_perm0_policy");
1041 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1042 let policy = policy.validate().expect("validate policy");
1043
1044 let a_t = policy.type_id_by_name("a_t").expect("look up type id");
1045 let b_t = policy.type_id_by_name("b_t").expect("look up type id");
1046
1047 assert!(is_explicitly_allowed(&policy, a_t, b_t, "class0", "perm0"));
1048 }
1049
1050 #[test]
1051 fn no_explicit_allow_type_type() {
1052 let policy_bytes =
1053 include_bytes!("../../testdata/micro_policies/no_allow_a_t_b_t_class0_perm0_policy");
1054 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1055 let policy = policy.validate().expect("validate policy");
1056
1057 let a_t = policy.type_id_by_name("a_t").expect("look up type id");
1058 let b_t = policy.type_id_by_name("b_t").expect("look up type id");
1059
1060 assert!(!is_explicitly_allowed(&policy, a_t, b_t, "class0", "perm0"));
1061 }
1062
1063 #[test]
1064 fn explicit_allow_type_attr() {
1065 let policy_bytes =
1066 include_bytes!("../../testdata/micro_policies/allow_a_t_b_attr_class0_perm0_policy");
1067 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1068 let policy = policy.validate().expect("validate policy");
1069
1070 let a_t = policy.type_id_by_name("a_t").expect("look up type id");
1071 let b_t = policy.type_id_by_name("b_t").expect("look up type id");
1072
1073 assert!(is_explicitly_allowed(&policy, a_t, b_t, "class0", "perm0"));
1074 }
1075
1076 #[test]
1077 fn no_explicit_allow_type_attr() {
1078 let policy_bytes =
1079 include_bytes!("../../testdata/micro_policies/no_allow_a_t_b_attr_class0_perm0_policy");
1080 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1081 let policy = policy.validate().expect("validate policy");
1082
1083 let a_t = policy.type_id_by_name("a_t").expect("look up type id");
1084 let b_t = policy.type_id_by_name("b_t").expect("look up type id");
1085
1086 assert!(!is_explicitly_allowed(&policy, a_t, b_t, "class0", "perm0"));
1087 }
1088
1089 #[test]
1090 fn explicit_allow_attr_attr() {
1091 let policy_bytes =
1092 include_bytes!("../../testdata/micro_policies/allow_a_attr_b_attr_class0_perm0_policy");
1093 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1094 let policy = policy.validate().expect("validate policy");
1095
1096 let a_t = policy.type_id_by_name("a_t").expect("look up type id");
1097 let b_t = policy.type_id_by_name("b_t").expect("look up type id");
1098
1099 assert!(is_explicitly_allowed(&policy, a_t, b_t, "class0", "perm0"));
1100 }
1101
1102 #[test]
1103 fn no_explicit_allow_attr_attr() {
1104 let policy_bytes = include_bytes!(
1105 "../../testdata/micro_policies/no_allow_a_attr_b_attr_class0_perm0_policy"
1106 );
1107 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1108 let policy = policy.validate().expect("validate policy");
1109
1110 let a_t = policy.type_id_by_name("a_t").expect("look up type id");
1111 let b_t = policy.type_id_by_name("b_t").expect("look up type id");
1112
1113 assert!(!is_explicitly_allowed(&policy, a_t, b_t, "class0", "perm0"));
1114 }
1115
1116 #[test]
1117 fn compute_explicitly_allowed_multiple_attributes() {
1118 let policy_bytes = include_bytes!(
1119 "../../testdata/micro_policies/allow_a_t_a1_attr_class0_perm0_a2_attr_class0_perm1_policy"
1120 );
1121 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1122 let policy = policy.validate().expect("validate policy");
1123
1124 let a_t = policy.type_id_by_name("a_t").expect("look up type id");
1125
1126 let classes = policy.0.parsed_policy().classes();
1127 let class =
1128 classes.iter().find(|class| class.name_bytes() == b"class0").expect("class not found");
1129 let raw_access_vector =
1130 policy.0.parsed_policy().compute_explicitly_allowed(a_t, a_t, class).allow.0;
1131
1132 assert_eq!(2, raw_access_vector.count_ones());
1137 }
1138
1139 #[test]
1140 fn compute_access_decision_with_constraints() {
1141 let policy_bytes =
1142 include_bytes!("../../testdata/micro_policies/allow_with_constraints_policy");
1143 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1144 let policy = policy.validate().expect("validate policy");
1145
1146 let source_context: SecurityContext = policy
1147 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1148 .expect("create source security context");
1149
1150 let target_context_satisfied: SecurityContext = source_context.clone();
1151 let decision_satisfied = policy.compute_access_decision(
1152 &source_context,
1153 &target_context_satisfied,
1154 KernelClass::File,
1155 );
1156 assert_eq!(decision_satisfied.allow, AccessVector(7));
1160
1161 let target_context_unsatisfied: SecurityContext = policy
1162 .parse_security_context(b"user1:object_r:type0:s0:c0-s0:c0".into())
1163 .expect("create target security context failing some constraints");
1164 let decision_unsatisfied = policy.compute_access_decision(
1165 &source_context,
1166 &target_context_unsatisfied,
1167 KernelClass::File,
1168 );
1169 assert_eq!(decision_unsatisfied.allow, AccessVector(4));
1172 }
1173
1174 #[test]
1175 fn compute_ioctl_access_decision_explicitly_allowed() {
1176 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1177 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1178 let policy = policy.validate().expect("validate policy");
1179
1180 let source_context: SecurityContext = policy
1181 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1182 .expect("create source security context");
1183 let target_context_matched: SecurityContext = source_context.clone();
1184
1185 let decision_single = policy.compute_xperms_access_decision(
1203 XpermsKind::Ioctl,
1204 &source_context,
1205 &target_context_matched,
1206 KernelClass::File,
1207 0xab,
1208 );
1209
1210 let mut expected_auditdeny =
1211 xperms_bitmap_from_elements((0x0..=0xff).collect::<Vec<_>>().as_slice());
1212 expected_auditdeny -= &xperms_bitmap_from_elements(&[0xcd, 0xef]);
1213
1214 let expected_decision_single = XpermsAccessDecision {
1215 allow: xperms_bitmap_from_elements(&[0xcd, 0xef]),
1216 auditallow: xperms_bitmap_from_elements(&[0xcd, 0xef]),
1217 auditdeny: expected_auditdeny,
1218 };
1219 assert_eq!(decision_single, expected_decision_single);
1220
1221 let decision_range = policy.compute_xperms_access_decision(
1222 XpermsKind::Ioctl,
1223 &source_context,
1224 &target_context_matched,
1225 KernelClass::File,
1226 0x10,
1227 );
1228 let expected_decision_range = XpermsAccessDecision {
1229 allow: XpermsBitmap::ALL,
1230 auditallow: XpermsBitmap::ALL,
1231 auditdeny: XpermsBitmap::NONE,
1232 };
1233 assert_eq!(decision_range, expected_decision_range);
1234 }
1235
1236 #[test]
1237 fn compute_ioctl_access_decision_denied() {
1238 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1239 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1240 let class_id = find_class_by_name(&unvalidated.0.classes(), "class_one_ioctl")
1241 .expect("look up class_one_ioctl")
1242 .id();
1243 let policy = unvalidated.validate().expect("validate policy");
1244 let source_context: SecurityContext = policy
1245 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1246 .expect("create source security context");
1247 let target_context_matched: SecurityContext = source_context.clone();
1248
1249 let decision_single = policy.compute_xperms_access_decision(
1253 XpermsKind::Ioctl,
1254 &source_context,
1255 &target_context_matched,
1256 class_id,
1257 0xdb,
1258 );
1259
1260 let expected_decision = XpermsAccessDecision {
1261 allow: XpermsBitmap::NONE,
1262 auditallow: XpermsBitmap::NONE,
1263 auditdeny: XpermsBitmap::ALL,
1264 };
1265 assert_eq!(decision_single, expected_decision);
1266 }
1267
1268 #[test]
1269 fn compute_ioctl_access_decision_unmatched() {
1270 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1271 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1272 let policy = policy.validate().expect("validate policy");
1273
1274 let source_context: SecurityContext = policy
1275 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1276 .expect("create source security context");
1277
1278 let target_context_unmatched: SecurityContext = policy
1280 .parse_security_context(b"user0:object_r:type1:s0-s0".into())
1281 .expect("create source security context");
1282
1283 for prefix in 0x0..=0xff {
1284 let decision = policy.compute_xperms_access_decision(
1285 XpermsKind::Ioctl,
1286 &source_context,
1287 &target_context_unmatched,
1288 KernelClass::File,
1289 prefix,
1290 );
1291 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1292 }
1293 }
1294
1295 #[test]
1296 fn compute_ioctl_earlier_redundant_prefixful_not_coalesced_into_prefixless() {
1297 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1298 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1299 let class_id = find_class_by_name(
1300 &unvalidated.0.classes(),
1301 "class_earlier_redundant_prefixful_not_coalesced_into_prefixless",
1302 )
1303 .expect("look up class_earlier_redundant_prefixful_not_coalesced_into_prefixless")
1304 .id();
1305 let policy = unvalidated.validate().expect("validate policy");
1306 let source_context: SecurityContext = policy
1307 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1308 .expect("create source security context");
1309 let target_context_matched: SecurityContext = source_context.clone();
1310
1311 let decision = policy.compute_xperms_access_decision(
1316 XpermsKind::Ioctl,
1317 &source_context,
1318 &target_context_matched,
1319 class_id,
1320 0x7f,
1321 );
1322 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1323 let decision = policy.compute_xperms_access_decision(
1324 XpermsKind::Ioctl,
1325 &source_context,
1326 &target_context_matched,
1327 class_id,
1328 0x80,
1329 );
1330 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1331 let decision = policy.compute_xperms_access_decision(
1332 XpermsKind::Ioctl,
1333 &source_context,
1334 &target_context_matched,
1335 class_id,
1336 0x81,
1337 );
1338 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1339 }
1340
1341 #[test]
1342 fn compute_ioctl_later_redundant_prefixful_not_coalesced_into_prefixless() {
1343 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1344 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1345 let class_id = find_class_by_name(
1346 &unvalidated.0.classes(),
1347 "class_later_redundant_prefixful_not_coalesced_into_prefixless",
1348 )
1349 .expect("look up class_later_redundant_prefixful_not_coalesced_into_prefixless")
1350 .id();
1351 let policy = unvalidated.validate().expect("validate policy");
1352 let source_context: SecurityContext = policy
1353 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1354 .expect("create source security context");
1355 let target_context_matched: SecurityContext = source_context.clone();
1356
1357 let decision = policy.compute_xperms_access_decision(
1362 XpermsKind::Ioctl,
1363 &source_context,
1364 &target_context_matched,
1365 class_id,
1366 0x8f,
1367 );
1368 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1369 let decision = policy.compute_xperms_access_decision(
1370 XpermsKind::Ioctl,
1371 &source_context,
1372 &target_context_matched,
1373 class_id,
1374 0x90,
1375 );
1376 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1377 let decision = policy.compute_xperms_access_decision(
1378 XpermsKind::Ioctl,
1379 &source_context,
1380 &target_context_matched,
1381 class_id,
1382 0x91,
1383 );
1384 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1385 }
1386
1387 #[test]
1388 fn compute_ioctl_earlier_and_later_redundant_prefixful_not_coalesced_into_prefixless() {
1389 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1390 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1391 let class_id = find_class_by_name(
1392 &unvalidated.0.classes(),
1393 "class_earlier_and_later_redundant_prefixful_not_coalesced_into_prefixless",
1394 )
1395 .expect("look up class_earlier_and_later_redundant_prefixful_not_coalesced_into_prefixless")
1396 .id();
1397 let policy = unvalidated.validate().expect("validate policy");
1398 let source_context: SecurityContext = policy
1399 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1400 .expect("create source security context");
1401 let target_context_matched: SecurityContext = source_context.clone();
1402
1403 let decision = policy.compute_xperms_access_decision(
1409 XpermsKind::Ioctl,
1410 &source_context,
1411 &target_context_matched,
1412 class_id,
1413 0x9f,
1414 );
1415 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1416 let decision = policy.compute_xperms_access_decision(
1417 XpermsKind::Ioctl,
1418 &source_context,
1419 &target_context_matched,
1420 class_id,
1421 0xa0,
1422 );
1423 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1424 let decision = policy.compute_xperms_access_decision(
1425 XpermsKind::Ioctl,
1426 &source_context,
1427 &target_context_matched,
1428 class_id,
1429 0xa1,
1430 );
1431 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1432 }
1433
1434 #[test]
1435 fn compute_ioctl_prefixfuls_that_coalesce_to_prefixless() {
1436 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1437 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1438 let class_id = find_class_by_name(
1439 &unvalidated.0.classes(),
1440 "class_prefixfuls_that_coalesce_to_prefixless",
1441 )
1442 .expect("look up class_prefixfuls_that_coalesce_to_prefixless")
1443 .id();
1444 let policy = unvalidated.validate().expect("validate policy");
1445 let source_context: SecurityContext = policy
1446 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1447 .expect("create source security context");
1448 let target_context_matched: SecurityContext = source_context.clone();
1449
1450 let decision = policy.compute_xperms_access_decision(
1456 XpermsKind::Ioctl,
1457 &source_context,
1458 &target_context_matched,
1459 class_id,
1460 0xaf,
1461 );
1462 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1463 let decision = policy.compute_xperms_access_decision(
1464 XpermsKind::Ioctl,
1465 &source_context,
1466 &target_context_matched,
1467 class_id,
1468 0xb0,
1469 );
1470 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1471 let decision = policy.compute_xperms_access_decision(
1472 XpermsKind::Ioctl,
1473 &source_context,
1474 &target_context_matched,
1475 class_id,
1476 0xb1,
1477 );
1478 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1479 }
1480
1481 #[test]
1482 fn compute_ioctl_prefixfuls_that_coalesce_to_prefixless_just_before_prefixless() {
1483 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1484 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1485 let class_id = find_class_by_name(
1486 &unvalidated.0.classes(),
1487 "class_prefixfuls_that_coalesce_to_prefixless_just_before_prefixless",
1488 )
1489 .expect("look up class_prefixfuls_that_coalesce_to_prefixless_just_before_prefixless")
1490 .id();
1491 let policy = unvalidated.validate().expect("validate policy");
1492 let source_context: SecurityContext = policy
1493 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1494 .expect("create source security context");
1495 let target_context_matched: SecurityContext = source_context.clone();
1496
1497 let decision = policy.compute_xperms_access_decision(
1504 XpermsKind::Ioctl,
1505 &source_context,
1506 &target_context_matched,
1507 class_id,
1508 0xbf,
1509 );
1510 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1511 let decision = policy.compute_xperms_access_decision(
1512 XpermsKind::Ioctl,
1513 &source_context,
1514 &target_context_matched,
1515 class_id,
1516 0xc0,
1517 );
1518 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1519 let decision = policy.compute_xperms_access_decision(
1520 XpermsKind::Ioctl,
1521 &source_context,
1522 &target_context_matched,
1523 class_id,
1524 0xc1,
1525 );
1526 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1527 let decision = policy.compute_xperms_access_decision(
1528 XpermsKind::Ioctl,
1529 &source_context,
1530 &target_context_matched,
1531 class_id,
1532 0xc2,
1533 );
1534 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1535 }
1536
1537 #[test]
1538 fn compute_ioctl_prefixless_just_before_prefixfuls_that_coalesce_to_prefixless() {
1539 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1540 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1541 let class_id = find_class_by_name(
1542 &unvalidated.0.classes(),
1543 "class_prefixless_just_before_prefixfuls_that_coalesce_to_prefixless",
1544 )
1545 .expect("look up class_prefixless_just_before_prefixfuls_that_coalesce_to_prefixless")
1546 .id();
1547 let policy = unvalidated.validate().expect("validate policy");
1548 let source_context: SecurityContext = policy
1549 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1550 .expect("create source security context");
1551 let target_context_matched: SecurityContext = source_context.clone();
1552
1553 let decision = policy.compute_xperms_access_decision(
1560 XpermsKind::Ioctl,
1561 &source_context,
1562 &target_context_matched,
1563 class_id,
1564 0xd5,
1565 );
1566 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1567 let decision = policy.compute_xperms_access_decision(
1568 XpermsKind::Ioctl,
1569 &source_context,
1570 &target_context_matched,
1571 class_id,
1572 0xd6,
1573 );
1574 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1575 let decision = policy.compute_xperms_access_decision(
1576 XpermsKind::Ioctl,
1577 &source_context,
1578 &target_context_matched,
1579 class_id,
1580 0xd7,
1581 );
1582 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1583 let decision = policy.compute_xperms_access_decision(
1584 XpermsKind::Ioctl,
1585 &source_context,
1586 &target_context_matched,
1587 class_id,
1588 0xd8,
1589 );
1590 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1591 }
1592
1593 #[test]
1604 fn compute_ioctl_ridiculous_permission_ordering() {
1605 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1606 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1607 let class_id =
1608 find_class_by_name(&unvalidated.0.classes(), "class_ridiculous_permission_ordering")
1609 .expect("look up class_ridiculous_permission_ordering")
1610 .id();
1611 let policy = unvalidated.validate().expect("validate policy");
1612 let source_context: SecurityContext = policy
1613 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1614 .expect("create source security context");
1615 let target_context_matched: SecurityContext = source_context.clone();
1616
1617 let decision = policy.compute_xperms_access_decision(
1622 XpermsKind::Ioctl,
1623 &source_context,
1624 &target_context_matched,
1625 class_id,
1626 0x00,
1627 );
1628 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1629 let decision = policy.compute_xperms_access_decision(
1630 XpermsKind::Ioctl,
1631 &source_context,
1632 &target_context_matched,
1633 class_id,
1634 0x01,
1635 );
1636 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1637 let decision = policy.compute_xperms_access_decision(
1638 XpermsKind::Ioctl,
1639 &source_context,
1640 &target_context_matched,
1641 class_id,
1642 0xbf,
1643 );
1644 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1645 let decision = policy.compute_xperms_access_decision(
1646 XpermsKind::Ioctl,
1647 &source_context,
1648 &target_context_matched,
1649 class_id,
1650 0xc0,
1651 );
1652 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1653 let decision = policy.compute_xperms_access_decision(
1654 XpermsKind::Ioctl,
1655 &source_context,
1656 &target_context_matched,
1657 class_id,
1658 0xce,
1659 );
1660 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1661 let decision = policy.compute_xperms_access_decision(
1662 XpermsKind::Ioctl,
1663 &source_context,
1664 &target_context_matched,
1665 class_id,
1666 0xcf,
1667 );
1668 assert_eq!(
1669 decision,
1670 XpermsAccessDecision {
1671 allow: xperms_bitmap_from_elements((0x0..=0xf2).collect::<Vec<_>>().as_slice()),
1672 auditallow: XpermsBitmap::NONE,
1673 auditdeny: XpermsBitmap::ALL,
1674 }
1675 );
1676 let decision = policy.compute_xperms_access_decision(
1677 XpermsKind::Ioctl,
1678 &source_context,
1679 &target_context_matched,
1680 class_id,
1681 0xd0,
1682 );
1683 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1684 let decision = policy.compute_xperms_access_decision(
1685 XpermsKind::Ioctl,
1686 &source_context,
1687 &target_context_matched,
1688 class_id,
1689 0xe9,
1690 );
1691 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1692 let decision = policy.compute_xperms_access_decision(
1693 XpermsKind::Ioctl,
1694 &source_context,
1695 &target_context_matched,
1696 class_id,
1697 0xf0,
1698 );
1699 assert_eq!(
1700 decision,
1701 XpermsAccessDecision {
1702 allow: xperms_bitmap_from_elements(&[0x01]),
1703 auditallow: XpermsBitmap::NONE,
1704 auditdeny: XpermsBitmap::ALL,
1705 }
1706 );
1707 let decision = policy.compute_xperms_access_decision(
1708 XpermsKind::Ioctl,
1709 &source_context,
1710 &target_context_matched,
1711 class_id,
1712 0xf1,
1713 );
1714 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1715 let decision = policy.compute_xperms_access_decision(
1716 XpermsKind::Ioctl,
1717 &source_context,
1718 &target_context_matched,
1719 class_id,
1720 0xfc,
1721 );
1722 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1723 let decision = policy.compute_xperms_access_decision(
1724 XpermsKind::Ioctl,
1725 &source_context,
1726 &target_context_matched,
1727 class_id,
1728 0xfd,
1729 );
1730 assert_eq!(
1731 decision,
1732 XpermsAccessDecision {
1733 allow: xperms_bitmap_from_elements((0xfa..=0xfd).collect::<Vec<_>>().as_slice()),
1734 auditallow: XpermsBitmap::NONE,
1735 auditdeny: XpermsBitmap::ALL,
1736 }
1737 );
1738 let decision = policy.compute_xperms_access_decision(
1739 XpermsKind::Ioctl,
1740 &source_context,
1741 &target_context_matched,
1742 class_id,
1743 0xfe,
1744 );
1745 assert_eq!(decision, XpermsAccessDecision::DENY_ALL);
1746 }
1747
1748 #[test]
1749 fn compute_nlmsg_access_decision_explicitly_allowed() {
1750 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1751 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1752 let policy = policy.validate().expect("validate policy");
1753
1754 let source_context: SecurityContext = policy
1755 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1756 .expect("create source security context");
1757 let target_context_matched: SecurityContext = source_context.clone();
1758
1759 let decision_single = policy.compute_xperms_access_decision(
1777 XpermsKind::Nlmsg,
1778 &source_context,
1779 &target_context_matched,
1780 KernelClass::NetlinkRouteSocket,
1781 0xab,
1782 );
1783
1784 let mut expected_auditdeny =
1785 xperms_bitmap_from_elements((0x0..=0xff).collect::<Vec<_>>().as_slice());
1786 expected_auditdeny -= &xperms_bitmap_from_elements(&[0xcd, 0xef]);
1787
1788 let expected_decision_single = XpermsAccessDecision {
1789 allow: xperms_bitmap_from_elements(&[0xcd, 0xef]),
1790 auditallow: xperms_bitmap_from_elements(&[0xcd, 0xef]),
1791 auditdeny: expected_auditdeny,
1792 };
1793 assert_eq!(decision_single, expected_decision_single);
1794
1795 let decision_range = policy.compute_xperms_access_decision(
1796 XpermsKind::Nlmsg,
1797 &source_context,
1798 &target_context_matched,
1799 KernelClass::NetlinkRouteSocket,
1800 0x10,
1801 );
1802 let expected_decision_range = XpermsAccessDecision {
1803 allow: XpermsBitmap::ALL,
1804 auditallow: XpermsBitmap::ALL,
1805 auditdeny: XpermsBitmap::NONE,
1806 };
1807 assert_eq!(decision_range, expected_decision_range);
1808 }
1809
1810 #[test]
1811 fn compute_nlmsg_access_decision_unmatched() {
1812 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1813 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1814 let policy = policy.validate().expect("validate policy");
1815
1816 let source_context: SecurityContext = policy
1817 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1818 .expect("create source security context");
1819
1820 let target_context_unmatched: SecurityContext = policy
1822 .parse_security_context(b"user0:object_r:type1:s0-s0".into())
1823 .expect("create source security context");
1824
1825 for prefix in 0x0..=0xff {
1826 let decision = policy.compute_xperms_access_decision(
1827 XpermsKind::Nlmsg,
1828 &source_context,
1829 &target_context_unmatched,
1830 KernelClass::NetlinkRouteSocket,
1831 prefix,
1832 );
1833 assert_eq!(decision, XpermsAccessDecision::ALLOW_ALL);
1834 }
1835 }
1836
1837 #[test]
1838 fn compute_ioctl_grant_does_not_cause_nlmsg_deny() {
1839 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1840 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1841 let class_id = find_class_by_name(
1842 &unvalidated.0.classes(),
1843 "class_ioctl_grant_does_not_cause_nlmsg_deny",
1844 )
1845 .expect("look up class_ioctl_grant_does_not_cause_nlmsg_deny")
1846 .id();
1847 let policy = unvalidated.validate().expect("validate policy");
1848 let source_context: SecurityContext = policy
1849 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1850 .expect("create source security context");
1851 let target_context_matched: SecurityContext = source_context.clone();
1852
1853 let ioctl_decision = policy.compute_xperms_access_decision(
1857 XpermsKind::Ioctl,
1858 &source_context,
1859 &target_context_matched,
1860 class_id,
1861 0x00,
1862 );
1863 assert_eq!(
1864 ioctl_decision,
1865 XpermsAccessDecision {
1866 allow: xperms_bitmap_from_elements(&[0x0002]),
1867 auditallow: XpermsBitmap::NONE,
1868 auditdeny: XpermsBitmap::ALL,
1869 }
1870 );
1871 let nlmsg_decision = policy.compute_xperms_access_decision(
1872 XpermsKind::Nlmsg,
1873 &source_context,
1874 &target_context_matched,
1875 class_id,
1876 0x00,
1877 );
1878 assert_eq!(nlmsg_decision, XpermsAccessDecision::ALLOW_ALL);
1879 }
1880
1881 #[test]
1882 fn compute_nlmsg_grant_does_not_cause_ioctl_deny() {
1883 let policy_bytes = include_bytes!("../../testdata/micro_policies/allowxperm_policy");
1884 let unvalidated = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1885 let class_id = find_class_by_name(
1886 &unvalidated.0.classes(),
1887 "class_nlmsg_grant_does_not_cause_ioctl_deny",
1888 )
1889 .expect("look up class_nlmsg_grant_does_not_cause_ioctl_deny")
1890 .id();
1891 let policy = unvalidated.validate().expect("validate policy");
1892 let source_context: SecurityContext = policy
1893 .parse_security_context(b"user0:object_r:type0:s0-s0".into())
1894 .expect("create source security context");
1895 let target_context_matched: SecurityContext = source_context.clone();
1896
1897 let nlmsg_decision = policy.compute_xperms_access_decision(
1901 XpermsKind::Nlmsg,
1902 &source_context,
1903 &target_context_matched,
1904 class_id,
1905 0x00,
1906 );
1907 assert_eq!(
1908 nlmsg_decision,
1909 XpermsAccessDecision {
1910 allow: xperms_bitmap_from_elements(&[0x0003]),
1911 auditallow: XpermsBitmap::NONE,
1912 auditdeny: XpermsBitmap::ALL,
1913 }
1914 );
1915 let ioctl_decision = policy.compute_xperms_access_decision(
1916 XpermsKind::Ioctl,
1917 &source_context,
1918 &target_context_matched,
1919 class_id,
1920 0x00,
1921 );
1922 assert_eq!(ioctl_decision, XpermsAccessDecision::ALLOW_ALL);
1923 }
1924
1925 #[test]
1926 fn compute_create_context_minimal() {
1927 let policy_bytes =
1928 include_bytes!("../../testdata/composite_policies/compiled/minimal_policy");
1929 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1930 let policy = policy.validate().expect("validate policy");
1931 let source = policy
1932 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
1933 .expect("valid source security context");
1934 let target = policy
1935 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
1936 .expect("valid target security context");
1937
1938 let actual = policy.compute_create_context(&source, &target, FileClass::File);
1939 let expected: SecurityContext = policy
1940 .parse_security_context(b"source_u:object_r:target_t:s0:c0".into())
1941 .expect("valid expected security context");
1942
1943 assert_eq!(expected, actual);
1944 }
1945
1946 #[test]
1947 fn new_security_context_minimal() {
1948 let policy_bytes =
1949 include_bytes!("../../testdata/composite_policies/compiled/minimal_policy");
1950 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1951 let policy = policy.validate().expect("validate policy");
1952 let source = policy
1953 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
1954 .expect("valid source security context");
1955 let target = policy
1956 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
1957 .expect("valid target security context");
1958
1959 let actual = policy.compute_create_context(&source, &target, KernelClass::Process);
1960
1961 assert_eq!(source, actual);
1962 }
1963
1964 #[test]
1965 fn compute_create_context_class_defaults() {
1966 let policy_bytes =
1967 include_bytes!("../../testdata/composite_policies/compiled/class_defaults_policy");
1968 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1969 let policy = policy.validate().expect("validate policy");
1970 let source = policy
1971 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
1972 .expect("valid source security context");
1973 let target = policy
1974 .parse_security_context(b"target_u:target_r:target_t:s1:c0-s1:c0.c1".into())
1975 .expect("valid target security context");
1976
1977 let actual = policy.compute_create_context(&source, &target, FileClass::File);
1978 let expected: SecurityContext = policy
1979 .parse_security_context(b"target_u:source_r:source_t:s1:c0-s1:c0.c1".into())
1980 .expect("valid expected security context");
1981
1982 assert_eq!(expected, actual);
1983 }
1984
1985 #[test]
1986 fn new_security_context_class_defaults() {
1987 let policy_bytes =
1988 include_bytes!("../../testdata/composite_policies/compiled/class_defaults_policy");
1989 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
1990 let policy = policy.validate().expect("validate policy");
1991 let source = policy
1992 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
1993 .expect("valid source security context");
1994 let target = policy
1995 .parse_security_context(b"target_u:target_r:target_t:s1:c0-s1:c0.c1".into())
1996 .expect("valid target security context");
1997
1998 let actual = policy.compute_create_context(&source, &target, KernelClass::Process);
1999 let expected: SecurityContext = policy
2000 .parse_security_context(b"target_u:source_r:source_t:s1:c0-s1:c0.c1".into())
2001 .expect("valid expected security context");
2002
2003 assert_eq!(expected, actual);
2004 }
2005
2006 #[test]
2007 fn compute_create_context_role_transition() {
2008 let policy_bytes =
2009 include_bytes!("../../testdata/composite_policies/compiled/role_transition_policy");
2010 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2011 let policy = policy.validate().expect("validate policy");
2012 let source = policy
2013 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
2014 .expect("valid source security context");
2015 let target = policy
2016 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
2017 .expect("valid target security context");
2018
2019 let actual = policy.compute_create_context(&source, &target, FileClass::File);
2020 let expected: SecurityContext = policy
2021 .parse_security_context(b"source_u:transition_r:target_t:s0:c0".into())
2022 .expect("valid expected security context");
2023
2024 assert_eq!(expected, actual);
2025 }
2026
2027 #[test]
2028 fn new_security_context_role_transition() {
2029 let policy_bytes =
2030 include_bytes!("../../testdata/composite_policies/compiled/role_transition_policy");
2031 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2032 let policy = policy.validate().expect("validate policy");
2033 let source = policy
2034 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
2035 .expect("valid source security context");
2036 let target = policy
2037 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
2038 .expect("valid target security context");
2039
2040 let actual = policy.compute_create_context(&source, &target, KernelClass::Process);
2041 let expected: SecurityContext = policy
2042 .parse_security_context(b"source_u:transition_r:source_t:s0:c0-s2:c0.c1".into())
2043 .expect("valid expected security context");
2044
2045 assert_eq!(expected, actual);
2046 }
2047
2048 #[test]
2049 #[ignore]
2051 fn compute_create_context_role_transition_not_allowed() {
2052 let policy_bytes = include_bytes!(
2053 "../../testdata/composite_policies/compiled/role_transition_not_allowed_policy"
2054 );
2055 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2056 let policy = policy.validate().expect("validate policy");
2057 let source = policy
2058 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
2059 .expect("valid source security context");
2060 let target = policy
2061 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
2062 .expect("valid target security context");
2063
2064 let actual = policy.compute_create_context(&source, &target, FileClass::File);
2065
2066 assert!(policy.validate_security_context(&actual).is_err());
2068 }
2069
2070 #[test]
2071 fn compute_create_context_type_transition() {
2072 let policy_bytes =
2073 include_bytes!("../../testdata/composite_policies/compiled/type_transition_policy");
2074 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2075 let policy = policy.validate().expect("validate policy");
2076 let source = policy
2077 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
2078 .expect("valid source security context");
2079 let target = policy
2080 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
2081 .expect("valid target security context");
2082
2083 let actual = policy.compute_create_context(&source, &target, FileClass::File);
2084 let expected: SecurityContext = policy
2085 .parse_security_context(b"source_u:object_r:transition_t:s0:c0".into())
2086 .expect("valid expected security context");
2087
2088 assert_eq!(expected, actual);
2089 }
2090
2091 #[test]
2092 fn new_security_context_type_transition() {
2093 let policy_bytes =
2094 include_bytes!("../../testdata/composite_policies/compiled/type_transition_policy");
2095 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2096 let policy = policy.validate().expect("validate policy");
2097 let source = policy
2098 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
2099 .expect("valid source security context");
2100 let target = policy
2101 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
2102 .expect("valid target security context");
2103
2104 let actual = policy.compute_create_context(&source, &target, KernelClass::Process);
2105 let expected: SecurityContext = policy
2106 .parse_security_context(b"source_u:source_r:transition_t:s0:c0-s2:c0.c1".into())
2107 .expect("valid expected security context");
2108
2109 assert_eq!(expected, actual);
2110 }
2111
2112 #[test]
2113 fn compute_create_context_range_transition() {
2114 let policy_bytes =
2115 include_bytes!("../../testdata/composite_policies/compiled/range_transition_policy");
2116 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2117 let policy = policy.validate().expect("validate policy");
2118 let source = policy
2119 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
2120 .expect("valid source security context");
2121 let target = policy
2122 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
2123 .expect("valid target security context");
2124
2125 let actual = policy.compute_create_context(&source, &target, FileClass::File);
2126 let expected: SecurityContext = policy
2127 .parse_security_context(b"source_u:object_r:target_t:s1:c1-s2:c1.c2".into())
2128 .expect("valid expected security context");
2129
2130 assert_eq!(expected, actual);
2131 }
2132
2133 #[test]
2134 fn new_security_context_range_transition() {
2135 let policy_bytes =
2136 include_bytes!("../../testdata/composite_policies/compiled/range_transition_policy");
2137 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2138 let policy = policy.validate().expect("validate policy");
2139 let source = policy
2140 .parse_security_context(b"source_u:source_r:source_t:s0:c0-s2:c0.c1".into())
2141 .expect("valid source security context");
2142 let target = policy
2143 .parse_security_context(b"target_u:target_r:target_t:s1:c1".into())
2144 .expect("valid target security context");
2145
2146 let actual = policy.compute_create_context(&source, &target, KernelClass::Process);
2147 let expected: SecurityContext = policy
2148 .parse_security_context(b"source_u:source_r:source_t:s1:c1-s2:c1.c2".into())
2149 .expect("valid expected security context");
2150
2151 assert_eq!(expected, actual);
2152 }
2153
2154 #[test]
2155 fn access_vector_formats() {
2156 assert_eq!(format!("{:x}", AccessVector::NONE), "0");
2157 assert_eq!(format!("{:x}", AccessVector::ALL), "ffffffff");
2158 assert_eq!(format!("{:?}", AccessVector::NONE), "AccessVector(00000000)");
2159 assert_eq!(format!("{:?}", AccessVector::ALL), "AccessVector(ffffffff)");
2160 }
2161
2162 #[test]
2163 fn policy_genfscon_root_path() {
2164 let policy_bytes =
2165 include_bytes!("../../testdata/composite_policies/compiled/genfscon_policy");
2166 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2167 let policy = policy.validate().expect("validate selinux policy");
2168
2169 {
2170 let context = policy.genfscon_label_for_fs_and_path(
2171 "fs_with_path_rules".into(),
2172 "/".into(),
2173 None,
2174 );
2175 assert_eq!(
2176 policy.serialize_security_context(&context.unwrap()),
2177 b"system_u:object_r:fs_with_path_rules_t:s0"
2178 )
2179 }
2180 {
2181 let context = policy.genfscon_label_for_fs_and_path(
2182 "fs_2_with_path_rules".into(),
2183 "/".into(),
2184 None,
2185 );
2186 assert_eq!(
2187 policy.serialize_security_context(&context.unwrap()),
2188 b"system_u:object_r:fs_2_with_path_rules_t:s0"
2189 )
2190 }
2191 }
2192
2193 #[test]
2194 fn policy_genfscon_subpaths() {
2195 let policy_bytes =
2196 include_bytes!("../../testdata/composite_policies/compiled/genfscon_policy");
2197 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2198 let policy = policy.validate().expect("validate selinux policy");
2199
2200 let path_label_expectations = [
2201 ("/a1/", "system_u:object_r:fs_with_path_rules_a1_t:s0"),
2205 ("/a1/b", "system_u:object_r:fs_with_path_rules_a1_t:s0"),
2206 ("/a1/b/c", "system_u:object_r:fs_with_path_rules_a1_b_c_t:s0"),
2207 ("/a2/", "system_u:object_r:fs_with_path_rules_t:s0"),
2210 ("/a2/b/c/d", "system_u:object_r:fs_with_path_rules_a2_b_t:s0"),
2211 ("/a3/b/c/d", "system_u:object_r:fs_with_path_rules_a3_t:s0"),
2214 ];
2215 for (path, expected_label) in path_label_expectations {
2216 let context = policy.genfscon_label_for_fs_and_path(
2217 "fs_with_path_rules".into(),
2218 path.into(),
2219 None,
2220 );
2221 assert_eq!(
2222 policy.serialize_security_context(&context.unwrap()),
2223 expected_label.as_bytes()
2224 )
2225 }
2226 }
2227
2228 #[test]
2229 fn policy_genfscon_mixed_order() {
2230 let policy_bytes =
2231 include_bytes!("../../testdata/composite_policies/compiled/genfscon_policy");
2232 let policy = parse_policy_by_value(policy_bytes.to_vec()).expect("parse policy");
2233 let policy = policy.validate().expect("validate selinux policy");
2234
2235 let path_label_expectations = [
2236 ("/", "system_u:object_r:fs_mixed_order_t:s0"),
2237 ("/a", "system_u:object_r:fs_mixed_order_a_t:s0"),
2238 ("/a/a", "system_u:object_r:fs_mixed_order_a_a_t:s0"),
2239 ("/a/b", "system_u:object_r:fs_mixed_order_a_b_t:s0"),
2240 ("/a/b/c", "system_u:object_r:fs_mixed_order_a_b_t:s0"),
2241 ];
2242 for (path, expected_label) in path_label_expectations {
2243 let context =
2244 policy.genfscon_label_for_fs_and_path("fs_mixed_order".into(), path.into(), None);
2245 assert_eq!(
2246 policy.serialize_security_context(&context.unwrap()),
2247 expected_label.as_bytes()
2248 );
2249 }
2250 }
2251}