| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 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 |
|
| 120 |
|
| 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 |
|
| 238 |
NAME = '' |
| 239 |
|
| 240 |
def __init__(self, tracing: bool = False) -> None: |
| 241 |
self._total_count = 0 |
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 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 |
|
| 254 |
|
| 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 |
|
| 303 |
self._total_count += len(chunk) |
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
self._capture(chunk) |
| 308 |
|
| 309 |
|
| 310 |
self.post_process() |
| 311 |
|
| 312 |
|
| 313 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
| 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 |
|
| 493 |
return True |
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 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 |
|
| 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 |
|
| 590 |
|
| 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 |
|
| 600 |
max_byte = self.I_FEATURES_MAX_BIT // 8 |
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
for i, byte_num in enumerate(reversed(range(self.I_FEATURES_LEN))): |
| 605 |
if byte_num == max_byte: |
| 606 |
|
| 607 |
|
| 608 |
allow_mask = (1 << (self.I_FEATURES_MAX_BIT % 8)) - 1 |
| 609 |
elif byte_num > max_byte: |
| 610 |
|
| 611 |
|
| 612 |
allow_mask = 0x0 |
| 613 |
else: |
| 614 |
|
| 615 |
|
| 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 |
|
| 633 |
byte = self.I_FEATURES_LEN - 1 - self.I_FEATURES_DATAFILE_BIT // 8 |
| 634 |
|
| 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 |
|
| 646 |
|
| 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 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
|
| 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 |
|
| 696 |
|
| 697 |
|
| 698 |
|
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
|
| 703 |
|
| 704 |
|
| 705 |
|
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
|
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
|
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
|
| 743 |
|
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
|
| 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 |
| 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 |
|
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
|
| 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 |
|
| 807 |
region_entry_first = 16 |
| 808 |
|
| 809 |
|
| 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 |
|
| 824 |
|
| 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 |
|
| 835 |
guid = self._guid(entry[:16]) |
| 836 |
if guid == self.METAREGION: |
| 837 |
|
| 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 |
|
| 845 |
|
| 846 |
|
| 847 |
|
| 848 |
|
| 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 |
|
| 859 |
return None |
| 860 |
|
| 861 |
|
| 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 |
|
| 871 |
|
| 872 |
|
| 873 |
|
| 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 |
|
| 886 |
|
| 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 |
|
| 896 |
|
| 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 |
|
| 907 |
|
| 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 |
|
| 916 |
|
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
|
| 928 |
|
| 929 |
|
| 930 |
|
| 931 |
|
| 932 |
|
| 933 |
|
| 934 |
|
| 935 |
|
| 936 |
|
| 937 |
|
| 938 |
|
| 939 |
|
| 940 |
|
| 941 |
|
| 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 |
|
| 953 |
|
| 954 |
DESC_OFFSET = 0x200 |
| 955 |
DESC_MAX_SIZE = (1 << 20) - 1 |
| 956 |
GD_AT_END = 0xFFFFFFFFFFFFFFFF |
| 957 |
|
| 958 |
|
| 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 |
|
| 966 |
|
| 967 |
|
| 968 |
self.new_region( |
| 969 |
'header', CaptureRegion(0, 512, min_length=self.MIN_SPARSE_HEADER) |
| 970 |
) |
| 971 |
|
| 972 |
|
| 973 |
|
| 974 |
|
| 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 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 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 |
|
| 1025 |
|
| 1026 |
|
| 1027 |
|
| 1028 |
|
| 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 |
|
| 1038 |
|
| 1039 |
self.new_region('footer', EndCaptureRegion(1536)) |
| 1040 |
self.add_safety_check(SafetyCheck('footer', self.check_footer)) |
| 1041 |
|
| 1042 |
|
| 1043 |
|
| 1044 |
|
| 1045 |
|
| 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 |
|
| 1052 |
|
| 1053 |
|
| 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 |
|
| 1067 |
|
| 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 |
|
| 1073 |
pass |
| 1074 |
try: |
| 1075 |
|
| 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 |
|
| 1086 |
|
| 1087 |
vmdktype = 'formatnotfound' |
| 1088 |
else: |
| 1089 |
|
| 1090 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1139 |
|
| 1140 |
for line in [x.strip() for x in self.desc_text.split('\n')]: |
| 1141 |
if line.startswith('#') or not line: |
| 1142 |
|
| 1143 |
continue |
| 1144 |
elif line.startswith('ddb'): |
| 1145 |
|
| 1146 |
ddb.append(line) |
| 1147 |
elif '=' in line and ' ' not in line.split('=')[0]: |
| 1148 |
|
| 1149 |
|
| 1150 |
header_fields.append(line) |
| 1151 |
elif line.split(' ')[0] in extent_access: |
| 1152 |
|
| 1153 |
extents.append(line) |
| 1154 |
else: |
| 1155 |
|
| 1156 |
LOG.error('Unsupported line %r in VMDK descriptor', line) |
| 1157 |
raise SafetyViolation(_('Invalid VMDK descriptor data')) |
| 1158 |
|
| 1159 |
|
| 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 |
|
| 1207 |
|
| 1208 |
|
| 1209 |
|
| 1210 |
|
| 1211 |
|
| 1212 |
|
| 1213 |
|
| 1214 |
|
| 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 |
|
| 1302 |
|
| 1303 |
|
| 1304 |
|
| 1305 |
|
| 1306 |
|
| 1307 |
|
| 1308 |
|
| 1309 |
|
| 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 |
|
| 1318 |
|
| 1319 |
|
| 1320 |
logical_block_size_data = self.region('header').data[128:132] |
| 1321 |
|
| 1322 |
|
| 1323 |
|
| 1324 |
|
| 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 |
|
| 1333 |
|
| 1334 |
|
| 1335 |
|
| 1336 |
volume_space_size_data = self.region('header').data[80:88] |
| 1337 |
|
| 1338 |
|
| 1339 |
(volume_space_size,) = struct.unpack('<L', volume_space_size_data[:4]) |
| 1340 |
|
| 1341 |
return volume_space_size * logical_block_size |
| 1342 |
|
| 1343 |
|
| 1344 |
|
| 1345 |
|
| 1346 |
|
| 1347 |
|
| 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 |
|
| 1357 |
|
| 1358 |
|
| 1359 |
|
| 1360 |
|
| 1361 |
|
| 1362 |
|
| 1363 |
|
| 1364 |
self.add_safety_check(SafetyCheck('mbr', self.check_mbr_partitions)) |
| 1365 |
|
| 1366 |
def _check_for_fat(self) -> bool: |
| 1367 |
|
| 1368 |
|
| 1369 |
|
| 1370 |
boot_sector = self.region('mbr').data |
| 1371 |
|
| 1372 |
|
| 1373 |
num_fats = boot_sector[0x10] |
| 1374 |
|
| 1375 |
|
| 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 |
|
| 1384 |
|
| 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 |
|
| 1426 |
|
| 1427 |
|
| 1428 |
|
| 1429 |
|
| 1430 |
|
| 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 |
|
| 1476 |
|
| 1477 |
|
| 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 |
|
| 1530 |
raise |
| 1531 |
|
| 1532 |
|
| 1533 |
|
| 1534 |
if not self._expected_format: |
| 1535 |
|
| 1536 |
|
| 1537 |
|
| 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 |
|
| 1547 |
|
| 1548 |
|
| 1549 |
|
| 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 |
|
| 1604 |
|
| 1605 |
|
| 1606 |
|
| 1607 |
return None |
| 1608 |
if not matches: |
| 1609 |
try: |
| 1610 |
|
| 1611 |
|
| 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 |
|
| 1636 |
|
| 1637 |
|
| 1638 |
raise ImageFormatError( |
| 1639 |
'Multiple formats detected: {}'.format( |
| 1640 |
','.join(str(i) for i in matches) |
| 1641 |
) |
| 1642 |
) |
| 1643 |
else: |
| 1644 |
try: |
| 1645 |
|
| 1646 |
|
| 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 |