img4

package
v0.0.0-prerelease Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2025 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ACI Types
	IM4P_ACIBT   = "acib" // ACI Bluetooth
	IM4P_ACIWIFI = "aciw" // ACI WiFi

	// Firmware Types
	IM4P_ALAMO             = "almo" // Alamo
	IM4P_ANE_FIRMWARE      = "anef" // ANE Firmware
	IM4P_AOP               = "aopf" // Always on processor firmware
	IM4P_ANS_FIRMWARE      = "ansf" // Apple NVME Storage controller firmware
	IM4P_AUDIO_CODEC_FW    = "acfw" // Audio Codec Firmware
	IM4P_AVE_FIRMWARE      = "avef" // AVE Firmware
	IM4P_GPU_FIRMWARE      = "gfxf" // GPU Firmware
	IM4P_MAGGIE_FIRMWARE   = "magg" // Maggie Firmware
	IM4P_MULTITOUCH_FW     = "mtfw" // Multitouch Firmware
	IM4P_PMP               = "pmpf" // PMP
	IM4P_RTP               = "rtpf" // RTP
	IM4P_SCE               = "scef" // SCE
	IM4P_SMARTIO_FW        = "siof" // SmartIOFirmware
	IM4P_WCH_FW_UPDATER    = "wchf" // WCHFirmwareUpdater
	IM4P_WIRELESS_CHARGING = "wchf" // Wireless Charging

	// Boot Components
	IM4P_IBEC       = "ibec" // iBEC
	IM4P_IBOOT      = "ibot" // iBoot
	IM4P_IBOOT_TEST = "itst" // iBootTest
	IM4P_IBSS       = "ibss" // iBSS
	IM4P_LLB        = "illb" // LLB
	IM4P_CFE_LOADER = "cfel" // Silicon Validation CFE loader
	IM4P_IBOOT_DATA = "ibdt" // iBoot Data

	// System Components
	IM4P_KERNELCACHE      = "krnl" // KernelCache
	IM4P_DEVICE_TREE      = "dtre" // DeviceTree
	IM4P_SEP              = "sepi" // SEP
	IM4P_HYPERVISOR       = "hypr" // Hypervisor
	IM4P_DIAGS            = "diag" // Diags
	IM4P_INPUT_DEVICE     = "ipdf" // Input Device
	IM4P_ISPOOF           = "ispf" // iSpoof(?)
	IM4P_ENVIRONMENT_VARS = "ienv" // Environment Variables

	// Display Components
	IM4P_DCP_FW     = "dcpf" // Display Coprocessor firmware, used on the iPhone 12 and later
	IM4P_DALI       = "dali" // Dali
	IM4P_HOMER      = "homr" // Homer

	// Battery/Charging UI
	IM4P_BATTERY_CHARGING0 = "chg0" // Charging indicator (bright), used in the battery low screen
	IM4P_BATTERY_CHARGING1 = "chg1" // Charging Indicator (dim), used in the battery low screen
	IM4P_BATTERY_FULL      = "batF" // Only used in China to indicate battery status while device is off
	IM4P_BATTERY_LOW0      = "bat0" // Empty battery, used in the battery low screen
	IM4P_BATTERY_LOW1      = "bat1" // Red composed onto empty battery, used in the battery low screen
	IM4P_GLYPH_CHARGING    = "glyC" // Used in the battery low screen
	IM4P_GLYPH_PLUGIN      = "glyP" // Used in the battery low screen
	IM4P_LOW_POWER_WALLET0 = "lpw0" // Used in the battery low screen with power reserve enabled
	IM4P_LOW_POWER_WALLET1 = "lpw1" // Used in the battery low screen with power reserve enabled
	IM4P_LOW_POWER_WALLET2 = "lpw2" // Used in the battery low screen with power reserve enabled
	IM4P_NEED_SERVICE      = "nsrv" // Need Service screen (removed in iOS 4.0+)
	IM4P_RECOVERY_MODE     = "recm" // Used when device is in Recovery Mode

	// Trust Cache Types
	IM4P_ENGINEERING_TRUST_CACHE = "dtrs" // EngineeringTrustCache
	IM4P_LOADABLE_TRUST_CACHE    = "ltrs" // LoadableTrustCache
	IM4P_STATIC_TRUST_CACHE      = "trst" // StaticTrustCache
	IM4P_BASE_SYSTEM_TRUST_CACHE = "bstc" // Base System Trust Cache
	IM4P_X86_BASE_SYSTEM_TC      = "xbtc" // x86 Base System Trust Cache

	// Restore Components
	IM4P_RESTORE_ANS_FW       = "rans" // Restore Apple NVME storage firmware
	IM4P_RESTORE_RAMDISK      = "rdsk" // RestoreRamDisk
	IM4P_RESTORE_DEVICE_TREE  = "rdtr" // RestoreDeviceTree
	IM4P_RESTORE_KERNEL_CACHE = "rkrn" // RestoreKernelCache
	IM4P_RESTORE_OS           = "rosi" // RestoreOS
	IM4P_RESTORE_DCP_FW       = "dcpf" // Restore Display Coprocessor firmware, used on the iPhone 12 and later
	IM4P_RESTORE_SEP          = "rsep" // rsep is also present in sepboot
	IM4P_RESTORE_TRUST_CACHE  = "rtsc" // RestoreTrustCache

	// FDR Trust Objects
	IM4P_FDR_TRUST_OBJECT_AP  = "fdrt" // FDR Trust Object for AP
	IM4P_FDR_TRUST_OBJECT_SEP = "fdrs" // FDR Trust Object for SEP

	// Audio Files
	IM4P_BOOT_CHIME          = "aubt" // Raw audio file
	IM4P_ACCESSIBILITY_CHIME = "auac" // Raw audio file
	IM4P_ATTACH_CHIME        = "aupr" // Raw audio file

	// System Volume Components
	IM4P_AUX_KERNEL_CACHE           = "auxk" // Aux Kernel Cache
	IM4P_BASE_SYSTEM_ROOT_HASH      = "csys" // Base System Volume Root Hash
	IM4P_SYSTEM_VOLUME_ROOT_HASH    = "isys" // System Volume Root Hash
	IM4P_X86_SYSTEM_VOLUME_HASH     = "xsys" // x86 System Volume Root hash
	IM4P_SYSTEM_VOLUME_METADATA     = "msys" // System Volume Canonical Metadata (Compressed gzip file)
	IM4P_X86_SYSTEM_VOLUME_METADATA = "xsys" // x86 System Volume Canonical Metadata (Compressed gzip file)

	// Special/Testing Components
	IM4P_AP_TICKET        = "SCAB" // On devices that don't use IMG4
	IM4P_OS_RAMDISK       = "osrd" // OSRamdisk
	IM4P_PE_HAMMER        = "hmmr" // PE Hammer test
	IM4P_PERSONALIZED_DMG = "pdmg" // PersonalizedDMG
	IM4P_PERTOS           = "pert" // PE RTOS environment
	IM4P_PHLEET           = "phlt" // Silicon Validation PHLEET test
	IM4P_RBM              = "rbmt" // Silicon Validation RBM test
	IM4P_SYSTEM_LOCKER    = "lckr" // System Locker
	IM4P_TSYS_TESTER      = "tsys" // TSYS Tester
	IM4P_LEAP_HAPTICS     = "lphp" // LeapHaptics
	IM4P_MAC_EFI          = "mefi" // Used only on T2 Macs

	// Unknown Types
	IM4P_CIOF = "ciof" // Unknown
	IM4P_TMUF = "tmuf" // Unknown
	IM4P_RPMP = "rpmp" // Unknown
	IM4P_LPOL = "lpol" // Unknown
	IM4P_RTMU = "rtmu" // Unknown
	IM4P_RCIO = "rcio" // Unknown
)

IM4P Types - these are the four-character codes used to identify different payload types in IMG4 containers

View Source
const (
	PRODUCTION  keybagType = 1
	DEVELOPMENT keybagType = 2
	DECRYPTED   keybagType = 3
)

Variables

View Source
var ComponentFourCCs = map[string]string{}/* 125 elements not displayed */

ComponentFourCCs is a map of component names to their four-character codes.

View Source
var CompressionTypes = []string{"none", "lzss", "lzfse", "lzfse_iboot"}

CompressionTypes is a list of supported compression algorithms

View Source
var ErrNotCompressed = fmt.Errorf("payload is not compressed")
View Source
var FourCCToComponent map[string]string

FourCCToComponent is a reverse map of ComponentFourCCs for efficient lookups

View Source
var PropertyFourCCs = map[string]string{

	"love": "ApOSLongVersion",
	"pave": "ApOSLongVersion",
	"apmv": "ProductMarketingVersion",
	"vnum": "VersionNumber",

	"prtp": "ApProductType",
	"tagt": "ApTarget",
	"tatp": "ApTargetType",
	"sdkp": "ApSDKPlatform",

	"BORD": "ApBoardID",
	"CHIP": "ApChipID",
	"ECID": "ExclusiveChipID",

	"SDOM": "ApSecurityDomain",
	"CEPO": "CertificateEpoch",
	"augs": "AugmentedSecurity",
	"styp": "SecurityType",
	"type": "Type",
	"clas": "DeviceClass",
	"fchp": "FirmwareChip",

	"srvn": "SecurityRevisionNumber",
	"snon": "SecurityNonce",
	"BNCH": "BootNonceHash",
	"DGST": "Digest",

	"CPRO": "CertificateProductionStatus",
	"CSEC": "CertificateSecurityMode",
	"EKEY": "EncryptionKeyRequired",
	"EPRO": "EncryptionProduction",
	"ESEC": "EncryptionSecurity",

	"tstp": "Timestamp",
}

PropertyFourCCs maps property fourCC codes to their BuildManifest field names This mapping was discovered through comprehensive analysis of IM4M manifests

Functions

func CompareManifestValues

func CompareManifestValues(a, b any) bool

CompareManifestValues compares two manifest property values

func DecryptPayload

func DecryptPayload(inputPath, outputPath string, iv, key []byte) error

DecryptPayload decrypts an IM4P payload using AES-CBC with provided IV and key

func ExtractManifestFromShsh

func ExtractManifestFromShsh(r io.Reader) ([]byte, error)

ExtractManifestFromShsh extracts IM4M manifest from SHSH blob with proper ASN.1 parsing

func ExtractManifestFromShshWithOptions

func ExtractManifestFromShshWithOptions(r io.Reader, extractUpdate, extractNoNonce bool) ([]byte, error)

ExtractManifestFromShshWithOptions extracts IM4M manifest from SHSH blob with options

func FormatPropertyValue

func FormatPropertyValue(value any) string

FormatPropertyValue formats property values for display

func MarshalProperties

func MarshalProperties(props map[string]any, format PropertyMarshalFormat) ([]byte, error)

MarshalProperties marshals properties to ASN.1 format Supports both RestoreInfo format (SEQUENCE with name+value) and Manifest format (SEQUENCE with name+SET)

func MarshalPropertiesSlice

func MarshalPropertiesSlice(props []Property, format PropertyMarshalFormat) ([]asn1.RawValue, error)

MarshalPropertiesSlice marshals []Property format to ASN.1 RawValues

func ParsePropertiesAs

func ParsePropertiesAs[T []Property | map[string]any](data []byte) (T, error)

ParsePropertiesAs parses properties from ASN.1 data and returns the specified type

func ParsePropertyMap

func ParsePropertyMap(data []byte) (map[string]any, error)

ParsePropertyMap parses ASN.1 property data into a map[string]any format Used by restore info for direct property access

func ParsePropertyValueWithTag

func ParsePropertyValueWithTag(rawValue asn1.RawValue, tag int) any

ParsePropertyValueWithTag dynamically detects and parses property values based on ASN.1 type and known tag

func PropertiesSliceToMap

func PropertiesSliceToMap(props []Property) map[string]any

PropertiesSliceToMap converts []Property to map[string]any

Types

type Compression

type Compression struct {
	Algorithm        CompressionAlgorithm `asn1:"integer" json:"algorithm,omitempty"`
	UncompressedSize int                  `asn1:"integer" json:"uncompressed_size,omitempty"`
}

type CompressionAlgorithm

type CompressionAlgorithm int
const (
	CompressionAlgorithmLZSS CompressionAlgorithm = iota
	CompressionAlgorithmLZFSE
	CompressionAlgorithmMAX
)

func (CompressionAlgorithm) String

func (c CompressionAlgorithm) String() string

type CreateConfig

type CreateConfig struct {
	// raw IM4P data
	InputData          []byte
	PayloadType        string
	PayloadVersion     string
	PayloadCompression string
	PayloadExtraData   []byte

	PayloadData     []byte
	ManifestData    []byte
	RestoreInfoData []byte

	// IM4R specific
	BootNonce string
}

type CreatePayloadConfig

type CreatePayloadConfig struct {
	Type        string
	Version     string
	Data        []byte
	ExtraData   []byte // Optional extra data to append after the main data
	Compression string
	Keybags     []Keybag
}

type DigestVerificationResult

type DigestVerificationResult struct {
	IsValid           bool
	MatchedIdentity   *bm.BuildIdentity
	IdentityIndex     int
	ComponentsChecked int
	MissingComponents []string
}

DigestVerificationResult holds the results of digest-based manifest verification

func VerifyManifestDigests

func VerifyManifestDigests(im4m *Manifest, buildManifest *bm.BuildManifest, verbose, strict bool) (*DigestVerificationResult, error)

VerifyManifestDigests verifies an IM4M manifest against a build manifest using digest comparison This matches the Python pyimg4 im4m_verify logic In non-strict mode (default), passes if all IM4M images have verified digests In strict mode, passes only if all BuildManifest components are present AND verified

type IM4M

type IM4M struct {
	Raw       asn1.RawContent
	Tag       string `asn1:"ia5"` // IM4M
	Version   int
	Body      asn1.RawValue `asn1:"set"`      // Manifest body as SET - parsed dynamically
	Signature []byte        `asn1:"optional"` // Optional signature data
	CertChain asn1.RawValue `asn1:"optional"` // Optional certificate chain
}

Manifest represents a unified IM4M manifest structure

type IM4P

type IM4P struct {
	Raw         asn1.RawContent
	Tag         string `asn1:"ia5"` // IM4P
	Type        string `asn1:"ia5"`
	Version     string `asn1:"ia5"`
	Data        []byte
	Compression Compression `asn1:"optional,omitempty"`
	Keybag      []byte      `asn1:"optional"`
	Properties  PAYP        `asn1:"optional,tag:0,class:context,explicit"`
	Hash        []byte      `asn1:"optional"`
}

type IM4R

type IM4R struct {
	Raw               asn1.RawContent
	Tag               string `asn1:"ia5"`
	RestoreProperties asn1.RawValue
}

type IMG4

type IMG4 struct {
	Raw         asn1.RawContent
	Tag         string        `asn1:"ia5"` // IMG4
	Payload     asn1.RawValue `asn1:"optional"`
	Manifest    asn1.RawValue `asn1:"explicit,tag:0,optional"`
	RestoreInfo asn1.RawValue `asn1:"explicit,tag:1,optional"`
}

type Im4pKeybag

type Im4pKeybag struct {
	Name    string   `json:"name,omitempty"`
	Keybags []Keybag `json:"kbags,omitempty"`
}

type Image

type Image struct {
	IMG4
	Payload     *Payload
	Manifest    *Manifest
	RestoreInfo *RestoreInfo
}

func Create

func Create(conf *CreateConfig) (*Image, error)

Create creates a complete IMG4 file from component files

func Open

func Open(path string) (*Image, error)

func Parse

func Parse(data []byte) (*Image, error)

func Personalize

func Personalize(conf *PersonalizeConfig) (*Image, error)

Personalize creates a personalized IMG4 file from component files

func (*Image) Marshal

func (i *Image) Marshal() ([]byte, error)

