diff --git a/lib/Handler/DocMdpHandler.php b/lib/Handler/DocMdpHandler.php index 2c72fb217a..cc5f330515 100644 --- a/lib/Handler/DocMdpHandler.php +++ b/lib/Handler/DocMdpHandler.php @@ -13,7 +13,13 @@ use OCA\Libresign\Enum\DocMdpLevel; use OCP\IL10N; +/** + * @psalm-type PdfObject = array{num: int, gen: int, value: string, entries: ?array, stream: ?string, end: int} + * @psalm-type SignedRevision = array{startxref: int, offsets: array, size: int, root: string, info: ?string} + */ class DocMdpHandler { + private const int MAX_NESTING_DEPTH = 64; + /** @var array Allowed modification types per DocMDP level */ private const array ALLOWED_MODIFICATIONS = [ 'CERTIFIED_NO_CHANGES_ALLOWED' => [], @@ -301,6 +307,15 @@ private function validateModifications(DocMdpLevel $docmdpLevel, array $modifica ); } + if ($this->hasOnlyValidationDataUpdates($pdfResource, $modificationInfo)) { + // TRANSLATORS Validation result for a certified PDF where, after signing, only long-term validation data (DSS: certificates, CRLs, OCSP responses) or document timestamps were added. DocMDP (document modification policy) permits this at every level. + return $this->buildValidationResult( + true, + File::MODIFICATION_ALLOWED, + $this->l10n->t('Only validation data or document timestamps were added after signing (allowed by DocMDP)') + ); + } + $modificationType = $this->analyzeModificationType($pdfResource, $modificationInfo); $allowedTypes = self::ALLOWED_MODIFICATIONS[$docmdpLevel->name] ?? null; @@ -419,6 +434,643 @@ private function analyzeModificationType($pdfResource, array $modificationInfo): return 'unknown'; } + /** + * ISO 32000-2 12.8.2.2.1 and ETSI EN 319 142-1 5.4: DocMDP restrictions do not + * apply to incremental updates that only add a DSS dictionary (with its VRI, + * Certs, CRLs and OCSPs) or a document timestamp. + * + * The bytes after the certified revision are parsed strictly as a sequence + * of incremental updates: indirect objects, a classic xref table listing + * exactly those objects, a trailer and startxref. Anything else (xref + * streams, unlisted or unparsable bytes, a changed /Root or /Info, /Encrypt) + * means the update is not validation data only. The certified revision must + * use classic xref tables, so that the objects an update rewrites can be + * compared with their certified version. + * + * New objects (numbers from the certified /Size on) are inert unless an + * existing object references them. Of the existing objects, an update may + * only rewrite: + * - the catalog, changing /DSS, /Extensions, /Version or appending + * timestamp fields to an inline /AcroForm; + * - the AcroForm, changing /SigFlags and appending timestamp fields to /Fields; + * - a page, appending timestamp fields to /Annots; + * - the document information dictionary, changing /ModDate and /Producer. + * A new field must be an invisible document timestamp field; any other new + * field, annotation or signature is not validation data. + * + * @param resource $pdfResource PDF file resource + */ + private function hasOnlyValidationDataUpdates($pdfResource, array $modificationInfo): bool { + if (empty($modificationInfo['details'])) { + return false; + } + + rewind($pdfResource); + $content = (string)stream_get_contents($pdfResource); + $coveredEnd = (int)$modificationInfo['details'][0]['coveredBytes']; + + $signed = $this->readSignedRevision($content, $coveredEnd); + if ($signed === null) { + return false; + } + $objects = $this->readIncrementalUpdates($content, $coveredEnd, $signed); + if (empty($objects)) { + return false; + } + + $newObjects = array_filter($objects, static fn (int $num): bool => $num >= $signed['size'], ARRAY_FILTER_USE_KEY); + $timestampFields = []; + foreach ($newObjects as $num => $object) { + $entries = $object['entries']; + if ($entries === null) { + continue; + } + $type = $entries['/Type'] ?? null; + if (in_array($type, ['/Sig', '/ObjStm', '/XRef'], true) + || (isset($entries['/ByteRange']) && $type !== '/DocTimeStamp')) { + return false; + } + if (isset($entries['/FT'])) { + if (!$this->isTimestampField($entries, $newObjects)) { + return false; + } + $timestampFields[$num . ' 0 R'] = true; + continue; + } + if ($type === '/Annot' || ($entries['/Subtype'] ?? null) === '/Widget') { + return false; + } + } + + $rootNum = (int)$signed['root']; + $catalog = $this->readSignedObject($content, $signed, $rootNum); + $acroFormRef = $catalog['entries']['/AcroForm'] ?? ''; + $acroFormNum = preg_match('/^(\d+) \d+ R$/', $acroFormRef, $match) ? (int)$match[1] : null; + $infoNum = $signed['info'] === null ? null : (int)$signed['info']; + + foreach ($objects as $num => $object) { + if ($num >= $signed['size']) { + continue; + } + $old = $this->readSignedObject($content, $signed, $num); + if ($old === null) { + return false; + } + if ($old['value'] === $object['value'] && $old['stream'] === $object['stream']) { + continue; + } + if ($old['stream'] !== null || $object['stream'] !== null + || $old['entries'] === null || $object['entries'] === null) { + return false; + } + + $allowed = match (true) { + $num === $rootNum => $this->isAllowedCatalogChange($old['entries'], $object['entries'], $timestampFields), + $num === $acroFormNum => $this->isAllowedAcroFormChange($old['entries'], $object['entries'], $timestampFields), + $num === $infoNum => $this->isAllowedEntriesChange($old['entries'], $object['entries'], [], ['/ModDate', '/Producer'], $timestampFields), + ($old['entries']['/Type'] ?? null) === '/Page' => $this->isAllowedEntriesChange($old['entries'], $object['entries'], ['/Annots'], [], $timestampFields), + default => false, + }; + if (!$allowed) { + return false; + } + } + + return true; + } + + /** + * A document timestamp field: merged field and widget without kids or + * actions, invisible (zero-area /Rect), whose value is a new + * /DocTimeStamp dictionary with /SubFilter /ETSI.RFC3161. + * + * @param array $entries + * @param array $newObjects + */ + private function isTimestampField(array $entries, array $newObjects): bool { + if (($entries['/FT'] ?? null) !== '/Sig' + || isset($entries['/Kids']) || isset($entries['/Parent']) || isset($entries['/A']) || isset($entries['/AA']) + || ($entries['/Type'] ?? '/Annot') !== '/Annot' + || ($entries['/Subtype'] ?? '/Widget') !== '/Widget') { + return false; + } + + $rect = $entries['/Rect'] ?? null; + $number = '(-?(?:\d+\.?\d*|\.\d+))'; + if ($rect === null || !preg_match("/^\\[{$number} {$number} {$number} {$number}\\]$/", $rect, $corners) + || abs(((float)$corners[3] - (float)$corners[1]) * ((float)$corners[4] - (float)$corners[2])) > 0.0) { + return false; + } + + if (!preg_match('/^(\d+) \d+ R$/', $entries['/V'] ?? '', $match)) { + return false; + } + $value = $newObjects[(int)$match[1]]['entries'] ?? null; + return $value !== null + && ($value['/Type'] ?? null) === '/DocTimeStamp' + && ($value['/SubFilter'] ?? null) === '/ETSI.RFC3161'; + } + + /** + * Trailer and object offsets of the certified revision, read through its + * classic xref tables. + * + * @return SignedRevision|null + */ + private function readSignedRevision(string $content, int $coveredEnd): ?array { + $signedContent = substr($content, 0, $coveredEnd); + $startxrefPos = strrpos($signedContent, 'startxref'); + if ($startxrefPos === false + || !preg_match('/\Gstartxref\s+(\d+)\s+%%EOF\s*$/', $signedContent, $match, 0, $startxrefPos)) { + return null; + } + $startxref = (int)$match[1]; + + $offsets = []; + $newestTrailer = null; + $visited = []; + $offset = $startxref; + while ($offset !== null) { + if (isset($visited[$offset]) || count($visited) >= 1000 || $offset >= $coveredEnd) { + return null; + } + $visited[$offset] = true; + $section = $this->readXrefSection($signedContent, $offset); + if ($section === null || isset($section['trailer']['/XRefStm'])) { + return null; + } + $newestTrailer ??= $section['trailer']; + foreach ($section['entries'] as $num => [$entryOffset, , $inUse]) { + if (!array_key_exists($num, $offsets)) { + $offsets[$num] = $inUse ? $entryOffset : null; + } + } + $prev = $section['trailer']['/Prev'] ?? null; + $offset = $prev === null ? null : (ctype_digit($prev) ? (int)$prev : -1); + if ($offset === -1) { + return null; + } + } + + $size = $newestTrailer['/Size'] ?? ''; + $root = $newestTrailer['/Root'] ?? ''; + $info = $newestTrailer['/Info'] ?? null; + if (!ctype_digit($size) || !preg_match('/^\d+ \d+ R$/', $root) + || ($info !== null && !preg_match('/^\d+ \d+ R$/', $info))) { + return null; + } + + return [ + 'startxref' => $startxref, + 'offsets' => array_filter($offsets, static fn (?int $entryOffset): bool => $entryOffset !== null), + 'size' => (int)$size, + 'root' => $root, + 'info' => $info, + ]; + } + + /** + * @param SignedRevision $signed + * @return PdfObject|null + */ + private function readSignedObject(string $content, array $signed, int $num): ?array { + if (!isset($signed['offsets'][$num])) { + return null; + } + $object = $this->readIndirectObject($content, $signed['offsets'][$num]); + return $object !== null && $object['num'] === $num ? $object : null; + } + + /** + * Parse every incremental update after the certified revision. + * + * @param SignedRevision $signed + * @return array|null Latest version of each object written by the updates + */ + private function readIncrementalUpdates(string $content, int $coveredEnd, array $signed): ?array { + $length = strlen($content); + $pos = $coveredEnd; + $prev = $signed['startxref']; + $objects = []; + + while (true) { + $pos += strspn($content, "\x00\t\n\x0c\r ", $pos); + if ($pos >= $length) { + return $objects; + } + + $revision = []; + $offsets = []; + while (preg_match('/\G\d+\s+\d+\s+obj\b/', $content, $match, 0, $pos)) { + $object = $this->readIndirectObject($content, $pos); + if ($object === null || isset($revision[$object['num']])) { + return null; + } + $revision[$object['num']] = $object; + $offsets[$object['num']] = [$pos, $object['gen']]; + $pos = $object['end']; + $pos += strspn($content, "\x00\t\n\x0c\r ", $pos); + } + + $xrefOffset = $pos; + $section = $this->readXrefSection($content, $pos); + if ($section === null) { + return null; + } + $pos = $section['end']; + if (!preg_match('/\G\s*startxref\s+(\d+)\s+%%EOF/', $content, $match, 0, $pos) + || (int)$match[1] !== $xrefOffset) { + return null; + } + $pos += strlen($match[0]); + + $trailer = $section['trailer']; + if (($trailer['/Prev'] ?? null) !== (string)$prev + || ($trailer['/Root'] ?? null) !== $signed['root'] + || ($trailer['/Info'] ?? $signed['info']) !== $signed['info'] + || isset($trailer['/Encrypt']) || isset($trailer['/XRefStm'])) { + return null; + } + + $listed = 0; + foreach ($section['entries'] as $num => [$entryOffset, $generation, $inUse]) { + if (!$inUse) { + if ($num !== 0) { + return null; + } + continue; + } + if (($offsets[$num] ?? null) !== [$entryOffset, $generation]) { + return null; + } + $listed++; + } + if ($listed !== count($revision)) { + return null; + } + + $objects = array_replace($objects, $revision); + $prev = $xrefOffset; + } + } + + /** + * Classic cross-reference table and its trailer at $pos. + * + * @return array{entries: array, trailer: array, end: int}|null + */ + private function readXrefSection(string $content, int $pos): ?array { + if (!preg_match('/\Gxref[ \t]*(?:\r\n|\r|\n)/', $content, $match, 0, $pos)) { + return null; + } + $pos += strlen($match[0]); + + $entries = []; + while (preg_match('/\G[ \t]*(\d+) (\d+)[ \t]*(?:\r\n|\r|\n)/', $content, $header, 0, $pos)) { + $pos += strlen($header[0]); + $first = (int)$header[1]; + for ($i = 0; $i < (int)$header[2]; $i++) { + if (!preg_match('/\G(\d{10}) (\d{5}) ([nf])(?: \r| \n|\r\n)/', $content, $entry, 0, $pos)) { + return null; + } + $pos += 20; + $entries[$first + $i] = [(int)$entry[1], (int)$entry[2], $entry[3] === 'n']; + } + } + + if (!preg_match('/\G\s*trailer\b/', $content, $match, 0, $pos)) { + return null; + } + $pos += strlen($match[0]); + $this->skipPdfWhitespace($content, $pos); + if (substr($content, $pos, 2) !== '<<') { + return null; + } + $trailer = $this->readPdfDictionary($content, $pos, 0); + if ($trailer === null) { + return null; + } + + return ['entries' => $entries, 'trailer' => $trailer, 'end' => $pos]; + } + + /** + * Indirect object at $pos: "N G obj", one value, an optional stream with a + * direct /Length, "endobj". + * + * @return PdfObject|null + */ + private function readIndirectObject(string $content, int $pos): ?array { + if (!preg_match('/\G(\d+)\s+(\d+)\s+obj\b/', $content, $match, 0, $pos)) { + return null; + } + $pos += strlen($match[0]); + + $this->skipPdfWhitespace($content, $pos); + $entries = null; + if (substr($content, $pos, 2) === '<<') { + $valueStart = $pos; + $entries = $this->readPdfDictionary($content, $pos, 0); + $value = $entries === null ? null : $this->readPdfValue($content, $valueStart, 0); + } else { + $value = $this->readPdfValue($content, $pos, 0); + } + if ($value === null) { + return null; + } + + $stream = null; + if (preg_match('/\G\s*stream(?:\r\n|\n)/', $content, $streamStart, 0, $pos)) { + $length = $entries['/Length'] ?? ''; + if (!ctype_digit($length)) { + return null; + } + $pos += strlen($streamStart[0]); + $stream = substr($content, $pos, (int)$length); + $pos += (int)$length; + if (strlen($stream) !== (int)$length || !preg_match('/\G\s*endstream\b/', $content, $streamEnd, 0, $pos)) { + return null; + } + $pos += strlen($streamEnd[0]); + } + + if (!preg_match('/\G\s*endobj\b/', $content, $end, 0, $pos)) { + return null; + } + + return [ + 'num' => (int)$match[1], + 'gen' => (int)$match[2], + 'value' => $value, + 'entries' => $entries, + 'stream' => $stream, + 'end' => $pos + strlen($end[0]), + ]; + } + + /** + * @param array $old + * @param array $new + * @param array $timestampFields + */ + private function isAllowedCatalogChange(array $old, array $new, array $timestampFields): bool { + if (!$this->isAllowedEntriesChange($old, $new, [], ['/DSS', '/Extensions', '/Version', '/AcroForm'], $timestampFields)) { + return false; + } + if (($old['/AcroForm'] ?? null) === ($new['/AcroForm'] ?? null)) { + return true; + } + + $oldAcroForm = $this->parseDictionaryEntries($old['/AcroForm'] ?? '<<>>'); + $newAcroForm = $this->parseDictionaryEntries($new['/AcroForm'] ?? ''); + return $oldAcroForm !== null + && $newAcroForm !== null + && $this->isAllowedAcroFormChange($oldAcroForm, $newAcroForm, $timestampFields); + } + + /** + * @param array $old + * @param array $new + * @param array $timestampFields + */ + private function isAllowedAcroFormChange(array $old, array $new, array $timestampFields): bool { + return $this->isAllowedEntriesChange($old, $new, ['/Fields'], ['/SigFlags'], $timestampFields); + } + + /** + * @param array $old + * @param array $new + * @param list $appendOnlyKeys Keys whose array may only gain timestamp fields + * @param list $freeKeys Keys whose value may change freely (checked elsewhere if needed) + * @param array $timestampFields References to the new timestamp fields + */ + private function isAllowedEntriesChange(array $old, array $new, array $appendOnlyKeys, array $freeKeys, array $timestampFields): bool { + foreach (array_keys($old + $new) as $key) { + $oldValue = $old[$key] ?? null; + $newValue = $new[$key] ?? null; + if ($oldValue === $newValue || in_array($key, $freeKeys, true)) { + continue; + } + if (!in_array($key, $appendOnlyKeys, true) || $newValue === null + || !$this->isTimestampFieldAppend($oldValue ?? '[]', $newValue, $timestampFields)) { + return false; + } + } + return true; + } + + /** + * An array of references that keeps every old entry and only gains + * references to the new timestamp fields. + * + * @param array $timestampFields + */ + private function isTimestampFieldAppend(string $old, string $new, array $timestampFields): bool { + $oldRefs = $this->parseReferenceArray($old); + $newRefs = $this->parseReferenceArray($new); + if ($oldRefs === null || $newRefs === null || array_slice($newRefs, 0, count($oldRefs)) !== $oldRefs) { + return false; + } + + foreach (array_slice($newRefs, count($oldRefs)) as $ref) { + if (!isset($timestampFields[$ref])) { + return false; + } + } + return true; + } + + /** + * @return list|null References like "5 0 R", or null when the value is not an array of references only + */ + private function parseReferenceArray(string $canonicalArray): ?array { + if (!preg_match('/^\[((?:\d+ \d+ R ?)*)\]$/', $canonicalArray, $match)) { + return null; + } + preg_match_all('/\d+ \d+ R/', $match[1], $refs); + return $refs[0]; + } + + /** + * Top-level entries of a PDF dictionary, each value in canonical form. + * + * @return array|null Null when the object is not a dictionary + */ + private function parseDictionaryEntries(string $object): ?array { + $pos = 0; + $this->skipPdfWhitespace($object, $pos); + if (substr($object, $pos, 2) !== '<<') { + return null; + } + return $this->readPdfDictionary($object, $pos, 0); + } + + /** + * @return array|null Null on malformed input or a duplicate key + */ + private function readPdfDictionary(string $pdf, int &$pos, int $depth): ?array { + if ($depth > self::MAX_NESTING_DEPTH) { + return null; + } + $pos += 2; + $entries = []; + while (true) { + $this->skipPdfWhitespace($pdf, $pos); + if ($pos >= strlen($pdf) || $pdf[$pos] !== '/') { + if (substr($pdf, $pos, 2) !== '>>') { + return null; + } + $pos += 2; + return $entries; + } + $key = $this->readPdfValue($pdf, $pos, $depth + 1); + $value = $this->readPdfValue($pdf, $pos, $depth + 1); + if ($key === null || $value === null || isset($entries[$key])) { + return null; + } + $entries[$key] = $value; + } + } + + /** + * Read one PDF object at $pos and return it in a canonical form: single + * spaces between tokens, dictionary keys sorted, names with #xx escapes + * decoded and strings compared by their bytes, so a rewritten but + * unchanged object compares equal regardless of the writer's formatting. + */ + private function readPdfValue(string $pdf, int &$pos, int $depth): ?string { + if ($depth > self::MAX_NESTING_DEPTH) { + return null; + } + $this->skipPdfWhitespace($pdf, $pos); + $length = strlen($pdf); + if ($pos >= $length) { + return null; + } + + if (substr($pdf, $pos, 2) === '<<') { + $entries = $this->readPdfDictionary($pdf, $pos, $depth + 1); + if ($entries === null) { + return null; + } + ksort($entries); + $parts = []; + foreach ($entries as $key => $value) { + $parts[] = $key . ' ' . $value; + } + return '<<' . implode(' ', $parts) . '>>'; + } + + $char = $pdf[$pos]; + if ($char === '[') { + $pos++; + $items = []; + while (true) { + $this->skipPdfWhitespace($pdf, $pos); + if ($pos >= $length) { + return null; + } + if ($pdf[$pos] === ']') { + $pos++; + return '[' . implode(' ', $items) . ']'; + } + $item = $this->readPdfValue($pdf, $pos, $depth + 1); + if ($item === null) { + return null; + } + $items[] = $item; + } + } + + if ($char === '(') { + $bytes = ''; + $nesting = 0; + for (; $pos < $length; $pos++) { + $current = $pdf[$pos]; + if ($current === '\\') { + $next = $pdf[++$pos] ?? ''; + if (preg_match('/\G[0-7]{1,3}/', $pdf, $octal, 0, $pos)) { + $bytes .= chr((int)octdec($octal[0]) & 0xff); + $pos += strlen($octal[0]) - 1; + } elseif ($next === "\r" && ($pdf[$pos + 1] ?? '') === "\n") { + $pos++; + } elseif ($next !== "\r" && $next !== "\n") { + $bytes .= strtr($next, 'nrtbf', "\n\r\t\x08\x0c"); + } + continue; + } + if ($current === '(' && $nesting++ === 0) { + continue; + } + if ($current === ')' && --$nesting === 0) { + $pos++; + return '<' . bin2hex($bytes) . '>'; + } + $bytes .= $current; + } + return null; + } + + if ($char === '<') { + $end = strpos($pdf, '>', $pos); + if ($end === false) { + return null; + } + $hex = strtolower((string)preg_replace('/\s+/', '', substr($pdf, $pos + 1, $end - $pos - 1))); + if (!ctype_xdigit($hex) && $hex !== '') { + return null; + } + $pos = $end + 1; + return '<' . $hex . (strlen($hex) % 2 === 1 ? '0' : '') . '>'; + } + + if (!preg_match('/\G\/?[^\x00\t\n\x0c\r ()<>\[\]{}\/%]*/', $pdf, $token, 0, $pos) || $token[0] === '') { + return null; + } + $pos += strlen($token[0]); + + if ($char === '/') { + return $this->canonicalName(substr($token[0], 1)); + } + + if (ctype_digit($token[0]) && preg_match('/\G\s+(\d+)\s+R(?![^\x00\t\n\x0c\r ()<>\[\]{}\/%])/', $pdf, $ref, 0, $pos)) { + $pos += strlen($ref[0]); + return $token[0] . ' ' . $ref[1] . ' R'; + } + + return $token[0]; + } + + /** + * Name with #xx escapes decoded, then re-escaped only where needed, so + * /ObjStm and /Obj#53tm compare equal. + */ + private function canonicalName(string $name): string { + $decoded = (string)preg_replace_callback( + '/#([0-9A-Fa-f]{2})/', + static fn (array $match): string => chr((int)hexdec($match[1])), + $name, + ); + return '/' . (string)preg_replace_callback( + '/[^\x21-\x7e]|[#()<>\[\]{}\/%]/', + static fn (array $match): string => sprintf('#%02X', ord($match[0])), + $decoded, + ); + } + + private function skipPdfWhitespace(string $pdf, int &$pos): void { + $length = strlen($pdf); + while ($pos < $length) { + if (str_contains("\x00\t\n\x0c\r ", $pdf[$pos])) { + $pos++; + } elseif ($pdf[$pos] === '%') { + $pos += strcspn($pdf, "\r\n", $pos); + } else { + return; + } + } + } + /** * ISO 32000-1 12.8.2.2.1: A document can contain only one signature field that contains a DocMDP transform method */ diff --git a/tests/php/Integration/Handler/DocMdpHandlerValidationDataTest.php b/tests/php/Integration/Handler/DocMdpHandlerValidationDataTest.php new file mode 100644 index 0000000000..ba7d78855a --- /dev/null +++ b/tests/php/Integration/Handler/DocMdpHandlerValidationDataTest.php @@ -0,0 +1,383 @@ +cleanupPaths as $path) { + if (is_file($path)) { + unlink($path); + } + } + parent::tearDown(); + } + + public function testDssAddedAfterP1CertificationIsAllowed(): void { + $signed = $this->signCertified(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); + $withDss = $this->appendIncrementalUpdate($signed, $this->dssObjects($signed)); + + $result = $this->extractDocMdpData($withDss); + + $this->assertSame(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED->value, $result['docmdp']['level']); + $this->assertTrue($result['modifications']['modified']); + $this->assertTrue($result['modification_validation']['valid'], $result['modification_validation']['message']); + $this->assertSame(LibreSignFile::MODIFICATION_ALLOWED, $result['modification_validation']['status']); + $this->assertSignatureStillValid($withDss); + } + + public function testContentChangeNextToDssAfterP1CertificationIsRejected(): void { + $signed = $this->signCertified(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); + $this->assertSame(1, preg_match('/\/Contents\s+(\d+)\s+0\s+R/', $signed, $contentRef)); + $changedText = 'Changed after certification!!'; + $objects = $this->dssObjects($signed); + $objects[(int)$contentRef[1]] = '<< /Length ' . strlen($changedText) . " >>\nstream\n{$changedText}\nendstream"; + $tampered = $this->appendIncrementalUpdate($signed, $objects); + + $result = $this->extractDocMdpData($tampered); + + $this->assertFalse($result['modification_validation']['valid']); + $this->assertSame(LibreSignFile::MODIFICATION_VIOLATION, $result['modification_validation']['status']); + } + + public static function forgeryProvider(): array { + return [ + 'trailer /Root replaced by a new catalog and page tree' => ['rootSwap'], + 'comment between generation and obj keyword' => ['commentObj'], + 'redefinition swallowed by an unterminated stream' => ['swallow'], + 'visible signature field with a non-timestamp value' => ['visibleField'], + 'duplicate /Pages key in the catalog' => ['duplicateKey'], + 'object stream behind a name escape' => ['objStmEscape'], + ]; + } + + /** + * Forged updates that look like validation data to a lenient reader must + * stay DocMDP violations. + */ + #[DataProvider('forgeryProvider')] + public function testForgedUpdateAfterP1CertificationIsRejected(string $forgery): void { + $signed = $this->signCertified(DocMdpLevel::CERTIFIED_NO_CHANGES_ALLOWED); + $this->assertGreaterThan(0, preg_match_all('/\/Size\s+(\d+)/', $signed, $size)); + $n = (int)end($size[1]) + 10; + $this->assertSame(1, preg_match('/\/Contents\s+(\d+)\s+0\s+R/', $signed, $contentRef)); + $contentNum = (int)$contentRef[1]; + $rootNum = $this->rootNumber($signed); + $text = 'BT /F1 24 Tf 72 720 Td (Forged) Tj ET'; + $forged = '<< /Length ' . strlen($text) . " >>\nstream\n{$text}\nendstream"; + $newPageTree = [ + $n + 1 => '<< /Type /Pages /Kids [' . ($n + 2) . ' 0 R] /Count 1 >>', + $n + 2 => '<< /Type /Page /Parent ' . ($n + 1) . ' 0 R /MediaBox [0 0 612 792] /Contents ' . ($n + 3) . ' 0 R >>', + $n + 3 => $forged, + ]; + + $pdf = match ($forgery) { + 'rootSwap' => (string)preg_replace( + '/\/Root\s+\d+\s+0\s+R(?=[^\/]*\/Prev[^%]*%%EOF\n$)/', + "/Root {$n} 0 R", + $this->appendIncrementalUpdate($signed, [$n => '<< /Type /Catalog /Pages ' . ($n + 1) . ' 0 R >>'] + $newPageTree), + ), + 'commentObj' => $this->appendIncrementalUpdate($signed, [$n => '<< /Type /DSS >>', $contentNum => $forged], [$contentNum => "{$contentNum} 0 %x\nobj"]), + 'swallow' => $this->appendSwallowedRedefinition($signed, $n, $contentNum, $forged), + 'visibleField' => $this->appendIncrementalUpdate($signed, $this->visibleFieldObjects($signed, $n)), + 'duplicateKey' => $this->appendIncrementalUpdate($signed, [ + $rootNum => substr_replace($this->latestObject($signed, $rootNum), '/Pages ' . ($n + 1) . ' 0 R>>', (int)strrpos($this->latestObject($signed, $rootNum), '>>'), 2), + ] + $newPageTree), + 'objStmEscape' => $this->appendIncrementalUpdate($signed, [$n => "<< /Type /Obj#53tm /N 0 /First 0 /Length 0 >>\nstream\n\nendstream"]), + }; + + $result = $this->extractDocMdpData($pdf); + + $this->assertFalse($result['modification_validation']['valid'], $forgery); + $this->assertSame(LibreSignFile::MODIFICATION_VIOLATION, $result['modification_validation']['status']); + } + + /** + * A visible full-page signature field whose value is an approval signature + * without /Type, appended to the page and the AcroForm. + * + * @return array + */ + private function visibleFieldObjects(string $signed, int $n): array { + $appearance = '0 0 0 rg BT /F1 24 Tf 72 720 Td (Forged overlay) Tj ET'; + $pageNum = 3; + $page = $this->latestObject($signed, $pageNum); + $catalog = $this->latestObject($signed, $this->rootNumber($signed)); + $this->assertSame(1, preg_match('/\/AcroForm\s+(\d+)\s+0\s+R/', $catalog, $acroFormRef)); + $acroFormNum = (int)$acroFormRef[1]; + + return [ + $n => "<< /FT /Sig /Type /Annot /Subtype /Widget /T (TS1) /Rect [0 0 612 792] /F 4 /P {$pageNum} 0 R /AP << /N " . ($n + 1) . ' 0 R >> /V ' . ($n + 2) . ' 0 R >>', + $n + 1 => '<< /Type /XObject /Subtype /Form /BBox [0 0 612 792] /Length ' . strlen($appearance) . " >>\nstream\n{$appearance}\nendstream", + $n + 2 => '<< /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange [0 0 0 0] /Contents <00> >>', + $pageNum => (string)preg_replace('/\/Annots\s*\[([^\]]*)\]/', "/Annots [\$1 {$n} 0 R]", $page), + $acroFormNum => (string)preg_replace('/\/Fields\s*\[([^\]]*)\]/', "/Fields [\$1 {$n} 0 R]", $this->latestObject($signed, $acroFormNum)), + ]; + } + + /** + * An unterminated stream object hides the redefinition from a + * regex-based object scan, while the xref points at it. + */ + private function appendSwallowedRedefinition(string $signed, int $n, int $contentNum, string $forged): string { + $this->assertGreaterThan(0, preg_match_all('/startxref\s+(\d+)/', $signed, $startxref)); + $update = "\n{$n} 0 obj\n<< /Length 0 >>\nstream\n"; + $offset = strlen($signed) + strlen($update); + $update .= "{$contentNum} 0 obj\n{$forged}\nendobj\n"; + $xrefOffset = strlen($signed) + strlen($update); + $update .= "xref\n{$contentNum} 1\n" . sprintf("%010d 00000 n \n", $offset) + . "trailer\n<< /Size " . ($n + 1) . ' /Root ' . $this->rootNumber($signed) . ' 0 R /Prev ' . end($startxref[1]) . " >>\n" + . "startxref\n{$xrefOffset}\n%%EOF\n"; + return $signed . $update; + } + + private function latestObject(string $pdf, int $number): string { + $this->assertGreaterThan(0, preg_match_all('/(?assertGreaterThan(0, preg_match_all('/\/Root\s+(\d+)\s+0\s+R/', $pdf, $root)); + return (int)end($root[1]); + } + + private function extractDocMdpData(string $pdf): array { + $resource = $this->resource($pdf); + $result = \OCP\Server::get(DocMdpHandler::class)->extractDocMdpData($resource); + fclose($resource); + return $result; + } + + private function assertSignatureStillValid(string $pdf): void { + $validationService = new PdfSignatureValidationService( + $this->getMockAppConfigWithReset(), + \OCP\Server::get(IL10NFactory::class)->get(Application::APP_ID), + \OCP\Server::get(LoggerInterface::class), + ); + $resource = $this->resource($pdf); + $entries = $validationService->validateFromResource($resource); + fclose($resource); + + $this->assertCount(1, $entries); + $this->assertTrue( + $entries[0]['signatureValidation']['isValid'] ?? false, + 'the certification signature must stay valid: ' . ($entries[0]['signatureValidation']['reason'] ?? 'n/a'), + ); + } + + /** + * DSS dictionary holding the throwaway CA certificate, the latest catalog + * with /DSS and /Version added, and the document information dictionary + * rewritten the way LTV tools do it (strings re-encoded, new /ModDate and + * /Producer). + * + * @return array object number => object body + */ + private function dssObjects(string $pdf): array { + $this->assertGreaterThan(0, preg_match_all('/\/Size\s+(\d+)/', $pdf, $size)); + $certObject = (int)end($size[1]); + $dssObject = $certObject + 1; + + $this->assertGreaterThan(0, preg_match_all('/\/Root\s+(\d+)\s+0\s+R/', $pdf, $root)); + $catalogObject = (int)end($root[1]); + $this->assertGreaterThan(0, preg_match_all('/(?>", (int)strrpos($catalog, '>>'), 2); + + $this->assertGreaterThan(0, preg_match_all('/\/Info\s+(\d+)\s+0\s+R/', $pdf, $info)); + $infoObject = (int)end($info[1]); + $this->assertGreaterThan(0, preg_match_all('/(?assertStringContainsString('(D\\072', $infoDict); + + $this->assertSame(1, preg_match('/-----BEGIN CERTIFICATE-----(.+)-----END CERTIFICATE-----/s', $this->caCertificate, $pem)); + $der = (string)base64_decode($pem[1]); + + return [ + $catalogObject => $catalog, + $infoObject => $infoDict, + $certObject => '<< /Length ' . strlen($der) . " >>\nstream\n{$der}\nendstream", + $dssObject => "<< /Type /DSS /Certs [{$certObject} 0 R] >>", + ]; + } + + /** + * @param array $objects object number => object body + * @param array $headers object number => header replacing "N 0 obj" + */ + private function appendIncrementalUpdate(string $pdf, array $objects, array $headers = []): string { + $this->assertGreaterThan(0, preg_match_all('/startxref\s+(\d+)/', $pdf, $startxref)); + $this->assertGreaterThan(0, preg_match_all('/\/Size\s+(\d+)/', $pdf, $size)); + $this->assertGreaterThan(0, preg_match_all('/\/Root\s+(\d+\s+\d+\s+R)/', $pdf, $root)); + + ksort($objects); + $update = ''; + $offsets = []; + foreach ($objects as $number => $body) { + $offsets[$number] = strlen($pdf) + strlen($update); + $header = $headers[$number] ?? "{$number} 0 obj"; + $update .= "{$header}\n{$body}\nendobj\n"; + } + + $xrefOffset = strlen($pdf) + strlen($update); + $update .= "xref\n"; + foreach ($offsets as $number => $offset) { + $update .= "{$number} 1\n" . sprintf("%010d 00000 n \n", $offset); + } + $newSize = max((int)end($size[1]), max(array_keys($objects)) + 1); + $update .= "trailer\n<< /Size {$newSize} /Root " . end($root[1]) . ' /Prev ' . end($startxref[1]) . " >>\n"; + $update .= "startxref\n{$xrefOffset}\n%%EOF\n"; + + return $pdf . $update; + } + + private function signCertified(DocMdpLevel $level): string { + $docMdpConfig = $this->createMock(ConfigService::class); + $docMdpConfig->method('isEnabled')->willReturn(true); + $docMdpConfig->method('getLevel')->willReturn($level); + + $certificateEngineFactory = $this->createMock(CertificateEngineFactory::class); + $certificateEngineFactory->method('getEngine')->willReturn($this->createMock(IEngineHandler::class)); + + $handler = new PhpNativeHandler( + $this->getMockAppConfigWithReset(), + $docMdpConfig, + \OCP\Server::get(\OCA\Libresign\Service\SignatureTextService::class), + \OCP\Server::get(\OCA\Libresign\Service\SignatureStampPreview\SignatureStampAppearanceBuilder::class), + \OCP\Server::get(\OCA\Libresign\Service\SignatureBackgroundService::class), + \OCP\Server::get(\OCA\Libresign\Service\Policy\PolicyService::class), + $certificateEngineFactory, + ); + + $content = $this->simplePdf(); + $node = $this->createMock(File::class); + $node->method('getContent')->willReturnCallback(static fn (): string => $content); + + $identity = $this->generatePkcs12(); + $handler->setInputFile($node) + ->setCertificate($identity['pfx']) + ->setPassword($identity['password']); + + return $handler->getSignedContent(); + } + + /** + * Throwaway CA and signing certificate, generated per test. + * + * @return array{pfx: string, password: string} + */ + private function generatePkcs12(): array { + $configPath = $this->tempPath(<<< 'OPENSSL' + [ req ] + distinguished_name = req_distinguished_name + [ req_distinguished_name ] + [ v3_ca ] + basicConstraints = critical,CA:TRUE + keyUsage = keyCertSign, cRLSign + [ signing_cert ] + basicConstraints = CA:FALSE + keyUsage = critical, digitalSignature, nonRepudiation + OPENSSL); + $configArgs = ['config' => $configPath, 'digest_alg' => 'sha256']; + $keyOptions = ['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]; + + $caKey = openssl_pkey_new($keyOptions); + $this->assertNotFalse($caKey); + $caCsr = openssl_csr_new(['commonName' => 'DocMDP Test Root'], $caKey, $configArgs); + $this->assertNotFalse($caCsr); + $caCert = openssl_csr_sign($caCsr, null, $caKey, 1, $configArgs + ['x509_extensions' => 'v3_ca'], random_int(1, 0x7fffffff)); + $this->assertNotFalse($caCert); + $this->assertTrue(openssl_x509_export($caCert, $this->caCertificate)); + + $leafKey = openssl_pkey_new($keyOptions); + $this->assertNotFalse($leafKey); + $leafCsr = openssl_csr_new(['commonName' => 'DocMDP Test Signer'], $leafKey, $configArgs); + $this->assertNotFalse($leafCsr); + $leafCert = openssl_csr_sign($leafCsr, $caCert, $caKey, 1, $configArgs + ['x509_extensions' => 'signing_cert'], random_int(1, 0x7fffffff)); + $this->assertNotFalse($leafCert); + + $password = bin2hex(random_bytes(8)); + $this->assertTrue(openssl_pkcs12_export($leafCert, $pfx, $leafKey, $password, ['extra_certs' => [$caCert]])); + + return ['pfx' => $pfx, 'password' => $password]; + } + + private function simplePdf(): string { + $text = 'BT /F1 12 Tf 72 720 Td (Certified content) Tj ET'; + $objects = [ + 1 => '<< /Type /Catalog /Pages 2 0 R >>', + 2 => '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', + 3 => '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>', + 4 => '<< /Length ' . strlen($text) . " >>\nstream\n{$text}\nendstream", + ]; + + $pdf = "%PDF-1.7\n"; + $offsets = []; + foreach ($objects as $number => $body) { + $offsets[$number] = strlen($pdf); + $pdf .= "{$number} 0 obj\n{$body}\nendobj\n"; + } + $xrefOffset = strlen($pdf); + $pdf .= "xref\n0 " . (count($objects) + 1) . "\n0000000000 65535 f \n"; + foreach ($offsets as $offset) { + $pdf .= sprintf("%010d 00000 n \n", $offset); + } + $pdf .= "trailer\n<< /Size " . (count($objects) + 1) . " /Root 1 0 R >>\nstartxref\n{$xrefOffset}\n%%EOF\n"; + + return $pdf; + } + + /** + * @return resource + */ + private function resource(string $content) { + $resource = fopen('php://memory', 'r+'); + $this->assertNotFalse($resource); + fwrite($resource, $content); + rewind($resource); + return $resource; + } + + private function tempPath(string $content): string { + $path = tempnam(sys_get_temp_dir(), 'libresign-docmdp-'); + $this->assertNotFalse($path); + $this->cleanupPaths[] = $path; + file_put_contents($path, $content); + return $path; + } +} diff --git a/tests/php/Unit/Handler/DocMdpHandlerTest.php b/tests/php/Unit/Handler/DocMdpHandlerTest.php index 24bd3c0295..b4aed9f5a1 100644 --- a/tests/php/Unit/Handler/DocMdpHandlerTest.php +++ b/tests/php/Unit/Handler/DocMdpHandlerTest.php @@ -370,6 +370,154 @@ public function testAdditionalSignaturesBasedOnDocMdpLevel(string|int $level, bo $this->assertSame($expectedAllowed, $result); } + /** @return array */ + private static function dssUpdate(): array { + return [ + 10 => "<< /Length 4 >>\nstream\n0000\nendstream", + 11 => '<< /Type /DSS /Certs [10 0 R] /OCSPs [] /CRLs [] >>', + // Same catalog rewritten by another writer, plus /DSS, /Extensions and /Version. + 1 => '<>/DSS 11 0 R' + . '/Extensions<>>>/Version/1.7>>', + // Information dictionary rewritten: strings re-encoded, new /ModDate and /Producer. + 7 => '<< /Producer (Generator\073 LTV) /ModDate <443a32303236303230323030303030305a> >>', + ]; + } + + /** @return array */ + private static function timestampUpdate(string $field = '/FT /Sig /T (Timestamp1) /Type /Annot /Subtype /Widget /F 132 /Rect [0 0 0 0] /P 3 0 R /V 12 0 R'): array { + return [ + 12 => '<< /Type /DocTimeStamp /Filter /Adobe.PPKLite /SubFilter /ETSI.RFC3161 /ByteRange [0 10 20 10] /Contents <00> >>', + 13 => "<< {$field} >>", + 3 => '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [13 0 R] >>', + 4 => '<< /SigFlags 3 /Fields [6 0 R 13 0 R] >>', + ]; + } + + public static function validationDataUpdateProvider(): array { + return [ + 'P=1 DSS' => [1, [self::dssUpdate()]], + 'P=2 DSS' => [2, [self::dssUpdate()]], + 'P=3 DSS' => [3, [self::dssUpdate()]], + 'P=1 document timestamp' => [1, [self::timestampUpdate()]], + 'P=1 DSS and document timestamp in one update' => [1, [self::dssUpdate() + self::timestampUpdate()]], + 'P=1 document timestamp, then DSS' => [1, [self::timestampUpdate(), self::dssUpdate()]], + ]; + } + + /** + * ISO 32000-2 12.8.2.2.1 / ETSI EN 319 142-1 5.4: adding a DSS or a document + * timestamp after certification is allowed at every DocMDP level. + */ + #[DataProvider('validationDataUpdateProvider')] + public function testValidationDataUpdateAfterCertificationIsAllowed(int $pValue, array $updates): void { + $result = $this->extractFromUpdates($pValue, $updates); + + $this->assertSame($pValue, $result['docmdp']['level']); + $this->assertTrue($result['modifications']['modified']); + $this->assertTrue($result['modification_validation']['valid']); + $this->assertSame(File::MODIFICATION_ALLOWED, $result['modification_validation']['status']); + } + + public static function contentChangeWithValidationDataProvider(): array { + $timestampField = '/FT /Sig /T (Timestamp1) /Type /Annot /Subtype /Widget /F 132 /Rect [0 0 0 0] /P 3 0 R /V 12 0 R'; + return [ + 'page content added' => [[self::dssUpdate() + [ + 20 => "<< /Length 18 >>\nstream\nBT (changed) Tj ET\nendstream", + 3 => '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 20 0 R >>', + ]]], + 'catalog action added' => [[[ + 10 => '<< /Type /DSS >>', + 1 => '<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R /Perms << /DocMDP 5 0 R >> /DSS 10 0 R /OpenAction 3 0 R >>', + ]]], + 'duplicate catalog key' => [[[ + 10 => '<< /Type /DSS >>', + 1 => '<< /Type /Catalog /Pages 2 0 R /Pages 20 0 R /AcroForm 4 0 R /Perms << /DocMDP 5 0 R >> /DSS 10 0 R >>', + ]]], + 'information dictionary title changed' => [[[7 => '<< /Producer (Generator) /ModDate (D:20260101000000Z) /Title (Changed) >>']]], + 'pages tree rewritten' => [[[2 => '<< /Type /Pages /Kids [3 0 R 20 0 R] /Count 2 >>', 20 => '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>']]], + 'text annotation added' => [[self::dssUpdate() + [ + 20 => '<< /Type /Annot /Subtype /Text /Rect [100 100 200 200] >>', + 3 => '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [20 0 R] >>', + ]]], + 'non-signature field appended' => [[self::dssUpdate() + [ + 20 => '<< /FT /Tx /T (Text1) /V (changed) >>', + 4 => '<< /SigFlags 3 /Fields [6 0 R 20 0 R] >>', + ]]], + 'existing field removed' => [[array_replace(self::timestampUpdate(), [4 => '<< /SigFlags 3 /Fields [13 0 R] >>'])]], + 'approval signature added' => [[self::dssUpdate() + [ + 20 => '<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /ETSI.CAdES.detached /ByteRange [0 10 20 10] /Contents <00> >>', + 21 => '<< /FT /Sig /T (Signature2) /V 20 0 R >>', + 4 => '<< /SigFlags 3 /Fields [6 0 R 21 0 R] >>', + ]]], + 'signature field value is not a document timestamp' => [[array_replace(self::timestampUpdate(), [ + 12 => '<< /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange [0 10 20 10] /Contents <00> >>', + ])]], + 'visible timestamp widget' => [[self::timestampUpdate(str_replace('[0 0 0 0]', '[0 0 612 792]', $timestampField))]], + 'timestamp field with an action' => [[self::timestampUpdate($timestampField . ' /AA << /F << /S /JavaScript /JS (x) >> >>')]], + 'timestamp field with kids' => [[self::timestampUpdate($timestampField . ' /Kids [3 0 R]')]], + 'object stream' => [[self::dssUpdate() + [20 => "<< /Type /ObjStm /N 1 /First 5 /Length 8 >>\nstream\n3 0 <<>>\nendstream"]]], + 'object stream behind a name escape' => [[self::dssUpdate() + [20 => "<< /Type /Obj#53tm /N 1 /First 5 /Length 8 >>\nstream\n3 0 <<>>\nendstream"]]], + ]; + } + + #[DataProvider('contentChangeWithValidationDataProvider')] + public function testP1RejectsContentChangeAlongsideValidationData(array $updates): void { + $result = $this->extractFromUpdates(1, $updates); + + $this->assertFalse($result['modification_validation']['valid']); + $this->assertSame(File::MODIFICATION_VIOLATION, $result['modification_validation']['status']); + } + + public static function forgedTrailerProvider(): array { + return [ + 'root replaced' => [['/Root' => '20 0 R']], + 'information dictionary replaced' => [['/Info' => '20 0 R']], + 'encryption added' => [['/Encrypt' => '20 0 R']], + 'previous section skipped' => [['/Prev' => '0']], + ]; + } + + #[DataProvider('forgedTrailerProvider')] + public function testP1RejectsValidationDataUpdateWithForgedTrailer(array $trailerOverrides): void { + $update = self::dssUpdate() + [20 => '<< /Type /Catalog /Pages 2 0 R >>']; + $result = $this->extractFromUpdates(1, [$update], $trailerOverrides); + + $this->assertFalse($result['modification_validation']['valid']); + } + + public function testP1RejectsObjectsOutsideTheUpdateXref(): void { + $pdf = PdfGenerator::createCertifiedPdfWithIncrementalUpdates(1, [self::dssUpdate()]); + // An object the xref does not list still reaches readers that rebuild the xref. + $pos = strrpos($pdf, "xref\n"); + $pdf = substr($pdf, 0, $pos) . "2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n" . substr($pdf, $pos); + + $result = $this->extractFromContent($pdf); + + $this->assertFalse($result['modification_validation']['valid']); + } + + public function testP1RejectsValidationDataInXrefStreamUpdate(): void { + $pdf = PdfGenerator::createCertifiedPdfWithIncrementalUpdates(1, [self::dssUpdate()]); + $pdf = substr($pdf, 0, strrpos($pdf, "xref\n")) + . "30 0 obj\n<< /Type /XRef /Size 31 /Root 1 0 R /W [1 4 1] /Length 0 >>\nstream\n\nendstream\nendobj\n" + . "startxref\n" . strlen($pdf) . "\n%%EOF\n"; + + $result = $this->extractFromContent($pdf); + + $this->assertFalse($result['modification_validation']['valid']); + } + + private function extractFromUpdates(int $pValue, array $updates, array $trailerOverrides = []): array { + return $this->extractFromContent(PdfGenerator::createCertifiedPdfWithIncrementalUpdates($pValue, $updates, $trailerOverrides)); + } + + private function extractFromContent(string $pdfContent): array { + $resource = PdfGenerator::createResourceFromContent($pdfContent); + $result = $this->handler->extractDocMdpData($resource); + fclose($resource); + return $result; + } + public function testRealJSignPdfWithDocMdpLevel1(): void { $pdfPath = __DIR__ . '/../../fixtures/pdfs/real_jsignpdf_level1.pdf'; diff --git a/tests/php/fixtures/PdfGenerator.php b/tests/php/fixtures/PdfGenerator.php index f5790c64a7..67c5c8efa3 100644 --- a/tests/php/fixtures/PdfGenerator.php +++ b/tests/php/fixtures/PdfGenerator.php @@ -55,6 +55,77 @@ public static function createPdfWithDocMdp(int $pValue, bool $withModifications return $pdf; } + /** + * Certified PDF with classic xref tables: objects 1-7 (catalog, pages, + * page, AcroForm, signature, signature field, information dictionary, + * /Size 8), followed by one incremental update per entry of $updates + * (object number => object body). + * + * @param list> $updates + * @param array $trailerOverrides Entries replaced (or removed with null) in the trailers of the updates + */ + public static function createCertifiedPdfWithIncrementalUpdates(int $pValue, array $updates, array $trailerOverrides = []): string { + $byteRangePlaceholder = str_repeat('#', 32); + $objects = [ + 1 => '<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R /Perms << /DocMDP 5 0 R >> >>', + 2 => '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', + 3 => '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>', + 4 => '<< /SigFlags 3 /Fields [6 0 R] >>', + 5 => "<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /ETSI.CAdES.detached\n" + . "/ByteRange [ 0 {$byteRangePlaceholder} ]\n" + . "/Reference [ << /Type /SigRef /TransformMethod /DocMDP\n" + . "/TransformParams << /Type /TransformParams /P {$pValue} /V /1.2 >> >> ]\n" + . '/Contents <' . str_repeat('00', 50) . '> >>', + 6 => '<< /FT /Sig /T (Signature1) /V 5 0 R >>', + 7 => '<< /Producer (Generator) /ModDate (D:20260101000000Z) >>', + ]; + + $pdf = "%PDF-1.7\n"; + $offsets = []; + foreach ($objects as $number => $body) { + $offsets[$number] = strlen($pdf); + $pdf .= "{$number} 0 obj\n{$body}\nendobj\n"; + } + $xrefOffset = strlen($pdf); + $pdf .= "xref\n0 8\n0000000000 65535 f \n"; + foreach ($offsets as $offset) { + $pdf .= sprintf("%010d 00000 n \n", $offset); + } + $pdf .= "trailer\n<< /Size 8 /Root 1 0 R /Info 7 0 R >>\nstartxref\n{$xrefOffset}\n%%EOF\n"; + + $contentsStart = (int)strpos($pdf, '/Contents <', $offsets[5]) + strlen('/Contents '); + $contentsEnd = (int)strpos($pdf, '>', $contentsStart) + 1; + $byteRange = str_pad("{$contentsStart} {$contentsEnd} " . (strlen($pdf) - $contentsEnd), strlen($byteRangePlaceholder)); + $pdf = str_replace($byteRangePlaceholder, $byteRange, $pdf); + + $size = 8; + foreach ($updates as $updateObjects) { + $offsets = []; + foreach ($updateObjects as $number => $body) { + $offsets[$number] = strlen($pdf); + $pdf .= "{$number} 0 obj\n{$body}\nendobj\n"; + } + $previousXref = $xrefOffset; + $xrefOffset = strlen($pdf); + $pdf .= "xref\n0 1\n0000000000 65535 f \n"; + foreach ($offsets as $number => $offset) { + $pdf .= "{$number} 1\n" . sprintf("%010d 00000 n \n", $offset); + } + $size = max($size, max(array_keys($updateObjects)) + 1); + $trailer = array_filter(array_replace( + ['/Size' => (string)$size, '/Root' => '1 0 R', '/Info' => '7 0 R', '/Prev' => (string)$previousXref], + $trailerOverrides, + ), static fn (?string $value): bool => $value !== null); + $pdf .= "trailer\n<<"; + foreach ($trailer as $key => $value) { + $pdf .= " {$key} {$value}"; + } + $pdf .= " >>\nstartxref\n{$xrefOffset}\n%%EOF\n"; + } + + return $pdf; + } + public static function createPdfWithFormFieldModification(int $pValue): string { $pdf = "%PDF-1.7\n"; $pdf .= "1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R /Perms << /DocMDP 5 0 R >> >>\nendobj\n";