• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include "core/fpdfapi/parser/cpdf_crypto_handler.h"
8 
9 #include <time.h>
10 
11 #include <algorithm>
12 #include <stack>
13 #include <utility>
14 
15 #include "constants/form_fields.h"
16 #include "core/fdrm/fx_crypt.h"
17 #include "core/fpdfapi/parser/cpdf_dictionary.h"
18 #include "core/fpdfapi/parser/cpdf_number.h"
19 #include "core/fpdfapi/parser/cpdf_object_walker.h"
20 #include "core/fpdfapi/parser/cpdf_parser.h"
21 #include "core/fpdfapi/parser/cpdf_security_handler.h"
22 #include "core/fpdfapi/parser/cpdf_simple_parser.h"
23 #include "core/fpdfapi/parser/cpdf_stream.h"
24 #include "core/fpdfapi/parser/cpdf_stream_acc.h"
25 #include "core/fpdfapi/parser/cpdf_string.h"
26 
27 namespace {
28 
29 constexpr char kContentsKey[] = "Contents";
30 constexpr char kTypeKey[] = "Type";
31 
32 }  // namespace
33 
34 // static
IsSignatureDictionary(const CPDF_Dictionary * dictionary)35 bool CPDF_CryptoHandler::IsSignatureDictionary(
36     const CPDF_Dictionary* dictionary) {
37   if (!dictionary)
38     return false;
39   const CPDF_Object* type_obj = dictionary->GetDirectObjectFor(kTypeKey);
40   if (!type_obj)
41     type_obj = dictionary->GetDirectObjectFor(pdfium::form_fields::kFT);
42   return type_obj && type_obj->GetString() == pdfium::form_fields::kSig;
43 }
44 
CryptBlock(bool bEncrypt,uint32_t objnum,uint32_t gennum,pdfium::span<const uint8_t> source,uint8_t * dest_buf,uint32_t & dest_size)45 void CPDF_CryptoHandler::CryptBlock(bool bEncrypt,
46                                     uint32_t objnum,
47                                     uint32_t gennum,
48                                     pdfium::span<const uint8_t> source,
49                                     uint8_t* dest_buf,
50                                     uint32_t& dest_size) {
51   if (m_Cipher == FXCIPHER_NONE) {
52     memcpy(dest_buf, source.data(), source.size());
53     return;
54   }
55   uint8_t realkey[16];
56   size_t realkeylen = sizeof(realkey);
57   if (m_Cipher != FXCIPHER_AES || m_KeyLen != 32) {
58     uint8_t key1[32];
59     PopulateKey(objnum, gennum, key1);
60 
61     if (m_Cipher == FXCIPHER_AES)
62       memcpy(key1 + m_KeyLen + 5, "sAlT", 4);
63     size_t len = m_Cipher == FXCIPHER_AES ? m_KeyLen + 9 : m_KeyLen + 5;
64     CRYPT_MD5Generate({key1, len}, realkey);
65     realkeylen = std::min(m_KeyLen + 5, sizeof(realkey));
66   }
67   if (m_Cipher == FXCIPHER_AES) {
68     CRYPT_AESSetKey(m_pAESContext.get(),
69                     m_KeyLen == 32 ? m_EncryptKey : realkey, m_KeyLen,
70                     bEncrypt);
71     if (bEncrypt) {
72       uint8_t iv[16];
73       for (int i = 0; i < 16; i++) {
74         iv[i] = (uint8_t)rand();
75       }
76       CRYPT_AESSetIV(m_pAESContext.get(), iv);
77       memcpy(dest_buf, iv, 16);
78       int nblocks = source.size() / 16;
79       CRYPT_AESEncrypt(m_pAESContext.get(), dest_buf + 16, source.data(),
80                        nblocks * 16);
81       uint8_t padding[16];
82       memcpy(padding, source.data() + nblocks * 16, source.size() % 16);
83       memset(padding + source.size() % 16, 16 - source.size() % 16,
84              16 - source.size() % 16);
85       CRYPT_AESEncrypt(m_pAESContext.get(), dest_buf + nblocks * 16 + 16,
86                        padding, 16);
87       dest_size = 32 + nblocks * 16;
88     } else {
89       CRYPT_AESSetIV(m_pAESContext.get(), source.data());
90       CRYPT_AESDecrypt(m_pAESContext.get(), dest_buf, source.data() + 16,
91                        source.size() - 16);
92       dest_size = source.size() - 16;
93       dest_size -= dest_buf[dest_size - 1];
94     }
95   } else {
96     ASSERT(dest_size == source.size());
97     if (dest_buf != source.data())
98       memcpy(dest_buf, source.data(), source.size());
99     CRYPT_ArcFourCryptBlock({dest_buf, dest_size}, {realkey, realkeylen});
100   }
101 }
102 
103 struct AESCryptContext {
104   bool m_bIV;
105   uint32_t m_BlockOffset;
106   CRYPT_aes_context m_Context;
107   uint8_t m_Block[16];
108 };
109 
CryptStart(uint32_t objnum,uint32_t gennum,bool bEncrypt)110 void* CPDF_CryptoHandler::CryptStart(uint32_t objnum,
111                                      uint32_t gennum,
112                                      bool bEncrypt) {
113   if (m_Cipher == FXCIPHER_NONE) {
114     return this;
115   }
116   if (m_Cipher == FXCIPHER_AES && m_KeyLen == 32) {
117     AESCryptContext* pContext = FX_Alloc(AESCryptContext, 1);
118     pContext->m_bIV = true;
119     pContext->m_BlockOffset = 0;
120     CRYPT_AESSetKey(&pContext->m_Context, m_EncryptKey, 32, bEncrypt);
121     if (bEncrypt) {
122       for (int i = 0; i < 16; i++) {
123         pContext->m_Block[i] = (uint8_t)rand();
124       }
125       CRYPT_AESSetIV(&pContext->m_Context, pContext->m_Block);
126     }
127     return pContext;
128   }
129   uint8_t key1[48];
130   PopulateKey(objnum, gennum, key1);
131 
132   if (m_Cipher == FXCIPHER_AES)
133     memcpy(key1 + m_KeyLen + 5, "sAlT", 4);
134 
135   uint8_t realkey[16];
136   size_t len = m_Cipher == FXCIPHER_AES ? m_KeyLen + 9 : m_KeyLen + 5;
137   CRYPT_MD5Generate({key1, len}, realkey);
138   size_t realkeylen = std::min(m_KeyLen + 5, sizeof(realkey));
139 
140   if (m_Cipher == FXCIPHER_AES) {
141     AESCryptContext* pContext = FX_Alloc(AESCryptContext, 1);
142     pContext->m_bIV = true;
143     pContext->m_BlockOffset = 0;
144     CRYPT_AESSetKey(&pContext->m_Context, realkey, 16, bEncrypt);
145     if (bEncrypt) {
146       for (int i = 0; i < 16; i++) {
147         pContext->m_Block[i] = (uint8_t)rand();
148       }
149       CRYPT_AESSetIV(&pContext->m_Context, pContext->m_Block);
150     }
151     return pContext;
152   }
153   CRYPT_rc4_context* pContext = FX_Alloc(CRYPT_rc4_context, 1);
154   CRYPT_ArcFourSetup(pContext, {realkey, realkeylen});
155   return pContext;
156 }
157 
CryptStream(void * context,pdfium::span<const uint8_t> source,CFX_BinaryBuf & dest_buf,bool bEncrypt)158 bool CPDF_CryptoHandler::CryptStream(void* context,
159                                      pdfium::span<const uint8_t> source,
160                                      CFX_BinaryBuf& dest_buf,
161                                      bool bEncrypt) {
162   if (!context)
163     return false;
164 
165   if (m_Cipher == FXCIPHER_NONE) {
166     dest_buf.AppendBlock(source.data(), source.size());
167     return true;
168   }
169   if (m_Cipher == FXCIPHER_RC4) {
170     int old_size = dest_buf.GetSize();
171     dest_buf.AppendBlock(source.data(), source.size());
172     CRYPT_ArcFourCrypt(static_cast<CRYPT_rc4_context*>(context),
173                        dest_buf.GetSpan().subspan(old_size, source.size()));
174     return true;
175   }
176   AESCryptContext* pContext = static_cast<AESCryptContext*>(context);
177   if (pContext->m_bIV && bEncrypt) {
178     dest_buf.AppendBlock(pContext->m_Block, 16);
179     pContext->m_bIV = false;
180   }
181   uint32_t src_off = 0;
182   uint32_t src_left = source.size();
183   while (1) {
184     uint32_t copy_size = 16 - pContext->m_BlockOffset;
185     if (copy_size > src_left) {
186       copy_size = src_left;
187     }
188     memcpy(pContext->m_Block + pContext->m_BlockOffset, source.data() + src_off,
189            copy_size);
190     src_off += copy_size;
191     src_left -= copy_size;
192     pContext->m_BlockOffset += copy_size;
193     if (pContext->m_BlockOffset == 16) {
194       if (!bEncrypt && pContext->m_bIV) {
195         CRYPT_AESSetIV(&pContext->m_Context, pContext->m_Block);
196         pContext->m_bIV = false;
197         pContext->m_BlockOffset = 0;
198       } else if (src_off < source.size()) {
199         uint8_t block_buf[16];
200         if (bEncrypt) {
201           CRYPT_AESEncrypt(&pContext->m_Context, block_buf, pContext->m_Block,
202                            16);
203         } else {
204           CRYPT_AESDecrypt(&pContext->m_Context, block_buf, pContext->m_Block,
205                            16);
206         }
207         dest_buf.AppendBlock(block_buf, 16);
208         pContext->m_BlockOffset = 0;
209       }
210     }
211     if (!src_left) {
212       break;
213     }
214   }
215   return true;
216 }
CryptFinish(void * context,CFX_BinaryBuf & dest_buf,bool bEncrypt)217 bool CPDF_CryptoHandler::CryptFinish(void* context,
218                                      CFX_BinaryBuf& dest_buf,
219                                      bool bEncrypt) {
220   if (!context) {
221     return false;
222   }
223   if (m_Cipher == FXCIPHER_NONE) {
224     return true;
225   }
226   if (m_Cipher == FXCIPHER_RC4) {
227     FX_Free(context);
228     return true;
229   }
230   auto* pContext = static_cast<AESCryptContext*>(context);
231   if (bEncrypt) {
232     uint8_t block_buf[16];
233     if (pContext->m_BlockOffset == 16) {
234       CRYPT_AESEncrypt(&pContext->m_Context, block_buf, pContext->m_Block, 16);
235       dest_buf.AppendBlock(block_buf, 16);
236       pContext->m_BlockOffset = 0;
237     }
238     memset(pContext->m_Block + pContext->m_BlockOffset,
239            (uint8_t)(16 - pContext->m_BlockOffset),
240            16 - pContext->m_BlockOffset);
241     CRYPT_AESEncrypt(&pContext->m_Context, block_buf, pContext->m_Block, 16);
242     dest_buf.AppendBlock(block_buf, 16);
243   } else if (pContext->m_BlockOffset == 16) {
244     uint8_t block_buf[16];
245     CRYPT_AESDecrypt(&pContext->m_Context, block_buf, pContext->m_Block, 16);
246     if (block_buf[15] <= 16) {
247       dest_buf.AppendBlock(block_buf, 16 - block_buf[15]);
248     }
249   }
250   FX_Free(pContext);
251   return true;
252 }
253 
Decrypt(uint32_t objnum,uint32_t gennum,const ByteString & str)254 ByteString CPDF_CryptoHandler::Decrypt(uint32_t objnum,
255                                        uint32_t gennum,
256                                        const ByteString& str) {
257   CFX_BinaryBuf dest_buf;
258   void* context = DecryptStart(objnum, gennum);
259   DecryptStream(context, str.raw_span(), dest_buf);
260   DecryptFinish(context, dest_buf);
261   return ByteString(dest_buf.GetBuffer(), dest_buf.GetSize());
262 }
263 
DecryptStart(uint32_t objnum,uint32_t gennum)264 void* CPDF_CryptoHandler::DecryptStart(uint32_t objnum, uint32_t gennum) {
265   return CryptStart(objnum, gennum, false);
266 }
DecryptGetSize(uint32_t src_size)267 uint32_t CPDF_CryptoHandler::DecryptGetSize(uint32_t src_size) {
268   return m_Cipher == FXCIPHER_AES ? src_size - 16 : src_size;
269 }
270 
IsCipherAES() const271 bool CPDF_CryptoHandler::IsCipherAES() const {
272   return m_Cipher == FXCIPHER_AES;
273 }
274 
DecryptObjectTree(RetainPtr<CPDF_Object> object)275 bool CPDF_CryptoHandler::DecryptObjectTree(RetainPtr<CPDF_Object> object) {
276   if (!object)
277     return false;
278 
279   struct MayBeSignature {
280     const CPDF_Dictionary* parent;
281     CPDF_Object* contents;
282   };
283 
284   std::stack<MayBeSignature> may_be_sign_dictionaries;
285   const uint32_t obj_num = object->GetObjNum();
286   const uint32_t gen_num = object->GetGenNum();
287 
288   CPDF_Object* object_to_decrypt = object.Get();
289   while (object_to_decrypt) {
290     CPDF_NonConstObjectWalker walker(object_to_decrypt);
291     object_to_decrypt = nullptr;
292     while (CPDF_Object* child = walker.GetNext()) {
293       const CPDF_Dictionary* parent_dict =
294           walker.GetParent() ? walker.GetParent()->GetDict() : nullptr;
295       if (walker.dictionary_key() == kContentsKey &&
296           (parent_dict->KeyExist(kTypeKey) ||
297            parent_dict->KeyExist(pdfium::form_fields::kFT))) {
298         // This object may be contents of signature dictionary.
299         // But now values of 'Type' and 'FT' of dictionary keys are encrypted,
300         // and we can not check this.
301         // Temporary skip it, to prevent signature corruption.
302         // It will be decrypted on next interations, if this is not contents of
303         // signature dictionary.
304         may_be_sign_dictionaries.push(MayBeSignature({parent_dict, child}));
305         walker.SkipWalkIntoCurrentObject();
306         continue;
307       }
308       // Strings decryption.
309       if (child->IsString()) {
310         // TODO(art-snake): Move decryption into the CPDF_String class.
311         CPDF_String* str = child->AsString();
312         str->SetString(Decrypt(obj_num, gen_num, str->GetString()));
313       }
314       // Stream decryption.
315       if (child->IsStream()) {
316         // TODO(art-snake): Move decryption into the CPDF_Stream class.
317         CPDF_Stream* stream = child->AsStream();
318         auto stream_access = pdfium::MakeRetain<CPDF_StreamAcc>(stream);
319         stream_access->LoadAllDataRaw();
320 
321         if (IsCipherAES() && stream_access->GetSize() < 16) {
322           stream->SetData({});
323           continue;
324         }
325 
326         CFX_BinaryBuf decrypted_buf;
327         decrypted_buf.EstimateSize(DecryptGetSize(stream_access->GetSize()));
328 
329         void* context = DecryptStart(obj_num, gen_num);
330         bool decrypt_result =
331             DecryptStream(context, stream_access->GetSpan(), decrypted_buf);
332         decrypt_result &= DecryptFinish(context, decrypted_buf);
333         if (decrypt_result) {
334           const uint32_t decrypted_size = decrypted_buf.GetSize();
335           stream->TakeData(decrypted_buf.DetachBuffer(), decrypted_size);
336         } else {
337           // Decryption failed, set the stream to empty
338           stream->SetData({});
339         }
340       }
341     }
342     // Signature dictionaries check.
343     while (!may_be_sign_dictionaries.empty()) {
344       auto dict_and_contents = may_be_sign_dictionaries.top();
345       may_be_sign_dictionaries.pop();
346       if (!IsSignatureDictionary(dict_and_contents.parent)) {
347         // This is not signature dictionary. Do decrypt its contents.
348         object_to_decrypt = dict_and_contents.contents;
349         break;
350       }
351     }
352   }
353   return true;
354 }
355 
DecryptStream(void * context,pdfium::span<const uint8_t> source,CFX_BinaryBuf & dest_buf)356 bool CPDF_CryptoHandler::DecryptStream(void* context,
357                                        pdfium::span<const uint8_t> source,
358                                        CFX_BinaryBuf& dest_buf) {
359   return CryptStream(context, source, dest_buf, false);
360 }
361 
DecryptFinish(void * context,CFX_BinaryBuf & dest_buf)362 bool CPDF_CryptoHandler::DecryptFinish(void* context, CFX_BinaryBuf& dest_buf) {
363   return CryptFinish(context, dest_buf, false);
364 }
365 
EncryptGetSize(pdfium::span<const uint8_t> source) const366 size_t CPDF_CryptoHandler::EncryptGetSize(
367     pdfium::span<const uint8_t> source) const {
368   return m_Cipher == FXCIPHER_AES ? source.size() + 32 : source.size();
369 }
370 
EncryptContent(uint32_t objnum,uint32_t gennum,pdfium::span<const uint8_t> source,uint8_t * dest_buf,uint32_t & dest_size)371 bool CPDF_CryptoHandler::EncryptContent(uint32_t objnum,
372                                         uint32_t gennum,
373                                         pdfium::span<const uint8_t> source,
374                                         uint8_t* dest_buf,
375                                         uint32_t& dest_size) {
376   CryptBlock(true, objnum, gennum, source, dest_buf, dest_size);
377   return true;
378 }
379 
CPDF_CryptoHandler(int cipher,const uint8_t * key,size_t keylen)380 CPDF_CryptoHandler::CPDF_CryptoHandler(int cipher,
381                                        const uint8_t* key,
382                                        size_t keylen)
383     : m_KeyLen(std::min<size_t>(keylen, 32)), m_Cipher(cipher) {
384   ASSERT(cipher != FXCIPHER_AES || keylen == 16 || keylen == 24 ||
385          keylen == 32);
386   ASSERT(cipher != FXCIPHER_AES2 || keylen == 32);
387   ASSERT(cipher != FXCIPHER_RC4 || (keylen >= 5 && keylen <= 16));
388 
389   if (m_Cipher != FXCIPHER_NONE)
390     memcpy(m_EncryptKey, key, m_KeyLen);
391 
392   if (m_Cipher == FXCIPHER_AES)
393     m_pAESContext.reset(FX_Alloc(CRYPT_aes_context, 1));
394 }
395 
396 CPDF_CryptoHandler::~CPDF_CryptoHandler() = default;
397 
PopulateKey(uint32_t objnum,uint32_t gennum,uint8_t * key)398 void CPDF_CryptoHandler::PopulateKey(uint32_t objnum,
399                                      uint32_t gennum,
400                                      uint8_t* key) {
401   memcpy(key, m_EncryptKey, m_KeyLen);
402   key[m_KeyLen + 0] = (uint8_t)objnum;
403   key[m_KeyLen + 1] = (uint8_t)(objnum >> 8);
404   key[m_KeyLen + 2] = (uint8_t)(objnum >> 16);
405   key[m_KeyLen + 3] = (uint8_t)gennum;
406   key[m_KeyLen + 4] = (uint8_t)(gennum >> 8);
407 }
408