Skip to content

Commit 5accd5b

Browse files
committed
pad truncated data in bits2byte instead of reading out of bounds
1 parent b7f7375 commit 5accd5b

2 files changed

Lines changed: 13 additions & 0 deletions

File tree

pypdf/generic/_image_xobject.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ def bits2byte(data: bytes, size: tuple[int, int], bits: int) -> bytes:
131131

132132
byte_buffer = bytearray(buffer_size)
133133
mask = (1 << bits) - 1
134+
135+
required = size[1] * ((size[0] * bits + 7) // 8)
136+
if len(data) < required:
137+
logger_warning("Image data is not rectangular. Adding padding.", source=__name__)
138+
data += b"\x00" * (required - len(data))
139+
134140
data_index = 0
135141
bit = 8 - bits
136142
for y in range(size[1]):

tests/generic/test_image_xobject.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,3 +276,10 @@ def test_bits2byte__limit() -> None:
276276
match=r"^Requested buffer size 76500000 exceeds limit of 75000000\.$"
277277
):
278278
bits2byte(data=b"TEST", size=(9000, 8500), bits=8)
279+
280+
281+
def test_bits2byte__truncated_data(caplog) -> None:
282+
# 4x4 image at 2 bits per sample needs 4 bytes; provide only 1.
283+
result = bits2byte(data=b"\x00", size=(4, 4), bits=2)
284+
assert result == bytes(16)
285+
assert "Image data is not rectangular. Adding padding." in caplog.text

0 commit comments

Comments
 (0)