]> rtime.felk.cvut.cz Git - hornmich/skoda-qr-demo.git/blob - QRScanner/mobile/jni/pdf/pdf-crypt.c
Add MuPDF native source codes
[hornmich/skoda-qr-demo.git] / QRScanner / mobile / jni / pdf / pdf-crypt.c
1 #include "mupdf/pdf.h"
2
3 enum
4 {
5         PDF_CRYPT_NONE,
6         PDF_CRYPT_RC4,
7         PDF_CRYPT_AESV2,
8         PDF_CRYPT_AESV3,
9         PDF_CRYPT_UNKNOWN,
10 };
11
12 typedef struct pdf_crypt_filter_s pdf_crypt_filter;
13
14 struct pdf_crypt_filter_s
15 {
16         int method;
17         int length;
18 };
19
20 struct pdf_crypt_s
21 {
22         pdf_obj *id;
23
24         int v;
25         int length;
26         pdf_obj *cf;
27         pdf_crypt_filter stmf;
28         pdf_crypt_filter strf;
29
30         int r;
31         unsigned char o[48];
32         unsigned char u[48];
33         unsigned char oe[32];
34         unsigned char ue[32];
35         int p;
36         int encrypt_metadata;
37
38         unsigned char key[32]; /* decryption key generated from password */
39 };
40
41 static void pdf_parse_crypt_filter(fz_context *ctx, pdf_crypt_filter *cf, pdf_crypt *crypt, char *name);
42
43 /*
44  * Create crypt object for decrypting strings and streams
45  * given the Encryption and ID objects.
46  */
47
48 pdf_crypt *
49 pdf_new_crypt(fz_context *ctx, pdf_obj *dict, pdf_obj *id)
50 {
51         pdf_crypt *crypt;
52         pdf_obj *obj;
53
54         crypt = fz_malloc_struct(ctx, pdf_crypt);
55
56         /* Common to all security handlers (PDF 1.7 table 3.18) */
57
58         obj = pdf_dict_gets(dict, "Filter");
59         if (!pdf_is_name(obj))
60         {
61                 pdf_free_crypt(ctx, crypt);
62                 fz_throw(ctx, FZ_ERROR_GENERIC, "unspecified encryption handler");
63         }
64         if (strcmp(pdf_to_name(obj), "Standard") != 0)
65         {
66                 pdf_free_crypt(ctx, crypt);
67                 fz_throw(ctx, FZ_ERROR_GENERIC, "unknown encryption handler: '%s'", pdf_to_name(obj));
68         }
69
70         crypt->v = 0;
71         obj = pdf_dict_gets(dict, "V");
72         if (pdf_is_int(obj))
73                 crypt->v = pdf_to_int(obj);
74         if (crypt->v != 1 && crypt->v != 2 && crypt->v != 4 && crypt->v != 5)
75         {
76                 pdf_free_crypt(ctx, crypt);
77                 fz_throw(ctx, FZ_ERROR_GENERIC, "unknown encryption version");
78         }
79
80         /* Standard security handler (PDF 1.7 table 3.19) */
81
82         obj = pdf_dict_gets(dict, "R");
83         if (pdf_is_int(obj))
84                 crypt->r = pdf_to_int(obj);
85         else if (crypt->v <= 4)
86         {
87                 fz_warn(ctx, "encryption dictionary missing revision value, guessing...");
88                 if (crypt->v < 2)
89                         crypt->r = 2;
90                 else if (crypt->v == 2)
91                         crypt->r = 3;
92                 else if (crypt->v == 4)
93                         crypt->r = 4;
94         }
95         else
96         {
97                 pdf_free_crypt(ctx, crypt);
98                 fz_throw(ctx, FZ_ERROR_GENERIC, "encryption dictionary missing version and revision value");
99         }
100         if (crypt->r < 1 || crypt->r > 6)
101         {
102                 int r = crypt->r;
103                 pdf_free_crypt(ctx, crypt);
104                 fz_throw(ctx, FZ_ERROR_GENERIC, "unknown crypt revision %d", r);
105         }
106
107         obj = pdf_dict_gets(dict, "O");
108         if (pdf_is_string(obj) && pdf_to_str_len(obj) == 32)
109                 memcpy(crypt->o, pdf_to_str_buf(obj), 32);
110         /* /O and /U are supposed to be 48 bytes long for revision 5 and 6, they're often longer, though */
111         else if (crypt->r >= 5 && pdf_is_string(obj) && pdf_to_str_len(obj) >= 48)
112                 memcpy(crypt->o, pdf_to_str_buf(obj), 48);
113         else
114         {
115                 pdf_free_crypt(ctx, crypt);
116                 fz_throw(ctx, FZ_ERROR_GENERIC, "encryption dictionary missing owner password");
117         }
118
119         obj = pdf_dict_gets(dict, "U");
120         if (pdf_is_string(obj) && pdf_to_str_len(obj) == 32)
121                 memcpy(crypt->u, pdf_to_str_buf(obj), 32);
122         /* /O and /U are supposed to be 48 bytes long for revision 5 and 6, they're often longer, though */
123         else if (crypt->r >= 5 && pdf_is_string(obj) && pdf_to_str_len(obj) >= 48)
124                 memcpy(crypt->u, pdf_to_str_buf(obj), 48);
125         else if (pdf_is_string(obj) && pdf_to_str_len(obj) < 32)
126         {
127                 fz_warn(ctx, "encryption password key too short (%d)", pdf_to_str_len(obj));
128                 memcpy(crypt->u, pdf_to_str_buf(obj), pdf_to_str_len(obj));
129         }
130         else
131         {
132                 pdf_free_crypt(ctx, crypt);
133                 fz_throw(ctx, FZ_ERROR_GENERIC, "encryption dictionary missing user password");
134         }
135
136         obj = pdf_dict_gets(dict, "P");
137         if (pdf_is_int(obj))
138                 crypt->p = pdf_to_int(obj);
139         else
140         {
141                 fz_warn(ctx, "encryption dictionary missing permissions");
142                 crypt->p = 0xfffffffc;
143         }
144
145         if (crypt->r == 5 || crypt->r == 6)
146         {
147                 obj = pdf_dict_gets(dict, "OE");
148                 if (!pdf_is_string(obj) || pdf_to_str_len(obj) != 32)
149                 {
150                         pdf_free_crypt(ctx, crypt);
151                         fz_throw(ctx, FZ_ERROR_GENERIC, "encryption dictionary missing owner encryption key");
152                 }
153                 memcpy(crypt->oe, pdf_to_str_buf(obj), 32);
154
155                 obj = pdf_dict_gets(dict, "UE");
156                 if (!pdf_is_string(obj) || pdf_to_str_len(obj) != 32)
157                 {
158                         pdf_free_crypt(ctx, crypt);
159                         fz_throw(ctx, FZ_ERROR_GENERIC, "encryption dictionary missing user encryption key");
160                 }
161                 memcpy(crypt->ue, pdf_to_str_buf(obj), 32);
162         }
163
164         crypt->encrypt_metadata = 1;
165         obj = pdf_dict_gets(dict, "EncryptMetadata");
166         if (pdf_is_bool(obj))
167                 crypt->encrypt_metadata = pdf_to_bool(obj);
168
169         /* Extract file identifier string */
170
171         if (pdf_is_array(id) && pdf_array_len(id) == 2)
172         {
173                 obj = pdf_array_get(id, 0);
174                 if (pdf_is_string(obj))
175                         crypt->id = pdf_keep_obj(obj);
176         }
177         else
178                 fz_warn(ctx, "missing file identifier, may not be able to do decryption");
179
180         /* Determine encryption key length */
181
182         crypt->length = 40;
183         if (crypt->v == 2 || crypt->v == 4)
184         {
185                 obj = pdf_dict_gets(dict, "Length");
186                 if (pdf_is_int(obj))
187                         crypt->length = pdf_to_int(obj);
188
189                 /* work-around for pdf generators that assume length is in bytes */
190                 if (crypt->length < 40)
191                         crypt->length = crypt->length * 8;
192
193                 if (crypt->length % 8 != 0)
194                 {
195                         pdf_free_crypt(ctx, crypt);
196                         fz_throw(ctx, FZ_ERROR_GENERIC, "invalid encryption key length");
197                 }
198                 if (crypt->length < 40 || crypt->length > 128)
199                 {
200                         pdf_free_crypt(ctx, crypt);
201                         fz_throw(ctx, FZ_ERROR_GENERIC, "invalid encryption key length");
202                 }
203         }
204
205         if (crypt->v == 5)
206                 crypt->length = 256;
207
208         if (crypt->v == 1 || crypt->v == 2)
209         {
210                 crypt->stmf.method = PDF_CRYPT_RC4;
211                 crypt->stmf.length = crypt->length;
212
213                 crypt->strf.method = PDF_CRYPT_RC4;
214                 crypt->strf.length = crypt->length;
215         }
216
217         if (crypt->v == 4 || crypt->v == 5)
218         {
219                 crypt->stmf.method = PDF_CRYPT_NONE;
220                 crypt->stmf.length = crypt->length;
221
222                 crypt->strf.method = PDF_CRYPT_NONE;
223                 crypt->strf.length = crypt->length;
224
225                 obj = pdf_dict_gets(dict, "CF");
226                 if (pdf_is_dict(obj))
227                 {
228                         crypt->cf = pdf_keep_obj(obj);
229                 }
230                 else
231                 {
232                         crypt->cf = NULL;
233                 }
234
235                 fz_try(ctx)
236                 {
237                         obj = pdf_dict_gets(dict, "StmF");
238                         if (pdf_is_name(obj))
239                                 pdf_parse_crypt_filter(ctx, &crypt->stmf, crypt, pdf_to_name(obj));
240
241                         obj = pdf_dict_gets(dict, "StrF");
242                         if (pdf_is_name(obj))
243                                 pdf_parse_crypt_filter(ctx, &crypt->strf, crypt, pdf_to_name(obj));
244                 }
245                 fz_catch(ctx)
246                 {
247                         pdf_free_crypt(ctx, crypt);
248                         fz_rethrow_message(ctx, "cannot parse string crypt filter (%d %d R)", pdf_to_num(obj), pdf_to_gen(obj));
249                 }
250
251                 /* in crypt revision 4, the crypt filter determines the key length */
252                 if (crypt->strf.method != PDF_CRYPT_NONE)
253                         crypt->length = crypt->stmf.length;
254         }
255
256         return crypt;
257 }
258
259 void
260 pdf_free_crypt(fz_context *ctx, pdf_crypt *crypt)
261 {
262         pdf_drop_obj(crypt->id);
263         pdf_drop_obj(crypt->cf);
264         fz_free(ctx, crypt);
265 }
266
267 /*
268  * Parse a CF dictionary entry (PDF 1.7 table 3.22)
269  */
270
271 static void
272 pdf_parse_crypt_filter(fz_context *ctx, pdf_crypt_filter *cf, pdf_crypt *crypt, char *name)
273 {
274         pdf_obj *obj;
275         pdf_obj *dict;
276         int is_identity = (strcmp(name, "Identity") == 0);
277         int is_stdcf = (!is_identity && (strcmp(name, "StdCF") == 0));
278
279         if (!is_identity && !is_stdcf)
280                 fz_throw(ctx, FZ_ERROR_GENERIC, "Crypt Filter not Identity or StdCF (%d %d R)", pdf_to_num(crypt->cf), pdf_to_gen(crypt->cf));
281
282         cf->method = PDF_CRYPT_NONE;
283         cf->length = crypt->length;
284
285         if (!crypt->cf)
286         {
287                 cf->method = (is_identity ? PDF_CRYPT_NONE : PDF_CRYPT_RC4);
288                 return;
289         }
290
291         dict = pdf_dict_gets(crypt->cf, name);
292         if (!pdf_is_dict(dict))
293                 fz_throw(ctx, FZ_ERROR_GENERIC, "cannot parse crypt filter (%d %d R)", pdf_to_num(crypt->cf), pdf_to_gen(crypt->cf));
294
295         obj = pdf_dict_gets(dict, "CFM");
296         if (pdf_is_name(obj))
297         {
298                 if (!strcmp(pdf_to_name(obj), "None"))
299                         cf->method = PDF_CRYPT_NONE;
300                 else if (!strcmp(pdf_to_name(obj), "V2"))
301                         cf->method = PDF_CRYPT_RC4;
302                 else if (!strcmp(pdf_to_name(obj), "AESV2"))
303                         cf->method = PDF_CRYPT_AESV2;
304                 else if (!strcmp(pdf_to_name(obj), "AESV3"))
305                         cf->method = PDF_CRYPT_AESV3;
306                 else
307                         fz_warn(ctx, "unknown encryption method: %s", pdf_to_name(obj));
308         }
309
310         obj = pdf_dict_gets(dict, "Length");
311         if (pdf_is_int(obj))
312                 cf->length = pdf_to_int(obj);
313
314         /* the length for crypt filters is supposed to be in bytes not bits */
315         if (cf->length < 40)
316                 cf->length = cf->length * 8;
317
318         if ((cf->length % 8) != 0)
319                 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid key length: %d", cf->length);
320
321         if ((crypt->r == 1 || crypt->r == 2 || crypt->r == 3 || crypt->r == 4) &&
322                 (cf->length < 0 || cf->length > 128))
323                 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid key length: %d", cf->length);
324         if ((crypt->r == 5 || crypt->r == 6) && cf->length != 256)
325                 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid key length: %d", cf->length);
326 }
327
328 /*
329  * Compute an encryption key (PDF 1.7 algorithm 3.2)
330  */
331
332 static const unsigned char padding[32] =
333 {
334         0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
335         0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
336         0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
337         0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
338 };
339
340 static void
341 pdf_compute_encryption_key(pdf_crypt *crypt, unsigned char *password, int pwlen, unsigned char *key)
342 {
343         unsigned char buf[32];
344         unsigned int p;
345         int i, n;
346         fz_md5 md5;
347
348         n = crypt->length / 8;
349
350         /* Step 1 - copy and pad password string */
351         if (pwlen > 32)
352                 pwlen = 32;
353         memcpy(buf, password, pwlen);
354         memcpy(buf + pwlen, padding, 32 - pwlen);
355
356         /* Step 2 - init md5 and pass value of step 1 */
357         fz_md5_init(&md5);
358         fz_md5_update(&md5, buf, 32);
359
360         /* Step 3 - pass O value */
361         fz_md5_update(&md5, crypt->o, 32);
362
363         /* Step 4 - pass P value as unsigned int, low-order byte first */
364         p = (unsigned int) crypt->p;
365         buf[0] = (p) & 0xFF;
366         buf[1] = (p >> 8) & 0xFF;
367         buf[2] = (p >> 16) & 0xFF;
368         buf[3] = (p >> 24) & 0xFF;
369         fz_md5_update(&md5, buf, 4);
370
371         /* Step 5 - pass first element of ID array */
372         fz_md5_update(&md5, (unsigned char *)pdf_to_str_buf(crypt->id), pdf_to_str_len(crypt->id));
373
374         /* Step 6 (revision 4 or greater) - if metadata is not encrypted pass 0xFFFFFFFF */
375         if (crypt->r >= 4)
376         {
377                 if (!crypt->encrypt_metadata)
378                 {
379                         buf[0] = 0xFF;
380                         buf[1] = 0xFF;
381                         buf[2] = 0xFF;
382                         buf[3] = 0xFF;
383                         fz_md5_update(&md5, buf, 4);
384                 }
385         }
386
387         /* Step 7 - finish the hash */
388         fz_md5_final(&md5, buf);
389
390         /* Step 8 (revision 3 or greater) - do some voodoo 50 times */
391         if (crypt->r >= 3)
392         {
393                 for (i = 0; i < 50; i++)
394                 {
395                         fz_md5_init(&md5);
396                         fz_md5_update(&md5, buf, n);
397                         fz_md5_final(&md5, buf);
398                 }
399         }
400
401         /* Step 9 - the key is the first 'n' bytes of the result */
402         memcpy(key, buf, n);
403 }
404
405 /*
406  * Compute an encryption key (PDF 1.7 ExtensionLevel 3 algorithm 3.2a)
407  */
408
409 static void
410 pdf_compute_encryption_key_r5(fz_context *ctx, pdf_crypt *crypt, unsigned char *password, int pwlen, int ownerkey, unsigned char *validationkey)
411 {
412         unsigned char buffer[128 + 8 + 48];
413         fz_sha256 sha256;
414         fz_aes aes;
415
416         /* Step 2 - truncate UTF-8 password to 127 characters */
417
418         if (pwlen > 127)
419                 pwlen = 127;
420
421         /* Step 3/4 - test password against owner/user key and compute encryption key */
422
423         memcpy(buffer, password, pwlen);
424         if (ownerkey)
425         {
426                 memcpy(buffer + pwlen, crypt->o + 32, 8);
427                 memcpy(buffer + pwlen + 8, crypt->u, 48);
428         }
429         else
430                 memcpy(buffer + pwlen, crypt->u + 32, 8);
431
432         fz_sha256_init(&sha256);
433         fz_sha256_update(&sha256, buffer, pwlen + 8 + (ownerkey ? 48 : 0));
434         fz_sha256_final(&sha256, validationkey);
435
436         /* Step 3.5/4.5 - compute file encryption key from OE/UE */
437
438         memcpy(buffer + pwlen, crypt->u + 40, 8);
439
440         fz_sha256_init(&sha256);
441         fz_sha256_update(&sha256, buffer, pwlen + 8);
442         fz_sha256_final(&sha256, buffer);
443
444         /* clear password buffer and use it as iv */
445         memset(buffer + 32, 0, sizeof(buffer) - 32);
446         if (aes_setkey_dec(&aes, buffer, crypt->length))
447                 fz_throw(ctx, FZ_ERROR_GENERIC, "AES key init failed (keylen=%d)", crypt->length);
448         aes_crypt_cbc(&aes, AES_DECRYPT, 32, buffer + 32, ownerkey ? crypt->oe : crypt->ue, crypt->key);
449 }
450
451 /*
452  * Compute an encryption key (PDF 1.7 ExtensionLevel 8 algorithm)
453  *
454  * Adobe has not yet released the details, so the algorithm reference is:
455  * http://esec-lab.sogeti.com/post/The-undocumented-password-validation-algorithm-of-Adobe-Reader-X
456  */
457
458 static void
459 pdf_compute_hardened_hash_r6(fz_context *ctx, unsigned char *password, int pwlen, unsigned char salt[16], unsigned char *ownerkey, unsigned char hash[32])
460 {
461         unsigned char data[(128 + 64 + 48) * 64];
462         unsigned char block[64];
463         int block_size = 32;
464         int data_len = 0;
465         int i, j, sum;
466
467         fz_sha256 sha256;
468         fz_sha384 sha384;
469         fz_sha512 sha512;
470         fz_aes aes;
471
472         /* Step 1: calculate initial data block */
473         fz_sha256_init(&sha256);
474         fz_sha256_update(&sha256, password, pwlen);
475         fz_sha256_update(&sha256, salt, 8);
476         if (ownerkey)
477                 fz_sha256_update(&sha256, ownerkey, 48);
478         fz_sha256_final(&sha256, block);
479
480         for (i = 0; i < 64 || i < data[data_len * 64 - 1] + 32; i++)
481         {
482                 /* Step 2: repeat password and data block 64 times */
483                 memcpy(data, password, pwlen);
484                 memcpy(data + pwlen, block, block_size);
485                 if (ownerkey)
486                         memcpy(data + pwlen + block_size, ownerkey, 48);
487                 data_len = pwlen + block_size + (ownerkey ? 48 : 0);
488                 for (j = 1; j < 64; j++)
489                         memcpy(data + j * data_len, data, data_len);
490
491                 /* Step 3: encrypt data using data block as key and iv */
492                 if (aes_setkey_enc(&aes, block, 128))
493                         fz_throw(ctx, FZ_ERROR_GENERIC, "AES key init failed (keylen=%d)", 128);
494                 aes_crypt_cbc(&aes, AES_ENCRYPT, data_len * 64, block + 16, data, data);
495
496                 /* Step 4: determine SHA-2 hash size for this round */
497                 for (j = 0, sum = 0; j < 16; j++)
498                         sum += data[j];
499
500                 /* Step 5: calculate data block for next round */
501                 block_size = 32 + (sum % 3) * 16;
502                 switch (block_size)
503                 {
504                 case 32:
505                         fz_sha256_init(&sha256);
506                         fz_sha256_update(&sha256, data, data_len * 64);
507                         fz_sha256_final(&sha256, block);
508                         break;
509                 case 48:
510                         fz_sha384_init(&sha384);
511                         fz_sha384_update(&sha384, data, data_len * 64);
512                         fz_sha384_final(&sha384, block);
513                         break;
514                 case 64:
515                         fz_sha512_init(&sha512);
516                         fz_sha512_update(&sha512, data, data_len * 64);
517                         fz_sha512_final(&sha512, block);
518                         break;
519                 }
520         }
521
522         memset(data, 0, sizeof(data));
523         memcpy(hash, block, 32);
524 }
525
526 static void
527 pdf_compute_encryption_key_r6(fz_context *ctx, pdf_crypt *crypt, unsigned char *password, int pwlen, int ownerkey, unsigned char *validationkey)
528 {
529         unsigned char hash[32];
530         unsigned char iv[16];
531         fz_aes aes;
532
533         if (pwlen > 127)
534                 pwlen = 127;
535
536         pdf_compute_hardened_hash_r6(ctx, password, pwlen,
537                 (ownerkey ? crypt->o : crypt->u) + 32,
538                 ownerkey ? crypt->u : NULL, validationkey);
539         pdf_compute_hardened_hash_r6(ctx, password, pwlen,
540                 crypt->u + 40, NULL, hash);
541
542         memset(iv, 0, sizeof(iv));
543         if (aes_setkey_dec(&aes, hash, 256))
544                 fz_throw(ctx, FZ_ERROR_GENERIC, "AES key init failed (keylen=256)");
545         aes_crypt_cbc(&aes, AES_DECRYPT, 32, iv,
546                 ownerkey ? crypt->oe : crypt->ue, crypt->key);
547 }
548
549 /*
550  * Computing the user password (PDF 1.7 algorithm 3.4 and 3.5)
551  * Also save the generated key for decrypting objects and streams in crypt->key.
552  */
553
554 static void
555 pdf_compute_user_password(fz_context *ctx, pdf_crypt *crypt, unsigned char *password, int pwlen, unsigned char *output)
556 {
557         if (crypt->r == 2)
558         {
559                 fz_arc4 arc4;
560
561                 pdf_compute_encryption_key(crypt, password, pwlen, crypt->key);
562                 fz_arc4_init(&arc4, crypt->key, crypt->length / 8);
563                 fz_arc4_encrypt(&arc4, output, padding, 32);
564         }
565
566         if (crypt->r == 3 || crypt->r == 4)
567         {
568                 unsigned char xor[32];
569                 unsigned char digest[16];
570                 fz_md5 md5;
571                 fz_arc4 arc4;
572                 int i, x, n;
573
574                 n = crypt->length / 8;
575
576                 pdf_compute_encryption_key(crypt, password, pwlen, crypt->key);
577
578                 fz_md5_init(&md5);
579                 fz_md5_update(&md5, padding, 32);
580                 fz_md5_update(&md5, (unsigned char*)pdf_to_str_buf(crypt->id), pdf_to_str_len(crypt->id));
581                 fz_md5_final(&md5, digest);
582
583                 fz_arc4_init(&arc4, crypt->key, n);
584                 fz_arc4_encrypt(&arc4, output, digest, 16);
585
586                 for (x = 1; x <= 19; x++)
587                 {
588                         for (i = 0; i < n; i++)
589                                 xor[i] = crypt->key[i] ^ x;
590                         fz_arc4_init(&arc4, xor, n);
591                         fz_arc4_encrypt(&arc4, output, output, 16);
592                 }
593
594                 memcpy(output + 16, padding, 16);
595         }
596
597         if (crypt->r == 5)
598         {
599                 pdf_compute_encryption_key_r5(ctx, crypt, password, pwlen, 0, output);
600         }
601
602         if (crypt->r == 6)
603         {
604                 pdf_compute_encryption_key_r6(ctx, crypt, password, pwlen, 0, output);
605         }
606 }
607
608 /*
609  * Authenticating the user password (PDF 1.7 algorithm 3.6
610  * and ExtensionLevel 3 algorithm 3.11)
611  * This also has the side effect of saving a key generated
612  * from the password for decrypting objects and streams.
613  */
614
615 static int
616 pdf_authenticate_user_password(fz_context *ctx, pdf_crypt *crypt, unsigned char *password, int pwlen)
617 {
618         unsigned char output[32];
619         pdf_compute_user_password(ctx, crypt, password, pwlen, output);
620         if (crypt->r == 2 || crypt->r == 5 || crypt->r == 6)
621                 return memcmp(output, crypt->u, 32) == 0;
622         if (crypt->r == 3 || crypt->r == 4)
623                 return memcmp(output, crypt->u, 16) == 0;
624         return 0;
625 }
626
627 /*
628  * Authenticating the owner password (PDF 1.7 algorithm 3.7
629  * and ExtensionLevel 3 algorithm 3.12)
630  * Generates the user password from the owner password
631  * and calls pdf_authenticate_user_password.
632  */
633
634 static int
635 pdf_authenticate_owner_password(fz_context *ctx, pdf_crypt *crypt, unsigned char *ownerpass, int pwlen)
636 {
637         unsigned char pwbuf[32];
638         unsigned char key[32];
639         unsigned char xor[32];
640         unsigned char userpass[32];
641         int i, n, x;
642         fz_md5 md5;
643         fz_arc4 arc4;
644
645         if (crypt->r == 5)
646         {
647                 /* PDF 1.7 ExtensionLevel 3 algorithm 3.12 */
648                 pdf_compute_encryption_key_r5(ctx, crypt, ownerpass, pwlen, 1, key);
649                 return !memcmp(key, crypt->o, 32);
650         }
651         else if (crypt->r == 6)
652         {
653                 /* PDF 1.7 ExtensionLevel 8 algorithm */
654                 pdf_compute_encryption_key_r6(ctx, crypt, ownerpass, pwlen, 1, key);
655                 return !memcmp(key, crypt->o, 32);
656         }
657
658         n = crypt->length / 8;
659
660         /* Step 1 -- steps 1 to 4 of PDF 1.7 algorithm 3.3 */
661
662         /* copy and pad password string */
663         if (pwlen > 32)
664                 pwlen = 32;
665         memcpy(pwbuf, ownerpass, pwlen);
666         memcpy(pwbuf + pwlen, padding, 32 - pwlen);
667
668         /* take md5 hash of padded password */
669         fz_md5_init(&md5);
670         fz_md5_update(&md5, pwbuf, 32);
671         fz_md5_final(&md5, key);
672
673         /* do some voodoo 50 times (Revision 3 or greater) */
674         if (crypt->r >= 3)
675         {
676                 for (i = 0; i < 50; i++)
677                 {
678                         fz_md5_init(&md5);
679                         fz_md5_update(&md5, key, 16);
680                         fz_md5_final(&md5, key);
681                 }
682         }
683
684         /* Step 2 (Revision 2) */
685         if (crypt->r == 2)
686         {
687                 fz_arc4_init(&arc4, key, n);
688                 fz_arc4_encrypt(&arc4, userpass, crypt->o, 32);
689         }
690
691         /* Step 2 (Revision 3 or greater) */
692         if (crypt->r >= 3)
693         {
694                 memcpy(userpass, crypt->o, 32);
695                 for (x = 0; x < 20; x++)
696                 {
697                         for (i = 0; i < n; i++)
698                                 xor[i] = key[i] ^ (19 - x);
699                         fz_arc4_init(&arc4, xor, n);
700                         fz_arc4_encrypt(&arc4, userpass, userpass, 32);
701                 }
702         }
703
704         return pdf_authenticate_user_password(ctx, crypt, userpass, 32);
705 }
706
707 static void pdf_docenc_from_utf8(char *password, const char *utf8, int n)
708 {
709         int i = 0, k, c;
710         while (*utf8 && i + 1 < n)
711         {
712                 utf8 += fz_chartorune(&c, utf8);
713                 for (k = 0; k < 256; k++)
714                 {
715                         if (c == pdf_doc_encoding[k])
716                         {
717                                 password[i++] = k;
718                                 break;
719                         }
720                 }
721                 /* FIXME: drop characters that can't be encoded or return an error? */
722         }
723         password[i] = 0;
724 }
725
726 static void pdf_saslprep_from_utf8(char *password, const char *utf8, int n)
727 {
728         /* TODO: stringprep with SALSprep profile */
729         fz_strlcpy(password, utf8, n);
730 }
731
732 int
733 pdf_authenticate_password(pdf_document *doc, const char *pwd_utf8)
734 {
735         char password[2048];
736
737         if (doc->crypt)
738         {
739                 password[0] = 0;
740                 if (pwd_utf8)
741                 {
742                         if (doc->crypt->r <= 4)
743                                 pdf_docenc_from_utf8(password, pwd_utf8, sizeof password);
744                         else
745                                 pdf_saslprep_from_utf8(password, pwd_utf8, sizeof password);
746                 }
747
748                 if (pdf_authenticate_user_password(doc->ctx, doc->crypt, (unsigned char *)password, strlen(password)))
749                         return 1;
750                 if (pdf_authenticate_owner_password(doc->ctx, doc->crypt, (unsigned char *)password, strlen(password)))
751                         return 1;
752                 return 0;
753         }
754         return 1;
755 }
756
757 int
758 pdf_needs_password(pdf_document *doc)
759 {
760         if (!doc->crypt)
761                 return 0;
762         if (pdf_authenticate_password(doc, ""))
763                 return 0;
764         return 1;
765 }
766
767 int
768 pdf_has_permission(pdf_document *doc, int p)
769 {
770         if (!doc->crypt)
771                 return 1;
772         return doc->crypt->p & p;
773 }
774
775 unsigned char *
776 pdf_crypt_key(pdf_document *doc)
777 {
778         if (doc->crypt)
779                 return doc->crypt->key;
780         return NULL;
781 }
782
783 int
784 pdf_crypt_version(pdf_document *doc)
785 {
786         if (doc->crypt)
787                 return doc->crypt->v;
788         return 0;
789 }
790
791 int pdf_crypt_revision(pdf_document *doc)
792 {
793         if (doc->crypt)
794                 return doc->crypt->r;
795         return 0;
796 }
797
798 char *
799 pdf_crypt_method(pdf_document *doc)
800 {
801         if (doc->crypt)
802         {
803                 switch (doc->crypt->strf.method)
804                 {
805                 case PDF_CRYPT_NONE: return "None";
806                 case PDF_CRYPT_RC4: return "RC4";
807                 case PDF_CRYPT_AESV2: return "AES";
808                 case PDF_CRYPT_AESV3: return "AES";
809                 case PDF_CRYPT_UNKNOWN: return "Unknown";
810                 }
811         }
812         return "None";
813 }
814
815 int
816 pdf_crypt_length(pdf_document *doc)
817 {
818         if (doc->crypt)
819                 return doc->crypt->length;
820         return 0;
821 }
822
823 /*
824  * PDF 1.7 algorithm 3.1 and ExtensionLevel 3 algorithm 3.1a
825  *
826  * Using the global encryption key that was generated from the
827  * password, create a new key that is used to decrypt individual
828  * objects and streams. This key is based on the object and
829  * generation numbers.
830  */
831
832 static int
833 pdf_compute_object_key(pdf_crypt *crypt, pdf_crypt_filter *cf, int num, int gen, unsigned char *key, int max_len)
834 {
835         fz_md5 md5;
836         unsigned char message[5];
837         int key_len = crypt->length / 8;
838
839         if (key_len > max_len)
840                 key_len = max_len;
841
842         if (cf->method == PDF_CRYPT_AESV3)
843         {
844                 memcpy(key, crypt->key, key_len);
845                 return key_len;
846         }
847
848         fz_md5_init(&md5);
849         fz_md5_update(&md5, crypt->key, key_len);
850         message[0] = (num) & 0xFF;
851         message[1] = (num >> 8) & 0xFF;
852         message[2] = (num >> 16) & 0xFF;
853         message[3] = (gen) & 0xFF;
854         message[4] = (gen >> 8) & 0xFF;
855         fz_md5_update(&md5, message, 5);
856
857         if (cf->method == PDF_CRYPT_AESV2)
858                 fz_md5_update(&md5, (unsigned char *)"sAlT", 4);
859
860         fz_md5_final(&md5, key);
861
862         if (key_len + 5 > 16)
863                 return 16;
864         return key_len + 5;
865 }
866
867 /*
868  * PDF 1.7 algorithm 3.1 and ExtensionLevel 3 algorithm 3.1a
869  *
870  * Decrypt all strings in obj modifying the data in-place.
871  * Recurse through arrays and dictionaries, but do not follow
872  * indirect references.
873  */
874
875 static void
876 pdf_crypt_obj_imp(fz_context *ctx, pdf_crypt *crypt, pdf_obj *obj, unsigned char *key, int keylen)
877 {
878         unsigned char *s;
879         int i, n;
880
881         if (pdf_is_indirect(obj))
882                 return;
883
884         if (pdf_is_string(obj))
885         {
886                 s = (unsigned char *)pdf_to_str_buf(obj);
887                 n = pdf_to_str_len(obj);
888
889                 if (crypt->strf.method == PDF_CRYPT_RC4)
890                 {
891                         fz_arc4 arc4;
892                         fz_arc4_init(&arc4, key, keylen);
893                         fz_arc4_encrypt(&arc4, s, s, n);
894                 }
895
896                 if (crypt->strf.method == PDF_CRYPT_AESV2 || crypt->strf.method == PDF_CRYPT_AESV3)
897                 {
898                         if (n == 0)
899                         {
900                                 /* Empty strings are permissible */
901                         }
902                         else if (n & 15 || n < 32)
903                                 fz_warn(ctx, "invalid string length for aes encryption");
904                         else
905                         {
906                                 unsigned char iv[16];
907                                 fz_aes aes;
908                                 memcpy(iv, s, 16);
909                                 if (aes_setkey_dec(&aes, key, keylen * 8))
910                                         fz_throw(ctx, FZ_ERROR_GENERIC, "AES key init failed (keylen=%d)", keylen * 8);
911                                 aes_crypt_cbc(&aes, AES_DECRYPT, n - 16, iv, s + 16, s);
912                                 /* delete space used for iv and padding bytes at end */
913                                 if (s[n - 17] < 1 || s[n - 17] > 16)
914                                         fz_warn(ctx, "aes padding out of range");
915                                 else
916                                         pdf_set_str_len(obj, n - 16 - s[n - 17]);
917                         }
918                 }
919         }
920
921         else if (pdf_is_array(obj))
922         {
923                 n = pdf_array_len(obj);
924                 for (i = 0; i < n; i++)
925                 {
926                         pdf_crypt_obj_imp(ctx, crypt, pdf_array_get(obj, i), key, keylen);
927                 }
928         }
929
930         else if (pdf_is_dict(obj))
931         {
932                 n = pdf_dict_len(obj);
933                 for (i = 0; i < n; i++)
934                 {
935                         pdf_crypt_obj_imp(ctx, crypt, pdf_dict_get_val(obj, i), key, keylen);
936                 }
937         }
938 }
939
940 void
941 pdf_crypt_obj(fz_context *ctx, pdf_crypt *crypt, pdf_obj *obj, int num, int gen)
942 {
943         unsigned char key[32];
944         int len;
945
946         len = pdf_compute_object_key(crypt, &crypt->strf, num, gen, key, 32);
947
948         pdf_crypt_obj_imp(ctx, crypt, obj, key, len);
949 }
950
951 /*
952  * PDF 1.7 algorithm 3.1 and ExtensionLevel 3 algorithm 3.1a
953  *
954  * Create filter suitable for de/encrypting a stream.
955  */
956 static fz_stream *
957 pdf_open_crypt_imp(fz_stream *chain, pdf_crypt *crypt, pdf_crypt_filter *stmf, int num, int gen)
958 {
959         unsigned char key[32];
960         int len;
961
962         len = pdf_compute_object_key(crypt, stmf, num, gen, key, 32);
963
964         if (stmf->method == PDF_CRYPT_RC4)
965                 return fz_open_arc4(chain, key, len);
966
967         if (stmf->method == PDF_CRYPT_AESV2 || stmf->method == PDF_CRYPT_AESV3)
968                 return fz_open_aesd(chain, key, len);
969
970         return fz_open_copy(chain);
971 }
972
973 fz_stream *
974 pdf_open_crypt(fz_stream *chain, pdf_crypt *crypt, int num, int gen)
975 {
976         return pdf_open_crypt_imp(chain, crypt, &crypt->stmf, num, gen);
977 }
978
979 fz_stream *
980 pdf_open_crypt_with_filter(fz_stream *chain, pdf_crypt *crypt, char *name, int num, int gen)
981 {
982         if (strcmp(name, "Identity"))
983         {
984                 pdf_crypt_filter cf;
985                 pdf_parse_crypt_filter(chain->ctx, &cf, crypt, name);
986                 return pdf_open_crypt_imp(chain, crypt, &cf, num, gen);
987         }
988         return chain;
989 }
990
991 #ifndef NDEBUG
992 void pdf_print_crypt(pdf_crypt *crypt)
993 {
994         int i;
995
996         printf("crypt {\n");
997
998         printf("\tv=%d length=%d\n", crypt->v, crypt->length);
999         printf("\tstmf method=%d length=%d\n", crypt->stmf.method, crypt->stmf.length);
1000         printf("\tstrf method=%d length=%d\n", crypt->strf.method, crypt->strf.length);
1001         printf("\tr=%d\n", crypt->r);
1002
1003         printf("\to=<");
1004         for (i = 0; i < 32; i++)
1005                 printf("%02X", crypt->o[i]);
1006         printf(">\n");
1007
1008         printf("\tu=<");
1009         for (i = 0; i < 32; i++)
1010                 printf("%02X", crypt->u[i]);
1011         printf(">\n");
1012
1013         printf("}\n");
1014 }
1015 #endif