Debian Codegraph @

oslo_utils/imageutils/format_inspector.py

raw symbols SCIP
1 # Copyright 2020 Red Hat, Inc
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 """
17 This is a python implementation of virtual disk format inspection routines
18 gathered from various public specification documents, as well as qemu disk
19 driver code. It attempts to store and parse the minimum amount of data
20 required, and in a streaming-friendly manner to collect metadata about
21 complex-format images.
22 """
23
24 import abc
25 from collections.abc import Callable, Generator
26 import struct
27 from typing import cast, Any, IO, TypedDict
28 from collections.abc import Iterator
29
30 import logging
31 from oslo_utils._i18n import _
32 from oslo_utils import units
33
34 LOG = logging.getLogger(__name__)
35
36
37 def _chunked_reader(
38 fileobj: IO[bytes] | 'InspectWrapper', chunk_size: int = 512
39 ) -> Generator[bytes, None, None]:
40 while True:
41 chunk = fileobj.read(chunk_size)
42 if not chunk:
43 break
44 yield chunk
45
46
47 class CaptureRegion:
48 """Represents a region of a file we want to capture.
49
50 A region of a file we want to capture requires a byte offset into
51 the file and a length. This is expected to be used by a data
52 processing loop, calling capture() with the most recently-read
53 chunk. This class handles the task of grabbing the desired region
54 of data across potentially multiple fractional and unaligned reads.
55
56 :param offset: Byte offset into the file starting the region
57 :param length: The length of the region
58 :param min_length: Consider this region complete if it has captured at
59 least this much data. This should generally NOT be used
60 but may be required for certain formats with highly
61 variable data structures.
62 """
63
64 def __init__(
65 self, offset: int, length: int, min_length: int | None = None
66 ) -> None:
67 self.offset = offset
68 self.length = length
69 self.data: bytes | bytearray = b''
70 self.min_length = min_length
71
72 @property
73 def complete(self) -> bool:
74 """Returns True when we have captured the desired data."""
75 if self.min_length is not None:
76 return self.min_length <= len(self.data)
77 else:
78 return self.length == len(self.data)
79
80 def capture(self, chunk: bytes, current_position: int) -> bytes:
81 """Process a chunk of data.
82
83 This should be called for each chunk in the read loop, at least
84 until complete returns True.
85
86 :param chunk: A chunk of bytes in the file
87 :param current_position: The position of the file processed by the
88 read loop so far. Note that this will be
89 the position in the file *after* the chunk
90 being presented.
91 """
92 read_start = current_position - len(chunk)
93 if (
94 read_start <= self.offset <= current_position
95 or self.offset <= read_start <= (self.offset + self.length)
96 ):
97 if read_start < self.offset:
98 lead_gap = self.offset - read_start
99 else:
100 lead_gap = 0
101 self.data += chunk[lead_gap:]
102 self.data = self.data[: self.length]
103 return b''
104
105
106 class EndCaptureRegion(CaptureRegion):
107 """Represents a region that captures the last N bytes of a stream.
108
109 This can only capture the last N bytes of a stream and not an arbitrary
110 region referenced from the end of the file since in most cases we do not
111 know how much data we will read.
112
113 :param offset: Byte offset from the end of the stream to capture (which
114 will also be the region length)
115 """
116
117 def __init__(self, offset: int) -> None:
118 super().__init__(offset, offset)
119 # We don't want to indicate completeness until we have the data we
120 # want *and* have reached EOF
121 self._complete = False
122
123 def capture(self, chunk: bytes, current_position: int) -> bytes:
124 self.data += chunk
125 self.data = self.data[0 - self.length :]
126 self.offset = current_position - len(self.data)
127 return b''
128
129 @property
130 def complete(self) -> bool:
131 return super().complete and self._complete
132
133 def finish(self) -> None:
134 """Indicate that the entire stream has been read."""
135 self._complete = True
136
137
138 class SafetyCheck:
139 """Represents a named safety check on an inspector"""
140
141 def __init__(
142 self,
143 name: str,
144 target_fn: Callable[[], None],
145 description: str | None = None,
146 ) -> None:
147 """A safety check, it's meta info, and result.
148
149 :param name: Should be a short name of the check (ideally no spaces)
150 :param target_fn: The implementation we run (no args) which returns
151 either None if the check passes, or a string reason why it failed.
152 :param description: An optional longer-format human-readable string
153 that describes the check.
154 """
155 self.name = name
156 self.target_fn = target_fn
157 self.description = description
158
159 def __call__(self) -> None:
160 """Executes the target check function, records the result.
161
162 :raises SafetyViolation: If an error check fails
163 """
164 try:
165 self.target_fn()
166 except SafetyViolation:
167 raise
168 except Exception as e:
169 LOG.error(
170 'Failed to run safety check %s on %s inspector: %s',
171 self.name,
172 self,
173 e,
174 )
175 raise SafetyViolation(_('Unexpected error'))
176
177 @classmethod
178 def null(cls) -> 'SafetyCheck':
179 """The "null" safety check always returns True.
180
181 This should only be used if there is no meaningful checks that can
182 be done for a given format.
183 """
184 return cls(
185 'null',
186 lambda: None,
187 _('This file format has no meaningful safety check'),
188 )
189
190 @classmethod
191 def banned(cls) -> 'SafetyCheck':
192 """The "banned" safety check always returns False.
193
194 This should be used for formats we want to identify but never allow,
195 generally because they are unsupported by any of our users and/or
196 we are unable to check for safety.
197 """
198
199 def fail() -> None:
200 raise SafetyViolation(_('This file format is not allowed'))
201
202 return cls('banned', fail, _('This file format is not allowed'))
203
204
205 class ImageFormatError(Exception):
206 """An unrecoverable image format error that aborts the process."""
207
208 pass
209
210
211 class SafetyViolation(Exception):
212 """Indicates a failure of a single safety violation."""
213
214 pass
215
216
217 class SafetyCheckFailed(Exception):
218 """Indictes that one or more of a series of safety checks failed."""
219
220 def __init__(self, failures: dict[str, Any]) -> None:
221 super().__init__(
222 _('Safety checks failed: %s') % ','.join(failures.keys())
223 )
224 self.failures = failures
225
226
227 class FileInspector(abc.ABC):
228 """A stream-based disk image inspector.
229
230 This base class works on raw images and is subclassed for more
231 complex types. It is to be presented with the file to be examined
232 one chunk at a time, during read processing and will only store
233 as much data as necessary to determine required attributes of
234 the file.
235 """
236
237 # This should match what qemu-img thinks this format is
238 NAME = ''
239
240 def __init__(self, tracing: bool = False) -> None:
241 self._total_count = 0
242
243 # NOTE(danms): The logging in here is extremely verbose for a reason,
244 # but should never really be enabled at that level at runtime. To
245 # retain all that work and assist in future debug, we have a separate
246 # debug flag that can be passed from a manual tool to turn it on.
247 self._tracing = tracing
248 self._capture_regions: dict[str, CaptureRegion] = {}
249 self._safety_checks: dict[str, SafetyCheck] = {}
250 self._finished = False
251 self._initialize()
252 if not self._safety_checks:
253 # Make sure we actively declare some safety check, even if it
254 # is a no-op.
255 raise RuntimeError(
256 'All inspectors must define at least one safety check'
257 )
258
259 def _trace(self, *args: Any, **kwargs: Any) -> None:
260 if self._tracing:
261 LOG.debug(*args, **kwargs)
262
263 @abc.abstractmethod
264 def _initialize(self) -> None:
265 """Set up inspector before we start processing data.
266
267 This should add the initial set of capture regions and safety checks.
268 """
269
270 def finish(self) -> None:
271 """Indicate that the entire stream has been read.
272
273 This should be called when the entire stream has been completely read,
274 which will mark any EndCaptureRegion objects as complete.
275 """
276 self._finished = True
277 for region in self._capture_regions.values():
278 if isinstance(region, EndCaptureRegion):
279 region.finish()
280
281 def _capture(self, chunk: bytes, only: list[str] | None = None) -> None:
282 if self._finished:
283 raise RuntimeError(
284 'Inspector has been marked finished, '
285 'no more data processing allowed'
286 )
287 for name, region in self._capture_regions.items():
288 if only and name not in only:
289 continue
290 if isinstance(region, EndCaptureRegion) or not region.complete:
291 region.capture(chunk, self._total_count)
292
293 def eat_chunk(self, chunk: bytes) -> None:
294 """Call this to present chunks of the file to the inspector."""
295 pre_regions = set(self._capture_regions.values())
296 pre_complete = {
297 region
298 for region in self._capture_regions.values()
299 if region.complete
300 }
301
302 # Increment our position-in-file counter
303 self._total_count += len(chunk)
304
305 # Run through the regions we know of to see if they want this
306 # data
307 self._capture(chunk)
308
309 # Let the format do some post-read processing of the stream
310 self.post_process()
311
312 # Check to see if the post-read processing added new regions
313 # which may require the current chunk.
314 new_regions = set(self._capture_regions.values()) - pre_regions
315 if new_regions:
316 self._capture(
317 chunk, only=[self.region_name(r) for r in new_regions]
318 )
319
320 post_complete = {
321 region
322 for region in self._capture_regions.values()
323 if region.complete
324 }
325 # Call the handler for any regions that are newly complete
326 for region in post_complete - pre_complete:
327 self.region_complete(self.region_name(region))
328
329 def post_process(self) -> None:
330 """Post-read hook to process what has been read so far.
331
332 This will be called after each chunk is read and potentially captured
333 by the defined regions. If any regions are defined by this call,
334 those regions will be presented with the current chunk in case it
335 is within one of the new regions.
336 """
337 pass
338
339 def region(self, name: str) -> CaptureRegion:
340 """Get a CaptureRegion by name."""
341 return self._capture_regions[name]
342
343 def region_name(self, region: CaptureRegion) -> str:
344 """Return the region name for a region object."""
345 for name in self._capture_regions:
346 if self._capture_regions[name] is region:
347 return name
348 raise ValueError('No such region')
349
350 def new_region(self, name: str, region: CaptureRegion) -> None:
351 """Add a new CaptureRegion by name."""
352 if self.has_region(name):
353 # This is a bug, we tried to add the same region twice
354 raise ImageFormatError(f'Inspector re-added region {name}')
355 self._capture_regions[name] = region
356
357 def has_region(self, name: str) -> bool:
358 """Returns True if named region has been defined."""
359 return name in self._capture_regions
360
361 def delete_region(self, name: str) -> None:
362 """Remove a capture region by name.
363
364 This will raise KeyError if the region does not exist.
365 """
366 del self._capture_regions[name]
367
368 def region_complete(self, region_name: str) -> None:
369 """Called when a region becomes complete.
370
371 Subclasses may implement this if they need to do one-time processing
372 of a region's data.
373 """
374 pass
375
376 def add_safety_check(self, check: SafetyCheck) -> None:
377 if not isinstance(check, SafetyCheck):
378 raise RuntimeError(
379 _('Unable to add safety check of type %s')
380 % (type(check).__name__)
381 )
382 if check.name in self._safety_checks:
383 raise RuntimeError(_('Duplicate check of name %s') % check.name)
384 self._safety_checks[check.name] = check
385
386 @property
387 @abc.abstractmethod
388 def format_match(self) -> bool:
389 """Returns True if the file appears to be the expected format."""
390
391 @property
392 def virtual_size(self) -> int:
393 """Returns the virtual size of the disk image, or zero if unknown."""
394 return self._total_count
395
396 @property
397 def actual_size(self) -> int:
398 """Returns the total size of the file, usually smaller than
399 virtual_size. NOTE: this will only be accurate if the entire
400 file is read and processed.
401 """
402 return self._total_count
403
404 @property
405 def complete(self) -> bool:
406 """Returns True if we have all the information needed."""
407 return all(r.complete for r in self._capture_regions.values())
408
409 def __str__(self) -> str:
410 """The string name of this file format."""
411 return self.NAME
412
413 @property
414 def context_info(self) -> dict[str, int]:
415 """Return info on amount of data held in memory for auditing.
416
417 This is a dict of region:sizeinbytes items that the inspector
418 uses to examine the file.
419 """
420 return {
421 name: len(region.data)
422 for name, region in self._capture_regions.items()
423 }
424
425 @classmethod
426 def from_file(cls, filename: str) -> 'FileInspector':
427 """Read as much of a file as necessary to complete inspection.
428
429 NOTE: Because we only read as much of the file as necessary, the
430 actual_size property will not reflect the size of the file, but the
431 amount of data we read before we satisfied the inspector.
432
433 :raises ImageFormatError: If we cannot parse the file.
434 """
435 inspector = cls()
436 with open(filename, 'rb') as f:
437 for chunk in _chunked_reader(f):
438 inspector.eat_chunk(chunk)
439 if inspector.complete:
440 # No need to eat any more data
441 break
442 inspector.finish()
443 if not inspector.complete or not inspector.format_match:
444 raise ImageFormatError('File is not in requested format')
445 return inspector
446
447 def safety_check(self) -> None:
448 """Perform all checks to determine if this file is safe.
449
450 :raises ImageFormatError: If safety cannot be guaranteed because of
451 parsing or other errors.
452 :raises SafetyCheckFailed: If one or more checks fails.
453 """
454 if not self.complete:
455 raise ImageFormatError(
456 _('Incomplete file cannot be safety checked')
457 )
458 if not self.format_match:
459 raise ImageFormatError(
460 _(
461 'Unable to safety check format %s '
462 'because content does not match'
463 )
464 % self
465 )
466 failures = {}
467 for check in self._safety_checks.values():
468 try:
469 check()
470 except SafetyViolation as exc:
471 exc.check = check # type: ignore[attr-defined]
472 failures[check.name] = exc
473 LOG.warning(
474 'Safety check %s on %s failed because %s',
475 check.name,
476 self,
477 exc,
478 )
479 if failures:
480 raise SafetyCheckFailed(failures)
481
482
483 class RawFileInspector(FileInspector):
484 NAME = 'raw'
485
486 def _initialize(self) -> None:
487 """Raw files have nothing to capture and no safety checks."""
488 self.add_safety_check(SafetyCheck.null())
489
490 @property
491 def format_match(self) -> bool:
492 # By definition, raw files are unformatted and thus we always match
493 return True
494
495
496 # The qcow2 format consists of a big-endian 72-byte header, of which
497 # only a small portion has information we care about:
498 #
499 # Dec Hex Name
500 # 0 0x00 Magic 4-bytes 'QFI\xfb'
501 # 4 0x04 Version (uint32_t, should always be 2 for modern files)
502 # . . .
503 # 8 0x08 Backing file offset (uint64_t)
504 # 24 0x18 Size in bytes (unint64_t)
505 # . . .
506 # 72 0x48 Incompatible features bitfield (6 bytes)
507 #
508 # https://gitlab.com/qemu-project/qemu/-/blob/master/docs/interop/qcow2.txt
509 class QEMUHeader(TypedDict, total=False):
510 magic: bytes
511 version: int
512 bf_offset: int
513 bf_sz: int
514 cluster_bits: int
515 size: int
516
517
518 class QcowInspector(FileInspector):
519 """QEMU QCOW Format
520
521 This should only require about 32 bytes of the beginning of the file
522 to determine the virtual size, and 104 bytes to perform the safety check.
523
524 This recognizes the (very) old v1 format but will raise a SafetyViolation
525 for it, as it should definitely not be in production use at this point.
526 """
527
528 NAME = 'qcow2'
529 BF_OFFSET = 0x08
530 BF_OFFSET_LEN = 8
531 I_FEATURES = 0x48
532 I_FEATURES_LEN = 8
533 I_FEATURES_DATAFILE_BIT = 3
534 I_FEATURES_MAX_BIT = 4
535
536 def _initialize(self) -> None:
537 self.qemu_header_info: QEMUHeader = {}
538 self.new_region('header', CaptureRegion(0, 512))
539 self.add_safety_check(
540 SafetyCheck('backing_file', self.check_backing_file)
541 )
542 self.add_safety_check(SafetyCheck('data_file', self.check_data_file))
543 self.add_safety_check(
544 SafetyCheck('unknown_features', self.check_unknown_features)
545 )
546
547 def region_complete(self, region_name: str) -> None:
548 self.qemu_header_info = cast(
549 QEMUHeader,
550 dict(
551 zip(
552 (
553 'magic',
554 'version',
555 'bf_offset',
556 'bf_sz',
557 'cluster_bits',
558 'size',
559 ),
560 struct.unpack('>4sIQIIQ', self.region('header').data[:32]),
561 )
562 ),
563 )
564 if not self.format_match:
565 self.qemu_header_info = {}
566
567 @property
568 def virtual_size(self) -> int:
569 return self.qemu_header_info.get('size', 0)
570
571 @property
572 def format_match(self) -> bool:
573 if not self.region('header').complete:
574 return False
575 return self.qemu_header_info.get('magic') == b'QFI\xfb'
576
577 def check_backing_file(self) -> None:
578 bf_offset_bytes = self.region('header').data[
579 self.BF_OFFSET : self.BF_OFFSET + self.BF_OFFSET_LEN
580 ]
581 # nonzero means "has a backing file"
582 (bf_offset,) = struct.unpack('>Q', bf_offset_bytes)
583 if bf_offset != 0:
584 raise SafetyViolation('Image has a backing file')
585
586 def check_unknown_features(self) -> None:
587 ver = self.qemu_header_info.get('version')
588 if ver == 2:
589 # Version 2 did not have the feature flag array, so no need to
590 # check it here.
591 return
592 elif ver != 3:
593 raise SafetyViolation('Unsupported qcow2 version')
594
595 i_features = self.region('header').data[
596 self.I_FEATURES : self.I_FEATURES + self.I_FEATURES_LEN
597 ]
598
599 # This is the maximum byte number we should expect any bits to be set
600 max_byte = self.I_FEATURES_MAX_BIT // 8
601
602 # The flag bytes are in big-endian ordering, so if we process
603 # them in index-order, they're reversed
604 for i, byte_num in enumerate(reversed(range(self.I_FEATURES_LEN))):
605 if byte_num == max_byte:
606 # If we're in the max-allowed byte, allow any bits less than
607 # the maximum-known feature flag bit to be set
608 allow_mask = (1 << (self.I_FEATURES_MAX_BIT % 8)) - 1
609 elif byte_num > max_byte:
610 # If we're above the byte with the maximum known feature flag
611 # bit, then we expect all zeroes
612 allow_mask = 0x0
613 else:
614 # Any earlier-than-the-maximum byte can have any of the flag
615 # bits set
616 allow_mask = 0xFF
617
618 if i_features[i] & ~allow_mask:
619 LOG.warning(
620 'Found unknown feature bit in byte %i: %s/%s',
621 byte_num,
622 bin(i_features[byte_num] & ~allow_mask),
623 bin(allow_mask),
624 )
625 raise SafetyViolation('Unknown QCOW2 features found')
626
627 def check_data_file(self) -> None:
628 i_features = self.region('header').data[
629 self.I_FEATURES : self.I_FEATURES + self.I_FEATURES_LEN
630 ]
631
632 # First byte of bitfield, which is i_features[7]
633 byte = self.I_FEATURES_LEN - 1 - self.I_FEATURES_DATAFILE_BIT // 8
634 # Third bit of bitfield, which is 0x04
635 bit = 1 << (self.I_FEATURES_DATAFILE_BIT - 1 % 8)
636 if bool(i_features[byte] & bit):
637 raise SafetyViolation('Image has data_file set')
638
639
640 class QEDInspector(FileInspector):
641 NAME = 'qed'
642
643 def _initialize(self) -> None:
644 self.new_region('header', CaptureRegion(0, 512))
645 # QED format is not supported by anyone, but we want to detect it
646 # and mark it as just always unsafe.
647 self.add_safety_check(SafetyCheck.banned())
648
649 @property
650 def format_match(self) -> bool:
651 if not self.region('header').complete:
652 return False
653 return self.region('header').data.startswith(b'QED\x00')
654
655
656 # The VHD (or VPC as QEMU calls it) format consists of a big-endian
657 # 512-byte "footer" at the beginning of the file with various
658 # information, most of which does not matter to us:
659 #
660 # Dec Hex Name
661 # 0 0x00 Magic string (8-bytes, always 'conectix')
662 # 40 0x28 Disk size (uint64_t)
663 #
664 # https://github.com/qemu/qemu/blob/master/block/vpc.c
665 class VHDInspector(FileInspector):
666 """Connectix/MS VPC VHD Format
667
668 This should only require about 512 bytes of the beginning of the file
669 to determine the virtual size.
670 """
671
672 NAME = 'vhd'
673
674 def _initialize(self) -> None:
675 self.new_region('header', CaptureRegion(0, 512))
676 self.add_safety_check(SafetyCheck.null())
677
678 @property
679 def format_match(self) -> bool:
680 return self.region('header').data.startswith(b'conectix')
681
682 @property
683 def virtual_size(self) -> int:
684 if not self.region('header').complete:
685 return 0
686
687 if not self.format_match:
688 return 0
689
690 return cast(
691 int, struct.unpack('>Q', self.region('header').data[40:48])[0]
692 )
693
694
695 # The VHDX format consists of a complex dynamic little-endian
696 # structure with multiple regions of metadata and data, linked by
697 # offsets with in the file (and within regions), identified by MSFT
698 # GUID strings. The header is a 320KiB structure, only a few pieces of
699 # which we actually need to capture and interpret:
700 #
701 # Dec Hex Name
702 # 0 0x00000 Identity (Technically 9-bytes, padded to 64KiB, the first
703 # 8 bytes of which are 'vhdxfile')
704 # 196608 0x30000 The Region table (64KiB of a 32-byte header, followed
705 # by up to 2047 36-byte region table entry structures)
706 #
707 # The region table header includes two items we need to read and parse,
708 # which are:
709 #
710 # 196608 0x30000 4-byte signature ('regi')
711 # 196616 0x30008 Entry count (uint32-t)
712 #
713 # The region table entries follow the region table header immediately
714 # and are identified by a 16-byte GUID, and provide an offset of the
715 # start of that region. We care about the "metadata region", identified
716 # by the METAREGION class variable. The region table entry is (offsets
717 # from the beginning of the entry, since it could be in multiple places):
718 #
719 # 0 0x00000 16-byte MSFT GUID
720 # 16 0x00010 Offset of the actual metadata region (uint64_t)
721 #
722 # When we find the METAREGION table entry, we need to grab that offset
723 # and start examining the region structure at that point. That
724 # consists of a metadata table of structures, which point to places in
725 # the data in an unstructured space that follows. The header is
726 # (offsets relative to the region start):
727 #
728 # 0 0x00000 8-byte signature ('metadata')
729 # . . .
730 # 16 0x00010 2-byte entry count (up to 2047 entries max)
731 #
732 # This header is followed by the specified number of metadata entry
733 # structures, identified by GUID:
734 #
735 # 0 0x00000 16-byte MSFT GUID
736 # 16 0x00010 4-byte offset (uint32_t, relative to the beginning of
737 # the metadata region)
738 #
739 # We need to find the "Virtual Disk Size" metadata item, identified by
740 # the GUID in the VIRTUAL_DISK_SIZE class variable, grab the offset,
741 # add it to the offset of the metadata region, and examine that 8-byte
742 # chunk of data that follows.
743 #
744 # The "Virtual Disk Size" is a naked uint64_t which contains the size
745 # of the virtual disk, and is our ultimate target here.
746 #
747 # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-vhdx/83e061f8-f6e2-4de1-91bd-5d518a43d477
748 class VHDXInspector(FileInspector):
749 """MS VHDX Format
750
751 This requires some complex parsing of the stream. The first 256KiB
752 of the image is stored to get the header and region information,
753 and then we capture the first metadata region to read those
754 records, find the location of the virtual size data and parse
755 it. This needs to store the metadata table entries up until the
756 VDS record, which may consist of up to 2047 32-byte entries at
757 max. Finally, it must store a chunk of data at the offset of the
758 actual VDS uint64.
759
760 """
761
762 NAME = 'vhdx'
763 METAREGION = '8B7CA206-4790-4B9A-B8FE-575F050F886E'
764 VIRTUAL_DISK_SIZE = '2FA54224-CD1B-4876-B211-5DBED83BF4B8'
765 VHDX_METADATA_TABLE_MAX_SIZE = 32 * 2048 # From qemu
766
767 def _initialize(self) -> None:
768 self.new_region('ident', CaptureRegion(0, 32))
769 self.new_region('header', CaptureRegion(192 * 1024, 64 * 1024))
770 self.add_safety_check(SafetyCheck.null())
771
772 def post_process(self) -> None:
773 # After reading a chunk, we may have the following conditions:
774 #
775 # 1. We may have just completed the header region, and if so,
776 # we need to immediately read and calculate the location of
777 # the metadata region, as it may be starting in the same
778 # read we just did.
779 # 2. We may have just completed the metadata region, and if so,
780 # we need to immediately calculate the location of the
781 # "virtual disk size" record, as it may be starting in the
782 # same read we just did.
783 if self.region('header').complete and not self.has_region('metadata'):
784 region = self._find_meta_region()
785 if region:
786 self.new_region('metadata', region)
787 elif self.has_region('metadata') and not self.has_region('vds'):
788 region = self._find_meta_entry(self.VIRTUAL_DISK_SIZE)
789 if region:
790 self.new_region('vds', region)
791
792 @property
793 def format_match(self) -> bool:
794 return self.region('ident').data.startswith(b'vhdxfile')
795
796 @staticmethod
797 def _guid(buf: bytes | bytearray) -> str:
798 """Format a MSFT GUID from the 16-byte input buffer."""
799 guid_format = '<IHHBBBBBBBB'
800 return (
801 '{:08X}-{:04X}-{:04X}-{:02X}{:02X}-'
802 '{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}'
803 ).format(*struct.unpack(guid_format, buf))
804
805 def _find_meta_region(self) -> CaptureRegion | None:
806 # The region table entries start after a 16-byte table header
807 region_entry_first = 16
808
809 # Parse the region table header to find the number of regions
810 regi, cksum, count, reserved = struct.unpack(
811 '<IIII', self.region('header').data[:16]
812 )
813 if regi != 0x69676572:
814 raise ImageFormatError(
815 'Region signature not found at {:x}'.format(
816 self.region('header').offset
817 )
818 )
819
820 if count >= 2048:
821 raise ImageFormatError('Region count is {int(count)} (limit 2047)')
822
823 # Process the regions until we find the metadata one; grab the
824 # offset and return
825 self._trace('Region entry first is %x', region_entry_first)
826 self._trace('Region entries %i', count)
827 meta_offset = 0
828 for i in range(0, count):
829 entry_start = region_entry_first + (i * 32)
830 entry_end = entry_start + 32
831 entry = self.region('header').data[entry_start:entry_end]
832 self._trace('Entry offset is %x', entry_start)
833
834 # GUID is the first 16 bytes
835 guid = self._guid(entry[:16])
836 if guid == self.METAREGION:
837 # This entry is the metadata region entry
838 meta_offset, meta_len, meta_req = struct.unpack(
839 '<QII', entry[16:]
840 )
841 self._trace(
842 'Meta entry %i specifies offset: %x', i, meta_offset
843 )
844 # NOTE(danms): The meta_len in the region descriptor is the
845 # entire size of the metadata table and data. This can be
846 # very large, so we should only capture the size required
847 # for the maximum length of the table, which is one 32-byte
848 # table header, plus up to 2047 32-byte entries.
849 meta_len = 2048 * 32
850 return CaptureRegion(meta_offset, meta_len)
851
852 self._trace('Did not find metadata region')
853 return None
854
855 def _find_meta_entry(self, desired_guid: str) -> CaptureRegion | None:
856 meta_buffer = self.region('metadata').data
857 if len(meta_buffer) < 32:
858 # Not enough data yet for full header
859 return None
860
861 # Make sure we found the metadata region by checking the signature
862 sig, reserved, count = struct.unpack('<8sHH', meta_buffer[:12])
863 if sig != b'metadata':
864 raise ImageFormatError(
865 f'Invalid signature for metadata region: {sig!r}'
866 )
867
868 entries_size = 32 + (count * 32)
869 if len(meta_buffer) < entries_size:
870 # Not enough data yet for all metadata entries. This is not
871 # strictly necessary as we could process whatever we have until
872 # we find the V-D-S one, but there are only 2047 32-byte
873 # entries max (~64k).
874 return None
875
876 if count >= 2048:
877 raise ImageFormatError(
878 'Metadata item count is {int(count)} (limit 2047)'
879 )
880
881 for i in range(0, count):
882 entry_offset = 32 + (i * 32)
883 guid = self._guid(meta_buffer[entry_offset : entry_offset + 16])
884 if guid == desired_guid:
885 # Found the item we are looking for by id.
886 # Stop our region from capturing
887 item_offset, item_length, _reserved = struct.unpack(
888 '<III', meta_buffer[entry_offset + 16 : entry_offset + 28]
889 )
890 item_length = min(
891 item_length, self.VHDX_METADATA_TABLE_MAX_SIZE
892 )
893 self.region('metadata').length = len(meta_buffer)
894 self._trace('Found entry at offset %x', item_offset)
895 # Metadata item offset is from the beginning of the metadata
896 # region, not the file.
897 return CaptureRegion(
898 self.region('metadata').offset + item_offset, item_length
899 )
900
901 self._trace('Did not find guid %s', desired_guid)
902 return None
903
904 @property
905 def virtual_size(self) -> int:
906 # Until we have found the offset and have enough metadata buffered
907 # to read it, return "unknown"
908 if not self.has_region('vds') or not self.region('vds').complete:
909 return 0
910
911 (size,) = struct.unpack('<Q', self.region('vds').data)
912 return cast(int, size)
913
914
915 # The VMDK format comes in a large number of variations, but the
916 # single-file 'monolithicSparse' version 4 one is mostly what we care
917 # about. It contains a 512-byte little-endian header, followed by a
918 # variable-length "descriptor" region of text. The header looks like:
919 #
920 # Dec Hex Name
921 # 0 0x00 4-byte magic string 'KDMV'
922 # 4 0x04 Version (uint32_t)
923 # 8 0x08 Flags (uint32_t, unused by us)
924 # 12 0x0C Number of 512 byte sectors in the disk (uint64_t)
925 # 20 0x14 Granularity (uint64_t, unused by us)
926 # 28 0x1C Descriptor offset in 512-byte sectors (uint64_t)
927 # 36 0x24 Descriptor size in 512-byte sectors (uint64_t)
928 # 44 0x2C Number of GTEs per GT (uint32_t)
929 # 48 0x30 Redundant level 0 metadata offset (uint64_t)
930 # 56 0x38 Pointer to level 0 of metadata (uint32_t)
931 #
932 # After we have the header, we need to find the descriptor region,
933 # which starts at the sector identified in the "descriptor offset"
934 # field, and is "descriptor size" 512-byte sectors long. Once we have
935 # that region, we need to parse it as text, looking for the
936 # createType=XXX line that specifies the mechanism by which the data
937 # extents are stored in this file. We only support the
938 # "monolithicSparse" format, so we just need to confirm that this file
939 # contains that specifier.
940 #
941 # https://www.vmware.com/app/vmdk/?src=vmdk
942 class VMDKInspector(FileInspector):
943 """vmware VMDK format (monolithicSparse and streamOptimized variants only)
944
945 This needs to store the 512 byte header and the descriptor region
946 which should be just after that. The descriptor region is some
947 variable number of 512 byte sectors, but is just text defining the
948 layout of the disk.
949 """
950
951 NAME = 'vmdk'
952 # The beginning and max size of the descriptor is also hardcoded in Qemu
953 # at 0x200 and 1MB - 1
954 DESC_OFFSET = 0x200
955 DESC_MAX_SIZE = (1 << 20) - 1
956 GD_AT_END = 0xFFFFFFFFFFFFFFFF
957 # This is the minimum amount of data we need to read to recognize and
958 # process a "Hosted Sparse Extent" header
959 MIN_SPARSE_HEADER = 64
960 MARKER_EOS = 0
961 MARKER_FOOTER = 3
962
963 def _initialize(self) -> None:
964 self.desc_text: str | None = None
965 # This is the header for "Hosted Sparse Extent" type files. It may
966 # or may not be used, depending on what kind of VMDK we are about to
967 # read.
968 self.new_region(
969 'header', CaptureRegion(0, 512, min_length=self.MIN_SPARSE_HEADER)
970 )
971 # The descriptor starts from the beginning in the some of the older
972 # formats, but we do not know which one we are reading yet. This
973 # will be deleted and re-created if we are reading one of the formats
974 # that embeds it later.
975 self.new_region(
976 'descriptor', CaptureRegion(0, self.DESC_MAX_SIZE, min_length=4)
977 )
978 self.add_safety_check(SafetyCheck('descriptor', self.check_descriptor))
979
980 def _parse_sparse_header(
981 self, region: str, offset: int = 0
982 ) -> tuple[bytes, int, int, int, int]:
983 (
984 sig,
985 ver,
986 _flags,
987 _sectors,
988 _grain,
989 desc_sec,
990 desc_num,
991 _numGTEsperGT,
992 _rgdOffset,
993 gdOffset,
994 ) = struct.unpack(
995 '<4sIIQQQQIQQ',
996 self.region(region).data[offset : offset + self.MIN_SPARSE_HEADER],
997 )
998 return sig, ver, desc_sec, desc_num, gdOffset
999
1000 def post_process(self) -> None:
1001 # If we have just completed the header region, we need to calculate
1002 # the location and length of the descriptor, which should immediately
1003 # follow and may have been partially-read in this read. If the header
1004 # was previously read and that region was deleted, we have nothing
1005 # to do here.
1006 if not self.has_region('header') or not self.region('header').complete:
1007 return
1008
1009 sig, ver, desc_sec, desc_num, gdOffset = self._parse_sparse_header(
1010 'header'
1011 )
1012
1013 try:
1014 is_text = True
1015 for char in self.region('header').data.decode('ascii'):
1016 if not char.isprintable() and not char.isspace():
1017 is_text = False
1018 break
1019 except UnicodeDecodeError:
1020 is_text = False
1021
1022 if sig != b'KDMV':
1023 if is_text:
1024 # We assume that if everything we have read so far is ASCII
1025 # text and the header doesn't have the sparse signature,
1026 # this must (or may be) a text-only VMDK descriptor file,
1027 # which still needs to be parsed and checked since qemu will
1028 # support it.
1029 self.delete_region('header')
1030 return
1031 raise ImageFormatError(f'Signature KDMV not found: {sig!r}')
1032
1033 if ver not in (1, 2, 3):
1034 raise ImageFormatError('Unsupported format version {int(ver)}')
1035
1036 if gdOffset == self.GD_AT_END and not self.has_region('footer'):
1037 # This means we have a footer, which takes precedence over the
1038 # header, which we cannot support since we stream.
1039 self.new_region('footer', EndCaptureRegion(1536))
1040 self.add_safety_check(SafetyCheck('footer', self.check_footer))
1041
1042 # Since we parse both desc_sec and desc_num (the location of the
1043 # VMDK's descriptor, expressed in 512 bytes sectors) we enforce a
1044 # check on the bounds to create a reasonable CaptureRegion. This
1045 # is similar to how it's done in qemu.
1046 desc_offset = desc_sec * 512
1047 desc_size = min(desc_num * 512, self.DESC_MAX_SIZE)
1048 if desc_offset != self.DESC_OFFSET:
1049 raise ImageFormatError("Wrong descriptor location")
1050
1051 # If we parsed a valid sparse header and we still have the original
1052 # descriptor region at BOF, recreate it with the actual offset of the
1053 # embedded one.
1054 if self.region('descriptor').offset == 0:
1055 self.delete_region('descriptor')
1056 self.new_region(
1057 'descriptor', CaptureRegion(desc_offset, desc_size)
1058 )
1059
1060 def region_complete(self, region_name: str) -> None:
1061 if region_name == 'descriptor':
1062 self._parse_descriptor()
1063
1064 def _parse_descriptor(self) -> None:
1065 try:
1066 # The sparse descriptor is null-padded to 512 bytes. Find the
1067 # first one and use it as the end of the text string.
1068 desc_data = self.region('descriptor').data
1069 pad_idx = desc_data.index(b'\x00')
1070 desc_data = desc_data[:pad_idx]
1071 except ValueError:
1072 # Not a sparse descriptor, proceed to decode as test
1073 pass
1074 try:
1075 # Descriptor is actually case-insensitive ASCII text
1076 desc_text = desc_data.decode('ascii').lower()
1077 except UnicodeDecodeError:
1078 LOG.error('VMDK descriptor failed to decode as ASCII')
1079 return
1080
1081 try:
1082 type_idx = desc_text.index('createtype="') + len('createtype="')
1083 type_end = desc_text.find('"', type_idx)
1084 except ValueError:
1085 # This means we did not find the createType= header, which is
1086 # fatal, so we should refuse this.
1087 vmdktype = 'formatnotfound'
1088 else:
1089 # Make sure we don't grab and log a huge chunk of data in a
1090 # maliciously-formatted descriptor region
1091 if type_end - type_idx < 64:
1092 vmdktype = desc_text[type_idx:type_end]
1093 else:
1094 vmdktype = 'formatnotfound'
1095
1096 self.desc_text = desc_text
1097 self.vmdktype = vmdktype
1098
1099 @property
1100 def format_match(self) -> bool:
1101 if self.has_region('header'):
1102 return self.region('header').data.startswith(b'KDMV')
1103 else:
1104 return self.vmdktype != 'formatnotfound'
1105
1106 @property
1107 def virtual_size(self) -> int:
1108 if not self.desc_text:
1109 # Not enough data yet
1110 return 0
1111
1112 if self.vmdktype not in ('monolithicsparse', 'streamoptimized'):
1113 LOG.warning('Unsupported VMDK format %r', self.vmdktype)
1114 return 0
1115
1116 sectors: int
1117
1118 # If we have the descriptor, we definitely have the header
1119 _sig, _ver, _flags, sectors, _grain, _desc_sec, _desc_num = (
1120 struct.unpack('<IIIQQQQ', self.region('header').data[:44])
1121 )
1122
1123 return sectors * 512
1124
1125 def check_descriptor(self) -> None:
1126 if not self.desc_text:
1127 raise SafetyViolation(_('No descriptor found'))
1128
1129 extent_access = ('rw', 'rdonly', 'noaccess')
1130 header_fields = []
1131 extents = []
1132 ddb = []
1133
1134 if self.vmdktype not in ('monolithicsparse', 'streamoptimized'):
1135 LOG.warning('Unsupported VMDK format %r', self.vmdktype)
1136 raise SafetyViolation('Unsupported subformat')
1137
1138 # NOTE(danms): Cautiously parse the VMDK descriptor. Each line must
1139 # be something we understand, otherwise we refuse it.
1140 for line in [x.strip() for x in self.desc_text.split('\n')]:
1141 if line.startswith('#') or not line:
1142 # Blank or comment lines are ignored
1143 continue
1144 elif line.startswith('ddb'):
1145 # DDB lines are allowed (but not used by us)
1146 ddb.append(line)
1147 elif '=' in line and ' ' not in line.split('=')[0]:
1148 # Header fields are a single word followed by an '=' and some
1149 # value
1150 header_fields.append(line)
1151 elif line.split(' ')[0] in extent_access:
1152 # Extent lines start with one of the three access modes
1153 extents.append(line)
1154 else:
1155 # Anything else results in a rejection
1156 LOG.error('Unsupported line %r in VMDK descriptor', line)
1157 raise SafetyViolation(_('Invalid VMDK descriptor data'))
1158
1159 # Check all the extent lines for concerning content
1160 for extent_line in extents:
1161 if '/' in extent_line:
1162 LOG.error(
1163 'Extent line %r contains unsafe characters', extent_line
1164 )
1165 raise SafetyViolation(_('Invalid extent filenames found'))
1166
1167 if not extents:
1168 LOG.error('VMDK file specified no extents')
1169 raise SafetyViolation(_('No extents found'))
1170
1171 def check_footer(self) -> None:
1172 h_sig, h_ver, h_desc_sec, h_desc_num, h_goff = (
1173 self._parse_sparse_header('header')
1174 )
1175 f_sig, f_ver, f_desc_sec, f_desc_num, f_goff = (
1176 self._parse_sparse_header('footer', 512)
1177 )
1178
1179 if h_sig != f_sig:
1180 raise SafetyViolation(
1181 _('Header and footer signature do not match')
1182 )
1183 if h_ver != f_ver:
1184 raise SafetyViolation(_('Header and footer versions do not match'))
1185 if h_desc_sec != f_desc_sec or h_desc_num != f_desc_num:
1186 raise SafetyViolation(
1187 _('Footer specifies a different descriptor than header')
1188 )
1189 if f_goff == self.GD_AT_END:
1190 raise SafetyViolation(_('Footer indicates another footer'))
1191
1192 pad = b'\x00' * 496
1193 val, size, typ, zero = struct.unpack(
1194 '<QII496s', self.region('footer').data[:512]
1195 )
1196 if size != 0 or typ != self.MARKER_FOOTER or zero != pad:
1197 raise SafetyViolation(_('Footer marker is invalid'))
1198
1199 val, size, typ, zero = struct.unpack(
1200 '<QII496s', self.region('footer').data[-512:]
1201 )
1202 if val != 0 or size != 0 or typ != self.MARKER_EOS or zero != pad:
1203 raise SafetyViolation(_('End-of-stream marker is invalid'))
1204
1205
1206 # The VirtualBox VDI format consists of a 512-byte little-endian
1207 # header, some of which we care about:
1208 #
1209 # Dec Hex Name
1210 # 64 0x40 4-byte Magic (0xbeda107f)
1211 # . . .
1212 # 368 0x170 Size in bytes (uint64_t)
1213 #
1214 # https://github.com/qemu/qemu/blob/master/block/vdi.c
1215 class VDIInspector(FileInspector):
1216 """VirtualBox VDI format
1217
1218 This only needs to store the first 512 bytes of the image.
1219 """
1220
1221 NAME = 'vdi'
1222
1223 def _initialize(self) -> None:
1224 self.new_region('header', CaptureRegion(0, 512))
1225 self.add_safety_check(SafetyCheck.null())
1226
1227 @property
1228 def format_match(self) -> bool:
1229 if not self.region('header').complete:
1230 return False
1231
1232 signature: int
1233
1234 (signature,) = struct.unpack(
1235 '<I', self.region('header').data[0x40:0x44]
1236 )
1237 return signature == 0xBEDA107F
1238
1239 @property
1240 def virtual_size(self) -> int:
1241 if not self.region('header').complete:
1242 return 0
1243 if not self.format_match:
1244 return 0
1245
1246 size: int
1247 (size,) = struct.unpack('<Q', self.region('header').data[0x170:0x178])
1248 return size
1249
1250
1251 class ISOInspector(FileInspector):
1252 """ISO 9660 and UDF format
1253
1254 we need to check the first 32KB + descriptor size
1255 to look for the ISO 9660 or UDF signature.
1256
1257 http://wiki.osdev.org/ISO_9660
1258 http://wiki.osdev.org/UDF
1259 mkisofs --help | grep udf
1260
1261 The Universal Disc Format or UDF is the filesystem used on DVDs and
1262 Blu-Ray discs.UDF is an extension of ISO 9660 and shares the same
1263 header structure and initial layout.
1264
1265 Like the CDFS(ISO 9660) file system,
1266 the UDF file system uses a 2048 byte sector size,
1267 and it designates that the first 16 sectors can be used by the OS
1268 to store proprietary data or boot logic.
1269
1270 That means we need to check the first 32KB + descriptor size
1271 to look for the ISO 9660 or UDF signature.
1272 both formats have an extent based layout, so we can't determine
1273 ahead of time where the descriptor will be located.
1274
1275 fortunately, the ISO 9660 and UDF formats have a Primary Volume Descriptor
1276 located at the beginning of the image, which contains the volume size.
1277
1278 """
1279
1280 NAME = 'iso'
1281
1282 def _initialize(self) -> None:
1283 self.new_region('system_area', CaptureRegion(0, 32 * units.Ki))
1284 self.new_region('header', CaptureRegion(32 * units.Ki, 2 * units.Ki))
1285 self.add_safety_check(SafetyCheck.null())
1286
1287 @property
1288 def format_match(self) -> bool:
1289 if not self.complete:
1290 return False
1291 signature = self.region('header').data[1:6]
1292 return signature in (b'CD001', b'NSR02', b'NSR03')
1293
1294 @property
1295 def virtual_size(self) -> int:
1296 if not self.complete:
1297 return 0
1298 if not self.format_match:
1299 return 0
1300
1301 # the header size is 2KB or 1 sector
1302 # the first header field is the descriptor type which is 1 byte
1303 # the second field is the standard identifier which is 5 bytes
1304 # the third field is the version which is 1 byte
1305 # the rest of the header contains type specific data is 2041 bytes
1306 # see http://wiki.osdev.org/ISO_9660#The_Primary_Volume_Descriptor
1307
1308 # we need to check that the descriptor type is 1
1309 # to ensure that this is a primary volume descriptor
1310 descriptor_type = self.region('header').data[0]
1311 if descriptor_type != 1:
1312 return 0
1313
1314 logical_block_size_data: bytes | bytearray
1315 logical_block_size: int
1316
1317 # The size in bytes of a logical block is stored at offset 128
1318 # and is 2 bytes long encoded in both little and big endian
1319 # int16_LSB-MSB so the field is 4 bytes long
1320 logical_block_size_data = self.region('header').data[128:132]
1321 # given the encoding we only need to read half the field so we
1322 # can use the first 2 bytes which are the little endian part
1323 # this is normally 2048 or 2KB but we need to check as it can be
1324 # different according to the ISO 9660 standard.
1325 (logical_block_size,) = struct.unpack(
1326 '<H', logical_block_size_data[:2]
1327 )
1328
1329 volume_space_size_data: bytes | bytearray
1330 volume_space_size: int
1331
1332 # The volume space size is the total number of logical blocks
1333 # and is stored at offset 80 and is 8 bytes long
1334 # as with the logical block size the field is encoded in both
1335 # little and big endian as an int32_LSB-MSB
1336 volume_space_size_data = self.region('header').data[80:88]
1337 # given the encoding we only need to read half the field so we
1338 # can use the first 4 bytes which are the little endian part
1339 (volume_space_size,) = struct.unpack('<L', volume_space_size_data[:4])
1340 # the virtual size is the volume space size * logical block size
1341 return volume_space_size * logical_block_size
1342
1343
1344 # GPT is a superset of legacy MBR and we can detect the two with the same
1345 # inspector. There may be more we can safety check for GPT, but detecting
1346 # both formats is simpler.
1347 # https://uefi.org/specs/UEFI/2.10/05_GUID_Partition_Table_Format.html
1348 class GPTInspector(FileInspector):
1349 NAME = 'gpt'
1350 MBR_SIGNATURE = 0xAA55
1351 MBR_PTE_START = 446
1352 MEDIA_TYPE_FDISK = 0xF8
1353
1354 def _initialize(self) -> None:
1355 self.new_region('mbr', CaptureRegion(0, 512))
1356 # TODO(danms): If we start inspecting the contents of the GPT
1357 # structures themselves, we need to realize that they are block-aligned
1358 # and not necessarily right after the PMBR at 512 bytes.
1359 # self.new_region('gpt', CaptureRegion(512, 512))
1360 # If we detect that this is a GPT, we may want to capture the backup
1361 # and assert that it is equivalent.
1362 # TODO(danms): Maybe add this region and associated checks:
1363 # self.new_region('gpt_backup', EndCaptureRegion(512))
1364 self.add_safety_check(SafetyCheck('mbr', self.check_mbr_partitions))
1365
1366 def _check_for_fat(self) -> bool:
1367 # A FAT filesystem looks like an MBR, but actually starts with a VBR,
1368 # which has the same signature as an MBR, but with more specifics in
1369 # the BPB (BIOS Parameter Block).
1370 boot_sector = self.region('mbr').data
1371 # num_fats is almost always 2 (never more or less) for any filesystem
1372 # not super tiny (think 1980s ramdisk)
1373 num_fats = boot_sector[0x10]
1374 # Media descriptor will basically always be "a fixed disk" for any of
1375 # our purposes, not a floppy disk
1376 media_desc = boot_sector[0x15]
1377 return num_fats == 2 and media_desc == self.MEDIA_TYPE_FDISK
1378
1379 @property
1380 def format_match(self) -> bool:
1381 if not self.region('mbr').complete:
1382 return False
1383 # Check to see if this looks like a VBR from a FAT filesystem so we
1384 # can exclude it
1385 is_fat = self._check_for_fat()
1386 (mbr_sig,) = struct.unpack('<H', self.region('mbr').data[510:512])
1387 return mbr_sig == self.MBR_SIGNATURE and not is_fat
1388
1389 def check_mbr_partitions(self) -> None:
1390 valid_partitions = []
1391 found_gpt = False
1392 for i in range(4):
1393 pte_start = self.MBR_PTE_START + (16 * i)
1394 pte = self.region('mbr').data[pte_start : pte_start + 16]
1395 (
1396 boot,
1397 starth,
1398 starts,
1399 startt,
1400 ostype,
1401 endh,
1402 ehds,
1403 endt,
1404 startlba,
1405 sizelba,
1406 ) = struct.unpack('<B3BB3BII', pte)
1407 if boot not in (0x00, 0x80):
1408 raise SafetyViolation(
1409 f'MBR PTE {int(i)} has invalid boot flag'
1410 )
1411 if ostype != 0:
1412 valid_partitions.append(i)
1413 if ostype == 0xEE:
1414 found_gpt = True
1415 if (starth, starts, startt) != (0x00, 0x02, 0x00):
1416 raise SafetyViolation('GPT MBR has invalid start CHS')
1417 if startlba != 0x00000001:
1418 raise SafetyViolation('GPT MBR has invalid start LBA')
1419 if found_gpt and valid_partitions != [0]:
1420 raise SafetyViolation('GPT MBR defines invalid extra partitions')
1421 if not valid_partitions:
1422 raise SafetyViolation('GPT MBR has no partitions defined')
1423
1424
1425 # The LUKSv1 format consists of a header with some metadata and key
1426 # information followed by a bulk non-sparse data payload which is the
1427 # encyrpted disk image.
1428 # https://gitlab.com/cryptsetup/cryptsetup/-/wikis/LUKS-standard/on-disk-format.pdf
1429 # LUKSv2 is a different but similar spec, which is not yet covered here (or
1430 # in qemu).
1431 class LUKSHeader(TypedDict, total=False):
1432 magic: bytes
1433 version: int
1434 cipher_alg: bytes
1435 cipher_mode: bytes
1436 hash: bytes
1437 payload_offset: int
1438
1439
1440 class LUKSInspector(FileInspector):
1441 NAME = 'luks'
1442
1443 def _initialize(self) -> None:
1444 self.new_region('header', CaptureRegion(0, 592))
1445 self.add_safety_check(SafetyCheck('version', self.check_version))
1446
1447 @property
1448 def format_match(self) -> bool:
1449 return self.region('header').data[:6] == b'LUKS\xba\xbe'
1450
1451 @property
1452 def header_items(self) -> LUKSHeader:
1453 fields = struct.unpack(
1454 '>6sh32s32s32sI', self.region('header').data[:108]
1455 )
1456 names = [
1457 'magic',
1458 'version',
1459 'cipher_alg',
1460 'cipher_mode',
1461 'hash',
1462 'payload_offset',
1463 ]
1464 return cast(LUKSHeader, dict(zip(names, fields)))
1465
1466 def check_version(self) -> None:
1467 header = self.header_items
1468 if header['version'] != 1:
1469 raise SafetyViolation(
1470 f'LUKS version {int(header["version"])} is not supported'
1471 )
1472
1473 @property
1474 def virtual_size(self) -> int:
1475 # NOTE(danms): This will not be correct until/unless the whole stream
1476 # has been read, since all we have is (effectively the size of the
1477 # header. This is similar to how RawFileInspector works.
1478 return super().virtual_size - self.header_items['payload_offset'] * 512
1479
1480
1481 class InspectWrapper:
1482 """A file-like object that wraps another and detects the format.
1483
1484 This passes chunks to a group of format inspectors (default: all)
1485 while reading. After the stream is finished (or enough has been read to
1486 make a confident decision), the format attribute will provide the
1487 inspector object that matched.
1488
1489 :param source: The file-like input stream to wrap
1490 :param expected_format: The format name anticipated to match, if any.
1491 If set to a format name, reading of the stream will
1492 be interrupted if the matching inspector raises
1493 an error (indicting a mismatch or any other
1494 problem). This allows the caller to abort before
1495 all data is processed.
1496 :param allowed_formats: A list of format names that limits the inspector
1497 objects that will be used. This may be a security
1498 hole if used improperly, but may be used to limit
1499 the detected formats to some smaller scope.
1500 """
1501
1502 def __init__(
1503 self,
1504 source: IO[bytes],
1505 expected_format: str | None = None,
1506 allowed_formats: list[str] | None = None,
1507 ) -> None:
1508 self._source = source
1509 self._expected_format = expected_format
1510 self._errored_inspectors: set[FileInspector] = set()
1511 self._inspectors = {
1512 v()
1513 for k, v in ALL_FORMATS.items()
1514 if not allowed_formats or k in allowed_formats
1515 }
1516 self._finished = False
1517
1518 def __iter__(self) -> Iterator[bytes]:
1519 return self
1520
1521 def _process_chunk(self, chunk: bytes) -> None:
1522 for inspector in [
1523 i for i in self._inspectors if i not in self._errored_inspectors
1524 ]:
1525 try:
1526 inspector.eat_chunk(chunk)
1527 except Exception as e:
1528 if inspector.NAME == self._expected_format:
1529 # If our desired inspector has failed, we cannot continue
1530 raise
1531 # Absolutely do not allow the format inspector to break
1532 # our streaming of the image for non-expected formats. If we
1533 # failed, just stop trying, log and keep going.
1534 if not self._expected_format:
1535 # If we are expecting to parse a specific format, we do
1536 # not need to log scary messages about the other formats
1537 # failing to parse the data as expected.
1538 LOG.debug(
1539 'Format inspector for %s does not match, '
1540 'excluding from consideration (%s)',
1541 inspector.NAME,
1542 e,
1543 )
1544 self._errored_inspectors.add(inspector)
1545 else:
1546 # If we are expecting a format, have read enough data to
1547 # satisfy that format's inspector, and no match is detected,
1548 # abort the stream immediately to save having to read the
1549 # entire thing before we signal the mismatch.
1550 if (
1551 inspector.NAME == self._expected_format
1552 and inspector.complete
1553 and not inspector.format_match
1554 ):
1555 raise ImageFormatError(
1556 'Content does not match expected format '
1557 f'{inspector.NAME!r}'
1558 )
1559
1560 def __next__(self) -> bytes:
1561 try:
1562 chunk = next(self._source)
1563 except StopIteration:
1564 self._finish()
1565 raise
1566 self._process_chunk(chunk)
1567 return chunk
1568
1569 def read(self, size: int) -> bytes:
1570 chunk = self._source.read(size)
1571 self._process_chunk(chunk)
1572 return chunk
1573
1574 def _finish(self) -> None:
1575 for inspector in self._inspectors:
1576 inspector.finish()
1577 self._finished = True
1578
1579 def close(self) -> None:
1580 if hasattr(self._source, 'close'):
1581 self._source.close()
1582 self._finish()
1583
1584 @property
1585 def formats(self) -> list[FileInspector] | None:
1586 """The formats (potentially multiple) determined from the content.
1587
1588 This is just like format, but returns a list of formats that matched,
1589 which may be more than one if appropriate. This should generally not
1590 be used as it is safer to allow one and only one format. However, there
1591 are situations where multiple formats could be detected legitimately
1592 (i.e. bootable ISOs) where we need to expose the case where we have
1593 found more than one. If no specific matches are made, this will return
1594 a list with just the Raw inspector, but will never include Raw in
1595 combination with others.
1596
1597 This will be None if a decision has not been reached.
1598 """
1599 non_raw = {i for i in self._inspectors if i.NAME != 'raw'}
1600 complete = all([i.complete for i in non_raw])
1601 matches = [i for i in non_raw if i.format_match]
1602 if not complete and not self._finished:
1603 # We do not know what our format is if we're still in progress
1604 # of reading the stream and have incomplete inspectors. However,
1605 # if EOF has been signaled, then we can assume the incomplete ones
1606 # are not matches.
1607 return None
1608 if not matches:
1609 try:
1610 # If nothing *specific* matched, we return the raw format to
1611 # indicate that we do not recognize this content at all.
1612 return [x for x in self._inspectors if str(x) == 'raw']
1613 except IndexError:
1614 raise ImageFormatError(
1615 'Content does not match any allowed format'
1616 )
1617 return matches
1618
1619 @property
1620 def format(self) -> FileInspector | None:
1621 """The format determined from the content.
1622
1623 If this is None, a decision has not been reached. Otherwise,
1624 it is a FileInspector that matches (which may be RawFileInspector
1625 if no other formats matched and enough of the stream has been read
1626 to make that determination). If more than one format matched, then
1627 ImageFormatError is raised. If the allowed_formats was constrained
1628 and raw was not included, then this will raise ImageFormatError to
1629 indicate that no suitable match was found.
1630 """
1631 matches = self.formats
1632 if matches is None:
1633 return matches
1634 elif len(matches) > 1:
1635 # Multiple format matches mean that not only can we not return a
1636 # decision here, but also means that there may be something
1637 # nefarious going on (i.e. hiding one header in another).
1638 raise ImageFormatError(
1639 'Multiple formats detected: {}'.format(
1640 ','.join(str(i) for i in matches)
1641 )
1642 )
1643 else:
1644 try:
1645 # The expected outcome of this is a single match of something
1646 # specific
1647 return matches[0]
1648 except IndexError:
1649 raise ImageFormatError(
1650 'Content does not match any allowed format'
1651 )
1652
1653
1654 ALL_FORMATS: dict[str, type[FileInspector]] = {
1655 'raw': RawFileInspector,
1656 'qcow2': QcowInspector,
1657 'vhd': VHDInspector,
1658 'vhdx': VHDXInspector,
1659 'vmdk': VMDKInspector,
1660 'vdi': VDIInspector,
1661 'qed': QEDInspector,
1662 'iso': ISOInspector,
1663 'gpt': GPTInspector,
1664 'luks': LUKSInspector,
1665 }
1666
1667
1668 def get_inspector(format_name: str) -> type[FileInspector] | None:
1669 """Returns a FormatInspector class based on the given name.
1670
1671 :param format_name: The name of the disk_format (raw, qcow2, etc).
1672 :returns: A FormatInspector or None if unsupported.
1673 """
1674
1675 return ALL_FORMATS.get(format_name)
1676
1677
1678 def detect_file_format(filename: str) -> FileInspector | None:
1679 """Attempts to detect the format of a file.
1680
1681 This runs through a file one time, running all the known inspectors in
1682 parallel. It stops reading the file once all of them matches or all of
1683 them are sure they don't match.
1684
1685 :param filename: The path to the file to inspect.
1686 :returns: A FormatInspector instance matching the file.
1687 :raises: ImageFormatError if multiple formats are detected.
1688 """
1689 with open(filename, 'rb') as f:
1690 wrapper = InspectWrapper(f)
1691 try:
1692 for _chunk in _chunked_reader(wrapper, 4096):
1693 if wrapper.format:
1694 return wrapper.format
1695 finally:
1696 wrapper.close()
1697 return wrapper.format