Debian Codegraph @

libs/pplib/pplib-src/src/ppcrypt.c

raw
1
2 #include "utilmd5.h"
3 #include "utilsha.h"
4
5 #include "pplib.h"
6
7 /* crypt struct */
8
9 static ppcrypt * ppcrypt_create (ppheap *heap)
10 {
11 ppcrypt *crypt;
12 crypt = (ppcrypt *)ppstruct_take(heap, sizeof(ppcrypt));
13 memset(crypt, 0, sizeof(ppcrypt));
14 return crypt;
15 }
16
17 int ppcrypt_type (ppcrypt *crypt, ppname *cryptname, ppuint *length, int *cryptflags)
18 {
19 ppdict *filterdict;
20 ppname *filtertype;
21 int cryptmd = 0, default256 = 0;
22
23 if (crypt->map == NULL || (filterdict = ppdict_rget_dict(crypt->map, cryptname->data)) == NULL)
24 return 0;
25 if ((filtertype = ppdict_get_name(filterdict, "CFM")) == NULL)
26 return 0;
27 *cryptflags = 0;
28 if (ppname_is(filtertype, "V2"))
29 *cryptflags |= PPCRYPT_INFO_RC4;
30 else if (ppname_is(filtertype, "AESV2"))
31 *cryptflags |= PPCRYPT_INFO_AES;
32 else if (ppname_is(filtertype, "AESV3"))
33 *cryptflags |= PPCRYPT_INFO_AES, default256 = 1;
34 else
35 return 0;
36 /* pdf spec page. 134: /Length is said to be optional bit-length of the key, but it seems to be a mistake, as Acrobat
37 produces /Length key with bytes lengths, opposite to /Length key of the main encrypt dict. */
38 if (length != NULL)
39 if (!ppdict_get_uint(filterdict, "Length", length))
40 *length = (*cryptflags & PPCRYPT_INFO_RC4) ? 5 : (default256 ? 32 : 16);
41 /* one of metadata flags is set iff there is an explicit EncryptMetadata key */
42 if (ppdict_get_bool(filterdict, "EncryptMetadata", &cryptmd))
43 *cryptflags |= (cryptmd ? PPCRYPT_INFO_MD : PPCRYPT_INFO_NOMD);
44 return 1;
45 }
46
47 /* V1..4 algorithms */
48
49 /* V1..4 unicode do PdfDocEncoding */
50
51 typedef struct {
52 uint32_t unicode;
53 uint32_t code;
54 uint32_t count;
55 } map_range_t;
56
57 static const map_range_t unicode_to_pdf_doc_encoding_map[] = {
58 { 32, 32, 95 },
59 { 161, 161, 12 },
60 { 174, 174, 82 },
61 { 305, 154, 1 },
62 { 321, 149, 1 },
63 { 322, 155, 1 },
64 { 338, 150, 1 },
65 { 339, 156, 1 },
66 { 352, 151, 1 },
67 { 353, 157, 1 },
68 { 376, 152, 1 },
69 { 381, 153, 1 },
70 { 382, 158, 1 },
71 { 402, 134, 1 },
72 { 710, 26, 1 },
73 { 711, 25, 1 },
74 { 728, 24, 1 },
75 { 729, 27, 1 },
76 { 730, 30, 1 },
77 { 731, 29, 1 },
78 { 732, 31, 1 },
79 { 733, 28, 1 },
80 { 8211, 133, 1 },
81 { 8212, 132, 1 },
82 { 8216, 143, 3 },
83 { 8220, 141, 2 },
84 { 8222, 140, 1 },
85 { 8224, 129, 2 },
86 { 8226, 128, 1 },
87 { 8230, 131, 1 },
88 { 8240, 139, 1 },
89 { 8249, 136, 2 },
90 { 8260, 135, 1 },
91 { 8364, 160, 1 },
92 { 8482, 146, 1 },
93 { 8722, 138, 1 },
94 { 64257, 147, 2 }
95 };
96
97 #define unicode_to_pdf_doc_encoding_entries (sizeof(unicode_to_pdf_doc_encoding_map) / sizeof(map_range_t))
98
99 static int unicode_to_pdf_doc_encoding (uint32_t unicode, uint8_t *pcode)
100 {
101 const map_range_t *left, *right, *mid;
102
103 left = &unicode_to_pdf_doc_encoding_map[0];
104 right = &unicode_to_pdf_doc_encoding_map[unicode_to_pdf_doc_encoding_entries - 1];
105 for ( ; left <= right; )
106 {
107 mid = left + ((right - left) / 2);
108 if (unicode > mid->unicode + mid->count - 1)
109 left = mid + 1;
110 else if (unicode < mid->unicode)
111 right = mid - 1;
112 else
113 {
114 *pcode = (uint8_t)(mid->code + (unicode - mid->unicode));
115 return 1;
116 }
117 }
118 return 0;
119 }
120
121 #define utf8_unicode2(p) (((p[0]&31)<<6)|(p[1]&63))
122 #define utf8_unicode3(p) (((p[0]&15)<<12)|((p[1]&63)<<6)|(p[2]&63))
123 #define utf8_unicode4(p) (((p[0]&7)<<18)|((p[1]&63)<<12)|((p[2]&63)<<6)|(p[3]&63))
124
125 #define utf8_get1(p, e, unicode) ((unicode = p[0]), p + 1)
126 #define utf8_get2(p, e, unicode) (p + 1 < e ? ((unicode = utf8_unicode2(p)), p + 2) : NULL)
127 #define utf8_get3(p, e, unicode) (p + 2 < e ? ((unicode = utf8_unicode3(p)), p + 3) : NULL)
128 #define utf8_get4(p, e, unicode) (p + 4 < e ? ((unicode = utf8_unicode3(p)), p + 4) : NULL)
129
130 #define utf8_get(p, e, unicode) \
131 (p[0] < 0x80 ? utf8_get1(p, e, unicode) : \
132 p[0] < 0xC0 ? NULL : \
133 p[0] < 0xE0 ? utf8_get2(p, e, unicode) : \
134 p[0] < 0xF0 ? utf8_get3(p, e, unicode) : utf8_get4(p, e, unicode))
135
136 static int ppcrypt_password_encoding (uint8_t *password, size_t *passwordlength)
137 {
138 uint8_t *p, newpassword[PPCRYPT_MAX_PASSWORD], *n;
139 const uint8_t *e;
140 uint32_t unicode = 0;
141
142 for (n = &newpassword[0], p = &password[0], e = p + *passwordlength; p < e; ++n)
143 {
144 p = utf8_get(p, e, unicode);
145 if (p == NULL)
146 return 0;
147 if (unicode_to_pdf_doc_encoding(unicode, n) == 0)
148 return 0;
149 }
150 *passwordlength = n - &newpassword[0];
151 memcpy(password, newpassword, *passwordlength);
152 return 1;
153 }
154
155 /* setup passwords */
156
157 static const uint8_t password_padding[] = {
158 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
159 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A
160 };
161
162 static void ppcrypt_set_user_password (ppcrypt *crypt, const void *userpass, size_t userpasslength)
163 {
164 crypt->userpasslength = userpasslength > PPCRYPT_MAX_PASSWORD ? PPCRYPT_MAX_PASSWORD : userpasslength;
165 memcpy(crypt->userpass, userpass, crypt->userpasslength);
166 if (crypt->algorithm_variant < 5)
167 {
168 if (ppcrypt_password_encoding(crypt->userpass, &crypt->userpasslength) == 0)
169 return;
170 if (crypt->userpasslength > 32)
171 crypt->userpasslength = 32;
172 else if (crypt->userpasslength < 32)
173 memcpy(&crypt->userpass[crypt->userpasslength], password_padding, 32 - crypt->userpasslength);
174 }
175 crypt->flags |= PPCRYPT_USER_PASSWORD;
176 }
177
178 static void ppcrypt_set_owner_password (ppcrypt *crypt, const void *ownerpass, size_t ownerpasslength)
179 {
180 crypt->ownerpasslength = ownerpasslength > PPCRYPT_MAX_PASSWORD ? PPCRYPT_MAX_PASSWORD : ownerpasslength;
181 memcpy(crypt->ownerpass, ownerpass, crypt->ownerpasslength);
182 if (crypt->algorithm_variant < 5)
183 {
184 if (ppcrypt_password_encoding(crypt->ownerpass, &crypt->ownerpasslength) == 0)
185 return;
186 if (crypt->ownerpasslength > 32)
187 crypt->ownerpasslength = 32;
188 else if (crypt->ownerpasslength < 32)
189 memcpy(&crypt->ownerpass[crypt->ownerpasslength], password_padding, 32 - crypt->ownerpasslength);
190 }
191 crypt->flags |= PPCRYPT_OWNER_PASSWORD;
192 }
193
194 /* V1..4 retrieving user password from owner password and owner key (variant < 5) */
195
196 static void ppcrypt_user_password_from_owner_key (ppcrypt *crypt, const void *ownerkey, size_t ownerkeysize)
197 {
198 uint8_t temp[16], rc4key[32], rc4key2[32];
199 uint8_t i;
200 ppuint k;
201 md5_state md5;
202
203 md5_digest_init(&md5);
204 md5_digest_add(&md5, crypt->ownerpass, 32);
205 md5_digest_get(&md5, rc4key, MD5_BYTES);
206 if (crypt->algorithm_revision >= 3)
207 {
208 for (i = 0; i < 50; ++i)
209 {
210 md5_digest(rc4key, 16, temp, MD5_BYTES);
211 memcpy(rc4key, temp, 16);
212 }
213 }
214 rc4_decode_data(ownerkey, ownerkeysize, crypt->userpass, rc4key, crypt->filekeylength);
215 if (crypt->algorithm_revision >= 3)
216 {
217 for (i = 1; i <= 19; ++i)
218 {
219 for (k = 0; k < crypt->filekeylength; ++k)
220 rc4key2[k] = rc4key[k] ^ i;
221 rc4_decode_data(crypt->userpass, 32, crypt->userpass, rc4key2, crypt->filekeylength);
222 }
223 }
224 //crypt->userpasslength = 32;
225 for (crypt->userpasslength = 0; crypt->userpasslength < 32; ++crypt->userpasslength)
226 if (memcmp(&crypt->userpass[crypt->userpasslength], password_padding, 32 - crypt->userpasslength) == 0)
227 break;
228 crypt->flags |= PPCRYPT_USER_PASSWORD;
229 }
230
231 /* V1..4 generating file key; pdf spec p. 125 */
232
233 static void ppcrypt_compute_file_key (ppcrypt *crypt, const void *ownerkey, size_t ownerkeysize, const void *id, size_t idsize)
234 {
235 uint32_t p;
236 uint8_t permissions[4], temp[16];
237 int i;
238 md5_state md5;
239
240 md5_digest_init(&md5);
241 md5_digest_add(&md5, crypt->userpass, 32);
242 md5_digest_add(&md5, ownerkey, ownerkeysize);
243 p = (uint32_t)crypt->permissions;
244 permissions[0] = get_number_byte1(p);
245 permissions[1] = get_number_byte2(p);
246 permissions[2] = get_number_byte3(p);
247 permissions[3] = get_number_byte4(p);
248 md5_digest_add(&md5, permissions, 4);
249 md5_digest_add(&md5, id, idsize);
250 if (crypt->algorithm_revision >= 4 && (crypt->flags & PPCRYPT_NO_METADATA))
251 md5_digest_add(&md5, "\xFF\xFF\xFF\xFF", 4);
252 md5_digest_get(&md5, crypt->filekey, MD5_BYTES);
253 if (crypt->algorithm_revision >= 3)
254 {
255 for (i = 0; i < 50; ++i)
256 {
257 md5_digest(crypt->filekey, (size_t)crypt->filekeylength, temp, MD5_BYTES);
258 memcpy(crypt->filekey, temp, 16);
259 }
260 }
261 }
262
263 /* V1..4 generating userkey for comparison with /U; requires a general file key and id; pdf spec page 126-127 */
264
265 static void ppcrypt_compute_user_key (ppcrypt *crypt, const void *id, size_t idsize, uint8_t password_hash[32])
266 {
267 uint8_t rc4key2[32];
268 uint8_t i;
269 ppuint k;
270
271 if (crypt->algorithm_revision <= 2)
272 {
273 rc4_encode_data(password_padding, 32, password_hash, crypt->filekey, crypt->filekeylength);
274 }
275 else
276 {
277 md5_state md5;
278 md5_digest_init(&md5);
279 md5_digest_add(&md5, password_padding, 32);
280 md5_digest_add(&md5, id, idsize);
281 md5_digest_get(&md5, password_hash, MD5_BYTES);
282 rc4_encode_data(password_hash, 16, password_hash, crypt->filekey, crypt->filekeylength);
283 for (i = 1; i <= 19; ++i)
284 {
285 for (k = 0; k < crypt->filekeylength; ++k)
286 rc4key2[k] = crypt->filekey[k] ^ i;
287 rc4_encode_data(password_hash, 16, password_hash, rc4key2, crypt->filekeylength);
288 }
289 for (i = 16; i < 32; ++i)
290 password_hash[i] = password_hash[i - 16] ^ i; /* arbitrary 16-bytes padding */
291 }
292 }
293
294 static ppcrypt_status ppcrypt_authenticate_legacy (ppcrypt *crypt, ppstring *userkey, ppstring *ownerkey, ppstring *id)
295 {
296 uint8_t password_hash[32];
297
298 if ((crypt->flags & PPCRYPT_USER_PASSWORD) == 0 && (crypt->flags & PPCRYPT_OWNER_PASSWORD) != 0)
299 ppcrypt_user_password_from_owner_key(crypt, ownerkey, ownerkey->size);
300 ppcrypt_compute_file_key(crypt, ownerkey->data, ownerkey->size, id->data, id->size);
301 ppcrypt_compute_user_key(crypt, id->data, id->size, password_hash); /* needs file key */
302 return memcmp(userkey->data, password_hash, (crypt->algorithm_revision >= 3 ? 16 : 32)) == 0 ? PPCRYPT_DONE : PPCRYPT_PASS;
303 }
304
305 /* V5 */
306
307 static const uint8_t nulliv[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; /* AES-256 initialization vector */
308
309 /* V5 R5..6 password hash */
310
311 #define PPCRYPT_MAX_MANGLED ((127+64+48)*64) // 127 password, 64 hash, 48 /U key
312
313 static void ppcrypt_password_hash_indeed (const uint8_t *password, size_t passwordlength, const uint8_t *userkey, uint8_t hash[64])
314 {
315 size_t hashlength, datalength;
316 uint8_t data[PPCRYPT_MAX_MANGLED], *pdata;
317 uint8_t *key, *iv;
318 uint8_t round, i;
319 uint32_t div3;
320
321 hashlength = 32; /* initial hash is sha256 */
322 round = 0;
323 do
324 {
325 /* concat password, hash, and /U value 64 times */
326 pdata = &data[0];
327 memcpy(pdata, password, passwordlength);
328 pdata += passwordlength;
329 memcpy(pdata, hash, hashlength);
330 pdata += hashlength;
331 if (userkey != NULL)
332 {
333 memcpy(pdata, userkey, 48);
334 pdata += 48;
335 }
336 datalength = pdata - &data[0];
337 for (i = 1; i < 64; ++i, pdata += datalength)
338 memcpy(pdata, &data[0], datalength);
339 datalength *= 64;
340
341 /* encrypt the data with aes128 using hash bytes 1..16 as key and bytes 17..32 as initialization vector
342 encryption inplace, CBC, no-padding, no change to datalength */
343 key = &hash[0]; iv = &hash[16];
344 aes_encode_data(data, datalength, data, key, 16, iv, AES_NULL_PADDING);
345
346 /* get modulo 3 of first 16 bytes number of encrypted data (sum of digits modulo 3) */
347 for (i = 0, div3 = 0; i < 16; ++i)
348 div3 += data[i];
349
350 /* compute new hash using sha256/384/512 */
351 switch (div3 % 3)
352 {
353 case 0:
354 sha256_digest(data, datalength, hash, SHA_BYTES);
355 hashlength = 32;
356 break;
357 case 1:
358 sha384_digest(data, datalength, hash, SHA_BYTES);
359 hashlength = 48;
360 break;
361 case 2:
362 sha512_digest(data, datalength, hash, SHA_BYTES);
363 hashlength = 64;
364 break;
365 }
366
367 /* do 64 times, then keep going until the last byte of data <= round - 32 */
368 } while (++round < 64 || round < data[datalength - 1] + 32);
369
370 }
371
372 static void ppcrypt_password_hash (ppcrypt *crypt, const uint8_t *password, size_t passwordlength, const uint8_t *salt, const uint8_t *userkey, uint8_t password_hash[32])
373 {
374 sha256_state sha;
375 uint8_t hash[64]; /* result password_hash is 32 bytes, but we need 64 for R6 procedure */
376
377 /* take sha256 of password, salt and /U */
378 sha256_digest_init(&sha);
379 sha256_digest_add(&sha, password, passwordlength);
380 sha256_digest_add(&sha, salt, 8);
381 if (userkey != NULL)
382 sha256_digest_add(&sha, userkey, 48);
383 sha256_digest_get(&sha, hash, SHA_BYTES);
384
385 /* V5 R5 - password_hash is the digest, V5 R6 - password_hash is mangled */
386 if (crypt->algorithm_revision >= 6)
387 ppcrypt_password_hash_indeed(password, passwordlength, userkey, hash);
388
389 memcpy(password_hash, hash, 32);
390 }
391
392 /* V5 permissions */
393
394 static ppcrypt_status ppcrypt_authenticate_permissions (ppcrypt *crypt, ppstring *perms)
395 {
396 uint8_t permsdata[16];
397
398 aes_decode_data(perms->data, perms->size, permsdata, crypt->filekey, crypt->filekeylength, nulliv, AES_NULL_PADDING);
399
400 if (permsdata[9] != 'a' || permsdata[10] != 'd' || permsdata[11] != 'b')
401 { /* if we get here, the password hash is correct, we don't need to fail because of unreadable perms (found such docs) */
402 crypt->flags |= PPCRYPT_UNREADABLE_PERMISSIONS;
403 return PPCRYPT_DONE;
404 }
405
406 /* do not check/update permissions flags here; they might be different inside crypt string */
407 if (0)
408 {
409 int64_t p;
410 int i;
411 for (p = 0, i = 0; i < 8; ++i)
412 p = p + (permsdata[i] << (i << 3)); /* low order bytes first */
413 crypt->permissions = (ppint)((int32_t)(p & 0x00000000FFFFFFFFLL)); /* unset bits 33..64, treat as 32-bit signed int */
414 }
415
416 if (permsdata[8] == 'T')
417 crypt->flags &= ~PPCRYPT_NO_METADATA;
418 else if (permsdata[8] == 'F')
419 crypt->flags |= PPCRYPT_NO_METADATA;
420
421 return PPCRYPT_DONE;
422 }
423
424 /* V5 authentication */
425
426 static ppcrypt_status ppcrypt_authenticate_user (ppcrypt *crypt, ppstring *u, ppstring *ue, ppstring *perms)
427 {
428 uint8_t password_hash[32], *salt;
429
430 salt = (uint8_t *)&u->data[32]; /* validation salt */
431 ppcrypt_password_hash(crypt, crypt->userpass, crypt->userpasslength, salt, NULL, password_hash);
432 if (memcmp(u->data, password_hash, 32) != 0)
433 return PPCRYPT_PASS;
434
435 salt = (uint8_t *)&u->data[40]; /* key salt */
436 ppcrypt_password_hash(crypt, crypt->userpass, crypt->userpasslength, salt, NULL, password_hash);
437 aes_decode_data(ue->data, 32, crypt->filekey, password_hash, 32, nulliv, AES_NULL_PADDING);
438
439 return ppcrypt_authenticate_permissions(crypt, perms);
440 }
441
442 static ppcrypt_status ppcrypt_authenticate_owner (ppcrypt *crypt, ppstring *u, ppstring *o, ppstring *oe, ppstring *perms)
443 {
444 uint8_t password_hash[32], *salt;
445
446 salt = (uint8_t *)&o->data[32]; /* validation salt */
447 ppcrypt_password_hash(crypt, crypt->ownerpass, crypt->ownerpasslength, salt, (uint8_t *)u->data, password_hash);
448 if (memcmp(o->data, password_hash, 32) != 0)
449 return PPCRYPT_PASS;
450
451 salt = (uint8_t *)&o->data[40]; /* key salt */
452 ppcrypt_password_hash(crypt, crypt->ownerpass, crypt->ownerpasslength, salt, (uint8_t *)u->data, password_hash);
453 aes_decode_data(oe->data, 32, crypt->filekey, password_hash, 32, nulliv, AES_NULL_PADDING);
454
455 return ppcrypt_authenticate_permissions(crypt, perms);
456 }
457
458
459 /* authentication */
460
461 static ppcrypt_status ppcrypt_authenticate (ppcrypt *crypt, ppstring *u, ppstring *ue, ppstring *o, ppstring *oe, ppstring *id, ppstring *perms)
462 {
463 /* V1..V4 */
464 if (crypt->algorithm_variant < 5)
465 return ppcrypt_authenticate_legacy(crypt, u, o, id);
466
467 /* V5 */
468 if (crypt->flags & PPCRYPT_USER_PASSWORD)
469 if (ppcrypt_authenticate_user(crypt, u, ue, perms) == PPCRYPT_DONE)
470 return PPCRYPT_DONE;
471 if (crypt->flags & PPCRYPT_OWNER_PASSWORD)
472 return ppcrypt_authenticate_owner(crypt, u, o, oe, perms);
473
474 return PPCRYPT_PASS;
475 }
476
477 /**/
478
479 ppcrypt_status ppdoc_crypt_init (ppdoc *pdf, const void *userpass, size_t userpasslength, const void *ownerpass, size_t ownerpasslength)
480 {
481 ppcrypt *crypt;
482 ppdict *trailer, *encrypt;
483 ppobj *obj;
484 ppname *name, **pkey;
485 ppstring *userkey, *ownerkey, *userkey_e = NULL, *ownerkey_e = NULL;
486 size_t hashlength;
487 pparray *idarray;
488 ppstring *id = NULL, *perms = NULL;
489 int cryptflags, encryptmd;
490 size_t strkeylength, stmkeylength;
491
492 trailer = ppxref_trailer(pdf->xref);
493 if ((obj = ppdict_get_obj(trailer, "Encrypt")) == NULL)
494 return PPCRYPT_NONE;
495
496 /* this happens early, before loading body, so if /Encrypt is indirect reference, it points nothing */
497 obj = ppobj_preloaded(pdf, obj);
498 if (obj->type != PPDICT)
499 return PPCRYPT_FAIL;
500 encrypt = obj->dict;
501 for (ppdict_first(encrypt, pkey, obj); *pkey != NULL; ppdict_next(pkey, obj))
502 (void)ppobj_preloaded(pdf, obj);
503
504 if ((name = ppdict_get_name(encrypt, "Filter")) != NULL && !ppname_is(name, "Standard"))
505 return PPCRYPT_FAIL;
506
507 if ((crypt = pdf->crypt) == NULL)
508 crypt = pdf->crypt = ppcrypt_create(&pdf->heap);
509
510 /* get /V /R /P */
511 if (!ppdict_get_uint(encrypt, "V", &crypt->algorithm_variant))
512 crypt->algorithm_variant = 0;
513 if (crypt->algorithm_variant < 1 || crypt->algorithm_variant > 5)
514 return PPCRYPT_FAIL;
515 if (!ppdict_get_uint(encrypt, "R", &crypt->algorithm_revision))
516 return PPCRYPT_FAIL;
517 if (!ppdict_get_int(encrypt, "P", &crypt->permissions))
518 return PPCRYPT_FAIL;
519
520 /* get /O /U /ID /OE /UE */
521 if ((userkey = ppdict_get_string(encrypt, "U")) == NULL || (ownerkey = ppdict_get_string(encrypt, "O")) == NULL)
522 return PPCRYPT_FAIL;
523 userkey = ppstring_decoded(userkey);
524 ownerkey = ppstring_decoded(ownerkey);
525
526 /* for some reason acrobat pads /O and /U to 127 bytes with NULL, so we don't check the exact length but ensure the minimal */
527 hashlength = crypt->algorithm_variant < 5 ? 32 : 48;
528 if (userkey->size < hashlength || ownerkey->size < hashlength)
529 return PPCRYPT_FAIL;
530 if (crypt->algorithm_variant < 5)
531 { // get first string from /ID (must not be ref)
532 if ((idarray = ppdict_get_array(trailer, "ID")) == NULL || (id = pparray_get_string(idarray, 0)) == NULL)
533 return PPCRYPT_FAIL;
534 id = ppstring_decoded(id);
535 }
536 else
537 {
538 if ((userkey_e = ppdict_get_string(encrypt, "UE")) == NULL || (ownerkey_e = ppdict_get_string(encrypt, "OE")) == NULL)
539 return PPCRYPT_FAIL;
540 userkey_e = ppstring_decoded(userkey_e);
541 ownerkey_e = ppstring_decoded(ownerkey_e);
542 if (userkey_e->size < 32 || ownerkey_e->size < 32)
543 return PPCRYPT_FAIL;
544 if ((perms = ppdict_get_string(encrypt, "Perms")) == NULL)
545 return PPCRYPT_FAIL;
546 perms = ppstring_decoded(perms);
547 if (perms->size != 16)
548 return PPCRYPT_FAIL;
549 }
550
551 /* collect flags and keylength */
552 switch (crypt->algorithm_revision)
553 {
554 case 1:
555 crypt->filekeylength = 5;
556 crypt->flags |= PPCRYPT_RC4;
557 break;
558 case 2: case 3:
559 if (ppdict_get_uint(encrypt, "Length", &crypt->filekeylength))
560 crypt->filekeylength >>= 3; /* 40..256 bits, 5..32 bytes*/
561 else
562 crypt->filekeylength = 5; /* 40 bits, 5 bytes */
563 crypt->flags |= PPCRYPT_RC4;
564 break;
565 case 4: case 5: case 6:
566 if ((crypt->map = ppdict_rget_dict(encrypt, "CF")) == NULL)
567 return PPCRYPT_FAIL;
568 for (ppdict_first(crypt->map, pkey, obj); *pkey != NULL; ppdict_next(pkey, obj))
569 (void)ppobj_preloaded(pdf, obj);
570 /* /EncryptMetadata relevant only for version >=4, may be also provided in crypt filter dictionary; which takes a precedence then?
571 we assume that if there is an explicit EncryptMetadata key, it overrides main encrypt dict flag or default flag (the default is true,
572 meaning that Metadata stream is encrypted as others) */
573 if (ppdict_get_bool(encrypt, "EncryptMetadata", &encryptmd) && !encryptmd)
574 crypt->flags |= PPCRYPT_NO_METADATA;
575
576 strkeylength = stmkeylength = 0;
577 /* streams filter */
578 if ((name = ppdict_get_name(encrypt, "StmF")) != NULL && ppcrypt_type(crypt, name, &stmkeylength, &cryptflags))
579 {
580 if (cryptflags & PPCRYPT_INFO_AES)
581 crypt->flags |= PPCRYPT_STREAM_AES;
582 else if (cryptflags & PPCRYPT_INFO_RC4)
583 crypt->flags |= PPCRYPT_STREAM_RC4;
584 if (cryptflags & PPCRYPT_INFO_NOMD)
585 crypt->flags |= PPCRYPT_NO_METADATA;
586 else if (cryptflags & PPCRYPT_INFO_MD)
587 crypt->flags &= ~PPCRYPT_NO_METADATA;
588 } /* else identity */
589 /* strings filter */
590 if ((name = ppdict_get_name(encrypt, "StrF")) != NULL && ppcrypt_type(crypt, name, &strkeylength, &cryptflags))
591 {
592 if (cryptflags & PPCRYPT_INFO_AES)
593 crypt->flags |= PPCRYPT_STRING_AES;
594 else if (cryptflags & PPCRYPT_INFO_RC4)
595 crypt->flags |= PPCRYPT_STRING_RC4;
596 } /* else identity */
597
598 /* /Length of encrypt dict is irrelevant here, theoretically every crypt filter may have own length... It means that we should
599 actually keep a different file key for streams and strings. But it leads to nonsense, as /U and /O entries refers to a single
600 keylength, without a distinction for strings/streams. So we have to assume /Length is consistent. To expose the limitation: */
601 if ((crypt->flags & PPCRYPT_STREAM) && (crypt->flags & PPCRYPT_STRING))
602 if (strkeylength != stmkeylength)
603 return PPCRYPT_FAIL;
604 crypt->filekeylength = stmkeylength ? stmkeylength : strkeylength;
605 if ((crypt->flags & PPCRYPT_STREAM) || (crypt->flags & PPCRYPT_STRING))
606 if (crypt->filekeylength == 0)
607 return PPCRYPT_FAIL;
608 break;
609 default:
610 return PPCRYPT_FAIL;
611 }
612
613 /* setup passwords */
614 if (userpass != NULL)
615 ppcrypt_set_user_password(crypt, userpass, userpasslength);
616 if (ownerpass != NULL)
617 ppcrypt_set_owner_password(crypt, ownerpass, ownerpasslength);
618 if ((crypt->flags & (PPCRYPT_USER_PASSWORD|PPCRYPT_OWNER_PASSWORD)) == 0)
619 return PPCRYPT_PASS;
620
621 return ppcrypt_authenticate(crypt, userkey, userkey_e, ownerkey, ownerkey_e, id, perms);
622 }
623
624 /* decrypting strings */
625
626 /*
627 Since strings are generally rare, but might occur in mass (name trees). We generate decryption key when needed.
628 All strings within the same reference are crypted with the same key. Both RC4 and AES algorithms expands
629 the crypt key in some way and the result of expansion is the same for the same crypt key. Instead of recreating
630 the ky for every string, we backup the initial decryption state.
631 */
632
633 static void ppcrypt_strkey (ppcrypt *crypt, ppref *ref, int aes)
634 {
635 if (crypt->cryptkeylength > 0)
636 { /* crypt key already generated, just reinitialize crypt states */
637 if (aes)
638 { /* aes codecs that works on c-strings do not modify aes_state flags at all, so we actually don't need to revitalize the state,
639 we only rewrite an initialization vector, which is modified during crypt procedure */
640 }
641 else
642 { /* rc4 crypt map is modified during crypt procedure, so here we reinitialize rc4 bytes map */
643 rc4_map_restore(&crypt->rc4state, &crypt->rc4copy);
644 }
645 return;
646 }
647
648 if (crypt->algorithm_variant < 5)
649 {
650 crypt->filekey[crypt->filekeylength + 0] = get_number_byte1(ref->number);
651 crypt->filekey[crypt->filekeylength + 1] = get_number_byte2(ref->number);
652 crypt->filekey[crypt->filekeylength + 2] = get_number_byte3(ref->number);
653 crypt->filekey[crypt->filekeylength + 3] = get_number_byte1(ref->version);
654 crypt->filekey[crypt->filekeylength + 4] = get_number_byte2(ref->version);
655
656 if (aes)
657 {
658 crypt->filekey[crypt->filekeylength + 5] = 0x73; // s
659 crypt->filekey[crypt->filekeylength + 6] = 0x41; // A
660 crypt->filekey[crypt->filekeylength + 7] = 0x6C; // l
661 crypt->filekey[crypt->filekeylength + 8] = 0x54; // T
662 }
663
664 md5_digest(crypt->filekey, crypt->filekeylength + (aes ? 9 : 5), crypt->cryptkey, MD5_BYTES);
665 crypt->cryptkeylength = crypt->filekeylength + 5 >= 16 ? 16 : crypt->filekeylength + 5;
666 }
667 else
668 {
669 memcpy(crypt->cryptkey, crypt->filekey, 32);
670 crypt->cryptkeylength = 32;
671 }
672
673 if (aes)
674 {
675 aes_decode_initialize(&crypt->aesstate, &crypt->aeskeyblock, crypt->cryptkey, crypt->cryptkeylength, NULL);
676 aes_pdf_mode(&crypt->aesstate);
677 }
678 else
679 {
680 rc4_state_initialize(&crypt->rc4state, &crypt->rc4map, crypt->cryptkey, crypt->cryptkeylength);
681 rc4_map_save(&crypt->rc4state, &crypt->rc4copy);
682 }
683 }
684
685 int ppstring_decrypt (ppcrypt *crypt, const void *input, size_t size, void *output, size_t *newsize)
686 {
687 int aes, rc4;
688 aes = crypt->flags & PPCRYPT_STRING_AES;
689 rc4 = crypt->flags & PPCRYPT_STRING_RC4;
690 if (aes || rc4)
691 {
692 ppcrypt_strkey(crypt, crypt->ref, aes);
693 if (aes)
694 *newsize = aes_decode_state_data(&crypt->aesstate, input, size, output);
695 else // if (rc4)
696 *newsize = rc4_decode_state_data(&crypt->rc4state, input, size, output);
697 return 1;
698 }
699 return 0; // identity crypt
700 }
701
702 /* decrypting streams */
703
704 /*
705 Streams are decrypted everytime when accessing the stream data. We need to be able to get or make
706 the key for decryption as long as the stream is alive. And to get the key we need the reference
707 number and version, plus document crypt info. First thought was to keep the reference to which
708 the stream belongs; stream->ref and accessing the crypt info stream->ref->xref->pdf->crypt.
709 It would be ok as long as absolutelly nothing happens with ref and crypt. At some point pplib
710 may drift into rewriting support, which would imply ref/xref/crypt/pdf structures modifications.
711 So I feel better with generating a crypt key for every stream in encrypted document, paying a cost
712 of md5 for all streams, not necessarily those actually read.
713
714 Key generation is the same as for strings, but different for distinct encryption methods (rc4 vs aes).
715 Since streams and strings might theoretically be encrypted with different filters. No reason to cacche
716 decryption state here.
717 */
718
719 ppstring * ppcrypt_stmkey (ppcrypt *crypt, ppref *ref, int aes, ppheap *heap)
720 {
721 ppstring *cryptkeystring;
722 //if (crypt->cryptkeylength > 0)
723 // return;
724
725 if (crypt->algorithm_variant < 5)
726 {
727 crypt->filekey[crypt->filekeylength + 0] = get_number_byte1(ref->number);
728 crypt->filekey[crypt->filekeylength + 1] = get_number_byte2(ref->number);
729 crypt->filekey[crypt->filekeylength + 2] = get_number_byte3(ref->number);
730 crypt->filekey[crypt->filekeylength + 3] = get_number_byte1(ref->version);
731 crypt->filekey[crypt->filekeylength + 4] = get_number_byte2(ref->version);
732
733 if (aes)
734 {
735 crypt->filekey[crypt->filekeylength + 5] = 0x73;
736 crypt->filekey[crypt->filekeylength + 6] = 0x41;
737 crypt->filekey[crypt->filekeylength + 7] = 0x6C;
738 crypt->filekey[crypt->filekeylength + 8] = 0x54;
739 }
740
741 md5_digest(crypt->filekey, crypt->filekeylength + (aes ? 9 : 5), crypt->cryptkey, MD5_BYTES);
742 crypt->cryptkeylength = crypt->filekeylength + 5 >= 16 ? 16 : crypt->filekeylength + 5; // how about 256bits AES??
743 }
744 else
745 { // we could actually generate this string once, but.. aes itself is way more expensive that we can earn here
746 memcpy(crypt->cryptkey, crypt->filekey, 32); // just for the record
747 crypt->cryptkeylength = 32;
748 }
749 cryptkeystring = ppstring_internal(crypt->cryptkey, crypt->cryptkeylength, heap);
750 return ppstring_decoded(cryptkeystring);
751 }