func (*Image) MarshalJSON

func (i *Image) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON representation of the image

func (*Image) String

func (i *Image) String() string

String returns a formatted string representation of the image

type KeyBags

type KeyBags struct {
	KeybagMetaData
	Files []Im4pKeybag `json:"files,omitempty"`
}

func GetKeybagsFromIPSW

func GetKeybagsFromIPSW(files []*zip.File, meta KeybagMetaData, pattern string) (*KeyBags, error)

type Keybag

type Keybag struct {
	Type keybagType
	IV   []byte
	Key  []byte
}

func (Keybag) MarshalJSON

func (k Keybag) MarshalJSON() ([]byte, error)

func (Keybag) String

func (k Keybag) String() string

type KeybagMetaData

type KeybagMetaData struct {
	Type    string   `json:"type,omitempty"`
	Version string   `json:"product_version,omitempty"`
	Build   string   `json:"product_build_version,omitempty"`
	Devices []string `json:"supported_product_types,omitempty"`
}

type Manifest

type Manifest struct {
	IM4M
	ManifestBody
}

Manifest represents the manifest structure

func CreateManifest

func CreateManifest() (*Manifest, error)

func OpenManifest

func OpenManifest(path string) (*Manifest, error)

func ParseManifest

func ParseManifest(data []byte) (*Manifest, error)

ParseManifest parses a raw IM4M manifest from bytes

func (*Manifest) GetTicket

func (m *Manifest) GetTicket(name string) (*ManifestImage, error)

func (*Manifest) HasTicket

func (m *Manifest) HasTicket(name string) bool

func (*Manifest) Marshal

func (m *Manifest) Marshal() ([]byte, error)

Marshal generates ASN.1 bytes for the manifest

func (*Manifest) MarshalJSON

func (m *Manifest) MarshalJSON() ([]byte, error)

func (*Manifest) String

func (m *Manifest) String() string

String returns a formatted string representation of the manifest

type ManifestBody

type ManifestBody struct {
	Properties []Property
	Images     []ManifestImage // Parsed images from the manifest body
}

type ManifestImage

type ManifestImage struct {
	Name       string     // 4-character image name
	Properties []Property // Image-specific properties
}

ManifestImage represents an image entry in the manifest

type PAYP

type PAYP struct {
	Raw asn1.RawContent
	Tag string        `asn1:"ia5"` // PAYP
	Set asn1.RawValue `asn1:"set"`
}

type Payload

type Payload struct {
	IM4P
	Encrypted  bool
	Keybags    []Keybag
	Properties map[string]any
	// contains filtered or unexported fields
}

func CreatePayload

func CreatePayload(conf *CreatePayloadConfig) (*Payload, error)

CreatePayload creates a new IM4P structure

func OpenPayload

func OpenPayload(path string) (*Payload, error)

func ParsePayload

func ParsePayload(data []byte) (*Payload, error)

func (*Payload) Decompress

func (p *Payload) Decompress() ([]byte, error)

func (*Payload) GetData

func (i *Payload) GetData() ([]byte, error)

func (*Payload) GetExtraData

func (i *Payload) GetExtraData() []byte

GetExtraData returns any extra data appended after the compressed payload

func (*Payload) HasExtraData

func (i *Payload) HasExtraData() bool

HasExtraData returns true if extra data was detected in the IM4P

func (*Payload) Marshal

func (p *Payload) Marshal() ([]byte, error)

func (*Payload) MarshalJSON

func (p *Payload) MarshalJSON() ([]byte, error)

func (*Payload) String

func (p *Payload) String() string

type PersonalizeConfig

type PersonalizeConfig struct {
	PayloadData   []byte
	ManifestData  []byte
	Component     string
	APParameters  map[string]any // AP parameters for nonce slot handling
	BuildIdentity map[string]any // Build identity information for nonce requirements
}

type PropType

type PropType int

PropType represents the expected type for a property

const (
	PropTypeAuto PropType = iota
	PropTypeInt
	PropTypeBool
	PropTypeString
	PropTypeHash
	PropTypeTimestamp
)

