-
Notifications
You must be signed in to change notification settings - Fork 243
/
PDFCore.py
8123 lines (7539 loc) · 334 KB
/
PDFCore.py
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
#
# peepdf is a tool to analyse and modify PDF files
# http://peepdf.eternal-todo.com
# By Jose Miguel Esparza <jesparza AT eternal-todo.com>
#
# Copyright (C) 2011-2017 Jose Miguel Esparza
#
# This file is part of peepdf.
#
# peepdf is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# peepdf is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with peepdf. If not, see <http://www.gnu.org/licenses/>.
#
'''
This module contains classes and methods to analyse and modify PDF files
'''
import sys,os,re,hashlib,struct,aes as AES
from PDFUtils import *
from PDFCrypto import *
from JSAnalysis import *
from PDFFilters import decodeStream,encodeStream
MAL_ALL = 1
MAL_HEAD = 2
MAL_EOBJ = 3
MAL_ESTREAM = 4
MAL_XREF = 5
MAL_BAD_HEAD = 6
pdfFile = None
newLine = os.linesep
isForceMode = False
isManualAnalysis = False
spacesChars = ['\x00','\x09','\x0a','\x0c','\x0d','\x20']
delimiterChars = ['<<','(','<','[','{','/','%']
monitorizedEvents = ['/OpenAction ','/AA ','/Names ','/AcroForm ', '/XFA ']
monitorizedActions = ['/JS ','/JavaScript','/Launch','/SubmitForm','/ImportData']
monitorizedElements = ['/EmbeddedFiles ',
'/EmbeddedFile',
'/JBIG2Decode',
'getPageNthWord',
'arguments.callee',
'/U3D',
'/PRC',
'/RichMedia',
'/Flash',
'.rawValue',
'keep.previous']
jsVulns = ['mailto',
'Collab.collectEmailInfo',
'util.printf',
'getAnnots',
'getIcon',
'spell.customDictionaryOpen',
'media.newPlayer',
'doc.printSeps',
'app.removeToolButton']
singUniqueName = 'CoolType.SING.uniqueName'
bmpVuln = 'BMP/RLE heap corruption'
vulnsDict = {'mailto':('mailto',['CVE-2007-5020']),
'Collab.collectEmailInfo':('Collab.collectEmailInfo',['CVE-2007-5659']),
'util.printf':('util.printf',['CVE-2008-2992']),
'/JBIG2Decode':('Adobe JBIG2Decode Heap Corruption',['CVE-2009-0658']),
'getIcon':('getIcon',['CVE-2009-0927']),
'getAnnots':('getAnnots',['CVE-2009-1492']),
'spell.customDictionaryOpen':('spell.customDictionaryOpen',['CVE-2009-1493']),
'media.newPlayer':('media.newPlayer',['CVE-2009-4324']),
'.rawValue':('Adobe Acrobat Bundled LibTIFF Integer Overflow',['CVE-2010-0188']),
singUniqueName:(singUniqueName,['CVE-2010-2883']),
'doc.printSeps':('doc.printSeps',['CVE-2010-4091']),
'/U3D':('/U3D',['CVE-2009-3953','CVE-2009-3959','CVE-2011-2462']),
'/PRC':('/PRC',['CVE-2011-4369']),
'keep.previous':('Adobe Reader XFA oneOfChild Un-initialized memory vulnerability',['CVE-2013-0640']), # https://labs.portcullis.co.uk/blog/cve-2013-0640-adobe-reader-xfa-oneofchild-un-initialized-memory-vulnerability-part-1/
bmpVuln:(bmpVuln,['CVE-2013-2729']),
'app.removeToolButton':('app.removeToolButton',['CVE-2013-3346'])}
jsContexts = {'global':None}
class PDFObject :
'''
Base class for all the PDF objects
'''
def __init__(self, raw = None):
'''
Constructor of a PDFObject
@param raw: The raw value of the PDF object
'''
self.references = []
self.type = ''
self.value = ''
self.rawValue = raw
self.JSCode = []
self.uriList = []
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.encryptedValue = raw
self.encryptionKey = ''
self.encrypted = False
self.errors = []
self.referencesInElements = {}
self.compressedIn = None
def addError(self, errorMessage):
'''
Add an error to the object
@param errorMessage: The error message to be added (string)
'''
if errorMessage not in self.errors:
self.errors.append(errorMessage)
def contains(self, string):
'''
Look for the string inside the object content
@param string: A string
@return: A boolean to specify if the string has been found or not
'''
value = str(self.value)
rawValue = str(self.rawValue)
encValue = str(self.encryptedValue)
if re.findall(string,value,re.IGNORECASE) != [] or re.findall(string,rawValue,re.IGNORECASE) != [] or re.findall(string,encValue,re.IGNORECASE) != []:
return True
if self.containsJS():
for js in self.JSCode:
if re.findall(string,js,re.IGNORECASE) != []:
return True
return False
def containsJS(self):
'''
Method to check if there are Javascript code inside the object
@return: A boolean
'''
return self.containsJScode
def containsURIs(self):
'''
Method to check if there are URIs inside the object
@return: A boolean
'''
if self.uriList:
return True
else:
return False
def encodeChars(self):
'''
Encode the content of the object if possible (only for PDFName, PDFString, PDFArray and PDFStreams)
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
return (0,'')
def encrypt(self, password):
'''
Encrypt the content of the object if possible
@param password: The password used to encrypt the object. It's dependent on the object.
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
return (0,'')
def getCompressedIn(self):
'''
Gets the id of the object (object stream) where the actual object is compressed
@return: The id (int) of the object stream or None if it's not compressed
'''
return self.compressedIn
def getEncryptedValue(self):
'''
Gets the encrypted value of the object
@return: The encrypted value or the raw value if the object is not encrypted
'''
return self.encryptedValue
def getEncryptionKey(self):
'''
Gets the encryption key (password) used to encrypt the object
@return: The password (string) or an empty string if it's not encrypted
'''
return self.encryptionKey
def getErrors(self):
'''
Gets the error messages found while parsing and processing the object
@return: The array of errors of the object
'''
return self.errors
def getRawValue(self):
'''
Gets the raw value of the object
@return: The raw value of the object, this means without applying filters or decoding characters
'''
return self.rawValue
def getReferences(self):
'''
Gets the referenced objects in the actual object
@return: An array of references in the object (Ex. ['1 0 R','12 0 R'])
'''
return self.references
def getReferencesInElements(self):
'''
Gets the dependencies between elements in the object and objects in the rest of the document.
@return: A dictionary of dependencies of the object (Ex. {'/Length':[5,'']} or {'/Length':[5,'354']})
'''
return self.referencesInElements
def getStats(self):
'''
Gets the statistics of the object
@return: An array of different statistics of the object (object type, compression, references, etc)
'''
stats = {}
stats['Object'] = self.type
stats['MD5'] = hashlib.md5(self.value).hexdigest()
stats['SHA1'] = hashlib.sha1(self.value).hexdigest()
if self.isCompressed():
stats['Compressed in'] = str(self.compressedIn)
else:
stats['Compressed in'] = None
stats['References'] = str(self.references)
if self.containsJScode:
stats['JSCode'] = True
if len(self.unescapedBytes) > 0:
stats['Escaped Bytes'] = True
else:
stats['Escaped Bytes'] = False
if len(self.urlsFound) > 0:
stats['URLs'] = True
else:
stats['URLs'] = False
else:
stats['JSCode'] = False
if self.isFaulty():
stats['Errors'] = str(len(self.errors))
else:
stats['Errors'] = None
return stats
def getType(self):
'''
Gets the type of the object
@return: The object type (bool, null, real, integer, name, string, hexstring, reference, array, dictionary, stream)
'''
return self.type
def getValue(self):
'''
Gets the value of the object
@return: The value of the object, this means after applying filters and/or decoding characters and strings
'''
return self.value
def isCompressed(self):
'''
Specifies if the object is compressed or not
@return: A boolean
'''
if self.compressedIn != None:
return True
else:
return False
def isEncrypted(self):
'''
Specifies if the object is encrypted or not
@return: A boolean
'''
return self.encrypted
def isFaulty(self):
'''
Specifies if the object has errors or not
@return: A boolean
'''
if self.errors == []:
return False
else:
return True
def replace(self, string1, string2):
'''
Searches the object for the 'string1' and if it's found it's replaced by 'string2'
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
if self.value.find(string1) == -1 and self.rawValue.find(string1) == -1:
return (-1,'String not found')
self.value = self.value.replace(string1, string2)
self.rawValue = self.rawValue.replace(string1, string2)
ret = self.update()
return ret
def resolveReferences(self):
'''
Replaces the reference to an object by its value if there are references not resolved. Ex. /Length 3 0 R
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
pass
def setReferencedJSObject(self, value):
'''
Modifies the referencedJSObject element
@param value: The new value (bool)
'''
self.referencedJSObject = value
ret = self.update()
return ret
def setCompressedIn(self, id):
'''
Sets the object id of the object stream containing the actual object
@param id: The object id (int)
'''
self.compressedIn = id
def setEncryptedValue(self, value):
'''
Sets the encrypted value of the object
@param value: The encrypted value (string)
'''
self.encryptedValue = value
def setEncryptionKey(self, password):
'''
Sets the password to encrypt/decrypt the object
@param password: The encryption key (string)
'''
self.encryptionKey = password
def setRawValue(self, newRawValue):
'''
Sets the raw value of the object and updates the object if some modification is needed
@param newRawValue: The new raw value (string)
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
self.rawValue = newRawValue
ret = self.update()
return ret
def setReferencesInElements(self, resolvedReferencesDict):
'''
Sets the resolved references array
@param resolvedReferencesDict: A dictionary with the resolved references
'''
self.referencesInElements = resolvedReferencesDict
def setValue(self, newValue):
'''
Sets the value of the object
@param newValue: The new value of the object (string)
'''
self.value = newValue
def update(self):
'''
Updates the object after some modification has occurred
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
self.encryptedValue = self.rawValue
return (0,'')
def toFile(self):
'''
Gets the raw or encrypted value of the object to write it to an output file
@return: The raw/encrypted value of the object (string)
'''
if self.encrypted:
return self.getEncryptedValue()
else:
return self.getRawValue()
class PDFBool (PDFObject) :
'''
Boolean object of a PDF document
'''
def __init__(self, value) :
self.type = 'bool'
self.errors = []
self.references = []
self.JSCode = []
self.uriList = []
self.encrypted = False
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.referencesInElements = {}
self.value = self.rawValue = self.encryptedValue = value
self.compressedIn = None
class PDFNull (PDFObject) :
'''
Null object of a PDF document
'''
def __init__(self, content) :
self.type = 'null'
self.errors = []
self.JSCode = []
self.uriList = []
self.compressedIn = None
self.encrypted = False
self.value = self.rawValue = self.encryptedValue = content
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.referencesInElements = {}
self.references = []
class PDFNum (PDFObject) :
'''
Number object of a PDF document: can be an integer or a real number.
'''
def __init__(self, num) :
self.errors = []
self.JSCode = []
self.uriList = []
self.compressedIn = None
self.encrypted = False
self.value = num
self.compressedIn = None
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.referencesInElements = {}
self.references = []
ret = self.update()
if ret[0] == -1:
if isForceMode:
self.addError(ret[1])
else:
raise Exception(ret[1])
def replace(self, string1, string2):
if self.value.find(string1) == -1:
return (-1,'String not found')
self.value = self.value.replace(string1, string2)
ret = self.update()
return ret
def update(self):
self.errors = []
try:
if self.value.find('.') != -1:
self.type = 'real'
self.rawValue = float(self.value)
else:
self.type = 'integer'
self.rawValue = int(self.value)
except:
errorMessage = 'Numeric conversion error'
self.addError(errorMessage)
return (-1,errorMessage)
self.encryptedValue = str(self.rawValue)
return (0,'')
def setRawValue(self, rawValue):
self.rawValue = rawValue
def setValue(self, value):
self.value = value
ret = self.update()
return ret
def toFile(self):
return str(self.rawValue)
class PDFName (PDFObject) :
'''
Name object of a PDF document
'''
def __init__(self, name) :
self.type = 'name'
self.errors = []
self.JSCode = []
self.uriList = []
self.references = []
self.compressedIn = None
if name[0] == '/':
self.rawValue = self.value = self.encryptedValue = name
else:
self.rawValue = self.value = self.encryptedValue = '/' + name
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.encryptedValue = ''
self.encrypted = False
self.referencesInElements = {}
ret = self.update()
if ret[0] == -1:
if isForceMode:
self.addError(ret[1])
else:
raise Exception(ret[1])
def update(self):
self.errors = []
errorMessage = ''
self.value = self.rawValue
self.encryptedValue = self.rawValue
hexNumbers = re.findall('#([0-9a-f]{2})', self.value, re.DOTALL | re.IGNORECASE)
try:
for hexNumber in hexNumbers:
self.value = self.value.replace('#' + hexNumber, chr(int(hexNumber,16)))
except:
errorMessage = 'Error in hexadecimal conversion'
self.addError(errorMessage)
return (-1,errorMessage)
return (0,'')
def encodeChars(self):
ret = encodeName(self.value)
if ret[0] == -1:
self.addError(ret[1])
return ret
else:
self.rawValue = ret[1]
return (0,'')
class PDFString (PDFObject) :
'''
String object of a PDF document
'''
def __init__(self, string) :
self.type = 'string'
self.errors = []
self.compressedIn = None
self.encrypted = False
self.value = self.rawValue = self.encryptedValue = string
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.JSCode = []
self.uriList = []
self.unescapedBytes = []
self.urlsFound = []
self.references = []
self.referencesInElements = {}
ret = self.update()
if ret[0] == -1:
if isForceMode:
self.addError(ret[1])
else:
raise Exception(ret[1])
def update(self, decrypt = False):
'''
Updates the object after some modification has occurred
@param decrypt: A boolean indicating if a decryption has been performed. By default: False.
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
self.errors = []
self.containsJScode = False
self.JSCode = []
self.unescapedBytes = []
self.urlsFound = []
self.rawValue = unescapeString(self.rawValue)
self.value = self.rawValue
'''
self.value = self.value.replace('\)',')')
self.value = self.value.replace('\\\\','\\')
self.value = self.value.replace('\\\r\\\n','')
self.value = self.value.replace('\\\r','')
self.value = self.value.replace('\\\n','')
'''
octalNumbers = re.findall('\\\\([0-7]{1,3})', self.value, re.DOTALL)
try:
for octal in octalNumbers:
#TODO: check!! \\\\?
self.value = self.value.replace('\\' + octal, chr(int(octal,8)))
except:
errorMessage = 'Error in octal conversion'
self.addError(errorMessage)
return (-1,errorMessage)
if isJavascript(self.value) or self.referencedJSObject:
self.containsJScode = True
self.JSCode, self.unescapedBytes, self.urlsFound, jsErrors, jsContexts['global'] = analyseJS(self.value, jsContexts['global'], isManualAnalysis)
if jsErrors != []:
for jsError in jsErrors:
errorMessage = 'Error analysing Javascript: '+jsError
if isForceMode:
self.addError(errorMessage)
else:
return (-1,errorMessage)
if self.encrypted and not decrypt:
ret = self.encrypt()
if ret[0] == -1:
return ret
return (0,'')
def encodeChars(self):
ret = encodeString(self.value)
if ret[0] == -1:
self.addError(ret[1])
return ret
else:
self.rawValue = ret[1]
return (0,'')
def encrypt(self, password = None):
self.encrypted = True
if password != None:
self.encryptionKey = password
try:
self.encryptedValue = RC4(self.rawValue,self.encryptionKey)
except:
errorMessage = 'Error encrypting with RC4'
self.addError(errorMessage)
return (-1,errorMessage)
return (0,'')
def decrypt(self, password = None, algorithm = 'RC4'):
'''
Decrypt the content of the object if possible
@param password: The password used to decrypt the object. It's dependent on the object.
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
self.encrypted = True
if password != None:
self.encryptionKey = password
try:
cleanString = unescapeString(self.encryptedValue)
if algorithm == 'RC4':
self.rawValue = RC4(cleanString,self.encryptionKey)
elif algorithm == 'AES':
ret = AES.decryptData(cleanString,self.encryptionKey)
if ret[0] != -1:
self.rawValue = ret[1]
else:
errorMessage = 'AES decryption error: '+ret[1]
self.addError(errorMessage)
return (-1,errorMessage)
except:
errorMessage = 'Error decrypting with '+str(algorithm)
self.addError(errorMessage)
return (-1,errorMessage)
ret = self.update(decrypt = True)
return (0,'')
def getEncryptedValue(self):
return '('+escapeString(self.encryptedValue)+')'
def getJSCode(self):
'''
Gets the Javascript code of the object
@return: An array of Javascript code sections
'''
return self.JSCode
def getRawValue(self):
return '('+escapeString(self.rawValue)+')'
def getUnescapedBytes(self):
'''
Gets the escaped bytes of the object unescaped
@return: An array of unescaped bytes (string)
'''
return self.unescapedBytes
def getURLs(self):
'''
Gets the URLs of the object
@return: An array of URLs
'''
return self.urlsFound
class PDFHexString (PDFObject) :
'''
Hexadecimal string object of a PDF document
'''
def __init__(self, hex) :
self.asciiValue = ''
self.type = 'hexstring'
self.errors = []
self.compressedIn = None
self.encrypted = False
self.value = '' # Value after hex decoding and decryption
self.rawValue = hex # Hex characters
self.encryptedValue = hex # Value after hex decoding
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.JSCode = []
self.uriList = []
self.unescapedBytes = []
self.urlsFound = []
self.referencesInElements = {}
self.references = []
ret = self.update()
if ret[0] == -1:
if isForceMode:
self.addError(ret[1])
else:
raise Exception(ret[1])
def update(self, decrypt = False, newHexValue = True):
'''
Updates the object after some modification has occurred
@param decrypt: A boolean indicating if a decryption has been performed. By default: False.
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
self.errors = []
self.containsJScode = False
self.JSCode = []
self.unescapedBytes = []
self.urlsFound = []
if not decrypt:
try:
if newHexValue:
# New hexadecimal value
self.value = ''
tmpValue = self.rawValue
if len(tmpValue) % 2 != 0:
tmpValue += '0'
self.value = tmpValue.decode('hex')
else:
# New decoded value
self.rawValue = self.value.encode('hex')
self.encryptedValue = self.value
except:
errorMessage = 'Error in hexadecimal conversion'
self.addError(errorMessage)
return (-1,errorMessage)
if isJavascript(self.value) or self.referencedJSObject:
self.containsJScode = True
self.JSCode, self.unescapedBytes, self.urlsFound, jsErrors, jsContexts['global'] = analyseJS(self.value, jsContexts['global'], isManualAnalysis)
if jsErrors != []:
for jsError in jsErrors:
errorMessage = 'Error analysing Javascript: '+jsError
if isForceMode:
self.addError(errorMessage)
else:
return (-1,errorMessage)
if self.encrypted and not decrypt:
ret = self.encrypt()
if ret[0] == -1:
return ret
return (0,'')
def encrypt(self, password = None):
self.encrypted = True
if password != None:
self.encryptionKey = password
try:
self.encryptedValue = RC4(self.value,self.encryptionKey)
self.rawValue = self.encryptedValue.encode('hex')
except:
errorMessage = 'Error encrypting with RC4'
self.addError(errorMessage)
return (-1,errorMessage)
return (0,'')
def decrypt(self, password = None, algorithm = 'RC4'):
'''
Decrypt the content of the object if possible
@param password: The password used to decrypt the object. It's dependent on the object.
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
self.encrypted = True
if password != None:
self.encryptionKey = password
try:
cleanString = unescapeString(self.encryptedValue)
if algorithm == 'RC4':
self.value = RC4(cleanString,self.encryptionKey)
elif algorithm == 'AES':
ret = AES.decryptData(cleanString,self.encryptionKey)
if ret[0] != -1:
self.value = ret[1]
else:
errorMessage = 'AES decryption error: '+ret[1]
self.addError(errorMessage)
return (-1,errorMessage)
except:
errorMessage = 'Error decrypting with '+str(algorithm)
self.addError(errorMessage)
return (-1,errorMessage)
ret = self.update(decrypt = True)
return ret
def getEncryptedValue(self):
return '<'+self.rawValue+'>'
def getJSCode(self):
'''
Gets the Javascript code of the object
@return: An array of Javascript code sections
'''
return self.JSCode
def getRawValue(self):
return '<'+self.rawValue+'>'
def getUnescapedBytes(self):
'''
Gets the escaped bytes of the object unescaped
@return: An array of unescaped bytes (string)
'''
return self.unescapedBytes
def getURLs(self):
'''
Gets the URLs of the object
@return: An array of URLs
'''
return self.urlsFound
class PDFReference (PDFObject) :
'''
Reference object of a PDF document
'''
def __init__(self, id, genNumber = '0') :
self.type = 'reference'
self.errors = []
self.JSCode = []
self.uriList = []
self.compressedIn = None
self.encrypted = False
self.value = self.rawValue = self.encryptedValue = id + ' ' + genNumber + ' R'
self.id = id
self.genNumber = genNumber
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.referencesInElements = {}
self.references = []
ret = self.update()
if ret[0] == -1:
if isForceMode:
self.addError(ret[1])
else:
raise Exception(ret[1])
def update(self):
self.errors = []
self.value = self.encryptedValue = self.rawValue
valueElements = self.rawValue.split()
if valueElements != []:
self.id = int(valueElements[0])
self.genNumber = int(valueElements[1])
else:
errorMessage = 'Error getting PDFReference elements'
self.addError(errorMessage)
return (-1,errorMessage)
return (0,'')
def getGenNumber(self):
'''
Gets the generation number of the reference
@return: The generation number (int)
'''
return self.genNumber
def getId(self):
'''
Gets the object id of the reference
@return: The object id (int)
'''
return self.id
def setGenNumber(self, newGenNumber):
'''
Sets the generation number of the reference
@param newGenNumber: The new generation number (int)
'''
self.genNumber = newGenNumber
def setId(self, newId):
'''
Sets the object id of the reference
@param newId: The new object id (int)
'''
self.id = newId
class PDFArray (PDFObject) :
'''
Array object of a PDF document
'''
def __init__(self, rawContent = '', elements = []) :
self.type = 'array'
self.errors = []
self.JSCode = []
self.uriList = []
self.compressedIn = None
self.encrypted = False
self.encryptedValue = rawContent
self.rawValue = rawContent
self.elements = elements
self.value = ''
self.updateNeeded = False
self.containsJScode = False
self.referencedJSObject = False
self.referencesInElements = {}
self.references = []
ret = self.update()
if ret[0] == -1:
if isForceMode:
self.addError(ret[1])
else:
raise Exception(ret[1])
def update(self, decrypt = False):
'''
Updates the object after some modification has occurred
@param decrypt: A boolean indicating if a decryption has been performed. By default: False.
@return: A tuple (status,statusContent), where statusContent is empty in case status = 0 or an error message in case status = -1
'''
errorMessage = ''
self.errors = []
self.encryptedValue = '[ '
self.rawValue = '[ '
self.value = '[ '
self.references = []
self.containsJScode = False
self.JSCode = []
self.unescapedBytes = []
self.urlsFound = []
for element in self.elements:
if element != None:
type = element.getType()
if type == 'reference':
self.references.append(element.getValue())
elif type == 'dictionary' or type == 'array':
self.references += element.getReferences()
if element.containsJS():
self.containsJScode = True
self.JSCode += element.getJSCode()
self.unescapedBytes += element.getUnescapedBytes()
self.urlsFound += element.getURLs()
if element.isFaulty():
for error in element.getErrors():
self.addError('Children element contains errors: ' + error)
if type in ['string','hexstring','array','dictionary'] and self.encrypted and not decrypt:
ret = element.encrypt(self.encryptionKey)
if ret[0] == -1:
errorMessage = 'Error encrypting element'
self.addError(errorMessage)