forked from patrickdw123/ParanoiDF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPDFConsole.py
executable file
·3963 lines (3809 loc) · 176 KB
/
PDFConsole.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
# ParanoiDF. A combination of several PDF analysis/manipulation tools to
# produce one of the most technically useful PDF analysis tools.
#
# Idea proposed by Julio Hernandez-Castro, University of Kent, UK.
# By Patrick Wragg
# University of Kent
# 21/07/2014
#
# With thanks to:
# Julio Hernandez-Castro, my supervisor.
# Jose Miguel Esparza for writing PeePDF (the basis of this tool).
# Didier Stevens for his "make-PDF" tools.
# Blake Hartstein for Jsunpack-n.
# Yusuke Shinyama for Pdf2txt.py (PDFMiner)
# Nacho Barrientos Arias for Pdfcrack.
# Kovid Goyal for Calibre (DRM removal).
# Jay Berkenbilt for QPDF.
#
# Copyright (C) 2014-2018 Patrick Wragg
#
# This file is part of ParanoiDF.
#
# ParanoiDF 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.
#
# ParanoiDF 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 ParanoiDF. If not, see <http://www.gnu.org/licenses/>.
#
# This was written by Jose Miguel Esparza for the tool PeePDF. It has been
# modified by Patrick Wragg 22/07/2014. I have added several new scripts/
# calls to tools that can be found between the #### markings.
'''
Implementation of the interactive console of ParanoiDF
'''
import cmd
import sys
import os
import re
import subprocess
import optparse
import hashlib
import jsbeautifier
import traceback
import redact
import imp
from PDFUtils import *
from PDFCrypto import *
from JSAnalysis import *
from PDFCore import *
from base64 import b64encode,b64decode
from PDFFilters import decodeStream,encodeStream
from jjdecode import JJDecoder
try:
from colorama import init, Fore, Back, Style
COLORIZED_OUTPUT = True
except:
COLORIZED_OUTPUT = False
# The GNU readline function does not handle correctly the colorized (ANSI) prompts, so this is a dirty fix
try:
import readline
RL_PROMPT_START_IGNORE = '\001'
RL_PROMPT_END_IGNORE = '\002'
except:
RL_PROMPT_START_IGNORE = RL_PROMPT_END_IGNORE = ''
try:
from bs4 import BeautifulSoup
except ImportError:
print 'BeautifulSoup needed for JS extraction. "pip install BeautifulSoup4". (Will include this in the build soon).'
sys.exit()
# File and variable redirections
FILE_WRITE = 1
FILE_ADD = 2
VAR_WRITE = 3
VAR_ADD = 4
newLine = os.linesep
errorsFile = 'errors.txt'
filter2RealFilterDict = {'b64':'base64','base64':'base64','asciihex':'/ASCIIHexDecode','ahx':'/ASCIIHexDecode','ascii85':'/ASCII85Decode','a85':'/ASCII85Decode','lzw':'/LZWDecode','flatedecode':'/FlateDecode','fl':'/FlateDecode','runlength':'/RunLengthDecode','rl':'/RunLengthDecode','ccittfax':'/CCITTFaxDecode','ccf':'/CCITTFaxDecode','jbig2':'/JBIG2Decode','dct':'/DCTDecode','jpx':'/JPXDecode'}
class PDFConsole(cmd.Cmd):
'''
Class of the ParanoiDF interactive console.
'''
def __init__(self, pdfFile, vtKey, avoidOutputColors = False, stdin = None):
global COLORIZED_OUTPUT
cmd.Cmd.__init__(self, stdin = stdin)
errorColorizedInit = False
self.warningColor = ''
self.errorColor = ''
self.alertColor = ''
self.staticColor = ''
self.resetColor = ''
if not COLORIZED_OUTPUT or avoidOutputColors:
self.avoidOutputColors = True
else:
try:
init()
self.warningColor = Fore.YELLOW
self.errorColor = Fore.RED
self.alertColor = Fore.RED
self.staticColor = Fore.BLUE
self.promptColor = RL_PROMPT_START_IGNORE + Fore.RED + RL_PROMPT_END_IGNORE
self.resetColor = Style.RESET_ALL
self.avoidOutputColors = False
except:
self.avoidOutputColors = True
COLORIZED_OUTPUT = False
if not self.avoidOutputColors:
self.prompt = self.promptColor + 'ParanoiDF> ' + RL_PROMPT_START_IGNORE + self.resetColor + RL_PROMPT_END_IGNORE
else:
self.prompt = 'ParanoiDF> '
self.use_rawinput = True
if stdin != None:
self.use_rawinput = False
self.prompt = ''
self.pdfFile = pdfFile
self.variables = {'output_limit':[1000,1000],
'malformed_options':[[],[]],
'header_file':[None,None],
'vt_key':[vtKey,vtKey]}
self.javaScriptContexts = {'global': None}
self.readOnlyVariables = ['malformed_options','header_file']
self.loggingFile = None
self.output = None
self.redirect = None
self.leaving = False
self.outputVarName = None
self.outputFileName = None
def emptyline(self):
return
def precmd(self, line):
if line == 'EOF':
return 'exit'
else:
return line
def postloop(self):
if self.use_rawinput:
print newLine + 'Leaving the ParanoiDF interactive console.' + newLine
self.leaving = True
######################################################################################################
def do_redact(self, argv): #See redact.py or tutorial.pdf for info.
args = self.parseArgs(argv)
numArgs = len(args)
try:
import nltk
except ImportError:
print 'No NLTK module found (Natural Language ToolKit), type <apt-get install python-nltk> to get.'
return True
try:
null = open('/dev/null', 'w')
subprocess.Popen('java', stdout=null, stderr=null)
null.close()
except OSError:
print 'No Java installed, type <apt-get install default-jre> to install.'
return True
dirCheck = os.path.dirname(os.path.abspath(sys.argv[0]))
redactDirCheck = dirCheck + '/redactDict/'
fontDirCheck = dirCheck + '/fonts/'
stanfordParserCheck = dirCheck + '/stanfordParser/'
if not os.path.isdir(redactDirCheck):
print 'Redact dictionary directory not found inside: ' + dirCheck
return True
if not os.path.isdir(fontDirCheck):
print 'No fonts directory found inside: ' + dirCheck
return True
if not os.path.isdir(stanfordParserCheck):
print 'No Stanford Parser directory found inside: ' + dirCheck
return True
if numArgs == 2:
wordType = args[0]
letterCase = args[1]
if wordType.lower() == 'w' or \
wordType.lower() == 's' or \
wordType.lower() == 'f' or \
wordType.lower() == 'c':
if letterCase.lower() == 'u' or \
letterCase.lower() == 'l' or \
letterCase.lower() == 'c':
redact.main(wordType, letterCase)
else:
self.help_redact()
else:
self.help_redact()
else:
self.help_redact()
def help_redact(self):
print newLine + 'Usage: redact $word-type $letter-case'
print newLine + 'Generate a list of words that will fit inside a redaction box ' \
'in a PDF document. The words (with a custom sentance) can then be ' \
'parsed in a grammar parser and displayed depending on their score.'
print newLine + 'Only dictionary words may be grammar parsed. (See tutorial.pdf on how to use)'
print newLine + 'Wordtypes:\nw = dictionary word\nc = country\nf = first name\ns = surname\n' \
'Lettercases:\nl = lowercase\nu = uppercase\nc = capitalised first letter'
print newLine + 'Example: redact w c'
def do_embedjs(self, argv): #Call to Didier Stevens make-pdf-javascript tool.
args = self.parseArgs(argv)
numArgs = len(args)
try:
import makeJavaScript
except ImportError:
print 'No makeJavaScript script found, check source repository and re-download.'
return True
if numArgs > 0:
if numArgs == 1:
option = 0
outputFile = args[0]
makeJavaScript.main(option, outputFile)
elif numArgs == 2:
option = args[0]
outputFile = args[1]
makeJavaScript.main(option, outputFile)
else:
self.help_embedjs()
else:
self.help_embedjs()
def help_embedjs(self):
print newLine + 'Usage: embedjs $javascript-file $output-pdf'
print ' embedjs output-pdf'
print newLine + 'Create a PDF document with embedded JavaScript that will ' \
'execute automatically when the document is opened. If no file is ' \
'opened, a default app.alert messagebox is embedded.'
print newLine + 'Example: embedjs button.js button.pdf' + newLine
def do_embedf(self,argv): #Call to Didier Stevens make-pdf-embedded tool.
args = self.parseArgs(argv)
numArgs = len(args)
try:
import makeEmbedded
except ImportError:
print 'No makeEmbedded script found, check source repository and re-download.'
return True
if numArgs == 2:
options = 0
embeddedFileName = args[0]
pdfFileName = args[1]
makeEmbedded.main(options, embeddedFileName, pdfFileName)
elif numArgs == 3:
options = args[0]
embeddedFileName = args[1]
pdfFileName = args[2]
makeEmbedded.main(options, embeddedFileName, pdfFileName)
else:
self.help_embedf()
def help_embedf(self):
print newLine + 'Usage: embedf [options] $file-to-embed $output-pdf'
print newLine + 'Create a PDF document with an embedded file.'
print newLine + 'Options (see example):'
print 'f=FILTERS\tFilters to apply, f for FlateDecode (default), ' \
'h for ASCIIHexDecode.'
print 't\t\tDo not add comment for binary format.'
print 'a\t\tAutoopen - Open the embedded file automatically when ' \
'the PDF is opened.'
print 'b\t\tAdd a "button" to launch the embedded file.'
print 's\t\t"hide" the embedded file by replacing /EmbeddedFiles ' \
'with /Embeddedfiles.'
print 'm=MESSAGE\tText to display in the PDF document.'
print newLine + 'Example: embedf a,t,b,f=f,m=Hello fileToEmbed.zip output.pdf' + newLine
#There was already a do_decrypt function in PeePDF. At the time of doing this project
#though, it did not work on a few of my PDFs. So I used QPDF for the time being because
#of time constraints (of building a new one). I contacted Jose though and he did update the do_decrypt method
#on the latest version of PeePdf. I can confirm that this works. Something I will do
#in the future is probably remove this decrypt method and implement Jose's again as
#having the implementation "in-house" is much better in my opinion than doing a system
#call to a program.
def do_decrypt(self,argv): #Decrypt the PDF using qpdf.
try:
null = open('/dev/null', 'w')
subprocess.Popen('qpdf', stdout=null, stderr=null)
null.close()
except OSError:
print 'No QPDF installed, type <apt-get install qpdf> to install.'
return True
args = self.parseArgs(argv)
numArgs = len(args)
if numArgs == 3:
password = args[0]
inputFile = args[1]
outputFile = args[2]
try:
file = open(inputFile)
file.close()
os.system('qpdf --password=' + password + ' --decrypt ' + inputFile + ' ' + outputFile)
except IOError:
print 'Input file not found.'
else:
self.help_decrypt()
def help_decrypt(self):
print newLine + 'Usage: decrypt $password $input-pdf $output-pdf'
print newLine + 'Decrypt a PDF document.' + newLine
#Encrypt using 128-bit RC4. Simple I know but stronger encryption is something I can
#add in the future.
def do_encrypt(self,argv):
try:
from pyPdf import PdfFileWriter, PdfFileReader
except ImportError:
print 'Module pyPdf needed, type <apt-get install python-pypdf> to obtain.'
return True
args = self.parseArgs(argv)
numArgs = len(args)
if numArgs == 3:
password = args[0]
inputFile = args[1]
outputFile = args[2]
try:
output = PdfFileWriter()
input = PdfFileReader(file(inputFile, 'rb'))
for i in range(0, input.getNumPages()):
output.addPage(input.getPage(i))
outputStream = file(outputFile, 'wb')
output.encrypt(password, use_128bit=True)
output.write(outputStream)
outputStream.close()
except IOError:
print 'Input file not found.'
else:
self.help_encrypt()
def help_encrypt(self):
print newLine + 'Usage: encrypt $password $input-pdf $output-pdf'
print newLine + 'Encrypt a PDF document.' + newLine
def do_crackpw(self, argv): #Use pdfcrack in-house to crack a password.
dirCheck = os.path.dirname(os.path.abspath(sys.argv[0]))
try:
null = open('/dev/null', 'w')
subprocess.Popen('pdfcrack', stdout=null, stderr=null)
null.close()
except OSError:
print 'No Pdfcrack installed, type <apt-get install pdfcrack> to install.'
return True
args = self.parseArgs(argv)
numArgs=len(args)
if numArgs == 1:
arg = args[0]
if arg.lower() == 'b':
os.system('pdfcrack -b')
elif arg[:2] == 'l=':
savedStateFile = arg[2:]
try:
file = open(savedStateFile)
file.close()
os.system('pdfcrack -l ' + savedStateFile)
except IOError:
print 'Saved state file not found.'
else:
try:
file = open(arg)
file.close()
try:
file = open(dirCheck + '/pdfcrack/charset.txt', 'r')
charset = file.read()
file.close()
print 'Brute forcing using chars from "pdfcrack/charset.txt".'
os.system('pdfcrack ' + arg + ' -c ' + charset)
except IOError:
print 'Charset file not found.'
except IOError:
print 'Input file not found.'
elif numArgs == 2:
options = args[0]
inputFile = args[1]
if options[:2] == 'w=':
dictFile = options[2:]
try:
file = open(dictFile)
file.close()
print 'Custom dictionary: ' + dictFile + ' being used.'
os.system('pdfcrack -w ' + dictFile + ' ' + inputFile)
except IOError:
print 'Dictionary file not found.'
else:
self.help_crackpw()
else:
self.help_crackpw()
def help_crackpw(self):
print newLine + 'Usage: crackpw [option] $input-file'
print ' crackpw $input-file'
print ' crackpw b'
print newLine + 'Brute force or dictionary attack a PDF document.'
print newLine + 'Options:\nb\t\tPerform benchmark and exit.\n' \
'w=FILE\t\tUse FILE as a source of passwords to try.\n' \
'l=FILE\t\tContinue from the state saved in FILE.'
print newLine + 'Example: crackpw w=dict.txt uncrackable.pdf' + newLine
def do_removeDRM(self,argv): #Use Calibre's "ebook-convert" to strip rights off a PDF.
try:
null = open('/dev/null', 'w')
subprocess.Popen('ebook-convert', stdout=null, stderr=null)
null.close()
except OSError:
print 'No Calibre installed, type <apt-get install calibre> to install.'
return True
args = self.parseArgs(argv)
numArgs = len(args)
if numArgs == 2:
inputFile = args[0]
outputFile = args[1]
if '.pdf' in inputFile and '.pdf' in outputFile:
try:
file = open(inputFile)
file.close()
os.system('ebook-convert ' + inputFile + ' ' + outputFile)
except IOError:
print 'Input file not found.'
else:
print '.pdf extension needed.'
else:
self.help_removeDRM()
def help_removeDRM(self):
print newLine + 'Usage: removeDRM $input-pdf $output-pdf'
print newLine + 'Remove DRM (editing, copying etc.) restrictions from PDF document.' + newLine
def do_extractJS(self,argv): #Use Jsunpack-n's PDF JavaScript extract script.
try:
import extractJavaScript
except ImportError:
print 'No extractJavaScript script found, check source repository and re-download.'
return True
args = self.parseArgs(argv)
numArgs = len(args)
if numArgs == 1:
inputFile = args[0]
try:
file = open(inputFile)
file.close()
extractJavaScript.main(inputFile)
except IOError:
print 'Input file not found.'
else:
self.help_extractJS()
def help_extractJS(self):
print newLine + 'Usage: extractJS $input-pdf'
print newLine + 'Extract JavaScript from PDF document.' + newLine
######################################################################################################
def do_bytes(self, argv):
if self.pdfFile == None:
message = '*** Error: You must open a file!!'
self.log_output('bytes ' + argv, message)
return False
bytes = ''
args = self.parseArgs(argv)
if args == None:
message = '*** Error: The command line arguments have not been parsed successfully!!'
self.log_output('bytes ' + argv, message)
return False
numArgs = len(args)
if numArgs == 2 or numArgs == 3:
offset = int(args[0])
size = int(args[1])
ret = getBytesFromFile(self.pdfFile.getPath(),offset,size)
if ret[0] == -1:
message = '*** Error: The file does not exist!!'
self.log_output('bytes ' + argv, message)
return False
bytes = ret[1]
if numArgs == 2:
self.log_output('bytes ' + argv, bytes, [bytes], bytesOutput = True)
else:
outputFile = args[2]
open(outputFile,'wb').write(bytes)
else:
self.help_bytes()
def help_bytes(self):
print newLine + 'Usage: bytes $offset $num_bytes [$file]'
print newLine + 'Shows or stores in the specified file $num_bytes of the file beginning from $offset' + newLine
def do_changelog(self, argv):
if self.pdfFile == None:
message = '*** Error: You must open a file!!'
self.log_output('changelog ' + argv, message)
return False
output = ''
args = self.parseArgs(argv)
if args == None:
message = '*** Error: The command line arguments have not been parsed successfully!!'
self.log_output('changelog ' + argv, message)
return False
if len(args) == 0:
version = None
elif len(args) == 1:
version = args[0]
else:
self.help_changelog()
return False
if version != None and not version.isdigit():
self.help_changelog()
return False
if version != None:
version = int(version)
if version > self.pdfFile.getNumUpdates():
message = '*** Error: The version number is not valid!!'
self.log_output('changelog ' + argv, message)
return False
if version == 0 or (version == None and self.pdfFile.getNumUpdates() == 0):
message = '*** No changes!!'
self.log_output('changelog ' + argv, message)
return False
# Getting information about original document
data = self.pdfFile.getBasicMetadata(0)
if data.has_key('author'):
output += '\tAuthor: ' + data['author'] + newLine
if data.has_key('creator'):
output += '\tCreator: ' + data['creator'] + newLine
if data.has_key('producer'):
output += '\tProducer: ' + data['producer'] + newLine
if data.has_key('creation'):
output += '\tCreation date: ' + data['creation'] + newLine
if output != '':
output = 'Original document information:' + newLine + output + newLine
# Getting changes for versions
changes = self.pdfFile.getChangeLog(version)
for i in range(len(changes)):
changelog = changes[i]
if changelog == [[],[],[],[]]:
output += 'No changes in version ' + str(i+1) + newLine
else:
output += 'Changes in version ' + str(i+1) + ':' + newLine
# Getting modification information
data = self.pdfFile.getBasicMetadata(i+1)
if data.has_key('author'):
output += '\tAuthor: ' + data['author'] + newLine
if data.has_key('creator'):
output += '\tCreator: ' + data['creator'] + newLine
if data.has_key('producer'):
output += '\tProducer: ' + data['producer'] + newLine
if data.has_key('modification'):
output += '\tModification date: ' + data['modification'] + newLine
addedObjects = changelog[0]
modifiedObjects = changelog[1]
removedObjects = changelog[2]
notMatchingObjects = changelog[3]
if addedObjects != []:
output += '\tAdded objects: ' + str(addedObjects) + newLine
if modifiedObjects != []:
output += '\tModified objects: ' + str(modifiedObjects) + newLine
if removedObjects != []:
output += '\tRemoved objects: ' + str(removedObjects) + newLine
if notMatchingObjects != []:
output += '\tIncoherent objects: ' + str(notMatchingObjects) + newLine
output += newLine
self.log_output('changelog ' + argv, output)
def help_changelog(self):
print newLine + 'Usage: changelog [$version]'
print newLine + 'Shows the changelog of the document or version of the document' + newLine
def do_decode(self, argv):
decodedContent = ''
src = ''
offset = 0
size = 0
validTypes = ['variable','file','raw']
notImplementedFilters = ['ccittfax''ccf','jbig2','dct','jpx']
filters = []
args = self.parseArgs(argv)
if args == None:
message = '*** Error: The command line arguments have not been parsed successfully!!'
self.log_output('decode ' + argv, message)
return False
if len(args) > 2:
type = args[0]
iniFilterArgs = 2
if type not in validTypes:
self.help_decode()
return False
if type == 'variable' or type == 'file':
src = args[1]
else:
if self.pdfFile == None:
message = '*** Error: You must open a file!!'
self.log_output('decode ' + argv, message)
return False
if len(args) < 3:
self.help_decode()
return False
iniFilterArgs = 3
offset = args[1]
size = args[2]
if not offset.isdigit() or not size.isdigit():
message = '*** Error: "offset" and "num_bytes" must be integers!!'
self.log_output('decode ' + argv, message)
return False
offset = int(args[1])
size = int(args[1])
for i in range(iniFilterArgs,len(args)):
filter = args[i].lower()
if filter not in filter2RealFilterDict.keys():
self.help_decode()
return False
if filter in notImplementedFilters:
message = '*** Error: Filter "'+filter+'" not implemented yet!!'
self.log_output('decode ' + argv, message)
return False
filters.append(filter)
else:
self.help_decode()
return False
if type == 'variable':
if not self.variables.has_key(src):
message = '*** Error: The variable does not exist!!'
self.log_output('decode ' + argv, message)
return False
else:
decodedContent = self.variables[src][0]
elif type == 'file':
if not os.path.exists(src):
message = '*** Error: The file does not exist!!'
self.log_output('decode ' + argv, message)
return False
else:
decodedContent = open(src,'rb').read()
else:
ret = getBytesFromFile(self.pdfFile.getPath(),offset,size)
if ret[0] == -1:
message = '*** Error: The file does not exist!!'
self.log_output('decode ' + argv, message)
return False
decodedContent = ret[1]
if decodedContent == '':
message = '*** Error: The content is empty!!'
self.log_output('decode ' + argv, message)
return False
for filter in filters:
realFilter = filter2RealFilterDict[filter]
if realFilter == 'base64':
try:
decodedContent = b64decode(decodedContent)
except:
message = '*** Error: '+str(sys.exc_info()[1])+'!!'
self.log_output('decode ' + argv, message)
return False
else:
ret = decodeStream(decodedContent, realFilter)
if ret[0] == -1:
message = '*** Error: '+ret[1]+'!!'
self.log_output('decode ' + argv, message)
return False
decodedContent = ret[1]
self.log_output('decode ' + argv, decodedContent, [decodedContent], bytesOutput = True)
def help_decode(self):
print newLine + 'Usage: decode variable $var_name $filter1 [$filter2 ...]'
print 'Usage: decode file $file_name $filter1 [$filter2 ...]'
print 'Usage: decode raw $offset $num_bytes $filter1 [$filter2 ...]' + newLine
print 'Decodes the content of the specified variable, file or raw bytes using the following filters or algorithms:'
print '\tbase64,b64: Base64'
print '\tasciihex,ahx: /ASCIIHexDecode'
print '\tascii85,a85: /ASCII85Decode'
print '\tlzw: /LZWDecode'
print '\tflatedecode,fl: /FlateDecode'
print '\trunlength,rl: /RunLengthDecode'
print '\tccittfax,ccf: /CCITTFaxDecode'
print '\tjbig2: /JBIG2Decode (Not implemented)'
print '\tdct: /DCTDecode (Not implemented)'
print '\tjpx: /JPXDecode (Not implemented)' + newLine
def do_encode(self, argv):
encodedContent = ''
src = ''
offset = 0
size = 0
validTypes = ['variable','file','raw']
notImplementedFilters = ['ascii85','a85','runlength','rl','jbig2','jpx','ccittfax','ccf','dct']
filters = []
args = self.parseArgs(argv)
if args == None:
message = '*** Error: The command line arguments have not been parsed successfully!!'
self.log_output('encode ' + argv, message)
return False
if len(args) > 2:
type = args[0]
iniFilterArgs = 2
if type not in validTypes:
self.help_encode()
return False
if type == 'variable' or type == 'file':
src = args[1]
else:
if self.pdfFile == None:
message = '*** Error: You must open a file!!'
self.log_output('decode ' + argv, message)
return False
if len(args) < 3:
self.help_encode()
return False
iniFilterArgs = 3
offset = args[1]
size = args[2]
if not offset.isdigit() or not size.isdigit():
message = '*** Error: "offset" and "num_bytes" must be integers!!'
self.log_output('encode ' + argv, message)
return False
offset = int(args[1])
size = int(args[1])
for i in range(iniFilterArgs,len(args)):
filter = args[i].lower()
if filter not in filter2RealFilterDict.keys():
self.help_encode()
return False
if filter in notImplementedFilters:
message = '*** Error: Filter "'+filter+'" not implemented yet!!'
self.log_output('encode ' + argv, message)
return False
filters.append(filter)
else:
self.help_encode()
return False
if type == 'variable':
if not self.variables.has_key(src):
message = '*** Error: The variable does not exist!!'
self.log_output('encode ' + argv, message)
return False
else:
encodedContent = self.variables[src][0]
elif type == 'file':
if not os.path.exists(src):
message = '*** Error: The file does not exist!!'
self.log_output('encode ' + argv, message)
return False
else:
encodedContent = open(src,'rb').read()
else:
ret = getBytesFromFile(self.pdfFile.getPath(),offset,size)
if ret[0] == -1:
message = '*** Error: The file does not exist!!'
self.log_output('encode ' + argv, message)
return False
encodedContent = ret[1]
if encodedContent == '':
message = '*** Error: The content is empty!!'
self.log_output('encode ' + argv, message)
return False
for filter in filters:
realFilter = filter2RealFilterDict[filter]
if realFilter == 'base64':
encodedContent = b64encode(encodedContent)
else:
ret = encodeStream(encodedContent, realFilter)
if ret[0] == -1:
message = '*** Error: '+ret[1]+'!!'
self.log_output('encode ' + argv, message)
return False
encodedContent = ret[1]
self.log_output('encode ' + argv, encodedContent, [encodedContent], bytesOutput = True)
def help_encode(self):
print newLine + 'Usage: encode variable $var_name $filter1 [$filter2 ...]'
print 'Usage: encode file $file_name $filter1 [$filter2 ...]'
print 'Usage: encode raw $offset $num_bytes $filter1 [$filter2 ...]' + newLine
print 'Encodes the content of the specified variable, file or raw bytes using the following filters or algorithms:'
print '\tbase64,b64: Base64'
print '\tasciihex,ahx: /ASCIIHexDecode'
print '\tascii85,a85: /ASCII85Decode (Not implemented)'
print '\tlzw: /LZWDecode'
print '\tflatedecode,fl: /FlateDecode'
print '\trunlength,rl: /RunLengthDecode (Not implemented)'
print '\tccittfax,ccf: /CCITTFaxDecode (Not implemented)'
print '\tjbig2: /JBIG2Decode (Not implemented)'
print '\tdct: /DCTDecode (Not implemented)'
print '\tjpx: /JPXDecode (Not implemented)' + newLine
def do_encode_strings(self, argv):
if self.pdfFile == None:
message = '*** Error: You must open a file!!'
self.log_output('encode_strings ' + argv, message)
return False
args = self.parseArgs(argv)
if args == None:
message = '*** Error: The command line arguments have not been parsed successfully!!'
self.log_output('encode_strings ' + argv, message)
return False
if len(args) == 0:
ret = self.pdfFile.encodeChars()
if ret[0] == -1:
message = '*** Error: '+ret[1]+'!!'
self.log_output('encode_strings ' + argv, message)
return False
message = 'File encoded successfully'
elif len(args) == 1 or len(args) == 2:
if len(args) == 1:
version = None
else:
version = args[1]
id = args[0]
if (not id.isdigit() and id != 'trailer') or (version != None and not version.isdigit()):
self.help_encode_strings()
return False
if version != None:
version = int(version)
if version > self.pdfFile.getNumUpdates():
message = '*** Error: The version number is not valid!!'
self.log_output('encode_strings ' + argv, message)
return False
if id == 'trailer':
ret = self.pdfFile.getTrailer(version)
if ret == None or ret[1] == [] or ret[1] == None or ret[1] == [None,None]:
message = '*** Error: Trailer not found!!'
self.log_output('encode_strings ' + argv, message)
return False
else:
trailerArray = ret[1]
version = ret[0]
if trailerArray[0] != None:
trailerArray[0].encodeChars()
ret = self.pdfFile.setTrailer(trailerArray,version)
if ret[0] == -1:
message = '*** Error: There were some problems in the modification process!!'
self.log_output('encode_strings ' + argv, message)
return False
message = 'Trailer encoded successfully'
else:
id = int(id)
object = self.pdfFile.getObject(id, version)
if object == None:
message = '*** Error: Object not found!!'
self.log_output('encode_strings ' + argv, message)
return False
objectType = object.getType()
if objectType not in ['string','name','array','dictionary','stream']:
message = '*** Error: This type of object cannot be encoded!!'
self.log_output('encode_strings ' + argv, message)
return False
ret = object.encodeChars()
if ret[0] == -1:
message = '*** Error: '+ret[1]+'!!'
self.log_output('encode_strings ' + argv, message)
return False
ret = self.pdfFile.setObject(id, object, version, True)
if ret[0] == -1:
message = '*** Error: There were some problems in the modification process!!'
self.log_output('encode_strings ' + argv, message)
return False
message = 'Object encoded successfully'
else:
self.help_encode_strings()
return False
self.log_output('encode_strings ' + argv, message)
def help_encode_strings(self):
print newLine + 'Usage: encode_strings [$object_id|trailer [$version]]'
print newLine + 'Encodes the strings and names included in the file, object or trailer' + newLine
def do_errors(self, argv):
if self.pdfFile == None:
message = '*** Error: You must open a file!!'
self.log_output('errors ' + argv, message)
return False
errors = ''
errorsArray = []
args = self.parseArgs(argv)
if args == None:
message = '*** Error: The command line arguments have not been parsed successfully!!'
self.log_output('errors ' + argv, message)
return False
if len(args) == 0:
errorsArray = self.pdfFile.getErrors()
for error in errorsArray:
errors += error
if error != errorsArray[-1]:
errors += newLine
if errors == '':
errors = 'No errors!!'
else:
errors = self.errorColor + errors + self.resetColor
self.log_output('errors ' + argv, errors)
return False
elif len(args) == 1:
version = None
elif len(args) == 2:
version = args[1]
else:
self.help_errors()
return False
id = args[0]
if (not id.isdigit() and id != 'trailer' and id != 'xref') or (version != None and not version.isdigit()):
self.help_errors()
return False
if version != None:
version = int(version)
if version > self.pdfFile.getNumUpdates():
message = '*** Error: The version number is not valid!!'
self.log_output('errors ' + argv, message)
return False
if id == 'xref':
ret = self.pdfFile.getXrefSection(version)
if ret == None or ret[1] == None or ret[1] == [] or ret[1] == [None,None]:
message = '*** Error: xref section not found!!'
self.log_output('errors ' + argv, message)
return False
else:
xrefArray = ret[1]
if xrefArray[0] != None:
errorsArray = xrefArray[0].getErrors()
if xrefArray[1] != None:
errorsArray += xrefArray[1].getErrors()
elif id == 'trailer':
ret = self.pdfFile.getTrailer(version)
if ret == None or ret[1] == None or ret[1] == [] or ret[1] == [None,None]:
message = '*** Error: Trailer not found!!'
self.log_output('errors ' + argv, message)
return False
else:
trailerArray = ret[1]
if trailerArray[0] != None:
errorsArray = trailerArray[0].getErrors()
if trailerArray[1] != None:
errorsArray += trailerArray[1].getErrors()
else:
id = int(id)
object = self.pdfFile.getObject(id, version)
if object == None:
message = '*** Error: Object not found!!'
self.log_output('errors ' + argv, message)
return False
errorsArray = object.getErrors()
messages,counters = countArrayElements(errorsArray)
for i in range(len(messages)):
errors += messages[i] + ' ('+ str(counters[i]) +') ' + newLine
if errors == '':
errors = 'No errors!!'
else:
errors = self.errorColor + errors + self.resetColor
self.log_output('errors ' + argv, errors)
def help_errors(self):
print newLine + 'Usage: errors [$object_id|xref|trailer [$version]]'
print newLine + 'Shows the errors of the file or object (object_id, xref, trailer)' + newLine
def do_exit(self, argv):
return True
def help_exit(self):
print newLine + 'Usage: exit'
print newLine + 'Exits from the console' + newLine
def do_filters(self, argv):
if self.pdfFile == None:
message = '*** Error: You must open a file!!'
self.log_output('errors ' + argv, message)
return False
message = ''
value = ''
filtersArray = []
notImplementedFilters = ['ascii85','a85','runlength','rl','jbig2','jpx','ccittfax','ccf','dct']
iniFilterArgs = 1
filters = []
args = self.parseArgs(argv)
if args == None:
message = '*** Error: The command line arguments have not been parsed successfully!!'
self.log_output('filters ' + argv, message)
return False
if len(args) == 0:
self.help_filters()
return False
elif len(args) == 1:
version = None
else:
if args[1].isdigit():
version = args[1]
iniFilterArgs = 2