Skip to main content

selinux/policy/
view.rs

1// Copyright 2025 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 super::arrays::SimpleArrayView;
6use super::parser::{PolicyCursor, PolicyData, PolicyOffset};
7use super::{Counted, Parse, PolicyValidationContext, Validate};
8
9use hashbrown::hash_table::HashTable;
10use rapidhash::RapidHasher;
11use static_assertions::const_assert;
12use std::fmt::Debug;
13use std::hash::{Hash, Hasher};
14use std::marker::PhantomData;
15use zerocopy::{FromBytes, Immutable, KnownLayout, Unaligned, little_endian as le};
16
17/// A trait for types that have metadata.
18///
19/// Many policy objects have a fixed-sized metadata section that is much faster to parse than the
20/// full object. This trait is used when walking the binary policy to find objects of interest
21/// efficiently.
22pub trait HasMetadata {
23    /// The Rust type that represents the metadata.
24    type Metadata: FromBytes + Sized;
25}
26
27/// A trait for types that can be walked through the policy data.
28///
29/// This trait is used when walking the binary policy to find objects of interest efficiently.
30pub trait Walk {
31    /// Walks the policy data to the next object of the given type.
32    ///
33    /// Returns an error if the cursor cannot be walked to the next object of the given type.
34    fn walk(policy_data: &PolicyData, offset: PolicyOffset) -> PolicyOffset;
35}
36
37/// A view into a policy object.
38///
39/// This struct contains the start and end offsets of the object in the policy data. To read the
40/// object, use [`View::read`].
41#[derive(Debug, Clone, Copy)]
42pub struct View<T> {
43    phantom: PhantomData<T>,
44
45    /// The start offset of the object in the policy data.
46    start: PolicyOffset,
47
48    /// The end offset of the object in the policy data.
49    end: PolicyOffset,
50}
51
52impl<T> View<T> {
53    /// Creates a new view from the start and end offsets.
54    pub fn new(start: PolicyOffset, end: PolicyOffset) -> Self {
55        Self { phantom: PhantomData, start, end }
56    }
57
58    /// The start offset of the object in the policy data.
59    fn start(&self) -> PolicyOffset {
60        self.start
61    }
62}
63
64impl<T: Sized> View<T> {
65    /// Creates a new view at the given start offset.
66    ///
67    /// The end offset is calculated as the start offset plus the size of the object.
68    pub fn at(start: PolicyOffset) -> Self {
69        let end = start + std::mem::size_of::<T>() as u32;
70        Self::new(start, end)
71    }
72}
73
74impl<T: FromBytes + Sized> View<T> {
75    /// Reads the object from the policy data.
76    ///
77    /// This function requires the object to have a fixed size and simply copies the object from
78    /// the policy data.
79    ///
80    /// For variable-sized objects, use [`View::parse`] instead.
81    pub fn read(&self, policy_data: &PolicyData) -> T {
82        debug_assert_eq!(self.end - self.start, std::mem::size_of::<T>() as u32);
83        let start = self.start as usize;
84        let end = self.end as usize;
85        T::read_from_bytes(&policy_data[start..end]).unwrap()
86    }
87}
88
89impl<T: HasMetadata> View<T> {
90    /// Returns a view into the metadata of the object.
91    ///
92    /// Assumes the metadata is at the start of the object.
93    pub fn metadata(&self) -> View<T::Metadata> {
94        View::<T::Metadata>::at(self.start)
95    }
96
97    /// Reads the metadata from the policy data.
98    pub fn read_metadata(&self, policy_data: &PolicyData) -> T::Metadata {
99        self.metadata().read(policy_data)
100    }
101}
102
103impl<T: Parse> View<T> {
104    /// Parses the object from the policy data.
105    ///
106    /// This function uses the [`Parse`] trait to parse the object from the policy data.
107    ///
108    /// If the object has a fixed size, prefer [`View::read`] instead.
109    pub fn parse(&self, policy_data: &PolicyData) -> T {
110        let cursor = PolicyCursor::new_at(policy_data, self.start);
111        let (object, _) =
112            T::parse(cursor).map_err(Into::<anyhow::Error>::into).expect("policy should be valid");
113        object
114    }
115}
116
117impl<T: Validate + Parse> Validate for View<T> {
118    type Error = anyhow::Error;
119
120    fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
121        let object = self.parse(&context.data);
122        object.validate(context).map_err(Into::<anyhow::Error>::into)
123    }
124}
125
126/// A view into the data of an array of objects.
127///
128/// This struct contains the start offset of the array and the number of objects in the array.
129/// To iterate over the objects, use [`ArrayDataView::iter`].
130#[derive(Debug, Clone, Copy)]
131pub struct ArrayDataView<D> {
132    phantom: PhantomData<D>,
133    start: PolicyOffset,
134    count: u32,
135}
136
137impl<D> ArrayDataView<D> {
138    /// Creates a new array data view from the start offset and count.
139    pub fn new(start: PolicyOffset, count: u32) -> Self {
140        Self { phantom: PhantomData, start, count }
141    }
142
143    /// Iterates over the objects in the array.
144    ///
145    /// The iterator returns views into the objects in the array.
146    ///
147    /// This function requires the policy data to be provided to the iterator because objects in
148    /// the array may have variable size.
149    pub fn iter(self, policy_data: &PolicyData) -> ArrayDataViewIter<D> {
150        ArrayDataViewIter::new(policy_data.clone(), self.start, self.count)
151    }
152}
153
154/// An iterator over the objects in an array.
155///
156/// This struct contains the cursor to the start of the array and the number of objects remaining
157/// to be iterated over.
158pub struct ArrayDataViewIter<D> {
159    phantom: PhantomData<D>,
160    policy_data: PolicyData,
161    offset: PolicyOffset,
162    remaining: u32,
163}
164
165impl<T> ArrayDataViewIter<T> {
166    /// Creates a new array data view iterator from the start cursor and remaining count.
167    fn new(policy_data: PolicyData, offset: PolicyOffset, remaining: u32) -> Self {
168        Self { phantom: PhantomData, policy_data, offset, remaining }
169    }
170}
171
172impl<D: Walk> std::iter::Iterator for ArrayDataViewIter<D> {
173    type Item = View<D>;
174
175    fn next(&mut self) -> Option<Self::Item> {
176        if self.remaining > 0 {
177            let start = self.offset;
178            self.offset = D::walk(&self.policy_data, start);
179            self.remaining -= 1;
180            Some(View::new(start, self.offset))
181        } else {
182            None
183        }
184    }
185}
186
187/// A view into the data of an array of objects.
188///
189/// This struct contains the start offset of the array and the number of objects in the array.
190/// To access the objects in the array, use [`ArrayView::data`].
191#[derive(Debug, Clone, Copy)]
192pub(super) struct ArrayView<M, D> {
193    phantom: PhantomData<(M, D)>,
194    start: PolicyOffset,
195    count: u32,
196}
197
198impl<M, D> ArrayView<M, D> {
199    /// Creates a new array view from the start offset and count.
200    pub fn new(start: PolicyOffset, count: u32) -> Self {
201        Self { phantom: PhantomData, start, count }
202    }
203}
204
205impl<M: Sized, D> ArrayView<M, D> {
206    /// Returns a view into the metadata of the array.
207    pub fn metadata(&self) -> View<M> {
208        View::<M>::at(self.start)
209    }
210
211    /// Returns a view into the data of the array.
212    pub fn data(&self) -> ArrayDataView<D> {
213        ArrayDataView::new(self.metadata().end, self.count)
214    }
215}
216
217fn parse_array_data<'a, D: Parse>(
218    cursor: PolicyCursor<'a>,
219    count: u32,
220) -> Result<PolicyCursor<'a>, anyhow::Error> {
221    let mut tail = cursor;
222    for _ in 0..count {
223        let (_, next) = D::parse(tail).map_err(Into::<anyhow::Error>::into)?;
224        tail = next;
225    }
226    Ok(tail)
227}
228
229impl<M: Counted + Parse + Sized, D: Parse> Parse for ArrayView<M, D> {
230    /// [`ArrayView`] abstracts over two types (`M` and `D`) that may have different [`Parse::Error`]
231    /// types. Unify error return type via [`anyhow::Error`].
232    type Error = anyhow::Error;
233
234    fn parse<'a>(cursor: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error> {
235        let start = cursor.offset();
236        let (metadata, cursor) = M::parse(cursor).map_err(Into::<anyhow::Error>::into)?;
237        let count = metadata.count();
238        let cursor = parse_array_data::<D>(cursor, count)?;
239        Ok((Self::new(start, count), cursor))
240    }
241}
242
243/// A trait for types that can be used as keys in a hash table.
244///
245/// This trait is used by [`HashedBlocksView`] to store and retrieve values.
246pub(super) trait Hashable {
247    type Key: Parse + Hash + Eq;
248    type Value: Parse + Walk;
249
250    /// Returns a reference to the key.
251    fn key(&self) -> &Self::Key;
252
253    /// Returns a [`SimpleArrayView`] into the values.
254    fn values(&self) -> &SimpleArrayView<Self::Value>;
255}
256
257/// Stores an mapping from a [`D::Key`] to a set of [`D::Value`]s
258#[derive(Debug, Clone)]
259pub(super) struct CustomKeyHashedView<D: Hashable> {
260    /// Stores the offset to D::Key.
261    index: HashTable<PolicyOffset>,
262    _phantom: PhantomData<D>,
263}
264
265impl<D: Hashable + Parse> CustomKeyHashedView<D> {
266    /// Returns an iterator over the entries with the specified `key` and parses and
267    /// emits those values.
268    pub(super) fn find_all(
269        &self,
270        query_key: D::Key,
271        policy_data: &PolicyData,
272    ) -> impl Iterator<Item = D::Value> {
273        let key_offset = self.index.find(compute_hash(&query_key), |&key_offset| {
274            let cursor = PolicyCursor::new_at(policy_data, key_offset);
275            let (key, _) = D::Key::parse(cursor)
276                .map_err(Into::<anyhow::Error>::into)
277                .expect("policy should be valid");
278
279            key == query_key
280        });
281
282        key_offset.into_iter().flat_map(move |&key_offset| {
283            let cursor = PolicyCursor::new_at(policy_data, key_offset);
284            let (entry, _) = D::parse(cursor)
285                .map_err(Into::<anyhow::Error>::into)
286                .expect("policy should be valid");
287
288            entry.values().data().iter(policy_data).map(move |v| v.parse(policy_data))
289        })
290    }
291}
292
293fn compute_hash<V: Hash>(val: &V) -> u64 {
294    let mut hasher = RapidHasher::default();
295    val.hash(&mut hasher);
296    hasher.finish()
297}
298
299impl<D: Hashable + Parse> Parse for CustomKeyHashedView<D> {
300    type Error = anyhow::Error;
301
302    /// Parses (D::Key, SimpleArrayView<D::Value>) entries and stores the keys into a CustomKeyHashedView.
303    fn parse<'a>(cursor: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error> {
304        // Parse the count of entries.
305        let (metadata, cursor) = le::U32::parse(cursor).map_err(Into::<anyhow::Error>::into)?;
306        let count = metadata.count();
307
308        // The index will store [`count`] entries. Reserve the necessary capacity ahead to avoid resizing later on.
309        let mut index = HashTable::with_capacity(count as usize);
310
311        let mut key_offset = cursor.offset();
312        let mut tail = cursor;
313        for _ in 0..count {
314            let (entry, next) = D::parse(tail).map_err(Into::<anyhow::Error>::into)?;
315            tail = next;
316
317            let key: &D::Key = entry.key();
318            index.insert_unique(compute_hash(&key), key_offset, |&key_offset| {
319                let policy_cursor = PolicyCursor::new_at(tail.data(), key_offset);
320                let (key, _) = D::Key::parse(policy_cursor)
321                    .map_err(Into::<anyhow::Error>::into)
322                    .expect("policy should be valid");
323                compute_hash::<D::Key>(&key)
324            });
325            key_offset = tail.offset();
326        }
327
328        Ok((Self { _phantom: PhantomData, index }, tail))
329    }
330}
331
332impl<D: Hashable + Parse> Validate for CustomKeyHashedView<D>
333where
334    SimpleArrayView<D::Value>: Validate<Error = anyhow::Error>,
335{
336    type Error = anyhow::Error;
337
338    fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
339        for key_offset in self.index.iter() {
340            let cursor = PolicyCursor::new_at(&context.data, *key_offset);
341            let (entry, _) = D::parse(cursor).map_err(Into::<anyhow::Error>::into)?;
342
343            entry.values().validate(context)?;
344        }
345        Ok(())
346    }
347}
348
349/// An iterator giving views of the objects in the underlying [`policy_data`] found from
350/// a single entry of a `HashedArrayView`.
351struct HashedArrayViewEntryIter<'a, D: HasMetadata> {
352    policy_data: &'a PolicyData,
353    limit: PolicyOffset,
354    metadata: D::Metadata,
355    offset: Option<PolicyOffset>,
356}
357
358/// An unsigned integer in the range [0, 0x1000000) stored in three unaligned bytes.
359//
360// TODO: https://fxbug.dev/479180246 - it would be better to get this type from a library
361// somewhere. Probably not https://docs.rs/u24 (because of "The type has the same size,
362// alignment, and memory layout as a little-endian encoded u32" in that implementation's
363// specification). But maybe from somewhere else?
364#[derive(Clone, Copy, Debug, KnownLayout, FromBytes, Immutable, PartialEq, Unaligned)]
365#[repr(C, packed)]
366pub(super) struct U24 {
367    low: u8,
368    middle: u8,
369    high: u8,
370}
371
372// U24's space-efficiency is its reason for existence.
373const_assert!(std::mem::size_of::<U24>() == 3);
374const_assert!(std::mem::align_of::<U24>() == 1);
375
376impl U24 {
377    /// The zero value.
378    pub const ZERO: Self = Self { low: 0, middle: 0, high: 0 };
379}
380
381impl TryFrom<u32> for U24 {
382    type Error = ();
383
384    fn try_from(value: u32) -> Result<Self, Self::Error> {
385        if 0x1000000 <= value {
386            Err(())
387        } else {
388            Ok(Self {
389                low: (value & 0xff) as u8,
390                middle: ((value >> 8) & 0xff) as u8,
391                high: ((value >> 16) & 0xff) as u8,
392            })
393        }
394    }
395}
396
397impl From<U24> for u32 {
398    fn from(value: U24) -> u32 {
399        ((value.high as u32) << 16) + ((value.middle as u32) << 8) + (value.low as u32)
400    }
401}
402
403impl<'a, D: HasMetadata + Walk> Iterator for HashedArrayViewEntryIter<'a, D>
404where
405    D::Metadata: Eq,
406{
407    type Item = View<D>;
408
409    fn next(&mut self) -> Option<Self::Item> {
410        if let Some(offset) = self.offset
411            && offset < self.limit
412        {
413            let element = View::<D>::at(offset);
414            let metadata = element.read_metadata(&self.policy_data);
415            if metadata == self.metadata {
416                self.offset = Some(D::walk(&self.policy_data, offset));
417                Some(element)
418            } else {
419                self.offset = None;
420                None
421            }
422        } else {
423            None
424        }
425    }
426}
427
428/// A view into the data of an array of objects, with efficient lookup based on metadata hash.
429///
430/// This struct contains only a vector of offsets into the policy data, to allow efficient lookup
431/// of vector elements with matching metadata.
432#[derive(Debug, Clone)]
433pub(super) struct HashedArrayView<D: HasMetadata> {
434    phantom: PhantomData<D>,
435    index: HashTable<U24>,
436    /// The offset in the policy data at which the elements indexed by this [`HashedArrayView`]
437    /// end. Iteration of elements by this [`HashedArrayView`] must not look for an element at
438    /// or beyond this offset.
439    limit: PolicyOffset,
440}
441
442impl<D: HasMetadata> HashedArrayView<D>
443where
444    D::Metadata: Hash,
445{
446    fn metadata_hash(metadata: &D::Metadata) -> u64 {
447        let mut hasher = RapidHasher::default();
448        metadata.hash(&mut hasher);
449        hasher.finish()
450    }
451}
452
453impl<D: Parse + HasMetadata + Walk> HashedArrayView<D>
454where
455    D::Metadata: Eq + PartialEq + Hash + Debug,
456{
457    /// Looks up the entry with the specified metadata `key`, and parses and returns the value.
458    /// This method is only appropriate to call when expecting to find at most one entry for
459    /// `key`; if there is a possibility of more than one element in the underlying
460    /// `policy_data` being associated with `key`, call `find_all` instead.
461    pub fn find(&self, key: D::Metadata, policy_data: &PolicyData) -> Option<D> {
462        let key_hash = Self::metadata_hash(&key);
463        let offset = self.index.find(key_hash, |&offset| {
464            let element = View::<D>::at(u32::from(offset));
465            key == element.read_metadata(policy_data)
466        })?;
467        let element = View::<D>::at(u32::from(*offset));
468        Some(element.parse(policy_data))
469    }
470
471    /// Returns an iterator over the entries with the specified metadata `key` and parses and
472    /// emits those values.
473    pub(super) fn find_all(
474        &self,
475        key: D::Metadata,
476        policy_data: &PolicyData,
477    ) -> impl Iterator<Item = D> {
478        let key_hash = Self::metadata_hash(&key);
479        let offset = self.index.find(key_hash, |&offset| {
480            let element = View::<D>::at(u32::from(offset));
481            key == element.read_metadata(policy_data)
482        });
483        (HashedArrayViewEntryIter {
484            policy_data: policy_data,
485            limit: self.limit,
486            metadata: key,
487            offset: offset.map(|offset| u32::from(*offset)),
488        })
489        .map(|element| element.parse(policy_data))
490    }
491
492    /// Returns an iterator that emits a view for each reachable element.
493    pub(super) fn iter(&self, policy_data: &PolicyData) -> impl Iterator<Item = View<D>> {
494        self.index
495            .iter()
496            .map(|offset| {
497                let element = View::<D>::at(u32::from(*offset));
498                HashedArrayViewEntryIter {
499                    policy_data: policy_data,
500                    limit: self.limit,
501                    metadata: element.read_metadata(policy_data),
502                    offset: Some(u32::from(*offset)),
503                }
504            })
505            .flatten()
506    }
507}
508
509impl<D: Parse + HasMetadata + Walk> Parse for HashedArrayView<D>
510where
511    D::Metadata: Eq + Debug + PartialEq + Parse + Hash,
512{
513    type Error = anyhow::Error;
514
515    fn parse<'a>(cursor: PolicyCursor<'a>) -> Result<(Self, PolicyCursor<'a>), Self::Error> {
516        let (array_view, cursor) = SimpleArrayView::<D>::parse(cursor)?;
517
518        // Allocate a hash table sized appropriately for the array size.
519        let mut index = HashTable::with_capacity(array_view.count as usize);
520
521        // Record the offset at which the last array element ends.
522        let limit = cursor.offset();
523
524        // Iterate over the elements inserting the first offset at which each is
525        // seen into a hash bucket.
526        for view in array_view.data().iter(cursor.data()) {
527            let metadata = view.read_metadata(cursor.data());
528
529            index
530                .entry(
531                    Self::metadata_hash(&metadata),
532                    |&offset| {
533                        let element = View::<D>::at(u32::from(offset));
534                        metadata == element.read_metadata(cursor.data())
535                    },
536                    |&offset| {
537                        let element = View::<D>::at(u32::from(offset));
538                        Self::metadata_hash(&element.read_metadata(cursor.data()))
539                    },
540                )
541                .or_insert(U24::try_from(view.start()).expect("Policy offsets ought fit in U24!"));
542        }
543
544        Ok((Self { phantom: PhantomData, index, limit }, cursor))
545    }
546}
547
548impl<D: Validate + Parse + HasMetadata + Walk> Validate for HashedArrayView<D>
549where
550    D::Metadata: Eq,
551{
552    type Error = anyhow::Error;
553
554    fn validate(&self, context: &PolicyValidationContext) -> Result<(), Self::Error> {
555        let policy_data = context.data.clone();
556        for element in self
557            .index
558            .iter()
559            .map(|offset| {
560                let element = View::<D>::at(u32::from(*offset));
561                HashedArrayViewEntryIter::<D> {
562                    policy_data: &policy_data,
563                    limit: self.limit,
564                    metadata: element.read_metadata(&policy_data),
565                    offset: Some(u32::from(*offset)),
566                }
567            })
568            .flatten()
569        {
570            element.validate(context)?;
571        }
572
573        Ok(())
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::U24;
580
581    #[test]
582    fn to_and_from_u24() {
583        for i in 0u32..0x10000 {
584            let u24_result = U24::try_from(i);
585            assert!(u24_result.is_ok());
586            let u24 = u24_result.unwrap();
587            assert_eq!(i >> 16, u24.high as u32);
588            assert_eq!((i >> 8) & 0xff, u24.middle as u32);
589            assert_eq!(i & 0xff, u24.low as u32);
590            let j = u32::from(u24);
591            assert_eq!(i, j);
592        }
593
594        assert!(U24::try_from(0x1000000).is_err());
595    }
596}