def update(self) -> None: """Update boot image.""" if self._boot_sections: self._header.first_boot_section_id = self._boot_sections[0].uid # calculate first boot tag block data_size = self._header.SIZE + self.HEADER_MAC_SIZE + self.KEY_BLOB_SIZE if self._cert_section is not None: data_size += self._cert_section.raw_size self._header.first_boot_tag_block = calc_cypher_block_count( data_size) # ... self._header.flags = 0x08 if self.signed else 0x04 self._header.image_blocks = calc_cypher_block_count( self.raw_size_without_signature) self._header.header_blocks = calc_cypher_block_count(self._header.SIZE) self._header.max_section_mac_count = 0 if self.signed: self._header.offset_to_certificate_block = (self._header.SIZE + self.HEADER_MAC_SIZE + self.KEY_BLOB_SIZE) self._header.offset_to_certificate_block += CmdHeader.SIZE + CertSectionV2.HMAC_SIZE * 2 self._header.max_section_mac_count = 1 for boot_sect in self._boot_sections: boot_sect.is_last = True # this is unified with elftosb self._header.max_section_mac_count += boot_sect.hmac_count # Update certificates block header cert_blk = self.cert_block if cert_blk is not None: cert_blk.header.build_number = self._header.build_number cert_blk.header.image_length = self.cert_header_size
def update(self) -> None: """Update BootImageV21.""" if self._boot_sections: self._header.first_boot_section_id = self._boot_sections[0].uid # calculate first boot tag block data_size = self._header.SIZE + self.HEADER_MAC_SIZE + self.KEY_BLOB_SIZE cert_blk = self.cert_block if cert_blk is not None: data_size += cert_blk.raw_size if not self.signed: # pragma: no cover # SB2.1 is always signed raise SPSDKError("Certificate block is not signed") data_size += cert_blk.signature_size self._header.first_boot_tag_block = calc_cypher_block_count( data_size) # ... self._header.image_blocks = calc_cypher_block_count(self.raw_size) self._header.header_blocks = calc_cypher_block_count(self._header.SIZE) self._header.offset_to_certificate_block = (self._header.SIZE + self.HEADER_MAC_SIZE + self.KEY_BLOB_SIZE) # Get HMAC count self._header.max_section_mac_count = 0 for boot_sect in self._boot_sections: boot_sect.is_last = True # unified with elftosb self._header.max_section_mac_count += boot_sect.hmac_count # Update certificates block header cert_clk = self.cert_block if cert_clk is not None: cert_clk.header.build_number = self._header.build_number cert_clk.header.image_length = self.cert_header_size
def export(self, padding: Optional[bytes] = None) -> bytes: """Serialize image object. :param padding: header padding (8 bytes) for testing purpose; None to use random values (recommended) :return: exported bytes :raises SPSDKError: Raised when there are no boot sections or is not signed or private keys are missing :raises SPSDKError: Raised when there is invalid dek or mac :raises SPSDKError: Raised when certificate data is not present :raises SPSDKError: Raised when there is invalid certificate block :raises SPSDKError: Raised when there is invalid length of exported data """ if len(self.dek) != 32 or len(self.mac) != 32: raise SPSDKError("Invalid dek or mac") # validate params if not self._boot_sections: raise SPSDKError("No boot section") if self.signed and (self._cert_section is None): raise SPSDKError( "Certificate section is required for signed images") # update internals self.update() # Add Image Header data data = self._header.export(padding=padding) # Add Image Header HMAC data data += crypto_backend().hmac(self.mac, data) # Add DEK and MAC keys data += crypto_backend().aes_key_wrap(self.kek, self.dek + self.mac) # Add Padding data += padding if padding else crypto_backend().random_bytes(8) # Add Certificates data if not self._header.nonce: raise SPSDKError("There is no nonce in the header") counter = Counter(self._header.nonce) counter.increment(calc_cypher_block_count(len(data))) if self._cert_section is not None: cert_sect_bin = self._cert_section.export(dek=self.dek, mac=self.mac, counter=counter) counter.increment(calc_cypher_block_count(len(cert_sect_bin))) data += cert_sect_bin # Add Boot Sections data for sect in self._boot_sections: data += sect.export(dek=self.dek, mac=self.mac, counter=counter) # Add Signature data if self.signed: private_key_pem_data = self.private_key_pem_data if private_key_pem_data is None: raise SPSDKError( "Private key not assigned, cannot sign the image") certificate_block = self.cert_block if not ((certificate_block is not None) and certificate_block. verify_private_key(private_key_pem_data)): raise SPSDKError("Invalid certificate block") data += crypto_backend().rsa_sign(private_key_pem_data, data) if len(data) != self.raw_size: raise SPSDKError("Invalid length of exported data") return data
def parse( cls, data: bytes, offset: int = 0, dek: bytes = b"", mac: bytes = b"", counter: Optional[Counter] = None, ) -> "CertSectionV2": """Parse Certificate Section from bytes array. :param data: Raw data of parsed image :param offset: The offset of input data :param dek: The DEK value in bytes (required) :param mac: The MAC value in bytes (required) :param counter: The counter object (required) :return: parsed cert section v2 object :raises SPSDKError: Raised when dek, mac, counter are not valid :raises SPSDKError: Raised when there is invalid header HMAC, TAG, FLAGS, Mark :raises SPSDKError: Raised when there is invalid certificate block HMAC """ if not isinstance(dek, bytes): raise SPSDKError("DEK value has invalid format") if not isinstance(mac, bytes): raise SPSDKError("MAC value has invalid format") if not isinstance(counter, Counter): raise SPSDKError("Counter value has invalid format") index = offset header_encrypted = data[index:index + CmdHeader.SIZE] index += CmdHeader.SIZE header_hmac = data[index:index + cls.HMAC_SIZE] index += cls.HMAC_SIZE cert_block_hmac = data[index:index + cls.HMAC_SIZE] index += cls.HMAC_SIZE if header_hmac != crypto_backend().hmac(mac, header_encrypted): raise SPSDKError("Invalid Header HMAC") header_encrypted = crypto_backend().aes_ctr_decrypt( dek, header_encrypted, counter.value) header = CmdHeader.parse(header_encrypted) if header.tag != EnumCmdTag.TAG: raise SPSDKError(f"Invalid Header TAG: 0x{header.tag:02X}") if header.flags != (EnumSectionFlag.CLEARTEXT | EnumSectionFlag.LAST_SECT): raise SPSDKError(f"Invalid Header FLAGS: 0x{header.flags:02X}") if header.address != cls.SECT_MARK: raise SPSDKError(f"Invalid Section Mark: 0x{header.address:08X}") # Parse Certificate Block cert_block = CertBlockV2.parse(data, index) if cert_block_hmac != crypto_backend().hmac( mac, data[index:index + cert_block.raw_size]): raise SPSDKError("Invalid Certificate Block HMAC") index += cert_block.raw_size cert_section_obj = cls(cert_block) counter.increment(calc_cypher_block_count(index - offset)) return cert_section_obj
def parse( cls, data: bytes, offset: int = 0, kek: bytes = bytes(), plain_sections: bool = False, ) -> "BootImageV21": """Parse image from bytes. :param data: Raw data of parsed image :param offset: The offset of input data :param kek: The Key for unwrapping DEK and MAC keys (required) :param plain_sections: Sections are not encrypted; this is used only for debugging, not supported by ROM code :return: BootImageV21 parsed object :raises Exception: raised when header is in incorrect format :raises Exception: raised when signature is incorrect :raises SPSDKError: Raised when kek is empty :raises Exception: raised when header's nonce not present" """ if not kek: raise SPSDKError("kek cannot be empty") index = offset header_raw_data = data[index:index + ImageHeaderV2.SIZE] index += ImageHeaderV2.SIZE # TODO not used right now: hmac_data = data[index: index + cls.HEADER_MAC_SIZE] index += cls.HEADER_MAC_SIZE key_blob = data[index:index + cls.KEY_BLOB_SIZE] index += cls.KEY_BLOB_SIZE key_blob_unwrap = crypto_backend().aes_key_unwrap(kek, key_blob[:-8]) dek = key_blob_unwrap[:32] mac = key_blob_unwrap[32:] # Parse Header header = ImageHeaderV2.parse(header_raw_data) if header.offset_to_certificate_block != (index - offset): raise Exception() # Parse Certificate Block cert_block = CertBlockV2.parse(data, index) index += cert_block.raw_size # Verify Signature signature_index = index # The image may containt SHA, in such a case the signature is placed # after SHA. Thus we must shift the index by SHA size. if header.flags & BootImageV21.FLAGS_SHA_PRESENT_BIT: signature_index += BootImageV21.SHA_256_SIZE result = cert_block.verify_data( data[signature_index:signature_index + cert_block.signature_size], data[offset:signature_index], ) if not result: raise Exception() # Check flags, if 0x8000 bit is set, the SB file contains SHA-256 between # certificate and signature. if header.flags & BootImageV21.FLAGS_SHA_PRESENT_BIT: bootable_section_sha256 = data[index:index + BootImageV21.SHA_256_SIZE] index += BootImageV21.SHA_256_SIZE index += cert_block.signature_size # Check first Boot Section HMAC # TODO: not implemented yet # hmac_data_calc = crypto_backend().hmac(mac, data[index + CmdHeader.SIZE: index + CmdHeader.SIZE + ((2) * 32)]) # if hmac_data != hmac_data_calc: # raise Exception() if not header.nonce: raise SPSDKError("Header's nonce not present") counter = Counter(header.nonce) counter.increment(calc_cypher_block_count(index - offset)) boot_section = BootSectionV2.parse(data, index, dek=dek, mac=mac, counter=counter, plain_sect=plain_sections) if header.flags & BootImageV21.FLAGS_SHA_PRESENT_BIT: computed_bootable_section_sha256 = internal_backend.hash( data[index:], algorithm="sha256") if bootable_section_sha256 != computed_bootable_section_sha256: raise SPSDKError(desc=( "Error: invalid Bootable section SHA." f"Expected {bootable_section_sha256.decode('utf-8')}," f"got {computed_bootable_section_sha256.decode('utf-8')}")) adv_params = SBV2xAdvancedParams(dek=dek, mac=mac, nonce=header.nonce, timestamp=header.timestamp) obj = cls( kek=kek, product_version=str(header.product_version), component_version=str(header.component_version), build_number=header.build_number, advanced_params=adv_params, ) obj.cert_block = cert_block obj.add_boot_section(boot_section) return obj
def export(self, padding: Optional[bytes] = None, dbg_info: Optional[List[str]] = None) -> bytes: """Serialize image object. :param padding: header padding (8 bytes) for testing purpose; None to use random values (recommended) :param dbg_info: optional list, where debug info is exported in text form :return: exported bytes :raises SPSDKError: Raised when there is no boot section to be added :raises SPSDKError: Raised when certificate is not assigned :raises SPSDKError: Raised when private key is not assigned :raises SPSDKError: Raised when private header's nonce is invalid :raises SPSDKError: Raised when private key does not match certificate :raises SPSDKError: Raised when there is no debug info """ # validate params if not self._boot_sections: raise SPSDKError("At least one Boot Section must be added") if self.cert_block is None: raise SPSDKError("Certificate is not assigned") if self.private_key_pem_data is None: raise SPSDKError("Private key not assigned, cannot sign the image") # Update internals if dbg_info is not None: dbg_info.append("[sb_file]") bs_dbg_info: Optional[List[str]] = list() if dbg_info else None self.update() # Export Boot Sections bs_data = bytes() # TODO: implement helper method for get key size in bytes. Now is working only with internal backend bs_offset = (ImageHeaderV2.SIZE + self.HEADER_MAC_SIZE + self.KEY_BLOB_SIZE + self.cert_block.raw_size + self.cert_block.signature_size) if self.header.flags & self.FLAGS_SHA_PRESENT_BIT: bs_offset += self.SHA_256_SIZE if not self._header.nonce: raise SPSDKError("Invalid header's nonce") counter = Counter(self._header.nonce, calc_cypher_block_count(bs_offset)) for sect in self._boot_sections: bs_data += sect.export(dek=self.dek, mac=self.mac, counter=counter, dbg_info=bs_dbg_info) # Export Header signed_data = self._header.export(padding=padding) if dbg_info: dbg_info.append("[header]") dbg_info.append(signed_data.hex()) # Add HMAC data first_bs_hmac_count = self._boot_sections[0].hmac_count hmac_data = bs_data[CmdHeader.SIZE:CmdHeader.SIZE + (first_bs_hmac_count * 32) + 32] hmac = crypto_backend().hmac(self.mac, hmac_data) signed_data += hmac if dbg_info: dbg_info.append("[hmac]") dbg_info.append(hmac.hex()) # Add KeyBlob data key_blob = crypto_backend().aes_key_wrap(self.kek, self.dek + self.mac) key_blob += b"\00" * (self.KEY_BLOB_SIZE - len(key_blob)) signed_data += key_blob if dbg_info: dbg_info.append("[key_blob]") dbg_info.append(key_blob.hex()) # Add Certificates data signed_data += self.cert_block.export() if dbg_info: dbg_info.append("[cert_block]") dbg_info.append(self.cert_block.export().hex()) # Add SHA-256 of Bootable sections if requested if self.header.flags & self.FLAGS_SHA_PRESENT_BIT: signed_data += internal_backend.hash(bs_data) # Add Signature data if not self.cert_block.verify_private_key(self.private_key_pem_data): raise SPSDKError("Private key does not match certificate") signature = crypto_backend().rsa_sign(self.private_key_pem_data, signed_data) if dbg_info: dbg_info.append("[signature]") dbg_info.append(signature.hex()) dbg_info.append("[boot_sections]") if not bs_dbg_info: raise SPSDKError("No debug information") dbg_info.extend(bs_dbg_info) return signed_data + signature + bs_data
def parse(cls, data: bytes, offset: int = 0, kek: bytes = bytes()) -> "BootImageV20": """Parse image from bytes. :param data: Raw data of parsed image :param offset: The offset of input data :param kek: The Key for unwrapping DEK and MAC keys (required) :return: parsed image object :raise Exception: raised when header is in wrong format :raise Exception: raised when there is invalid header version :raise Exception: raised when signature is incorrect :raises SPSDKError: Raised when kek is empty :raises Exception: raised when header's nonce is not present """ if not kek: raise SPSDKError("kek cannot be empty") index = offset header_raw_data = data[index:index + ImageHeaderV2.SIZE] index += ImageHeaderV2.SIZE header_mac_data = data[index:index + cls.HEADER_MAC_SIZE] index += cls.HEADER_MAC_SIZE key_blob = data[index:index + cls.KEY_BLOB_SIZE] index += cls.KEY_BLOB_SIZE key_blob_unwrap = crypto_backend().aes_key_unwrap(kek, key_blob[:-8]) dek = key_blob_unwrap[:32] mac = key_blob_unwrap[32:] header_mac_data_calc = crypto_backend().hmac(mac, header_raw_data) if header_mac_data != header_mac_data_calc: raise Exception() # Parse Header header = ImageHeaderV2.parse(header_raw_data) if header.version != "2.0": raise Exception( f"Invalid Header Version: {header.version} instead 2.0") image_size = header.image_blocks * 16 # Initialize counter if not header.nonce: raise SPSDKError("Header's nonce not present") counter = Counter(header.nonce) counter.increment(calc_cypher_block_count(index - offset)) # ... signed = header.flags == 0x08 adv_params = SBV2xAdvancedParams(dek=dek, mac=mac, nonce=header.nonce, timestamp=header.timestamp) obj = cls( signed, kek=kek, product_version=str(header.product_version), component_version=str(header.component_version), build_number=header.build_number, advanced_params=adv_params, ) # Parse Certificate section if header.flags == 0x08: cert_sect = CertSectionV2.parse(data, index, dek=dek, mac=mac, counter=counter) obj._cert_section = cert_sect index += cert_sect.raw_size # Check Signature if not cert_sect.cert_block.verify_data( data[offset + image_size:], data[offset:offset + image_size]): raise Exception() # Parse Boot Sections while index < (image_size + offset): boot_section = BootSectionV2.parse(data, index, dek=dek, mac=mac, counter=counter) obj.add_boot_section(boot_section) index += boot_section.raw_size return obj
def parse(cls, data: bytes, offset: int = 0, kek: bytes = bytes(), plain_sections: bool = False) -> 'BootImageV21': """Parse image from bytes. :param data: Raw data of parsed image :param offset: The offset of input data :param kek: The Key for unwrapping DEK and MAC keys (required) :param plain_sections: Sections are not encrypted; this is used only for debugging, not supported by ROM code :return: BootImageV21 parsed object :raise Exception: raised when header is in incorrect format :raise Exception: raised when signature is incorrect """ assert kek, 'kek cannot be empty' index = offset header_raw_data = data[index:index + ImageHeaderV2.SIZE] index += ImageHeaderV2.SIZE # TODO not used right now: hmac_data = data[index: index + cls.HEADER_MAC_SIZE] index += cls.HEADER_MAC_SIZE key_blob = data[index:index + cls.KEY_BLOB_SIZE] index += cls.KEY_BLOB_SIZE key_blob_unwrap = crypto_backend().aes_key_unwrap(kek, key_blob[:-8]) dek = key_blob_unwrap[:32] mac = key_blob_unwrap[32:] # Parse Header header = ImageHeaderV2.parse(header_raw_data) if header.offset_to_certificate_block != (index - offset): raise Exception() # Parse Certificate Block cert_block = CertBlockV2.parse(data, index) index += cert_block.raw_size # Verify Signature if not cert_block.verify_data( data[index:index + cert_block.signature_size], data[offset:index]): raise Exception() index += cert_block.signature_size # Check first Boot Section HMAC # TODO: not implemented yet # hmac_data_calc = crypto_backend().hmac(mac, data[index + CmdHeader.SIZE: index + CmdHeader.SIZE + ((2) * 32)]) # if hmac_data != hmac_data_calc: # raise Exception() assert header.nonce counter = Counter(header.nonce) counter.increment(calc_cypher_block_count(index - offset)) boot_section = BootSectionV2.parse(data, index, dek=dek, mac=mac, counter=counter, plain_sect=plain_sections) adv_params = SBV2xAdvancedParams(dek=dek, mac=mac, nonce=header.nonce, timestamp=header.timestamp) obj = cls(kek=kek, product_version=str(header.product_version), component_version=str(header.component_version), build_number=header.build_number, advanced_params=adv_params) obj.cert_block = cert_block obj.add_boot_section(boot_section) return obj
def export(self, padding: Optional[bytes] = None, dbg_info: Optional[List[str]] = None) -> bytes: """Serialize image object. :param padding: header padding (8 bytes) for testing purpose; None to use random values (recommended) :param dbg_info: optional list, where debug info is exported in text form :return: exported bytes :raise ValueError: raised when there is no boot section to be added :raise ValueError: raise when certificate is not assigned :raise ValueError: raise when private key is not assigned """ # validate params if not self._boot_sections: raise ValueError("At least one Boot Section must be added") if self.cert_block is None: raise ValueError('Certificate is not assigned') if self.private_key_pem_data is None: raise ValueError('Private key not assigned, cannot sign the image') # Update internals if dbg_info is not None: dbg_info.append('[sb_file]') bs_dbg_info: Optional[List[str]] = list() if dbg_info else None self.update() # Export Boot Sections bs_data = bytes() # TODO: implement helper method for get key size in bytes. Now is working only with internal backend bs_offset = (ImageHeaderV2.SIZE + self.HEADER_MAC_SIZE + self.KEY_BLOB_SIZE + self.cert_block.raw_size + self.cert_block.signature_size) assert self._header.nonce counter = Counter(self._header.nonce, calc_cypher_block_count(bs_offset)) for sect in self._boot_sections: bs_data += sect.export(dek=self.dek, mac=self.mac, counter=counter, dbg_info=bs_dbg_info) # Export Header signed_data = self._header.export(padding=padding) if dbg_info: dbg_info.append('[header]') dbg_info.append(signed_data.hex()) # Add HMAC data first_bs_hmac_count = self._boot_sections[0].hmac_count hmac_data = bs_data[CmdHeader.SIZE:CmdHeader.SIZE + (first_bs_hmac_count * 32) + 32] hmac = crypto_backend().hmac(self.mac, hmac_data) signed_data += hmac if dbg_info: dbg_info.append('[hmac]') dbg_info.append(hmac.hex()) # Add KeyBlob data key_blob = crypto_backend().aes_key_wrap(self.kek, self.dek + self.mac) key_blob += b'\00' * (self.KEY_BLOB_SIZE - len(key_blob)) signed_data += key_blob if dbg_info: dbg_info.append('[key_blob]') dbg_info.append(key_blob.hex()) # Add Certificates data signed_data += self.cert_block.export() if dbg_info: dbg_info.append('[cert_block]') dbg_info.append(self.cert_block.export().hex()) # Add Signature data assert self.cert_block.verify_private_key( self.private_key_pem_data ) # verify private key matches certificate signature = crypto_backend().rsa_sign(self.private_key_pem_data, signed_data) if dbg_info: dbg_info.append('[signature]') dbg_info.append(signature.hex()) dbg_info.append('[boot_sections]') assert bs_dbg_info dbg_info.extend(bs_dbg_info) return signed_data + signature + bs_data