Debian Codegraph @

podofo/test/unit/ParserTest.cpp

raw symbols SCIP
1 /**
2 * Copyright (C) 2007 by Dominik Seichter <[email protected]>
3 * Copyright (C) 2021 by Francesco Pretto <[email protected]>
4 *
5 * Licensed under GNU Library General Public 2.0 or later.
6 * Some rights reserved. See COPYING, AUTHORS.
7 */
8
9 /*
10 Notes:
11
12 1) out of memory tests don't run if Address Santizer (ASAN) is enabled because
13 ASAN terminates the unit test process the first time it attempts to allocate
14 too much memory (so running the tests with and without ASAN is recommended)
15
16 2) PoDoFo log warnings about inconsistencies or values out of range are expected
17 because the tests are supplying invalid values to check PoDoFo behaves correctly
18 in those situations
19 */
20
21 #include <limits>
22
23 #include <sstream>
24
25 #include <PdfTest.h>
26
27 using namespace std;
28 using namespace PoDoFo;
29
30 static string generateXRefEntries(size_t count);
31 static bool canOutOfMemoryKillUnitTests();
32 static void testReadXRefSubsection();
33 static size_t getStackOverflowDepth();
34
35 // this value is from Table C.1 in Appendix C.2 Architectural Limits in PDF 32000-1:2008
36 // on 32-bit systems sizeof(PdfParser::TXRefEntry)=16 => max size of m_offsets=16*8,388,607 = 134 MB
37 // on 64-bit systems sizeof(PdfParser::TXRefEntry)=24 => max size of m_offsets=16*8,388,607 = 201 MB
38 constexpr unsigned maxNumberOfIndirectObjects = 8388607;
39
40 namespace PoDoFo
41 {
42 class PdfParserTest : public PdfParser
43 {
44 public:
45 PdfParserTest(PdfIndirectObjectList& objectList, string buff)
46 : PdfParser(objectList), m_buffer(std::move(buff)), m_device(new SpanStreamDevice(m_buffer))
47 {
48 }
49
50 void ReadXRefContents(size_t offset, bool positionAtEnd)
51 {
52 // call protected method
53 PdfParser::ReadXRefContents(*m_device, offset, positionAtEnd);
54 }
55
56 void ReadXRefSubsection(int64_t firstObject, int64_t objectCount)
57 {
58 // call protected method
59 PdfParser::ReadXRefSubsection(*m_device, firstObject, objectCount);
60 }
61
62 void ReadXRefStreamContents(size_t offset, bool readOnlyTrailer)
63 {
64 // call protected method
65 PdfParser::ReadXRefStreamContents(*m_device, offset, readOnlyTrailer);
66 }
67
68 void ReadDocumentStructure()
69 {
70 // call protected method
71 PdfParser::ReadDocumentStructure(*m_device);
72 }
73
74 void ReadObjects()
75 {
76 // call protected method
77 PdfParser::ReadObjects(*m_device);
78 }
79
80 bool IsPdfFile()
81 {
82 // call protected method
83 return PdfParser::IsPdfFile(*m_device);
84 }
85
86 const shared_ptr<InputStreamDevice>& GetDevice() { return m_device; }
87
88 private:
89 string m_buffer;
90 shared_ptr<InputStreamDevice> m_device;
91 };
92 }
93
94 TEST_CASE("TestMaxObjectCount")
95 {
96 PdfParser::SetMaxObjectCount(numeric_limits<unsigned short>::max());
97 testReadXRefSubsection();
98
99 PdfParser::SetMaxObjectCount(maxNumberOfIndirectObjects);
100 testReadXRefSubsection();
101 }
102
103 // NOTE: This test is too long to be normally done on every run
104 TEST_CASE("TestMaxObjectCount2", "[.]")
105 {
106 PdfParser::SetMaxObjectCount(numeric_limits<unsigned>::max());
107 testReadXRefSubsection();
108 }
109
110
111 TEST_CASE("TestReadXRefContents")
112 {
113 try
114 {
115 // generate an xref section
116 // xref
117 // 0 3
118 // 0000000000 65535 f
119 // 0000000018 00000 n
120 // 0000000077 00000 n
121 // trailer << /Root 1 0 R /Size 3 >>
122 // startxref
123 // 0
124 // %%EOF
125 ostringstream oss;
126 oss << "xref\r\n0 3\r\n";
127 oss << generateXRefEntries(3);
128 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
129 oss << "startxref 0\r\n";
130 oss << "%EOF";
131 PdfIndirectObjectList objects;
132 PdfParserTest parser(objects, oss.str());
133 parser.ReadXRefContents(0, false);
134 // expected to succeed
135 }
136 catch (PdfError&)
137 {
138 FAIL("Should not throw PdfError");
139 }
140 catch (exception&)
141 {
142 FAIL("Unexpected exception type");
143 }
144
145 try
146 {
147 // generate an xref section with missing xref entries
148 // xref
149 // 0 3
150 // 0000000000 65535 f
151 // 0000000018 00000 n
152 //
153 // trailer << /Root 1 0 R /Size 3 >>
154 // startxref
155 // 0
156 // %%EOF
157 ostringstream oss;
158 oss << "xref\r\n0 3\r\n";
159 oss << generateXRefEntries(2); // 2 entries supplied, but expecting 3 entries
160 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
161 oss << "startxref 0\r\n";
162 oss << "%EOF";
163 PdfIndirectObjectList objects;
164 PdfParserTest parser(objects, oss.str());
165 parser.ReadXRefContents(0, false);
166 }
167 catch (PdfError& error)
168 {
169 REQUIRE(error.GetCode() == PdfErrorCode::NoTrailer);
170 }
171 catch (exception&)
172 {
173 FAIL("Unexpected exception type");
174 }
175
176 try
177 {
178 // TODO malformed entries are not detected
179 // generate an xref section with badly formed xref entries
180 // xref
181 // 0 3
182 // 000000000 65535
183 // 00000000065535 x
184 // 0000000
185 // 0000000018 00000 n
186 // 0000000077 00000 n
187 // trailer << /Root 1 0 R /Size 3 >>
188 // startxref
189 // 0
190 // %%EOF
191 ostringstream oss;
192 oss << "xref\r\n0 5\r\n";
193 oss << "000000000 65535\r\n";
194 oss << "00000000065535 x\r\n";
195 oss << "0000000\r\n";
196 oss << generateXRefEntries(2);
197 oss << "trailer << /Root 1 0 R /Size 5 >>\r\n";
198 oss << "startxref 0\r\n";
199 oss << "%EOF";
200 PdfIndirectObjectList objects;
201 PdfParserTest parser(objects, oss.str());
202 parser.ReadXRefContents(0, false);
203 // succeeds reading badly formed xref entries - should it?
204 }
205 catch (PdfError& error)
206 {
207 REQUIRE(error.GetCode() == PdfErrorCode::NoTrailer);
208 }
209 catch (exception&)
210 {
211 FAIL("Unexpected exception type");
212 }
213
214 // CVE-2017-8053 ReadXRefContents and ReadXRefStreamContents are mutually recursive
215 // and can cause stack overflow
216
217 try
218 {
219 // generate an xref section and one XRef stream that references itself
220 // via the /Prev entry (but use a slightly lower offset by linking to
221 // to whitespace discarded by the tokenizer just before the xref section)
222 // xref
223 // 0 1
224 // 000000000 65535
225 // 2 0 obj << /Type XRef /Prev offsetXrefStmObj2 >> stream ... endstream
226 // trailer << /Root 1 0 R /Size 3 >>
227 // startxref
228 // offsetXrefStmObj2
229 // %%EOF
230 ostringstream oss;
231
232 // object stream contents - length excludes trailing whitespace
233 string streamContents =
234 "01 0E8A 0\r\n"
235 "02 0002 00\r\n";
236 size_t streamContentsLength = streamContents.size() - strlen("\r\n");
237
238 // xref section at offset 0
239 //size_t offsetXref = 0;
240 oss << "xref\r\n0 1\r\n";
241 oss << generateXRefEntries(1);
242
243 // XRef stream at offsetXrefStm1, but any /Prev entries pointing to any offet between
244 // offsetXrefStm1Whitespace and offsetXrefStm1 point to the same /Prev section
245 // because the PDF processing model says tokenizer must discard whitespace and comments
246 size_t offsetXrefStm1Whitespace = oss.str().length();
247 oss << " \r\n";
248 oss << "% comments and leading white space are ignored - see PdfTokenizer::GetNextToken\r\n";
249 size_t offsetXrefStm1 = oss.str().length();
250 oss << "2 0 obj ";
251 oss << "<< /Type /XRef ";
252 oss << "/Length " << streamContentsLength << " ";
253 oss << "/Index [2 2] ";
254 oss << "/Size 3 ";
255 oss << "/Prev " << offsetXrefStm1Whitespace << " "; // xref /Prev offset points back to start of this stream object
256 oss << "/W [1 2 1] ";
257 oss << "/Filter /ASCIIHexDecode ";
258 oss << ">>\r\n";
259 oss << "stream\r\n";
260 oss << streamContents;
261 oss << "endstream\r\n";
262 oss << "endobj\r\n";
263
264 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
265 oss << "startxref " << offsetXrefStm1 << "\r\n";
266 oss << "%EOF";
267
268 PdfIndirectObjectList objects;
269 PdfParserTest parser(objects, oss.str());
270 parser.ReadXRefContents(offsetXrefStm1, false);
271 // succeeds in current code - should it?
272 }
273 catch (PdfError& error)
274 {
275 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefType);
276 }
277 catch (exception&)
278 {
279 FAIL("Unexpected exception type");
280 }
281
282 try
283 {
284 // generate an xref section and two XRef streams that reference each other
285 // via the /Prev entry
286 // xref
287 // 0 1
288 // 000000000 65535
289 // 2 0 obj << /Type XRef /Prev offsetXrefStmObj3 >> stream ... endstream
290 // 3 0 obj << /Type XRef /Prev offsetXrefStmObj2 >> stream ... endstream
291 // trailer << /Root 1 0 R /Size 3 >>
292 // startxref
293 // offsetXrefStmObj2
294 // %%EOF
295 ostringstream oss;
296
297 // object stream contents - length excludes trailing whitespace
298 string streamContents =
299 "01 0E8A 0\r\n"
300 "02 0002 00\r\n";
301 size_t streamContentsLength = streamContents.size() - strlen("\r\n");
302
303 // xref section at offset 0
304 //size_t offsetXref = 0;
305 oss << "xref\r\n0 1\r\n";
306 oss << generateXRefEntries(1);
307
308 // xrefstm at offsetXrefStm1
309 size_t offsetXrefStm1 = oss.str().length();
310 oss << "2 0 obj ";
311 oss << "<< /Type /XRef ";
312 oss << "/Length " << streamContentsLength << " ";
313 oss << "/Index [2 2] ";
314 oss << "/Size 3 ";
315 oss << "/Prev 185 "; // xref stream 1 sets xref stream 2 as previous in chain
316 oss << "/W [1 2 1] ";
317 oss << "/Filter /ASCIIHexDecode ";
318 oss << ">>\r\n";
319 oss << "stream\r\n";
320 oss << streamContents;
321 oss << "endstream\r\n";
322 oss << "endobj\r\n";
323
324 // xrefstm at offsetXrefStm2
325 size_t offsetXrefStm2 = oss.str().length();
326 REQUIRE(offsetXrefStm2 == 185); // hard-coded in /Prev entry in XrefStm1 above
327 oss << "3 0 obj ";
328 oss << "<< /Type /XRef ";
329 oss << "/Length " << streamContentsLength << " ";
330 oss << "/Index [2 2] ";
331 oss << "/Size 3 ";
332 oss << "/Prev " << offsetXrefStm1 << " "; // xref stream 2 sets xref stream 1 as previous in chain
333 oss << "/W [1 2 1] ";
334 oss << "/Filter /ASCIIHexDecode ";
335 oss << ">>\r\n";
336 oss << "stream\r\n";
337 oss << streamContents;
338 oss << "endstream\r\n";
339 oss << "endobj\r\n";
340
341 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
342 oss << "startxref " << offsetXrefStm2 << "\r\n";
343 oss << "%EOF";
344
345 PdfIndirectObjectList objects;
346 PdfParserTest parser(objects, oss.str());
347 parser.ReadXRefContents(offsetXrefStm2, false);
348 // succeeds in current code - should it?
349 }
350 catch (PdfError& error)
351 {
352 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefType);
353 }
354 catch (exception&)
355 {
356 FAIL("Unexpected exception type");
357 }
358
359 try
360 {
361 // generate an xref section and lots of XRef streams without loops but reference
362 // the previous stream via the /Prev entry
363 // xref
364 // 0 1
365 // 000000000 65535
366 // 2 0 obj << /Type XRef >> stream ... endstream
367 // 3 0 obj << /Type XRef /Prev offsetStreamObj(2) >> stream ... endstream
368 // 4 0 obj << /Type XRef /Prev offsetStreamObj(3) >> stream ... endstream
369 // ...
370 // N 0 obj << /Type XRef /Prev offsetStreamObj(N-1) >> stream ... endstream
371 // trailer << /Root 1 0 R /Size 3 >>
372 // startxref
373 // offsetStreamObj(N)
374 // %%EOF
375 ostringstream oss;
376 size_t prevOffset = 0;
377 size_t currentOffset = 0;
378
379 // object stream contents - length excludes trailing whitespace
380 string streamContents =
381 "01 0E8A 0\r\n"
382 "02 0002 00\r\n";
383 size_t streamContentsLength = streamContents.size() - strlen("\r\n");
384
385 // xref section at offset 0
386 //size_t offsetXref = 0;
387 oss << "xref\r\n0 1\r\n";
388 oss << generateXRefEntries(1);
389
390 // this caused stack overflow on macOS 64-bit with around 3000 streams
391 // and on Windows 32-bit with around 1000 streams
392
393 constexpr size_t maxXrefStreams = 10000;
394 for (size_t i = 0; i < maxXrefStreams; i++)
395 {
396 size_t objNo = i + 2;
397
398 // xrefstm at currentOffset linked back to stream at prevOffset
399 prevOffset = currentOffset;
400 currentOffset = oss.str().length();
401 oss << objNo << " 0 obj ";
402 oss << "<< /Type /XRef ";
403 oss << "/Length " << streamContentsLength << " ";
404 oss << "/Index [2 2] ";
405 oss << "/Size 3 ";
406 if (prevOffset > 0)
407 oss << "/Prev " << prevOffset << " ";
408 oss << "/W [1 2 1] ";
409 oss << "/Filter /ASCIIHexDecode ";
410 oss << ">>\r\n";
411 oss << "stream\r\n";
412 oss << streamContents;
413 oss << "endstream\r\n";
414 oss << "endobj\r\n";
415 }
416
417 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
418 oss << "startxref " << currentOffset << "\r\n";
419 oss << "%EOF";
420
421 PdfIndirectObjectList objects;
422 PdfParserTest parser(objects, oss.str());
423 parser.ReadXRefContents(currentOffset, false);
424 // succeeds in current code - should it?
425 }
426 catch (PdfError& error)
427 {
428 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefType);
429 }
430 catch (exception&)
431 {
432 FAIL("Unexpected exception type");
433 }
434 }
435
436 void testReadXRefSubsection()
437 {
438 int64_t firstObject = 0;
439 int64_t objectCount = 0;
440
441 // TODO does ReadXRefSubsection with objectCount = 0 make sense ???
442
443 // CVE-2017-5855 m_offsets.resize() NULL ptr read
444 // CVE-2017-6844 m_offsets.resize() buffer overwrite
445 // false positives due to AFL setting allocator_may_return_null=1 which causes
446 // ASAN to return NULL instead of throwing bad_alloc for out-of-memory conditions
447 // https://github.com/mirrorer/afl/blob/master/docs/env_variables.txt#L248
448 // https://github.com/google/sanitizers/issues/295#issuecomment-234273218
449 // the test for CVE-2018-5296 below checks that PoDoFo restricts allocations
450
451 // CVE-2018-5296 m_offsets.resize() malloc failure when large size specified
452 // check PoDoFo throws PdfError and not anything derived from exception
453 // check PoDoFo can't allocate unrestricted amounts of memory
454
455 if (PdfParser::GetMaxObjectCount() <= maxNumberOfIndirectObjects)
456 {
457 try
458 {
459 string strInput = generateXRefEntries(PdfParser::GetMaxObjectCount());
460 PdfIndirectObjectList objects;
461 PdfParserTest parser(objects, strInput);
462 firstObject = 0;
463 objectCount = PdfParser::GetMaxObjectCount();
464 parser.ReadXRefSubsection(firstObject, objectCount);
465 // expected to succeed
466 }
467 catch (PdfError&)
468 {
469 FAIL("should not throw PdfError");
470 }
471 catch (exception&)
472 {
473 FAIL("Unexpected exception type");
474 }
475 }
476 else
477 {
478 // test has been called from testMaxObjectCount with PdfParser::SetMaxObjectCount()
479 // set to a large value (large allocs are tested in address space tests below)
480 }
481
482 // don't run the following test if PdfParser::GetMaxObjectCount()+1 will overflow
483 // in the numXRefEntries calculation below (otherwise we get an ASAN error)
484 if (PdfParser::GetMaxObjectCount() < numeric_limits<unsigned>::max())
485 {
486 // don't generate xrefs for high values of GetMaxObjectCount() e.g. don't try to generate 2**63 xrefs
487 unsigned numXRefEntries = std::min(maxNumberOfIndirectObjects + 1, PdfParser::GetMaxObjectCount() + 1);
488
489 try
490 {
491 string strInput = generateXRefEntries(numXRefEntries);
492 PdfIndirectObjectList objects;
493 PdfParserTest parser(objects, strInput);
494 firstObject = 0;
495 objectCount = (int64_t)PdfParser::GetMaxObjectCount() + 1;
496 parser.ReadXRefSubsection(firstObject, objectCount);
497 FAIL("PdfError not thrown");
498 }
499 catch (PdfError& error)
500 {
501 // too many indirect objects in Trailer /Size key throws PdfErrorCode::ValueOutOfRange
502 // but too many indirect objects in xref table throws PdfErrorCode::InvalidXRef
503 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
504 }
505 catch (exception&)
506 {
507 FAIL("Wrong exception type");
508 }
509 }
510
511 // CVE-2018-5296 try to allocate more than address space size
512 // should throw a bad_length exception in STL which is rethrown as a PdfError
513 try
514 {
515 // this attempts to allocate numeric_limits<size_t>::max()/2 * sizeof(TXRefEntry)
516 // on 32-bit systems this allocates 2**31 * sizeof(TXRefEntry) = 2**31 * 16 (larger than 32-bit address space)
517 // on LP64 (macOS,*nix) systems this allocates 2**63 * sizeof(TXRefEntry) = 2**63 * 24 (larger than 64-bit address space)
518 // on LLP64 (Win64) systems this allocates 2**31 * sizeof(TXRefEntry) = 2**31 * 16 (smaller than 64-bit address space)
519 string strInput = " ";
520 PdfIndirectObjectList objects;
521 PdfParserTest parser(objects, strInput);
522 firstObject = 1;
523 objectCount = numeric_limits<size_t>::max() / 2 - 1;
524 parser.ReadXRefSubsection(firstObject, objectCount);
525 FAIL("PdfError not thrown");
526 }
527 catch (PdfError& error)
528 {
529 // if objectCount > PdfParser::GetMaxObjectCount() then we'll see PdfErrorCode::InvalidXRef
530 // otherwise we'll see PdfErrorCode::ValueOutOfRange or PdfErrorCode::OutOfMemory (see testMaxObjectCount)
531 REQUIRE((error.GetCode() == PdfErrorCode::InvalidXRef
532 || error.GetCode() == PdfErrorCode::ValueOutOfRange
533 || error.GetCode() == PdfErrorCode::OutOfMemory));
534 }
535 catch (exception&)
536 {
537 FAIL("Wrong exception type");
538 }
539
540 // CVE-2018-5296 try to allocate 95% of VM address space size (which should always fail)
541 if (!canOutOfMemoryKillUnitTests())
542 {
543 constexpr size_t maxObjects = numeric_limits<size_t>::max() / sizeof(PdfXRefEntry) / 100 * 95;
544
545 try
546 {
547 string strInput = " ";
548 PdfIndirectObjectList objects;
549 PdfParserTest parser(objects, strInput);
550 firstObject = 1;
551 objectCount = maxObjects;
552 parser.ReadXRefSubsection(firstObject, objectCount);
553 FAIL("PdfError not thrown");
554 }
555 catch (PdfError& error)
556 {
557 if (maxObjects >= (size_t)PdfParser::GetMaxObjectCount())
558 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
559 else
560 REQUIRE(error.GetCode() == PdfErrorCode::OutOfMemory);
561 }
562 catch (exception&)
563 {
564 FAIL("Wrong exception type");
565 }
566 }
567
568 // CVE-2015-8981 happens because this->GetNextNumber() can return negative numbers
569 // in range (LONG_MIN to LONG_MAX) so the xref section below causes a buffer underflow
570 // because m_offsets[-5].bParsed is set to true when first entry is read
571 // NOTE: vector operator[] is not bounds checked
572
573 // xref
574 // -5 5
575 // 0000000000 65535 f
576 // 0000000018 00000 n
577 // 0000000077 00000 n
578 // 0000000178 00000 n
579 // 0000000457 00000 n
580 // trailer
581 // << /Root 1 0 R
582 // /Size 5
583 //>>
584 // startxref
585 // 565
586 // %%EOF
587
588 try
589 {
590 string strInput = "0000000000 65535 f\r\n";
591 PdfIndirectObjectList objects;
592 PdfParserTest parser(objects, strInput);
593 firstObject = -5LL;
594 objectCount = 5;
595 parser.ReadXRefSubsection(firstObject, objectCount);
596 FAIL("PdfError not thrown");
597 }
598 catch (PdfError& error)
599 {
600 REQUIRE((error.GetCode() == PdfErrorCode::ValueOutOfRange || error.GetCode() == PdfErrorCode::NoXRef));
601 }
602 catch (exception&)
603 {
604 FAIL("Wrong exception type");
605 }
606
607 // CVE-2015-8981 can also happen due to integer overflow in firstObject+objectCount
608 // in the example below 2147483647=0x7FFF, so 0x7FFF + 0x7FFF = 0XFFFE = -2 on a 32-bit system
609 // which means m_offsets.size()=5 because m_offsets.resize() is never called and
610 // m_offsets[2147483647].bParsed is set to true when first entry is read
611 // NOTE: vector operator[] is not bounds checked
612
613 // 2147483647 2147483647
614 // 0000000000 65535 f
615 // 0000000018 00000 n
616 // 0000000077 00000 n
617 // 0000000178 00000 n
618 // 0000000457 00000 n
619 // trailer
620 // << /Root 1 0 R
621 // /Size 5
622 //>>
623 // startxref
624 // 565
625 // %%EOF
626
627 try
628 {
629 string strInput = "0000000000 65535 f\r\n";
630 PdfIndirectObjectList objects;
631 PdfParserTest parser(objects, strInput);
632 firstObject = numeric_limits<unsigned>::max();
633 objectCount = numeric_limits<unsigned>::max();
634 parser.ReadXRefSubsection(firstObject, objectCount);
635 FAIL("PdfError not thrown");
636 }
637 catch (PdfError& error)
638 {
639 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
640 }
641 catch (exception&)
642 {
643 FAIL("Wrong exception type");
644 }
645
646 try
647 {
648 string strInput = "0000000000 65535 f\r\n";
649 PdfIndirectObjectList objects;
650 PdfParserTest parser(objects, strInput);
651 firstObject = numeric_limits<int64_t>::max();
652 objectCount = numeric_limits<int64_t>::max();
653 parser.ReadXRefSubsection(firstObject, objectCount);
654 FAIL("PdfError not thrown");
655 }
656 catch (PdfError& error)
657 {
658 REQUIRE(error.GetCode() == PdfErrorCode::ValueOutOfRange);
659 }
660 catch (exception&)
661 {
662 FAIL("Wrong exception type");
663 }
664
665 // test for integer overflows in ReadXRefSubsection (CVE-2017-5853) which caused
666 // wrong buffer size to be calculated and then triggered buffer overflow (CVE-2017-6844)
667 // the overflow checks in ReadXRefSubsection depend on the value returned by GetMaxObjectCount
668 // if the value changes these checks need looked at again
669 REQUIRE(PdfParser::GetMaxObjectCount() <= numeric_limits<unsigned>::max());
670
671 // test CVE-2017-5853 signed integer overflow in firstObject + objectCount
672 // CVE-2017-5853 1.1 - firstObject < 0
673 try
674 {
675 string strInput = " ";
676 PdfIndirectObjectList objects;
677 PdfParserTest parser(objects, strInput);
678 firstObject = -1LL;
679 objectCount = 1;
680 parser.ReadXRefSubsection(firstObject, objectCount);
681 FAIL("PdfError not thrown");
682 }
683 catch (PdfError& error)
684 {
685 REQUIRE(error.GetCode() == PdfErrorCode::ValueOutOfRange);
686 }
687 catch (exception&)
688 {
689 FAIL("Wrong exception type");
690 }
691
692 // CVE-2017-5853 1.2 - firstObject = min value of unsigned
693 try
694 {
695 string strInput = " ";
696 PdfIndirectObjectList objects;
697 PdfParserTest parser(objects, strInput);
698 firstObject = numeric_limits<unsigned>::min();
699 objectCount = 1;
700 parser.ReadXRefSubsection(firstObject, objectCount);
701 FAIL("PdfError not thrown");
702 }
703 catch (PdfError& error)
704 {
705 REQUIRE(error.GetCode() == PdfErrorCode::UnexpectedEOF);
706 }
707 catch (exception&)
708 {
709 FAIL("Wrong exception type");
710 }
711
712 // CVE-2017-5853 1.3 - firstObject = min value of int64_t
713 try
714 {
715 string strInput = " ";
716 PdfIndirectObjectList objects;
717 PdfParserTest parser(objects, strInput);
718 firstObject = numeric_limits<int64_t>::min();
719 objectCount = 1;
720 parser.ReadXRefSubsection(firstObject, objectCount);
721 FAIL("PdfError not thrown");
722 }
723 catch (PdfError& error)
724 {
725 REQUIRE(error.GetCode() == PdfErrorCode::ValueOutOfRange);
726 }
727 catch (exception&)
728 {
729 FAIL("Wrong exception type");
730 }
731
732 // CVE-2017-5853 1.4 - firstObject = min value of size_t is zero (size_t is unsigned)
733 // and zero is a valid value for firstObject
734
735 // CVE-2017-5853 1.5 - firstObject = max value of unsigned
736 try
737 {
738 string strInput = " ";
739 PdfIndirectObjectList objects;
740 PdfParserTest parser(objects, strInput);
741 firstObject = numeric_limits<unsigned>::max();
742 objectCount = 1;
743 parser.ReadXRefSubsection(firstObject, objectCount);
744 FAIL("PdfError not thrown");
745 }
746 catch (PdfError& error)
747 {
748 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
749 }
750 catch (exception&)
751 {
752 FAIL("Wrong exception type");
753 }
754
755 // CVE-2017-5853 1.6 - firstObject = max value of int64_t
756 try
757 {
758 string strInput = " ";
759 PdfIndirectObjectList objects;
760 PdfParserTest parser(objects, strInput);
761 firstObject = numeric_limits<int64_t>::max();
762 objectCount = 1;
763 parser.ReadXRefSubsection(firstObject, objectCount);
764 FAIL("PdfError not thrown");
765 }
766 catch (PdfError& error)
767 {
768 REQUIRE(error.GetCode() == PdfErrorCode::ValueOutOfRange);
769 }
770 catch (exception&)
771 {
772 FAIL("Wrong exception type");
773 }
774
775 // CVE-2017-5853 1.7 - firstObject = max value of size_t
776 try
777 {
778 string strInput = " ";
779 PdfIndirectObjectList objects;
780 PdfParserTest parser(objects, strInput);
781 firstObject = numeric_limits<size_t>::max();
782 objectCount = 1;
783 parser.ReadXRefSubsection(firstObject, objectCount);
784 FAIL("PdfError not thrown");
785 }
786 catch (PdfError& error)
787 {
788 // weird: different errors returned depending on architecture
789 REQUIRE((error.GetCode() == PdfErrorCode::ValueOutOfRange || sizeof(size_t) == 4));
790 REQUIRE((error.GetCode() == PdfErrorCode::InvalidXRef || sizeof(size_t) == 8));
791 }
792 catch (exception&)
793 {
794 FAIL("Wrong exception type");
795 }
796
797 // CVE-2017-5853 1.8 - firstObject = PdfParser::GetMaxObjectCount()
798 try
799 {
800 string strInput = " ";
801 PdfIndirectObjectList objects;
802 PdfParserTest parser(objects, strInput);
803 REQUIRE(PdfParser::GetMaxObjectCount() > 0);
804 firstObject = PdfParser::GetMaxObjectCount();
805 objectCount = 1;
806 parser.ReadXRefSubsection(firstObject, objectCount);
807 FAIL("PdfError not thrown");
808 }
809 catch (PdfError& error)
810 {
811 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
812 }
813 catch (exception&)
814 {
815 FAIL("Wrong exception type");
816 }
817
818 // CVE-2017-5853 2.1 - objectCount < 0
819 try
820 {
821 string strInput = " ";
822 PdfIndirectObjectList objects;
823 PdfParserTest parser(objects, strInput);
824 firstObject = 1;
825 objectCount = -1LL;
826 parser.ReadXRefSubsection(firstObject, objectCount);
827 FAIL("PdfError not thrown");
828 }
829 catch (PdfError& error)
830 {
831 REQUIRE(error.GetCode() == PdfErrorCode::ValueOutOfRange);
832 }
833 catch (exception&)
834 {
835 FAIL("Wrong exception type");
836 }
837
838 // CVE-2017-5853 2.2 - objectCount = min value of int
839 try
840 {
841 string strInput = " ";
842 PdfIndirectObjectList objects;
843 PdfParserTest parser(objects, strInput);
844 firstObject = 1;
845 objectCount = numeric_limits<int>::min();
846 parser.ReadXRefSubsection(firstObject, objectCount);
847 FAIL("PdfError not thrown");
848 }
849 catch (PdfError& error)
850 {
851 REQUIRE(error.GetCode() == PdfErrorCode::ValueOutOfRange);
852 }
853 catch (exception&)
854 {
855 FAIL("Wrong exception type");
856 }
857
858 // CVE-2017-5853 2.3 - objectCount = min value of int64_t
859 try
860 {
861 string strInput = " ";
862 PdfIndirectObjectList objects;
863 PdfParserTest parser(objects, strInput);
864 firstObject = 1;
865 objectCount = numeric_limits<int64_t>::min();
866 parser.ReadXRefSubsection(firstObject, objectCount);
867 FAIL("PdfError not thrown");
868 }
869 catch (PdfError& error)
870 {
871 REQUIRE(error.GetCode() == PdfErrorCode::ValueOutOfRange);
872 }
873 catch (exception&)
874 {
875 FAIL("Wrong exception type");
876 }
877
878 // CVE-2017-5853 2.4 - objectCount = min value of size_t is zero (size_t is unsigned)
879 // and zero is a valid value for firstObject
880 // TODO
881
882 // CVE-2017-5853 2.5 - objectCount = max value of unsigned
883 try
884 {
885 string strInput = " ";
886 PdfIndirectObjectList objects;
887 PdfParserTest parser(objects, strInput);
888 firstObject = 1;
889 objectCount = numeric_limits<unsigned>::max();
890 parser.ReadXRefSubsection(firstObject, objectCount);
891 FAIL("PdfError not thrown");
892 }
893 catch (PdfError& error)
894 {
895 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
896 }
897 catch (exception&)
898 {
899 FAIL("Wrong exception type");
900 }
901
902 // CVE-2017-5853 2.6 - objectCount = max value of int64_t
903 try
904 {
905 string strInput = " ";
906 PdfIndirectObjectList objects;
907 PdfParserTest parser(objects, strInput);
908 firstObject = 1;
909 objectCount = numeric_limits<int64_t>::max();
910 parser.ReadXRefSubsection(firstObject, objectCount);
911 FAIL("PdfError not thrown");
912 }
913 catch (PdfError& error)
914 {
915 REQUIRE(error.GetCode() == PdfErrorCode::ValueOutOfRange);
916 }
917 catch (exception&)
918 {
919 FAIL("Wrong exception type");
920 }
921
922 // CVE-2017-5853 2.7 - objectCount = max value of size_t
923 try
924 {
925 string strInput = " ";
926 PdfIndirectObjectList objects;
927 PdfParserTest parser(objects, strInput);
928 firstObject = 1;
929 objectCount = numeric_limits<size_t>::max();
930 parser.ReadXRefSubsection(firstObject, objectCount);
931 FAIL("PdfError not thrown");
932 }
933 catch (PdfError& error)
934 {
935 // weird: different errors returned depending on architecture
936 REQUIRE((error.GetCode() == PdfErrorCode::ValueOutOfRange || sizeof(size_t) == 4));
937 REQUIRE((error.GetCode() == PdfErrorCode::InvalidXRef || sizeof(size_t) == 8));
938 }
939 catch (exception&)
940 {
941 FAIL("Wrong exception type");
942 }
943
944 // CVE-2017-5853 2.8 - objectCount = PdfParser::GetMaxObjectCount()
945 try
946 {
947 string strInput = " ";
948 PdfIndirectObjectList objects;
949 PdfParserTest parser(objects, strInput);
950 firstObject = 1;
951 objectCount = PdfParser::GetMaxObjectCount();
952 parser.ReadXRefSubsection(firstObject, objectCount);
953 FAIL("PdfError not thrown");
954 }
955 catch (PdfError& error)
956 {
957 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
958 }
959 catch (exception&)
960 {
961 FAIL("Wrong exception type");
962 }
963
964 // CVE-2017-5853 2.9 - finally - loop through a set of interesting bit patterns
965 static uint64_t s_values[] =
966 {
967 //(1ull << 64) - 1,
968 //(1ull << 64),
969 //(1ull << 64) + 1,
970 (1ull << 63) - 1,
971 (1ull << 63),
972 (1ull << 63) + 1,
973 (1ull << 62) - 1,
974 (1ull << 62),
975 (1ull << 62) + 1,
976
977 (1ull << 49) - 1,
978 (1ull << 49),
979 (1ull << 49) + 1,
980 (1ull << 48) - 1,
981 (1ull << 48),
982 (1ull << 48) + 1,
983 (1ull << 47) - 1,
984 (1ull << 47),
985 (1ull << 47) + 1,
986
987 (1ull << 33) - 1,
988 (1ull << 33),
989 (1ull << 33) + 1,
990 (1ull << 32) - 1,
991 (1ull << 32),
992 (1ull << 32) + 1,
993 (1ull << 31) - 1,
994 (1ull << 31),
995 (1ull << 31) + 1,
996
997 (1ull << 25) - 1,
998 (1ull << 33),
999 (1ull << 33) + 1,
1000 (1ull << 24) - 1,
1001 (1ull << 24),
1002 (1ull << 24) + 1,
1003 (1ull << 31) - 1,
1004 (1ull << 31),
1005 (1ull << 31) + 1,
1006
1007 (1ull << 17) - 1,
1008 (1ull << 17),
1009 (1ull << 17) + 1,
1010 (1ull << 16) - 1,
1011 (1ull << 16),
1012 (1ull << 16) + 1,
1013 (1ull << 15) - 1,
1014 (1ull << 15),
1015 (1ull << 15) + 1,
1016
1017 (uint64_t)-1,
1018 0,
1019 1
1020 };
1021 constexpr size_t numValues = sizeof(s_values) / sizeof(s_values[0]);
1022
1023 for (size_t i = 0; i < numValues; i++)
1024 {
1025 for (size_t j = 0; j < numValues; j++)
1026 {
1027 try
1028 {
1029 string strInput = " ";
1030 PdfIndirectObjectList objects;
1031 PdfParserTest parser(objects, strInput);
1032 firstObject = s_values[i];
1033 objectCount = s_values[j];
1034
1035 if (canOutOfMemoryKillUnitTests() && (firstObject > maxNumberOfIndirectObjects || objectCount > maxNumberOfIndirectObjects))
1036 {
1037 // can't call this in test environments where an out-of-memory condition terminates
1038 // unit test process before all tests have run (e.g. AddressSanitizer)
1039 }
1040 else
1041 {
1042 parser.ReadXRefSubsection(firstObject, objectCount);
1043 // some combinations of firstObject/objectCount from s_values are legal - so we expect to reach here sometimes
1044 }
1045 }
1046 catch (PdfError& error)
1047 {
1048 // other combinations of firstObject/objectCount from s_values are illegal
1049 // if we reach here it should be an invalid xref value of some type
1050 REQUIRE((error.GetCode() == PdfErrorCode::InvalidXRef || error.GetCode() == PdfErrorCode::ValueOutOfRange
1051 || error.GetCode() == PdfErrorCode::UnexpectedEOF
1052 || error.GetCode() == PdfErrorCode::OutOfMemory));
1053 }
1054 catch (exception&)
1055 {
1056 // and should never reach here
1057 FAIL("Wrong exception type");
1058 }
1059 }
1060 }
1061 }
1062
1063 TEST_CASE("TestReadXRefStreamContents")
1064 {
1065 // test valid stream
1066 try
1067 {
1068 // generate an XRef stream with valid /W values
1069 ostringstream oss;
1070 size_t offsetStream;
1071 size_t offsetEndstream;
1072
1073 // XRef stream with 5 entries
1074 size_t lengthXRefObject = 58;
1075 size_t offsetXRefObject = oss.str().length();
1076 oss << "2 0 obj ";
1077 oss << "<< /Type /XRef ";
1078 oss << "/Length " << lengthXRefObject << " ";
1079 oss << "/Index [2 2] ";
1080 oss << "/Size 5 ";
1081 oss << "/W [1 2 1] ";
1082 oss << "/Filter /ASCIIHexDecode ";
1083 oss << ">>\r\n";
1084 oss << "stream\r\n";
1085 offsetStream = oss.str().length();
1086 oss << "01 0E8A 00\r\n";
1087 oss << "02 0002 00\r\n";
1088 oss << "02 0002 01\r\n";
1089 oss << "02 0002 02\r\n";
1090 oss << "02 0002 03\r\n";
1091 offsetEndstream = oss.str().length();
1092 oss << "endstream\r\n";
1093 oss << "endobj\r\n";
1094 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1095
1096 // trailer
1097 oss << "startxref " << offsetXRefObject << "\r\n";
1098 oss << "%%EOF";
1099
1100 PdfIndirectObjectList objects;
1101 PdfParserTest parser(objects, oss.str());
1102 parser.ReadXRefStreamContents(offsetXRefObject, false);
1103 // should succeed
1104 }
1105 catch (PdfError&)
1106 {
1107 FAIL("Unexpected PdfError");
1108 }
1109 catch (exception&)
1110 {
1111 FAIL("Unexpected exception type");
1112 }
1113
1114 // CVE-2018-5295: integer overflow caused by checking sum of /W entry values /W [ 1 2 9223372036854775807 ]
1115 // see https://bugzilla.redhat.com/show_bug.cgi?id=1531897 (/W values used were extracted from PoC file)
1116 try
1117 {
1118 ostringstream oss;
1119 size_t offsetStream;
1120 size_t offsetEndstream;
1121
1122 // XRef stream
1123 size_t lengthXRefObject = 58;
1124 size_t offsetXRefObject = 10;
1125 oss << "%PDF-1.4\r\n";
1126 oss << "2 0 obj ";
1127 oss << "<< /Type /XRef ";
1128 oss << "/Length " << lengthXRefObject << " ";
1129 oss << "/Index [2 2] ";
1130 oss << "/Size 5 ";
1131 oss << "/W [ 1 2 9223372036854775807 ] ";
1132 oss << "/Filter /ASCIIHexDecode ";
1133 oss << ">>\r\n";
1134 oss << "stream\r\n";
1135 offsetStream = oss.str().length();
1136 oss << "01 0E8A 00\r\n";
1137 oss << "02 0002 00\r\n";
1138 oss << "02 0002 01\r\n";
1139 oss << "02 0002 02\r\n";
1140 oss << "02 0002 03\r\n";
1141 offsetEndstream = oss.str().length();
1142 oss << "endstream\r\n";
1143 oss << "endobj\r\n";
1144 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // check /Length entry in XRef stream above
1145
1146 // trailer
1147 oss << "startxref " << offsetXRefObject << "\r\n";
1148 oss << "%%EOF";
1149
1150 auto inputStr = oss.str();
1151 PdfXRefEntries offsets;
1152 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1153 PdfMemDocument doc;
1154 // Parse a doc using XRef stream with invalid /W entries
1155 doc.LoadFromDevice(device);
1156 FAIL("Should throw exception");
1157 }
1158 catch (PdfError& error)
1159 {
1160 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefStream);
1161 }
1162 catch (exception&)
1163 {
1164 FAIL("Unexpected exception type");
1165 }
1166
1167 // CVE-2017-8787: heap based overflow caused by unchecked /W entry values /W [ 1 -4 2 ]
1168 // see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=861738 for value of /W array
1169 try
1170 {
1171 ostringstream oss;
1172 size_t offsetStream;
1173 size_t offsetEndstream;
1174
1175 // XRef stream
1176 size_t lengthXRefObject = 58;
1177 size_t offsetXRefObject = 10;
1178 oss << "%PDF-1.4\r\n";
1179 oss << "2 0 obj ";
1180 oss << "<< /Type /XRef ";
1181 oss << "/Length " << lengthXRefObject << " ";
1182 oss << "/Index [2 2] ";
1183 oss << "/Size 5 ";
1184 oss << "/W [ 1 -4 2 ] ";
1185 oss << "/Filter /ASCIIHexDecode ";
1186 oss << ">>\r\n";
1187 oss << "stream\r\n";
1188 offsetStream = oss.str().length();
1189 oss << "01 0E8A 00\r\n";
1190 oss << "02 0002 00\r\n";
1191 oss << "02 0002 01\r\n";
1192 oss << "02 0002 02\r\n";
1193 oss << "02 0002 03\r\n";
1194 offsetEndstream = oss.str().length();
1195 oss << "endstream\r\n";
1196 oss << "endobj\r\n";
1197 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // check /Length entry in XRef stream above
1198
1199 // trailer
1200 oss << "startxref " << offsetXRefObject << "\r\n";
1201 oss << "%%EOF";
1202
1203 auto inputStr = oss.str();
1204 PdfXRefEntries offsets;
1205 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1206 PdfMemDocument doc;
1207 // Parse a doc using XRef stream with invalid /W entries
1208 doc.LoadFromDevice(device);
1209 FAIL("Should throw exception");
1210 }
1211 catch (PdfError& error)
1212 {
1213 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefStream);
1214 }
1215 catch (exception&)
1216 {
1217 FAIL("Unexpected exception type");
1218 }
1219
1220 // /W entry values /W [ 4095 1 1 ] for data in form 02 0002 00 (doesn't match size of entry)
1221 try
1222 {
1223 ostringstream oss;
1224 size_t offsetStream;
1225 size_t offsetEndstream;
1226
1227 // XRef stream
1228 size_t lengthXRefObject = 58;
1229 size_t offsetXRefObject = 10;
1230 oss << "%PDF-1.4\r\n";
1231 oss << "2 0 obj ";
1232 oss << "<< /Type /XRef ";
1233 oss << "/Length " << lengthXRefObject << " ";
1234 oss << "/Index [2 2] ";
1235 oss << "/Size 5 ";
1236 oss << "/W [ 4095 1 1 ] ";
1237 oss << "/Filter /ASCIIHexDecode ";
1238 oss << ">>\r\n";
1239 oss << "stream\r\n";
1240 offsetStream = oss.str().length();
1241 oss << "01 0E8A 00\r\n";
1242 oss << "02 0002 00\r\n";
1243 oss << "02 0002 01\r\n";
1244 oss << "02 0002 02\r\n";
1245 oss << "02 0002 03\r\n";
1246 offsetEndstream = oss.str().length();
1247 oss << "endstream\r\n";
1248 oss << "endobj\r\n";
1249 REQUIRE((offsetEndstream - offsetStream - strlen("\r\n")) == lengthXRefObject); // check /Length entry in XRef stream above
1250
1251 // trailer
1252 oss << "startxref " << offsetXRefObject << "\r\n";
1253 oss << "%%EOF";
1254
1255 auto inputStr = oss.str();
1256 PdfXRefEntries offsets;
1257 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1258 PdfMemDocument doc;
1259 // Parse a doc using XRef stream with invalid /W entries
1260 doc.LoadFromDevice(device);
1261 FAIL("Should throw exception");
1262 }
1263 catch (PdfError& error)
1264 {
1265 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefStream);
1266 }
1267 catch (exception&)
1268 {
1269 FAIL("Unexpected exception type");
1270 }
1271
1272 // /W entry values /W [ 4 4 4 ] for data in form 02 0002 00 (doesn't match size of entry)
1273 try
1274 {
1275 ostringstream oss;
1276 size_t offsetStream;
1277 size_t offsetEndstream;
1278
1279 // XRef stream
1280 size_t lengthXRefObject = 58;
1281 size_t offsetXRefObject = 10;
1282 oss << "%PDF-1.4\r\n";
1283 oss << "2 0 obj ";
1284 oss << "<< /Type /XRef ";
1285 oss << "/Length " << lengthXRefObject << " ";
1286 oss << "/Index [2 2] ";
1287 oss << "/Size 5 ";
1288 oss << "/W [ 4 4 4 ] ";
1289 oss << "/Filter /ASCIIHexDecode ";
1290 oss << ">>\r\n";
1291 oss << "stream\r\n";
1292 offsetStream = oss.str().length();
1293 oss << "01 0E8A 00\r\n";
1294 oss << "02 0002 00\r\n";
1295 oss << "02 0002 01\r\n";
1296 oss << "02 0002 02\r\n";
1297 oss << "02 0002 03\r\n";
1298 offsetEndstream = oss.str().length();
1299 oss << "endstream\r\n";
1300 oss << "endobj\r\n";
1301 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // check /Length entry in XRef stream above
1302
1303 // trailer
1304 oss << "startxref " << offsetXRefObject << "\r\n";
1305 oss << "%%EOF";
1306
1307 auto inputStr = oss.str();
1308 PdfXRefEntries offsets;
1309 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1310 PdfMemDocument doc;
1311 // Parse a doc using XRef stream with invalid /W entries
1312 doc.LoadFromDevice(device);
1313 FAIL("Should throw exception");
1314 }
1315 catch (PdfError& error)
1316 {
1317 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefStream);
1318 }
1319 catch (exception&)
1320 {
1321 FAIL("Unexpected exception type");
1322 }
1323
1324 // /W entry values /W [ 1 4 4 ] (size=9) for data 01 0E8A 0\r\n02 0002 00\r\n (size=8 bytes)
1325 try
1326 {
1327 ostringstream oss;
1328 size_t offsetStream;
1329 size_t offsetEndstream;
1330
1331 // XRef stream
1332 size_t lengthXRefObject = 22;
1333 size_t offsetXRefObject = 10;
1334 oss << "%PDF-1.4\r\n";
1335 oss << "2 0 obj ";
1336 oss << "<< /Type /XRef ";
1337 oss << "/Length " << lengthXRefObject << " ";
1338 oss << "/Index [2 2] ";
1339 oss << "/Size 2 ";
1340 oss << "/W [ 1 4 4 ] ";
1341 oss << "/Filter /ASCIIHexDecode ";
1342 oss << ">>\r\n";
1343 oss << "stream\r\n";
1344 offsetStream = oss.str().length();
1345 oss << "01 0E8A 00\r\n";
1346 oss << "02 0002 00\r\n";
1347 offsetEndstream = oss.str().length();
1348 oss << "endstream\r\n";
1349 oss << "endobj\r\n";
1350 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // check /Length entry in XRef stream above
1351
1352 // trailer
1353 oss << "startxref " << offsetXRefObject << "\r\n";
1354 oss << "%%EOF";
1355
1356 auto inputStr = oss.str();
1357 PdfXRefEntries offsets;
1358 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1359 PdfMemDocument doc;
1360 // Parse a doc using XRef stream with invalid /W entries
1361 doc.LoadFromDevice(device);
1362 FAIL("Should throw exception");
1363 }
1364 catch (PdfError& error)
1365 {
1366 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefStream);
1367 }
1368 catch (exception&)
1369 {
1370 FAIL("Unexpected exception type");
1371 }
1372
1373 try
1374 {
1375 ostringstream oss;
1376 size_t offsetStream;
1377 size_t offsetEndstream;
1378
1379 size_t lengthXRefObject = 22;
1380 size_t offsetXRefObject = 34;
1381 oss << "%PDF-1.4\r\n";
1382 oss << "1 0 obj\r\n";
1383 oss << "<< >>\r\n";
1384 oss << "endobj\r\n";
1385 oss << "2 0 obj\r\n";
1386 oss << "<< /Type /XRef ";
1387 oss << "/Length " << lengthXRefObject << " ";
1388 oss << "/Index [1 2] ";
1389 oss << "/Root 1 0 R ";
1390 oss << "/Size 3 ";
1391 oss << "/W [1 2 1] ";
1392 oss << "/Filter /ASCIIHexDecode ";
1393 oss << ">>\r\n";
1394 oss << "stream\r\n";
1395 offsetStream = oss.str().length();
1396 oss << "01 000A 00\r\n";
1397 oss << "01 001A 00\r\n";
1398 offsetEndstream = oss.str().length();
1399 oss << "endstream\r\n";
1400 oss << "endobj\r\n";
1401 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1402
1403 // trailer
1404 oss << "startxref " << offsetXRefObject << "\r\n";
1405 oss << "%%EOF";
1406
1407 auto inputStr = oss.str();
1408 PdfXRefEntries offsets;
1409 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1410 PdfMemDocument doc;
1411 doc.LoadFromDevice(device);
1412 }
1413 catch (PdfError&)
1414 {
1415 FAIL("Unexpected PdfError");
1416 }
1417 catch (exception&)
1418 {
1419 FAIL("Unexpected exception type");
1420 }
1421
1422 // XRef stream with 5 entries but /Size 2 specified
1423 try
1424 {
1425 ostringstream oss;
1426 size_t offsetStream;
1427 size_t offsetEndstream;
1428
1429 size_t lengthXRefObject = 58;
1430 size_t offsetXRefObject = 10;
1431 oss << "%PDF-1.4\r\n";
1432 oss << "2 0 obj ";
1433 oss << "<< /Type /XRef ";
1434 oss << "/Length " << lengthXRefObject << " ";
1435 oss << "/Index [2 2] ";
1436 oss << "/Size 10 ";
1437 oss << "/W [1 2 1] ";
1438 oss << "/Filter /ASCIIHexDecode ";
1439 oss << ">>\r\n";
1440 oss << "stream\r\n";
1441 offsetStream = oss.str().length();
1442 oss << "01 0E8A 00\r\n";
1443 oss << "01 0002 00\r\n";
1444 oss << "01 0002 01\r\n";
1445 oss << "01 0002 02\r\n";
1446 oss << "01 0002 03\r\n";
1447 offsetEndstream = oss.str().length();
1448 oss << "endstream\r\n";
1449 oss << "endobj\r\n";
1450 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1451
1452 // trailer
1453 oss << "startxref " << offsetXRefObject << "\r\n";
1454 oss << "%%EOF";
1455
1456 auto inputStr = oss.str();
1457 PdfXRefEntries offsets;
1458 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1459 PdfMemDocument doc;
1460 doc.LoadFromDevice(device);
1461 FAIL("Should throw exception");
1462 }
1463 catch (PdfError& error)
1464 {
1465 (void)error;
1466 // FIXME We should throw on exact error
1467 //REQUIRE(error.GetError() == PdfErrorCode::NoXRef);
1468 }
1469 catch (exception&)
1470 {
1471 FAIL("Unexpected exception type");
1472 }
1473
1474 // XRef stream with 5 entries but /Size 10 specified
1475 try
1476 {
1477 ostringstream oss;
1478 size_t offsetStream;
1479 size_t offsetEndstream;
1480
1481 size_t lengthXRefObject = 58;
1482 size_t offsetXRefObject = 10;
1483 oss << "%PDF-1.4\r\n";
1484 oss << "2 0 obj ";
1485 oss << "<< /Type /XRef ";
1486 oss << "/Length " << lengthXRefObject << " ";
1487 oss << "/Index [2 2] ";
1488 oss << "/Size 10 ";
1489 oss << "/W [1 2 1] ";
1490 oss << "/Filter /ASCIIHexDecode ";
1491 oss << ">>\r\n";
1492 oss << "stream\r\n";
1493 offsetStream = oss.str().length();
1494 oss << "01 0E8A 00\r\n";
1495 oss << "01 0002 00\r\n";
1496 oss << "01 0002 01\r\n";
1497 oss << "01 0002 02\r\n";
1498 oss << "01 0002 03\r\n";
1499 offsetEndstream = oss.str().length();
1500 oss << "endstream\r\n";
1501 oss << "endobj\r\n";
1502 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1503
1504 // trailer
1505 oss << "startxref " << offsetXRefObject << "\r\n";
1506 oss << "%%EOF";
1507
1508 auto inputStr = oss.str();
1509 PdfXRefEntries offsets;
1510 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1511 PdfMemDocument doc;
1512 doc.LoadFromDevice(device);
1513 FAIL("Should throw exception");
1514 }
1515 catch (PdfError& error)
1516 {
1517 (void)error;
1518 // FIXME We should throw on exact error
1519 //REQUIRE(error.GetError() == PdfErrorCode::NoXRef);
1520 }
1521 catch (exception&)
1522 {
1523 FAIL("Unexpected exception type");
1524 }
1525
1526 // XRef stream with /Index [0 0] array
1527 try
1528 {
1529 ostringstream oss;
1530 size_t offsetStream;
1531 size_t offsetEndstream;
1532
1533 size_t lengthXRefObject = 58;
1534 size_t offsetXRefObject = 10;
1535 oss << "%PDF-1.4\r\n";
1536 oss << "2 0 obj ";
1537 oss << "<< /Type /XRef ";
1538 oss << "/Length " << lengthXRefObject << " ";
1539 oss << "/Index [0 0] ";
1540 oss << "/Size 5 ";
1541 oss << "/W [1 2 1] ";
1542 oss << "/Filter /ASCIIHexDecode ";
1543 oss << ">>\r\n";
1544 oss << "stream\r\n";
1545 offsetStream = oss.str().length();
1546 oss << "01 0E8A 00\r\n";
1547 oss << "02 0002 00\r\n";
1548 oss << "02 0002 01\r\n";
1549 oss << "02 0002 02\r\n";
1550 oss << "02 0002 03\r\n";
1551 offsetEndstream = oss.str().length();
1552 oss << "endstream\r\n";
1553 oss << "endobj\r\n";
1554 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1555
1556 // trailer
1557 oss << "startxref " << offsetXRefObject << "\r\n";
1558 oss << "%%EOF";
1559
1560 auto inputStr = oss.str();
1561 PdfXRefEntries offsets;
1562 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1563 PdfMemDocument doc;
1564 doc.LoadFromDevice(device);
1565 FAIL("Should throw exception");
1566 }
1567 catch (PdfError& error)
1568 {
1569 (void)error;
1570 // FIXME We should throw on exact error
1571 //REQUIRE(error.GetError() == PdfErrorCode::NoXRef);
1572 }
1573 catch (exception&)
1574 {
1575 FAIL("Unexpected exception type");
1576 }
1577
1578 // XRef stream with /Index [-1 -1] array
1579 try
1580 {
1581 ostringstream oss;
1582 size_t offsetStream;
1583 size_t offsetEndstream;
1584
1585 size_t lengthXRefObject = 58;
1586 size_t offsetXRefObject = 10;
1587 oss << "%PDF-1.4\r\n";
1588 oss << "2 0 obj ";
1589 oss << "<< /Type /XRef ";
1590 oss << "/Length " << lengthXRefObject << " ";
1591 oss << "/Index [-1 -1] ";
1592 oss << "/Size 5 ";
1593 oss << "/W [1 2 1] ";
1594 oss << "/Filter /ASCIIHexDecode ";
1595 oss << ">>\r\n";
1596 oss << "stream\r\n";
1597 offsetStream = oss.str().length();
1598 oss << "01 0E8A 00\r\n";
1599 oss << "02 0002 00\r\n";
1600 oss << "02 0002 01\r\n";
1601 oss << "02 0002 02\r\n";
1602 oss << "02 0002 03\r\n";
1603 offsetEndstream = oss.str().length();
1604 oss << "endstream\r\n";
1605 oss << "endobj\r\n";
1606 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1607
1608 // trailer
1609 oss << "startxref " << offsetXRefObject << "\r\n";
1610 oss << "%%EOF";
1611
1612 auto inputStr = oss.str();
1613 PdfXRefEntries offsets;
1614 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1615 PdfMemDocument doc;
1616 doc.LoadFromDevice(device);
1617 FAIL("Should throw exception");
1618 }
1619 catch (PdfError& error)
1620 {
1621 (void)error;
1622 // FIXME We should throw on exact error
1623 //REQUIRE(error.GetError() == PdfErrorCode::NoXRef);
1624 }
1625 catch (exception&)
1626 {
1627 FAIL("Unexpected exception type");
1628 }
1629
1630 // XRef stream with /Index array with no entries
1631 try
1632 {
1633 ostringstream oss;
1634 size_t offsetStream;
1635 size_t offsetEndstream;
1636
1637 size_t lengthXRefObject = 58;
1638 size_t offsetXRefObject = 10;
1639 oss << "%PDF-1.4\r\n";
1640 oss << "2 0 obj ";
1641 oss << "<< /Type /XRef ";
1642 oss << "/Length " << lengthXRefObject << " ";
1643 oss << "/Index [ ] ";
1644 oss << "/Size 5 ";
1645 oss << "/W [1 2 1] ";
1646 oss << "/Filter /ASCIIHexDecode ";
1647 oss << ">>\r\n";
1648 oss << "stream\r\n";
1649 offsetStream = oss.str().length();
1650 oss << "01 0E8A 00\r\n";
1651 oss << "02 0002 00\r\n";
1652 oss << "02 0002 01\r\n";
1653 oss << "02 0002 02\r\n";
1654 oss << "02 0002 03\r\n";
1655 offsetEndstream = oss.str().length();
1656 oss << "endstream\r\n";
1657 oss << "endobj\r\n";
1658 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1659
1660 // trailer
1661 oss << "startxref " << offsetXRefObject << "\r\n";
1662 oss << "%%EOF";
1663
1664 auto inputStr = oss.str();
1665 PdfXRefEntries offsets;
1666 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1667 PdfMemDocument doc;
1668 doc.LoadFromDevice(device);
1669 FAIL("Should throw exception");
1670 }
1671 catch (PdfError& error)
1672 {
1673 (void)error;
1674 // FIXME We should throw on exact error
1675 //REQUIRE(error.GetError() == PdfErrorCode::NoXRef);
1676 }
1677 catch (exception&)
1678 {
1679 FAIL("Unexpected exception type");
1680 }
1681
1682 // XRef stream with /Index array with 3 entries
1683 try
1684 {
1685 ostringstream oss;
1686 size_t offsetStream;
1687 size_t offsetEndstream;
1688
1689 size_t lengthXRefObject = 58;
1690 size_t offsetXRefObject = 10;
1691 oss << "%PDF-1.4\r\n";
1692 oss << "2 0 obj ";
1693 oss << "<< /Type /XRef ";
1694 oss << "/Length " << lengthXRefObject << " ";
1695 oss << "/Index [2 2 2] ";
1696 oss << "/Size 5 ";
1697 oss << "/W [1 2 1] ";
1698 oss << "/Filter /ASCIIHexDecode ";
1699 oss << ">>\r\n";
1700 oss << "stream\r\n";
1701 offsetStream = oss.str().length();
1702 oss << "01 0E8A 00\r\n";
1703 oss << "02 0002 00\r\n";
1704 oss << "02 0002 01\r\n";
1705 oss << "02 0002 02\r\n";
1706 oss << "02 0002 03\r\n";
1707 offsetEndstream = oss.str().length();
1708 oss << "endstream\r\n";
1709 oss << "endobj\r\n";
1710 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1711
1712 // trailer
1713 oss << "startxref " << offsetXRefObject << "\r\n";
1714 oss << "%%EOF";
1715
1716 auto inputStr = oss.str();
1717 PdfXRefEntries offsets;
1718 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1719 PdfMemDocument doc;
1720 doc.LoadFromDevice(device);
1721 FAIL("Should throw exception");
1722 }
1723 catch (PdfError& error)
1724 {
1725 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefStream);
1726 }
1727 catch (exception&)
1728 {
1729 FAIL("Unexpected exception type");
1730 }
1731
1732 // XRef stream with /Index array with 22 entries
1733 try
1734 {
1735 ostringstream oss;
1736 size_t offsetStream;
1737 size_t offsetEndstream;
1738
1739 size_t lengthXRefObject = 58;
1740 size_t offsetXRefObject = 10;
1741 oss << "%PDF-1.4\r\n";
1742 oss << "2 0 obj ";
1743 oss << "<< /Type /XRef ";
1744 oss << "/Length " << lengthXRefObject << " ";
1745 oss << "/Index [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22] ";
1746 oss << "/Size 5 ";
1747 oss << "/W [1 2 1] ";
1748 oss << "/Filter /ASCIIHexDecode ";
1749 oss << ">>\r\n";
1750 oss << "stream\r\n";
1751 offsetStream = oss.str().length();
1752 oss << "00 0000 00\r\n";
1753 oss << "00 0000 00\r\n";
1754 oss << "00 0000 00\r\n";
1755 oss << "00 0000 00\r\n";
1756 oss << "00 0000 00\r\n";
1757 offsetEndstream = oss.str().length();
1758 oss << "endstream\r\n";
1759 oss << "endobj\r\n";
1760 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
1761
1762 // trailer
1763 oss << "startxref " << offsetXRefObject << "\r\n";
1764 oss << "%%EOF";
1765
1766 auto inputStr = oss.str();
1767 PdfXRefEntries offsets;
1768 auto device = std::make_shared<SpanStreamDevice>(inputStr);
1769 PdfMemDocument doc;
1770 doc.LoadFromDevice(device);
1771 FAIL("Should throw exception");
1772 }
1773 catch (PdfError& error)
1774 {
1775 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRefStream);
1776 }
1777 catch (exception&)
1778 {
1779 FAIL("Unexpected exception type");
1780 }
1781 }
1782
1783 TEST_CASE("testReadObjects")
1784 {
1785 // CVE-2017-8378 - m_offsets out-of-bounds access when referenced encryption dictionary object doesn't exist
1786 try
1787 {
1788 ostringstream oss;
1789 oss << "%PDF-1.0\r\n";
1790 oss << "xref\r\n0 3\r\n";
1791 oss << generateXRefEntries(3);
1792 oss << "trailer << /Root 1 0 R /Size 3 /Encrypt 3 0 R >>\r\n";
1793 oss << "startxref 0\r\n";
1794 oss << "%%EOF";
1795 PdfIndirectObjectList objects;
1796 auto docbuff = oss.str();
1797 PdfParserTest parser(objects, docbuff);
1798 parser.ReadDocumentStructure();
1799 parser.ReadObjects();
1800 FAIL("Should throw exception");
1801 }
1802 catch (PdfError& error)
1803 {
1804 REQUIRE(error.GetCode() == PdfErrorCode::InvalidEncryptionDict);
1805 }
1806 catch (exception&)
1807 {
1808 FAIL("Unexpected exception type");
1809 }
1810 }
1811
1812 TEST_CASE("testIsPdfFile")
1813 {
1814 try
1815 {
1816 string strInput = "%PDF-1.0";
1817 PdfIndirectObjectList objects;
1818 PdfParserTest parser(objects, strInput);
1819 REQUIRE(parser.IsPdfFile());
1820 }
1821 catch (PdfError&)
1822 {
1823 FAIL("Unexpected PdfError");
1824 }
1825 catch (exception&)
1826 {
1827 FAIL("Wrong exception type");
1828 }
1829
1830 try
1831 {
1832 string strInput = "%PDF-1.1";
1833 PdfIndirectObjectList objects;
1834 PdfParserTest parser(objects, strInput);
1835 REQUIRE(parser.IsPdfFile());
1836 }
1837 catch (PdfError&)
1838 {
1839 FAIL("Unexpected PdfError");
1840 }
1841 catch (exception&)
1842 {
1843 FAIL("Wrong exception type");
1844 }
1845
1846 try
1847 {
1848 string strInput = "%PDF-1.7";
1849 PdfIndirectObjectList objects;
1850 PdfParserTest parser(objects, strInput);
1851 REQUIRE(parser.IsPdfFile());
1852 }
1853 catch (PdfError&)
1854 {
1855 FAIL("Unexpected PdfError");
1856 }
1857 catch (exception&)
1858 {
1859 FAIL("Wrong exception type");
1860 }
1861
1862 try
1863 {
1864 string strInput = "%PDF-1.9";
1865 PdfIndirectObjectList objects;
1866 PdfParserTest parser(objects, strInput);
1867 REQUIRE(!parser.IsPdfFile());
1868 }
1869 catch (PdfError&)
1870 {
1871 FAIL("Unexpected PdfError");
1872 }
1873 catch (exception&)
1874 {
1875 FAIL("Wrong exception type");
1876 }
1877
1878 try
1879 {
1880 string strInput = "%PDF-2.0";
1881 PdfIndirectObjectList objects;
1882 PdfParserTest parser(objects, strInput);
1883 REQUIRE(parser.IsPdfFile());
1884 }
1885 catch (PdfError&)
1886 {
1887 FAIL("Unexpected PdfError");
1888 }
1889 catch (exception&)
1890 {
1891 FAIL("Wrong exception type");
1892 }
1893
1894 try
1895 {
1896 string strInput = "%!PS-Adobe-2.0";
1897 PdfIndirectObjectList objects;
1898 PdfParserTest parser(objects, strInput);
1899 REQUIRE(!parser.IsPdfFile());
1900 }
1901 catch (PdfError&)
1902 {
1903 FAIL("Unexpected PdfError");
1904 }
1905 catch (exception&)
1906 {
1907 FAIL("Wrong exception type");
1908 }
1909
1910 try
1911 {
1912 string strInput = "GIF89a";
1913 PdfIndirectObjectList objects;
1914 PdfParserTest parser(objects, strInput);
1915 REQUIRE(!parser.IsPdfFile());
1916 }
1917 catch (PdfError&)
1918 {
1919 FAIL("Unexpected PdfError");
1920 }
1921 catch (exception&)
1922 {
1923 FAIL("Wrong exception type");
1924 }
1925 }
1926
1927 TEST_CASE("testSaveIncrementalRoundTrip")
1928 {
1929 ostringstream oss;
1930 oss << "%PDF-1.1\n";
1931 unsigned currObj = 1;
1932 streamoff objPos[20];
1933
1934 // Pages
1935
1936 unsigned pagesObj = currObj;
1937 objPos[currObj] = oss.tellp();
1938 oss << currObj++ << " 0 obj\n";
1939 oss << "<</Type /Pages /Count 0 /Kids []>>\n";
1940 oss << "endobj\n";
1941
1942 // Root catalog
1943
1944 unsigned rootObj = currObj;
1945 objPos[currObj] = oss.tellp();
1946 oss << currObj++ << " 0 obj\n";
1947 oss << "<</Type /Catalog /Pages " << pagesObj << " 0 R>>\n";
1948 oss << "endobj\n";
1949
1950 // ID
1951 unsigned idObj = currObj;
1952 objPos[currObj] = oss.tellp();
1953 oss << currObj++ << " 0 obj\n";
1954 oss << "[<F1E375363A6314E3766EDF396D614748> <F1E375363A6314E3766EDF396D614748>]\n";
1955 oss << "endobj\n";
1956
1957 streamoff xrefPos = oss.tellp();
1958 oss << "xref\n";
1959 oss << "0 " << currObj << "\n";
1960 oss << "0000000000 65535 f \n";
1961 for (unsigned i = 1; i < currObj; i++)
1962 oss << utls::Format("{:010d} 00000 n \n", objPos[i]);
1963
1964 oss << "trailer <<\n"
1965 << " /Size " << currObj << "\n"
1966 << " /Root " << rootObj << " 0 R\n"
1967 << " /ID " << idObj << " 0 R\n" // indirect ID
1968 << ">>\n"
1969 << "startxref\n"
1970 << xrefPos << "\n"
1971 << "%%EOF\n";
1972
1973 string docBuff = oss.str();
1974 try
1975 {
1976 PdfMemDocument doc;
1977 // load for update
1978 doc.LoadFromBuffer(docBuff);
1979
1980 StringStreamDevice outDev(docBuff);
1981
1982 doc.SaveUpdate(outDev);
1983 doc.LoadFromBuffer(docBuff);
1984 }
1985 catch (PdfError&)
1986 {
1987 FAIL("Unexpected PdfError");
1988 }
1989 }
1990
1991 // CVE-2018-8002, CVE-2021-30470
1992 TEST_CASE("testNestedArrays")
1993 {
1994 // test valid stream
1995 // generate an XRef stream with no deeply nested arrays
1996 ostringstream oss;
1997 size_t offsetStream;
1998 size_t offsetEndstream;
1999 size_t offsetXRefObject;
2000 string buffer;
2001
2002 // XRef stream with 5 entries
2003 constexpr size_t lengthXRefObject = 58;
2004
2005 offsetXRefObject = oss.str().length();
2006 oss << "2 0 obj ";
2007 oss << "<< /Type /XRef ";
2008 oss << "/Length " << lengthXRefObject << " ";
2009 oss << "/Index [2 2] ";
2010 oss << "/Size 5 ";
2011 oss << "/W [1 2 1] ";
2012 oss << "/Filter /ASCIIHexDecode ";
2013 oss << ">>\r\n";
2014 oss << "stream\r\n";
2015 offsetStream = oss.str().length();
2016 oss << "01 0E8A 00\r\n";
2017 oss << "02 0002 00\r\n";
2018 oss << "02 0002 01\r\n";
2019 oss << "02 0002 02\r\n";
2020 oss << "02 0002 03\r\n";
2021 offsetEndstream = oss.str().length();
2022 oss << "endstream\r\n";
2023 oss << "endobj\r\n";
2024 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
2025
2026 // trailer
2027 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
2028 oss << "startxref " << offsetXRefObject << "\r\n";
2029 oss << "%EOF";
2030
2031 buffer = oss.str();
2032
2033 {
2034 PdfIndirectObjectList objects;
2035 PdfParserTest parser(objects, buffer);
2036 parser.ReadXRefStreamContents(offsetXRefObject, false);
2037 REQUIRE(true);
2038 }
2039
2040 // CVE-2021-30470 - lots of [[[[[]]]]] brackets represent nested arrays which caused stack overflow
2041 try
2042 {
2043 // generate an XRef stream with deeply nested arrays
2044 oss.str("");
2045 const size_t maxNesting = getStackOverflowDepth(); // big enough to cause stack overflow
2046 // XRef stream with 5 entries
2047 offsetXRefObject = oss.str().length();
2048 oss << "2 0 obj ";
2049 oss << "<< /Type /XRef ";
2050 oss << "/Length " << lengthXRefObject << " ";
2051 oss << "/Index [2 2] ";
2052 oss << "/Size 5 ";
2053 oss << "/W [1 2 1] ";
2054
2055 // output [[[[[[[[[[[0]]]]]]]]]]]
2056 for (size_t i = 0; i < maxNesting; i++)
2057 {
2058 oss << "[";
2059 }
2060 oss << "0";
2061 for (size_t i = 0; i < maxNesting; i++)
2062 {
2063 oss << "]";
2064 }
2065 oss << " ";
2066
2067 oss << "/Filter /ASCIIHexDecode ";
2068 oss << ">>\r\n";
2069 oss << "stream\r\n";
2070 offsetStream = oss.str().length();
2071 oss << "01 0E8A 00\r\n";
2072 oss << "02 0002 00\r\n";
2073 oss << "02 0002 01\r\n";
2074 oss << "02 0002 02\r\n";
2075 oss << "02 0002 03\r\n";
2076 offsetEndstream = oss.str().length();
2077 oss << "endstream\r\n";
2078 oss << "endobj\r\n";
2079 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
2080
2081 // trailer
2082 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
2083 oss << "startxref " << offsetXRefObject << "\r\n";
2084 oss << "%EOF";
2085
2086 buffer = oss.str();
2087
2088 PdfIndirectObjectList objects;
2089 PdfParserTest parser(objects, buffer);
2090 parser.ReadXRefStreamContents(offsetXRefObject, false);
2091 FAIL("Should throw exception");
2092 }
2093 catch (PdfError& error)
2094 {
2095 // this must match the error value thrown by PdfRecursionGuard
2096 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
2097 }
2098 }
2099
2100 // CVE-2018-8002, CVE-2021-30470
2101 TEST_CASE("testNestedDictionaries")
2102 {
2103 // test valid stream
2104 // generate an XRef stream with no deeply nested dictionaries
2105 ostringstream oss;
2106 size_t offsetStream;
2107 size_t offsetEndstream;
2108 size_t offsetXRefObject;
2109 string buffer;
2110
2111 // XRef stream with 5 entries
2112 constexpr size_t lengthXRefObject = 58;
2113
2114 offsetXRefObject = oss.str().length();
2115 oss << "2 0 obj ";
2116 oss << "<< /Type /XRef ";
2117 oss << "/Length " << lengthXRefObject << " ";
2118 oss << "/Index [2 2] ";
2119 oss << "/Size 5 ";
2120 oss << "/W [1 2 1] ";
2121 oss << "/Filter /ASCIIHexDecode ";
2122 oss << ">>\r\n";
2123 oss << "stream\r\n";
2124 offsetStream = oss.str().length();
2125 oss << "01 0E8A 00\r\n";
2126 oss << "02 0002 00\r\n";
2127 oss << "02 0002 01\r\n";
2128 oss << "02 0002 02\r\n";
2129 oss << "02 0002 03\r\n";
2130 offsetEndstream = oss.str().length();
2131 oss << "endstream\r\n";
2132 oss << "endobj\r\n";
2133 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
2134
2135 // trailer
2136 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
2137 oss << "startxref " << offsetXRefObject << "\r\n";
2138 oss << "%EOF";
2139
2140 buffer = oss.str();
2141
2142 {
2143 PdfIndirectObjectList objects;
2144 PdfParserTest parser(objects, buffer);
2145 parser.ReadXRefStreamContents(offsetXRefObject, false);
2146 REQUIRE(true);
2147 }
2148
2149 // CVE-2021-30470 - lots of <<<>>> brackets represent nested dictionaries which caused stack overflow
2150 try
2151 {
2152 // generate an XRef stream with deeply nested dictionaries
2153 oss.str("");
2154
2155 const size_t maxNesting = getStackOverflowDepth(); // big enough to cause stack overflow
2156 // XRef stream with 5 entries
2157 offsetXRefObject = oss.str().length();
2158 oss << "2 0 obj ";
2159 oss << "<< /Type /XRef ";
2160 oss << "/Length " << lengthXRefObject << " ";
2161 oss << "/Index [2 2] ";
2162 oss << "/Size 5 ";
2163 oss << "/W [1 2 1] ";
2164
2165 // output << << << /Test 0 >> >> >>
2166 for (size_t i = 0; i < maxNesting; i++)
2167 {
2168 oss << "<< ";
2169 }
2170 oss << " /Test 0";
2171 for (size_t i = 0; i < maxNesting; i++)
2172 {
2173 oss << " >>";
2174 }
2175 oss << " ";
2176
2177 oss << "/Filter /ASCIIHexDecode ";
2178 oss << ">>\r\n";
2179 oss << "stream\r\n";
2180 offsetStream = oss.str().length();
2181 oss << "01 0E8A 00\r\n";
2182 oss << "02 0002 00\r\n";
2183 oss << "02 0002 01\r\n";
2184 oss << "02 0002 02\r\n";
2185 oss << "02 0002 03\r\n";
2186 offsetEndstream = oss.str().length();
2187 oss << "endstream\r\n";
2188 oss << "endobj\r\n";
2189 REQUIRE(offsetEndstream - offsetStream - strlen("\r\n") == lengthXRefObject); // hard-coded in /Length entry in XRef stream above
2190
2191 // trailer
2192 oss << "trailer << /Root 1 0 R /Size 3 >>\r\n";
2193 oss << "startxref " << offsetXRefObject << "\r\n";
2194 oss << "%EOF";
2195
2196 buffer = oss.str();
2197
2198 PdfIndirectObjectList objects;
2199 PdfParserTest parser(objects, buffer);
2200 parser.ReadXRefStreamContents(offsetXRefObject, false);
2201 FAIL("Should throw exception");
2202 }
2203 catch (PdfError& error)
2204 {
2205 // this must match the error value thrown by PdfRecursionGuard
2206 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
2207 }
2208 }
2209
2210 // CVE-2021-30471
2211 TEST_CASE("testNestedNameTree")
2212 {
2213 // test for valid but deeply nested name tree
2214 // maxDepth must be less than GetMaxObjectCount otherwise PdfParser::ResizeOffsets
2215 // throws an error when reading the xref offsets table, and no outlines are read
2216 ostringstream oss;
2217 const size_t maxDepth = getStackOverflowDepth() - 6 - 1;
2218 const size_t numObjects = maxDepth + 6;
2219 vector<size_t> offsets(numObjects);
2220 size_t xrefOffset = 0;
2221
2222 offsets[0] = 0;
2223 oss << "%PDF-1.0\r\n";
2224
2225 offsets[1] = oss.tellp();
2226 oss << "1 0 obj<</Type/Catalog /Pages 2 0 R /Names 4 0 R>>endobj ";
2227
2228 offsets[2] = oss.tellp();
2229 oss << "2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj ";
2230
2231 offsets[3] = oss.tellp();
2232 oss << "3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj ";
2233
2234 // the name dictionary
2235 offsets[4] = oss.tellp();
2236 oss << "4 0 obj<</Dests 5 0 R>>endobj ";
2237
2238 // root of /Dests name tree
2239 offsets[5] = oss.tellp();
2240 oss << "5 0 obj<</Kids [6 0 R]>>endobj ";
2241
2242 // create name tree nested to maxDepth where each intermediate node has one child
2243 // except single leaf node at maxDepth
2244 for (size_t objNo = 6; objNo < numObjects; objNo++)
2245 {
2246 offsets[objNo] = oss.tellp();
2247
2248 if (objNo < numObjects - 1)
2249 oss << objNo << " 0 obj<</Kids [" << objNo + 1 << " 0 R] /Limits [(A) (Z)]>>endobj ";
2250 else
2251 oss << objNo << " 0 obj<</Limits [(A) (Z)] /Names [ (A) (Avalue) (Z) (Zvalue) ] >>endobj ";
2252 }
2253
2254 // output xref table
2255 oss << "\r\n";
2256 xrefOffset = oss.tellp();
2257 oss << "xref\r\n";
2258 oss << "0 " << numObjects << "\r\n";
2259
2260 oss << "0000000000 65535 f\r\n";
2261
2262 for (size_t objNo = 1; objNo < offsets.size(); objNo++)
2263 {
2264 // write xref entries like
2265 // "0000000010 00000 n\r\n"
2266 char refEntry[21];
2267 snprintf(refEntry, 21, "%010zu 00000 n\r\n", offsets[objNo]);
2268
2269 oss << refEntry;
2270 }
2271
2272 oss << "trailer<</Size " << numObjects << "/Root 1 0 R>>\r\n";
2273 oss << "startxref\r\n";
2274 oss << xrefOffset << "\r\n";
2275 oss << "%%EOF";
2276
2277 auto buffer = oss.str();
2278
2279 try
2280 {
2281 PdfMemDocument doc;
2282 doc.LoadFromBuffer(buffer);
2283
2284 auto names = doc.GetNames();
2285 if (names != nullptr)
2286 {
2287 PdfDictionary dict;
2288 names->ToDictionary("Dests", dict);
2289 }
2290
2291 FAIL("Should throw exception");
2292 }
2293 catch (PdfError& error)
2294 {
2295 // this must match the error value thrown by PdfRecursionGuard
2296 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
2297 }
2298 }
2299
2300 // CVE-2021-30471
2301 TEST_CASE("testLoopingNameTree")
2302 {
2303 string strNoLoop =
2304 "%PDF-1.0\r\n"
2305 "1 0 obj<</Type/Catalog/Pages 2 0 R /Names 4 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj 4 0 obj<</Dests 2 0 R>>endobj\r\n"
2306 "xref\r\n"
2307 "0 5\r\n"
2308 "0000000000 65535 f\r\n"
2309 "0000000010 00000 n\r\n"
2310 "0000000066 00000 n\r\n"
2311 "0000000115 00000 n\r\n"
2312 "0000000161 00000 n\r\n"
2313 "trailer<</Size 4/Root 1 0 R>>\r\n"
2314 "startxref\r\n"
2315 "192\r\n"
2316 "%%EOF";
2317
2318 {
2319 PdfMemDocument doc;
2320 doc.LoadFromBuffer(strNoLoop);
2321
2322 auto names = doc.GetNames();
2323 if (names != nullptr)
2324 {
2325 PdfDictionary dict;
2326 names->ToDictionary("Dests", dict);
2327 }
2328 }
2329
2330 // CVE-2021-30471 /Dests points at pages tree root which has a /Kids entry loooping back to pages tree root
2331 string strSelfLoop =
2332 "%PDF-1.0\r\n"
2333 "1 0 obj<</Type/Catalog/Pages 2 0 R /Names 4 0 R>>endobj 2 0 obj<</Type/Pages/Kids[2 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj 4 0 obj<</Dests 2 0 R>>endobj\r\n"
2334 "xref\r\n"
2335 "0 5\r\n"
2336 "0000000000 65535 f\r\n"
2337 "0000000010 00000 n\r\n"
2338 "0000000066 00000 n\r\n"
2339 "0000000115 00000 n\r\n"
2340 "0000000161 00000 n\r\n"
2341 "trailer<</Size 4/Root 1 0 R>>\r\n"
2342 "startxref\r\n"
2343 "192\r\n"
2344 "%%EOF";
2345
2346 try
2347 {
2348 PdfMemDocument doc;
2349 doc.LoadFromBuffer(strSelfLoop);
2350
2351 auto names = doc.GetNames();
2352 if (names != nullptr)
2353 {
2354 PdfDictionary dict;
2355 names->ToDictionary("Dests", dict);
2356 }
2357
2358 FAIL("Should throw exception");
2359 }
2360 catch (PdfError& error)
2361 {
2362 // this must match the error value thrown by PdfRecursionGuard
2363 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
2364 }
2365
2366 // CVE-2021-30471 /Dests points at pages tree which has a /Kids entry loooping back to ancestor (document root)
2367 string strAncestorLoop =
2368 "%PDF-1.0\r\n"
2369 "1 0 obj<</Type/Catalog/Pages 2 0 R /Names 4 0 R>>endobj 2 0 obj<</Type/Pages/Kids[1 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj 4 0 obj<</Dests 2 0 R>>endobj\r\n"
2370 "xref\r\n"
2371 "0 5\r\n"
2372 "0000000000 65535 f\r\n"
2373 "0000000010 00000 n\r\n"
2374 "0000000066 00000 n\r\n"
2375 "0000000115 00000 n\r\n"
2376 "0000000161 00000 n\r\n"
2377 "trailer<</Size 4/Root 1 0 R>>\r\n"
2378 "startxref\r\n"
2379 "192\r\n"
2380 "%%EOF";
2381
2382 try
2383 {
2384 PdfMemDocument doc;
2385 doc.LoadFromBuffer(strAncestorLoop);
2386
2387 auto names = doc.GetNames();
2388 if (names != nullptr)
2389 {
2390 PdfDictionary dict;
2391 names->ToDictionary("Dests", dict);
2392 }
2393
2394 FAIL("Should throw exception");
2395 }
2396 catch (PdfError& error)
2397 {
2398 REQUIRE(error.GetCode() == PdfErrorCode::InvalidDataType);
2399 }
2400 }
2401
2402 // CVE-2021-30471
2403 TEST_CASE("testNestedPageTree")
2404 {
2405 // test for valid but deeply nested page tree
2406 // maxDepth must be less than GetMaxObjectCount otherwise PdfParser::ResizeOffsets
2407 // throws an error when reading the xref offsets table, and no outlines are read
2408 ostringstream oss;
2409 const size_t maxDepth = getStackOverflowDepth() - 4 - 1;
2410 const size_t numObjects = maxDepth + 4;
2411 vector<size_t> offsets(numObjects);
2412 size_t xrefOffset = 0;
2413
2414 offsets[0] = 0;
2415 oss << "%PDF-1.0\r\n";
2416
2417 offsets[1] = oss.tellp();
2418 oss << "1 0 obj<</Type/Catalog /AcroForm 2 0 R /Pages 3 0 R>>endobj ";
2419
2420 offsets[2] = oss.tellp();
2421 oss << "2 0 obj<</Type/AcroForm >>endobj ";
2422
2423 offsets[3] = oss.tellp();
2424 oss << "3 0 obj<</Type/Pages /Kids [4 0 R] /Count 1 >>endobj ";
2425
2426 // create pages tree nested to maxDepth where each node has one child
2427 // except single leaf node at maxDepth
2428 for (size_t objNo = 4; objNo < numObjects; objNo++)
2429 {
2430 offsets[objNo] = oss.tellp();
2431
2432 if (objNo < numObjects - 1)
2433 oss << objNo << " 0 obj<</Type/Pages /Kids [" << objNo + 1 << " 0 R] /Parent " << objNo - 1 << " 0 R /Count 1 >>endobj ";
2434 else
2435 oss << objNo << " 0 obj<</Type/Page /Parent " << objNo - 1 << " 0 R >>endobj ";
2436 }
2437
2438 // output xref table
2439 oss << "\r\n";
2440 xrefOffset = oss.tellp();
2441 oss << "xref\r\n";
2442 oss << "0 " << numObjects << "\r\n";
2443
2444 oss << "0000000000 65535 f\r\n";
2445
2446 for (size_t objNo = 1; objNo < offsets.size(); objNo++)
2447 {
2448 // write xref entries like
2449 // "0000000010 00000 n\r\n"
2450 char refEntry[21];
2451 snprintf(refEntry, 21, "%010zu 00000 n\r\n", offsets[objNo]);
2452
2453 oss << refEntry;
2454 }
2455
2456 oss << "trailer<</Size " << numObjects << "/Root 1 0 R>>\r\n";
2457 oss << "startxref\r\n";
2458 oss << xrefOffset << "\r\n";
2459 oss << "%%EOF";
2460
2461 auto buffer = oss.str();
2462 try
2463 {
2464 PdfMemDocument doc;
2465 doc.LoadFromBuffer(buffer);
2466
2467 auto& pages = doc.GetPages();
2468 for (unsigned pageNo = 0; pageNo < pages.GetCount(); pageNo++)
2469 (void)pages.GetPageAt(pageNo);
2470
2471 FAIL("Should throw exception");
2472 }
2473 catch (PdfError& error)
2474 {
2475 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
2476 }
2477 }
2478
2479 // CVE-2021-30471
2480 TEST_CASE("testLoopingPageTree")
2481 {
2482 // test PDF without nested kids
2483 string strNoLoop =
2484 "%PDF-1.0\r\n"
2485 "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj\r\n"
2486 "xref\r\n"
2487 "0 4\r\n"
2488 "0000000000 65535 f\r\n"
2489 "0000000010 00000 n\r\n"
2490 "0000000053 00000 n\r\n"
2491 "0000000102 00000 n\r\n"
2492 "trailer<</Size 4/Root 1 0 R>>\r\n"
2493 "startxref\r\n"
2494 "149\r\n"
2495 "%%EOF";
2496
2497 {
2498 PdfMemDocument doc;
2499 doc.LoadFromBuffer(strNoLoop);
2500 auto& pages = doc.GetPages();
2501 for (unsigned pageNo = 0; pageNo < doc.GetPages().GetCount(); pageNo++)
2502 (void)pages.GetPageAt(pageNo);
2503 REQUIRE(true);
2504 }
2505
2506 // CVE-2021-30471 test for pages tree /Kids array that refer back to pages tree root
2507 string strSelfLoop =
2508 "%PDF-1.0\r\n"
2509 "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[2 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj\r\n"
2510 "xref\r\n"
2511 "0 4\r\n"
2512 "0000000000 65535 f\r\n"
2513 "0000000010 00000 n\r\n"
2514 "0000000053 00000 n\r\n"
2515 "0000000102 00000 n\r\n"
2516 "trailer<</Size 4/Root 1 0 R>>\r\n"
2517 "startxref\r\n"
2518 "149\r\n"
2519 "%%EOF";
2520
2521 try
2522 {
2523 PdfMemDocument doc;
2524 doc.LoadFromBuffer(strSelfLoop);
2525 auto& pages = doc.GetPages();
2526 for (unsigned pageNo = 0; pageNo < pages.GetCount(); pageNo++)
2527 (void)pages.GetPageAt(pageNo);
2528
2529 FAIL("Should throw exception");
2530 }
2531 catch (PdfError& error)
2532 {
2533 REQUIRE(error.GetCode() == PdfErrorCode::BrokenFile);
2534 }
2535
2536 // CVE-2021-30471 test for pages tree /Kids array that refer back to an ancestor (document root object)
2537 string strAncestorLoop =
2538 "%PDF-1.0\r\n"
2539 "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[1 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj\r\n"
2540 "xref\r\n"
2541 "0 4\r\n"
2542 "0000000000 65535 f\r\n"
2543 "0000000010 00000 n\r\n"
2544 "0000000053 00000 n\r\n"
2545 "0000000102 00000 n\r\n"
2546 "trailer<</Size 4/Root 1 0 R>>\r\n"
2547 "startxref\r\n"
2548 "149\r\n"
2549 "%%EOF";
2550
2551 try
2552 {
2553 PdfMemDocument doc;
2554 doc.LoadFromBuffer(strAncestorLoop);
2555 auto& pages = doc.GetPages();
2556 pages.GetPageAt(0);
2557 FAIL("Should throw exception");
2558 }
2559 catch (PdfError& error)
2560 {
2561 REQUIRE(error.GetCode() == PdfErrorCode::BrokenFile);
2562 }
2563 }
2564
2565 // CVE-2020-18971
2566 TEST_CASE("testNestedOutlines")
2567 {
2568 // test for valid but deeply nested outlines
2569 // maxDepth must be less than GetMaxObjectCount otherwise PdfParser::ResizeOffsets
2570 // throws an error when reading the xref offsets table, and no outlines are read
2571 ostringstream oss;
2572 const size_t maxDepth = getStackOverflowDepth() - 4 - 1;
2573 const size_t numObjects = maxDepth + 4;
2574 vector<size_t> offsets(numObjects);
2575 size_t xrefOffset = 0;
2576
2577 offsets[0] = 0;
2578 oss << "%PDF-1.0\r\n";
2579
2580 offsets[1] = oss.tellp();
2581 oss << "1 0 obj<</Type/Catalog /AcroForm 2 0 R /Outlines 3 0 R>>endobj ";
2582
2583 offsets[2] = oss.tellp();
2584 oss << "2 0 obj<</Type/AcroForm >>endobj ";
2585
2586 offsets[3] = oss.tellp();
2587 oss << "3 0 obj<</Type/Outlines /First 4 0 R /Count " << maxDepth << " /Last 5 0 R >>endobj ";
2588
2589 // create outlines tree nested to maxDepth where each node has one child
2590 // except single leaf node at maxDepth
2591 for (size_t objNo = 4; objNo < numObjects; objNo++)
2592 {
2593 offsets[objNo] = oss.tellp();
2594
2595 if (objNo < numObjects - 1)
2596 oss << objNo << " 0 obj<</Title (Outline Item) /First " << objNo + 1 << " 0 R /Last " << objNo + 1 << " 0 R>>endobj ";
2597 else
2598 oss << objNo << " 0 obj<</Title (Outline Item)>>endobj ";
2599 }
2600
2601 // output xref table
2602 oss << "\r\n";
2603 xrefOffset = oss.tellp();
2604 oss << "xref\r\n";
2605 oss << "0 " << numObjects << "\r\n";
2606
2607 oss << "0000000000 65535 f\r\n";
2608
2609 for (size_t objNo = 1; objNo < offsets.size(); objNo++)
2610 {
2611 // write xref entries like
2612 // "0000000010 00000 n\r\n"
2613 char szXrefEntry[21];
2614 snprintf(szXrefEntry, 21, "%010zu 00000 n\r\n", offsets[objNo]);
2615
2616 oss << szXrefEntry;
2617 }
2618
2619 oss << "trailer<</Size " << numObjects << "/Root 1 0 R>>\r\n";
2620 oss << "startxref\r\n";
2621 oss << xrefOffset << "\r\n";
2622 oss << "%%EOF";
2623
2624 auto buffer = oss.str();
2625 try
2626 {
2627 PdfMemDocument doc;
2628 doc.LoadFromBuffer(buffer);
2629
2630 // load should succeed, then GetOutlines goes recursive due to /Outlines deep nesting
2631 (void)doc.GetOutlines();
2632 FAIL("Should throw exception");
2633 }
2634 catch (PdfError& error)
2635 {
2636 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
2637 }
2638 }
2639
2640 // CVE-2020-18971
2641 TEST_CASE("testLoopingOutlines")
2642 {
2643 // CVE-2020-18971 - PdfOutlineItem /Next refers a preceding sibling
2644 string strNextLoop =
2645 "%PDF-1.0\r\n"
2646 "1 0 obj<</Type/Catalog /AcroForm 2 0 R /Outlines 3 0 R>>endobj "
2647 "2 0 obj<</Type/AcroForm >>endobj "
2648 "3 0 obj<</Type/Outlines /First 4 0 R /Count 2 /Last 5 0 R >>endobj "
2649 "4 0 obj<</Title (Outline Item 1) /Next 5 0 R>>endobj "
2650 "5 0 obj<</Title (Outline Item 2) /Next 4 0 R>>endobj " // /Next loops back to previous outline item
2651 "\r\n"
2652 "xref\r\n"
2653 "0 6\r\n"
2654 "0000000000 65535 f\r\n"
2655 "0000000010 00000 n\r\n"
2656 "0000000073 00000 n\r\n"
2657 "0000000106 00000 n\r\n"
2658 "0000000173 00000 n\r\n"
2659 "0000000226 00000 n\r\n"
2660 "trailer<</Size 6/Root 1 0 R>>\r\n"
2661 "startxref\r\n"
2662 "281\r\n"
2663 "%%EOF";
2664
2665 try
2666 {
2667 PdfMemDocument doc;
2668 doc.LoadFromBuffer(strNextLoop);
2669
2670 // load should succeed, then GetOutlines goes recursive due to /Outlines loop
2671 (void)doc.GetOutlines();
2672 FAIL("Should throw exception");
2673 }
2674 catch (PdfError& error)
2675 {
2676 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
2677 }
2678
2679 // https://sourceforge.net/p/podofo/tickets/25/
2680 string strSelfLoop =
2681 "%PDF-1.0\r\n"
2682 "1 0 obj<</Type/Catalog/Outlines 2 0 R>>endobj "
2683 "2 0 obj<</Type/Outlines /First 2 0 R /Last 2 0 R /Count 1>>endobj" // /First and /Last loop to self
2684 "\r\n"
2685 "xref\r\n"
2686 "0 3\r\n"
2687 "0000000000 65535 f\r\n"
2688 "0000000010 00000 n\r\n"
2689 "0000000056 00000 n\r\n"
2690 "trailer<</Size 3/Root 1 0 R>>\r\n"
2691 "startxref\r\n"
2692 "123\r\n"
2693 "%%EOF";
2694
2695 try
2696 {
2697 PdfMemDocument doc;
2698 doc.LoadFromBuffer(strNextLoop);
2699
2700 // load should succeed, then GetOutlines goes recursive due to /Outlines loop
2701 (void)doc.GetOutlines();
2702 FAIL("Should throw exception");
2703 }
2704 catch (PdfError& error)
2705 {
2706 REQUIRE(error.GetCode() == PdfErrorCode::InvalidXRef);
2707 }
2708 }
2709
2710 TEST_CASE("TestManyTrailer")
2711 {
2712 try
2713 {
2714 PdfCommon::SetMaxRecursionDepth(256);
2715 PdfMemDocument doc;
2716 doc.Load(TestUtils::GetTestInputFilePath("Empty160trailer.pdf"));
2717 }
2718 catch (PdfError&)
2719 {
2720 return;
2721 }
2722 FAIL("Should fail with stack overflow");
2723 }
2724
2725 TEST_CASE("TestManyTrailerXRefStream")
2726 {
2727 try
2728 {
2729 PdfMemDocument doc;
2730 doc.Load(TestUtils::GetTestInputFilePath("EmptyXRefStream225Trailer.pdf"));
2731 }
2732 catch (PdfError&)
2733 {
2734 return;
2735 }
2736 FAIL("Should fail with stack overflow");
2737 }
2738
2739 // This tests saving the update on a document with
2740 // compressed object stream with an indirect length
2741 // still produces a readable file
2742 TEST_CASE("TestCompressedObjectStreamIndirectLength")
2743 {
2744 string outpath = TestUtils::GetTestOutputFilePath("TestCompressedObjectStreamIndirectLength.pdf");
2745
2746 PdfMemDocument doc;
2747 {
2748 FileStreamDevice device(TestUtils::GetTestInputFilePath("PDFUA-Reference", "PDFUA-Ref-2-02_Invoice.pdf"));
2749 FileStreamDevice out(outpath, FileMode::Create);
2750 device.CopyTo(out);
2751 }
2752
2753 doc.Load(outpath);
2754 doc.SaveUpdate(outpath);
2755 doc.Load(outpath);
2756 }
2757
2758 string generateXRefEntries(size_t count)
2759 {
2760 string strXRefEntries;
2761
2762 // generates a block of 20-byte xref entries
2763 // 0000000000 65535 f\r\n
2764 // 0000000120 00000 n\r\n
2765 // 0000000120 00000 n\r\n
2766 // 0000000120 00000 n\r\n
2767 try
2768 {
2769 strXRefEntries.reserve(count * 20);
2770 for (size_t i = 0; i < count; i++)
2771 {
2772 if (i == 0)
2773 strXRefEntries.append("0000000000 65535 f\r\n");
2774 else
2775 strXRefEntries.append("0000000120 00000 n\r\n");
2776 }
2777 }
2778 catch (exception&)
2779 {
2780 // if this fails it's a bug in the unit tests and not PoDoFo
2781 FAIL("generateXRefEntries memory allocation failure");
2782 }
2783
2784 return strXRefEntries;
2785 }
2786
2787 bool canOutOfMemoryKillUnitTests()
2788 {
2789 // test if out of memory conditions will kill the unit test process
2790 // which prevents tests completing
2791
2792 #if defined(_WIN32)
2793 // on Windows 32/64 allocations close to size of VM address space always fail gracefully
2794 bool canTerminateProcess = false;
2795 #elif defined( __APPLE__ )
2796 // on macOS/iOS allocations close to size of VM address space fail gracefully
2797 // unless Address Sanitizer (ASAN) is enabled
2798 #if __has_feature(address_sanitizer)
2799 // ASAN terminates the process if alloc fails - and using allocator_may_return_null=1
2800 // to continue after an allocation doesn't work in C++ because new returns null which is
2801 // forbidden by the C++ spec and terminates process when 'this' is dereferenced in constructor
2802 // see https://github.com/google/sanitizers/issues/295
2803 bool canTerminateProcess = true;
2804 #else
2805 // if alloc fails following message is logged
2806 // *** mach_vm_map failed (error code=3)
2807 // *** error: can't allocate region
2808 // *** set a breakpoint in malloc_error_break to debug
2809 bool canTerminateProcess = false;
2810 #endif
2811 #elif defined( __linux__ )
2812 // TODO do big allocs succeed then trigger OOM-killer fiasco??
2813 bool canTerminateProcess = false;
2814 #else
2815 // other systems - assume big allocs faily gracefully and throw bad_alloc
2816 bool canTerminateProcess = false;
2817 #endif
2818 return canTerminateProcess;
2819 }
2820
2821 size_t getStackOverflowDepth()
2822 {
2823 // calculate stack overflow depth - need to do this because a value that consistently overflows a 64-bit stack
2824 // doesn't work on 32-bit systems because they run out of heap in ReadObjects before they get a chance to overflow stack
2825 // this is because sizeof(PdfParserObject) = 472 bytes (and there's one of these for every object read)
2826 constexpr size_t parserObjectSize = sizeof(PdfParserObject);
2827
2828 #if defined(_WIN64)
2829 // 1 MB default stack size, 64-bit address space, Windows x64 ABI
2830 // each stack frame has at least 4 64-bit stack params, 4 64-bit register params, plus 64-bit return address
2831 // stack frame size increases if function contains local variables or more than 4 parameters
2832 // see https://docs.microsoft.com/en-us/cpp/build/stack-usage?view=msvc-170
2833 constexpr size_t stackSize = 1 * 1024 * 1024;
2834 constexpr size_t frameSize = sizeof(void*) * (4 + 4 + 1); // 4 stack params + 4 register params + return address
2835 constexpr size_t maxFrames = stackSize / frameSize; // overflows at 14,563 recursive calls (or sooner if functions contain local variables)
2836 #elif defined(_WIN32)
2837 // 1 MB default stack size, 32-bit address space (can't allocate more than 2GB), Windows x86 thiscall calling convention
2838 // each stack frame has at least 32-bit EBP and return address
2839 // stack frame size increases if function contains local variables or any parameters
2840 constexpr size_t stackSize = 1 * 1024 * 1024;
2841 constexpr size_t frameSize = sizeof(void*) * (1 + 1); // EBP and return address
2842 constexpr size_t maxFrames = stackSize / frameSize; // overflows at 131,072 recursive calls (or sooner if functions contain local variables or has parameters)
2843 #else
2844 // assume 8MB macOS / Linux default stack size, 64-bit address space, System V AMD64 ABI
2845 // each stack frame has at least 64-bit EBP and return address
2846 // stack frame size increases if function contains local variables or any parameters
2847 constexpr size_t stackSize = 8 * 1024 * 1024;
2848 constexpr size_t frameSize = sizeof(void*) * (1 + 1); // EBP and return address
2849 constexpr size_t maxFrames = stackSize / frameSize; // overflows at 524,288 recursive calls (or sooner if functions contain local variables or has parameters)
2850 #endif
2851
2852 // add a few frames to sure we go beyond end of stack
2853 constexpr size_t overflowDepth = maxFrames + 1000;
2854
2855 // overflowDepth must be less than GetMaxObjectCount otherwise PdfParser::ResizeOffsets
2856 // throws an error when reading the xref offsets table, and no recursive calls are made
2857 // must also be allocate less than half of address space to prevent out-of-memory exceptions
2858 REQUIRE(overflowDepth < PdfParser::GetMaxObjectCount());
2859 REQUIRE(overflowDepth * parserObjectSize < numeric_limits<size_t>::max() / 2);
2860
2861 return overflowDepth;
2862 }