type Property

type Property struct {
	Name  string // 4-character property name (CHIP, BORD, etc.)
	Value any    // int, bool, string, or []byte based on ASN.1 type detection
}

Property represents a dynamic IMG4 property with auto-detected type

func ParsePropertySet

func ParsePropertySet(data []byte) ([]Property, error)

ParsePropertySet parses a SET of properties dynamically into []Property format Used by both manifest MANP and image descriptors

func PropertiesMapToSlice

func PropertiesMapToSlice(props map[string]any) []Property

PropertiesMapToSlice converts map[string]any to []Property

type PropertyMarshalFormat

type PropertyMarshalFormat int

PropertyMarshalFormat specifies the ASN.1 structure format for property marshaling

const (
	// RestoreInfoFormat - used by IM4R, has SEQUENCE with name and value
	RestoreInfoFormat PropertyMarshalFormat = iota
	// ManifestFormat - used by IM4M, has SEQUENCE with name and SET containing value
	ManifestFormat
)

type PropertyMismatch

type PropertyMismatch struct {
	Property string
	Expected any
	Actual   any
}

PropertyMismatch represents a property that doesn't match between manifests

type RestoreInfo

type RestoreInfo struct {
	IM4R
	Properties map[string]any
}

RestoreInfo represents an IM4R (Image4 Restore Info) structure

func CreateRestoreInfo

func CreateRestoreInfo(nonce any) (*RestoreInfo, error)

CreateRestoreInfo creates RestoreInfo from a boot nonce value

func New

func New(properties map[string]any) *RestoreInfo

New creates a new RestoreInfo with the given properties

func NewWithBootNonce

func NewWithBootNonce(nonce uint64) *RestoreInfo

NewWithBootNonce creates a new RestoreInfo with only a boot nonce

func OpenRestoreInfo

func OpenRestoreInfo(path string) (*RestoreInfo, error)

func ParseRestoreInfo

func ParseRestoreInfo(data []byte) (*RestoreInfo, error)

ParseRestoreInfo parses a standalone IM4R file and returns the restore info

func (*RestoreInfo) BootNonce

func (r *RestoreInfo) BootNonce() (uint64, bool)

BootNonce returns the boot nonce (BNCN) value if present

func (*RestoreInfo) Get

func (r *RestoreInfo) Get(name string) (any, bool)

Get returns the value of a property by name

func (*RestoreInfo) Has

func (r *RestoreInfo) Has(name string) bool

Has checks if a property exists

func (*RestoreInfo) Marshal

func (r *RestoreInfo) Marshal() ([]byte, error)

Marshal marshals the RestoreInfo to ASN.1 bytes (IM4R format)

func (*RestoreInfo) MarshalJSON

func (r *RestoreInfo) MarshalJSON() ([]byte, error)

func (*RestoreInfo) String

func (r *RestoreInfo) String() string

String returns a formatted string representation of the restore info

type RestoreInfoError

type RestoreInfoError struct {
	Op  string // Operation that failed
	Err error  // Underlying error
}

RestoreInfoError represents parsing errors with context

func (*RestoreInfoError) Error

func (e *RestoreInfoError) Error() string

func (*RestoreInfoError) Unwrap

func (e *RestoreInfoError) Unwrap() error

type ValidationResult

type ValidationResult struct {
	IsValid    bool
	Structure  string
	Components []string
	Errors     []string
	Warnings   []string
}

ValidationResult holds the results of IMG4 structure validation

func ValidateImg4Structure

func ValidateImg4Structure(r io.Reader) (*ValidationResult, error)

ValidateImg4Structure performs structural validation on an IMG4 file

type VerificationResult

type VerificationResult struct {
	IsValid           bool
	PropertiesChecked int
	Mismatches        []PropertyMismatch
}

VerificationResult holds the results of manifest verification

func VerifyManifestProperties

func VerifyManifestProperties(im4m *Manifest, bm *bm.BuildManifest, verbose, allowExtra bool) (*VerificationResult, error)

VerifyManifestProperties verifies an IM4M manifest against a build manifest

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL