Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/sb2/sections.py

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2019-2024 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7
8 """Sections within SBfile."""
9
10 from typing import Iterator, List
11
12 from ...crypto.hmac import hmac_sha256
13 from ...crypto.symmetric import Counter, aes_ctr_decrypt
14 from ...exceptions import SPSDKError
15 from ...utils.abstract import BaseClass
16 from .commands import CmdBaseClass, CmdHeader, EnumCmdTag, EnumSectionFlag, parse_command
17
18 ########################################################################################################################
19 # Boot Image Sections
20 ########################################################################################################################
21
22
23 class BootSectionV2(BaseClass):
24 """Boot Section V2."""
25
26 HMAC_SIZE = 32
27
28 @property
29 def uid(self) -> int:
30 """Boot Section UID."""
31 return self._header.address
32
33 @uid.setter
34 def uid(self, value: int) -> None:
35 self._header.address = value
36
37 @property
38 def is_last(self) -> bool:
39 """Check whether the section is the last one."""
40 return self._header.flags & EnumSectionFlag.LAST_SECT.tag != 0
41
42 @is_last.setter
43 def is_last(self, value: bool) -> None:
44 assert isinstance(value, bool)
45 self._header.flags = EnumSectionFlag.BOOTABLE.tag
46 if value:
47 self._header.flags |= EnumSectionFlag.LAST_SECT.tag
48
49 @property
50 def hmac_count(self) -> int:
51 """Number of HMACs."""
52 raw_size = 0
53 hmac_count = 0
54 for cmd in self._commands:
55 raw_size += cmd.raw_size
56 if raw_size > 0:
57 block_count = (raw_size + 15) // 16
58 hmac_count = self._hmac_count if block_count >= self._hmac_count else block_count
59 return hmac_count
60
61 @property
62 def raw_size(self) -> int:
63 """Raw size of section."""
64 size = CmdHeader.SIZE + self.HMAC_SIZE
65 size += self.hmac_count * self.HMAC_SIZE
66 for cmd in self._commands:
67 size += cmd.raw_size
68 if size % 16:
69 size += 16 - (size % 16)
70 return size
71
72 def __init__(self, uid: int, *commands: CmdBaseClass, hmac_count: int = 1) -> None:
73 """Initialize BootSectionV2.
74
75 :param uid: section unique identification
76 :param commands: List of commands
77 :param hmac_count: The number of HMAC entries
78 """
79 self._header = CmdHeader(EnumCmdTag.TAG.tag, EnumSectionFlag.BOOTABLE.tag)
80 self._commands: List[CmdBaseClass] = []
81 self._hmac_count = hmac_count
82 for cmd in commands:
83 self.append(cmd)
84 # Initialize HMAC count
85 if not isinstance(self._hmac_count, int) or self._hmac_count == 0:
86 self._hmac_count = 1
87 # section UID
88 self.uid = uid
89
90 def __len__(self) -> int:
91 return len(self._commands)
92
93 def __getitem__(self, key: int) -> CmdBaseClass:
94 return self._commands[key]
95
96 def __setitem__(self, key: int, value: CmdBaseClass) -> None:
97 self._commands[key] = value
98
99 def __iter__(self) -> Iterator[CmdBaseClass]:
100 return self._commands.__iter__()
101
102 def append(self, cmd: CmdBaseClass) -> None:
103 """Add command to section."""
104 assert isinstance(cmd, CmdBaseClass)
105 self._commands.append(cmd)
106
107 def __repr__(self) -> str:
108 return f"BootSectionV2: {len(self)} commands."
109
110 def __str__(self) -> str:
111 """Get object info."""
112 nfo = ""
113 for index, cmd in enumerate(self._commands):
114 nfo += f" {index}) {str(cmd)}\n"
115 return nfo
116
117 # pylint: disable=too-many-locals
118 @classmethod
119 def parse(
120 cls, data: bytes, offset: int, plain_sect: bool, dek: bytes, mac: bytes, counter: Counter
121 ) -> "BootSectionV2":
122 """Parse Boot Section from bytes.
123
124 :param data: Raw data of parsed image
125 :param offset: The offset of input data
126 :param plain_sect: If the sections are not encrypted; It is used for debugging only, not supported by ROM code
127 :param dek: The DEK value in bytes (required)
128 :param mac: The MAC value in bytes (required)
129 :param counter: The counter object (required)
130 :return: exported bytes
131 :raises SPSDKError: raised when dek, mac, counter have invalid format
132 """
133 if not isinstance(dek, bytes):
134 raise SPSDKError("Invalid type of dek, should be bytes")
135 if not isinstance(mac, bytes):
136 raise SPSDKError("Invalid type of mac, should be bytes")
137 if not isinstance(counter, Counter):
138 raise SPSDKError("Invalid type of counter")
139 # Get Header specific data
140 header_encrypted = data[offset : offset + CmdHeader.SIZE]
141 header_hmac_data = data[offset + CmdHeader.SIZE : offset + CmdHeader.SIZE + cls.HMAC_SIZE]
142 offset += CmdHeader.SIZE + cls.HMAC_SIZE
143 # Check header HMAC
144 if header_hmac_data != hmac_sha256(mac, header_encrypted):
145 raise SPSDKError("Invalid header HMAC")
146 # Decrypt header
147 header_decrypted = aes_ctr_decrypt(dek, header_encrypted, counter.value)
148 counter.increment()
149 # Parse header
150 header = CmdHeader.parse(header_decrypted)
151 counter.increment((header.data + 1) * 2)
152 # Get HMAC data
153 hmac_data = data[offset : offset + (cls.HMAC_SIZE * header.data)]
154 offset += cls.HMAC_SIZE * header.data
155 encrypted_commands = data[offset : offset + (header.count * 16)]
156 # Check HMAC
157 hmac_index = 0
158 hmac_count = header.data
159 block_size = (header.count // hmac_count) * 16
160 section_size = header.count * 16
161 while hmac_count > 0:
162 if hmac_count == 1:
163 block_size = section_size
164 hmac_block = hmac_sha256(mac, data[offset : offset + block_size])
165 if hmac_block != hmac_data[hmac_index : hmac_index + cls.HMAC_SIZE]:
166 raise SPSDKError("HMAC failed")
167 hmac_count -= 1
168 hmac_index += cls.HMAC_SIZE
169 section_size -= block_size
170 offset += block_size
171 # Decrypt commands
172 decrypted_commands = b""
173 for hmac_index in range(0, len(encrypted_commands), 16):
174 encr_block = encrypted_commands[hmac_index : hmac_index + 16]
175 decrypted_block = (
176 encr_block if plain_sect else aes_ctr_decrypt(dek, encr_block, counter.value)
177 )
178 decrypted_commands += decrypted_block
179 counter.increment()
180 # ...
181 cmd_offset = 0
182 obj = cls(header.address, hmac_count=header.data)
183 while cmd_offset < len(decrypted_commands):
184 cmd_obj = parse_command(decrypted_commands[cmd_offset:])
185 cmd_offset += cmd_obj.raw_size
186 obj.append(cmd_obj)
187 return obj