|
| 1 | +"""Security tests for the geotiff subpackage. |
| 2 | +
|
| 3 | +Tests for: |
| 4 | +- Unbounded allocation guard (issue #1184) |
| 5 | +- VRT path traversal prevention (issue #1185) |
| 6 | +""" |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import os |
| 10 | +import struct |
| 11 | +import tempfile |
| 12 | + |
| 13 | +import numpy as np |
| 14 | +import pytest |
| 15 | + |
| 16 | +from xrspatial.geotiff._reader import ( |
| 17 | + MAX_PIXELS_DEFAULT, |
| 18 | + _check_dimensions, |
| 19 | + _read_strips, |
| 20 | + _read_tiles, |
| 21 | + read_to_array, |
| 22 | +) |
| 23 | +from xrspatial.geotiff._header import parse_header, parse_all_ifds |
| 24 | +from xrspatial.geotiff._dtypes import tiff_dtype_to_numpy |
| 25 | +from .conftest import make_minimal_tiff |
| 26 | + |
| 27 | + |
| 28 | +# --------------------------------------------------------------------------- |
| 29 | +# Cat 1: Unbounded allocation guard |
| 30 | +# --------------------------------------------------------------------------- |
| 31 | + |
| 32 | +class TestDimensionGuard: |
| 33 | + def test_check_dimensions_rejects_oversized(self): |
| 34 | + """_check_dimensions raises when total pixels exceed the limit.""" |
| 35 | + with pytest.raises(ValueError, match="exceed the safety limit"): |
| 36 | + _check_dimensions(100_000, 100_000, 1, MAX_PIXELS_DEFAULT) |
| 37 | + |
| 38 | + def test_check_dimensions_accepts_normal(self): |
| 39 | + """_check_dimensions does not raise for normal sizes.""" |
| 40 | + _check_dimensions(1000, 1000, 1, MAX_PIXELS_DEFAULT) |
| 41 | + |
| 42 | + def test_check_dimensions_considers_samples(self): |
| 43 | + """Multi-band images multiply the pixel budget.""" |
| 44 | + # 50_000 x 50_000 x 3 = 7.5 billion, should be rejected |
| 45 | + with pytest.raises(ValueError, match="exceed the safety limit"): |
| 46 | + _check_dimensions(50_000, 50_000, 3, MAX_PIXELS_DEFAULT) |
| 47 | + |
| 48 | + def test_custom_limit(self): |
| 49 | + """A custom max_pixels lets callers tighten or relax the limit.""" |
| 50 | + # Tight limit: 100 pixels |
| 51 | + with pytest.raises(ValueError, match="exceed the safety limit"): |
| 52 | + _check_dimensions(20, 20, 1, max_pixels=100) |
| 53 | + |
| 54 | + # Relaxed: passes with large limit |
| 55 | + _check_dimensions(100_000, 100_000, 1, max_pixels=100_000_000_000) |
| 56 | + |
| 57 | + def test_read_strips_rejects_huge_header(self): |
| 58 | + """_read_strips refuses to allocate when header claims huge dims.""" |
| 59 | + # Build a valid TIFF with small pixel data but huge header dimensions. |
| 60 | + # We fake the header to claim 100000x100000 but only provide 4x4 data. |
| 61 | + data = make_minimal_tiff(4, 4, np.dtype('float32')) |
| 62 | + header = parse_header(data) |
| 63 | + ifds = parse_all_ifds(data, header) |
| 64 | + ifd = ifds[0] |
| 65 | + |
| 66 | + # Monkey-patch the IFD width/height to simulate a crafted header |
| 67 | + from xrspatial.geotiff._header import IFDEntry |
| 68 | + ifd.entries[256] = IFDEntry(tag=256, type_id=3, count=1, value=100_000) |
| 69 | + ifd.entries[257] = IFDEntry(tag=257, type_id=3, count=1, value=100_000) |
| 70 | + |
| 71 | + dtype = tiff_dtype_to_numpy(ifd.bits_per_sample, ifd.sample_format) |
| 72 | + |
| 73 | + with pytest.raises(ValueError, match="exceed the safety limit"): |
| 74 | + _read_strips(data, ifd, header, dtype, max_pixels=1_000_000) |
| 75 | + |
| 76 | + def test_read_tiles_rejects_huge_header(self): |
| 77 | + """_read_tiles refuses to allocate when header claims huge dims.""" |
| 78 | + data = make_minimal_tiff(8, 8, np.dtype('float32'), tiled=True, tile_size=4) |
| 79 | + header = parse_header(data) |
| 80 | + ifds = parse_all_ifds(data, header) |
| 81 | + ifd = ifds[0] |
| 82 | + |
| 83 | + from xrspatial.geotiff._header import IFDEntry |
| 84 | + ifd.entries[256] = IFDEntry(tag=256, type_id=3, count=1, value=100_000) |
| 85 | + ifd.entries[257] = IFDEntry(tag=257, type_id=3, count=1, value=100_000) |
| 86 | + |
| 87 | + dtype = tiff_dtype_to_numpy(ifd.bits_per_sample, ifd.sample_format) |
| 88 | + |
| 89 | + with pytest.raises(ValueError, match="exceed the safety limit"): |
| 90 | + _read_tiles(data, ifd, header, dtype, max_pixels=1_000_000) |
| 91 | + |
| 92 | + def test_read_to_array_max_pixels_kwarg(self, tmp_path): |
| 93 | + """read_to_array passes max_pixels through to the internal readers.""" |
| 94 | + expected = np.arange(16, dtype=np.float32).reshape(4, 4) |
| 95 | + data = make_minimal_tiff(4, 4, np.dtype('float32'), pixel_data=expected) |
| 96 | + path = str(tmp_path / "small.tif") |
| 97 | + with open(path, 'wb') as f: |
| 98 | + f.write(data) |
| 99 | + |
| 100 | + # Should succeed with a generous limit |
| 101 | + arr, _ = read_to_array(path, max_pixels=1_000_000) |
| 102 | + np.testing.assert_array_equal(arr, expected) |
| 103 | + |
| 104 | + # Should fail with a tiny limit |
| 105 | + with pytest.raises(ValueError, match="exceed the safety limit"): |
| 106 | + read_to_array(path, max_pixels=10) |
| 107 | + |
| 108 | + def test_normal_read_unaffected(self, tmp_path): |
| 109 | + """Normal reads within the default limit are not affected.""" |
| 110 | + expected = np.arange(64, dtype=np.float32).reshape(8, 8) |
| 111 | + data = make_minimal_tiff(8, 8, np.dtype('float32'), pixel_data=expected) |
| 112 | + path = str(tmp_path / "normal.tif") |
| 113 | + with open(path, 'wb') as f: |
| 114 | + f.write(data) |
| 115 | + |
| 116 | + arr, _ = read_to_array(path) |
| 117 | + np.testing.assert_array_equal(arr, expected) |
| 118 | + |
| 119 | + |
| 120 | +# --------------------------------------------------------------------------- |
| 121 | +# Cat 5: VRT path traversal |
| 122 | +# --------------------------------------------------------------------------- |
| 123 | + |
| 124 | +class TestVRTPathTraversal: |
| 125 | + def test_relative_path_canonicalized(self, tmp_path): |
| 126 | + """Relative paths in VRT SourceFilename are canonicalized.""" |
| 127 | + from xrspatial.geotiff._vrt import parse_vrt |
| 128 | + |
| 129 | + vrt_xml = '''<VRTDataset rasterXSize="4" rasterYSize="4"> |
| 130 | + <VRTRasterBand dataType="Float32" band="1"> |
| 131 | + <SimpleSource> |
| 132 | + <SourceFilename relativeToVRT="1">../../../etc/shadow</SourceFilename> |
| 133 | + <SourceBand>1</SourceBand> |
| 134 | + <SrcRect xOff="0" yOff="0" xSize="4" ySize="4"/> |
| 135 | + <DstRect xOff="0" yOff="0" xSize="4" ySize="4"/> |
| 136 | + </SimpleSource> |
| 137 | + </VRTRasterBand> |
| 138 | +</VRTDataset>''' |
| 139 | + |
| 140 | + vrt_dir = str(tmp_path / "subdir") |
| 141 | + os.makedirs(vrt_dir) |
| 142 | + |
| 143 | + vrt = parse_vrt(vrt_xml, vrt_dir) |
| 144 | + source_path = vrt.bands[0].sources[0].filename |
| 145 | + |
| 146 | + # After canonicalization, the path should NOT contain ".." |
| 147 | + assert ".." not in source_path |
| 148 | + # It should be an absolute path |
| 149 | + assert os.path.isabs(source_path) |
| 150 | + # Verify it was resolved through realpath |
| 151 | + assert source_path == os.path.realpath(source_path) |
| 152 | + |
| 153 | + def test_normal_relative_path_still_works(self, tmp_path): |
| 154 | + """Normal relative paths without traversal still resolve correctly.""" |
| 155 | + from xrspatial.geotiff._vrt import parse_vrt |
| 156 | + |
| 157 | + vrt_xml = '''<VRTDataset rasterXSize="4" rasterYSize="4"> |
| 158 | + <VRTRasterBand dataType="Float32" band="1"> |
| 159 | + <SimpleSource> |
| 160 | + <SourceFilename relativeToVRT="1">data/tile.tif</SourceFilename> |
| 161 | + <SourceBand>1</SourceBand> |
| 162 | + <SrcRect xOff="0" yOff="0" xSize="4" ySize="4"/> |
| 163 | + <DstRect xOff="0" yOff="0" xSize="4" ySize="4"/> |
| 164 | + </SimpleSource> |
| 165 | + </VRTRasterBand> |
| 166 | +</VRTDataset>''' |
| 167 | + |
| 168 | + vrt_dir = str(tmp_path) |
| 169 | + vrt = parse_vrt(vrt_xml, vrt_dir) |
| 170 | + source_path = vrt.bands[0].sources[0].filename |
| 171 | + |
| 172 | + expected = os.path.realpath(os.path.join(vrt_dir, "data", "tile.tif")) |
| 173 | + assert source_path == expected |
| 174 | + |
| 175 | + def test_absolute_path_also_canonicalized(self, tmp_path): |
| 176 | + """Absolute paths in VRT are also canonicalized.""" |
| 177 | + from xrspatial.geotiff._vrt import parse_vrt |
| 178 | + |
| 179 | + vrt_xml = '''<VRTDataset rasterXSize="4" rasterYSize="4"> |
| 180 | + <VRTRasterBand dataType="Float32" band="1"> |
| 181 | + <SimpleSource> |
| 182 | + <SourceFilename relativeToVRT="0">/tmp/../tmp/test.tif</SourceFilename> |
| 183 | + <SourceBand>1</SourceBand> |
| 184 | + <SrcRect xOff="0" yOff="0" xSize="4" ySize="4"/> |
| 185 | + <DstRect xOff="0" yOff="0" xSize="4" ySize="4"/> |
| 186 | + </SimpleSource> |
| 187 | + </VRTRasterBand> |
| 188 | +</VRTDataset>''' |
| 189 | + |
| 190 | + vrt = parse_vrt(vrt_xml, str(tmp_path)) |
| 191 | + source_path = vrt.bands[0].sources[0].filename |
| 192 | + |
| 193 | + assert ".." not in source_path |
| 194 | + assert source_path == os.path.realpath("/tmp/../tmp/test.tif") |
0 commit comments