forked from hy05190134/PdfTextExtract
/
crypt.go
1294 lines (1119 loc) · 34.2 KB
/
crypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.md', which is part of this source code package.
*/
package core
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rc4"
"errors"
"fmt"
"io"
"../common"
)
// PdfCrypt provides PDF encryption/decryption support.
// The PDF standard supports encryption of strings and streams (Section 7.6).
// TODO (v3): Consider unexporting.
type PdfCrypt struct {
Filter string
Subfilter string
V int
Length int
R int
O []byte
U []byte
P int
EncryptMetadata bool
Id0 string
EncryptionKey []byte
DecryptedObjects map[PdfObject]bool
EncryptedObjects map[PdfObject]bool
Authenticated bool
// Crypt filters (V4).
CryptFilters CryptFilters
StreamFilter string
StringFilter string
parser *PdfParser
}
// AccessPermissions is a list of access permissions for a PDF file.
type AccessPermissions struct {
Printing bool
Modify bool
ExtractGraphics bool
Annotate bool
// Allow form filling, if annotation is disabled? If annotation enabled, is not looked at.
FillForms bool
DisabilityExtract bool // not clear what this means!
// Allow rotating, editing page order.
RotateInsert bool
// Limit print quality (lowres), assuming Printing is true.
FullPrintQuality bool
}
const padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF" +
"\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C" +
"\xA9\xFE\x64\x53\x69\x7A"
// CryptFilter represents information from a CryptFilter dictionary.
// TODO (v3): Unexport.
type CryptFilter struct {
Cfm string
Length int
}
// CryptFilters is a map of crypt filter name and underlying CryptFilter info.
// TODO (v3): Unexport.
type CryptFilters map[string]CryptFilter
// LoadCryptFilters loads crypt filter information from the encryption dictionary (V4 only).
// TODO (v3): Unexport.
func (crypt *PdfCrypt) LoadCryptFilters(ed *PdfObjectDictionary) error {
crypt.CryptFilters = CryptFilters{}
obj := ed.Get("CF")
obj = TraceToDirectObject(obj) // XXX may need to resolve reference...
if ref, isRef := obj.(*PdfObjectReference); isRef {
o, err := crypt.parser.LookupByReference(*ref)
if err != nil {
common.Log.Debug("Error looking up CF reference")
return err
}
obj = TraceToDirectObject(o)
}
cf, ok := obj.(*PdfObjectDictionary)
if !ok {
common.Log.Debug("Invalid CF, type: %T", obj)
return errors.New("Invalid CF")
}
for _, name := range cf.Keys() {
v := cf.Get(name)
if ref, isRef := v.(*PdfObjectReference); isRef {
o, err := crypt.parser.LookupByReference(*ref)
if err != nil {
common.Log.Debug("Error lookup up dictionary reference")
return err
}
v = TraceToDirectObject(o)
}
dict, ok := v.(*PdfObjectDictionary)
if !ok {
return fmt.Errorf("Invalid dict in CF (name %s) - not a dictionary but %T", name, v)
}
if name == "Identity" {
common.Log.Debug("ERROR - Cannot overwrite the identity filter - Trying next")
continue
}
// If Type present, should be CryptFilter.
if typename, ok := dict.Get("Type").(*PdfObjectName); ok {
if string(*typename) != "CryptFilter" {
return fmt.Errorf("CF dict type != CryptFilter (%s)", typename)
}
}
cf := CryptFilter{}
// Method.
cfMethod := "None" // Default.
cfm, ok := dict.Get("CFM").(*PdfObjectName)
if ok {
if *cfm == "V2" {
cfMethod = "V2"
} else if *cfm == "AESV2" {
cfMethod = "AESV2"
} else {
return fmt.Errorf("Unsupported crypt filter (%s)", *cfm)
}
}
if cfMethod != "V2" && cfMethod != "AESV2" {
return fmt.Errorf("Unsupported crypt filter (%s)", cfMethod)
}
cf.Cfm = cfMethod
// Length.
cf.Length = 0
length, ok := dict.Get("Length").(*PdfObjectInteger)
if ok {
if *length%8 != 0 {
return fmt.Errorf("Crypt filter length not multiple of 8 (%d)", *length)
}
// Standard security handler expresses the length in multiples of 8 (16 means 128)
// We only deal with standard so far. (Public key not supported yet).
if *length < 5 || *length > 16 {
if *length == 64 || *length == 128 {
common.Log.Debug("STANDARD VIOLATION: Crypt Length appears to be in bits rather than bytes - assuming bits (%d)", *length)
*length /= 8
} else {
return fmt.Errorf("Crypt filter length not in range 40 - 128 bit (%d)", *length)
}
}
cf.Length = int(*length)
}
crypt.CryptFilters[string(name)] = cf
}
// Cannot be overwritten.
crypt.CryptFilters["Identity"] = CryptFilter{}
// StrF strings filter.
crypt.StringFilter = "Identity"
if strf, ok := ed.Get("StrF").(*PdfObjectName); ok {
if _, exists := crypt.CryptFilters[string(*strf)]; !exists {
return fmt.Errorf("Crypt filter for StrF not specified in CF dictionary (%s)", *strf)
}
crypt.StringFilter = string(*strf)
}
// StmF streams filter.
crypt.StreamFilter = "Identity"
if stmf, ok := ed.Get("StmF").(*PdfObjectName); ok {
if _, exists := crypt.CryptFilters[string(*stmf)]; !exists {
return fmt.Errorf("Crypt filter for StmF not specified in CF dictionary (%s)", *stmf)
}
crypt.StreamFilter = string(*stmf)
}
return nil
}
// PdfCryptMakeNew makes the document crypt handler based on the encryption dictionary
// and trailer dictionary. Returns an error on failure to process.
func PdfCryptMakeNew(parser *PdfParser, ed, trailer *PdfObjectDictionary) (PdfCrypt, error) {
crypter := PdfCrypt{}
crypter.DecryptedObjects = map[PdfObject]bool{}
crypter.EncryptedObjects = map[PdfObject]bool{}
crypter.Authenticated = false
crypter.parser = parser
filter, ok := ed.Get("Filter").(*PdfObjectName)
if !ok {
common.Log.Debug("ERROR Crypt dictionary missing required Filter field!")
return crypter, errors.New("Required crypt field Filter missing")
}
if *filter != "Standard" {
common.Log.Debug("ERROR Unsupported filter (%s)", *filter)
return crypter, errors.New("Unsupported Filter")
}
crypter.Filter = string(*filter)
subfilter, ok := ed.Get("SubFilter").(*PdfObjectString)
if ok {
crypter.Subfilter = string(*subfilter)
common.Log.Debug("Using subfilter %s", subfilter)
}
if L, ok := ed.Get("Length").(*PdfObjectInteger); ok {
if (*L % 8) != 0 {
common.Log.Debug("ERROR Invalid encryption length")
return crypter, errors.New("Invalid encryption length")
}
crypter.Length = int(*L)
} else {
crypter.Length = 40
}
V, ok := ed.Get("V").(*PdfObjectInteger)
if ok {
if *V >= 1 && *V <= 2 {
crypter.V = int(*V)
// Default algorithm is V2.
crypter.CryptFilters = CryptFilters{}
crypter.CryptFilters["Default"] = CryptFilter{Cfm: "V2", Length: crypter.Length}
} else if *V == 4 {
crypter.V = int(*V)
if err := crypter.LoadCryptFilters(ed); err != nil {
return crypter, err
}
} else {
common.Log.Debug("ERROR Unsupported encryption algo V = %d", *V)
return crypter, errors.New("Unsupported algorithm")
}
} else {
crypter.V = 0
}
R, ok := ed.Get("R").(*PdfObjectInteger)
if !ok {
return crypter, errors.New("Encrypt dictionary missing R")
}
if *R < 2 || *R > 4 {
return crypter, errors.New("Invalid R")
}
crypter.R = int(*R)
O, ok := ed.Get("O").(*PdfObjectString)
if !ok {
return crypter, errors.New("Encrypt dictionary missing O")
}
if len(*O) != 32 {
return crypter, fmt.Errorf("Length(O) != 32 (%d)", len(*O))
}
crypter.O = []byte(*O)
U, ok := ed.Get("U").(*PdfObjectString)
if !ok {
return crypter, errors.New("Encrypt dictionary missing U")
}
if len(*U) != 32 {
// Strictly this does not cause an error.
// If O is OK and others then can still read the file.
common.Log.Debug("Warning: Length(U) != 32 (%d)", len(*U))
//return crypter, errors.New("Length(U) != 32")
}
crypter.U = []byte(*U)
P, ok := ed.Get("P").(*PdfObjectInteger)
if !ok {
return crypter, errors.New("Encrypt dictionary missing permissions attr")
}
crypter.P = int(*P)
em, ok := ed.Get("EncryptMetadata").(*PdfObjectBool)
if ok {
crypter.EncryptMetadata = bool(*em)
} else {
crypter.EncryptMetadata = true // True by default.
}
// Default: empty ID.
// Strictly, if file is encrypted, the ID should always be specified
// but clearly not everyone is following the specification.
id0 := PdfObjectString("")
if idArray, ok := trailer.Get("ID").(*PdfObjectArray); ok && len(*idArray) >= 1 {
id0obj, ok := (*idArray)[0].(*PdfObjectString)
if !ok {
return crypter, errors.New("Invalid trailer ID")
}
id0 = *id0obj
} else {
common.Log.Debug("Trailer ID array missing or invalid!")
}
crypter.Id0 = string(id0)
return crypter, nil
}
// GetAccessPermissions returns the PDF access permissions as an AccessPermissions object.
func (crypt *PdfCrypt) GetAccessPermissions() AccessPermissions {
perms := AccessPermissions{}
P := crypt.P
if P&(1<<2) > 0 {
perms.Printing = true
}
if P&(1<<3) > 0 {
perms.Modify = true
}
if P&(1<<4) > 0 {
perms.ExtractGraphics = true
}
if P&(1<<5) > 0 {
perms.Annotate = true
}
if P&(1<<8) > 0 {
perms.FillForms = true
}
if P&(1<<9) > 0 {
perms.DisabilityExtract = true
}
if P&(1<<10) > 0 {
perms.RotateInsert = true
}
if P&(1<<11) > 0 {
perms.FullPrintQuality = true
}
return perms
}
// GetP returns the P entry to be used in Encrypt dictionary based on AccessPermissions settings.
func (perms AccessPermissions) GetP() int32 {
var P int32 = 0
if perms.Printing { // bit 3
P |= (1 << 2)
}
if perms.Modify { // bit 4
P |= (1 << 3)
}
if perms.ExtractGraphics { // bit 5
P |= (1 << 4)
}
if perms.Annotate { // bit 6
P |= (1 << 5)
}
if perms.FillForms {
P |= (1 << 8) // bit 9
}
if perms.DisabilityExtract {
P |= (1 << 9) // bit 10
}
if perms.RotateInsert {
P |= (1 << 10) // bit 11
}
if perms.FullPrintQuality {
P |= (1 << 11) // bit 12
}
return P
}
// Check whether the specified password can be used to decrypt the document.
func (crypt *PdfCrypt) authenticate(password []byte) (bool, error) {
// Also build the encryption/decryption key.
crypt.Authenticated = false
// Try user password.
common.Log.Trace("Debugging authentication - user pass")
authenticated, err := crypt.Alg6(password)
if err != nil {
return false, err
}
if authenticated {
common.Log.Trace("this.Authenticated = True")
crypt.Authenticated = true
return true, nil
}
// Try owner password also.
// May not be necessary if only want to get all contents.
// (user pass needs to be known or empty).
common.Log.Trace("Debugging authentication - owner pass")
authenticated, err = crypt.Alg7(password)
if err != nil {
return false, err
}
if authenticated {
common.Log.Trace("this.Authenticated = True")
crypt.Authenticated = true
return true, nil
}
return false, nil
}
// Check access rights and permissions for a specified password. If either user/owner password is specified,
// full rights are granted, otherwise the access rights are specified by the Permissions flag.
//
// The bool flag indicates that the user can access and can view the file.
// The AccessPermissions shows what access the user has for editing etc.
// An error is returned if there was a problem performing the authentication.
func (crypt *PdfCrypt) checkAccessRights(password []byte) (bool, AccessPermissions, error) {
perms := AccessPermissions{}
// Try owner password -> full rights.
isOwner, err := crypt.Alg7(password)
if err != nil {
return false, perms, err
}
if isOwner {
// owner -> full rights.
perms.Annotate = true
perms.DisabilityExtract = true
perms.ExtractGraphics = true
perms.FillForms = true
perms.FullPrintQuality = true
perms.Modify = true
perms.Printing = true
perms.RotateInsert = true
return true, perms, nil
}
// Try user password.
isUser, err := crypt.Alg6(password)
if err != nil {
return false, perms, err
}
if isUser {
// User password specified correctly -> access granted with specified permissions.
return true, crypt.GetAccessPermissions(), nil
}
// Cannot even view the file.
return false, perms, nil
}
func (crypt *PdfCrypt) paddedPass(pass []byte) []byte {
key := make([]byte, 32)
if len(pass) >= 32 {
for i := 0; i < 32; i++ {
key[i] = pass[i]
}
} else {
for i := 0; i < len(pass); i++ {
key[i] = pass[i]
}
for i := len(pass); i < 32; i++ {
key[i] = padding[i-len(pass)]
}
}
return key
}
// Generates a key for encrypting a specific object based on the
// object and generation number, as well as the document encryption key.
func (crypt *PdfCrypt) makeKey(filter string, objNum, genNum uint32, ekey []byte) ([]byte, error) {
cf, ok := crypt.CryptFilters[filter]
if !ok {
common.Log.Debug("ERROR Unsupported crypt filter (%s)", filter)
return nil, fmt.Errorf("Unsupported crypt filter (%s)", filter)
}
isAES := false
if cf.Cfm == "AESV2" {
isAES = true
}
key := make([]byte, len(ekey)+5)
for i := 0; i < len(ekey); i++ {
key[i] = ekey[i]
}
for i := 0; i < 3; i++ {
b := byte((objNum >> uint32(8*i)) & 0xff)
key[i+len(ekey)] = b
}
for i := 0; i < 2; i++ {
b := byte((genNum >> uint32(8*i)) & 0xff)
key[i+len(ekey)+3] = b
}
if isAES {
// If using the AES algorithm, extend the encryption key an
// additional 4 bytes by adding the value “sAlT”, which
// corresponds to the hexadecimal values 0x73, 0x41, 0x6C, 0x54.
key = append(key, 0x73)
key = append(key, 0x41)
key = append(key, 0x6C)
key = append(key, 0x54)
}
// Take the MD5.
h := md5.New()
h.Write(key)
hashb := h.Sum(nil)
if len(ekey)+5 < 16 {
return hashb[0 : len(ekey)+5], nil
}
return hashb, nil
}
// Check if object has already been processed.
func (crypt *PdfCrypt) isDecrypted(obj PdfObject) bool {
_, ok := crypt.DecryptedObjects[obj]
if ok {
common.Log.Trace("Already decrypted")
return true
}
common.Log.Trace("Not decrypted yet")
return false
}
// Decrypt a buffer with a selected crypt filter.
func (crypt *PdfCrypt) decryptBytes(buf []byte, filter string, okey []byte) ([]byte, error) {
common.Log.Trace("Decrypt bytes")
cf, ok := crypt.CryptFilters[filter]
if !ok {
common.Log.Debug("ERROR Unsupported crypt filter (%s)", filter)
return nil, fmt.Errorf("Unsupported crypt filter (%s)", filter)
}
cfMethod := cf.Cfm
if cfMethod == "V2" {
// Standard RC4 algorithm.
ciph, err := rc4.NewCipher(okey)
if err != nil {
return nil, err
}
common.Log.Trace("RC4 Decrypt: % x", buf)
ciph.XORKeyStream(buf, buf)
common.Log.Trace("to: % x", buf)
return buf, nil
} else if cfMethod == "AESV2" {
// Strings and streams encrypted with AES shall use a padding
// scheme that is described in Internet RFC 2898, PKCS #5:
// Password-Based Cryptography Specification Version 2.0; see
// the Bibliography. For an original message length of M,
// the pad shall consist of 16 - (M mod 16) bytes whose value
// shall also be 16 - (M mod 16).
//
// A 9-byte message has a pad of 7 bytes, each with the value
// 0x07. The pad can be unambiguously removed to determine the
// original message length when decrypting. Note that the pad is
// present when M is evenly divisible by 16; it contains 16 bytes
// of 0x10.
ciph, err := aes.NewCipher(okey)
if err != nil {
return nil, err
}
// If using the AES algorithm, the Cipher Block Chaining (CBC)
// mode, which requires an initialization vector, is used. The
// block size parameter is set to 16 bytes, and the initialization
// vector is a 16-byte random number that is stored as the first
// 16 bytes of the encrypted stream or string.
if len(buf) < 16 {
common.Log.Debug("ERROR AES invalid buf %s", buf)
return buf, fmt.Errorf("AES: Buf len < 16 (%d)", len(buf))
}
iv := buf[:16]
buf = buf[16:]
if len(buf)%16 != 0 {
common.Log.Debug(" iv (%d): % x", len(iv), iv)
common.Log.Debug("buf (%d): % x", len(buf), buf)
return buf, fmt.Errorf("AES buf length not multiple of 16 (%d)", len(buf))
}
mode := cipher.NewCBCDecrypter(ciph, iv)
common.Log.Trace("AES Decrypt (%d): % x", len(buf), buf)
common.Log.Trace("chop AES Decrypt (%d): % x", len(buf), buf)
mode.CryptBlocks(buf, buf)
common.Log.Trace("to (%d): % x", len(buf), buf)
if len(buf) == 0 {
common.Log.Trace("Empty buf, returning empty string")
return buf, nil
}
// The padded length is indicated by the last values. Remove those.
padLen := int(buf[len(buf)-1])
if padLen >= len(buf) {
common.Log.Debug("Illegal pad length")
return buf, fmt.Errorf("Invalid pad length")
}
buf = buf[:len(buf)-padLen]
return buf, nil
}
return nil, fmt.Errorf("Unsupported crypt filter method (%s)", cfMethod)
}
// Decrypt an object with specified key. For numbered objects,
// the key argument is not used and a new one is generated based
// on the object and generation number.
// Traverses through all the subobjects (recursive).
//
// Does not look up references.. That should be done prior to calling.
func (crypt *PdfCrypt) Decrypt(obj PdfObject, parentObjNum, parentGenNum int64) error {
if crypt.isDecrypted(obj) {
return nil
}
if io, isIndirect := obj.(*PdfIndirectObject); isIndirect {
crypt.DecryptedObjects[io] = true
common.Log.Trace("Decrypting indirect %d %d obj!", io.ObjectNumber, io.GenerationNumber)
objNum := (*io).ObjectNumber
genNum := (*io).GenerationNumber
err := crypt.Decrypt(io.PdfObject, objNum, genNum)
if err != nil {
return err
}
return nil
}
if so, isStream := obj.(*PdfObjectStream); isStream {
// Mark as decrypted first to avoid recursive issues.
crypt.DecryptedObjects[so] = true
objNum := (*so).ObjectNumber
genNum := (*so).GenerationNumber
common.Log.Trace("Decrypting stream %d %d !", objNum, genNum)
// TODO: Check for crypt filter (V4).
// The Crypt filter shall be the first filter in the Filter array entry.
dict := so.PdfObjectDictionary
streamFilter := "Default" // Default RC4.
if crypt.V >= 4 {
streamFilter = crypt.StreamFilter
common.Log.Trace("this.StreamFilter = %s", crypt.StreamFilter)
if filters, ok := dict.Get("Filter").(*PdfObjectArray); ok {
// Crypt filter can only be the first entry.
if firstFilter, ok := (*filters)[0].(*PdfObjectName); ok {
if *firstFilter == "Crypt" {
// Crypt filter overriding the default.
// Default option is Identity.
streamFilter = "Identity"
// Check if valid crypt filter specified in the decode params.
if decodeParams, ok := dict.Get("DecodeParms").(*PdfObjectDictionary); ok {
if filterName, ok := decodeParams.Get("Name").(*PdfObjectName); ok {
if _, ok := crypt.CryptFilters[string(*filterName)]; ok {
common.Log.Trace("Using stream filter %s", *filterName)
streamFilter = string(*filterName)
}
}
}
}
}
}
common.Log.Trace("with %s filter", streamFilter)
if streamFilter == "Identity" {
// Identity: pass unchanged.
return nil
}
}
err := crypt.Decrypt(so.PdfObjectDictionary, objNum, genNum)
if err != nil {
return err
}
okey, err := crypt.makeKey(streamFilter, uint32(objNum), uint32(genNum), crypt.EncryptionKey)
if err != nil {
return err
}
so.Stream, err = crypt.decryptBytes(so.Stream, streamFilter, okey)
if err != nil {
return err
}
// Update the length based on the decrypted stream.
dict.Set("Length", MakeInteger(int64(len(so.Stream))))
return nil
}
if s, isString := obj.(*PdfObjectString); isString {
common.Log.Trace("Decrypting string!")
stringFilter := "Default"
if crypt.V >= 4 {
// Currently only support Identity / RC4.
common.Log.Trace("with %s filter", crypt.StringFilter)
if crypt.StringFilter == "Identity" {
// Identity: pass unchanged: No action.
return nil
} else {
stringFilter = crypt.StringFilter
}
}
key, err := crypt.makeKey(stringFilter, uint32(parentObjNum), uint32(parentGenNum), crypt.EncryptionKey)
if err != nil {
return err
}
// Overwrite the encrypted with decrypted string.
decrypted := make([]byte, len(*s))
for i := 0; i < len(*s); i++ {
decrypted[i] = (*s)[i]
}
common.Log.Trace("Decrypt string: %s : % x", decrypted, decrypted)
decrypted, err = crypt.decryptBytes(decrypted, stringFilter, key)
if err != nil {
return err
}
*s = PdfObjectString(decrypted)
return nil
}
if a, isArray := obj.(*PdfObjectArray); isArray {
for _, o := range *a {
err := crypt.Decrypt(o, parentObjNum, parentGenNum)
if err != nil {
return err
}
}
return nil
}
if d, isDict := obj.(*PdfObjectDictionary); isDict {
isSig := false
if t := d.Get("Type"); t != nil {
typeStr, ok := t.(*PdfObjectName)
if ok && *typeStr == "Sig" {
isSig = true
}
}
for _, keyidx := range d.Keys() {
o := d.Get(keyidx)
// How can we avoid this check, i.e. implement a more smart
// traversal system?
if isSig && string(keyidx) == "Contents" {
// Leave the Contents of a Signature dictionary.
continue
}
if string(keyidx) != "Parent" && string(keyidx) != "Prev" && string(keyidx) != "Last" { // Check not needed?
err := crypt.Decrypt(o, parentObjNum, parentGenNum)
if err != nil {
return err
}
}
}
return nil
}
return nil
}
// Check if object has already been processed.
func (crypt *PdfCrypt) isEncrypted(obj PdfObject) bool {
_, ok := crypt.EncryptedObjects[obj]
if ok {
common.Log.Trace("Already encrypted")
return true
}
common.Log.Trace("Not encrypted yet")
return false
}
// Encrypt a buffer with the specified crypt filter and key.
func (crypt *PdfCrypt) encryptBytes(buf []byte, filter string, okey []byte) ([]byte, error) {
common.Log.Trace("Encrypt bytes")
cf, ok := crypt.CryptFilters[filter]
if !ok {
common.Log.Debug("ERROR Unsupported crypt filter (%s)", filter)
return nil, fmt.Errorf("Unsupported crypt filter (%s)", filter)
}
cfMethod := cf.Cfm
if cfMethod == "V2" {
// Standard RC4 algorithm.
ciph, err := rc4.NewCipher(okey)
if err != nil {
return nil, err
}
common.Log.Trace("RC4 Encrypt: % x", buf)
ciph.XORKeyStream(buf, buf)
common.Log.Trace("to: % x", buf)
return buf, nil
} else if cfMethod == "AESV2" {
// Strings and streams encrypted with AES shall use a padding
// scheme that is described in Internet RFC 2898, PKCS #5:
// Password-Based Cryptography Specification Version 2.0; see
// the Bibliography. For an original message length of M,
// the pad shall consist of 16 - (M mod 16) bytes whose value
// shall also be 16 - (M mod 16).
//
// A 9-byte message has a pad of 7 bytes, each with the value
// 0x07. The pad can be unambiguously removed to determine the
// original message length when decrypting. Note that the pad is
// present when M is evenly divisible by 16; it contains 16 bytes
// of 0x10.
ciph, err := aes.NewCipher(okey)
if err != nil {
return nil, err
}
common.Log.Trace("AES Encrypt (%d): % x", len(buf), buf)
// If using the AES algorithm, the Cipher Block Chaining (CBC)
// mode, which requires an initialization vector, is used. The
// block size parameter is set to 16 bytes, and the initialization
// vector is a 16-byte random number that is stored as the first
// 16 bytes of the encrypted stream or string.
pad := 16 - len(buf)%16
for i := 0; i < pad; i++ {
buf = append(buf, byte(pad))
}
common.Log.Trace("Padded to %d bytes", len(buf))
// Generate random 16 bytes, place in beginning of buffer.
ciphertext := make([]byte, 16+len(buf))
iv := ciphertext[:16]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(ciph, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], buf)
buf = ciphertext
common.Log.Trace("to (%d): % x", len(buf), buf)
return buf, nil
}
return nil, fmt.Errorf("Unsupported crypt filter method (%s)", cfMethod)
}
// Encrypt an object with specified key. For numbered objects,
// the key argument is not used and a new one is generated based
// on the object and generation number.
// Traverses through all the subobjects (recursive).
//
// Does not look up references.. That should be done prior to calling.
func (crypt *PdfCrypt) Encrypt(obj PdfObject, parentObjNum, parentGenNum int64) error {
if crypt.isEncrypted(obj) {
return nil
}
if io, isIndirect := obj.(*PdfIndirectObject); isIndirect {
crypt.EncryptedObjects[io] = true
common.Log.Trace("Encrypting indirect %d %d obj!", io.ObjectNumber, io.GenerationNumber)
objNum := (*io).ObjectNumber
genNum := (*io).GenerationNumber
err := crypt.Encrypt(io.PdfObject, objNum, genNum)
if err != nil {
return err
}
return nil
}
if so, isStream := obj.(*PdfObjectStream); isStream {
crypt.EncryptedObjects[so] = true
objNum := (*so).ObjectNumber
genNum := (*so).GenerationNumber
common.Log.Trace("Encrypting stream %d %d !", objNum, genNum)
// TODO: Check for crypt filter (V4).
// The Crypt filter shall be the first filter in the Filter array entry.
dict := so.PdfObjectDictionary
streamFilter := "Default" // Default RC4.
if crypt.V >= 4 {
// For now. Need to change when we add support for more than
// Identity / RC4.
streamFilter = crypt.StreamFilter
common.Log.Trace("this.StreamFilter = %s", crypt.StreamFilter)
if filters, ok := dict.Get("Filter").(*PdfObjectArray); ok {
// Crypt filter can only be the first entry.
if firstFilter, ok := (*filters)[0].(*PdfObjectName); ok {
if *firstFilter == "Crypt" {
// Crypt filter overriding the default.
// Default option is Identity.
streamFilter = "Identity"
// Check if valid crypt filter specified in the decode params.
if decodeParams, ok := dict.Get("DecodeParms").(*PdfObjectDictionary); ok {
if filterName, ok := decodeParams.Get("Name").(*PdfObjectName); ok {
if _, ok := crypt.CryptFilters[string(*filterName)]; ok {
common.Log.Trace("Using stream filter %s", *filterName)
streamFilter = string(*filterName)
}
}
}
}
}
}
common.Log.Trace("with %s filter", streamFilter)
if streamFilter == "Identity" {
// Identity: pass unchanged.
return nil
}
}
err := crypt.Encrypt(so.PdfObjectDictionary, objNum, genNum)
if err != nil {
return err
}
okey, err := crypt.makeKey(streamFilter, uint32(objNum), uint32(genNum), crypt.EncryptionKey)
if err != nil {
return err
}
so.Stream, err = crypt.encryptBytes(so.Stream, streamFilter, okey)
if err != nil {
return err
}
// Update the length based on the encrypted stream.
dict.Set("Length", MakeInteger(int64(len(so.Stream))))
return nil
}
if s, isString := obj.(*PdfObjectString); isString {
common.Log.Trace("Encrypting string!")
stringFilter := "Default"
if crypt.V >= 4 {
common.Log.Trace("with %s filter", crypt.StringFilter)
if crypt.StringFilter == "Identity" {
// Identity: pass unchanged: No action.
return nil
} else {
stringFilter = crypt.StringFilter
}
}
key, err := crypt.makeKey(stringFilter, uint32(parentObjNum), uint32(parentGenNum), crypt.EncryptionKey)
if err != nil {
return err
}
encrypted := make([]byte, len(*s))
for i := 0; i < len(*s); i++ {
encrypted[i] = (*s)[i]
}
common.Log.Trace("Encrypt string: %s : % x", encrypted, encrypted)
encrypted, err = crypt.encryptBytes(encrypted, stringFilter, key)
if err != nil {
return err
}
*s = PdfObjectString(encrypted)
return nil
}
if a, isArray := obj.(*PdfObjectArray); isArray {
for _, o := range *a {
err := crypt.Encrypt(o, parentObjNum, parentGenNum)
if err != nil {
return err
}
}
return nil
}
if d, isDict := obj.(*PdfObjectDictionary); isDict {
isSig := false
if t := d.Get("Type"); t != nil {
typeStr, ok := t.(*PdfObjectName)
if ok && *typeStr == "Sig" {
isSig = true