Skip to main content
coreydaley.dev

Reading a DMG in the App Sandbox without mounting it

A sandboxed Mac App Store app can’t mount a disk image. In my testing, hdiutil attach run from inside the App Sandbox fails with “Device not configured”, and hdiutil create -srcfolder is blocked the same way. Yet Purrchiver opens a .dmg like any other archive, lists its files, and extracts them. This is how it reads one without mounting it.

Split the job: Apple unwraps, my code parses

A DMG is layers. The outside is a UDIF container, a set of compressed (and possibly AES-encrypted) chunks. Inside that is a disk: usually a partition map, then a file system. Reading a file means getting through all of it.

Some hdiutil commands work fine in the sandbox, because they read and write image files instead of attaching disks. Purrchiver already used makehybrid and convert that way to create DMGs. convert can also turn a DMG into a plain raw disk image:

hdiutil convert input.dmg -format UDTO -o /tmp/raw   # writes /tmp/raw.cdr

That one command removes the container, the block compression, and, given the password, the encryption. For an image made with makehybrid, what’s left is a flat image that starts with an Apple Partition Map, followed by an HFS+ volume. The rest is parsing, which is plain file reading and needs no special access.

A small HFS+ reader

The parser is original code, a few hundred lines of Swift, written from Apple’s HFS+ technical note (TN1150). It only lists files and reads their data. It never writes. The path through the image:

  1. Partition map. Block 0 starts with ER, the driver descriptor map. The map entries follow in 512-byte blocks, each starting with PM. Find the entry whose type is Apple_HFS and read its starting block. If there’s no ER at all, assume a bare HFS+ volume at offset 0.
  2. Volume header. It’s 1,024 bytes into the volume. Check the signature (H+, or HX for case-sensitive HFSX), then read the allocation block size and the location of the catalog file: its size and its first eight extents.
  3. Catalog B-tree. Read the catalog file, take the node size and the first leaf node from the header node, and follow the leaf nodes in order. Each record’s key holds a parent folder ID and a name in big-endian UTF-16. Folder records give a folder ID. File records give the data fork’s size and its extents. Thread records can be skipped, because the keys already have the names.
  4. Paths. Build full paths by following parent IDs up to the root folder, which is always ID 2.
  5. File data. An extent is a start block and a block count. Seek to partitionStart + start × blockSize, copy in 1 MiB chunks, and stop at the file’s size.

Everything is read big-endian with a few helpers:

extension Array where Element == UInt8 {
    func be16(_ o: Int) -> UInt16 { UInt16(self[o]) << 8 | UInt16(self[o + 1]) }
    func be32(_ o: Int) -> UInt32 {
        UInt32(be16(o)) << 16 | UInt32(be16(o + 2))
    }
}

Names are converted to precomposed Unicode on the way out, so a name like café matches what you’d type, not the decomposed form stored on disk.

An image downloaded from the internet is untrusted input, so every value from the image has a limit. The catalog read is capped at 256 MB. The leaf walk stops after as many nodes as the catalog can hold. The parent-ID walk stops after 256 levels. The partition map scan is limited too. Extracted paths go through the same path-safety check Purrchiver uses for every other format, so an entry can’t write outside the folder you chose.

Never let hdiutil ask for the password

The bug I most wanted to prevent: run hdiutil convert on an encrypted image without a password, and it doesn’t fail. In my testing it brought up the system’s own password dialog, outside Purrchiver, and waited for it.

So the code checks first. hdiutil isencrypted reads only metadata and is fast. If the image is encrypted and there’s no password yet, Purrchiver stops before running convert and shows its own password prompt, the same one every other encrypted archive uses. If a password was given and convert still fails, an encrypted image means the password was wrong, and anything else is reported as a real read error.

if passphrase == nil, isEncrypted(dmg) { throw DMGError.passwordRequired }
// ...run convert...
// on failure: isEncrypted(dmg) ? .passwordIncorrect : the real error

A test checks that an encrypted image with no password returns “password required” without starting the interactive prompt. That’s the behavior a user would notice first if it broke.

