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_kind: &XpermsKind, xperms_prefix: u8, xperms: &ExtendedPermissions| {
262                match xperms_kind {
263                    XpermsKind::Ioctl => match xperms.xperms_type {
264                        XPERMS_TYPE_IOCTL_PREFIX_AND_POSTFIXES => (xperms.xperms_optional_prefix
265                            == xperms_prefix)
266                            .then_some(xperms.xperms_bitmap),
267                        XPERMS_TYPE_IOCTL_PREFIXES => xperms
268                            .xperms_bitmap
269                            .contains(xperms_prefix)
270                            .then_some(XpermsBitmap::ALL),
271                        _ => None,
272                    },
273                    XpermsKind::Nlmsg => match xperms.xperms_type {
274                        XPERMS_TYPE_NLMSG => (xperms.xperms_optional_prefix == xperms_prefix)
275                            .then_some(xperms.xperms_bitmap),
276                        _ => None,
277                    },
278                }
279            };
280
281        let source_attribute_bitmap: &ExtensibleBitmap =
282            &self.attribute_maps[(source_context.type_().0.get() - 1) as usize];
283        let target_attribute_bitmap: &ExtensibleBitmap =
284            &self.attribute_maps[(target_context.type_().0.get() - 1) as usize];
285
286        for access_vector_rule_view in self.access_vector_rules() {
287            let metadata = access_vector_rule_view.read_metadata(&self.data);
288
289            if !metadata.is_allowxperm()
290                && !metadata.is_auditallowxperm()
291                && !metadata.is_dontauditxperm()
292            {
293                continue;
294            }
295            if metadata.target_class() != target_class_id {
296                continue;
297            }
298            if !source_attribute_bitmap.is_set(metadata.source_type().0.get() - 1) {
299                continue;
300            }
301            if !target_attribute_bitmap.is_set(metadata.target_type().0.get() - 1) {
302                continue;
303            }
304
305            let access_control_rule = access_vector_rule_view.parse(&self.data);
306            if let Some(xperms) = access_control_rule.extended_permissions() {
307                // Only filter xperms if there is at least one `allowxperm` rule for the relevant
308                // kind of extended permission. If this condition is not satisfied by any
309                // access vector rule, then all xperms of the relevant type are allowed.
310                if metadata.is_allowxperm() && xperms_types.contains(&xperms.xperms_type) {
311                    explicit_allow.get_or_insert(XpermsBitmap::NONE);
312                }
313                let Some(ref xperms_bitmap) =
314                    bitmap_if_prefix_matches(&xperms_kind, xperms_prefix, xperms)
315                else {
316                    continue;
317                };
318                if metadata.is_allowxperm() {
319                    (*explicit_allow.get_or_insert(XpermsBitmap::NONE)) |= xperms_bitmap;
320                }
321                if metadata.is_auditallowxperm() {
322                    auditallow |= xperms_bitmap;
323                }
324                if metadata.is_dontauditxperm() {
325                    auditdeny -= xperms_bitmap;
326                }
327            }
328        }
329        let allow = explicit_allow.unwrap_or(XpermsBitmap::ALL);
330        XpermsAccessDecision { allow, auditallow, auditdeny }
331    }
332
333    /// Returns the policy entry for the specified initial Security Context.
334    pub(super) fn initial_context(&self, id: crate::InitialSid) -> &Context {
335        let id = le::U32::from(id as u32);
336        // [`InitialSids`] validates that all `InitialSid` values are defined by the policy.
337        &self.initial_sids.data.iter().find(|initial| initial.id() == id).unwrap().context()
338    }
339
340    /// Returns the `User` structure for the requested Id. Valid policies include definitions
341    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
342    pub(super) fn user(&self, id: UserId) -> &User {
343        self.users.data.iter().find(|x| x.id() == id).unwrap()
344    }
345
346    /// Returns the named user, if present in the policy.
347    pub(super) fn user_by_name(&self, name: &str) -> Option<&User> {
348        self.users.data.iter().find(|x| x.name_bytes() == name.as_bytes())
349    }
350
351    /// Returns the `Role` structure for the requested Id. Valid policies include definitions
352    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
353    pub(super) fn role(&self, id: RoleId) -> &Role {
354        self.roles.data.iter().find(|x| x.id() == id).unwrap()
355    }
356
357    /// Returns the named role, if present in the policy.
358    pub(super) fn role_by_name(&self, name: &str) -> Option<&Role> {
359        self.roles.data.iter().find(|x| x.name_bytes() == name.as_bytes())
360    }
361
362    /// Returns the `Type` structure for the requested Id. Valid policies include definitions
363    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
364    pub(super) fn type_(&self, id: TypeId) -> &Type {
365        self.types.data.iter().find(|x| x.id() == id).unwrap()
366    }
367
368    /// Returns the named type, if present in the policy.
369    pub(super) fn type_by_name(&self, name: &str) -> Option<&Type> {
370        self.types.data.iter().find(|x| x.name_bytes() == name.as_bytes())
371    }
372
373    /// Returns the extensible bitmap describing the set of types/domains for which permission
374    /// checks are permissive.
375    pub(super) fn permissive_types(&self) -> &ExtensibleBitmap {
376        &self.permissive_map
377    }
378
379    /// Returns the `Sensitivity` structure for the requested Id. Valid policies include definitions
380    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
381    pub(super) fn sensitivity(&self, id: SensitivityId) -> &Sensitivity {
382        self.sensitivities.data.iter().find(|x| x.id() == id).unwrap()
383    }
384
385    /// Returns the named sensitivity level, if present in the policy.
386    pub(super) fn sensitivity_by_name(&self, name: &str) -> Option<&Sensitivity> {
387        self.sensitivities.data.iter().find(|x| x.name_bytes() == name.as_bytes())
388    }
389
390    /// Returns the `Category` structure for the requested Id. Valid policies include definitions
391    /// for all the Ids they refer to internally; supply some other Id will trigger a panic.
392    pub(super) fn category(&self, id: CategoryId) -> &Category {
393        self.categories.data.iter().find(|y| y.id() == id).unwrap()
394    }
395
396    /// Returns the named category, if present in the policy.
397    pub(super) fn category_by_name(&self, name: &str) -> Option<&Category> {
398        self.categories.data.iter().find(|x| x.name_bytes() == name.as_bytes())
399    }
400
401    pub(super) fn classes(&self) -> &Classes {
402        &self.classes.data
403    }
404
405    pub(super) fn common_symbols(&self) -> &CommonSymbols {
406        &self.common_symbols.data
407    }
408
409    pub(super) fn conditional_booleans(&self) -> &Vec<ConditionalBoolean> {
410        &self.conditional_booleans.data
411    }
412
413    pub(super) fn fs_uses(&self) -> &FsUses {
414        &self.fs_uses.data
415    }
416
417    pub(super) fn generic_fs_contexts(&self) -> &GenericFsContexts {
418        &self.generic_fs_contexts.data
419    }
420
421    pub(super) fn role_allowlist(&self) -> &[RoleAllow] {
422        &self.role_allowlist.data
423    }
424
425    pub(super) fn role_transitions(&self) -> &[RoleTransition] {
426        &self.role_transitions.data
427    }
428
429    pub(super) fn range_transitions(&self) -> &RangeTransitions {
430        &self.range_transitions.data
431    }
432
433    pub(super) fn access_vector_rules(&self) -> impl Iterator<Item = View<AccessVectorRule>> {
434        self.access_vector_rules.data().iter(&self.data)
435    }
436
437    pub(super) fn find_access_vector_rule(
438        &self,
439        source: TypeId,
440        target: TypeId,
441        class: ClassId,
442        rule_type: u16,
443    ) -> Option<AccessVectorRule> {
444        let query = AccessVectorRuleMetadata::for_query(source, target, class, rule_type);
445        self.access_vector_rules.find(query, &self.data)
446    }
447
448    #[cfg(test)]
449    pub(super) fn access_vector_rules_for_test(
450        &self,
451    ) -> impl Iterator<Item = AccessVectorRule> + use<'_> {
452        self.access_vector_rules().map(|view| view.parse(&self.data))
453    }
454
455    pub(super) fn compute_filename_transition(
456        &self,
457        source_type: TypeId,
458        target_type: TypeId,
459        class: ClassId,
460        name: NullessByteStr<'_>,
461    ) -> Option<TypeId> {
462        match &self.filename_transition_list {
463            FilenameTransitionList::PolicyVersionGeq33(list) => {
464                let entry = list.data.iter().find(|transition| {
465                    transition.target_type() == target_type
466                        && transition.target_class() == class
467                        && transition.name_bytes() == name.as_bytes()
468                })?;
469                entry
470                    .outputs()
471                    .iter()
472                    .find(|entry| entry.has_source_type(source_type))
473                    .map(|x| x.out_type())
474            }
475            FilenameTransitionList::PolicyVersionLeq32(list) => list
476                .data
477                .iter()
478                .find(|transition| {
479                    transition.target_class() == class
480                        && transition.target_type() == target_type
481                        && transition.source_type() == source_type
482                        && transition.name_bytes() == name.as_bytes()
483                })
484                .map(|x| x.out_type()),
485        }
486    }
487
488    // Validate an MLS range statement against sets of defined sensitivity and category
489    // IDs:
490    // - Verify that all sensitivity and category IDs referenced in the MLS levels are
491    //   defined.
492    // - Verify that the range is internally consistent; i.e., the high level (if any)
493    //   dominates the low level.
494    fn validate_mls_range(
495        &self,
496        low_level: &MlsLevel,
497        high_level: &Option<MlsLevel>,
498        sensitivity_ids: &HashSet<SensitivityId>,
499        category_ids: &HashSet<CategoryId>,
500    ) -> Result<(), anyhow::Error> {
501        validate_id(sensitivity_ids, low_level.sensitivity(), "sensitivity")?;
502        for id in low_level.category_ids() {
503            validate_id(category_ids, id, "category")?;
504        }
505        if let Some(high) = high_level {
506            validate_id(sensitivity_ids, high.sensitivity(), "sensitivity")?;
507            for id in high.category_ids() {
508                validate_id(category_ids, id, "category")?;
509            }
510            if !high.dominates(low_level) {
511                return Err(ValidateError::InvalidMlsRange {
512                    low: low_level.serialize(self).into(),
513                    high: high.serialize(self).into(),
514                }
515                .into());
516            }
517        }
518        Ok(())
519    }
520}
521
522impl ParsedPolicy {
523    /// Parses the binary policy stored in `bytes`. It is an error for `bytes` to have trailing
524    /// bytes after policy parsing completes.
525    pub(super) fn parse(data: PolicyData) -> Result<Self, anyhow::Error> {
526        let cursor = PolicyCursor::new(data.clone());
527        let (policy, tail) = parse_policy_internal(cursor, data)?;
528        let num_bytes = tail.len();
529        if num_bytes > 0 {
530            return Err(ParseError::TrailingBytes { num_bytes }.into());
531        }
532        Ok(policy)
533    }
534}
535
536/// Parses an entire binary policy.
537fn parse_policy_internal(
538    bytes: PolicyCursor,
539    data: PolicyData,
540) -> Result<(ParsedPolicy, PolicyCursor), anyhow::Error> {
541    let tail = bytes;
542
543    let (magic, tail) = PolicyCursor::parse::<Magic>(tail).context("parsing magic")?;
544
545    let (signature, tail) =
546        Signature::parse(tail).map_err(Into::<anyhow::Error>::into).context("parsing signature")?;
547
548    let (policy_version, tail) =
549        PolicyCursor::parse::<PolicyVersion>(tail).context("parsing policy version")?;
550    let policy_version_value = policy_version.policy_version();
551
552    let (config, tail) = Config::parse(tail)
553        .map_err(Into::<anyhow::Error>::into)
554        .context("parsing policy config")?;
555
556    let (counts, tail) =
557        PolicyCursor::parse::<Counts>(tail).context("parsing high-level policy object counts")?;
558
559    let (policy_capabilities, tail) = ExtensibleBitmap::parse(tail)
560        .map_err(Into::<anyhow::Error>::into)
561        .context("parsing policy capabilities")?;
562
563    let (permissive_map, tail) = ExtensibleBitmap::parse(tail)
564        .map_err(Into::<anyhow::Error>::into)
565        .context("parsing permissive map")?;
566
567    let (common_symbols, tail) = SymbolList::<CommonSymbol>::parse(tail)
568        .map_err(Into::<anyhow::Error>::into)
569        .context("parsing common symbols")?;
570
571    let (classes, tail) = SymbolList::<Class>::parse(tail)
572        .map_err(Into::<anyhow::Error>::into)
573        .context("parsing classes")?;
574
575    let (roles, tail) = SymbolList::<Role>::parse(tail)
576        .map_err(Into::<anyhow::Error>::into)
577        .context("parsing roles")?;
578
579    let (types, tail) = SymbolList::<Type>::parse(tail)
580        .map_err(Into::<anyhow::Error>::into)
581        .context("parsing types")?;
582
583    let (users, tail) = SymbolList::<User>::parse(tail)
584        .map_err(Into::<anyhow::Error>::into)
585        .context("parsing users")?;
586
587    let (conditional_booleans, tail) = SymbolList::<ConditionalBoolean>::parse(tail)
588        .map_err(Into::<anyhow::Error>::into)
589        .context("parsing conditional booleans")?;
590
591    let (sensitivities, tail) = SymbolList::<Sensitivity>::parse(tail)
592        .map_err(Into::<anyhow::Error>::into)
593        .context("parsing sensitivites")?;
594
595    let (categories, tail) = SymbolList::<Category>::parse(tail)
596        .map_err(Into::<anyhow::Error>::into)
597        .context("parsing categories")?;
598
599    let (access_vector_rules, tail) = HashedArrayView::<le::U32, AccessVectorRule>::parse(tail)
600        .map_err(Into::<anyhow::Error>::into)
601        .context("parsing access vector rules")?;
602
603    let (conditional_lists, tail) = SimpleArray::<ConditionalNodes>::parse(tail)
604        .map_err(Into::<anyhow::Error>::into)
605        .context("parsing conditional lists")?;
606
607    let (role_transitions, tail) = RoleTransitions::parse(tail)
608        .map_err(Into::<anyhow::Error>::into)
609        .context("parsing role transitions")?;
610
611    let (role_allowlist, tail) = RoleAllows::parse(tail)
612        .map_err(Into::<anyhow::Error>::into)
613        .context("parsing role allow rules")?;
614
615    let (filename_transition_list, tail) = if policy_version_value >= 33 {
616        let (filename_transition_list, tail) = SimpleArray::<FilenameTransitions>::parse(tail)
617            .map_err(Into::<anyhow::Error>::into)
618            .context("parsing standard filename transitions")?;
619        (FilenameTransitionList::PolicyVersionGeq33(filename_transition_list), tail)
620    } else {
621        let (filename_transition_list, tail) =
622            SimpleArray::<DeprecatedFilenameTransitions>::parse(tail)
623                .map_err(Into::<anyhow::Error>::into)
624                .context("parsing deprecated filename transitions")?;
625        (FilenameTransitionList::PolicyVersionLeq32(filename_transition_list), tail)
626    };
627
628    let (initial_sids, tail) = SimpleArray::<InitialSids>::parse(tail)
629        .map_err(Into::<anyhow::Error>::into)
630        .context("parsing initial sids")?;
631
632    let (filesystems, tail) = SimpleArray::<NamedContextPairs>::parse(tail)
633        .map_err(Into::<anyhow::Error>::into)
634        .context("parsing filesystem contexts")?;
635
636    let (ports, tail) = SimpleArray::<Ports>::parse(tail)
637        .map_err(Into::<anyhow::Error>::into)
638        .context("parsing ports")?;
639
640    let (network_interfaces, tail) = SimpleArray::<NamedContextPairs>::parse(tail)
641        .map_err(Into::<anyhow::Error>::into)
642        .context("parsing network interfaces")?;
643
644    let (nodes, tail) = SimpleArray::<Nodes>::parse(tail)
645        .map_err(Into::<anyhow::Error>::into)
646        .context("parsing nodes")?;
647
648    let (fs_uses, tail) = SimpleArray::<FsUses>::parse(tail)
649        .map_err(Into::<anyhow::Error>::into)
650        .context("parsing fs uses")?;
651
652    let (ipv6_nodes, tail) = SimpleArray::<IPv6Nodes>::parse(tail)
653        .map_err(Into::<anyhow::Error>::into)
654        .context("parsing ipv6 nodes")?;
655
656    let (infinitiband_partition_keys, infinitiband_end_ports, tail) =
657        if policy_version_value >= MIN_POLICY_VERSION_FOR_INFINITIBAND_PARTITION_KEY {
658            let (infinity_band_partition_keys, tail) =
659                SimpleArray::<InfinitiBandPartitionKeys>::parse(tail)
660                    .map_err(Into::<anyhow::Error>::into)
661                    .context("parsing infiniti band partition keys")?;
662            let (infinitiband_end_ports, tail) = SimpleArray::<InfinitiBandEndPorts>::parse(tail)
663                .map_err(Into::<anyhow::Error>::into)
664                .context("parsing infiniti band end ports")?;
665            (Some(infinity_band_partition_keys), Some(infinitiband_end_ports), tail)
666        } else {
667            (None, None, tail)
668        };
669
670    let (generic_fs_contexts, tail) = SimpleArray::<GenericFsContexts>::parse(tail)
671        .map_err(Into::<anyhow::Error>::into)
672        .context("parsing generic filesystem contexts")?;
673
674    let (range_transitions, tail) = SimpleArray::<RangeTransitions>::parse(tail)
675        .map_err(Into::<anyhow::Error>::into)
676        .context("parsing range transitions")?;
677
678    let primary_names_count = types.metadata.primary_names_count();
679    let mut attribute_maps = Vec::with_capacity(primary_names_count as usize);
680    let mut tail = tail;
681
682    for i in 0..primary_names_count {
683        let (item, next_tail) = ExtensibleBitmap::parse(tail)
684            .map_err(Into::<anyhow::Error>::into)
685            .with_context(|| format!("parsing {}th attribute map", i))?;
686        attribute_maps.push(item);
687        tail = next_tail;
688    }
689    let tail = tail;
690    let attribute_maps = attribute_maps;
691
692    Ok((
693        ParsedPolicy {
694            data,
695            magic,
696            signature,
697            policy_version,
698            config,
699            counts,
700            policy_capabilities,
701            permissive_map,
702            common_symbols,
703            classes,
704            roles,
705            types,
706            users,
707            conditional_booleans,
708            sensitivities,
709            categories,
710            access_vector_rules,
711            conditional_lists,
712            role_transitions,
713            role_allowlist,
714            filename_transition_list,
715            initial_sids,
716            filesystems,
717            ports,
718            network_interfaces,
719            nodes,
720            fs_uses,
721            ipv6_nodes,
722            infinitiband_partition_keys,
723            infinitiband_end_ports,
724            generic_fs_contexts,
725            range_transitions,
726            attribute_maps,
727        },
728        tail,
729    ))
730}
731
732impl ParsedPolicy {
733    pub fn validate(&self) -> Result<(), anyhow::Error> {
734        let mut context = PolicyValidationContext { data: self.data.clone() };
735
736        self.magic
737            .validate(&mut context)
738            .map_err(Into::<anyhow::Error>::into)
739            .context("validating magic")?;
740        self.signature
741            .validate(&mut context)
742            .map_err(Into::<anyhow::Error>::into)
743            .context("validating signature")?;
744        self.policy_version
745            .validate(&mut context)
746            .map_err(Into::<anyhow::Error>::into)
747            .context("validating policy_version")?;
748        self.config
749            .validate(&mut context)
750            .map_err(Into::<anyhow::Error>::into)
751            .context("validating config")?;
752        self.counts
753            .validate(&mut context)
754            .map_err(Into::<anyhow::Error>::into)
755            .context("validating counts")?;
756        self.policy_capabilities
757            .validate(&mut context)
758            .map_err(Into::<anyhow::Error>::into)
759            .context("validating policy_capabilities")?;
760        self.permissive_map
761            .validate(&mut context)
762            .map_err(Into::<anyhow::Error>::into)
763            .context("validating permissive_map")?;
764        self.common_symbols
765            .validate(&mut context)
766            .map_err(Into::<anyhow::Error>::into)
767            .context("validating common_symbols")?;
768        self.classes
769            .validate(&mut context)
770            .map_err(Into::<anyhow::Error>::into)
771            .context("validating classes")?;
772        self.roles
773            .validate(&mut context)
774            .map_err(Into::<anyhow::Error>::into)
775            .context("validating roles")?;
776        self.types
777            .validate(&mut context)
778            .map_err(Into::<anyhow::Error>::into)
779            .context("validating types")?;
780        self.users
781            .validate(&mut context)
782            .map_err(Into::<anyhow::Error>::into)
783            .context("validating users")?;
784        self.conditional_booleans
785            .validate(&mut context)
786            .map_err(Into::<anyhow::Error>::into)
787            .context("validating conditional_booleans")?;
788        self.sensitivities
789            .validate(&mut context)
790            .map_err(Into::<anyhow::Error>::into)
791            .context("validating sensitivities")?;
792        self.categories
793            .validate(&mut context)
794            .map_err(Into::<anyhow::Error>::into)
795            .context("validating categories")?;
796        self.access_vector_rules
797            .validate(&mut context)
798            .map_err(Into::<anyhow::Error>::into)
799            .context("validating access_vector_rules")?;
800        self.conditional_lists
801            .validate(&mut context)
802            .map_err(Into::<anyhow::Error>::into)
803            .context("validating conditional_lists")?;
804        self.role_transitions
805            .validate(&mut context)
806            .map_err(Into::<anyhow::Error>::into)
807            .context("validating role_transitions")?;
808        self.role_allowlist
809            .validate(&mut context)
810            .map_err(Into::<anyhow::Error>::into)
811            .context("validating role_allowlist")?;
812        self.filename_transition_list
813            .validate(&mut context)
814            .map_err(Into::<anyhow::Error>::into)
815            .context("validating filename_transition_list")?;
816        self.initial_sids
817            .validate(&mut context)
818            .map_err(Into::<anyhow::Error>::into)
819            .context("validating initial_sids")?;
820        self.filesystems
821            .validate(&mut context)
822            .map_err(Into::<anyhow::Error>::into)
823            .context("validating filesystems")?;
824        self.ports
825            .validate(&mut context)
826            .map_err(Into::<anyhow::Error>::into)
827            .context("validating ports")?;
828        self.network_interfaces
829            .validate(&mut context)
830            .map_err(Into::<anyhow::Error>::into)
831            .context("validating network_interfaces")?;
832        self.nodes
833            .validate(&mut context)
834            .map_err(Into::<anyhow::Error>::into)
835            .context("validating nodes")?;
836        self.fs_uses
837            .validate(&mut context)
838            .map_err(Into::<anyhow::Error>::into)
839            .context("validating fs_uses")?;
840        self.ipv6_nodes
841            .validate(&mut context)
842            .map_err(Into::<anyhow::Error>::into)
843            .context("validating ipv6 nodes")?;
844        self.infinitiband_partition_keys
845            .validate(&mut context)
846            .map_err(Into::<anyhow::Error>::into)
847            .context("validating infinitiband_partition_keys")?;
848        self.infinitiband_end_ports
849            .validate(&mut context)
850            .map_err(Into::<anyhow::Error>::into)
851            .context("validating infinitiband_end_ports")?;
852        self.generic_fs_contexts
853            .validate(&mut context)
854            .map_err(Into::<anyhow::Error>::into)
855            .context("validating generic_fs_contexts")?;
856        self.range_transitions
857            .validate(&mut context)
858            .map_err(Into::<anyhow::Error>::into)
859            .context("validating range_transitions")?;
860        self.attribute_maps
861            .validate(&mut context)
862            .map_err(Into::<anyhow::Error>::into)
863            .context("validating attribute_maps")?;
864
865        // Collate the sets of user, role, type, sensitivity and category Ids.
866        let user_ids: HashSet<UserId> = self.users.data.iter().map(|x| x.id()).collect();
867        let role_ids: HashSet<RoleId> = self.roles.data.iter().map(|x| x.id()).collect();
868        let class_ids: HashSet<ClassId> = self.classes.data.iter().map(|x| x.id()).collect();
869        let type_ids: HashSet<TypeId> = self.types.data.iter().map(|x| x.id()).collect();
870        let sensitivity_ids: HashSet<SensitivityId> =
871            self.sensitivities.data.iter().map(|x| x.id()).collect();
872        let category_ids: HashSet<CategoryId> =
873            self.categories.data.iter().map(|x| x.id()).collect();
874
875        // Validate that users use only defined sensitivities and categories, and that
876        // each user's MLS levels are internally consistent (i.e., the high level
877        // dominates the low level).
878        for user in &self.users.data {
879            self.validate_mls_range(
880                user.mls_range().low(),
881                user.mls_range().high(),
882                &sensitivity_ids,
883                &category_ids,
884            )?;
885        }
886
887        // Validate that initial contexts use only defined user, role, type, etc Ids.
888        // Check that all sensitivity and category IDs are defined and that MLS levels
889        // are internally consistent.
890        for initial_sid in &self.initial_sids.data {
891            let context = initial_sid.context();
892            validate_id(&user_ids, context.user_id(), "user")?;
893            validate_id(&role_ids, context.role_id(), "role")?;
894            validate_id(&type_ids, context.type_id(), "type")?;
895            self.validate_mls_range(
896                context.low_level(),
897                context.high_level(),
898                &sensitivity_ids,
899                &category_ids,
900            )?;
901        }
902
903        // Validate that contexts specified in filesystem labeling rules only use
904        // policy-defined Ids for their fields. Check that MLS levels are internally
905        // consistent.
906        for fs_use in &self.fs_uses.data {
907            let context = fs_use.context();
908            validate_id(&user_ids, context.user_id(), "user")?;
909            validate_id(&role_ids, context.role_id(), "role")?;
910            validate_id(&type_ids, context.type_id(), "type")?;
911            self.validate_mls_range(
912                context.low_level(),
913                context.high_level(),
914                &sensitivity_ids,
915                &category_ids,
916            )?;
917        }
918
919        // Validate that roles output by role- transitions & allows are defined.
920        for transition in &self.role_transitions.data {
921            validate_id(&role_ids, transition.current_role(), "current_role")?;
922            validate_id(&type_ids, transition.type_(), "type")?;
923            validate_id(&class_ids, transition.class(), "class")?;
924            validate_id(&role_ids, transition.new_role(), "new_role")?;
925        }
926        for allow in &self.role_allowlist.data {
927            validate_id(&role_ids, allow.source_role(), "source_role")?;
928            validate_id(&role_ids, allow.new_role(), "new_role")?;
929        }
930
931        // Validate that types output by access vector rules are defined.
932        for access_vector_rule_view in self.access_vector_rules() {
933            let access_vector_rule = access_vector_rule_view.parse(&self.data);
934            if let Some(type_id) = access_vector_rule.new_type() {
935                validate_id(&type_ids, type_id, "new_type")?;
936            }
937        }
938
939        // Validate that constraints are well-formed by evaluating against
940        // a source and target security context.
941        let initial_context = SecurityContext::new_from_policy_context(
942            self.initial_context(crate::InitialSid::Kernel),
943        );
944        for class in self.classes() {
945            for constraint in class.constraints() {
946                constraint
947                    .constraint_expr()
948                    .evaluate(&initial_context, &initial_context)
949                    .map_err(Into::<anyhow::Error>::into)
950                    .context("validating constraints")?;
951            }
952        }
953
954        // To-do comments for cross-policy validations yet to be implemented go here.
955        // TODO(b/356569876): Determine which "bounds" should be verified for correctness here.
956
957        Ok(())
958    }
959}
960
961fn validate_id<IdType: Debug + Eq + Hash>(
962    id_set: &HashSet<IdType>,
963    id: IdType,
964    debug_kind: &'static str,
965) -> Result<(), anyhow::Error> {
966    if !id_set.contains(&id) {
967        return Err(ValidateError::UnknownId { kind: debug_kind, id: format!("{:?}", id) }.into());
968    }
969    Ok(())
970}