Debian Codegraph @

podofo/test/unit/BoundsCheckTest.cpp

raw
1 // SPDX-FileCopyrightText: 2026 PoDoFo contributors
2 // SPDX-License-Identifier: MIT-0
3
4 #include <PdfTest.h>
5
6 using namespace std;
7 using namespace PoDoFo;
8
9 // Subclass PdfTokenizer to expose protected ReadString / ReadHexString
10 class TestableTokenizer : public PdfTokenizer
11 {
12 public:
13 using PdfTokenizer::ReadString;
14 using PdfTokenizer::ReadHexString;
15 };
16
17 // ---------------------------------------------------------------------------
18 // 1) Unterminated regular string – must be rejected when it exceeds the
19 // maximum allowed string length instead of growing until OOM.
20 // ---------------------------------------------------------------------------
21 TEST_CASE("TestStringGrowthIsBounded")
22 {
23 // Build a '(' followed by data exceeding MaxStringLength with no
24 // closing ')'. After the fix the size cap rejects this; before the
25 // fix m_charBuffer grows without limit.
26 constexpr size_t payloadSize = PdfTokenizer::MaxStringLength + 1;
27 string input(payloadSize + 1, 'A');
28 input[0] = '('; // opening paren, never closed
29
30 SpanStreamDevice device(input);
31 TestableTokenizer tokenizer;
32 PdfVariant variant;
33
34 // Consume the '(' token first
35 string_view token;
36 PdfTokenType tokenType;
37 REQUIRE(tokenizer.TryReadNextToken(device, token, tokenType));
38 REQUIRE(tokenType == PdfTokenType::ParenthesisLeft);
39
40 // ReadString should throw ValueOutOfRange because the string exceeds
41 // the maximum allowed length
42 try
43 {
44 tokenizer.ReadString(device, variant, nullptr, { true, false });
45 FAIL("Expected PdfError to be thrown");
46 }
47 catch (const PdfError& e)
48 {
49 REQUIRE(e.GetCode() == PdfErrorCode::ValueOutOfRange);
50 }
51 }
52
53 // ---------------------------------------------------------------------------
54 // 2) Unterminated hex string – same pattern, different code path.
55 // ---------------------------------------------------------------------------
56 TEST_CASE("TestHexStringGrowthIsBounded")
57 {
58 constexpr size_t payloadSize = PdfTokenizer::MaxStringLength + 1;
59 string input(payloadSize + 1, 'A'); // 'A' is a valid hex digit
60 input[0] = '<'; // opening angle bracket, never closed
61
62 SpanStreamDevice device(input);
63 TestableTokenizer tokenizer;
64 PdfVariant variant;
65
66 string_view token;
67 PdfTokenType tokenType;
68 REQUIRE(tokenizer.TryReadNextToken(device, token, tokenType));
69 REQUIRE(tokenType == PdfTokenType::AngleBracketLeft);
70
71 try
72 {
73 tokenizer.ReadHexString(device, variant, nullptr, { true, false });
74 FAIL("Expected PdfError to be thrown");
75 }
76 catch (const PdfError& e)
77 {
78 REQUIRE(e.GetCode() == PdfErrorCode::ValueOutOfRange);
79 }
80 }
81
82 // ---------------------------------------------------------------------------
83 // 3) Object stream with offset beyond buffer – readObjectsFromStream must
84 // reject first+offset that exceeds the decompressed buffer length.
85 // We test via PdfObjectStreamParser indirectly by crafting a minimal PDF
86 // with an ObjStm whose /First is larger than the stream content.
87 //
88 // This test builds a complete XRef-stream-based PDF so the parser
89 // actually enters the object stream parsing code path.
90 // ---------------------------------------------------------------------------
91 TEST_CASE("TestObjectStreamOffsetBeyondBuffer")
92 {
93 // Strategy: Build a PDF 1.5 document with:
94 // obj 1 = catalog (normal object at known offset)
95 // obj 2 = ObjStm with /First 99999, but stream content is tiny
96 // obj 3 = compressed inside obj 2 (referenced via XRef stream type-2)
97 // obj 4 = XRef stream (the cross-reference itself)
98 //
99 // The XRef stream tells the parser that obj 3 lives inside obj 2,
100 // triggering PdfObjectStreamParser::Parse which should now fail
101 // because /First (99999) exceeds the stream buffer.
102
103 // --- Object 1: catalog ---
104 ostringstream oss;
105 oss << "%PDF-1.5\n";
106
107 size_t obj1Pos = oss.str().size();
108 oss << "1 0 obj\n"
109 << "<< /Type /Catalog /Pages 1 0 R >>\n"
110 << "endobj\n";
111
112 // --- Object 2: ObjStm with bad /First ---
113 // Stream content: "3 0\n42" means object #3 is at offset 0 from /First, value=42
114 string objStmContent = "3 0\n42";
115 size_t obj2Pos = oss.str().size();
116 oss << "2 0 obj\n"
117 << "<< /Type /ObjStm /N 1 /First 99999 /Length "
118 << objStmContent.size() << " >>\n"
119 << "stream\n"
120 << objStmContent
121 << "\nendstream\n"
122 << "endobj\n";
123
124 // --- Object 4: XRef stream ---
125 // W = [1 2 1]: type(1 byte), field2(2 bytes), field3(1 byte)
126 // Entries (5 total: obj 0-4):
127 // obj 0: type=0 (free), next=0, gen=0
128 // obj 1: type=1 (normal), offset=obj1Pos, gen=0
129 // obj 2: type=1 (normal), offset=obj2Pos, gen=0
130 // obj 3: type=2 (compressed), stream_obj=2, index=0
131 // obj 4: type=1 (normal), offset=obj4Pos, gen=0 <-- self
132 size_t obj4Pos = oss.str().size();
133
134 // We need to encode the xref stream binary content.
135 // Each entry is 4 bytes: [type:1][field2_hi:1][field2_lo:1][field3:1]
136 // We'll use ASCIIHexDecode so we can write hex in the stream.
137 // Entry format with W=[1 2 1]:
138 // obj 0: 00 0000 00
139 // obj 1: 01 XXXX 00 (XXXX = obj1Pos as 2 bytes)
140 // obj 2: 01 YYYY 00 (YYYY = obj2Pos as 2 bytes)
141 // obj 3: 02 0002 00 (compressed in obj 2, index 0)
142 // obj 4: 01 ZZZZ 00 (ZZZZ = obj4Pos as 2 bytes)
143
144 ostringstream xrefData;
145 xrefData << utls::Format("{:02X}{:04X}{:02X}", 0, 0, 0);
146 xrefData << utls::Format("{:02X}{:04X}{:02X}", 1, (unsigned)obj1Pos, 0);
147 xrefData << utls::Format("{:02X}{:04X}{:02X}", 1, (unsigned)obj2Pos, 0);
148 xrefData << utls::Format("{:02X}{:04X}{:02X}", 2, 2, 0);
149 xrefData << utls::Format("{:02X}{:04X}{:02X}", 1, (unsigned)obj4Pos, 0);
150 string xrefHex = xrefData.str();
151
152 oss << "4 0 obj\n"
153 << "<< /Type /XRef /Size 5 /W [1 2 1]"
154 << " /Root 1 0 R"
155 << " /Filter /ASCIIHexDecode"
156 << " /Length " << xrefHex.size()
157 << " >>\n"
158 << "stream\n"
159 << xrefHex
160 << "\nendstream\n"
161 << "endobj\n";
162
163 oss << "startxref\n" << obj4Pos << "\n%%EOF\n";
164
165 string pdfBuf = oss.str();
166
167 // Loading should trigger reading obj 3 from the ObjStm (obj 2),
168 // which should fail because /First=99999 exceeds the stream content.
169 // Before the fix, this is caught incidentally by SpanStreamDevice::Seek
170 // throwing ValueOutOfRange. After the fix, PdfObjectStreamParser should
171 // detect this explicitly and throw BrokenFile before reaching the Seek.
172 bool threw = false;
173 PdfErrorCode caughtCode = PdfErrorCode::Unknown;
174 try
175 {
176 PdfMemDocument doc;
177 doc.LoadFromBuffer(pdfBuf);
178 // If we get here, access obj 3 to force parsing
179 (void)doc.GetObjects().GetObject(PdfReference(3, 0));
180 }
181 catch (const PdfError& e)
182 {
183 threw = true;
184 caughtCode = e.GetCode();
185 }
186 REQUIRE(threw);
187 // After the fix this should be BrokenFile (explicit bounds check);
188 // before the fix it was ValueOutOfRange (incidental Seek failure).
189 REQUIRE(caughtCode == PdfErrorCode::BrokenFile);
190 }
191
192