Encryption.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /*
  2. * Copyright (c) 2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteBuffer.h>
  7. #include <LibCrypto/Hash/MD5.h>
  8. #include <LibPDF/CommonNames.h>
  9. #include <LibPDF/Document.h>
  10. #include <LibPDF/Encryption.h>
  11. namespace PDF {
  12. static constexpr Array<u8, 32> standard_encryption_key_padding_bytes = {
  13. 0x28,
  14. 0xBF,
  15. 0x4E,
  16. 0x5E,
  17. 0x4E,
  18. 0x75,
  19. 0x8A,
  20. 0x41,
  21. 0x64,
  22. 0x00,
  23. 0x4E,
  24. 0x56,
  25. 0xFF,
  26. 0xFA,
  27. 0x01,
  28. 0x08,
  29. 0x2E,
  30. 0x2E,
  31. 0x00,
  32. 0xB6,
  33. 0xD0,
  34. 0x68,
  35. 0x3E,
  36. 0x80,
  37. 0x2F,
  38. 0x0C,
  39. 0xA9,
  40. 0xFE,
  41. 0x64,
  42. 0x53,
  43. 0x69,
  44. 0x7A,
  45. };
  46. PDFErrorOr<NonnullRefPtr<SecurityHandler>> SecurityHandler::create(Document* document, NonnullRefPtr<DictObject> encryption_dict)
  47. {
  48. auto filter = TRY(encryption_dict->get_name(document, CommonNames::Filter))->name();
  49. if (filter == "Standard")
  50. return TRY(StandardSecurityHandler::create(document, encryption_dict));
  51. dbgln("Unrecognized security handler filter: {}", filter);
  52. TODO();
  53. }
  54. PDFErrorOr<NonnullRefPtr<StandardSecurityHandler>> StandardSecurityHandler::create(Document* document, NonnullRefPtr<DictObject> encryption_dict)
  55. {
  56. auto revision = encryption_dict->get_value(CommonNames::R).get<int>();
  57. auto o = TRY(encryption_dict->get_string(document, CommonNames::O))->string();
  58. auto u = TRY(encryption_dict->get_string(document, CommonNames::U))->string();
  59. auto p = encryption_dict->get_value(CommonNames::P).get<int>();
  60. auto length = encryption_dict->get_value(CommonNames::Length).get<int>() / 8;
  61. bool encrypt_metadata = true;
  62. if (encryption_dict->contains(CommonNames::EncryptMetadata))
  63. encryption_dict->get_value(CommonNames::EncryptMetadata).get<bool>();
  64. return adopt_ref(*new StandardSecurityHandler(document, revision, o, u, p, encrypt_metadata, length));
  65. }
  66. StandardSecurityHandler::StandardSecurityHandler(Document* document, size_t revision, String const& o_entry, String const& u_entry, u32 flags, bool encrypt_metadata, size_t length)
  67. : m_document(document)
  68. , m_revision(revision)
  69. , m_o_entry(o_entry)
  70. , m_u_entry(u_entry)
  71. , m_flags(flags)
  72. , m_encrypt_metadata(encrypt_metadata)
  73. , m_length(length)
  74. {
  75. }
  76. template<>
  77. ByteBuffer StandardSecurityHandler::compute_user_password_value<true>(ByteBuffer password_string)
  78. {
  79. // Algorithm 4: Computing the encryption dictionary's U (user password)
  80. // value (Security handlers of revision 2)
  81. // a) Create an encryption key based on the user password string, as
  82. // described in [Algorithm 2]
  83. auto encryption_key = compute_encryption_key(password_string);
  84. // b) Encrypt the 32-byte padding string shown in step (a) of [Algorithm 2],
  85. // using an RC4 encryption function with the encryption key from the
  86. // preceding step.
  87. RC4 rc4(encryption_key);
  88. auto output = rc4.encrypt(standard_encryption_key_padding_bytes);
  89. // c) Store the result of step (b) as the value of the U entry in the
  90. // encryption dictionary.
  91. return output;
  92. }
  93. template<>
  94. ByteBuffer StandardSecurityHandler::compute_user_password_value<false>(ByteBuffer password_string)
  95. {
  96. // Algorithm 5: Computing the encryption dictionary's U (user password)
  97. // value (Security handlers of revision 3 or greater)
  98. // a) Create an encryption key based on the user password string, as
  99. // described in [Algorithm 2]
  100. auto encryption_key = compute_encryption_key(password_string);
  101. // b) Initialize the MD5 hash functino and pass the 32-byte padding string
  102. // shown in step (a) of [Algorithm 2] as input to this function
  103. Crypto::Hash::MD5 md5;
  104. md5.update(standard_encryption_key_padding_bytes);
  105. // e) Pass the first element of the file's file identifier array to the MD5
  106. // hash function.
  107. auto id_array = MUST(m_document->trailer()->get_array(m_document, CommonNames::ID));
  108. auto first_element_string = MUST(id_array->get_string_at(m_document, 0))->string();
  109. md5.update(first_element_string);
  110. // d) Encrypt the 16-byte result of the hash, using an RC4 encryption function
  111. // with the encryption key from step (a).
  112. RC4 rc4(encryption_key);
  113. auto out = md5.peek();
  114. auto buffer = rc4.encrypt(out.bytes());
  115. // e) Do the following 19 times:
  116. //
  117. // Take the output from the previous invocation of the RC4 function and pass
  118. // it as input to a new invocation of the function; use an encryption key generated
  119. // by taking each byte of the original encryption key obtained in step (a) and
  120. // performing an XOR operation between the that byte and the single-byte value of
  121. // the iteration counter (from 1 to 19).
  122. auto new_encryption_key = MUST(ByteBuffer::create_uninitialized(encryption_key.size()));
  123. for (size_t i = 1; i <= 19; i++) {
  124. for (size_t j = 0; j < encryption_key.size(); j++)
  125. new_encryption_key[j] = encryption_key[j] ^ i;
  126. RC4 new_rc4(new_encryption_key);
  127. buffer = new_rc4.encrypt(buffer);
  128. }
  129. // f) Append 16 bytes of the arbitrary padding to the output from the final invocation
  130. // of the RC4 function and store the 32-byte result as the value of the U entry in
  131. // the encryption dictionary.
  132. VERIFY(buffer.size() == 16);
  133. for (size_t i = 0; i < 16; i++)
  134. buffer.append(0xab);
  135. return buffer;
  136. }
  137. bool StandardSecurityHandler::try_provide_user_password(StringView password_string)
  138. {
  139. // Algorithm 6: Authenticating the user password
  140. // a) Perform all but the last step of [Algorithm 4] or [Algorithm 5] using the
  141. // supplied password string.
  142. ByteBuffer password_buffer = MUST(ByteBuffer::copy(password_string.bytes()));
  143. if (m_revision == 2) {
  144. password_buffer = compute_user_password_value<true>(password_buffer);
  145. } else {
  146. password_buffer = compute_user_password_value<false>(password_buffer);
  147. }
  148. // b) If the result of step (a) is equal to the value of the encryption
  149. // dictionary's "U" entry (comparing the first 16 bytes in the case of security
  150. // handlers of revision 3 or greater), the password supplied is the correct user
  151. // password.
  152. auto u_bytes = m_u_entry.bytes();
  153. if (m_revision >= 3)
  154. return u_bytes.slice(0, 16) == password_buffer.bytes().slice(0, 16);
  155. return u_bytes == password_buffer.bytes();
  156. }
  157. ByteBuffer StandardSecurityHandler::compute_encryption_key(ByteBuffer password_string)
  158. {
  159. // This function should never be called after we have a valid encryption key.
  160. VERIFY(!m_encryption_key.has_value());
  161. // 7.6.3.3 Encryption Key Algorithm
  162. // Algorithm 2: Computing an encryption key
  163. // a) Pad or truncate the password string to exactly 32 bytes. If the password string
  164. // is more than 32 bytes long, use only its first 32 bytes; if it is less than 32
  165. // bytes long, pad it by appending the required number of additional bytes from the
  166. // beginning of the following padding string: [omitted]
  167. if (password_string.size() > 32) {
  168. password_string.resize(32);
  169. } else {
  170. password_string.append(standard_encryption_key_padding_bytes.data(), 32 - password_string.size());
  171. }
  172. // b) Initialize the MD5 hash function and pass the result of step (a) as input to
  173. // this function.
  174. Crypto::Hash::MD5 md5;
  175. md5.update(password_string);
  176. // c) Pass the value of the encryption dictionary's "O" entry to the MD5 hash function.
  177. md5.update(m_o_entry);
  178. // d) Convert the integer value of the P entry to a 32-bit unsigned binary number and pass
  179. // these bytes to the MD5 hash function, low-order byte first.
  180. md5.update(reinterpret_cast<u8 const*>(&m_flags), sizeof(m_flags));
  181. // e) Pass the first element of the file's file identifier array to the MD5 hash function.
  182. auto id_array = MUST(m_document->trailer()->get_array(m_document, CommonNames::ID));
  183. auto first_element_string = MUST(id_array->get_string_at(m_document, 0))->string();
  184. md5.update(first_element_string);
  185. // f) (Security handlers of revision 4 or greater) if the document metadata is not being
  186. // encrypted, pass 4 bytes with the value 0xffffffff to the MD5 hash function.
  187. if (m_revision >= 4 && !m_encrypt_metadata) {
  188. u32 value = 0xffffffff;
  189. md5.update(reinterpret_cast<u8 const*>(&value), 4);
  190. }
  191. // g) Finish the hash.
  192. // h) (Security handlers of revision 3 or greater) Do the following 50 times:
  193. //
  194. // Take the output from the previous MD5 hash and pass the first n bytes
  195. // of the output as input into a new MD5 hash, where n is the number of
  196. // bytes of the encryption key as defined by the value of the encryption
  197. // dictionary's Length entry.
  198. if (m_revision >= 3) {
  199. ByteBuffer n_bytes;
  200. for (u32 i = 0; i < 50; i++) {
  201. Crypto::Hash::MD5 new_md5;
  202. n_bytes.ensure_capacity(m_length);
  203. while (n_bytes.size() < m_length) {
  204. auto out = md5.peek().bytes();
  205. for (size_t j = 0; j < out.size() && n_bytes.size() < m_length; j++)
  206. n_bytes.append(out[j]);
  207. }
  208. VERIFY(n_bytes.size() == m_length);
  209. new_md5.update(n_bytes);
  210. md5 = move(new_md5);
  211. n_bytes.clear();
  212. }
  213. }
  214. // i) Set the encryption key to the first n bytes of the output from the final MD5
  215. // hash, where n shall always be 5 for security handlers of revision 2 but, for
  216. // security handlers of revision 3 or greater, shall depend on the value of the
  217. // encryption dictionary's Length entry.
  218. size_t n;
  219. if (m_revision == 2) {
  220. n = 5;
  221. } else if (m_revision >= 3) {
  222. n = m_length;
  223. } else {
  224. VERIFY_NOT_REACHED();
  225. }
  226. ByteBuffer encryption_key;
  227. encryption_key.ensure_capacity(n);
  228. while (encryption_key.size() < n) {
  229. auto out = md5.peek();
  230. for (size_t i = 0; encryption_key.size() < n && i < out.data_length(); i++)
  231. encryption_key.append(out.bytes()[i]);
  232. }
  233. m_encryption_key = encryption_key;
  234. return encryption_key;
  235. }
  236. void StandardSecurityHandler::encrypt(NonnullRefPtr<Object> object, Reference reference) const
  237. {
  238. // 7.6.2 General Encryption Algorithm
  239. // Algorithm 1: Encryption of data using the RC3 or AES algorithms
  240. // FIXME: Support AES
  241. VERIFY(m_encryption_key.has_value());
  242. // a) Obtain the object number and generation number from the object identifier of
  243. // the string or stream to be encrypted. If the string is a direct object, use
  244. // the identifier of the indirect object containing it.
  245. //
  246. // Note: This is always passed in at parse time because objects don't know their own
  247. // object number.
  248. // b) For all strings and streams with crypt filter specifier; treating the object
  249. // number as binary integers, extends the origin n-byte encryption key to n + 5
  250. // bytes by appending the low-order 3 bytes of the object number and the low-order
  251. // 2 bytes of the generation number in that order, low-order byte first. ...
  252. auto encryption_key = m_encryption_key.value();
  253. ReadonlyBytes bytes;
  254. Function<void(ByteBuffer const&)> assign;
  255. if (object->is<StreamObject>()) {
  256. auto stream = object->cast<StreamObject>();
  257. bytes = stream->bytes();
  258. assign = [&stream](ByteBuffer const& buffer) {
  259. stream->buffer() = buffer;
  260. };
  261. if (stream->dict()->contains(CommonNames::Filter)) {
  262. auto filter = MUST(stream->dict()->get_name(m_document, CommonNames::Filter))->name();
  263. if (filter == "Crypt")
  264. TODO();
  265. }
  266. } else if (object->is<StringObject>()) {
  267. auto string = object->cast<StringObject>();
  268. bytes = string->string().bytes();
  269. assign = [&string](ByteBuffer const& buffer) {
  270. string->set_string(String(buffer.bytes()));
  271. };
  272. } else {
  273. VERIFY_NOT_REACHED();
  274. }
  275. auto index = reference.as_ref_index();
  276. auto generation = reference.as_ref_generation_index();
  277. encryption_key.append(index & 0xff);
  278. encryption_key.append((index >> 8) & 0xff);
  279. encryption_key.append((index >> 16) & 0xff);
  280. encryption_key.append(generation & 0xff);
  281. encryption_key.append((generation >> 8) & 0xff);
  282. // c) Initialize the MD5 hash function and pass the result of step (b) as input to this
  283. // function.
  284. Crypto::Hash::MD5 md5;
  285. md5.update(encryption_key);
  286. // d) Use the first (n + 5) bytes, up to a maximum of 16, of the output from the MD5
  287. // hash as the key for the RC4 or AES symmetric key algorithms, along with the string
  288. // or stream data to be encrypted.
  289. auto key = MUST(ByteBuffer::copy(md5.peek().bytes()));
  290. if (key.size() > min(encryption_key.size(), 16))
  291. key.resize(encryption_key.size());
  292. RC4 rc4(key);
  293. auto output = rc4.encrypt(bytes);
  294. assign(output);
  295. }
  296. void StandardSecurityHandler::decrypt(NonnullRefPtr<Object> object, Reference reference) const
  297. {
  298. // AES and RC4 are both symmetric, so decryption is the same as encryption
  299. encrypt(object, reference);
  300. }
  301. static constexpr auto identity_permutation = iota_array<size_t, 256>(0);
  302. RC4::RC4(ReadonlyBytes key)
  303. : m_bytes(identity_permutation)
  304. {
  305. size_t j = 0;
  306. for (size_t i = 0; i < 256; i++) {
  307. j = (j + m_bytes[i] + key[i % key.size()]) & 0xff;
  308. swap(m_bytes[i], m_bytes[j]);
  309. }
  310. }
  311. void RC4::generate_bytes(ByteBuffer& bytes)
  312. {
  313. size_t i = 0;
  314. size_t j = 0;
  315. for (size_t count = 0; count < bytes.size(); count++) {
  316. i = (i + 1) % 256;
  317. j = (j + m_bytes[i]) % 256;
  318. swap(m_bytes[i], m_bytes[j]);
  319. bytes[count] = m_bytes[(m_bytes[i] + m_bytes[j]) % 256];
  320. }
  321. }
  322. ByteBuffer RC4::encrypt(ReadonlyBytes bytes)
  323. {
  324. auto output = MUST(ByteBuffer::create_uninitialized(bytes.size()));
  325. generate_bytes(output);
  326. for (size_t i = 0; i < bytes.size(); i++)
  327. output[i] ^= bytes[i];
  328. return output;
  329. }
  330. }