Debian Codegraph @

oslo_utils/tests/imageutils/test_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 import io
17 import os
18 import struct
19 import subprocess
20 import tempfile
21 from unittest import mock
22
23 import ddt
24
25 from oslo_utils.imageutils import format_inspector
26 from oslo_utils.imageutils import QemuImgInfo
27 from oslo_utils.tests import base as test_base
28 from oslo_utils import units
29
30
31 TEST_IMAGE_PREFIX = 'oslo-unittest-formatinspector-'
32
33
34 def get_size_format_from_qemu_img(filename):
35 output = subprocess.check_output(
36 f'qemu-img info --output=json "{filename}"', shell=True
37 )
38 info = QemuImgInfo(output, format='json')
39 return info.virtual_size, info.file_format
40
41
42 @ddt.ddt
43 class TestFormatInspectors(test_base.BaseTestCase):
44 def setUp(self):
45 super().setUp()
46 self._created_files = []
47
48 def tearDown(self):
49 super().tearDown()
50 for fn in self._created_files:
51 try:
52 os.remove(fn)
53 except Exception:
54 pass
55
56 def _create_iso(self, image_size, subformat='9660'):
57 """Create an ISO file of the given size.
58
59 :param image_size: The size of the image to create in bytes
60 :param subformat: The subformat to use, if any
61 """
62
63 # these tests depend on mkisofs
64 # being installed and in the path,
65 # if it is not installed, skip
66 try:
67 subprocess.check_output('mkisofs --version', shell=True)
68 except Exception:
69 self.skipTest('mkisofs not installed')
70
71 size = image_size // units.Mi
72 base_cmd = "mkisofs"
73 if subformat == 'udf':
74 # depending on the distribution mkisofs may not support udf
75 # and may be provided by genisoimage instead. As a result we
76 # need to check if the command supports udf via help
77 # instead of checking the installed version.
78 # mkisofs --help outputs to stderr so we need to
79 # redirect it to stdout to use grep.
80 try:
81 subprocess.check_output(
82 'mkisofs --help 2>&1 | grep udf', shell=True
83 )
84 except Exception:
85 self.skipTest('mkisofs does not support udf format')
86 base_cmd += " -udf"
87 prefix = TEST_IMAGE_PREFIX
88 prefix += f'-{subformat}-'
89 fn = tempfile.mktemp(prefix=prefix, suffix='.iso')
90 self._created_files.append(fn)
91 subprocess.check_output(
92 f'dd if=/dev/zero of={fn} bs=1M count={int(size)}', shell=True
93 )
94 # We need to use different file as input and output as the behavior
95 # of mkisofs is version dependent if both the input and the output
96 # are the same and can cause test failures
97 out_fn = f"{fn}.iso"
98 subprocess.check_output(
99 f'{base_cmd} -V "TEST" -o {out_fn} {fn}', shell=True
100 )
101 self._created_files.append(out_fn)
102 return out_fn
103
104 def _create_gpt(self, image_size, subformat='gpt'):
105 data = bytearray(b'\x00' * 512 * 10)
106 # The last two bytes of the first sector is the little-endian signature
107 # value 0xAA55
108 data[510:512] = b'\x55\xaa'
109
110 # This is one EFI Protective MBR partition in the first PTE slot,
111 # which is 16 bytes starting at offset 446.
112 data[446 : 446 + 16] = struct.pack(
113 '<BBBBBBBBII',
114 0x00, # boot
115 0x00, # start C
116 0x02, # start H
117 0x00, # start S
118 0xEE, # OS type
119 0x00, # end C
120 0x00, # end H
121 0x00, # end S
122 0x01, # start LBA
123 0x00, # size LBA
124 )
125 fn = tempfile.mktemp(prefix=f'{TEST_IMAGE_PREFIX}-gpt-{subformat}')
126 with open(fn, 'wb') as f:
127 f.write(data)
128 self._created_files.append(fn)
129 return fn
130
131 def _create_luks(self, image_size, subformat):
132 fn = tempfile.mktemp(suffix='.luks')
133 cmd = [
134 'qemu-img',
135 'create',
136 '-f',
137 'luks',
138 '--object',
139 'secret,id=sec0,data=secret-passphrase',
140 '-o',
141 'key-secret=sec0',
142 fn,
143 f'{int(image_size)}',
144 ]
145 subprocess.check_output(' '.join(cmd), shell=True)
146 return fn
147
148 def _create_img(
149 self, fmt, size, subformat=None, options=None, backing_file=None
150 ):
151 """Create an image file of the given format and size.
152
153 :param fmt: The format to create
154 :param size: The size of the image to create in bytes
155 :param subformat: The subformat to use, if any
156 :param options: A dictionary of options to pass to the format
157 :param backing_file: The backing file to use, if any
158 """
159 # some CI nodes mount /tmp using tmpfs, which can cause memory
160 # exhaustion for larger images: ensure that doesn't happen
161 assert size <= 256 * units.Mi, f'disk too big: {size / units.Mi} MiB'
162
163 if fmt == 'iso':
164 return self._create_iso(size, subformat)
165 if fmt == 'gpt':
166 return self._create_gpt(size, subformat)
167 if fmt == 'luks':
168 return self._create_luks(size, subformat)
169
170 if fmt == 'vhd':
171 # QEMU calls the vhd format vpc
172 fmt = 'vpc'
173
174 # these tests depend on qemu-img being installed and in the path,
175 # if it is not installed, skip. we also need to ensure that the
176 # format is supported by qemu-img, this can vary depending on the
177 # distribution so we need to check if the format is supported via
178 # the help output.
179 try:
180 subprocess.check_output(
181 f'qemu-img --help | grep {fmt}', shell=True
182 )
183 except Exception:
184 self.skipTest(
185 f'qemu-img not installed or does not support {fmt} format'
186 )
187
188 if options is None:
189 options = {}
190 opt = ''
191 prefix = TEST_IMAGE_PREFIX
192
193 if subformat:
194 options['subformat'] = subformat
195 prefix += subformat + '-'
196
197 if options:
198 opt += '-o ' + ','.join(f'{k}={v}' for k, v in options.items())
199
200 if backing_file is not None:
201 opt += f' -b {backing_file} -F raw'
202
203 fn = tempfile.mktemp(prefix=prefix, suffix=f'.{fmt}')
204 self._created_files.append(fn)
205 subprocess.check_output(
206 f'qemu-img create -f {fmt} {opt} {fn} {int(size)}', shell=True
207 )
208 return fn
209
210 def _create_allocated_vmdk(self, size_mb, subformat=None):
211 # We need a "big" VMDK file to exercise some parts of the code of the
212 # format_inspector. A way to create one is to first create an empty
213 # file, and then to convert it with the -S 0 option.
214
215 if subformat is None:
216 # Matches qemu-img default, see `qemu-img convert -O vmdk -o help`
217 subformat = 'monolithicSparse'
218
219 prefix = TEST_IMAGE_PREFIX
220 prefix += f'-{subformat}-'
221 fn = tempfile.mktemp(prefix=prefix, suffix='.vmdk')
222 self._created_files.append(fn)
223 raw = tempfile.mktemp(prefix=prefix, suffix='.raw')
224 self._created_files.append(raw)
225
226 # Create a file with pseudo-random data, otherwise it will get
227 # compressed in the streamOptimized format
228 subprocess.check_output(
229 f'dd if=/dev/urandom of={raw} bs=1M count={int(size_mb)}',
230 shell=True,
231 )
232
233 # Convert it to VMDK
234 subprocess.check_output(
235 f'qemu-img convert -f raw -O vmdk -o subformat={subformat} '
236 f'-S 0 {raw} {fn}',
237 shell=True,
238 )
239 return fn
240
241 def _test_format_at_block_size(self, format_name, img, block_size):
242 wrapper = format_inspector.InspectWrapper(open(img, 'rb'), format_name)
243 current_block_size = block_size
244 while True:
245 chunk = wrapper.read(current_block_size)
246 if not chunk:
247 break
248 # If we've already settled on a format, the block size no longer
249 # really matters for correctness since we won't be capturing and
250 # parsing anything else. Bump up the block size so we will eat
251 # the rest of the file more efficiently. This matters for formats
252 # that are non-sparse and for which the virtual_size calculation
253 # relies on the actual size of the file (i.e. raw, gpt, luks, etc)
254 try:
255 if current_block_size == block_size and wrapper.format:
256 current_block_size = 64 * units.Ki
257 except Exception:
258 pass
259
260 wrapper.close()
261 self.assertIsNotNone(wrapper.format, 'Failed to detect format')
262 return wrapper.format
263
264 def _test_format_at_image_size(
265 self, format_name, image_size, subformat=None, safety_check=False
266 ):
267 """Test the format inspector for the given format at the
268 given image size.
269
270 :param format_name: The format to test
271 :param image_size: The size of the image to create in bytes
272 :param subformat: The subformat to use, if any
273 """
274 img = self._create_img(format_name, image_size, subformat=subformat)
275
276 # Some formats have internal alignment restrictions making this not
277 # always exactly like image_size, so get the real value for comparison
278 virtual_size, _ = get_size_format_from_qemu_img(img)
279
280 # Read the format in various sizes, some of which will read whole
281 # sections in a single read, others will be completely unaligned, etc.
282 block_sizes = [64 * units.Ki, 1 * units.Mi]
283 # ISO images have a 32KB system area at the beginning of the image
284 # as a result reading that in 17 or 512 byte blocks takes too long,
285 # causing the test to fail. The 64KiB block size is enough to read
286 # the system area and header in a single read. the 1MiB block size
287 # adds very little time to the test so we include it.
288 if format_name != 'iso':
289 block_sizes.extend([17, 512])
290 for block_size in block_sizes:
291 fmt = self._test_format_at_block_size(format_name, img, block_size)
292 self.assertTrue(
293 fmt.format_match,
294 f'Failed to match {format_name} at '
295 f'size {int(image_size)} block {int(block_size)}',
296 )
297 self.assertEqual(
298 virtual_size,
299 fmt.virtual_size,
300 f'Failed to calculate size for {format_name} at '
301 f'size {int(image_size)} block {int(block_size)}',
302 )
303 memory = sum(fmt.context_info.values())
304 self.assertLess(
305 memory,
306 512 * units.Ki,
307 f'Format used more than 512KiB of memory: {fmt.context_info}',
308 )
309 if safety_check:
310 fmt.safety_check()
311 # If the safety check is supposed to pass, we can also make
312 # sure our detection works
313 det = format_inspector.detect_file_format(img)
314 self.assertEqual(det.__class__, fmt.__class__)
315
316 def _test_format(self, format_name, subformat=None):
317 # Try a few different image sizes, including some odd and very small
318 # sizes
319 for image_size in (128, 129, 7):
320 self._test_format_at_image_size(
321 format_name,
322 image_size * units.Mi,
323 subformat=subformat,
324 safety_check=True,
325 )
326
327 @ddt.data('qcow2', 'vhd', 'vhdx', 'vmdk', 'gpt', 'luks')
328 def test_format(self, format):
329 self._test_format(format)
330
331 @ddt.unpack
332 @ddt.data(('iso', 'iso9660'), ('iso', 'udf'), ('vmdk', 'streamOptimized'))
333 def test_subformat(self, format, subformat):
334 self._test_format(format, subformat=subformat)
335
336 def _generate_bad_iso(self):
337 # we want to emulate a malicious user who uploads a an
338 # ISO file has a qcow2 header in the system area
339 # of the ISO file
340 # we will create a qcow2 image and an ISO file
341 # and then copy the qcow2 header to the ISO file
342 # e.g.
343 # mkisofs -o orig.iso /etc/resolv.conf
344 # qemu-img create orig.qcow2 -f qcow2 64M
345 # dd if=orig.qcow2 of=outcome bs=32K count=1
346 # dd if=orig.iso of=outcome bs=32K skip=1 seek=1
347
348 qcow = self._create_img('qcow2', 5 * units.Mi)
349 iso = self._create_iso(64 * units.Mi, subformat='9660')
350 # first ensure the files are valid
351 iso_fmt = self._test_format_at_block_size('iso', iso, 4 * units.Ki)
352 self.assertTrue(iso_fmt.format_match)
353 qcow_fmt = self._test_format_at_block_size('qcow2', qcow, 4 * units.Ki)
354 self.assertTrue(qcow_fmt.format_match)
355 # now copy the qcow2 header to an ISO file
356 prefix = TEST_IMAGE_PREFIX
357 prefix += '-bad-'
358 fn = tempfile.mktemp(prefix=prefix, suffix='.iso')
359 self._created_files.append(fn)
360 subprocess.check_output(
361 f'dd if={qcow} of={fn} bs=32K count=1', shell=True
362 )
363 subprocess.check_output(
364 f'dd if={iso} of={fn} bs=32K skip=1 seek=1', shell=True
365 )
366 return qcow, iso, fn
367
368 def test_bad_iso_qcow2(self):
369 # Test that an iso with a qcow2 header in the system area will be
370 # rejected because it matches more than one format (iso and qcow2).
371 # This is an important case because qemu-img does not support iso,
372 # and can be fooled into thinking one is a qcow2 by putting the header
373 # for one in ISO9660's "system area", which is technically a valid
374 # thing to do.
375 _, _, fn = self._generate_bad_iso()
376
377 self.assertRaisesRegex(
378 format_inspector.ImageFormatError,
379 'Multiple formats detected',
380 self._test_format_at_block_size,
381 'iso',
382 fn,
383 4 * units.Ki,
384 )
385
386 def test_bad_iso_qcow2_multiple_matches(self):
387 # Test that we can access multiple detected formats if we specifically
388 # ask for them.
389 _, _, fn = self._generate_bad_iso()
390 with open(fn, 'rb') as f:
391 wrapper = format_inspector.InspectWrapper(f)
392 # Eat the whole file
393 while wrapper.read(1024):
394 pass
395
396 # Make sure we fail the single-format test
397 self.assertRaises(
398 format_inspector.ImageFormatError, getattr, wrapper, 'format'
399 )
400
401 # Make sure the multiple detected formats are exposed
402 formats = wrapper.formats
403 assert formats is not None
404 self.assertEqual(['iso', 'qcow2'], sorted(x.NAME for x in formats))
405
406 def test_from_file_reads_minimum(self):
407 img = self._create_img('qcow2', 5 * units.Mi)
408 file_size = os.stat(img).st_size
409 fmt = format_inspector.QcowInspector.from_file(img)
410 # We know everything we need from the first 512 bytes of a QCOW image,
411 # so make sure that we did not read the whole thing when we inspect
412 # a local file.
413 self.assertLess(fmt.actual_size, file_size)
414
415 def test_qed_always_unsafe(self):
416 img = self._create_img('qed', 5 * units.Mi)
417 inspector = format_inspector.get_inspector('qed')
418 assert inspector is not None
419 fmt = inspector.from_file(img)
420 self.assertTrue(fmt.format_match)
421 self.assertRaises(format_inspector.SafetyCheckFailed, fmt.safety_check)
422
423 def test_vmdk_non_sparse_unsafe(self):
424 img = self._create_img(
425 'vmdk', 5 * units.Mi, subformat='monolithicFlat'
426 )
427 fmt = format_inspector.detect_file_format(img)
428 assert fmt is not None
429 self.assertEqual('vmdk', fmt.NAME)
430 e = self.assertRaises(
431 format_inspector.SafetyCheckFailed, fmt.safety_check
432 )
433 self.assertIn('Unsupported subformat', str(e.failures['descriptor']))
434
435 def _test_vmdk_bad_descriptor_offset(self, subformat=None):
436 format_name = 'vmdk'
437 image_size = 5 * units.Mi
438 descriptorOffsetAddr = 0x1C
439 BAD_ADDRESS = 0x400
440 img = self._create_img(format_name, image_size, subformat=subformat)
441
442 # Corrupt the header
443 fd = open(img, 'r+b')
444 fd.seek(descriptorOffsetAddr)
445 fd.write(struct.pack('<Q', BAD_ADDRESS // 512))
446 fd.close()
447
448 # Read the format in various sizes, some of which will read whole
449 # sections in a single read, others will be completely unaligned, etc.
450 for block_size in (64 * units.Ki, 512, 17, 1 * units.Mi):
451 self.assertRaisesRegex(
452 format_inspector.ImageFormatError,
453 'Wrong descriptor location',
454 self._test_format_at_block_size,
455 'vmdk',
456 img,
457 block_size,
458 )
459
460 def test_vmdk_bad_descriptor_offset(self):
461 self._test_vmdk_bad_descriptor_offset()
462
463 def test_vmdk_bad_descriptor_offset_stream_optimized(self):
464 self._test_vmdk_bad_descriptor_offset(subformat='streamOptimized')
465
466 def _test_vmdk_bad_descriptor_mem_limit(self, subformat=None):
467 format_name = 'vmdk'
468 image_size = 5 * units.Mi
469 virtual_size = 5 * units.Mi
470 descriptorOffsetAddr = 0x1C
471 descriptorSizeAddr = descriptorOffsetAddr + 8
472 twoMBInSectors = (2 << 20) // 512
473 # We need a big VMDK because otherwise we will not have enough data to
474 # fill-up the CaptureRegion.
475 img = self._create_allocated_vmdk(
476 image_size // units.Mi, subformat=subformat
477 )
478
479 # Corrupt the end of descriptor address so it "ends" at 2MB
480 fd = open(img, 'r+b')
481 fd.seek(descriptorSizeAddr)
482 fd.write(struct.pack('<Q', twoMBInSectors))
483 fd.close()
484
485 # Read the format in various sizes, some of which will read whole
486 # sections in a single read, others will be completely unaligned, etc.
487 for block_size in (64 * units.Ki, 512, 17, 1 * units.Mi):
488 fmt = self._test_format_at_block_size(format_name, img, block_size)
489 self.assertTrue(
490 fmt.format_match,
491 f'Failed to match {format_name} at '
492 f'size {int(image_size)} block {int(block_size)}',
493 )
494 self.assertEqual(
495 virtual_size,
496 fmt.virtual_size,
497 f'Failed to calculate size for {format_name} at '
498 f'size {int(image_size)} block {int(block_size)}',
499 )
500 memory = sum(fmt.context_info.values())
501 self.assertLess(
502 memory,
503 1.5 * units.Mi,
504 f'Format used more than 1.5MiB of memory: {fmt.context_info}',
505 )
506
507 def test_vmdk_bad_descriptor_mem_limit(self):
508 self._test_vmdk_bad_descriptor_mem_limit()
509
510 def test_vmdk_bad_descriptor_mem_limit_stream_optimized(self):
511 self._test_vmdk_bad_descriptor_mem_limit(subformat='streamOptimized')
512
513 def test_qcow2_safety_checks(self):
514 # Create backing and data-file names (and initialize the backing file)
515 backing_fn = tempfile.mktemp(prefix='backing')
516 self._created_files.append(backing_fn)
517 with open(backing_fn, 'w') as f:
518 f.write('foobar')
519 data_fn = tempfile.mktemp(prefix='data')
520 self._created_files.append(data_fn)
521
522 # A qcow with no backing or data file is safe
523 fn = self._create_img('qcow2', 5 * units.Mi, None)
524 inspector = format_inspector.QcowInspector.from_file(fn)
525 inspector.safety_check()
526
527 # A backing file makes it unsafe
528 fn = self._create_img(
529 'qcow2', 5 * units.Mi, None, backing_file=backing_fn
530 )
531 inspector = format_inspector.QcowInspector.from_file(fn)
532 self.assertRaisesRegex(
533 format_inspector.SafetyCheckFailed,
534 '.*backing_file.*',
535 inspector.safety_check,
536 )
537
538 # A data-file makes it unsafe
539 fn = self._create_img(
540 'qcow2',
541 5 * units.Mi,
542 options={'data_file': data_fn, 'data_file_raw': 'on'},
543 )
544 inspector = format_inspector.QcowInspector.from_file(fn)
545 self.assertRaisesRegex(
546 format_inspector.SafetyCheckFailed,
547 '.*data_file.*',
548 inspector.safety_check,
549 )
550
551 # Trying to load a non-QCOW file is an error
552 self.assertRaises(
553 format_inspector.ImageFormatError,
554 format_inspector.QcowInspector.from_file,
555 backing_fn,
556 )
557
558 def test_qcow2_feature_flag_checks(self):
559 data = bytearray(512)
560 data[0:4] = b'QFI\xfb'
561 inspector = format_inspector.QcowInspector()
562 inspector.region('header').data = data
563
564 def set_version(ver):
565 data[0x07] = ver
566 inspector.region_complete('header')
567
568 # All zeros, known version, no feature flags - all good
569 set_version(3)
570 inspector.check_unknown_features()
571
572 # A feature flag set in the first byte (highest-order) is not
573 # something we know about, so fail.
574 data[0x48] = 0x01
575 (
576 self.assertRaisesRegex(
577 format_inspector.SafetyViolation,
578 'Unknown QCOW2 features found',
579 inspector.check_unknown_features,
580 ),
581 )
582
583 # The first bit in the last byte (lowest-order) is known (the dirty
584 # bit) so that should pass
585 data[0x48] = 0x00
586 data[0x4F] = 0x01
587 inspector.check_unknown_features()
588
589 # Currently (as of 2024), the high-order feature flag bit in the low-
590 # order byte is not assigned, so make sure we reject it.
591 data[0x4F] = 0x80
592 (
593 self.assertRaisesRegex(
594 format_inspector.SafetyViolation,
595 'Unknown QCOW2 features found',
596 inspector.check_unknown_features,
597 ),
598 )
599
600 # Version 1 should be rejected outright
601 set_version(1)
602 self.assertRaisesRegex(
603 format_inspector.SafetyViolation,
604 'Unsupported qcow2 version',
605 inspector.check_unknown_features,
606 )
607
608 # Version 4 should be rejected outright
609 set_version(4)
610 self.assertRaisesRegex(
611 format_inspector.SafetyViolation,
612 'Unsupported qcow2 version',
613 inspector.check_unknown_features,
614 )
615
616 # Version 2 had no feature flagging, so with the above flags still
617 # set, we should not process that data as feature flags and pass here.
618 set_version(2)
619 inspector.check_unknown_features()
620
621 def test_qcow2_future_flags(self):
622 class Qcow2Future(format_inspector.QcowInspector):
623 """A hypothetical future where qcow2 has 12 extra features."""
624
625 I_FEATURES_MAX_BIT = 12
626
627 data = bytearray(512)
628 data[0:4] = b'QFI\xfb'
629 inspector = Qcow2Future()
630 inspector.region('header').data = data
631 data[0x07] = 3
632 inspector.region_complete('header')
633
634 # Bit 8 is allowed
635 data[0x4F] = 0x80
636 inspector.check_unknown_features()
637
638 # Bit 9 is allowed
639 data[0x4E] = 0x01
640 inspector.check_unknown_features()
641
642 # Bit 16 is not allowed
643 data[0x4E] = 0x81
644 self.assertRaisesRegex(
645 format_inspector.SafetyViolation,
646 'Unknown QCOW2 features found',
647 inspector.check_unknown_features,
648 )
649
650 def test_vdi(self):
651 self._test_format('vdi')
652
653 def test_invalid_data(self):
654 wrapper = format_inspector.InspectWrapper(open(__file__, 'rb'))
655 while True:
656 chunk = wrapper.read(32)
657 if not chunk:
658 break
659
660 wrapper.close()
661 # Make sure this was not detected as any other format
662 self.assertEqual('raw', str(wrapper.format))
663
664 # Make sure that all of the other inspectors do not match and did not
665 # use too much memory
666 for fmt in wrapper._inspectors:
667 if str(fmt) == 'raw':
668 continue
669 self.assertFalse(fmt.format_match)
670 memory = sum(fmt.context_info.values())
671 self.assertLess(
672 memory,
673 512 * units.Ki,
674 f'Format used more than 512KiB of memory: {fmt.context_info}',
675 )
676
677 def test_invalid_data_without_raw(self):
678 wrapper = format_inspector.InspectWrapper(
679 open(__file__, 'rb'), allowed_formats=['qcow2', 'vmdk']
680 )
681 while True:
682 chunk = wrapper.read(32)
683 if not chunk:
684 break
685
686 wrapper.close()
687 # Make sure this was not detected as any other format
688 self.assertRaises(
689 format_inspector.ImageFormatError, lambda: wrapper.format
690 )
691
692 def test_vmdk_invalid_type(self):
693 fmt = format_inspector.VMDKInspector()
694 with open(__file__, 'rb') as f:
695 fmt.eat_chunk(f.read())
696
697 fake_rgn = mock.MagicMock()
698 fake_rgn.complete = True
699 fake_rgn.data = b'foocreateType="someunknownformat"bar'
700
701 with mock.patch.object(fmt, 'has_region', return_value=True):
702 with mock.patch.object(fmt, 'region', return_value=fake_rgn):
703 self.assertEqual(0, fmt.virtual_size)
704
705 def test_vmdk_with_footer(self):
706 img_fn = self._create_img(
707 'vmdk', 5 * units.Mi, subformat='streamOptimized'
708 )
709
710 # Make the file signal that there is a footer, add a footer, but with
711 # invalid data
712 with open(img_fn, 'rb+') as f:
713 # Write the "expect a footer" sentinel into the header
714 f.seek(56)
715 f.write(
716 struct.pack('<Q', format_inspector.VMDKInspector.GD_AT_END)
717 )
718 # Add room for the footer marker, footer, and EOS marker, but
719 # filled with zeroes (which is invalid)
720 f.seek(0, 2)
721 f.write(b'\x00' * 512 * 3)
722 fmt = format_inspector.VMDKInspector.from_file(img_fn)
723 self.assertRaisesRegex(
724 format_inspector.SafetyCheckFailed, 'footer', fmt.safety_check
725 )
726
727 # Make the footer and footer/EOS markers legit
728 header = bytearray(fmt.region('header').data)
729 # This is gdOffset, which must not be GD_AT_END in the footer
730 header[56:57] = b'\x00'
731 with open(img_fn, 'rb+') as f:
732 # This is the footer marker (type=3)
733 f.seek(-512 * 3 + 12, 2)
734 f.write(b'\x03\x00\x00\x00')
735 # Second-to-last sector is the footer, which must be a copy of the
736 # header but with gdOffset set to something other than the flag.
737 f.seek(-512 * 2, 2)
738 f.write(header)
739
740 # With everything set to legit values, we should pass the check now
741 fmt = format_inspector.VMDKInspector.from_file(img_fn)
742 fmt.safety_check()
743
744 # Make sure we properly detect this type of VMDK
745 det = format_inspector.detect_file_format(img_fn)
746 self.assertEqual(format_inspector.VMDKInspector, det.__class__)
747
748 def test_vmdk_footer_checks(self):
749 def make_header(sig=b'KDMV', ver=1, d_sec=1, d_off=0x200, gdo=None):
750 return struct.pack(
751 '<4sIIQQQQIQQ',
752 sig,
753 ver,
754 0,
755 0,
756 0,
757 d_sec,
758 d_off,
759 0,
760 0,
761 gdo or format_inspector.VMDKInspector.GD_AT_END,
762 )
763
764 def make_footer(
765 fm_typ=3,
766 fm_sz=0,
767 fm_pad=b'\x00',
768 eos_typ=0,
769 eos_sz=0,
770 eos_pad=b'\x00',
771 **header,
772 ):
773 region = bytearray(b'\x00' * 512 * 3)
774 region[512:1024] = make_header(**header)
775 region[8] = fm_sz
776 region[12] = fm_typ
777 region[16:512] = fm_pad * 496
778
779 region[1024 + 8] = eos_sz
780 region[1024 + 12] = eos_typ
781 region[1024 + 16 :] = eos_pad * 496
782 return region
783
784 fmt = format_inspector.VMDKInspector()
785 fmt.new_region('footer', format_inspector.EndCaptureRegion(512 * 3))
786 fmt.region('header').data = make_header()
787
788 # Signature must match header
789 fmt.region('footer').data = make_footer(sig=b'leak')
790 self.assertRaisesRegex(
791 format_inspector.SafetyViolation, 'signature', fmt.check_footer
792 )
793
794 # Version must match header
795 fmt.region('footer').data = make_footer(ver=2)
796 self.assertRaisesRegex(
797 format_inspector.SafetyViolation, 'version', fmt.check_footer
798 )
799
800 # Descriptor cannot be longer
801 fmt.region('footer').data = make_footer(d_sec=2)
802 self.assertRaisesRegex(
803 format_inspector.SafetyViolation, 'descriptor', fmt.check_footer
804 )
805
806 # Descriptor cannot be relocated
807 fmt.region('footer').data = make_footer(d_off=0x300)
808 self.assertRaisesRegex(
809 format_inspector.SafetyViolation, 'descriptor', fmt.check_footer
810 )
811
812 # Footer must not have GD_AT_END implying another footer
813 fmt.region('footer').data = make_footer()
814 self.assertRaisesRegex(
815 format_inspector.SafetyViolation,
816 'another footer',
817 fmt.check_footer,
818 )
819
820 # Footer marker type must be correct
821 fmt.region('footer').data = make_footer(gdo=123, fm_typ=7)
822 self.assertRaisesRegex(
823 format_inspector.SafetyViolation, 'marker', fmt.check_footer
824 )
825
826 # Footer marker must indicate size=0
827 fmt.region('footer').data = make_footer(gdo=123, fm_sz=1)
828 self.assertRaisesRegex(
829 format_inspector.SafetyViolation, 'marker', fmt.check_footer
830 )
831
832 # Footer marker must be zero-padded
833 fmt.region('footer').data = make_footer(gdo=123, fm_pad=b'\x01')
834 self.assertRaisesRegex(
835 format_inspector.SafetyViolation, 'marker', fmt.check_footer
836 )
837
838 # EOS marker type must be correct
839 fmt.region('footer').data = make_footer(gdo=123, eos_typ=7)
840 self.assertRaisesRegex(
841 format_inspector.SafetyViolation, 'marker', fmt.check_footer
842 )
843
844 # EOS marker must indicate size=0
845 fmt.region('footer').data = make_footer(gdo=123, eos_sz=1)
846 self.assertRaisesRegex(
847 format_inspector.SafetyViolation, 'marker', fmt.check_footer
848 )
849
850 # EOS marker must be zero-padded
851 fmt.region('footer').data = make_footer(gdo=123, eos_pad=b'\x01')
852 self.assertRaisesRegex(
853 format_inspector.SafetyViolation, 'marker', fmt.check_footer
854 )
855
856 # Everything in place should pass
857 fmt.region('footer').data = make_footer(gdo=123)
858 fmt.check_footer()
859
860 def test_vmdk_safety_checks(self):
861 descriptor_lines = [
862 '# a comment',
863 'createType monolithicFlat',
864 '',
865 ' ',
866 'someUnknownThing=foo',
867 'ddb whatever',
868 'rw 0 somefile.vmdk',
869 ]
870
871 def setup_check():
872 fmt = format_inspector.VMDKInspector()
873 fmt.region('header').data = b'KDMV' * 128
874 data = ('\n'.join(descriptor_lines)).encode()
875 data += b'\x00' * (512 - len(data))
876 fmt.region('descriptor').data = data
877 fmt.region_complete('descriptor')
878 return fmt
879
880 # This should fail because the createType header is broken
881 fmt = setup_check()
882 e = self.assertRaises(
883 format_inspector.SafetyCheckFailed, fmt.safety_check
884 )
885 self.assertIn('Unsupported subformat', str(e.failures['descriptor']))
886
887 # This should fail because the createType is not safe
888 descriptor_lines[1] = 'createType="monolithicFlat"'
889 e = self.assertRaises(
890 format_inspector.SafetyCheckFailed, fmt.safety_check
891 )
892 self.assertIn('Unsupported subformat', str(e.failures['descriptor']))
893
894 # Fix createType and make sure we pass now
895 descriptor_lines[1] = 'createType="monolithicSparse"'
896 fmt = setup_check()
897 fmt.safety_check()
898
899 # Add an extent in an invalid mode which we will not recognize and fail
900 descriptor_lines.append('wronly 2048 somefile2.vmdk')
901 fmt = setup_check()
902 e = self.assertRaises(
903 format_inspector.SafetyCheckFailed, fmt.safety_check
904 )
905 self.assertIn('descriptor data', str(e.failures['descriptor']))
906
907 # Add an extent with a valid mode but an invalid character
908 descriptor_lines[-1] = 'rw 2048 /etc/hosts'
909 fmt = setup_check()
910 e = self.assertRaises(
911 format_inspector.SafetyCheckFailed, fmt.safety_check
912 )
913 self.assertIn('extent filenames', str(e.failures['descriptor']))
914
915 # Make sure we fail if there are no extents
916 descriptor_lines.pop()
917 descriptor_lines.pop()
918 fmt = setup_check()
919 e = self.assertRaises(
920 format_inspector.SafetyCheckFailed, fmt.safety_check
921 )
922 self.assertIn('No extents found', str(e.failures['descriptor']))
923
924 def test_vmdk_format_checks(self):
925 # Invalid signature
926 fmt = format_inspector.VMDKInspector()
927 chunk: bytes | bytearray = b'\x00' * 512
928 self.assertRaisesRegex(
929 format_inspector.ImageFormatError,
930 'Signature',
931 fmt.eat_chunk,
932 chunk,
933 )
934
935 # Good signature but unknown version
936 fmt = format_inspector.VMDKInspector()
937 chunk = b'KDMV\x00' + (b'\x00' * 512)
938 self.assertRaisesRegex(
939 format_inspector.ImageFormatError,
940 'Unsupported format version',
941 fmt.eat_chunk,
942 chunk,
943 )
944
945 # Good signature and version, no footer, invalid descriptor location
946 fmt = format_inspector.VMDKInspector()
947 chunk = bytearray(b'\x00' * 512)
948 chunk[0:5] = b'KDMV\x01'
949 self.assertRaisesRegex(
950 format_inspector.ImageFormatError,
951 'Wrong descriptor location',
952 fmt.eat_chunk,
953 chunk,
954 )
955
956 def test_gpt_mbr_check(self):
957 data = bytearray(b'\x00' * 512 * 2)
958 data[510:512] = b'\x55\xaa'
959 fmt = format_inspector.GPTInspector()
960
961 def mkpte(n=0, boot=0, ostype=0xEE, starth=2, startlba=1):
962 data[446 + n * 16 : 446 + n * 16 + 16] = struct.pack(
963 '<BBBBBBBBII',
964 boot, # boot
965 0x00, # start C
966 starth, # start H
967 0x00, # start S
968 ostype, # OS type
969 0x00, # end C
970 0x00, # end H
971 0x00, # end S
972 startlba, # start LBA
973 0x00, # size LBA
974 )
975 fmt.region('mbr').data = data
976 fmt.region_complete('mbr')
977
978 # Make sure we pass with EFI partition and correct values
979 mkpte()
980 fmt.check_mbr_partitions()
981
982 # Make sure we fail if the boot flag is not one of the valid values
983 mkpte(boot=0xA)
984 self.assertRaisesRegex(
985 format_inspector.SafetyViolation,
986 'invalid boot flag',
987 fmt.check_mbr_partitions,
988 )
989
990 # Make sure we fail if no partitions are defined. This is probably
991 # not a safety problem, but may mean that we mis-identified the image.
992 mkpte(ostype=0)
993 self.assertRaisesRegex(
994 format_inspector.SafetyViolation,
995 'no partitions defined',
996 fmt.check_mbr_partitions,
997 )
998
999 # EFI Protective MBRs are not allowed to have any other partitions
1000 # defined other than the GPT-protecting one.
1001 mkpte()
1002 mkpte(n=1)
1003 self.assertRaisesRegex(
1004 format_inspector.SafetyViolation,
1005 'invalid extra partitions',
1006 fmt.check_mbr_partitions,
1007 )
1008
1009 # Make sure that we tolerate any start CHS value for non-EFI types,
1010 # but refuse outside the required values for EFI.
1011 mkpte(n=1, ostype=2)
1012 mkpte(ostype=0x8E, starth=1)
1013 fmt.check_mbr_partitions()
1014 mkpte(starth=1)
1015 self.assertRaisesRegex(
1016 format_inspector.SafetyViolation,
1017 'invalid start CHS',
1018 fmt.check_mbr_partitions,
1019 )
1020
1021 # Make sure that we tolerate any start LBA value for non-EFI types,
1022 # but refuse outside the required values for EFI.
1023 mkpte(ostype=0x8E, startlba=2)
1024 fmt.check_mbr_partitions()
1025 mkpte(startlba=2)
1026 self.assertRaisesRegex(
1027 format_inspector.SafetyViolation,
1028 'invalid start LBA',
1029 fmt.check_mbr_partitions,
1030 )
1031
1032 def test_unique_names(self):
1033 for key, inspector_cls in format_inspector.ALL_FORMATS.items():
1034 self.assertEqual(key, inspector_cls.NAME)
1035
1036
1037 class TestFormatInspectorInfra(test_base.BaseTestCase):
1038 def _test_capture_region_bs(self, bs):
1039 data = b''.join(chr(x).encode() for x in range(ord('A'), ord('z')))
1040
1041 regions = [
1042 format_inspector.CaptureRegion(3, 9),
1043 format_inspector.CaptureRegion(0, 256),
1044 format_inspector.CaptureRegion(32, 8),
1045 format_inspector.EndCaptureRegion(32),
1046 format_inspector.EndCaptureRegion(5),
1047 ]
1048
1049 for region in regions:
1050 # None of them should be complete yet
1051 self.assertFalse(region.complete)
1052
1053 pos = 0
1054 for i in range(0, len(data), bs):
1055 chunk = data[i : i + bs]
1056 pos += len(chunk)
1057 for region in regions:
1058 region.capture(chunk, pos)
1059
1060 # The end regions should not be complete until we signal EOF
1061 self.assertFalse(regions[3].complete)
1062 self.assertFalse(regions[4].complete)
1063
1064 for region in regions:
1065 try:
1066 region.finish() # type: ignore
1067 except AttributeError:
1068 pass
1069
1070 self.assertEqual(data[3:12], regions[0].data)
1071 self.assertEqual(data[0:256], regions[1].data)
1072 self.assertEqual(data[32:40], regions[2].data)
1073 self.assertEqual(data[-32:], regions[3].data)
1074 self.assertEqual(data[-5:], regions[4].data)
1075
1076 # The small regions should be complete
1077 self.assertTrue(regions[0].complete)
1078 self.assertTrue(regions[2].complete)
1079
1080 # The end regions should be complete
1081 self.assertTrue(regions[3].complete)
1082 self.assertTrue(regions[4].complete)
1083
1084 # This region extended past the available data, so not complete
1085 self.assertFalse(regions[1].complete)
1086
1087 def test_capture_region(self):
1088 for block_size in (1, 3, 7, 13, 32, 64):
1089 self._test_capture_region_bs(block_size)
1090
1091 def _get_wrapper(self, data):
1092 source = io.BytesIO(data)
1093 return format_inspector.InspectWrapper(source)
1094
1095 def test_info_wrapper_file_like(self):
1096 data = b''.join(chr(x).encode() for x in range(ord('A'), ord('z')))
1097 wrapper = self._get_wrapper(data)
1098
1099 read_data = b''
1100 while True:
1101 chunk = wrapper.read(8)
1102 if not chunk:
1103 break
1104 read_data += chunk
1105
1106 self.assertEqual(data, read_data)
1107
1108 def test_info_wrapper_iter_like(self):
1109 data = b''.join(chr(x).encode() for x in range(ord('A'), ord('z')))
1110 wrapper = self._get_wrapper(data)
1111
1112 read_data = b''
1113 for chunk in wrapper:
1114 read_data += chunk
1115
1116 self.assertEqual(data, read_data)
1117
1118 @mock.patch.object(format_inspector.VMDKInspector, 'eat_chunk')
1119 def test_info_wrapper_file_like_eats_error(self, mock_eat):
1120 wrapper = self._get_wrapper(b'123456')
1121 mock_eat.side_effect = Exception('fail')
1122
1123 data = b''
1124 while True:
1125 chunk = wrapper.read(3)
1126 if not chunk:
1127 break
1128 data += chunk
1129
1130 # Make sure we got all the data despite the error
1131 self.assertEqual(b'123456', data)
1132
1133 # Make sure we only called this once and never again after
1134 # the error was raised
1135 mock_eat.assert_called_once_with(b'123')
1136
1137 @mock.patch.object(format_inspector.VMDKInspector, 'eat_chunk')
1138 @mock.patch.object(format_inspector.LOG, 'debug')
1139 def test_wrapper_iter_like_eats_error(
1140 self, mock_log, mock_eat, expected=None
1141 ):
1142 wrapper = format_inspector.InspectWrapper(
1143 iter([b'123', b'456']), # type: ignore
1144 expected_format=expected,
1145 )
1146 mock_eat.side_effect = Exception('fail')
1147
1148 data = b''
1149 for chunk in wrapper:
1150 data += chunk
1151
1152 # Make sure we got all the data despite the error
1153 self.assertEqual(b'123456', data)
1154
1155 # Make sure we only called this once and never again after
1156 # the error was raised
1157 mock_eat.assert_called_once_with(b'123')
1158 if expected:
1159 self.assertFalse(mock_log.called)
1160 else:
1161 self.assertTrue(mock_log.called)
1162
1163 def test_wrapper_iter_like_eats_error_expected_quiet(self):
1164 # Test with an expected format, but not the one we're going to
1165 # intentionally fail to make sure that we do not log failures
1166 # for non-expected formats.
1167 self.test_wrapper_iter_like_eats_error(expected='vhd')
1168
1169 def test_wrapper_aborts_early(self):
1170 # Run the InspectWrapper with non-qcow2 data, expecting qcow2, first
1171 # read past the header should raise the error and abort us early.
1172 data = io.BytesIO(b'\x00' * units.Mi)
1173 wrapper = format_inspector.InspectWrapper(
1174 data, expected_format='qcow2'
1175 )
1176 self.assertRaises(
1177 format_inspector.ImageFormatError, wrapper.read, 2048
1178 )
1179 # We should only have read 2048 bytes from the 1MiB of source data if
1180 # we aborted early.
1181 self.assertEqual(2048, data.tell())
1182
1183 def test_get_inspector(self):
1184 self.assertEqual(
1185 format_inspector.QcowInspector,
1186 format_inspector.get_inspector('qcow2'),
1187 )
1188 self.assertIsNone(format_inspector.get_inspector('foo'))
1189
1190 def test_safety_check_records_result(self):
1191 def fake_check():
1192 raise format_inspector.SafetyViolation('myresult')
1193
1194 check = format_inspector.SafetyCheck(
1195 'foo', fake_check, description='a fake check'
1196 )
1197 self.assertRaisesRegex(
1198 format_inspector.SafetyViolation, 'myresult', check
1199 )
1200
1201 def test_safety_check_records_failure(self):
1202 # This check will fail with ValueError
1203 check = format_inspector.SafetyCheck(
1204 'foo',
1205 lambda: int('a'), # type: ignore
1206 description='a fake check',
1207 )
1208 self.assertRaisesRegex(
1209 format_inspector.SafetyViolation, 'Unexpected error', check
1210 )
1211
1212 def test_safety_check_constants(self):
1213 null_check = format_inspector.SafetyCheck.null()
1214 self.assertIsInstance(null_check, format_inspector.SafetyCheck)
1215 self.assertIsNone(null_check()) # type: ignore
1216
1217 banned_check = format_inspector.SafetyCheck.banned()
1218 self.assertIsInstance(banned_check, format_inspector.SafetyCheck)
1219 self.assertRaisesRegex(
1220 format_inspector.SafetyViolation, 'not allowed', banned_check
1221 )
1222
1223 def test_safety_check_error_conditions(self):
1224 inspector = format_inspector.QcowInspector()
1225 self.assertRaisesRegex(
1226 format_inspector.ImageFormatError,
1227 'Incomplete file.*',
1228 inspector.safety_check,
1229 )
1230 inspector.eat_chunk(b'\x00' * 512)
1231 self.assertRaisesRegex(
1232 format_inspector.ImageFormatError,
1233 'content does not match',
1234 inspector.safety_check,
1235 )
1236
1237 self.assertRaises(RuntimeError, inspector.add_safety_check, 'foo')
1238
1239 def test_safety_checks_required(self):
1240 class BadSafetyCheck(format_inspector.FileInspector):
1241 def _initialize(self):
1242 # No safety checks!
1243 return
1244
1245 @property
1246 def format_match(self):
1247 return True
1248
1249 self.assertRaisesRegex(
1250 RuntimeError, 'at least one safety', BadSafetyCheck
1251 )
1252
1253 def test_finish_is_final(self):
1254 fmt = format_inspector.RawFileInspector()
1255 fmt.eat_chunk(b'\x00')
1256 fmt.finish()
1257 self.assertRaises(RuntimeError, fmt.eat_chunk, b'\x00')
1258
1259
1260 class TestFormatInspectorsTargeted(test_base.BaseTestCase):
1261 def _make_vhd_meta(self, guid_raw, item_length):
1262 # Meta region header, padded to 32 bytes
1263 data = struct.pack('<8sHH', b'metadata', 0, 1)
1264 data += b'0' * 20
1265
1266 # Metadata table entry, 16-byte GUID, 12-byte information,
1267 # padded to 32-bytes
1268 data += guid_raw
1269 data += struct.pack('<III', 256, item_length, 0)
1270 data += b'0' * 6
1271
1272 return data
1273
1274 def test_vhd_table_over_limit(self):
1275 ins = format_inspector.VHDXInspector()
1276 meta = format_inspector.CaptureRegion(0, 0)
1277 desired = b'012345678ABCDEF0'
1278 # This is a poorly-crafted image that specifies a larger table size
1279 # than is allowed
1280 meta.data = self._make_vhd_meta(desired, 33 * 2048)
1281 ins.new_region('metadata', meta)
1282 new_region = ins._find_meta_entry(ins._guid(desired))
1283 assert new_region is not None
1284 # Make sure we clamp to our limit of 32 * 2048
1285 self.assertEqual(
1286 format_inspector.VHDXInspector.VHDX_METADATA_TABLE_MAX_SIZE,
1287 new_region.length,
1288 )
1289
1290 def test_vhd_table_under_limit(self):
1291 ins = format_inspector.VHDXInspector()
1292 meta = format_inspector.CaptureRegion(0, 0)
1293 desired = b'012345678ABCDEF0'
1294 meta.data = self._make_vhd_meta(desired, 16 * 2048)
1295 ins.new_region('metadata', meta)
1296 new_region = ins._find_meta_entry(ins._guid(desired))
1297 assert new_region is not None
1298 # Table size was under the limit, make sure we get it back
1299 self.assertEqual(16 * 2048, new_region.length)