Debian Codegraph @

podofo/test/unit/EncryptTest.cpp

raw
1 // SPDX-FileCopyrightText: 2008 Dominik Seichter <[email protected]>
2 // SPDX-FileCopyrightText: 2021 Francesco Pretto <[email protected]>
3 // SPDX-License-Identifier: MIT-0
4
5 #include <PdfTest.h>
6 #include <podofo/private/PdfParser.h>
7 #include <podofo/private/OpenSSLInternal.h>
8
9 using namespace std;
10 using namespace PoDoFo;
11
12 static void testAuthenticate(PdfEncrypt& encrypt, PdfEncryptContext& context);
13 static void testEncrypt(PdfEncrypt& encrypt, PdfEncryptContext& context);
14 static void createEncryptedPdf(const string_view& filename);
15
16 charbuff s_encBuffer;
17 PdfPermissions s_protection;
18
19 constexpr string_view ReferenceHash_R_11_0("298ACCFDC32BB2BC32BFD580883219AB");
20
21 #define PDF_USER_PASSWORD "user"
22 #define PDF_OWNER_PASSWORD "podofo"
23
24 namespace PoDoFo
25 {
26 class PdfEncryptTest
27 {
28 public:
29 static void TestLoadEncrypedFilePdfParser();
30 };
31 }
32
33 namespace
34 {
35 struct Paths
36 {
37 Paths()
38 {
39 const char* buffer1 = "Somekind of drawing \001 buffer that possibly \003 could contain PDF drawing commands";
40 const char* buffer2 = " possibly could contain PDF drawing\003 commands";
41
42 size_t len = strlen(buffer1) + 2 * strlen(buffer2);
43 s_encBuffer.resize(len);
44
45 memcpy(s_encBuffer.data(), buffer1, strlen(buffer1) * sizeof(char));
46 memcpy(s_encBuffer.data() + strlen(buffer1), buffer2, strlen(buffer2));
47 memcpy(s_encBuffer.data() + strlen(buffer1) + strlen(buffer2), buffer2, strlen(buffer2));
48
49 s_protection = PdfPermissions::Print |
50 PdfPermissions::Edit |
51 PdfPermissions::Copy |
52 PdfPermissions::EditNotes |
53 PdfPermissions::FillAndSign |
54 PdfPermissions::Accessible |
55 PdfPermissions::DocAssembly |
56 PdfPermissions::HighPrint;
57 }
58 } s_init;
59 }
60
61 METHOD_AS_TEST_CASE(PdfEncryptTest::TestLoadEncrypedFilePdfParser, "TestLoadEncrypedFilePdfParser")
62
63 TEST_CASE("TestEncryptedPDFs")
64 {
65 charbuff buffer;
66 PdfMemDocument doc;
67 doc.Load(TestUtils::GetTestInputFilePath("TemplateClearText.pdf"));
68 doc.GetObjects().MustGetObject(PdfReference(11, 0)).MustGetStream().CopyTo(buffer);
69 REQUIRE(ssl::ComputeMD5Str(buffer) == ReferenceHash_R_11_0);
70
71 vector<string> testPaths = {
72 TestUtils::GetTestInputFilePath("RC4V2-40.pdf"),
73 TestUtils::GetTestInputFilePath("RC4V2-56.pdf"),
74 TestUtils::GetTestInputFilePath("RC4V2-80.pdf"),
75 TestUtils::GetTestInputFilePath("RC4V2-96.pdf"),
76 TestUtils::GetTestInputFilePath("RC4V2-128.pdf"),
77 TestUtils::GetTestInputFilePath("AESV2-128.pdf"),
78 TestUtils::GetTestInputFilePath("AESV3R6-256.pdf"),
79 TestUtils::GetTestInputFilePath("RC4V2-40_KeyLength41Violation.pdf"),
80 TestUtils::GetTestInputFilePath("RC4V2-56_KeyLength57Violation.pdf"),
81 TestUtils::GetTestInputFilePath("RC4V2-80_KeyLength81Violation.pdf"),
82 TestUtils::GetTestInputFilePath("RC4V2-96_KeyLength97Violation.pdf"),
83 TestUtils::GetTestInputFilePath("RC4V2-128_KeyLength129Violation.pdf"),
84 TestUtils::GetTestInputFilePath("AESV2-128_KeyLength129Violation.pdf"),
85 TestUtils::GetTestInputFilePath("AESV3R6-256_KeyLength257Violation.pdf"),
86 };
87
88 for (auto& path : testPaths)
89 {
90 doc.Load(path, "userpass");
91 doc.GetObjects().MustGetObject(PdfReference(11, 0)).MustGetStream().CopyTo(buffer);
92 REQUIRE(ssl::ComputeMD5Str(buffer) == ReferenceHash_R_11_0);
93
94 doc.Load(path, "ownerpass");
95 doc.GetObjects().MustGetObject(PdfReference(11, 0)).MustGetStream().CopyTo(buffer);
96 REQUIRE(ssl::ComputeMD5Str(buffer) == ReferenceHash_R_11_0);
97 }
98 }
99
100 TEST_CASE("TestEncryptDecryptPDFs")
101 {
102 PdfEncryptionAlgorithm algorithms[] = {
103 PdfEncryptionAlgorithm::RC4V2,
104 PdfEncryptionAlgorithm::RC4V2,
105 PdfEncryptionAlgorithm::RC4V2,
106 PdfEncryptionAlgorithm::RC4V2,
107 PdfEncryptionAlgorithm::RC4V2,
108 PdfEncryptionAlgorithm::AESV2,
109 PdfEncryptionAlgorithm::AESV3R6,
110 };
111
112 PdfKeyLength keyLengths[] = {
113 PdfKeyLength::L40,
114 PdfKeyLength::L56,
115 PdfKeyLength::L80,
116 PdfKeyLength::L96,
117 PdfKeyLength::L128,
118 PdfKeyLength::L128,
119 PdfKeyLength::L256,
120 };
121
122 charbuff pdfBuffer;
123 charbuff objBuffer;
124 PdfMemDocument doc;
125 for (unsigned i = 0; i < std::size(algorithms); i++)
126 {
127 doc.Load(TestUtils::GetTestInputFilePath("TemplateClearText.pdf"));
128 doc.SetEncrypted("userpass", "ownerpass", PdfPermissions::Default,
129 algorithms[i], keyLengths[i]);
130
131 pdfBuffer.clear();
132 BufferStreamDevice device(pdfBuffer);
133 doc.Save(device);
134
135 doc.LoadFromBuffer(pdfBuffer, "userpass");
136 doc.GetObjects().MustGetObject(PdfReference(11, 0)).MustGetStream().CopyTo(objBuffer);
137 REQUIRE(ssl::ComputeMD5Str(objBuffer) == ReferenceHash_R_11_0);
138
139 doc.LoadFromBuffer(pdfBuffer, "ownerpass");
140 doc.GetObjects().MustGetObject(PdfReference(11, 0)).MustGetStream().CopyTo(objBuffer);
141 REQUIRE(ssl::ComputeMD5Str(objBuffer) == ReferenceHash_R_11_0);
142 }
143 }
144
145 TEST_CASE("TestDefaultEncryption")
146 {
147 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD);
148
149 PdfEncryptContext context;
150 testAuthenticate(*encrypt, context);
151 testEncrypt(*encrypt, context);
152 }
153
154 TEST_CASE("TestRC4")
155 {
156 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
157 PdfEncryptionAlgorithm::RC4V1,
158 PdfKeyLength::L40);
159
160 PdfEncryptContext context;
161 testAuthenticate(*encrypt, context);
162 testEncrypt(*encrypt, context);
163 }
164
165 TEST_CASE("TestRC4v2_40")
166 {
167 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
168 PdfEncryptionAlgorithm::RC4V2,
169 PdfKeyLength::L40);
170
171 PdfEncryptContext context;
172 testAuthenticate(*encrypt, context);
173 testEncrypt(*encrypt, context);
174 }
175
176 TEST_CASE("TestRC4v2_56")
177 {
178 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
179 PdfEncryptionAlgorithm::RC4V2,
180 PdfKeyLength::L56);
181
182 PdfEncryptContext context;
183 testAuthenticate(*encrypt, context);
184 testEncrypt(*encrypt, context);
185 }
186
187 TEST_CASE("TestRC4v2_80")
188 {
189 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
190 PdfEncryptionAlgorithm::RC4V2,
191 PdfKeyLength::L80);
192
193 PdfEncryptContext context;
194 testAuthenticate(*encrypt, context);
195 testEncrypt(*encrypt, context);
196 }
197
198 TEST_CASE("TestRC4v2_96")
199 {
200 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
201 PdfEncryptionAlgorithm::RC4V2,
202 PdfKeyLength::L96);
203
204 PdfEncryptContext context;
205 testAuthenticate(*encrypt, context);
206 testEncrypt(*encrypt, context);
207 }
208
209 TEST_CASE("TestRC4v2_128")
210 {
211 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
212 PdfEncryptionAlgorithm::RC4V2,
213 PdfKeyLength::L128);
214
215 PdfEncryptContext context;
216 testAuthenticate(*encrypt, context);
217 testEncrypt(*encrypt, context);
218 }
219
220 TEST_CASE("TestAESV2")
221 {
222 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
223 PdfEncryptionAlgorithm::AESV2,
224 PdfKeyLength::L128);
225
226 PdfEncryptContext context;
227 testAuthenticate(*encrypt, context);
228 // AES decryption is not yet implemented.
229 // Therefore we have to disable this test.
230 //TestEncrypt(encrypt, context);
231 }
232
233 TEST_CASE("TestAESV3R5")
234 {
235 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
236 PdfEncryptionAlgorithm::AESV3R5,
237 PdfKeyLength::L256);
238
239 PdfEncryptContext context;
240 testAuthenticate(*encrypt, context);
241 // AES decryption is not yet implemented.
242 // Therefore we have to disable this test.
243 //TestEncrypt(encrypt, context);
244 }
245
246 TEST_CASE("TestAESV3R6")
247 {
248 auto encrypt = PdfEncrypt::Create(PDF_USER_PASSWORD, PDF_OWNER_PASSWORD, s_protection,
249 PdfEncryptionAlgorithm::AESV3R6,
250 PdfKeyLength::L256);
251
252 PdfEncryptContext context;
253 testAuthenticate(*encrypt, context);
254 // AES decryption is not yet implemented.
255 // Therefore we have to disable this test.
256 //TestEncrypt(encrypt, context);
257 }
258
259 TEST_CASE("TestEnableAlgorithms")
260 {
261 // By default every algorithms should be enabled
262 REQUIRE(PdfEncrypt::IsEncryptionEnabled(PdfEncryptionAlgorithm::RC4V1));
263 REQUIRE(PdfEncrypt::IsEncryptionEnabled(PdfEncryptionAlgorithm::RC4V2));
264 REQUIRE(PdfEncrypt::IsEncryptionEnabled(PdfEncryptionAlgorithm::AESV2));
265 REQUIRE(PdfEncrypt::IsEncryptionEnabled(PdfEncryptionAlgorithm::AESV3R5));
266 REQUIRE(PdfEncrypt::IsEncryptionEnabled(PdfEncryptionAlgorithm::AESV3R6));
267
268 PdfEncryptionAlgorithm testAlgorithms = PdfEncryptionAlgorithm::AESV2;
269 testAlgorithms |= PdfEncryptionAlgorithm::RC4V1 | PdfEncryptionAlgorithm::RC4V2;
270 testAlgorithms |= PdfEncryptionAlgorithm::AESV3R5 | PdfEncryptionAlgorithm::AESV3R6;;
271 REQUIRE(testAlgorithms == PdfEncrypt::GetEnabledEncryptionAlgorithms());
272 }
273
274 void PdfEncryptTest::TestLoadEncrypedFilePdfParser()
275 {
276 string tempFile = TestUtils::GetTestOutputFilePath("TestLoadEncrypedFilePdfParser.pdf");
277 createEncryptedPdf(tempFile);
278
279 auto device = std::make_shared<FileStreamDevice>(tempFile);
280 // Try loading with PdfParser
281 PdfIndirectObjectList objects;
282 PdfParser parser(objects);
283
284 try
285 {
286 parser.Parse(*device);
287
288 // Must throw an exception
289 FAIL("Encrypted file not recognized!");
290 }
291 catch (PdfError& e)
292 {
293 if (e.GetCode() != PdfErrorCode::InvalidPassword)
294 FAIL("Invalid encryption exception thrown!");
295 }
296
297 parser.SetPassword(PDF_USER_PASSWORD);
298 }
299
300 TEST_CASE("TestLoadEncrypedFilePdfMemDocument")
301 {
302 string tempFile = TestUtils::GetTestOutputFilePath("TestLoadEncrypedFilePdfMemDocument.pdf");
303 createEncryptedPdf(tempFile);
304
305 // Try loading with PdfParser
306 PdfMemDocument document;
307 try
308 {
309 document.Load(tempFile);
310
311 // Must throw an exception
312 FAIL("Encrypted file not recognized!");
313 }
314 catch (...)
315 {
316
317 }
318
319 document.Load(tempFile, PDF_USER_PASSWORD);
320 }
321
322 // Test a big encrypted content writing and reading
323 TEST_CASE("TestEncryptBigBuffer")
324 {
325 string tempFile = TestUtils::GetTestOutputFilePath("TestBigBuffer.pdf");
326 PdfReference bufferRef;
327
328 constexpr unsigned BufferSize = 100000;
329
330 {
331 // Create a document with a big enough buffer and ensure it won't
332 // be compressed, so the encryption will operate on a big buffer
333 PdfMemDocument doc;
334 (void)doc.GetPages().CreatePage(PdfPageSize::A4);
335 auto& obj = doc.GetObjects().CreateDictionaryObject();
336 {
337 vector<char> testBuff(BufferSize);
338 auto stream = obj.GetOrCreateStream().GetOutputStream(PdfFilterList());
339 stream.Write(testBuff.data(), testBuff.size());
340 }
341 bufferRef = obj.GetIndirectReference();
342 doc.GetCatalog().GetDictionary().AddKeyIndirect("TestBigBuffer"_n, obj);
343
344 doc.SetEncrypted(PDF_USER_PASSWORD, "owner");
345 doc.Save(tempFile, PdfSaveOptions::NoFlateCompress);
346 }
347
348 {
349 PdfMemDocument doc;
350 doc.Load(tempFile, PDF_USER_PASSWORD);
351 auto& obj = doc.GetObjects().MustGetObject(bufferRef);
352 charbuff buff;
353 obj.MustGetStream().CopyTo(buff);
354 REQUIRE(buff.size() == BufferSize);
355 }
356 }
357
358 TEST_CASE("TestEncryptMetadataFalse")
359 {
360 PdfMemDocument doc;
361 // This one has /EncryptMetadata false and /Filter[/Crypt] in /Metadata
362 doc.Load(TestUtils::GetTestInputFilePath("EncryptMetadataFalseCrypt.pdf"), "userpass");
363 REQUIRE(doc.GetMetadata().GetProducer()->GetString() == "PoDoFo - http://podofo.sf.net");
364
365 // This one has /EncryptMetadata false and no /Filter in /Metadata. Should still work
366 doc.Load(TestUtils::GetTestInputFilePath("EncryptMetadataFalseNoCrypt.pdf"), "userpass");
367 REQUIRE(doc.GetMetadata().GetProducer()->GetString() == "PoDoFo - http://podofo.sf.net");
368 }
369
370 TEST_CASE("TestRemoveEncryption")
371 {
372 PdfMemDocument doc;
373 doc.Load(TestUtils::GetTestInputFilePath("AESV2-128.pdf"), "userpass");
374 doc.SetEncrypt(nullptr);
375 doc.Save(TestUtils::GetTestOutputFilePath("Decrypted.pdf"));
376 doc.Load(TestUtils::GetTestOutputFilePath("Decrypted.pdf"));
377 charbuff objBuffer;
378 doc.GetObjects().MustGetObject(PdfReference(11, 0)).MustGetStream().CopyTo(objBuffer);
379 REQUIRE(ssl::ComputeMD5Str(objBuffer) == ReferenceHash_R_11_0);
380 }
381
382 void testAuthenticate(PdfEncrypt& encrypt, PdfEncryptContext& context)
383 {
384 PdfString documentId = PdfString::FromHexData("BF37541A9083A51619AD5924ECF156DF");
385
386 encrypt.EnsureEncryptionInitialized(documentId, context);
387
388 PdfEncryptContext authenticationTestContext;
389 INFO("authenticate using user password");
390 encrypt.Authenticate(PDF_USER_PASSWORD, documentId, authenticationTestContext);
391 REQUIRE(authenticationTestContext.GetAuthResult() == PdfAuthResult::User);
392 INFO("authenticate using owner password");
393 encrypt.Authenticate(PDF_OWNER_PASSWORD, documentId, authenticationTestContext);
394 REQUIRE(authenticationTestContext.GetAuthResult() == PdfAuthResult::Owner);
395 INFO("authenticate using wrong password");
396 encrypt.Authenticate("wrongpassword", documentId, authenticationTestContext);
397 REQUIRE(authenticationTestContext.GetAuthResult() == PdfAuthResult::Failed);
398 }
399
400 TEST_CASE("TestPreserveEncrypt")
401 {
402 vector<string> testPaths = {
403 TestUtils::GetTestInputFilePath("AESV3R6-256.pdf"),
404 TestUtils::GetTestInputFilePath("AESV2-128.pdf"),
405 TestUtils::GetTestInputFilePath("RC4V2-128.pdf")
406 };
407
408 // Saving the PDF should preserve both user/owner authorizations
409
410 PdfMemDocument doc;
411 charbuff pdfBuffer;
412 charbuff objBuffer;
413 auto testSave = [&](bool incremental, bool isOwner)
414 {
415 for (auto& path : testPaths)
416 {
417 doc.Load(path, isOwner ? "ownerpass" : "userpass");
418 pdfBuffer.clear();
419 BufferStreamDevice device(pdfBuffer);
420 if (incremental)
421 {
422 utls::ReadTo(pdfBuffer, path);
423 doc.SaveUpdate(device);
424 }
425 else
426 {
427 doc.Save(device);
428 }
429
430 doc.LoadFromBuffer(pdfBuffer, isOwner ? "userpass" : "ownerpass");
431 doc.GetObjects().MustGetObject(PdfReference(11, 0)).MustGetStream().CopyTo(objBuffer);
432 REQUIRE(ssl::ComputeMD5Str(objBuffer) == ReferenceHash_R_11_0);
433 }
434 };
435
436 // Try all combinations regular/incremental save and user/owner access
437 testSave(false, false);
438 testSave(false, true);
439 testSave(true, false);
440 testSave(true, true);
441 }
442
443 void testEncrypt(PdfEncrypt& encrypt, PdfEncryptContext& context)
444 {
445 charbuff encrypted;
446 // Encrypt buffer
447 try
448 {
449 encrypt.EncryptTo(encrypted, s_encBuffer, context, PdfReference(7, 0));
450 }
451 catch (PdfError& e)
452 {
453 FAIL(e.ErrorMessage(e.GetCode()));
454 }
455
456 charbuff decrypted;
457 // Decrypt buffer
458 try
459 {
460 encrypt.DecryptTo(decrypted, encrypted, context, PdfReference(7, 0));
461 }
462 catch (PdfError& e)
463 {
464 FAIL(e.ErrorMessage(e.GetCode()));
465 }
466
467 INFO("compare encrypted and decrypted buffers");
468 REQUIRE(memcmp(s_encBuffer.data(), decrypted.data(), s_encBuffer.size()) == 0);
469 }
470
471 void createEncryptedPdf(const string_view& filename)
472 {
473 PdfMemDocument doc;
474 auto& page = doc.GetPages().CreatePage(PdfPageSize::A4);
475 PdfPainter painter;
476 painter.SetCanvas(page);
477
478 auto font = doc.GetFonts().SearchFont("LiberationSans");
479 if (font == nullptr)
480 FAIL("Could not find Arial font");
481
482 painter.TextState.SetFont(*font, 16);
483 painter.DrawText("Hello World", 100, 100);
484 painter.FinishDrawing();
485
486 doc.SetEncrypted(PDF_USER_PASSWORD, "owner");
487 doc.Save(filename);
488
489 INFO(utls::Format("Wrote: {} (R={})", filename, doc.GetEncrypt()->GetRevision()));
490 }