Skip to main content

dylex/kernelcache/
mod.rs

1//! Kernelcache parsing, search, and extraction.
2//!
3//! Supports Mach-O kernel collections (`MH_FILESET`) and legacy prelinked
4//! kernels (`MH_EXECUTE` with `__PRELINK_INFO`), either raw or wrapped in IMG4
5//! or IM4P containers and compressed with LZFSE or complzss.
6//!
7//! File offsets in fileset members are collection-relative. Legacy prelinked
8//! kexts use image-relative offsets and are located through prelink metadata.
9//! Extracted images retain unslid virtual addresses and are intended for
10//! static analysis.
11//!
12//! # Example
13//!
14//! ```no_run
15//! use dylex::KernelCacheContext;
16//!
17//! fn main() -> dylex::Result<()> {
18//!     let cache = KernelCacheContext::open("kernelcache.release.mac16j")?;
19//!     let sandbox = cache.resolve_image("com.apple.security.sandbox")?;
20//!     std::fs::write("sandbox.macho", cache.extract_image(sandbox)?)?;
21//!     Ok(())
22//! }
23//! ```
24
25mod compression;
26mod container;
27mod discovery;
28mod extract;
29mod fileset;
30mod fixups;
31mod lookup;
32mod prelink;
33mod reader;
34mod strings;
35
36pub use compression::Compression;
37pub use container::Container;
38pub use discovery::{
39    CollectionIdentity, DiscoveryCommand, KernelCandidate, KernelDiscoveryReport, KernelUuid,
40    discover_kernelcaches,
41};
42
43use std::collections::HashSet;
44use std::fmt;
45use std::fs;
46use std::path::Path;
47use std::sync::OnceLock;
48
49use crate::error::{Error, Result};
50use crate::macho::{MH_EXECUTE, MH_FILESET, MH_MAGIC, MH_MAGIC_64, MachOContext, SegmentInfo};
51
52use fixups::Rebase;
53use reader::{read_u32, slice, to_usize};
54
55/// Upper bound on input, decoded, and extracted image sizes (1 GiB).
56const MAX_SIZE: usize = 1 << 30;
57
58/// Size of `mach_header` and `mach_header_64`.
59const MACH_HEADER_SIZE: usize = 28;
60const MACH_HEADER_64_SIZE: usize = 32;
61/// Offset of `sizeofcmds` in either Mach-O header.
62const SIZEOFCMDS_OFFSET: usize = 20;
63
64/// Image ID of the kernel itself.
65pub const KERNEL_IMAGE_ID: &str = "com.apple.kernel";
66
67/// Segment whose data is shared collection metadata rather than image contents.
68const LINKEDIT_SEGMENT: &str = "__LINKEDIT";
69
70// =============================================================================
71// Public Types
72// =============================================================================
73
74/// Layout of a decoded kernelcache.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum KernelCacheFormat {
77    /// An `MH_FILESET` kernel collection with one `LC_FILESET_ENTRY` per image.
78    Fileset,
79    /// An `MH_EXECUTE` kernel whose kexts are described by `__PRELINK_INFO`.
80    Prelinked,
81}
82
83impl fmt::Display for KernelCacheFormat {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str(match self {
86            Self::Fileset => "fileset (MH_FILESET)",
87            Self::Prelinked => "prelinked (MH_EXECUTE)",
88        })
89    }
90}
91
92/// Container and compression removed while decoding the input.
93#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
94pub struct InputEncoding {
95    /// IMG4 or IM4P wrapper, if any.
96    pub container: Option<Container>,
97    /// Payload compression, if any.
98    pub compression: Option<Compression>,
99}
100
101/// The kernel or an executable kext embedded in a kernelcache.
102///
103/// Codeless prelink records are not represented.
104#[derive(Debug)]
105pub struct KernelImage {
106    /// Fileset entry ID or `CFBundleIdentifier`; the kernel is [`KERNEL_IMAGE_ID`].
107    pub id: String,
108    /// Unslid address of the embedded Mach-O header.
109    pub address: u64,
110    /// Offset of the embedded Mach-O header in the decoded collection.
111    pub file_offset: u64,
112    /// Parsed header and load commands. Segment contents remain in the collection.
113    pub macho: MachOContext,
114    offset_base: OffsetBase,
115}
116
117/// How the file offsets in an image's load commands are interpreted.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119enum OffsetBase {
120    /// Offsets are relative to the start of the collection (fileset members and the kernel).
121    Collection,
122    /// Offsets are relative to the image's own Mach-O header (legacy prelinked kexts).
123    Image,
124}
125
126impl KernelImage {
127    /// Returns the segment, other than `__LINKEDIT`, whose VM range contains `address`.
128    pub fn segment_containing(&self, address: u64) -> Option<&SegmentInfo> {
129        self.macho
130            .segments()
131            .find(|segment| segment.name() != LINKEDIT_SEGMENT && vm_contains(segment, address))
132    }
133
134    /// The image header's file offset, expressed in the image's own offset space.
135    fn local_header_offset(&self) -> u64 {
136        match self.offset_base {
137            OffsetBase::Collection => self.file_offset,
138            OffsetBase::Image => 0,
139        }
140    }
141}
142
143/// A decoded kernelcache with validated embedded Mach-O headers.
144#[derive(Debug)]
145pub struct KernelCacheContext {
146    /// Decoded collection bytes.
147    data: Vec<u8>,
148    encoding: InputEncoding,
149    /// Outer Mach-O header and load commands.
150    pub macho: MachOContext,
151    /// The kernel and executable kexts, in container order.
152    pub images: Vec<KernelImage>,
153    /// Chained-fixup targets for the whole collection, decoded on first use.
154    /// Errors are stored as `(offset, reason)` because [`Error`] is not `Clone`.
155    rebases: OnceLock<std::result::Result<Vec<Rebase>, (usize, String)>>,
156}
157
158// =============================================================================
159// Opening and Validation
160// =============================================================================
161
162impl KernelCacheContext {
163    /// Opens a raw Mach-O, IMG4/IM4P, LZFSE, or complzss kernelcache.
164    ///
165    /// Encrypted payloads must be decrypted before opening.
166    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
167        let path = path.as_ref();
168        if fs::metadata(path)?.len() > MAX_SIZE as u64 {
169            return Err(Error::parse(0, "kernelcache input exceeds 1 GiB"));
170        }
171        Self::from_vec(fs::read(path)?)
172    }
173
174    /// Parses a kernelcache from bytes, removing any supported wrapper or compression.
175    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
176        Self::from_vec(bytes.to_vec())
177    }
178
179    fn from_vec(input: Vec<u8>) -> Result<Self> {
180        if input.len() > MAX_SIZE {
181            return Err(Error::parse(0, "kernelcache input exceeds 1 GiB"));
182        }
183        let (data, encoding) = decode_input(input)?;
184        let macho = parse_macho_at(&data, 0)?;
185        for segment in macho.segments() {
186            check_segment_extent(segment, "outer")?;
187            let command = &segment.command;
188            if command.filesize != 0 {
189                slice(
190                    &data,
191                    to_usize(command.fileoff)?,
192                    to_usize(command.filesize)?,
193                )?;
194            }
195        }
196        let images = match macho.header.filetype {
197            MH_FILESET => fileset::read_images(&data, &macho)?,
198            MH_EXECUTE if macho.segment(prelink::PRELINK_INFO_SEGMENT).is_some() => {
199                prelink::read_images(&data, &macho)?
200            }
201            _ => {
202                return Err(Error::parse(
203                    0,
204                    "expected MH_FILESET or a prelinked MH_EXECUTE kernel",
205                ));
206            }
207        };
208        let cache = Self {
209            data,
210            encoding,
211            macho,
212            images,
213            rebases: OnceLock::new(),
214        };
215        cache.validate_images()?;
216        Ok(cache)
217    }
218
219    /// Checks image IDs, CPU types, and segment and section extents.
220    fn validate_images(&self) -> Result<()> {
221        let mut ids = HashSet::with_capacity(self.images.len());
222        for image in &self.images {
223            if !ids.insert(image.id.as_str()) {
224                return Err(Error::parse(
225                    0,
226                    format!("duplicate kernelcache image ID {:?}", image.id),
227                ));
228            }
229            if image.macho.header.cputype != self.macho.header.cputype {
230                return Err(Error::parse(0, "embedded CPU type differs from collection"));
231            }
232            for segment in image.macho.segments() {
233                check_segment_extent(segment, "member")?;
234                let command = &segment.command;
235                for section in &segment.sections {
236                    let within_segment = section
237                        .section
238                        .addr
239                        .checked_sub(command.vmaddr)
240                        .and_then(|start| start.checked_add(section.section.size))
241                        .is_some_and(|end| end <= command.vmsize);
242                    if section.section.size != 0 && !within_segment {
243                        return Err(Error::parse(
244                            section.struct_offset,
245                            "section extends beyond segment VM range",
246                        ));
247                    }
248                }
249                if command.filesize != 0 {
250                    self.member_bytes(image, command.fileoff, command.filesize)?;
251                }
252            }
253        }
254        Ok(())
255    }
256}
257
258/// Removes an IMG4/IM4P wrapper and LZFSE or complzss compression, if present.
259fn decode_input(input: Vec<u8>) -> Result<(Vec<u8>, InputEncoding)> {
260    let (container, payload) = match container::unwrap(&input)? {
261        Some((container, payload)) => (Some(container), payload),
262        None => (None, input.as_slice()),
263    };
264    let compression = Compression::detect(payload);
265    let encoding = InputEncoding {
266        container,
267        compression,
268    };
269    let data = match compression {
270        Some(compression) => compression.decompress(payload)?,
271        None if container.is_some() => payload.to_vec(),
272        None => input,
273    };
274    Ok((data, encoding))
275}
276
277/// Parses the Mach-O header and load commands at `offset`.
278///
279/// Only the header and its commands are copied; segment contents stay in `data`.
280fn parse_macho_at(data: &[u8], offset: usize) -> Result<MachOContext> {
281    let header_size = match read_u32(data, offset)? {
282        MH_MAGIC => MACH_HEADER_SIZE,
283        MH_MAGIC_64 => MACH_HEADER_64_SIZE,
284        magic => return Err(Error::InvalidMachoMagic(magic)),
285    };
286    let header = slice(data, offset, header_size)?;
287    let commands_size = read_u32(header, SIZEOFCMDS_OFFSET)? as usize;
288    let macho = MachOContext::new(slice(data, offset, header_size + commands_size)?, offset)?;
289    let parsed_size: usize = macho
290        .load_commands
291        .iter()
292        .map(|command| command.size() as usize)
293        .sum();
294    if parsed_size != commands_size {
295        return Err(Error::parse(offset, "load command count and size disagree"));
296    }
297    Ok(macho)
298}
299
300/// Rejects segments whose VM range overflows or whose file size exceeds their VM size.
301fn check_segment_extent(segment: &SegmentInfo, scope: &str) -> Result<()> {
302    let command = &segment.command;
303    if command.vmaddr.checked_add(command.vmsize).is_none() {
304        return Err(Error::parse(
305            0,
306            format!("{scope} segment {} VM range overflow", segment.name()),
307        ));
308    }
309    if command.filesize > command.vmsize {
310        return Err(Error::parse(
311            0,
312            format!(
313                "{scope} segment {} file size exceeds VM size",
314                segment.name()
315            ),
316        ));
317    }
318    Ok(())
319}
320
321/// Returns whether `address` lies in the segment's VM range.
322fn vm_contains(segment: &SegmentInfo, address: u64) -> bool {
323    address
324        .checked_sub(segment.command.vmaddr)
325        .is_some_and(|delta| delta < segment.command.vmsize)
326}
327
328// =============================================================================
329// Accessors
330// =============================================================================
331
332impl KernelCacheContext {
333    /// Layout of the decoded collection.
334    pub fn format(&self) -> KernelCacheFormat {
335        if self.macho.header.filetype == MH_FILESET {
336            KernelCacheFormat::Fileset
337        } else {
338            KernelCacheFormat::Prelinked
339        }
340    }
341
342    /// Container and compression removed while decoding.
343    pub fn encoding(&self) -> InputEncoding {
344        self.encoding
345    }
346
347    /// Architecture recorded in the outer Mach-O header.
348    pub fn architecture(&self) -> &str {
349        self.macho.header.arch_name()
350    }
351
352    /// Size of the decoded collection in bytes.
353    pub fn total_size(&self) -> usize {
354        self.data.len()
355    }
356
357    /// Resolves an exact image ID, then a unique substring.
358    ///
359    /// Ambiguity is an error listing the candidates; the first match is never
360    /// chosen silently.
361    pub fn resolve_image(&self, query: &str) -> Result<&KernelImage> {
362        if let Some(image) = self.images.iter().find(|image| image.id == query) {
363            return Ok(image);
364        }
365        let candidates: Vec<_> = self
366            .images
367            .iter()
368            .filter(|image| image.id.contains(query))
369            .collect();
370        match candidates.as_slice() {
371            [image] => Ok(image),
372            [] => Err(Error::ImageNotFound { name: query.into() }),
373            _ => Err(Error::AmbiguousImage {
374                query: query.into(),
375                candidates: candidates.iter().map(|image| image.id.clone()).collect(),
376            }),
377        }
378    }
379
380    /// Maps an offset from an image's load commands to a collection offset.
381    fn member_offset(&self, image: &KernelImage, offset: u64) -> Result<usize> {
382        let offset = match image.offset_base {
383            OffsetBase::Collection => Some(offset),
384            OffsetBase::Image => offset.checked_add(image.file_offset),
385        };
386        to_usize(offset.ok_or_else(|| Error::parse(0, "member file offset overflow"))?)
387    }
388
389    /// Returns `size` bytes at an offset taken from an image's load commands.
390    fn member_bytes(&self, image: &KernelImage, offset: u64, size: u64) -> Result<&[u8]> {
391        slice(
392            &self.data,
393            self.member_offset(image, offset)?,
394            to_usize(size)?,
395        )
396    }
397}