Keeping the password off the command line

New in Purrchiver 1.1. If you don't see it, update Purrchiver from the App Store.

Getting the password to hdiutil turned out to be the harder problem. convert -stdinpass applies only to the image being written, not the one being read: given the right password for the source, it fails with “Authentication error”. The only option for the source’s password, -srcimagekey passphrase=…, puts it in the command’s arguments, where any other process running as the same user can read it with ps -ww. Purrchiver 1.0 did that.

1.1 opens an encrypted image through a throwaway copy instead:

  1. Clone the DMG into the app’s temporary folder. When the DMG is on the same APFS volume, usually your startup disk, a clone is instant and takes no extra space; otherwise it’s a full copy.
  2. Change the clone’s password from yours to a random one-time key with hdiutil chpass, which reads both passwords from standard input.
  3. Run convert on the clone with the one-time key.
  4. Delete the clone.

Only the one-time key ever appears in an argument list, and it unlocks nothing but a temporary copy that’s deleted when the convert finishes. Your real password, which you may use elsewhere, never does, and your own DMG is never written to. The hdiutil calls go through a single function, so a test records every argument list and checks that the password isn’t in any of them.

Limits

This reader covers what it needs to and no more:

  • HFS+ only. A DMG can contain an APFS volume instead. convert handles those, but the reader stops with an error.
  • Apple Partition Map only. hdiutil create uses a GUID partition table by default, and the reader doesn’t parse one yet, so an HFS+ image made that way doesn’t open either.
  • No HFS+ compression or resource forks. Images made with makehybrid, which is how Purrchiver creates DMGs, don’t use these. Other images can.
  • Read-only. Creating a DMG is a separate path.
  • A temporary copy. The raw image is a full-size copy in the app’s sandboxed temporary folder. It’s kept for as long as Purrchiver is reading from it, so files can be read on demand, and deleted afterwards. For an encrypted image, that copy is decrypted.

The tests cover listing and extracting plain and encrypted images, a file spanning many blocks coming out byte-for-byte, a wrong password, a missing password, and the no-prompt guarantee above.

What 1.1 fixes

New in Purrchiver 1.1. If you don't see it, update Purrchiver from the App Store.

In 1.0, a file the reader couldn’t fully handle could come out short or empty without a warning. 1.1 closes that gap:

  • Fragmented files. A file’s catalog record holds only its first eight extents; the rest are in the extents overflow file, a second B-tree. The reader now reads it when a file needs more than eight, so heavily fragmented files come out whole, and a test checks one with more than eight extents byte for byte.
  • Hard links. HFS+ stores a hard-linked file once, in a hidden folder, and each link is a small placeholder pointing to it. The reader now follows the placeholder to the real data, and the hidden folders and journal files are no longer listed.
  • Compressed files are read. A file with HFS+ compression has an empty data fork; its data is in a decmpfs extended attribute, or in the resource fork for larger files. Update, October 21: when I wrote this, 1.1 only named those files and left them out. It now decodes them, with Apple’s Compression framework: zlib, LZVN and LZFSE, inline or in resource-fork chunks. A disk image of an installed app is full of them. A kind it doesn’t know, or data that doesn’t decode to the right size, is still left out by name, and the rest of the image extracts. A folder hard link is named and left out too.
  • A final check. If a file’s extents run out before its size says they should, extraction fails with an error instead of writing a short file.

What to take away

  • In the sandbox, hdiutil commands that only read and write image files work. The ones that attach a disk don’t.
  • hdiutil convert -format UDTO turns any DMG it can open into a plain image you can parse yourself.
  • Reading HFS+ for listing and extraction is a few hundred lines before compression. TN1150 has everything you need; for compressed files, the decmpfs header in the attributes B-tree says where the data is and how it’s packed.
  • Check for encryption before calling a tool that might prompt.
  • A password in a command’s arguments is visible to other processes. If a tool reads it from standard input for only some operations, route the work through one of those, even if it means working on a copy.

Related posts