psptool 3.7__tar.gz → 3.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. {psptool-3.7 → psptool-3.8}/.github/workflows/publish.yml +23 -0
  2. {psptool-3.7 → psptool-3.8}/PKG-INFO +5 -3
  3. {psptool-3.7 → psptool-3.8}/README.md +4 -2
  4. {psptool-3.7 → psptool-3.8}/psptool/__main__.py +9 -4
  5. {psptool-3.7 → psptool-3.8}/psptool/blob.py +79 -47
  6. {psptool-3.7 → psptool-3.8}/psptool/cert_tree.py +67 -7
  7. {psptool-3.7 → psptool-3.8}/psptool/directory.py +75 -48
  8. {psptool-3.7 → psptool-3.8}/psptool/entry.py +27 -27
  9. {psptool-3.7 → psptool-3.8}/psptool/fet.py +6 -2
  10. {psptool-3.7 → psptool-3.8}/psptool/file.py +46 -14
  11. psptool-3.8/psptool/header_file.py +432 -0
  12. {psptool-3.7 → psptool-3.8}/psptool/key_store_file.py +22 -1
  13. psptool-3.8/psptool/lms.py +70 -0
  14. {psptool-3.7 → psptool-3.8}/psptool/psptool.py +25 -0
  15. {psptool-3.7 → psptool-3.8}/psptool/pubkey_file.py +60 -4
  16. {psptool-3.7 → psptool-3.8}/psptool/rom.py +4 -1
  17. {psptool-3.7 → psptool-3.8}/psptool/utils.py +2 -2
  18. psptool-3.8/tests/integration/test_replace.py +169 -0
  19. psptool-3.8/tests/unit/signed_rom.py +121 -0
  20. {psptool-3.7 → psptool-3.8}/tests/unit/synthetic_rom.py +1 -1
  21. psptool-3.8/tests/unit/test_checksums.py +64 -0
  22. psptool-3.8/tests/unit/test_keys.py +131 -0
  23. {psptool-3.7 → psptool-3.8}/tests/unit/test_rom_layouts.py +105 -0
  24. psptool-3.8/tests/unit/test_signature_layouts.py +173 -0
  25. psptool-3.7/psptool/header_file.py +0 -218
  26. {psptool-3.7 → psptool-3.8}/.github/workflows/python-tests.yml +0 -0
  27. {psptool-3.7 → psptool-3.8}/.gitignore +0 -0
  28. {psptool-3.7 → psptool-3.8}/.gitmodules +0 -0
  29. {psptool-3.7 → psptool-3.8}/LICENSE +0 -0
  30. {psptool-3.7 → psptool-3.8}/psptool/__init__.py +0 -0
  31. {psptool-3.7 → psptool-3.8}/psptool/crypto.py +0 -0
  32. {psptool-3.7 → psptool-3.8}/psptool/errors.py +0 -0
  33. {psptool-3.7 → psptool-3.8}/psptool/firmware.py +0 -0
  34. {psptool-3.7 → psptool-3.8}/psptool/microcode_file.py +0 -0
  35. {psptool-3.7 → psptool-3.8}/pyproject.toml +0 -0
  36. {psptool-3.7 → psptool-3.8}/tests/__init__.py +0 -0
  37. {psptool-3.7 → psptool-3.8}/tests/create_metrics.sh +0 -0
  38. {psptool-3.7 → psptool-3.8}/tests/gha_metrics.py +0 -0
  39. {psptool-3.7 → psptool-3.8}/tests/integration/__init__.py +0 -0
  40. {psptool-3.7 → psptool-3.8}/tests/integration/test_psptrace.py +0 -0
  41. {psptool-3.7 → psptool-3.8}/tests/integration/test_rom_files.py +0 -0
  42. {psptool-3.7 → psptool-3.8}/tests/metrics.txt +0 -0
  43. {psptool-3.7 → psptool-3.8}/tests/unit/__init__.py +0 -0
  44. {psptool-3.7 → psptool-3.8}/tests/unit/test_cli.py +0 -0
  45. {psptool-3.7 → psptool-3.8}/tests/unit/test_key_store_file.py +0 -0
  46. {psptool-3.7 → psptool-3.8}/tests/unit/test_zen_generation_backfill.py +0 -0
@@ -51,3 +51,26 @@ jobs:
51
51
  path: dist/
52
52
  - name: Publish distribution to PyPI
53
53
  uses: pypa/gh-action-pypi-publish@release/v1
54
+
55
+ github-release:
56
+ name: Create GitHub Release
57
+ needs:
58
+ - publish-to-pypi
59
+ runs-on: ubuntu-latest
60
+ permissions:
61
+ contents: write # needed to create GitHub releases
62
+ steps:
63
+ - name: Download all the dists
64
+ uses: actions/download-artifact@v8
65
+ with:
66
+ name: python-package-distributions
67
+ path: dist/
68
+ - name: Create GitHub Release
69
+ env:
70
+ GITHUB_TOKEN: ${{ github.token }}
71
+ run: >-
72
+ gh release create
73
+ "${{ github.ref_name }}"
74
+ --repo "${{ github.repository }}"
75
+ --generate-notes
76
+ dist/*
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: psptool
3
- Version: 3.7
3
+ Version: 3.8
4
4
  Summary: PSPTool is a tool for dealing with AMD binary blobs
5
5
  Author-email: Christian Werling <cwerling@posteo.de>
6
6
  License-File: LICENSE
@@ -18,6 +18,8 @@ It is based on reverse-engineering efforts of AMD's **proprietary filesystem** u
18
18
  PSPTool favourably works with UEFI images as obtained through BIOS updates. If these updates are only available through Windows executables, tools like [innoextract](https://github.com/dscharrer/innoextract) can help.
19
19
 
20
20
  PSPTool was developed at TU Berlin in context of the following research:
21
+ - 2026, paper: [Hello Again: Exploiting Replay Protected Monotonic Counters to Brute-Force Windows Hello PINs](https://arxiv.org/abs/2611.18126)
22
+ - 2025, paper: [Three Glitches to Rule One Car: Fault Injection Attacks on a Connected EV](https://dl.acm.org/doi/pdf/10.1145/3708821.3710820)
21
23
  - 2023, talk: [Jailbreaking an Electric Vehicle in 2023 or What It Means to Hotwire Tesla's x86-Based Seat Heater](https://www.blackhat.com/us-23/briefings/schedule/#jailbreaking-an-electric-vehicle-in--or-what-it-means-to-hotwire-teslas-x-based-seat-heater-33049)
22
24
  - 2023, paper: [faulTPM: Exposing AMD fTPMs' Deepest Secrets](https://arxiv.org/abs/2304.14717)
23
25
  - 2021, paper: [One Glitch to Rule Them All: Fault Injection Attacks Against AMD's Secure Encrypted Virtualization](https://arxiv.org/abs/2108.04575)
@@ -867,6 +869,6 @@ b'\x01\x00\x00\x00\x1b\xb9\x87\xc3YIF\x06\xb1t\x94V\x01\xc9\xea[\x1b\xb9\x87\xc3
867
869
  [...]
868
870
  > my_stuff = [...]
869
871
  > psp.blob.roms[0].directories[0].files[1].move_buffer(0x60000, 0x1000)
870
- > psp.blob.roms[0].set_bytes(0x60000, 0x1000, my_stuff)
872
+ > psp.blob.roms[0].set_bytes(0x60000, my_stuff)
871
873
  > psp.to_file('my_modified_bios.bin')
872
- ```
874
+ ```
@@ -7,6 +7,8 @@ It is based on reverse-engineering efforts of AMD's **proprietary filesystem** u
7
7
  PSPTool favourably works with UEFI images as obtained through BIOS updates. If these updates are only available through Windows executables, tools like [innoextract](https://github.com/dscharrer/innoextract) can help.
8
8
 
9
9
  PSPTool was developed at TU Berlin in context of the following research:
10
+ - 2026, paper: [Hello Again: Exploiting Replay Protected Monotonic Counters to Brute-Force Windows Hello PINs](https://arxiv.org/abs/2611.18126)
11
+ - 2025, paper: [Three Glitches to Rule One Car: Fault Injection Attacks on a Connected EV](https://dl.acm.org/doi/pdf/10.1145/3708821.3710820)
10
12
  - 2023, talk: [Jailbreaking an Electric Vehicle in 2023 or What It Means to Hotwire Tesla's x86-Based Seat Heater](https://www.blackhat.com/us-23/briefings/schedule/#jailbreaking-an-electric-vehicle-in--or-what-it-means-to-hotwire-teslas-x-based-seat-heater-33049)
11
13
  - 2023, paper: [faulTPM: Exposing AMD fTPMs' Deepest Secrets](https://arxiv.org/abs/2304.14717)
12
14
  - 2021, paper: [One Glitch to Rule Them All: Fault Injection Attacks Against AMD's Secure Encrypted Virtualization](https://arxiv.org/abs/2108.04575)
@@ -856,6 +858,6 @@ b'\x01\x00\x00\x00\x1b\xb9\x87\xc3YIF\x06\xb1t\x94V\x01\xc9\xea[\x1b\xb9\x87\xc3
856
858
  [...]
857
859
  > my_stuff = [...]
858
860
  > psp.blob.roms[0].directories[0].files[1].move_buffer(0x60000, 0x1000)
859
- > psp.blob.roms[0].set_bytes(0x60000, 0x1000, my_stuff)
861
+ > psp.blob.roms[0].set_bytes(0x60000, my_stuff)
860
862
  > psp.to_file('my_modified_bios.bin')
861
- ```
863
+ ```
@@ -123,7 +123,8 @@ def main():
123
123
  '-r idx: specifies rom_index (default: 0)',
124
124
  '-d idx: specifies directory_index',
125
125
  '-e idx: specifies file_index',
126
- '-s file: specifies subfile (i.e. the new file contents)',
126
+ '-s file: specifies substitution file (i.e. the new file contents)',
127
+ '(optional to allow plain re-signs)',
127
128
  '-o file: specifies outfile',
128
129
  '-p file: specifies file-stub (e.g. \'keys/id\') for the re-signing keys',
129
130
  '-a pass: specifies password for the re-signing keys'
@@ -239,13 +240,17 @@ def main():
239
240
  if args.directory_index is not None and args.file_index is not None and args.outfile is not None:
240
241
  file = psp.blob.roms[args.rom_index].directories[args.directory_index].files[args.file_index]
241
242
 
242
- # Substituting an file is actually optional to allow plain re-signs
243
+ # Learn which bytes each signature covers while the original keys and files are
244
+ # still in place, so that resigning signs the same ones
245
+ psp.cert_tree.verify_all()
246
+
247
+ # Substituting a file is actually optional to allow plain re-signs
243
248
  if args.subfile is not None:
244
249
  with open(args.subfile, 'rb') as f:
245
250
  sub_binary = f.read()
246
251
  # Keep the existing file's address, but adapt its size
247
- file.move_buffer(file.get_address(), len(sub_binary))
248
- file.set_bytes(0, len(sub_binary), sub_binary)
252
+ file.move_buffer(file.get_address(), len(sub_binary) + file.signature.len)
253
+ file.set_bytes(0, sub_binary)
249
254
 
250
255
  privkeys = None
251
256
  if args.privkeystub:
@@ -15,6 +15,7 @@
15
15
  # along with this program. If not, see <https://www.gnu.org/licenses/>.
16
16
 
17
17
  import re
18
+ import struct
18
19
  import binascii
19
20
 
20
21
  from typing import List
@@ -23,7 +24,7 @@ from .fet import EmptyFet
23
24
  from .rom import Rom
24
25
  from .utils import NestedBuffer, RangeDict
25
26
  from .file import File
26
- from .pubkey_file import PubkeyFile, InlinePubkeyFile
27
+ from .pubkey_file import PubkeyFile, InlinePubkeyFile, UnknownPubkeyFileVersion
27
28
 
28
29
 
29
30
  class Blob(NestedBuffer):
@@ -47,7 +48,14 @@ class Blob(NestedBuffer):
47
48
  0xc20000,
48
49
  0x820000,
49
50
  0x120000,
51
+ # A second, minimal EFS with its own boot loader on AM5. Only taken at the start
52
+ # of a 16MB page, see EARLY_FET_OFFSET.
53
+ 0x001000,
50
54
  )
55
+ EARLY_FET_OFFSET = 0x001000
56
+
57
+ # Directory entry type of a FET for a separate image
58
+ ANOTHER_FET_TYPE = 0x46
51
59
 
52
60
  class NoFirmwareEntryTableError(Exception):
53
61
  pass
@@ -63,13 +71,25 @@ class Blob(NestedBuffer):
63
71
  rom_size = _rom_size * 1024 * 1024
64
72
  self.psptool.ph.print_warning(f"Input file is {self.buffer_size:#x}, will assume ROM size of {_rom_size}M")
65
73
 
74
+ # Early FETs go last, so that ROM 0 (the default of -X and -R) stays the main ROM
75
+ fet_locations = sorted(self._find_fets(),
76
+ key=lambda location: location % self._MAX_PAGE_SIZE == self.EARLY_FET_OFFSET)
77
+
66
78
  # For each FET, we try to create a ROM starting at `FET - offset`
67
- for fet_location in self._find_fets():
79
+ for fet_location in fet_locations:
80
+ another_fet = self._another_fet_at(fet_location)
81
+ if another_fet is not None:
82
+ # Its table addresses a separate image, not a ROM in this file
83
+ self.psptool.ph.print_info(f"Not parsing FET at {hex(fet_location)} inside {another_fet}")
84
+ continue
68
85
  fet_parsed = False
69
86
  for fet_offset in self.POSSIBLE_FET_OFFSETS:
70
87
  if fet_location < fet_offset:
71
88
  # would lead to Blob underflow
72
89
  continue
90
+ if fet_offset == self.EARLY_FET_OFFSET and (fet_location - fet_offset) % self._MAX_PAGE_SIZE:
91
+ # Too short an offset to tell a ROM start from data that looks like a FET
92
+ continue
73
93
  rom_page = int(fet_location / self._MAX_PAGE_SIZE)
74
94
  if fet_location - fet_offset + rom_size - rom_page * self._MAX_PAGE_SIZE > self.buffer_size:
75
95
  # would lead to Blob overflow
@@ -98,6 +118,17 @@ class Blob(NestedBuffer):
98
118
  def __repr__(self):
99
119
  return f'Blob({self.roms=})'
100
120
 
121
+ def _another_fet_at(self, address: int):
122
+ """The ANOTHER_FET entry of a parsed ROM holding this address, if any. Other entries
123
+ are not checked, as their sizes can overstate what they hold."""
124
+ for rom in self.roms:
125
+ for directory in rom.directories:
126
+ for file in directory.files:
127
+ if file.type == self.ANOTHER_FET_TYPE and \
128
+ file.get_address() <= address < file.get_address() + file.buffer_size:
129
+ return file
130
+ return None
131
+
101
132
  def _create_first_page_rom(self, rom_size, rom_offset, fet_offset):
102
133
  psptool = self.psptool
103
134
  directories = dict(psptool.directories_by_offset)
@@ -106,7 +137,7 @@ class Blob(NestedBuffer):
106
137
  try:
107
138
  return Rom(self, rom_size, rom_offset, fet_offset, psptool)
108
139
  except AssertionError as e:
109
- if 'overflows ROM bounds' not in str(e) or rom_offset + self._BIG_ROM_SIZE > self.buffer_size:
140
+ if 'overflows ROM bounds' not in str(e):
110
141
  raise
111
142
 
112
143
  # Drop what the failed attempt registered before parsing again
@@ -114,6 +145,12 @@ class Blob(NestedBuffer):
114
145
  psptool.files_by_offset = files
115
146
  for file, count in references.items():
116
147
  del file.references[count:]
148
+ if rom_offset + self._BIG_ROM_SIZE > self.buffer_size:
149
+ # The input is shorter than what its entries address, e.g. a region carved out of
150
+ # a capsule: keep what is there
151
+ psptool.ph.print_warning(f"File offset past the end of the input, skipping entries outside "
152
+ f"its {rom_size >> 20}M")
153
+ return Rom(self, rom_size, rom_offset, fet_offset, psptool, cut_short=True)
117
154
  psptool.ph.print_warning(f"File offset past {rom_size >> 20}M, will assume ROM size of "
118
155
  f"{self._BIG_ROM_SIZE >> 20}M")
119
156
  return Rom(self, self._BIG_ROM_SIZE, rom_offset, fet_offset, psptool)
@@ -158,55 +195,50 @@ class Blob(NestedBuffer):
158
195
  fet_offset = m.start() + 4
159
196
  yield fet_offset
160
197
 
161
- def _find_inline_pubkeys(self, fp):
198
+ def find_inline_pubkey_entries(self, ids) -> List[InlinePubkeyFile]:
199
+ """ Find public keys with the given key ids (hex strings) embedded in files with a
200
+ header, such as the keys in Zen 2 boot loaders that sign SMU, SEC_GASKET and
201
+ DEBUG_UNLOCK. A key is recognized by its version before the key id and its key
202
+ sizes, at any alignment. Found keys are added to the inline_keys of their file. """
203
+ if not ids:
204
+ return []
205
+ pattern = re.compile(b'|'.join(re.escape(binascii.a2b_hex(key_id)) for key_id in sorted(ids)))
162
206
 
163
- """ Try to find a pubkey in any of the found files.
164
- The pubkey is identified by its fingerprint. If found, the pubkey is
165
- added to the list of pubkeys of the blob """
166
207
  found_pubkeys = []
167
-
168
- for file in self.unique_files():
169
- if type(file) == PubkeyFile:
170
- continue # Pubkeys don't have inline keys but will only produce false positives
171
- m = re.finditer(re.escape(binascii.a2b_hex(fp)), file.get_bytes())
172
- for index in m:
173
- start_offset = index.start() - 4
174
- if int.from_bytes(self[start_offset:start_offset + 4], 'little') in PubkeyFile.KNOWN_VERSIONS:
175
- # Maybe a pubkey. Determine its size:
176
- pub_exp_size = int.from_bytes(self[start_offset + 0x38: start_offset + 0x3c],
177
- 'little')
178
- if pub_exp_size == 2048:
179
- size = 0x240
180
- elif pub_exp_size == 4096:
181
- size = 0x440
182
- else:
183
- continue
184
-
185
- key_id = self[start_offset + 0x04: start_offset + 0x14]
186
- cert_id = self[start_offset + 0x14: start_offset + 0x24]
187
-
188
- if key_id != cert_id and cert_id != b'\0' * 0x10:
189
- if pub_exp_size == 2048:
190
- size += 0x100
191
- else:
192
- size += 0x200
193
-
194
- try:
195
- file = InlinePubkeyFile(file, start_offset, size, self, self.psptool)
196
- assert isinstance(file, PubkeyFile)
197
- file.inline_keys.add(file)
198
- found_pubkeys.append(file)
199
- except File.ParseError as e:
200
- self.psptool.ph.print_warning(f"_find_pubkey: File parse error at 0x{start_offset:x}")
201
- self.psptool.ph.print_warning(f'{e}')
208
+ for file in sorted(self.unique_files()):
209
+ if isinstance(file, PubkeyFile) or not hasattr(file, 'inline_keys'):
210
+ continue
211
+ data = file.get_bytes()
212
+ for match in pattern.finditer(data):
213
+ inline_key = self._inline_pubkey_at(file, data, match.start() - 4)
214
+ if inline_key is not None:
215
+ file.inline_keys.add(inline_key)
216
+ found_pubkeys.append(inline_key)
202
217
 
203
218
  return found_pubkeys
204
219
 
205
- def find_inline_pubkey_entries(self, ids):
206
- found_pkes = []
207
- for key_id in ids:
208
- found_pkes += self._find_inline_pubkeys(key_id)
209
- return found_pkes
220
+ def _inline_pubkey_at(self, file: File, data: bytes, start: int):
221
+ if start < 0 or start + PubkeyFile.HEADER_LEN > len(data):
222
+ return None
223
+ version, = struct.unpack_from('<I', data, start)
224
+ pubexp_bits, modulus_bits = struct.unpack_from('<II', data, start + 0x38)
225
+ if version not in PubkeyFile.KNOWN_VERSIONS or pubexp_bits != modulus_bits or pubexp_bits not in (2048, 4096):
226
+ return None
227
+
228
+ size = PubkeyFile.HEADER_LEN + 2 * (pubexp_bits >> 3)
229
+ key_id = data[start + 0x04:start + 0x14]
230
+ certifying_id = data[start + 0x14:start + 0x24]
231
+ if certifying_id not in (key_id, bytes(0x10)):
232
+ # Signed key; assume the certifying key has the same size
233
+ size += pubexp_bits >> 3
234
+ if start + size > len(data):
235
+ return None
236
+
237
+ try:
238
+ return InlinePubkeyFile(file, start, size, self, self.psptool)
239
+ except (File.ParseError, UnknownPubkeyFileVersion, AssertionError) as e:
240
+ self.psptool.ph.print_warning(f"Could not parse inline key at 0x{file.get_address() + start:x}: {e}")
241
+ return None
210
242
 
211
243
  def get_files_by_type(self, type_) -> List[File]:
212
244
  all_files = self.unique_files()
@@ -52,7 +52,22 @@ class SignedEntity:
52
52
  @staticmethod
53
53
  def _from_pubkey_file(pkf, psptool):
54
54
  if pkf.is_signed:
55
- return SignedEntity(pkf, pkf.certifying_id, pkf.signature, psptool)
55
+ certifying_id = pkf.certifying_id
56
+ if certifying_id.get_bytes() == bytes(len(certifying_id)):
57
+ # An unnamed certifying key is the AMD root key of the same directory
58
+ # (SEC_DBG_PUBLIC_KEY on Mendocino)
59
+ root_key = SignedEntity._root_key_of(pkf)
60
+ if root_key is not None:
61
+ certifying_id = root_key.key_id
62
+ return SignedEntity(pkf, certifying_id, pkf.signature, psptool)
63
+ return None
64
+
65
+ @staticmethod
66
+ def _root_key_of(file):
67
+ for directory in file.references:
68
+ for other in directory.files:
69
+ if other is not file and other.type == 0x00 and type(other) is PubkeyFile:
70
+ return other
56
71
  return None
57
72
 
58
73
  @staticmethod
@@ -95,7 +110,26 @@ class SignedEntity:
95
110
  return True
96
111
 
97
112
  def verify_with_pubkey(self, pubkey: PublicKey) -> bool:
98
- return pubkey.verify_blob((self.file.get_signed_bytes()), self.signature.get_bytes())
113
+ if self._verify_signature_with_pubkey(pubkey, self.signature):
114
+ return True
115
+ signature_at_end = getattr(self.file, 'signature_at_end', None)
116
+ if signature_at_end is not None and self._verify_signature_with_pubkey(pubkey, signature_at_end):
117
+ self.file.use_signature_at_end()
118
+ self.signature = Signature.from_nested_buffer(self.file.signature)
119
+ return True
120
+ return False
121
+
122
+ def _verify_signature_with_pubkey(self, pubkey: PublicKey, signature: NestedBuffer) -> bool:
123
+ signature = signature.get_bytes()
124
+ if pubkey.verify_blob(self.file.get_signed_bytes(), signature):
125
+ return True
126
+ # Remember a signature over the body as stored, so that get_signed_bytes (and thus
127
+ # resigning) uses it from now on
128
+ if getattr(self.file, 'can_sign_stored_body', False) and not self.file.signs_stored_body:
129
+ if pubkey.verify_blob(self.file.get_stored_signed_bytes(), signature):
130
+ self.file.signs_stored_body = True
131
+ return True
132
+ return False
99
133
 
100
134
  # resigns this file only
101
135
  def resign_only(self, privkey: PrivateKey):
@@ -114,7 +148,7 @@ class SignedEntity:
114
148
  assert len(signature) == self.signature.buffer_size, f'Could not resign {self} with {privkey}: ' \
115
149
  f'The new signature has the wrong length ' \
116
150
  f'{len(signature)} != {self.signature.buffer_size}'
117
- self.signature.set_bytes(0, len(signature), signature)
151
+ self.signature.set_bytes(0, signature)
118
152
 
119
153
  def resign_and_replace(self, privkeys: PrivateKeyDict = None, recursive: bool = False):
120
154
  # this resigns self (multiple times!)
@@ -215,7 +249,7 @@ class PublicKeyEntity:
215
249
  def replace_crypto_material(self, crypto_material: bytes):
216
250
  assert len(crypto_material) == self._crypto_material.buffer_size, f'Crypto material has wrong size: {len(crypto_material)} != {self._crypto_material.buffer_size}'
217
251
  self._public_key = None
218
- self._crypto_material.set_bytes(0, len(crypto_material), crypto_material)
252
+ self._crypto_material.set_bytes(0, crypto_material)
219
253
 
220
254
  def replace_only(self, pubkey: PublicKey):
221
255
  print(f'Replacing {self}')
@@ -375,6 +409,9 @@ class CertificateTree:
375
409
  key_store_file.signed_entity = signed_entity
376
410
 
377
411
  for key_store_key in key_store_file.key_store.keys:
412
+ if key_store_key.is_lms:
413
+ # LMS signatures are not supported
414
+ continue
378
415
  pubkey = PublicKeyEntity._from_key_store_key(key_store_key, self.psptool)
379
416
  try:
380
417
  self.add_pubkey_entity(pubkey)
@@ -396,15 +433,38 @@ class CertificateTree:
396
433
  if type(file) == KeyStoreFile:
397
434
  ct.add_key_store_file(file)
398
435
 
399
- # Add unlisted/inline keys as found by additional blob parsing efforts
400
- ids_to_find = ct.ids
436
+ # Add unlisted/inline keys as found by additional blob parsing efforts, again for
437
+ # the ids the found keys bring in, as inline keys can certify each other
438
+ searched_ids = set()
439
+ ids_to_find = set(ct.ids)
401
440
  while ids_to_find:
441
+ searched_ids |= ids_to_find
402
442
  for pubkey in blob.find_inline_pubkey_entries(ids_to_find):
403
443
  ct.add_pubkey_file(pubkey)
404
- ids_to_find = ct.ids.difference(ids_to_find)
444
+ ids_to_find = ct.ids - searched_ids
445
+
446
+ # Settle where the signature of files with two candidates is, as that also decides
447
+ # their body for listing and extraction
448
+ for file in blob.unique_files():
449
+ if getattr(file, 'signature_at_end', None) is not None and file.signed_entity is not None:
450
+ try:
451
+ file.signed_entity.is_verified()
452
+ except errors.NoCertifyingKey:
453
+ pass
405
454
 
406
455
  return ct
407
456
 
457
+ def verify_all(self):
458
+ """Verify each signature once. Whether a compressed or encrypted file is signed as
459
+ stored or decrypted/decompressed is only known from a signature that verified, and
460
+ resigning replaces the keys it could verify with."""
461
+ for signed_entities in self.signed_entities.values():
462
+ for signed_entity in signed_entities:
463
+ try:
464
+ signed_entity.is_verified()
465
+ except errors.NoCertifyingKey:
466
+ pass
467
+
408
468
  def unique_pubkeys(self, key_id):
409
469
  unique_keys = list()
410
470
  for key in self.pubkeys[key_id]:
@@ -16,7 +16,7 @@
16
16
 
17
17
  import struct
18
18
 
19
- from .entry import DirectoryEntry, BiosDirectoryEntry
19
+ from .entry import DirectoryEntry, BiosDirectoryEntry, AddressMode
20
20
  from .utils import NestedBuffer, fletcher32
21
21
  from .file import File, BiosFile, SECONDARY_DIRECTORY_ENTRY_TYPES, TERTIARY_DIRECTORY_ENTRY_TYPES
22
22
 
@@ -31,11 +31,25 @@ class Directory(NestedBuffer):
31
31
  ENTRY_SIZE = DirectoryEntry.ENTRY_SIZE
32
32
  FILE_CLASS = File
33
33
 
34
+ # Platform IDs from the tertiary directory headers. For the newer ones, the boot loader
35
+ # version and image they were seen in.
34
36
  ZEN_GENERATION_IDS = {'Zen 1' : [b'\x00\x09\xBC', b'\x00\x0A\xBC'],
35
- 'Zen 2' : [b'\x05\x0B\xBC', b'\x01\x0A\xBC'],
36
- 'Zen 3' : [b'\x01\x0C\xBC', b'\x00\x0C\xBC'],
37
- 'Zen 4' : [b'\x04\x0D\xBC', b'\x0B\x0D\xBC'],
38
- 'Zen 4/5': [b'\x03\x0D\xBC']
37
+ 'Zen 2' : [b'\x05\x0B\xBC', b'\x01\x0A\xBC',
38
+ b'\x00\x0B\xBC', # 0.E.0.3B, Threadripper Pro (Supermicro M12SWA-TF)
39
+ b'\x09\x0D\xBC'], # 0.35.0.1D, Mendocino laptop (Lenovo l1cn*ww)
40
+ 'Zen 3' : [b'\x01\x0C\xBC', b'\x00\x0C\xBC',
41
+ b'\x0D\x0B\xBC'], # 0.26.0.29, Threadripper Pro (Supermicro M12SWA-TF)
42
+ 'Zen 3+' : [b'\x02\x0D\xBC'], # 0.28.0.6B, Rembrandt laptop (ASUS ROG)
43
+ 'Zen 4' : [b'\x04\x0D\xBC', b'\x0B\x0D\xBC',
44
+ b'\x01\x0D\xBC'], # 0.2A.0.22, Threadripper 7000 (Supermicro H13SRA)
45
+ 'Zen 4/5': [b'\x03\x0D\xBC'],
46
+ 'Zen 5' : [b'\x0B\x0E\xBC', # 0.3E.0.D0 and 0.3E.C.74, AM5 board and Ryzen AI 300 laptop
47
+ b'\x10\x0E\xBC', # 0.3E.0.D0, AM5 board (MSI)
48
+ b'\x02\x0E\xBC', # 0.3E.C.74, Ryzen AI 300 laptop (Framework Laptop 13)
49
+ b'\x09\x0E\xBC', # 0.40.2.65, Ryzen AI Max (Framework Desktop)
50
+ b'\x00\x0E\xBC', b'\x0C\x0E\xBC', # 0.47.0.1F, Threadripper 9000
51
+ b'\x0D\x0E\xBC', b'\x11\x0E\xBC'], # (Supermicro H13SRA)
52
+ 'Zen 6' : [b'\x00\x00\xBF'], # 0.43.1.76, EPYC Venice (Supermicro H15SPT-G)
39
53
  }
40
54
 
41
55
  # Empirical mapping from PSP_FW_BOOT_LOADER (entry type 0x01) version
@@ -49,6 +63,8 @@ class Directory(NestedBuffer):
49
63
  0x07: 'Zen 1', # Naples server (NaplesPI-SP3): H11DSI, MZ31-AR, S8026
50
64
  0x09: 'Zen 1', 0x0A: 'Zen 1', # Naples / Raven Ridge consumer
51
65
  0x0B: 'Zen 2', 0x0C: 'Zen 2', # Rome
66
+ 0x11: 'Zen 3', # Cezanne (0.11.1.81, coreboot image)
67
+ 0x1A: 'Zen 2', # Van Gogh (0.1A.0.30, Steam Deck F7A0115)
52
68
  0x13: 'Zen 3', # Milan
53
69
  0x29: 'Zen 4', # Genoa, Siena (Zen 4c shares the major)
54
70
  0x3D: 'Zen 5', # Turin (Bergamo also lands here per the issue)
@@ -70,19 +86,26 @@ class Directory(NestedBuffer):
70
86
  def bios_directory_class(cls):
71
87
  return BiosDirectory
72
88
 
89
+ @staticmethod
90
+ def blob_address(fet, offset) -> int:
91
+ """Key for psptool.directories_by_offset: ROMs in one file can hold different
92
+ directories at the same ROM offset (e.g. the two ROMs of Supermicro M12SWA-TF)"""
93
+ return fet.rom.get_address() + (offset & fet.rom.addr_mask)
94
+
73
95
  @classmethod
74
96
  def create_directories_if_not_exist(cls, offset, fet, zen_generation=None) -> List['Directory']:
75
97
  # Recursively return or create and return found directories
76
98
 
77
- if offset in fet.psptool.directories_by_offset:
78
- fet.psptool.directories_by_offset[offset].update_zen_generation(fet, zen_generation)
79
- return [fet.psptool.directories_by_offset[offset]]
99
+ key = cls.blob_address(fet, offset)
100
+ if key in fet.psptool.directories_by_offset:
101
+ fet.psptool.directories_by_offset[key].update_zen_generation(fet, zen_generation)
102
+ return [fet.psptool.directories_by_offset[key]]
80
103
  else:
81
104
  # 1. Create the immediate directory in front of us
82
105
  created_directories = []
83
106
  try:
84
107
  directory = cls.from_offset(fet, offset, zen_generation)
85
- fet.psptool.directories_by_offset[offset] = directory
108
+ fet.psptool.directories_by_offset[key] = directory
86
109
  created_directories.append(directory)
87
110
  except Directory.ParseError as e:
88
111
  # Handle empty entries gracefully (like master branch)
@@ -110,13 +133,23 @@ class Directory(NestedBuffer):
110
133
  continue
111
134
 
112
135
  actual_tertiary_offset = int.from_bytes(directory_body[16:20], 'little')
113
- zen_generation_id = directory_body[21:24]
114
- tertiary_zen_generation = cls.get_possible_zen_generation(zen_generation_id)
115
- if tertiary_zen_generation == 'unknown':
116
- fet.psptool.ph.print_warning(f"Unknown {zen_generation_id=}")
117
-
118
- zen_generation_id = hex(int.from_bytes(directory_body[20:24], 'little'))
119
- tertiary_zen_generation += f' (PSP ID {zen_generation_id})'
136
+ psp_id = directory_body[20:24]
137
+ # Slot headers without the leading checksum hold the L2 location at 0xc and
138
+ # leave the PSP ID erased (Van Gogh, Steam Deck F7A0115)
139
+ short_header_offset = int.from_bytes(directory_body[12:16], 'little')
140
+ if not cls._is_directory_at(fet, actual_tertiary_offset) and \
141
+ cls._is_directory_at(fet, short_header_offset):
142
+ actual_tertiary_offset = short_header_offset
143
+ psp_id = directory_body[16:20]
144
+
145
+ if psp_id == b'\xff' * 4:
146
+ tertiary_zen_generation = zen_generation
147
+ else:
148
+ zen_generation_id = psp_id[1:4]
149
+ tertiary_zen_generation = cls.get_possible_zen_generation(zen_generation_id)
150
+ if tertiary_zen_generation == 'unknown':
151
+ fet.psptool.ph.print_warning(f"Unknown {zen_generation_id=}")
152
+ tertiary_zen_generation += f' (PSP ID {hex(int.from_bytes(psp_id, "little"))})'
120
153
 
121
154
  # Resolve one more indirection
122
155
  tertiary_directories = cls.create_directories_if_not_exist(
@@ -125,9 +158,18 @@ class Directory(NestedBuffer):
125
158
 
126
159
  return created_directories
127
160
 
161
+ @classmethod
162
+ def _is_directory_at(cls, fet, offset) -> bool:
163
+ offset &= fet.rom.addr_mask
164
+ if offset + 4 > fet.rom.buffer_size:
165
+ return False
166
+ return fet.rom.get_bytes(offset, 4) in cls.DIRECTORY_MAGICS + BiosDirectory.DIRECTORY_MAGICS
167
+
128
168
  @classmethod
129
169
  def from_offset(cls, fet, rom_offset, zen_generation=None):
130
170
  rom_offset &= fet.rom.addr_mask
171
+ if rom_offset + 4 > fet.rom.buffer_size:
172
+ raise Directory.ParseError(f"Directory offset 0x{rom_offset:x} is outside the ROM")
131
173
  magic = fet.rom.get_bytes(rom_offset, 4)
132
174
 
133
175
  if magic == b'\xff\xff\xff\xff' or magic == b'\x00\x00\x00\x00':
@@ -174,6 +216,7 @@ class Directory(NestedBuffer):
174
216
  # create/link files
175
217
  for entry in self.entries:
176
218
  file = self.FILE_CLASS.create_file_if_not_exists(self, entry)
219
+ entry.file = file
177
220
  if file is not None:
178
221
  self.files.append(file)
179
222
 
@@ -204,18 +247,14 @@ class Directory(NestedBuffer):
204
247
  self.header[8:12] = struct.pack('<I', self.count)
205
248
  self.update_checksum()
206
249
 
207
- # 00b: x86 Physical address
208
- # 01b: Offset from start of the BIOS (flash offset)
209
- # 10b: Offset from start of directory header
210
- # 11b: Offset from start of partition
211
250
  @property
212
- def address_mode(self):
251
+ def address_mode(self) -> AddressMode:
213
252
  info = struct.unpack('<L', self.additional_info)[0]
214
253
  version = (info >> 31) & 1
215
254
  if version == 1:
216
- return (info >> 24) & 3
255
+ return AddressMode((info >> 24) & 3)
217
256
  else:
218
- return (info >> 29) & 3
257
+ return AddressMode((info >> 29) & 3)
219
258
 
220
259
  def verify_checksum(self):
221
260
  data = self[0x8:]
@@ -227,40 +266,28 @@ class Directory(NestedBuffer):
227
266
 
228
267
  def update_checksum(self):
229
268
  data = self[0x8:] # checksum is calculated from after the checksum field in the header
230
- self.checksum.set_bytes(0, 4, fletcher32(data))
269
+ self.checksum.set_bytes(0, fletcher32(data))
231
270
 
232
271
  def update_entry_fields(self, file: File, type_, size, offset):
233
- # 1. Find respective Entry for a given File
272
+ # 1. Find respective entry for a given file
234
273
  entry = None
235
- for index, my_entry in enumerate(self.entries):
236
- # We assume that each directory has at most one entry of a given type
237
- if my_entry.type == file.type:
238
- entry = my_entry
274
+ for e in self.entries:
275
+ if e.file is file:
276
+ entry = e
239
277
  break
240
- assert(entry is not None)
278
+ assert entry is not None, f'No entry for {file} in {self}'
241
279
 
242
280
  # 2. Update fields
243
281
  entry.type = type_
244
282
  if entry.type not in File.NO_SIZE_ENTRY_TYPES:
245
283
  entry.size = size
246
284
 
247
- # Convert the ROM buffer offset back to the value the entry expects, preserving address mode.
248
- # This mirrors the inverse of file_offset() in entry.py.
249
- addr_mode = self.address_mode
250
- if addr_mode == 2 or addr_mode == 3:
251
- addr_mode = entry.address_mode
252
-
253
- if addr_mode == 0:
254
- # x86 physical: preserve upper bits (e.g. 0xFF000000), replace lower bits
255
- addr_mask = self.rom.addr_mask
256
- upper_mask = 0xFFFFFFFF ^ addr_mask
257
- entry.offset = (entry.offset & upper_mask) | (offset & addr_mask)
258
- elif addr_mode == 1:
259
- entry.offset = offset
260
- elif addr_mode == 2 or addr_mode == 3:
261
- entry.offset = offset - self.buffer_offset
262
- else:
263
- entry.offset = offset
285
+ # file_offset() is affine in entry.offset (within the
286
+ # address mask), so shifting entry.offset by the file's
287
+ # displacement keeps the address mode and upper bits
288
+ # intact, and leaves in-place replacements untouched.
289
+ entry.offset += offset - entry.file_offset()
290
+ assert entry.file_offset() == offset, f'Offset {offset:#x} is not representable by {entry}'
264
291
 
265
292
  # 3. Update checksum
266
293
  self.update_checksum()
@@ -276,7 +303,7 @@ class Directory(NestedBuffer):
276
303
  else:
277
304
  return
278
305
  for offset in self.secondary_directory_offsets:
279
- dir = fet.psptool.directories_by_offset[offset]
306
+ dir = fet.psptool.directories_by_offset[self.blob_address(fet, offset)]
280
307
  dir.update_zen_generation(fet, zen_generation)
281
308
 
282
309