selinux/policy/
parsed_policy.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::policy::arrays::{
6    ACCESS_VECTOR_RULE_TYPE_ALLOW, ACCESS_VECTOR_RULE_TYPE_AUDITALLOW,
7    ACCESS_VECTOR_RULE_TYPE_DONTAUDIT, AccessVectorRuleMetadata, ExtendedPermissions,
8    XPERMS_TYPE_NLMSG,
9};
10use crate::{NullessByteStr, PolicyCap};
11
12use super::arrays::{
13    AccessVectorRule, ConditionalNodes, Context, DeprecatedFilenameTransitions,
14    FilenameTransitionList, FilenameTransitions, FsUses, GenericFsContexts, IPv6Nodes,
15    InfinitiBandEndPorts, InfinitiBandPartitionKeys, InitialSids,
16    MIN_POLICY_VERSION_FOR_INFINITIBAND_PARTITION_KEY, NamedContextPairs, Nodes, Ports,
17    RangeTransitions, RoleAllow, RoleAllows, RoleTransition, RoleTransitions, SimpleArray,
18    XPERMS_TYPE_IOCTL_PREFIX_AND_POSTFIXES, XPERMS_TYPE_IOCTL_PREFIXES,
19};
20use super::error::{ParseError, ValidateError};
21use super::extensible_bitmap::ExtensibleBitmap;
22use super::metadata::{Config, Counts, HandleUnknown, Magic, PolicyVersion, Signature};
23use super::parser::{PolicyCursor, PolicyData};
24use super::security_context::{Level, SecurityContext};
25use super::symbols::{
26    Category, Class, Classes, CommonSymbol, CommonSymbols, ConditionalBoolean, MlsLevel, Role,
27    Sensitivity, SymbolList, Type, User,
28};
29use super::view::{HashedArrayView, View};
30use super::{
31    AccessDecision, AccessVector, CategoryId, ClassId, Parse, PolicyValidationContext, RoleId,
32    SELINUX_AVD_FLAGS_PERMISSIVE, SensitivityId, TypeId, UserId, Validate, XpermsAccessDecision,
33    XpermsBitmap, XpermsKind,
34};
35
36use anyhow::Context as _;
37use std::collections::HashSet;
38use std::fmt::Debug;
39use std::hash::Hash;
40use std::iter::Iterator;
41use std::num::NonZeroU32;
42use zerocopy::little_endian as le;
43
44/// A parsed binary policy.
45#[derive(Debug)]
46pub struct ParsedPolicy {
47    /// The raw policy data.
48    pub data: PolicyData,
49
50    /// A distinctive number that acts as a binary format-specific header for SELinux binary policy
51    /// files.
52    magic: Magic,
53    /// A length-encoded string, "SE Linux", which identifies this policy as an SE Linux policy.
54    signature: Signature,
55    /// The policy format version number. Different version may support different policy features.
56    policy_version: PolicyVersion,
57    /// Whole-policy configuration, such as how to handle queries against unknown classes.
58    config: Config,
59    /// High-level counts of subsequent policy elements.
60    counts: Counts,
61    policy_capabilities: ExtensibleBitmap,
62    permissive_map: ExtensibleBitmap,
63    /// Common permissions that can be mixed in to classes.
64    common_symbols: SymbolList<CommonSymbol>,
65    /// The set of classes referenced by this policy.
66    classes: SymbolList<Class>,
67    /// The set of roles referenced by this policy.
68    roles: SymbolList<Role>,
69    /// The set of types referenced by this policy.
70    types: SymbolList<Type>,
71    /// The set of users referenced by this policy.
72    users: SymbolList<User>,
73    /// The set of dynamically adjustable booleans referenced by this policy.
74    conditional_booleans: SymbolList<ConditionalBoolean>,
75    /// The set of sensitivity levels referenced by this policy.
76    sensitivities: SymbolList<Sensitivity>,
77    /// The set of categories referenced by this policy.
78    categories: SymbolList<Category>,
79    /// The set of access vector rules referenced by this policy.
80    access_vector_rules: HashedArrayView<le::U32, AccessVectorRule>,
81    conditional_lists: SimpleArray<ConditionalNodes>,
82    /// The set of role transitions to apply when instantiating new objects.
83    role_transitions: RoleTransitions,
84    /// The set of role transitions allowed by policy.
85    role_allowlist: RoleAllows,
86    filename_transition_list: FilenameTransitionList,
87    initial_sids: SimpleArray<InitialSids>,
88    filesystems: SimpleArray<NamedContextPairs>,
89    ports: SimpleArray<Ports>,
90    network_interfaces: SimpleArray<NamedContextPairs>,
91    nodes: SimpleArray<Nodes>,
92    fs_uses: SimpleArray<FsUses>,
93    ipv6_nodes: SimpleArray<IPv6Nodes>,
94    infinitiband_partition_keys: Option<SimpleArray<InfinitiBandPartitionKeys>>,
95    infinitiband_end_ports: Option<SimpleArray<InfinitiBandEndPorts>>,
96    /// A set of labeling statements to apply to given filesystems and/or their subdirectories.
97    /// Corresponds to the `genfscon` labeling statement in the policy.
98    generic_fs_contexts: SimpleArray<GenericFsContexts>,
99    range_transitions: SimpleArray<RangeTransitions>,
100    /// Extensible bitmaps that encode associations between types and attributes.
101    attribute_maps: Vec<ExtensibleBitmap>,
102}
103
104impl ParsedPolicy {
105    /// The policy version stored in the underlying binary policy.
106    pub fn policy_version(&self) -> u32 {
107        self.policy_version.policy_version()
108    }
109
110    /// The way "unknown" policy decisions should be handed according to the underlying binary
111    /// policy.
112    pub fn handle_unknown(&self) -> HandleUnknown {
113        self.config.handle_unknown()
114    }
115
116    /// Returns true if the specified capability is in the policy's enabled capabilities set.
117    pub fn has_policycap(&self, policy_cap: PolicyCap) -> bool {
118        self.policy_capabilities.is_set(policy_cap as u32)
119    }
120
121    /// Computes the access granted to `source_type` on `target_type`, for the specified
122    /// `target_class`. The result is a set of access vectors with bits set for each
123    /// `target_class` permission, describing which permissions are allowed, and
124    /// which should have access checks audit-logged when denied, or allowed.
125    ///
126    /// An [`AccessDecision`] is accumulated, starting from no permissions to be granted,
127    /// nor audit-logged if allowed, and all permissions to be audit-logged if denied.
128    /// Permissions that are explicitly `allow`ed, but that are subject to unsatisfied
129    /// constraints, are removed from the allowed set. Matching policy statements then
130    /// add permissions to the granted & audit-allow sets, or remove them from the
131    /// audit-deny set.
132    pub(super) fn compute_access_decision(
133        &self,
134        source_context: &SecurityContext,
135        target_context: &SecurityContext,
136        target_class: &Class,
137    ) -> AccessDecision {
138        let mut access_decision = self.compute_explicitly_allowed(
139            source_context.type_(),
140            target_context.type_(),
141            target_class,
142        );
143        access_decision.allow -=
144            self.compute_denied_by_constraints(source_context, target_context, target_class);
145        access_decision
146    }
147
148    /// Computes the access granted to `source_type` on `target_type`, for the specified
149    /// `target_class`. The result is a set of access vectors with bits set for each
150    /// `target_class` permission, describing which permissions are explicitly allowed,
151    /// and which should have access checks audit-logged when denied, or allowed.
152    pub(super) fn compute_explicitly_allowed(
153        &self,
154        source_type: TypeId,
155        target_type: TypeId,
156        target_class: &Class,
157    ) -> AccessDecision {
158        let target_class_id = target_class.id();
159
160        let mut computed_access_vector = AccessVector::NONE;
161        let mut computed_audit_allow = AccessVector::NONE;
162        let mut computed_audit_deny = AccessVector::ALL;
163
164        let source_attribute_bitmap: &ExtensibleBitmap =
165            &self.attribute_maps[(source_type.0.get() - 1) as usize];
166        let target_attribute_bitmap: &ExtensibleBitmap =
167            &self.attribute_maps[(target_type.0.get() - 1) as usize];
168
169        for source_bit_index in source_attribute_bitmap.indices_of_set_bits() {
170            let source_id = TypeId(NonZeroU32::new(source_bit_index + 1).unwrap());
171            for target_bit_index in target_attribute_bitmap.indices_of_set_bits() {
172                let target_id = TypeId(NonZeroU32::new(target_bit_index + 1).unwrap());
173
174                if let Some(allow_rule) = self.find_access_vector_rule(
175                    source_id,
176                    target_id,
177                    target_class_id,
178                    ACCESS_VECTOR_RULE_TYPE_ALLOW,
179                ) {
180                    // `access_vector` has bits set for each permission allowed by this rule.
181                    computed_access_vector |= allow_rule.access_vector().unwrap();
182                }
183                if let Some(auditallow_rule) = self.find_access_vector_rule(
184                    source_id,
185                    target_id,
186                    target_class_id,
187                    ACCESS_VECTOR_RULE_TYPE_AUDITALLOW,
188                ) {
189                    // `access_vector` has bits set for each permission to audit when allowed.
190                    computed_audit_allow |= auditallow_rule.access_vector().unwrap();
191                }
192                if let Some(dontaudit_rule) = self.find_access_vector_rule(
193                    source_id,
194                    target_id,
195                    target_class_id,
196                    ACCESS_VECTOR_RULE_TYPE_DONTAUDIT,
197                ) {
198                    // `access_vector` has bits cleared for each permission not to audit on denial.
199                    computed_audit_deny &= dontaudit_rule.access_vector().unwrap();
200                }
201            }
202        }
203
204        // TODO: https://fxbug.dev/362706116 - Collate the auditallow & auditdeny sets.
205        let mut flags = 0;
206        if self.permissive_types().is_set(source_type.0.get()) {
207            flags |= SELINUX_AVD_FLAGS_PERMISSIVE;
208        }
209        AccessDecision {
210            allow: computed_access_vector,
211            auditallow: computed_audit_allow,
212            auditdeny: computed_audit_deny,
213            flags,
214            todo_bug: None,
215        }
216    }
217
218    /// A permission is denied if it matches at least one unsatisfied constraint.
219    fn compute_denied_by_constraints(
220        &self,
221        source_context: &SecurityContext,
222        target_context: &SecurityContext,
223        target_class: &Class,
224    ) -> AccessVector {
225        let mut denied = AccessVector::NONE;
226        for constraint in target_class.constraints().iter() {
227            match constraint.constraint_expr().evaluate(source_context, target_context) {
228                Err(err) => {
229                    unreachable!("validated constraint expression failed to evaluate: {:?}", err)
230                }
231                Ok(false) => denied |= constraint.access_vector(),
232                Ok(true) => {}
233            }
234        }
235        denied
236    }
237
238    /// Computes the access decision for set of extended permissions of a given kind and with a
239    /// given prefix byte, for a particular source and target context and target class.
240    pub(super) fn compute_xperms_access_decision(
241        &self,
242        xperms_kind: XpermsKind,
243        source_context: &SecurityContext,
244        target_context: &SecurityContext,
245        target_class: &Class,
246        xperms_prefix: u8,
247    ) -> XpermsAccessDecision {
248        let target_class_id = target_class.id();
249
250        let mut explicit_allow: Option<XpermsBitmap> = None;
251        let mut auditallow = XpermsBitmap::NONE;
252        let mut auditdeny = XpermsBitmap::ALL;
253
254        let xperms_types = match xperms_kind {
255            XpermsKind::Ioctl => {
256                [XPERMS_TYPE_IOCTL_PREFIX_AND_POSTFIXES, XPERMS_TYPE_IOCTL_PREFIXES].as_slice()
257            }
258            XpermsKind::Nlmsg => [XPERMS_TYPE_NLMSG].as_slice(),
259        };
260        let bitmap_if_prefix_matches =
261            |xperms_prefix: u8, xperms: &ExtendedPermissions| match xperms_kind {
262                XpermsKind::Ioctl => match xperms.xperms_type {
263                    XPERMS_TYPE_IOCTL_PREFIX_AND_POSTFIXES => (xperms.xperms_optional_prefix
264                        == xperms_prefix)
265                        .then_some(xperms.xperms_bitmap),
266                    XPERMS_TYPE_IOCTL_PREFIXES => {
267                        xperms.xperms_bitmap.contains(xperms_prefix).then_some(XpermsBitmap::ALL)
268                    }
269                    _ => None,
270                },
271                XpermsKind::Nlmsg => match xperms.xperms_type {
272                    XPERMS_TYPE_NLMSG => (xperms.xperms_optional_prefix == xperms_prefix)
273                        .then_some(xperms.xperms_bitmap),
274                    _ => None,
275                },
276            };
277
278        let source_attribute_bitmap: &ExtensibleBitmap =
279            &self.attribute_maps[(source_context.type_().0.get() - 1) as usize];
280        let target_attribute_bitmap: &ExtensibleBitmap =
281            &self.attribute_maps[(target_context.type_().0.get() - 1) as usize];
282
283        for access_vector_rule_view in self.access_vector_rules() {
284            let metadata = access_vector_rule_view.read_metadata(&self.data);
285
286            if !metadata.is_allowxperm()
287                && !metadata.is_auditallowxperm()
288                && !metadata.is_dontauditxperm()
289            {
290                continue;
291            }
292            if metadata.target_class() != target_class_id {
293                continue;
294            }
295            if !source_attribute_bitmap.is_set(metadata.source_type().0.get() - 1) {
296                continue;
297            }
298            if !target_attribute_bitmap.is_set(metadata.target_type().0.get() - 1) {
299                continue;
300            }
301
302            let access_control_rule = access_vector_rule_view.parse(&self.data);
303            if let Some(xperms) = access_control_rule.extended_permissions() {
304                // Only filter xperms if there is at least one `allowxperm` rule for the relevant
305                // kind of extended permission. If this condition is not satisfied by any
306                // access vector rule, then all xperms of the relevant type are allowed.
307                if metadata.is_allowxperm() && xperms_types.contains(&xperms.xperms_type) {
308                    explicit_allow.get_or_insert(XpermsBitmap::NONE);
309                }
310                let Some(ref xperms_bitmap) = bitmap_if_prefix_matches(xperms_prefix, xperms)
311                else {
312                    continue;
313                };
314                if metadata.is_allowxperm() {
315                    (*explicit_allow.get_or_insert(XpermsBitmap::NONE)) |= xperms_bitmap;
316                }
317                if metadata.is_auditallowxperm() {
318                    auditallow |= xperms_bitmap;
319                }
320                if metadata.is_dontauditxperm() {
321                    auditdeny -= xperms_bitmap;
322                }
323            }
324        }
325        let allow = explicit_allow.unwrap_or(XpermsBitmap::ALL);
326        XpermsAccessDecision { allow, auditallow, auditdeny }
327    }
328
329    /// Returns the policy entry for the specified initial Security Context.
330    pub(super) fn initial_context(&self, id: crate::InitialSid) -> &Context {
331        let id = le::U32::from(id as u32);
332        // [`InitialSids`] validates that all `InitialSid` values are defined by the policy.
333        &self.initial_sids.data.iter().find(|initial| initial.id() == id).unwrap().context()
334    }
335
336    /// Returns the `User` structure for the requested Id. Valid policies include definitions
337    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
338    pub(super) fn user(&self, id: UserId) -> &User {
339        self.users.data.iter().find(|x| x.id() == id).unwrap()
340    }
341
342    /// Returns the named user, if present in the policy.
343    pub(super) fn user_by_name(&self, name: &str) -> Option<&User> {
344        self.users.data.iter().find(|x| x.name_bytes() == name.as_bytes())
345    }
346
347    /// Returns the `Role` structure for the requested Id. Valid policies include definitions
348    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
349    pub(super) fn role(&self, id: RoleId) -> &Role {
350        self.roles.data.iter().find(|x| x.id() == id).unwrap()
351    }
352
353    /// Returns the named role, if present in the policy.
354    pub(super) fn role_by_name(&self, name: &str) -> Option<&Role> {
355        self.roles.data.iter().find(|x| x.name_bytes() == name.as_bytes())
356    }
357
358    /// Returns the `Type` structure for the requested Id. Valid policies include definitions
359    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
360    pub(super) fn type_(&self, id: TypeId) -> &Type {
361        self.types.data.iter().find(|x| x.id() == id).unwrap()
362    }
363
364    /// Returns the named type, if present in the policy.
365    pub(super) fn type_by_name(&self, name: &str) -> Option<&Type> {
366        self.types.data.iter().find(|x| x.name_bytes() == name.as_bytes())
367    }
368
369    /// Returns the extensible bitmap describing the set of types/domains for which permission
370    /// checks are permissive.
371    pub(super) fn permissive_types(&self) -> &ExtensibleBitmap {
372        &self.permissive_map
373    }
374
375    /// Returns the `Sensitivity` structure for the requested Id. Valid policies include definitions
376    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
377    pub(super) fn sensitivity(&self, id: SensitivityId) -> &Sensitivity {
378        self.sensitivities.data.iter().find(|x| x.id() == id).unwrap()
379    }
380
381    /// Returns the named sensitivity level, if present in the policy.
382    pub(super) fn sensitivity_by_name(&self, name: &str) -> Option<&Sensitivity> {
383        self.sensitivities.data.iter().find(|x| x.name_bytes() == name.as_bytes())
384    }
385
386    /// Returns the `Category` structure for the requested Id. Valid policies include definitions
387    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
388    pub(super) fn category(&self, id: CategoryId) -> &Category {
389        self.categories.data.iter().find(|y| y.id() == id).unwrap()
390    }
391
392    /// Returns the named category, if present in the policy.
393    pub(super) fn category_by_name(&self, name: &str) -> Option<&Category> {
394        self.categories.data.iter().find(|x| x.name_bytes() == name.as_bytes())
395    }
396
397    pub(super) fn classes(&self) -> &Classes {
398        &self.classes.data
399    }
400
401    pub(super) fn common_symbols(&self) -> &CommonSymbols {
402        &self.common_symbols.data
403    }
404
405    pub(super) fn conditional_booleans(&self) -> &Vec<ConditionalBoolean> {
406        &self.conditional_booleans.data
407    }
408
409    pub(super) fn fs_uses(&self) -> &FsUses {
410        &self.fs_uses.data
411    }
412
413    pub(super) fn generic_fs_contexts(&self) -> &GenericFsContexts {
414        &self.generic_fs_contexts.data
415    }
416
417    pub(super) fn role_allowlist(&self) -> &[RoleAllow] {
418        &self.role_allowlist.data
419    }
420
421    pub(super) fn role_transitions(&self) -> &[RoleTransition] {
422        &self.role_transitions.data
423    }
424
425    pub(super) fn range_transitions(&self) -> &RangeTransitions {
426        &self.range_transitions.data
427    }
428
429    pub(super) fn access_vector_rules(&self) -> impl Iterator<Item = View<AccessVectorRule>> {
430        self.access_vector_rules.data().iter(&self.data)
431    }
432
433    pub(super) fn find_access_vector_rule(
434        &self,
435        source: TypeId,
436        target: TypeId,
437        class: ClassId,
438        rule_type: u16,
439    ) -> Option<AccessVectorRule> {
440        let query = AccessVectorRuleMetadata::for_query(source, target, class, rule_type);
441        self.access_vector_rules.find(query, &self.data)
442    }
443
444    #[cfg(test)]
445    pub(super) fn access_vector_rules_for_test(
446        &self,
447    ) -> impl Iterator<Item = AccessVectorRule> + use<'_> {
448        self.access_vector_rules().map(|view| view.parse(&self.data))
449    }
450
451    pub(super) fn compute_filename_transition(
452        &self,
453        source_type: TypeId,
454        target_type: TypeId,
455        class: ClassId,
456        name: NullessByteStr<'_>,
457    ) -> Option<TypeId> {
458        match &self.filename_transition_list {
459            FilenameTransitionList::PolicyVersionGeq33(list) => {
460                let entry = list.data.iter().find(|transition| {
461                    transition.target_type() == target_type
462                        && transition.target_class() == class
463                        && transition.name_bytes() == name.as_bytes()
464                })?;
465                entry
466                    .outputs()
467                    .iter()
468                    .find(|entry| entry.has_source_type(source_type))
469                    .map(|x| x.out_type())
470            }
471            FilenameTransitionList::PolicyVersionLeq32(list) => list
472                .data
473                .iter()
474                .find(|transition| {
475                    transition.target_class() == class
476                        && transition.target_type() == target_type
477                        && transition.source_type() == source_type
478                        && transition.name_bytes() == name.as_bytes()
479                })
480                .map(|x| x.out_type()),
481        }
482    }
483
484    // Validate an MLS range statement against sets of defined sensitivity and category
485    // IDs:
486    // - Verify that all sensitivity and category IDs referenced in the MLS levels are
487    //   defined.
488    // - Verify that the range is internally consistent; i.e., the high level (if any)
489    //   dominates the low level.
490    fn validate_mls_range(
491        &self,
492        low_level: &MlsLevel,
493        high_level: &Option<MlsLevel>,
494        sensitivity_ids: &HashSet<SensitivityId>,
495        category_ids: &HashSet<CategoryId>,
496    ) -> Result<(), anyhow::Error> {
497        validate_id(sensitivity_ids, low_level.sensitivity(), "sensitivity")?;
498        for id in low_level.category_ids() {
499            validate_id(category_ids, id, "category")?;
500        }
501        if let Some(high) = high_level {
502            validate_id(sensitivity_ids, high.sensitivity(), "sensitivity")?;
503            for id in high.category_ids() {
504                validate_id(category_ids, id, "category")?;
505            }
506            if !high.dominates(low_level) {
507                return Err(ValidateError::InvalidMlsRange {
508                    low: low_level.serialize(self).into(),
509                    high: high.serialize(self).into(),
510                }
511                .into());
512            }
513        }
514        Ok(())
515    }
516}
517
518impl ParsedPolicy {
519    /// Parses the binary policy stored in `bytes`. It is an error for `bytes` to have trailing
520    /// bytes after policy parsing completes.
521    pub(super) fn parse(data: PolicyData) -> Result<Self, anyhow::Error> {
522        let cursor = PolicyCursor::new(data.clone());
523        let (policy, tail) = parse_policy_internal(cursor, data)?;
524        let num_bytes = tail.len();
525        if num_bytes > 0 {
526            return Err(ParseError::TrailingBytes { num_bytes }.into());
527        }
528        Ok(policy)
529    }
530}
531
532/// Parses an entire binary policy.
533fn parse_policy_internal(
534    bytes: PolicyCursor,
535    data: PolicyData,
536) -> Result<(ParsedPolicy, PolicyCursor), anyhow::Error> {
537    let tail = bytes;
538
539    let (magic, tail) = PolicyCursor::parse::<Magic>(tail).context("parsing magic")?;
540
541    let (signature, tail) =
542        Signature::parse(tail).map_err(Into::<anyhow::Error>::into).context("parsing signature")?;
543
544    let (policy_version, tail) =
545        PolicyCursor::parse::<PolicyVersion>(tail).context("parsing policy version")?;
546    let policy_version_value = policy_version.policy_version();
547
548    let (config, tail) = Config::parse(tail)
549        .map_err(Into::<anyhow::Error>::into)
550        .context("parsing policy config")?;
551
552    let (counts, tail) =
553        PolicyCursor::parse::<Counts>(tail).context("parsing high-level policy object counts")?;
554
555    let (policy_capabilities, tail) = ExtensibleBitmap::parse(tail)
556        .map_err(Into::<anyhow::Error>::into)
557        .context("parsing policy capabilities")?;
558
559    let (permissive_map, tail) = ExtensibleBitmap::parse(tail)
560        .map_err(Into::<anyhow::Error>::into)
561        .context("parsing permissive map")?;
562
563    let (common_symbols, tail) = SymbolList::<CommonSymbol>::parse(tail)
564        .map_err(Into::<anyhow::Error>::into)
565        .context("parsing common symbols")?;
566
567    let (classes, tail) = SymbolList::<Class>::parse(tail)
568        .map_err(Into::<anyhow::Error>::into)
569        .context("parsing classes")?;
570
571    let (roles, tail) = SymbolList::<Role>::parse(tail)
572        .map_err(Into::<anyhow::Error>::into)
573        .context("parsing roles")?;
574
575    let (types, tail) = SymbolList::<Type>::parse(tail)
576        .map_err(Into::<anyhow::Error>::into)
577        .context("parsing types")?;
578
579    let (users, tail) = SymbolList::<User>::parse(tail)
580        .map_err(Into::<anyhow::Error>::into)
581        .context("parsing users")?;
582
583    let (conditional_booleans, tail) = SymbolList::<ConditionalBoolean>::parse(tail)
584        .map_err(Into::<anyhow::Error>::into)
585        .context("parsing conditional booleans")?;
586
587    let (sensitivities, tail) = SymbolList::<Sensitivity>::parse(tail)
588        .map_err(Into::<anyhow::Error>::into)
589        .context("parsing sensitivites")?;
590
591    let (categories, tail) = SymbolList::<Category>::parse(tail)
592        .map_err(Into::<anyhow::Error>::into)
593        .context("parsing categories")?;
594
595    let (access_vector_rules, tail) = HashedArrayView::<le::U32, AccessVectorRule>::parse(tail)
596        .map_err(Into::<anyhow::Error>::into)
597        .context("parsing access vector rules")?;
598
599    let (conditional_lists, tail) = SimpleArray::<ConditionalNodes>::parse(tail)
600        .map_err(Into::<anyhow::Error>::into)
601        .context("parsing conditional lists")?;
602
603    let (role_transitions, tail) = RoleTransitions::parse(tail)
604        .map_err(Into::<anyhow::Error>::into)
605        .context("parsing role transitions")?;
606
607    let (role_allowlist, tail) = RoleAllows::parse(tail)
608        .map_err(Into::<anyhow::Error>::into)
609        .context("parsing role allow rules")?;
610
611    let (filename_transition_list, tail) = if policy_version_value >= 33 {
612        let (filename_transition_list, tail) = SimpleArray::<FilenameTransitions>::parse(tail)
613            .map_err(Into::<anyhow::Error>::into)
614            .context("parsing standard filename transitions")?;
615        (FilenameTransitionList::PolicyVersionGeq33(filename_transition_list), tail)
616    } else {
617        let (filename_transition_list, tail) =
618            SimpleArray::<DeprecatedFilenameTransitions>::parse(tail)
619                .map_err(Into::<anyhow::Error>::into)
620                .context("parsing deprecated filename transitions")?;
621        (FilenameTransitionList::PolicyVersionLeq32(filename_transition_list), tail)
622    };
623
624    let (initial_sids, tail) = SimpleArray::<InitialSids>::parse(tail)
625        .map_err(Into::<anyhow::Error>::into)
626        .context("parsing initial sids")?;
627
628    let (filesystems, tail) = SimpleArray::<NamedContextPairs>::parse(tail)
629        .map_err(Into::<anyhow::Error>::into)
630        .context("parsing filesystem contexts")?;
631
632    let (ports, tail) = SimpleArray::<Ports>::parse(tail)
633        .map_err(Into::<anyhow::Error>::into)
634        .context("parsing ports")?;
635
636    let (network_interfaces, tail) = SimpleArray::<NamedContextPairs>::parse(tail)
637        .map_err(Into::<anyhow::Error>::into)
638        .context("parsing network interfaces")?;
639
640    let (nodes, tail) = SimpleArray::<Nodes>::parse(tail)
641        .map_err(Into::<anyhow::Error>::into)
642        .context("parsing nodes")?;
643
644    let (fs_uses, tail) = SimpleArray::<FsUses>::parse(tail)
645        .map_err(Into::<anyhow::Error>::into)
646        .context("parsing fs uses")?;
647
648    let (ipv6_nodes, tail) = SimpleArray::<IPv6Nodes>::parse(tail)
649        .map_err(Into::<anyhow::Error>::into)
650        .context("parsing ipv6 nodes")?;
651
652    let (infinitiband_partition_keys, infinitiband_end_ports, tail) =
653        if policy_version_value >= MIN_POLICY_VERSION_FOR_INFINITIBAND_PARTITION_KEY {
654            let (infinity_band_partition_keys, tail) =
655                SimpleArray::<InfinitiBandPartitionKeys>::parse(tail)
656                    .map_err(Into::<anyhow::Error>::into)
657                    .context("parsing infiniti band partition keys")?;
658            let (infinitiband_end_ports, tail) = SimpleArray::<InfinitiBandEndPorts>::parse(tail)
659                .map_err(Into::<anyhow::Error>::into)
660                .context("parsing infiniti band end ports")?;
661            (Some(infinity_band_partition_keys), Some(infinitiband_end_ports), tail)
662        } else {
663            (None, None, tail)
664        };
665
666    let (generic_fs_contexts, tail) = SimpleArray::<GenericFsContexts>::parse(tail)
667        .map_err(Into::<anyhow::Error>::into)
668        .context("parsing generic filesystem contexts")?;
669
670    let (range_transitions, tail) = SimpleArray::<RangeTransitions>::parse(tail)
671        .map_err(Into::<anyhow::Error>::into)
672        .context("parsing range transitions")?;
673
674    let primary_names_count = types.metadata.primary_names_count();
675    let mut attribute_maps = Vec::with_capacity(primary_names_count as usize);
676    let mut tail = tail;
677
678    for i in 0..primary_names_count {
679        let (item, next_tail) = ExtensibleBitmap::parse(tail)
680            .map_err(Into::<anyhow::Error>::into)
681            .with_context(|| format!("parsing {}th attribute map", i))?;
682        attribute_maps.push(item);
683        tail = next_tail;
684    }
685    let tail = tail;
686    let attribute_maps = attribute_maps;
687
688    Ok((
689        ParsedPolicy {
690            data,
691            magic,
692            signature,
693            policy_version,
694            config,
695            counts,
696            policy_capabilities,
697            permissive_map,
698            common_symbols,
699            classes,
700            roles,
701            types,
702            users,
703            conditional_booleans,
704            sensitivities,
705            categories,
706            access_vector_rules,
707            conditional_lists,
708            role_transitions,
709            role_allowlist,
710            filename_transition_list,
711            initial_sids,
712            filesystems,
713            ports,
714            network_interfaces,
715            nodes,
716            fs_uses,
717            ipv6_nodes,
718            infinitiband_partition_keys,
719            infinitiband_end_ports,
720            generic_fs_contexts,
721            range_transitions,
722            attribute_maps,
723        },
724        tail,
725    ))
726}
727
728impl ParsedPolicy {
729    pub fn validate(&self) -> Result<(), anyhow::Error> {
730        let mut context = PolicyValidationContext { data: self.data.clone() };
731
732        self.magic
733            .validate(&mut context)
734            .map_err(Into::<anyhow::Error>::into)
735            .context("validating magic")?;
736        self.signature
737            .validate(&mut context)
738            .map_err(Into::<anyhow::Error>::into)
739            .context("validating signature")?;
740        self.policy_version
741            .validate(&mut context)
742            .map_err(Into::<anyhow::Error>::into)
743            .context("validating policy_version")?;
744        self.config
745            .validate(&mut context)
746            .map_err(Into::<anyhow::Error>::into)
747            .context("validating config")?;
748        self.counts
749            .validate(&mut context)
750            .map_err(Into::<anyhow::Error>::into)
751            .context("validating counts")?;
752        self.policy_capabilities
753            .validate(&mut context)
754            .map_err(Into::<anyhow::Error>::into)
755            .context("validating policy_capabilities")?;
756        self.permissive_map
757            .validate(&mut context)
758            .map_err(Into::<anyhow::Error>::into)
759            .context("validating permissive_map")?;
760        self.common_symbols
761            .validate(&mut context)
762            .map_err(Into::<anyhow::Error>::into)
763            .context("validating common_symbols")?;
764        self.classes
765            .validate(&mut context)
766            .map_err(Into::<anyhow::Error>::into)
767            .context("validating classes")?;
768        self.roles
769            .validate(&mut context)
770            .map_err(Into::<anyhow::Error>::into)
771            .context("validating roles")?;
772        self.types
773            .validate(&mut context)
774            .map_err(Into::<anyhow::Error>::into)
775            .context("validating types")?;
776        self.users
777            .validate(&mut context)
778            .map_err(Into::<anyhow::Error>::into)
779            .context("validating users")?;
780        self.conditional_booleans
781            .validate(&mut context)
782            .map_err(Into::<anyhow::Error>::into)
783            .context("validating conditional_booleans")?;
784        self.sensitivities
785            .validate(&mut context)
786            .map_err(Into::<anyhow::Error>::into)
787            .context("validating sensitivities")?;
788        self.categories
789            .validate(&mut context)
790            .map_err(Into::<anyhow::Error>::into)
791            .context("validating categories")?;
792        self.access_vector_rules
793            .validate(&mut context)
794            .map_err(Into::<anyhow::Error>::into)
795            .context("validating access_vector_rules")?;
796        self.conditional_lists
797            .validate(&mut context)
798            .map_err(Into::<anyhow::Error>::into)
799            .context("validating conditional_lists")?;
800        self.role_transitions
801            .validate(&mut context)
802            .map_err(Into::<anyhow::Error>::into)
803            .context("validating role_transitions")?;
804        self.role_allowlist
805            .validate(&mut context)
806            .map_err(Into::<anyhow::Error>::into)
807            .context("validating role_allowlist")?;
808        self.filename_transition_list
809            .validate(&mut context)
810            .map_err(Into::<anyhow::Error>::into)
811            .context("validating filename_transition_list")?;
812        self.initial_sids
813            .validate(&mut context)
814            .map_err(Into::<anyhow::Error>::into)
815            .context("validating initial_sids")?;
816        self.filesystems
817            .validate(&mut context)
818            .map_err(Into::<anyhow::Error>::into)
819            .context("validating filesystems")?;
820        self.ports
821            .validate(&mut context)
822            .map_err(Into::<anyhow::Error>::into)
823            .context("validating ports")?;
824        self.network_interfaces
825            .validate(&mut context)
826            .map_err(Into::<anyhow::Error>::into)
827            .context("validating network_interfaces")?;
828        self.nodes
829            .validate(&mut context)
830            .map_err(Into::<anyhow::Error>::into)
831            .context("validating nodes")?;
832        self.fs_uses
833            .validate(&mut context)
834            .map_err(Into::<anyhow::Error>::into)
835            .context("validating fs_uses")?;
836        self.ipv6_nodes
837            .validate(&mut context)
838            .map_err(Into::<anyhow::Error>::into)
839            .context("validating ipv6 nodes")?;
840        self.infinitiband_partition_keys
841            .validate(&mut context)
842            .map_err(Into::<anyhow::Error>::into)
843            .context("validating infinitiband_partition_keys")?;
844        self.infinitiband_end_ports
845            .validate(&mut context)
846            .map_err(Into::<anyhow::Error>::into)
847            .context("validating infinitiband_end_ports")?;
848        self.generic_fs_contexts
849            .validate(&mut context)
850            .map_err(Into::<anyhow::Error>::into)
851            .context("validating generic_fs_contexts")?;
852        self.range_transitions
853            .validate(&mut context)
854            .map_err(Into::<anyhow::Error>::into)
855            .context("validating range_transitions")?;
856        self.attribute_maps
857            .validate(&mut context)
858            .map_err(Into::<anyhow::Error>::into)
859            .context("validating attribute_maps")?;
860
861        // Collate the sets of user, role, type, sensitivity and category Ids.
862        let user_ids: HashSet<UserId> = self.users.data.iter().map(|x| x.id()).collect();
863        let role_ids: HashSet<RoleId> = self.roles.data.iter().map(|x| x.id()).collect();
864        let class_ids: HashSet<ClassId> = self.classes.data.iter().map(|x| x.id()).collect();
865        let type_ids: HashSet<TypeId> = self.types.data.iter().map(|x| x.id()).collect();
866        let sensitivity_ids: HashSet<SensitivityId> =
867            self.sensitivities.data.iter().map(|x| x.id()).collect();
868        let category_ids: HashSet<CategoryId> =
869            self.categories.data.iter().map(|x| x.id()).collect();
870
871        // Validate that users use only defined sensitivities and categories, and that
872        // each user's MLS levels are internally consistent (i.e., the high level
873        // dominates the low level).
874        for user in &self.users.data {
875            self.validate_mls_range(
876                user.mls_range().low(),
877                user.mls_range().high(),
878                &sensitivity_ids,
879                &category_ids,
880            )?;
881        }
882
883        // Validate that initial contexts use only defined user, role, type, etc Ids.
884        // Check that all sensitivity and category IDs are defined and that MLS levels
885        // are internally consistent.
886        for initial_sid in &self.initial_sids.data {
887            let context = initial_sid.context();
888            validate_id(&user_ids, context.user_id(), "user")?;
889            validate_id(&role_ids, context.role_id(), "role")?;
890            validate_id(&type_ids, context.type_id(), "type")?;
891            self.validate_mls_range(
892                context.low_level(),
893                context.high_level(),
894                &sensitivity_ids,
895                &category_ids,
896            )?;
897        }
898
899        // Validate that contexts specified in filesystem labeling rules only use
900        // policy-defined Ids for their fields. Check that MLS levels are internally
901        // consistent.
902        for fs_use in &self.fs_uses.data {
903            let context = fs_use.context();
904            validate_id(&user_ids, context.user_id(), "user")?;
905            validate_id(&role_ids, context.role_id(), "role")?;
906            validate_id(&type_ids, context.type_id(), "type")?;
907            self.validate_mls_range(
908                context.low_level(),
909                context.high_level(),
910                &sensitivity_ids,
911                &category_ids,
912            )?;
913        }
914
915        // Validate that roles output by role- transitions & allows are defined.
916        for transition in &self.role_transitions.data {
917            validate_id(&role_ids, transition.current_role(), "current_role")?;
918            validate_id(&type_ids, transition.type_(), "type")?;
919            validate_id(&class_ids, transition.class(), "class")?;
920            validate_id(&role_ids, transition.new_role(), "new_role")?;
921        }
922        for allow in &self.role_allowlist.data {
923            validate_id(&role_ids, allow.source_role(), "source_role")?;
924            validate_id(&role_ids, allow.new_role(), "new_role")?;
925        }
926
927        // Validate that types output by access vector rules are defined.
928        for access_vector_rule_view in self.access_vector_rules() {
929            let access_vector_rule = access_vector_rule_view.parse(&self.data);
930            if let Some(type_id) = access_vector_rule.new_type() {
931                validate_id(&type_ids, type_id, "new_type")?;
932            }
933        }
934
935        // Validate that constraints are well-formed by evaluating against
936        // a source and target security context.
937        let initial_context = SecurityContext::new_from_policy_context(
938            self.initial_context(crate::InitialSid::Kernel),
939        );
940        for class in self.classes() {
941            for constraint in class.constraints() {
942                constraint
943                    .constraint_expr()
944                    .evaluate(&initial_context, &initial_context)
945                    .map_err(Into::<anyhow::Error>::into)
946                    .context("validating constraints")?;
947            }
948        }
949
950        // To-do comments for cross-policy validations yet to be implemented go here.
951        // TODO(b/356569876): Determine which "bounds" should be verified for correctness here.
952
953        Ok(())
954    }
955}
956
957fn validate_id<IdType: Debug + Eq + Hash>(
958    id_set: &HashSet<IdType>,
959    id: IdType,
960    debug_kind: &'static str,
961) -> Result<(), anyhow::Error> {
962    if !id_set.contains(&id) {
963        return Err(ValidateError::UnknownId { kind: debug_kind, id: format!("{:?}", id) }.into());
964    }
965    Ok(())
966}