Skip to content

Initial findings #1

Closed
Closed

Description

@packdat

Running a few tests with the new version i encountered some shortcomings I'd like to point out.
The method i used for these tests is very simple:

        private bool VerifyPdfCanBeImported(string filePath)
        {
            try
            {
                var document = PdfReader.Open(filePath, PdfDocumentOpenMode.Import);
                var documentCopy = new PdfDocument();
                foreach (var page in document.Pages)
                {
                    documentCopy.AddPage(page);
                }
                documentCopy.Save(Path.Combine(Path.GetTempPath(), "out.pdf"));
                return true;
            }
            catch (Exception ex)
            {
                var message = string.Format("{0}:{1}{2}{1}{1}", filePath, Environment.NewLine, ex);
                Console.WriteLine(message);
            }
            return false;
        }
  1. FlateDecode skips PNG-Decoding
    Exception:
    PdfSharp.Pdf.IO.PdfReaderException: Unexpected token '' in PDF stream. The file may be corrupted. If you think this is a bug in PDFsharp, please send us your PDF file.
    (the token can be anything, it is not limited to an empty string)
    It seems there are only a few lines of code missing in method FlateDecode.Decode.
    Between msOutput.Flush() and return msOutput.GetBuffer() these lines are missing:

        if (msOutput.Length >= 0)
        {
            msOutput.Capacity = (int)msOutput.Length;
            if (parms?.DecodeParms != null)
                return StreamDecoder.Decode(msOutput.GetBuffer(), parms.DecodeParms);
        }
    

    These lines are present at the end of the file (in the #else block), as well as in LzwDecode.Decode
     
     

  2. Improper handling of encrypted object-streams
    Exception:
    System.IO.InvalidDataException: The archive entry was compressed using an unsupported compression method.
    This happens with encrypted documents containing object-streams (which are encrypted).
    When the parser encounters an object stream in the PDF, it immediately tries to extract the objects from the stream.
    Problem is, the object stream is still encrypted (decryption happens after all objects are read).
    When the object stream is flate-encoded, the decoder tries to deflate encrpyted data, leading to the mentioned exception.
    I was able to fix this by inserting the following lines at the beginning of PdfObjectStream.PdfObjectStream(PdfDictionary dict):

    	// while objects inside an object-stream are not encrypted, the object-streams themself ARE !
    	// 7.5.7, Page 47:
    	// In an encrypted file (i.e., entire object stream is encrypted),
    	// strings occurring anywhere in an object stream shall not be separately encrypted.
    	var xrefEncrypt = _document._trailer.Elements[PdfTrailer.Keys.Encrypt] as PdfReference;
    	if (xrefEncrypt != null && _document.SecurityHandler != null)
    		_document.SecurityHandler.DecryptObject(dict);
    

    The method PdfStandardSecurityHandler.DecryptObject had to be made internal for this to work.
    You also have to make sure, you're not decrypting the streams again when the whole document is decrypted.
    I simply used a flag in PdfStandardSecurityHandler and inserted the following code at the beginning of PdfStandardSecurityHandler.DecryptDictionary:

            // skip objects read from object streams (already done in PdfObjectStream.ctor())
            if (skipObjectStreams && (dict.Elements.GetName("/Type") == "/ObjStm" || dict.Reference != null && dict.Reference.Position < 0))
                return;    
    

    The flag skipObjectStreams is set in PdfStandardSecurityHandler.DecryptDocument.
     
     

  3. Improper calculation of decryption key (V5 R6)
    Exception:
    PdfSharp.Pdf.IO.PdfReaderException: The document seems to be not correctly encrypted. Could not verify P with Perms key.
    In class PdfEncryptionV5 the encryption key is not calculated correctly.
    In Method GetUserOwnerKeySalt there is this single line of code:

        return userOwnerValue.Skip(40).ToArray();
    

    The issue could be fixed by replacing it with this line:

        return userOwnerValue.Skip(40).Take(8).ToArray();
    
  4. Also encryption-related but merely a suggestion/question.
    Some documents i encountered (which are AES-encrypted) seem to be incompletely/incorrectly encrypted.
    When importing these documents, a CryptographicException is throw with the error message Padding is invalid and cannot be removed.
    Looking at the supposedly encrypted data as a hex-dump i realized, the data was in fact NOT encrypted (i.e. it contained readable text).
    I would therefore suggest surrounding the code in method DecryptForEnteredObject(ref byte[] bytes) (in classes PdfEncryptionV5 and PdfEncryptionV1To4) with a try -> catch -> ignore block.
    That would make documents exhibiting this issue readable.
    If there is something inherently wrong with the encryption of a document, the library will probably bail out somewhere else, but I'm not 100% sure about that as I've never encountered a document like that.

Attached is a zip containing a document for each point in this list for reproduction.
documents.zip

If it helps, i could create separate issues for each point as well as pull-requests.

Activity

  1. StLange commented on Apr 11, 2023

    @StLange
    Member

    Thank you for your excellent feedback, pull-requests are not necessary. We will come back to it very soon. This week we are still on Easter vacation.

  2. added
    bug
    on Apr 11, 2023
  3. StLange commented on Apr 27, 2023

    @StLange
    Member

    The bugs are fixed in Preview-2 that we published yesterday. We also ignore encryption errors caused by buggy PDF files as the default behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions