├── .gitignore ├── .travis.yml ├── AUTHORS ├── CHANGELOG ├── COPYING ├── README ├── README.md ├── TODO ├── appveyor.yml ├── peepdf.dtd ├── peepdf ├── JSAnalysis.py ├── PDFConsole.py ├── PDFCore.py ├── PDFCrypto.py ├── PDFFilters.py ├── PDFUtils.py ├── __init__.py ├── aes.py ├── ccitt.py ├── jjdecode.py ├── lzw.py └── main.py ├── setup.py └── tests ├── files ├── BB-1-Overview.pdf ├── js_in_pdf.js ├── phishing0.pdf └── worldreport.pdf └── test_pee.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .cache 3 | .idea 4 | peepdf.egg-info/ 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | matrix: 4 | fast_finish: true 5 | include: 6 | - python: 2.7 7 | - python: 3.5 8 | - python: 3.6 9 | - os: osx 10 | language: generic 11 | 12 | before_install: 13 | - | 14 | if [[ $TRAVIS_OS_NAME == "osx" ]]; then 15 | # The following wasn't required in the past and therefore may become 16 | # obsolete once again in the future. Let's wait and see. 17 | wget https://bootstrap.pypa.io/get-pip.py 18 | sudo python get-pip.py 19 | sudo pip install virtualenv 20 | virtualenv $HOME 21 | source $HOME/bin/activate 22 | fi 23 | - '[[ $TRAVIS_OS_NAME == "linux" ]] && sudo apt-get update -qq || true' 24 | - '[[ $TRAVIS_OS_NAME == "linux" ]] && sudo apt-get install python-dev libffi-dev libxml2-dev libxslt1-dev libjpeg-dev || true' 25 | 26 | install: 27 | - pip install -e . 28 | - pip install pytest pytest-cov mock coveralls 29 | 30 | script: 31 | - py.test --cov=peepdf 32 | 33 | after_success: 34 | - codecov 35 | - coveralls 36 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Jose Miguel Esparza 2 | http://eternal-todo.com 3 | http://twitter.com/EternalTodo -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | ----------------------------------------------- 2 | peepdf 0.3 r235, 2014-06-09 3 | ----------------------------------------------- 4 | 5 | * New features: 6 | 7 | - Added descriptive titles for the vulns found 8 | - Added detection of CVE-2013-2729 (Adobe Reader BMP/RLE heap corruption) 9 | - Added support for more than one script block in objects containing Javascript (e.g. XFA objects) 10 | - Updated colorama to version 3.1 (2014-04-19) 11 | - Added detection of CVE-2013-3346 (ToolButton Use-After-Free) 12 | - Added command "js_vars" to show the variables defined in the Javascript context and their content 13 | - Added command "js_jjdecode" to decode Javascript code using the jjencode algorithm (Thanks to Nahuel Riva @crackinglandia) 14 | - Added static detection for CVE-2010-0188 15 | - Added detection for CoolType.dll SING uniqueName vulnerability (CVE-2010-2883). Better late than never ;p 16 | - Added new command "vtcheck" to check for detection on VirusTotal (API key included) 17 | - Added option to avoid automatic Javascript analysis (useful with endless loops) 18 | - Added PyV8 as Javascript engine and removed Spidermonkey (Windows issues). 19 | 20 | * Fixes: 21 | 22 | - Fixed bug when encrypting/decrypting hexadecimal objects (Thanks to Timo Hirvonen for the feedback) 23 | - Fixed silly bug related to abbreviated PDF Filters 24 | - Fixed bug related to the GNU readline function not handling correctly colorized prompts 25 | - Fixed log_output function, it was storing the previous command output instead of the current one 26 | - Fixed bug in PDFStream to show the stream content when the stream dictionary is empty (Thanks to Nahuel Riva) 27 | - Fixed Issue 12, related to bad JS code parsing due to HTML entities in the XFA form (Thanks to robomotic) 28 | - Fixed Issue 10 related to bad error handling in the PDFFile.decrypt() method 29 | - Fixed Issue 9, related to an uncaught exception when PyV8 is not installed 30 | - Fixed bug in do_metadata() when objects contain /Metadata but they are not really Metadata objects 31 | 32 | * Others 33 | 34 | - Removed the old redirection method using the "set" command, it is useless now with the shell-like redirection (>, >>, $>, $>>) 35 | 36 | * Known issues 37 | 38 | - It exists a problem related to the readline module in Mac OS X (it uses editline instead of GNU readline), not handling correctly colorized prompts. 39 | 40 | ----------------------------------------------- 41 | peepdf Black Hat Vegas (0.2 r156), 2012-07-25 42 | ----------------------------------------------- 43 | 44 | * New features: 45 | 46 | - Added "grinch mode" execution to avoid colorized output 47 | - Added more colors in the interactive console output: warning, errors, important information... 48 | - Changed sctest command, now it's implemented with pylibemu 49 | - Added decrypt command to parse password protected documents 50 | - Modified analyseJS() to extract JS code from XDP packets and unescape HTML entities 51 | - Added function unescapeHTMLEntities() to unescape HTML entities 52 | - Added AES decryption support (128 and 256 bits). 53 | - Added hashes in objects information (info $object_id) 54 | - Added support for decoding CCITTFaxDecode filters (Thanks to @binjo) 55 | 56 | * Fixes: 57 | 58 | - Fix to show decrypt errors 59 | - Fixed silly bug with /EncryptMetadata element 60 | - Added missing binary file operations 61 | - Fixed Issue 5: Resolved false positives when monitoring some elements like actions, events, etc. (Thanks to @hiddenillusion) 62 | - Bug in PDFStream.decode and PDFStream.encode, dealing with an array of filter parameters (Thanks to @binjo) 63 | 64 | 65 | ----------------------------------------------- 66 | peepdf Black Hat Arsenal (0.1 r92), 2012-03-16 67 | ----------------------------------------------- 68 | 69 | * New features: 70 | 71 | - Added support for more parameters in Flate/LZW decode (stream filters) 72 | - Encryption algorithm now showing in document information 73 | - Added XML output and SHA hash to file information 74 | - Improved unescape function to support mixed escaped formats (eg. "%u6734%34%u8790") 75 | - Added xor and xor_search commands 76 | - Added easy way of redirect console output (>, >>, $>, $>>) 77 | - Added xor function by Evan Fosmark 78 | - Added detection of CVE-2011-4369 (/PRC) 79 | - Added hash command (Thanks to @binjo for code and comments) 80 | - Added js_beautify command 81 | - Update function added 82 | - Added new vulns and showing information related to non JS vulns 83 | - Added escape sequence in the limited output 84 | - Added ascii85 decode from pdfminer to improve code and avoid bugs (Thanks to Brandon Dixon!) 85 | - Added lzwdecode from pdfminer to improve code and avoid bugs 86 | 87 | * Fixes: 88 | 89 | - Update process rewritten, now based on hashing of files 90 | - Silly bug in computeUserPass function (Thanks to Christian Martorella!) 91 | - Added binary mode in files operations 92 | - Recursion bug in update function 93 | - Minor bug in do_embed function 94 | - Bug to support encoding following PDF specifications (Issue 3 by czchen) 95 | - Bug to handle negative numbers in P element 96 | - Bug in the xref table when creating a new PDF (Issue 2) 97 | - Silly bug when parsing filter parameters 98 | - Bug related to updating objects and statistics of PDF files 99 | - Some bugs related to offsets calculation 100 | - Fixed "replace" function in PDFObjectStream 101 | - Fix in asciiHexDecode filter function 102 | 103 | 104 | ----------------------------------------------- 105 | peepdf 0.1 r15, 2011-05-05 106 | ----------------------------------------------- 107 | 108 | - Initial Release 109 | 110 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | 2 | GNU GENERAL PUBLIC LICENSE 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | the GNU General Public License is intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | 636 | Copyright (C) 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | Copyright (C) 657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 658 | This is free software, and you are welcome to redistribute it 659 | under certain conditions; type `show c' for details. 660 | 661 | The hypothetical commands `show w' and `show c' should show the appropriate 662 | parts of the General Public License. Of course, your program's commands 663 | might be different; for a GUI interface, you would use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or school, 666 | if any, to sign a "copyright disclaimer" for the program, if necessary. 667 | For more information on this, and how to apply and follow the GNU GPL, see 668 | . 669 | 670 | The GNU General Public License does not permit incorporating your program 671 | into proprietary programs. If your program is a subroutine library, you 672 | may consider it more useful to permit linking proprietary applications with 673 | the library. If this is what you want to do, use the GNU Lesser General 674 | Public License instead of this License. But first, please read 675 | . 676 | 677 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | ** Home page ** 2 | 3 | http://peepdf.eternal-todo.com 4 | http://twitter.com/peepdf 5 | 6 | 7 | ** Dependencies ** 8 | 9 | 10 | - In order to analyse Javascript code "PyV8" is needed: 11 | 12 | http://code.google.com/p/pyv8/ 13 | 14 | 15 | - The "sctest" command is a wrapper of "sctest" (libemu). Besides libemu pylibemu is used and must be installed: 16 | 17 | http://libemu.carnivore.it (latest version from git repository, Sourceforge package is outdated) 18 | https://github.com/buffer/pylibemu 19 | 20 | 21 | - Included modules: lzw, ccitt (Thanks to all the developers!!) 22 | 23 | 24 | ** Installation ** 25 | 26 | Run, in peepdf directory 27 | 28 | easy_install . 29 | 30 | The setup script handles the installation of jsbeautifier, colorama, pythonaes and lxml 31 | 32 | 33 | ** Execution ** 34 | 35 | There are two important options when peepdf is executed: 36 | 37 | -f: Ignores the parsing errors. Analysing malicious files propably leads to parsing errors, so this parameter should be set. 38 | -l: Sets the loose mode, so does not search for the endobj tag because it's not obligatory. Helpful with malformed files. 39 | 40 | 41 | * Simple execution 42 | 43 | Shows the statistics of the file after being decoded/decrypted and analysed: 44 | 45 | peepdf.py [options] pdf_file 46 | 47 | 48 | * Interactive console 49 | 50 | Executes the interactive console to let play with the PDF file: 51 | 52 | peepdf.py -i [options] pdf_file 53 | 54 | If no PDF file is specified it's possible to use the decode/encode/js*/sctest commands and create a new PDF file: 55 | 56 | peepdf.py -i 57 | 58 | 59 | * Batch execution 60 | 61 | It's possible to use a commands file to specify the commands to be executed in the batch mode. This type of execution is good to automatise analysis of several files: 62 | 63 | peepdf.py [options] -s commands_file pdf_file 64 | 65 | 66 | 67 | ** Updating ** 68 | 69 | The option has been desactivated as it is not working for now. 70 | To update, cd to peepdf directory and type: 71 | 72 | git pull origin master 73 | easy_install . 74 | 75 | 76 | 77 | ** Some hints ** 78 | 79 | If the information shown when a PDF file is parsed is not enough to know if it's harmful or not, the following commands can help to do it: 80 | 81 | * tree 82 | 83 | Shows the tree graph of the file or specified version. Here we can see suspicious elements. 84 | 85 | 86 | * offsets 87 | 88 | Shows the physical map of the file or the specified version of the document. This is helpful to see unusual big objects or big spaces between objects. 89 | 90 | 91 | * search 92 | 93 | Search the specified string or hexadecimal string in the objects (decoded and encrypted streams included). 94 | 95 | 96 | * object/rawobject 97 | 98 | Shows the (raw) content of the object. 99 | 100 | 101 | * stream/rawstream 102 | 103 | Shows the (raw) content of the stream. 104 | 105 | 106 | * The rest of commands, of course 107 | 108 | > help 109 | 110 | 111 | 112 | ** Bugs ** 113 | 114 | Send me bugs and comments, please!! ;) You can do it via mail (jesparza AT eternal-todo.com) or through Github (https://github.com/jesparza/peepdf/issues). 115 | 116 | Thanks!! 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Linux Build Status](https://travis-ci.org/jbremer/peepdf.png)](https://travis-ci.org/jbremer/peepdf) 2 | [![Windows Build status](https://ci.appveyor.com/api/projects/status/bpa5ao97264oqe8f?svg=true)](https://ci.appveyor.com/project/jbremer/peepdf) 3 | [![Coverage Status](https://coveralls.io/repos/github/jbremer/peepdf/badge.svg)](https://coveralls.io/github/jbremer/peepdf) 4 | 5 | peepdf is a **Python tool to explore PDF files** in order to find out if the file can be harmful or not. The aim of this tool is to provide all the necessary components that 6 | a security researcher could need in a PDF analysis without using 3 or 4 tools to make 7 | all the tasks. With peepdf it's possible to see all the objects in the document showing 8 | the suspicious elements, supports all the most used filters and encodings, it can parse different versions of a file, object streams and encrypted files. With the installation 9 | of [PyV8](https://code.google.com/p/pyv8) and [Pylibemu](https://github.com/buffer/pylibemu) it provides **Javascript and shellcode analysis** wrappers too. Apart of this it's able to create new PDF files and to modify/obfuscate existent ones. 10 | 11 | The main functionalities of peepdf are the following: 12 | 13 | **Analysis:** 14 | 15 | * Decodings: hexadecimal, octal, name objects 16 | * More used filters 17 | * References in objects and where an object is referenced 18 | * Strings search (including streams) 19 | * Physical structure (offsets) 20 | * Logical tree structure 21 | * Metadata 22 | * Modifications between versions (changelog) 23 | * Compressed objects (object streams) 24 | * Analysis and modification of Javascript (PyV8): unescape, replace, join 25 | * Shellcode analysis (Libemu python wrapper, pylibemu) 26 | * Variables (set command) 27 | * Extraction of old versions of the document 28 | * Easy extraction of objects, Javascript code, shellcodes (>, >>, $>, $>>) 29 | * Checking hashes on **VirusTotal** 30 | 31 | 32 | **Creation/Modification:** 33 | 34 | * Basic PDF creation 35 | * Creation of PDF with Javascript executed wen the document is opened 36 | * Creation of object streams to compress objects 37 | * Embedded PDFs 38 | * Strings and names obfuscation 39 | * Malformed PDF output: without endobj, garbage in the header, bad header... 40 | * Filters modification 41 | * Objects modification 42 | 43 | 44 | **Execution modes:** 45 | 46 | * Simple command line execution 47 | * **Powerful interactive console** (colorized or not) 48 | * Batch mode 49 | 50 | 51 | **TODO:** 52 | 53 | * Embedded PDFs analysis 54 | * Improving automatic Javascript analysis 55 | * GUI 56 | 57 | 58 | **Related articles:** 59 | 60 | * [Spammed CVE-2013-2729 PDF exploit dropping ZeuS-P2P/Gameover](http://eternal-todo.com/blog/cve-2013-2729-exploit-zeusp2p-gameover) 61 | * [New peepdf v0.2 (Version Black Hat Vegas 2012)](http://eternal-todo.com/blog/peepdf-v0.2-black-hat-usa-arsenal-vegas) 62 | * [peepdf supports CCITTFaxDecode encoded streams](http://eternal-todo.com/blog/peepdf-ccittfaxdecode-support) 63 | * [Explanation of the changelog of peepdf for Black Hat Europe Arsenal 2012](http://eternal-todo.com/blog/peepdf-black-hat-arsenal-2012) 64 | * [How to extract streams and shellcodes from a PDF, the easy way](http://eternal-todo.com/blog/extract-streams-shellcode-peepdf) 65 | * [Static analysis of a CVE-2011-2462 PDF exploit](http://eternal-todo.com/blog/cve-2011-2462-exploit-analysis-peepdf) 66 | * [Analysis of a malicious PDF from a SEO Sploit Pack](http://eternal-todo.com/blog/seo-sploit-pack-pdf-analysis) 67 | * Analysing the [Honeynet Project challenge PDF file](http://www.honeynet.org/challenges/2010_6_malicious_pdf) with peepdf [Part 1](http://eternal-todo.com/blog/analysing-honeynet-pdf-challenge-peepdf-i) [Part 2](http://eternal-todo.com/blog/analysing-honeynet-pdf-challenge-peepdf-ii) 68 | * [Analyzing Suspicious PDF Files With Peepdf](http://blog.zeltser.com/post/6780160077/peepdf-malicious-pdf-analysis) 69 | 70 | 71 | **Included in:** 72 | 73 | * [REMnux](http://zeltser.com/remnux/) 74 | * [BackTrack 5](https://www.backtrack-linux.com/forensics-auditor/) 75 | * [Kali Linux](http://www.kali.org/) 76 | 77 | **You are free to contribute with feedback, bugs, patches, etc. Any help is welcome. Also, if you really enjoy using peepdf, you think it is worth it and you feel really generous today you can donate some bucks to the project ;) Thanks!** 78 | 79 | [![](https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=X5RRGLX5DTNKS) 80 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | Pending tasks: 2 | 3 | - Add detection of more exploits/vulns 4 | - Documentation of methods in PDFCore.py 5 | - Add the rest of supported stream filters (better testing of existent) 6 | - Automatic analysis of embedded PDF files 7 | - Improve the automatic Javascript analysis, getting code from other parts of the documents (getAnnots, etc) 8 | - GUI 9 | - ... -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - PYTHON: "C:/Python27" 4 | 5 | install: 6 | - "set PATH=%PYTHON%;%PYTHON%/Scripts;%PATH%" 7 | 8 | - "python.exe setup.py develop" 9 | - "pip.exe install pytest pytest-cov mock" 10 | 11 | build: false 12 | 13 | test_script: 14 | - "pytest.exe --cov=peepdf" 15 | -------------------------------------------------------------------------------- /peepdf.dtd: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /peepdf/JSAnalysis.py: -------------------------------------------------------------------------------- 1 | # 2 | # peepdf is a tool to analyse and modify PDF files 3 | # http://peepdf.eternal-todo.com 4 | # By Jose Miguel Esparza 5 | # 6 | # Copyright (C) 2011-2018 Jose Miguel Esparza 7 | # 8 | # This file is part of peepdf. 9 | # 10 | # peepdf is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # peepdf is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with peepdf. If not, see . 22 | # 23 | 24 | ''' 25 | This module contains some functions to analyse Javascript code inside the PDF file 26 | ''' 27 | 28 | import jsbeautifier 29 | import os 30 | import re 31 | import sys 32 | import traceback 33 | 34 | from peepdf.PDFUtils import unescapeHTMLEntities, escapeString 35 | 36 | try: 37 | import v8py 38 | 39 | class Global(v8py.Class): 40 | evalCode = '' 41 | 42 | def evalOverride(self, expression): 43 | self.evalCode += '\n\n// New evaluated code\n' + expression 44 | return 45 | 46 | JS_MODULE = True 47 | except: 48 | JS_MODULE = False 49 | 50 | class Global(object): 51 | pass 52 | 53 | 54 | errorsFile = os.path.expanduser("~/.peepdf-error.txt") 55 | newLine = os.linesep 56 | reJSscript = ']*?contentType\s*?=\s*?[\'"]application/x-javascript[\'"][^>]*?>(.*?)' 57 | preDefinedCode = 'var app = this;' 58 | 59 | # Regex that matches any character that's <32 && >127 and not a whitespace. 60 | bad_chars_re = "|".join(re.escape(chr(ch)) for ch in ( 61 | [ch for ch in range(32) if chr(ch) not in "\n\r\t\f"] + 62 | [ch for ch in range(128, 256)] 63 | )) 64 | 65 | def analyseJS(code, context=None, manualAnalysis=False): 66 | ''' 67 | Hooks the eval function and search for obfuscated elements in the Javascript code 68 | 69 | @param code: The Javascript code (string) 70 | @return: List with analysis information of the Javascript code: [JSCode,unescapedBytes,urlsFound,errors,context], where 71 | JSCode is a list with the several stages Javascript code, 72 | unescapedBytes is a list with the parameters of unescape functions, 73 | urlsFound is a list with the URLs found in the unescaped bytes, 74 | errors is a list of errors, 75 | context is the context of execution of the Javascript code. 76 | ''' 77 | errors = [] 78 | jsCode = [] 79 | unescapedBytes = [] 80 | urlsFound = [] 81 | 82 | try: 83 | code = unescapeHTMLEntities(code) 84 | scriptElements = re.findall(reJSscript, code, re.DOTALL | re.IGNORECASE) 85 | if scriptElements: 86 | code = '' 87 | for scriptElement in scriptElements: 88 | code += scriptElement + '\n\n' 89 | code = jsbeautifier.beautify(code) 90 | jsCode.append(code) 91 | 92 | if code is not None and JS_MODULE and not manualAnalysis: 93 | if context is None: 94 | if JS_MODULE: 95 | context = v8py.Context(Global()) 96 | 97 | context.enter() 98 | # Hooking the eval function 99 | context.eval('eval=evalOverride') 100 | # context.eval(preDefinedCode) 101 | while True: 102 | try: 103 | context.eval(code) 104 | evalCode = context.eval('evalCode') 105 | evalCode = jsbeautifier.beautify(evalCode) 106 | if evalCode != '' and evalCode != code: 107 | code = evalCode 108 | jsCode.append(code) 109 | else: 110 | break 111 | except: 112 | error = str(sys.exc_info()[1]) 113 | f = open(os.path.expanduser("~/.peepdf-jserror.log"), "ab") 114 | f.write(error + newLine) 115 | errors.append(error) 116 | break 117 | 118 | if code != '': 119 | escapedVars = re.findall('(\w*?)\s*?=\s*?(unescape\((.*?)\))', code, re.DOTALL) 120 | for var in escapedVars: 121 | bytes = var[2] 122 | if bytes.find('+') != -1 or bytes.find('%') == -1: 123 | varContent = getVarContent(code, bytes) 124 | if len(varContent) > 150: 125 | ret = unescape(varContent) 126 | if ret[0] != -1: 127 | bytes = ret[1] 128 | urls = re.findall('https?://.*$', bytes, re.DOTALL) 129 | if bytes not in unescapedBytes: 130 | unescapedBytes.append(bytes) 131 | for url in urls: 132 | if url not in urlsFound: 133 | urlsFound.append(url) 134 | else: 135 | bytes = bytes[1:-1] 136 | if len(bytes) > 150: 137 | ret = unescape(bytes) 138 | if ret[0] != -1: 139 | bytes = ret[1] 140 | urls = re.findall('https?://.*$', bytes, re.DOTALL) 141 | if bytes not in unescapedBytes: 142 | unescapedBytes.append(bytes) 143 | for url in urls: 144 | if url not in urlsFound: 145 | urlsFound.append(url) 146 | except: 147 | traceback.print_exc(file=open(errorsFile, 'a')) 148 | errors.append('Unexpected error in the JSAnalysis module!!') 149 | finally: 150 | for js in jsCode: 151 | if js is None or js == '': 152 | jsCode.remove(js) 153 | return [jsCode, unescapedBytes, urlsFound, errors, context] 154 | 155 | 156 | def getVarContent(jsCode, varContent): 157 | ''' 158 | Given the Javascript code and the content of a variable this method tries to obtain the real value of the variable, cleaning expressions like "a = eval; a(js_code);" 159 | 160 | @param jsCode: The Javascript code (string) 161 | @param varContent: The content of the variable (string) 162 | @return: A string with real value of the variable 163 | ''' 164 | clearBytes = '' 165 | varContent = varContent.replace('\n', '') 166 | varContent = varContent.replace('\r', '') 167 | varContent = varContent.replace('\t', '') 168 | varContent = varContent.replace(' ', '') 169 | parts = varContent.split('+') 170 | for part in parts: 171 | if re.match('["\'].*?["\']', part, re.DOTALL): 172 | clearBytes += part[1:-1] 173 | else: 174 | part = escapeString(part) 175 | varContent = re.findall(part + '\s*?=\s*?(.*?)[,;]', jsCode, re.DOTALL) 176 | if varContent: 177 | clearBytes += getVarContent(jsCode, varContent[0]) 178 | return clearBytes 179 | 180 | 181 | def isJavascript(content): 182 | ''' 183 | Given an string this method looks for typical Javscript strings and try to identify if the string contains Javascrit code or not. 184 | 185 | @param content: A string 186 | @return: A boolean, True if it seems to contain Javascript code or False in the other case 187 | ''' 188 | jsStrings = [ 189 | 'var ', ';', ')', '(', 'function ', '=', '{', '}', 'if ', 190 | 'else', 'return', 'while ', 'for ', ',', 'eval', 191 | ] 192 | keyStrings = [';', '(', ')'] 193 | stringsFound = [] 194 | limit = 15 195 | minDistinctStringsFound = 4 196 | minRatio = 10 197 | results = 0 198 | length = len(content) 199 | smallScriptLength = 100 200 | 201 | if content.startswith("/GS1 gs"): 202 | return False 203 | 204 | if re.findall(reJSscript, content, re.DOTALL | re.IGNORECASE): 205 | return True 206 | 207 | _, count = re.subn(bad_chars_re, "", content, len(content) // 10) 208 | if int(count) == len(content) // 10: 209 | return False 210 | 211 | for string in jsStrings: 212 | cont = content.count(string) 213 | results += cont 214 | if cont > 0 and string not in stringsFound: 215 | stringsFound.append(string) 216 | elif cont == 0 and string in keyStrings: 217 | return False 218 | 219 | numDistinctStringsFound = len(stringsFound) 220 | ratio = (results*100.0)/length 221 | if (results > limit and numDistinctStringsFound >= minDistinctStringsFound) or \ 222 | (length < smallScriptLength and ratio > minRatio): 223 | return True 224 | else: 225 | return False 226 | 227 | 228 | def searchObfuscatedFunctions(jsCode, function): 229 | ''' 230 | Search for obfuscated functions in the Javascript code 231 | 232 | @param jsCode: The Javascript code (string) 233 | @param function: The function name to look for (string) 234 | @return: List with obfuscated functions information [functionName,functionCall,containsReturns] 235 | ''' 236 | obfuscatedFunctionsInfo = [] 237 | if jsCode is not None: 238 | match = re.findall('\W('+function+'\s{0,5}?\((.*?)\)\s{0,5}?;)', jsCode, re.DOTALL) 239 | if match: 240 | for m in match: 241 | if re.findall('return', m[1], re.IGNORECASE): 242 | obfuscatedFunctionsInfo.append([function, m, True]) 243 | else: 244 | obfuscatedFunctionsInfo.append([function, m, False]) 245 | obfuscatedFunctions = re.findall('\s*?((\w*?)\s*?=\s*?'+function+')\s*?;', jsCode, re.DOTALL) 246 | for obfuscatedFunction in obfuscatedFunctions: 247 | obfuscatedElement = obfuscatedFunction[1] 248 | obfuscatedFunctionsInfo += searchObfuscatedFunctions(jsCode, obfuscatedElement) 249 | return obfuscatedFunctionsInfo 250 | 251 | 252 | def unescape(escapedBytes, str=True): 253 | ''' 254 | This method unescapes the given string 255 | 256 | @param escapedBytes: A string to unescape 257 | @return: A tuple (status,statusContent), where statusContent is an unescaped string in case status = 0 or an error in case status = -1 258 | ''' 259 | # TODO: modify to accept a list of escaped strings? 260 | unescapedBytes = '' 261 | if str: 262 | unicodePadding = '\x00' 263 | else: 264 | unicodePadding = '' 265 | try: 266 | if escapedBytes.lower().find('%u') != -1 or escapedBytes.lower().find('\\u') != -1 or escapedBytes.find('%') != -1: 267 | if escapedBytes.lower().find('\\u') != -1: 268 | splitBytes = escapedBytes.split('\\') 269 | else: 270 | splitBytes = escapedBytes.split('%') 271 | for i in range(len(splitBytes)): 272 | splitByte = splitBytes[i] 273 | if splitByte == '': 274 | continue 275 | if len(splitByte) > 4 and re.match('u[0-9a-f]{4}', splitByte[:5], re.IGNORECASE): 276 | unescapedBytes += chr(int(splitByte[3]+splitByte[4], 16))+chr(int(splitByte[1]+splitByte[2], 16)) 277 | if len(splitByte) > 5: 278 | for j in range(5, len(splitByte)): 279 | unescapedBytes += splitByte[j] + unicodePadding 280 | elif len(splitByte) > 1 and re.match('[0-9a-f]{2}', splitByte[:2], re.IGNORECASE): 281 | unescapedBytes += chr(int(splitByte[0]+splitByte[1], 16)) + unicodePadding 282 | if len(splitByte) > 2: 283 | for j in range(2, len(splitByte)): 284 | unescapedBytes += splitByte[j] + unicodePadding 285 | else: 286 | if i != 0: 287 | unescapedBytes += '%' + unicodePadding 288 | for j in range(len(splitByte)): 289 | unescapedBytes += splitByte[j] + unicodePadding 290 | else: 291 | unescapedBytes = escapedBytes 292 | except: 293 | return (-1, 'Error while unescaping the bytes') 294 | return (0, unescapedBytes) 295 | -------------------------------------------------------------------------------- /peepdf/PDFCrypto.py: -------------------------------------------------------------------------------- 1 | # 2 | # peepdf is a tool to analyse and modify PDF files 3 | # http://peepdf.eternal-todo.com 4 | # By Jose Miguel Esparza 5 | # 6 | # Copyright (C) 2011-2017 Jose Miguel Esparza 7 | # 8 | # This file is part of peepdf. 9 | # 10 | # peepdf is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # peepdf is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with peepdf. If not, see . 22 | # 23 | 24 | ''' 25 | Module to manage cryptographic operations with PDF files 26 | ''' 27 | 28 | import hashlib 29 | import itertools 30 | import struct 31 | import random 32 | import warnings 33 | import sys 34 | import peepdf.aes 35 | import six 36 | 37 | warnings.filterwarnings("ignore") 38 | 39 | paddingString = b'\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' 40 | 41 | 42 | def computeEncryptionKey(password, dictOwnerPass, dictUserPass, dictOE, dictUE, fileID, pElement, dictKeyLength=128, revision=3, encryptMetadata=False, passwordType=None): 43 | ''' 44 | Compute an encryption key to encrypt/decrypt the PDF file 45 | 46 | @param password: The password entered by the user 47 | @param dictOwnerPass: The owner password from the standard security handler dictionary 48 | @param dictUserPass: The user password from the standard security handler dictionary 49 | @param dictOE: The owner encrypted string from the standard security handler dictionary 50 | @param dictUE:The user encrypted string from the standard security handler dictionary 51 | @param fileID: The /ID element in the trailer dictionary of the PDF file 52 | @param pElement: The /P element of the Encryption dictionary 53 | @param dictKeyLength: The length of the key 54 | @param revision: The algorithm revision 55 | @param encryptMetadata: A boolean extracted from the standard security handler dictionary to specify if it's necessary to encrypt the document metadata or not 56 | @param passwordType: It specifies the given password type. It can be 'USER', 'OWNER' or None. 57 | @return: A tuple (status,statusContent), where statusContent is the encryption key in case status = 0 or an error message in case status = -1 58 | ''' 59 | try: 60 | if revision != 5: 61 | keyLength = dictKeyLength/8 62 | lenPass = len(password) 63 | if lenPass > 32: 64 | password = password[:32] 65 | elif lenPass < 32: 66 | password += paddingString[:32-lenPass] 67 | md5input = password + dictOwnerPass + struct.pack(b' 3 and not encryptMetadata: 69 | md5input += '\xFF'*4 70 | key = hashlib.md5(md5input).digest() 71 | if revision > 2: 72 | counter = 0 73 | while counter < 50: 74 | key = hashlib.md5(key[:keyLength]).digest() 75 | counter += 1 76 | key = key[:keyLength] 77 | elif revision == 2: 78 | key = key[:5] 79 | return (0, key) 80 | else: 81 | if passwordType == 'USER': 82 | password = password.encode('utf-8')[:127] 83 | kSalt = dictUserPass[40:48] 84 | intermediateKey = hashlib.sha256(password + kSalt).digest() 85 | ret = peepdf.aes.decryptData('\0'*16+dictUE, intermediateKey) 86 | elif passwordType == 'OWNER': 87 | password = password.encode('utf-8')[:127] 88 | kSalt = dictOwnerPass[40:48] 89 | intermediateKey = hashlib.sha256(password + kSalt + dictUserPass).digest() 90 | ret = peepdf.aes.decryptData('\0'*16+dictOE, intermediateKey) 91 | return ret 92 | except: 93 | return (-1, 'ComputeEncryptionKey error: %s %s' % (str(sys.exc_info()[0]), str(sys.exc_info()[1]))) 94 | 95 | 96 | def computeObjectKey(id, generationNum, encryptionKey, keyLengthBytes, algorithm='RC4'): 97 | ''' 98 | Compute the key necessary to encrypt each object, depending on the id and generation number. Only necessary with /V < 5. 99 | 100 | @param id: The object id 101 | @param generationNum: The generation number of the object 102 | @param encryptionKey: The encryption key 103 | @param keyLengthBytes: The length of the encryption key in bytes 104 | @param algorithm: The algorithm used in the encryption/decryption process 105 | @return A tuple (status,statusContent), where statusContent is the computed key in case status = 0 or an error message in case status = -1 106 | ''' 107 | try: 108 | key = encryptionKey + struct.pack(' 32: 137 | ownerPassString = ownerPassString[:32] 138 | elif lenPass < 32: 139 | ownerPassString += paddingString[:32-lenPass] 140 | rc4Key = hashlib.md5(ownerPassString).digest() 141 | if revision > 2: 142 | counter = 0 143 | while counter < 50: 144 | rc4Key = hashlib.md5(rc4Key).digest() 145 | counter += 1 146 | rc4Key = rc4Key[:keyLength] 147 | lenPass = len(userPassString) 148 | if lenPass > 32: 149 | userPassString = userPassString[:32] 150 | elif lenPass < 32: 151 | userPassString += paddingString[:32-lenPass] 152 | ownerPass = RC4(userPassString, rc4Key) 153 | if revision > 2: 154 | counter = 1 155 | while counter <= 19: 156 | newKey = '' 157 | for i in range(len(rc4Key)): 158 | newKey += chr(ord(rc4Key[i]) ^ counter) 159 | ownerPass = RC4(ownerPass, newKey) 160 | counter += 1 161 | return (0, ownerPass) 162 | except: 163 | return (-1, 'ComputeOwnerPass error: %s %s' % (str(sys.exc_info()[0]), str(sys.exc_info()[1]))) 164 | 165 | 166 | def computeUserPass(userPassString, dictO, fileID, pElement, keyLength=128, revision=3, encryptMetadata=False): 167 | ''' 168 | Compute the user password of the PDF file 169 | 170 | @param userPassString: The user password entered by the user 171 | @param ownerPass: The computed owner password 172 | @param fileID: The /ID element in the trailer dictionary of the PDF file 173 | @param pElement: The /P element of the /Encryption dictionary 174 | @param keyLength: The length of the key 175 | @param revision: The algorithm revision 176 | @param encryptMetadata: A boolean extracted from the standard security handler dictionary to specify if it's necessary to encrypt the document metadata or not 177 | @return: A tuple (status,statusContent), where statusContent is the computed password in case status = 0 or an error message in case status = -1 178 | ''' 179 | # TODO: revision 5 180 | userPass = '' 181 | dictU = '' 182 | dictOE = '' 183 | dictUE = '' 184 | ret = computeEncryptionKey(userPassString, dictO, dictU, dictOE, dictUE, fileID, pElement, keyLength, revision, encryptMetadata) 185 | if ret[0] != -1: 186 | rc4Key = ret[1] 187 | else: 188 | return ret 189 | try: 190 | if revision == 2: 191 | userPass = RC4(paddingString, rc4Key) 192 | elif revision > 2: 193 | counter = 1 194 | md5Input = paddingString + fileID 195 | hashResult = hashlib.md5(md5Input).digest() 196 | userPass = RC4(hashResult, rc4Key) 197 | while counter <= 19: 198 | newKey = '' 199 | for i in range(len(rc4Key)): 200 | newKey += chr(ord(rc4Key[i]) ^ counter) 201 | userPass = RC4(userPass, newKey) 202 | counter += 1 203 | counter = 0 204 | while counter < 16: 205 | userPass += chr(random.randint(32, 255)) 206 | counter += 1 207 | else: 208 | # This should not be possible or the PDF specification does not say anything about it 209 | return (-1, 'ComputeUserPass error: revision number is < 2 (%d)' % revision) 210 | return (0, userPass) 211 | except: 212 | return (-1, 'ComputeUserPass error: %s %s' % (str(sys.exc_info()[0]), str(sys.exc_info()[1]))) 213 | 214 | 215 | def isUserPass(password, computedUserPass, dictU, revision): 216 | ''' 217 | Checks if the given password is the User password of the file 218 | 219 | @param password: The given password or the empty password 220 | @param computedUserPass: The computed user password of the file 221 | @param dictU: The /U element of the /Encrypt dictionary 222 | @param revision: The number of revision of the standard security handler 223 | @return The boolean telling if the given password is the user password or not 224 | ''' 225 | if revision == 5: 226 | vSalt = dictU[32:40] 227 | inputHash = hashlib.sha256(password + vSalt).digest() 228 | if inputHash == dictU[:32]: 229 | return True 230 | else: 231 | return False 232 | elif revision == 3 or revision == 4: 233 | if computedUserPass[:16] == dictU[:16]: 234 | return True 235 | else: 236 | return False 237 | elif revision < 3: 238 | if computedUserPass == dictU: 239 | return True 240 | else: 241 | return False 242 | 243 | def isOwnerPass(password, dictO, dictU, computedUserPass, keyLength, revision): 244 | ''' 245 | Checks if the given password is the owner password of the file 246 | 247 | @param password: The given password or the empty password 248 | @param dictO: The /O element of the /Encrypt dictionary 249 | @param dictU: The /U element of the /Encrypt dictionary 250 | @param computedUserPass: The computed user password of the file 251 | @param keyLength: The length of the key 252 | @param revision: The algorithm revision 253 | @return The boolean telling if the given password is the owner password or not 254 | ''' 255 | if revision == 5: 256 | vSalt = dictO[32:40] 257 | inputHash = hashlib.sha256(password + vSalt + dictU).digest() 258 | if inputHash == dictO[:32]: 259 | return True 260 | else: 261 | return False 262 | else: 263 | keyLength = keyLength/8 264 | lenPass = len(password) 265 | if lenPass > 32: 266 | password = password[:32] 267 | elif lenPass < 32: 268 | password += paddingString[:32-lenPass] 269 | rc4Key = hashlib.md5(password).digest() 270 | if revision > 2: 271 | counter = 0 272 | while counter < 50: 273 | rc4Key = hashlib.md5(rc4Key).digest() 274 | counter += 1 275 | rc4Key = rc4Key[:keyLength] 276 | if revision == 2: 277 | userPass = RC4(dictO, rc4Key) 278 | elif revision > 2: 279 | counter = 19 280 | while counter >= 0: 281 | newKey = '' 282 | for i in range(len(rc4Key)): 283 | newKey += chr(ord(rc4Key[i]) ^ counter) 284 | dictO = RC4(dictO, newKey) 285 | counter -= 1 286 | userPass = dictO 287 | else: 288 | # Is it possible?? 289 | userPass = '' 290 | return isUserPass(userPass, computedUserPass, dictU, revision) 291 | 292 | 293 | def RC4(data, key): 294 | ''' 295 | RC4 implementation 296 | 297 | @param data: Bytes to be encrypyed/decrypted 298 | @param key: Key used for the algorithm 299 | @return: The encrypted/decrypted bytes 300 | ''' 301 | y = 0 302 | hash = {} 303 | box = {} 304 | ret = '' 305 | keyLength = len(key) 306 | dataLength = len(data) 307 | 308 | # Initialization 309 | for x in range(256): 310 | if six.PY3: 311 | hash[x] = ord(chr(key[x % keyLength])) 312 | else: 313 | hash[x] = ord(key[x % keyLength]) 314 | box[x] = x 315 | for x in range(256): 316 | y = (y + int(box[x]) + int(hash[x])) % 256 317 | tmp = box[x] 318 | box[x] = box[y] 319 | box[y] = tmp 320 | 321 | z = y = 0 322 | for x in range(0, dataLength): 323 | z = (z + 1) % 256 324 | y = (y + box[z]) % 256 325 | tmp = box[z] 326 | box[z] = box[y] 327 | box[y] = tmp 328 | k = box[((box[z] + box[y]) % 256)] 329 | if six.PY3: 330 | ret += chr(data[x] ^ k) 331 | else: 332 | ret += chr(ord(data[x]) ^ k) 333 | return ret 334 | 335 | 336 | ''' 337 | Author: Evan Fosmark (http://www.evanfosmark.com/2008/06/xor-encryption-with-python/) 338 | ''' 339 | def xor(bytes, key): 340 | ''' 341 | Simple XOR implementation 342 | 343 | @param bytes: Bytes to be xored 344 | @param key: Key used for the operation, it's cycled. 345 | @return: The xored bytes 346 | ''' 347 | key = itertools.cycle(key) 348 | return ''.join(chr(ord(x) ^ ord(y)) for (x, y) in zip(bytes, key)) 349 | -------------------------------------------------------------------------------- /peepdf/PDFFilters.py: -------------------------------------------------------------------------------- 1 | # 2 | # peepdf is a tool to analyse and modify PDF files 3 | # http://peepdf.eternal-todo.com 4 | # By Jose Miguel Esparza 5 | # 6 | # Copyright (C) 2011-2017 Jose Miguel Esparza 7 | # 8 | # This file is part of peepdf. 9 | # 10 | # peepdf is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # peepdf is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with peepdf. If not, see . 22 | # 23 | 24 | # Some code has been reused and modified from the original by Mathieu Fenniak: 25 | # Parameters management in Flate and LZW algorithms, asciiHexDecode and ascii85Decode 26 | # 27 | # Copyright (c) 2006, Mathieu Fenniak 28 | # All rights reserved. 29 | # 30 | # Redistribution and use in source and binary forms, with or without 31 | # modification, are permitted provided that the following conditions are 32 | # met: 33 | # 34 | # * Redistributions of source code must retain the above copyright notice, 35 | # this list of conditions and the following disclaimer. 36 | # * Redistributions in binary form must reproduce the above copyright notice, 37 | # this list of conditions and the following disclaimer in the documentation 38 | # and/or other materials provided with the distribution. 39 | # * The name of the author may not be used to endorse or promote products 40 | # derived from this software without specific prior written permission. 41 | # 42 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 43 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 44 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 45 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 46 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 47 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 48 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 49 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 50 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 51 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 52 | # POSSIBILITY OF SUCH DAMAGE. 53 | 54 | 55 | ''' 56 | Module to manage encoding/decoding in PDF files 57 | ''' 58 | 59 | import zlib 60 | import struct 61 | import six 62 | 63 | import peepdf.lzw 64 | 65 | from peepdf.PDFUtils import getNumsFromBytes, getBytesFromBits, getBitsFromNum 66 | from peepdf.ccitt import CCITTFax 67 | 68 | 69 | def decodeStream(stream, filter, parameters={}): 70 | ''' 71 | Decode the given stream 72 | 73 | @param stream: Stream to be decoded (string) 74 | @param filter: Filter to apply to decode the stream 75 | @param parameters: List of PDFObjects containing the parameters for the filter 76 | @return: A tuple (status,statusContent), where statusContent is the decoded stream in case status = 0 or an error in case status = -1 77 | ''' 78 | if filter == '/ASCIIHexDecode' or filter == '/AHx': 79 | ret = asciiHexDecode(stream) 80 | elif filter == '/ASCII85Decode' or filter == '/A85': 81 | ret = ascii85Decode(stream) 82 | elif filter == '/LZWDecode' or filter == '/LZW': 83 | ret = lzwDecode(stream, parameters) 84 | elif filter == '/FlateDecode' or filter == '/Fl': 85 | ret = flateDecode(stream, parameters) 86 | elif filter == '/RunLengthDecode' or filter == '/RL': 87 | ret = runLengthDecode(stream) 88 | elif filter == '/CCITTFaxDecode' or filter == '/CCF': 89 | ret = ccittFaxDecode(stream, parameters) 90 | elif filter == '/JBIG2Decode': 91 | ret = jbig2Decode(stream, parameters) 92 | elif filter == '/DCTDecode' or filter == '/DCT': 93 | ret = dctDecode(stream, parameters) 94 | elif filter == '/JPXDecode': 95 | ret = jpxDecode(stream) 96 | elif filter == '/Crypt': 97 | ret = crypt(stream, parameters) 98 | else: 99 | ret = (-1, 'Unknown filter "%s"' % filter) 100 | return ret 101 | 102 | 103 | def encodeStream(stream, filter, parameters={}): 104 | ''' 105 | Encode the given stream 106 | 107 | @param stream: Stream to be decoded (string) 108 | @param filter: Filter to apply to decode the stream 109 | @param parameters: List of PDFObjects containing the parameters for the filter 110 | @return: A tuple (status,statusContent), where statusContent is the encoded stream in case status = 0 or an error in case status = -1 111 | ''' 112 | if filter == '/ASCIIHexDecode': 113 | ret = asciiHexEncode(stream) 114 | elif filter == '/ASCII85Decode': 115 | ret = ascii85Encode(stream) 116 | elif filter == '/LZWDecode': 117 | ret = lzwEncode(stream, parameters) 118 | elif filter == '/FlateDecode': 119 | ret = flateEncode(stream, parameters) 120 | elif filter == '/RunLengthDecode': 121 | ret = runLengthEncode(stream) 122 | elif filter == '/CCITTFaxDecode': 123 | ret = ccittFaxEncode(stream, parameters) 124 | elif filter == '/JBIG2Decode': 125 | ret = jbig2Encode(stream, parameters) 126 | elif filter == '/DCTDecode': 127 | ret = dctEncode(stream, parameters) 128 | elif filter == '/JPXDecode': 129 | ret = jpxEncode(stream) 130 | elif filter == '/Crypt': 131 | ret = crypt(stream, parameters) 132 | else: 133 | ret = (-1, 'Unknown filter "%s"' % filter) 134 | return ret 135 | 136 | 137 | ''' 138 | The ascii85Decode code is part of pdfminer (http://pypi.python.org/pypi/pdfminer/) 139 | 140 | Copyright (c) 2004-2010 Yusuke Shinyama 141 | 142 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 143 | 144 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 145 | 146 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 147 | 148 | """ 149 | In ASCII85 encoding, every four bytes are encoded with five ASCII 150 | letters, using 85 different types of characters (as 256**4 < 85**5). 151 | When the length of the original bytes is not a multiple of 4, a special 152 | rule is used for round up. 153 | 154 | The Adobe's ASCII85 implementation is slightly different from 155 | its original in handling the last characters. 156 | 157 | The sample string is taken from: 158 | http://en.wikipedia.org/w/index.php?title=Ascii85 159 | 160 | >>> ascii85decode('9jqo^BlbD-BleB1DJ+*+F(f,q') 161 | 'Man is distinguished' 162 | >>> ascii85decode('E,9)oF*2M7/c~>') 163 | 'pleasure.' 164 | """ 165 | 166 | ''' 167 | 168 | 169 | def ascii85Decode(stream): 170 | ''' 171 | Method to decode streams using ASCII85 172 | 173 | @param stream: A PDF stream 174 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 175 | ''' 176 | n = b = 0 177 | decodedStream = '' 178 | try: 179 | for c in stream: 180 | if '!' <= c and c <= 'u': 181 | n += 1 182 | b = b * 85 + (ord(c) - 33) 183 | if n == 5: 184 | decodedStream += struct.pack('>L', b) 185 | n = b = 0 186 | elif c == 'z': 187 | assert n == 0 188 | decodedStream += '\0\0\0\0' 189 | elif c == '~': 190 | if n: 191 | for _ in range(5 - n): 192 | b = b * 85 + 84 193 | decodedStream += struct.pack('>L', b)[:n - 1] 194 | break 195 | except: 196 | return (-1, 'Unspecified error') 197 | return (0, decodedStream) 198 | 199 | 200 | def ascii85Encode(stream): 201 | ''' 202 | Method to encode streams using ASCII85 (NOT SUPPORTED YET) 203 | 204 | @param stream: A PDF stream 205 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 206 | ''' 207 | return (-1, 'Ascii85Encode not supported yet') 208 | 209 | 210 | def asciiHexDecode(stream): 211 | ''' 212 | Method to decode streams using hexadecimal encoding 213 | 214 | @param stream: A PDF stream 215 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 216 | ''' 217 | eod = '>' 218 | decodedStream = '' 219 | char = '' 220 | index = 0 221 | while index < len(stream): 222 | c = stream[index] 223 | if c == eod: 224 | if len(decodedStream) % 2 != 0: 225 | char += '0' 226 | try: 227 | decodedStream += chr(int(char, base=16)) 228 | except: 229 | return (-1, 'Error in hexadecimal conversion') 230 | break 231 | elif c.isspace(): 232 | index += 1 233 | continue 234 | char += c 235 | if len(char) == 2: 236 | try: 237 | decodedStream += chr(int(char, base=16)) 238 | except: 239 | return (-1, 'Error in hexadecimal conversion') 240 | char = '' 241 | index += 1 242 | return (0, decodedStream) 243 | 244 | 245 | def asciiHexEncode(stream): 246 | ''' 247 | Method to encode streams using hexadecimal encoding 248 | 249 | @param stream: A PDF stream 250 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 251 | ''' 252 | try: 253 | encodedStream = stream.encode('hex') 254 | except: 255 | return (-1, 'Error in hexadecimal conversion') 256 | return (0, encodedStream) 257 | 258 | 259 | def flateDecode(stream, parameters): 260 | ''' 261 | Method to decode streams using the Flate algorithm 262 | 263 | @param stream: A PDF stream 264 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 265 | ''' 266 | decodedStream = '' 267 | try: 268 | if six.PY3: 269 | decodedStream = zlib.decompress(stream.encode('latin-1')) 270 | decodedStream = decodedStream.decode('latin-1') 271 | 272 | else: 273 | decodedStream = zlib.decompress(stream) 274 | except Exception as a: 275 | return (-1, 'Error decompressing string') 276 | 277 | if parameters is None or parameters == {}: 278 | return (0, decodedStream) 279 | else: 280 | if "/Predictor" in parameters: 281 | predictor = parameters['/Predictor'].getRawValue() 282 | else: 283 | predictor = 1 284 | # Columns = number of samples per row 285 | if "/Columns" in parameters: 286 | columns = parameters['/Columns'].getRawValue() 287 | else: 288 | columns = 1 289 | # Colors = number of components per sample 290 | if "/Colors" in parameters: 291 | colors = parameters['/Colors'].getRawValue() 292 | if colors < 1: 293 | colors = 1 294 | else: 295 | colors = 1 296 | # BitsPerComponent: number of bits per color component 297 | if "/BitsPerComponent" in parameters: 298 | bits = parameters['/BitsPerComponent'].getRawValue() 299 | if bits not in [1, 2, 4, 8, 16]: 300 | bits = 8 301 | else: 302 | bits = 8 303 | if predictor is not None and predictor != 1: 304 | ret = post_prediction(decodedStream, predictor, columns, colors, bits) 305 | return ret 306 | else: 307 | return (0, decodedStream) 308 | 309 | 310 | def flateEncode(stream, parameters): 311 | ''' 312 | Method to encode streams using the Flate algorithm 313 | 314 | @param stream: A PDF stream 315 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 316 | ''' 317 | if parameters is None or parameters == {}: 318 | try: 319 | return (0, zlib.compress(stream)) 320 | except: 321 | return (-1, 'Error compressing string') 322 | else: 323 | if "/Predicator" in parameters: 324 | predictor = parameters['/Predictor'].getRawValue() 325 | else: 326 | predictor = 1 327 | # Columns = number of samples per row 328 | if "/Columns" in parameters: 329 | columns = parameters['/Columns'].getRawValue() 330 | else: 331 | columns = 1 332 | # Colors = number of components per sample 333 | if "/Colors" in parameters: 334 | colors = parameters['/Colors'].getRawValue() 335 | if colors < 1: 336 | colors = 1 337 | else: 338 | colors = 1 339 | # BitsPerComponent: number of bits per color component 340 | if "/BitsPerComponent" in parameters: 341 | bits = parameters['/BitsPerComponent'].getRawValue() 342 | if bits not in [1, 2, 4, 8, 16]: 343 | bits = 8 344 | else: 345 | bits = 8 346 | if predictor is not None and predictor != 1: 347 | ret = pre_prediction(stream, predictor, columns, colors, bits) 348 | if ret[0] == -1: 349 | return ret 350 | output = ret[1] 351 | else: 352 | output = stream 353 | try: 354 | return (0, zlib.compress(output)) 355 | except: 356 | return (-1, 'Error compressing string') 357 | 358 | 359 | def lzwDecode(stream, parameters): 360 | ''' 361 | Method to decode streams using the LZW algorithm 362 | 363 | @param stream: A PDF stream 364 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 365 | ''' 366 | decodedStream = '' 367 | try: 368 | decodedStream = peepdf.lzw.lzwdecode(stream) 369 | except: 370 | return (-1, 'Error decompressing string') 371 | 372 | if parameters is None or parameters == {}: 373 | return (0, decodedStream) 374 | else: 375 | if "/Predictor" in parameters: 376 | predictor = parameters['/Predictor'].getRawValue() 377 | else: 378 | predictor = 1 379 | # Columns = number of samples per row 380 | if "/Columns" in parameters: 381 | columns = parameters['/Columns'].getRawValue() 382 | else: 383 | columns = 1 384 | # Colors = number of components per sample 385 | if "/Colors" in parameters: 386 | colors = parameters['/Colors'].getRawValue() 387 | if colors < 1: 388 | colors = 1 389 | else: 390 | colors = 1 391 | # BitsPerComponent: number of bits per color component 392 | if "/BitsPerComponent" in parameters: 393 | bits = parameters['/BitsPerComponent'].getRawValue() 394 | if bits not in [1, 2, 4, 8, 16]: 395 | bits = 8 396 | else: 397 | bits = 8 398 | if predictor is not None and predictor != 1: 399 | ret = post_prediction(decodedStream, predictor, columns, colors, bits) 400 | return ret 401 | else: 402 | return (0, decodedStream) 403 | 404 | 405 | def lzwEncode(stream, parameters): 406 | ''' 407 | Method to encode streams using the LZW algorithm 408 | 409 | @param stream: A PDF stream 410 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 411 | ''' 412 | encodedStream = '' 413 | if parameters is None or parameters == {}: 414 | try: 415 | generator = peepdf.lzw.compress(stream) 416 | for c in generator: 417 | encodedStream += c 418 | return (0, encodedStream) 419 | except: 420 | return (-1, 'Error compressing string') 421 | else: 422 | if "/Predictor" in parameters: 423 | predictor = parameters['/Predictor'].getRawValue() 424 | else: 425 | predictor = 1 426 | # Columns = number of samples per row 427 | if "/Columns" in parameters: 428 | columns = parameters['/Columns'].getRawValue() 429 | else: 430 | columns = 1 431 | # Colors = number of components per sample 432 | if "/Colors" in parameters: 433 | colors = parameters['/Colors'].getRawValue() 434 | if colors < 1: 435 | colors = 1 436 | else: 437 | colors = 1 438 | # BitsPerComponent: number of bits per color component 439 | if "/BitsPerComponent" in parameters: 440 | bits = parameters['/BitsPerComponent'].getRawValue() 441 | if bits not in [1, 2, 4, 8, 16]: 442 | bits = 8 443 | else: 444 | bits = 8 445 | if predictor is not None and predictor != 1: 446 | ret = pre_prediction(stream, predictor, columns, colors, bits) 447 | if ret[0] == -1: 448 | return ret 449 | output = ret[1] 450 | else: 451 | output = stream 452 | try: 453 | generator = peepdf.lzw.compress(output) 454 | for c in generator: 455 | encodedStream += c 456 | return (0, encodedStream) 457 | except: 458 | return (-1, 'Error decompressing string') 459 | 460 | 461 | def pre_prediction(stream, predictor, columns, colors, bits): 462 | ''' 463 | Predictor function to make the stream more predictable and improve compression (PDF Specification) 464 | 465 | @param stream: The stream to be modified 466 | @param predictor: The type of predictor to apply 467 | @param columns: Number of samples per row 468 | @param colors: Number of colors per sample 469 | @param bits: Number of bits per color 470 | @return: A tuple (status,statusContent), where statusContent is the modified stream in case status = 0 or an error in case status = -1 471 | ''' 472 | 473 | output = '' 474 | # TODO: TIFF and more PNG predictions 475 | 476 | # PNG prediction 477 | if predictor >= 10 and predictor <= 15: 478 | # PNG prediction can vary from row to row 479 | for row in range(len(stream) / columns): 480 | rowdata = [ord(x) for x in stream[(row * columns):((row + 1) * columns)]] 481 | filterByte = predictor - 10 482 | rowdata = [filterByte] + rowdata 483 | if filterByte == 0: 484 | pass 485 | elif filterByte == 1: 486 | for i in range(len(rowdata) - 1, 1, -1): 487 | if rowdata[i] < rowdata[i - 1]: 488 | rowdata[i] = rowdata[i] + 256 - rowdata[i - 1] 489 | else: 490 | rowdata[i] = rowdata[i] - rowdata[i - 1] 491 | elif filterByte == 2: 492 | (-1, 'Unsupported predictor') 493 | else: 494 | return (-1, 'Unsupported predictor') 495 | output += (''.join([chr(x) for x in rowdata])) 496 | return (0, output) 497 | else: 498 | return (-1, 'Unsupported predictor') 499 | 500 | 501 | def post_prediction(decodedStream, predictor, columns, colors, bits): 502 | ''' 503 | Predictor function to obtain the real stream, removing the prediction (PDF Specification) 504 | 505 | @param decodedStream: The decoded stream to be modified 506 | @param predictor: The type of predictor to apply 507 | @param columns: Number of samples per row 508 | @param colors: Number of colors per sample 509 | @param bits: Number of bits per color 510 | @return: A tuple (status,statusContent), where statusContent is the modified decoded stream in case status = 0 or an error in case status = -1 511 | ''' 512 | 513 | output = '' 514 | bytesPerRow = (colors * bits * columns + 7) / 8 515 | 516 | # TIFF - 2 517 | # http://www.gnupdf.org/PNG_and_TIFF_Predictors_Filter#TIFF 518 | if predictor == 2: 519 | numRows = len(decodedStream) / bytesPerRow 520 | bitmask = 2 ** bits - 1 521 | outputBitsStream = '' 522 | for rowIndex in range(numRows): 523 | row = decodedStream[rowIndex * bytesPerRow:rowIndex * bytesPerRow + bytesPerRow] 524 | ret, colorNums = getNumsFromBytes(row, bits) 525 | if ret == -1: 526 | return (ret, colorNums) 527 | pixel = [0 for x in range(colors)] 528 | for i in range(columns): 529 | for j in range(colors): 530 | diffPixel = colorNums[i + j] 531 | pixel[j] = (pixel[j] + diffPixel) & bitmask 532 | ret, outputBits = getBitsFromNum(pixel[j], bits) 533 | if ret == -1: 534 | return (ret, outputBits) 535 | outputBitsStream += outputBits 536 | output = getBytesFromBits(outputBitsStream) 537 | return output 538 | # PNG prediction 539 | # http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html 540 | # http://www.gnupdf.org/PNG_and_TIFF_Predictors_Filter#TIFF 541 | elif predictor >= 10 and predictor <= 15: 542 | bytesPerRow += 1 543 | numRows = (len(decodedStream) + bytesPerRow - 1) / bytesPerRow 544 | numSamplesPerRow = columns + 1 545 | bytesPerSample = (colors * bits + 7) / 8 546 | upRowdata = (0,) * numSamplesPerRow 547 | for row in range(numRows): 548 | rowdata = [ord(x) for x in decodedStream[(row * bytesPerRow):((row + 1) * bytesPerRow)]] 549 | # PNG prediction can vary from row to row 550 | filterByte = rowdata[0] 551 | rowdata[0] = 0 552 | 553 | if filterByte == 0: 554 | # None 555 | pass 556 | elif filterByte == 1: 557 | # Sub - 11 558 | for i in range(1, numSamplesPerRow): 559 | if i < bytesPerSample: 560 | prevSample = 0 561 | else: 562 | prevSample = rowdata[i - bytesPerSample] 563 | rowdata[i] = (rowdata[i] + prevSample) % 256 564 | elif filterByte == 2: 565 | # Up - 12 566 | for i in range(1, numSamplesPerRow): 567 | upSample = upRowdata[i] 568 | rowdata[i] = (rowdata[i] + upSample) % 256 569 | elif filterByte == 3: 570 | # Average - 13 571 | for i in range(1, numSamplesPerRow): 572 | upSample = upRowdata[i] 573 | if i < bytesPerSample: 574 | prevSample = 0 575 | else: 576 | prevSample = rowdata[i - bytesPerSample] 577 | rowdata[i] = (rowdata[i] + ((prevSample + upSample) / 2)) % 256 578 | elif filterByte == 4: 579 | # Paeth - 14 580 | for i in range(1, numSamplesPerRow): 581 | upSample = upRowdata[i] 582 | if i < bytesPerSample: 583 | prevSample = 0 584 | upPrevSample = 0 585 | else: 586 | prevSample = rowdata[i - bytesPerSample] 587 | upPrevSample = upRowdata[i - bytesPerSample] 588 | p = prevSample + upSample - upPrevSample 589 | pa = abs(p - prevSample) 590 | pb = abs(p - upSample) 591 | pc = abs(p - upPrevSample) 592 | if pa <= pb and pa <= pc: 593 | nearest = prevSample 594 | elif pb <= pc: 595 | nearest = upSample 596 | else: 597 | nearest = upPrevSample 598 | rowdata[i] = (rowdata[i] + nearest) % 256 599 | else: 600 | # Optimum - 15 601 | # return (-1,'Unsupported predictor') 602 | pass 603 | upRowdata = rowdata 604 | output += (''.join([chr(x) for x in rowdata[1:]])) 605 | return (0, output) 606 | else: 607 | return (-1, 'Wrong value for predictor') 608 | 609 | 610 | def runLengthDecode(stream): 611 | ''' 612 | Method to decode streams using the Run-Length algorithm 613 | 614 | @param stream: A PDF stream 615 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 616 | ''' 617 | decodedStream = '' 618 | index = 0 619 | try: 620 | while index < len(stream): 621 | length = ord(stream[index]) 622 | if length >= 0 and length < 128: 623 | decodedStream += stream[index + 1:index + length + 2] 624 | index += length + 2 625 | elif length > 128 and length < 256: 626 | decodedStream += stream[index + 1] * (257 - length) 627 | index += 2 628 | else: 629 | break 630 | except: 631 | return (-1, 'Error decoding string') 632 | return (0, decodedStream) 633 | 634 | 635 | def runLengthEncode(stream): 636 | ''' 637 | Method to encode streams using the Run-Length algorithm (NOT IMPLEMENTED YET) 638 | 639 | @param stream: A PDF stream 640 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 641 | ''' 642 | return (-1, 'RunLengthEncode not supported yet') 643 | 644 | 645 | def ccittFaxDecode(stream, parameters): 646 | ''' 647 | Method to decode streams using the CCITT facsimile standard 648 | 649 | @param stream: A PDF stream 650 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 651 | ''' 652 | decodedStream = '' 653 | 654 | if parameters is None or parameters == {}: 655 | try: 656 | decodedStream = CCITTFax().decode(stream) 657 | return (0, decodedStream) 658 | except: 659 | return (-1, 'Error decompressing string') 660 | else: 661 | # K = A code identifying the encoding scheme used 662 | if "/K" in parameters: 663 | k = parameters['/K'].getRawValue() 664 | if type(k) != int: 665 | k = 0 666 | else: 667 | if k != 0: 668 | # Only supported "Group 3, 1-D" encoding (Pure one-dimensional encoding) 669 | return (-1, 'CCITT encoding scheme not supported') 670 | else: 671 | k = 0 672 | # EndOfLine = A flag indicating whether end-of-line bit patterns are required to be present in the encoding. 673 | if "/EndOfLine" in parameters: 674 | eol = parameters['/EndOfLine'].getRawValue() 675 | if eol == 'true': 676 | eol = True 677 | else: 678 | eol = False 679 | else: 680 | eol = False 681 | # EncodedByteAlign = A flag indicating whether the filter expects extra 0 bits before each encoded line so that the line begins on a byte boundary 682 | if "/EncodeByteAlign" in parameters: 683 | byteAlign = parameters['/EncodedByteAlign'].getRawValue() 684 | if byteAlign == 'true': 685 | byteAlign = True 686 | else: 687 | byteAlign = False 688 | else: 689 | byteAlign = False 690 | # Columns = The width of the image in pixels. 691 | if "/Columns" in parameters: 692 | columns = parameters['/Columns'].getRawValue() 693 | if type(columns) != int: 694 | columns = 1728 695 | else: 696 | columns = 1728 697 | # Rows = The height of the image in scan lines. 698 | if "/Rows" in parameters: 699 | rows = parameters['/Rows'].getRawValue() 700 | if type(rows) != int: 701 | rows = 0 702 | else: 703 | rows = 0 704 | # EndOfBlock = number of samples per row 705 | if "/EndOfBlock" in parameters: 706 | eob = parameters['/EndOfBlock'].getRawValue() 707 | if eob == 'false': 708 | eob = False 709 | else: 710 | eob = True 711 | else: 712 | eob = True 713 | # BlackIs1 = A flag indicating whether 1 bits are to be interpreted as black pixels and 0 bits as white pixels 714 | if "/BlackIs1" in parameters: 715 | blackIs1 = parameters['/BlackIs1'].getRawValue() 716 | if blackIs1 == 'true': 717 | blackIs1 = True 718 | else: 719 | blackIs1 = False 720 | else: 721 | blackIs1 = False 722 | # DamagedRowsBeforeError = The number of damaged rows of data to be tolerated before an error occurs 723 | if "/DamagedRowsBeforeError" in parameters: 724 | damagedRowsBeforeError = parameters['/DamagedRowsBeforeError'].getRawValue() 725 | else: 726 | damagedRowsBeforeError = 0 727 | try: 728 | decodedStream = CCITTFax().decode(stream, k, eol, byteAlign, columns, rows, eob, blackIs1, 729 | damagedRowsBeforeError) 730 | return (0, decodedStream) 731 | except: 732 | return (-1, 'Error decompressing string') 733 | 734 | 735 | def ccittFaxEncode(stream, parameters): 736 | ''' 737 | Method to encode streams using the CCITT facsimile standard (NOT IMPLEMENTED YET) 738 | 739 | @param stream: A PDF stream 740 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 741 | ''' 742 | return (-1, 'CcittFaxEncode not supported yet') 743 | 744 | 745 | def crypt(stream, parameters): 746 | ''' 747 | Method to encrypt streams using a PDF security handler (NOT IMPLEMENTED YET) 748 | 749 | @param stream: A PDF stream 750 | @return: A tuple (status,statusContent), where statusContent is the encrypted PDF stream in case status = 0 or an error in case status = -1 751 | ''' 752 | if parameters is None or parameters == {}: 753 | return (0, stream) 754 | else: 755 | if "/Name" not in parameters or parameters['/Name'] is None: 756 | return (0, stream) 757 | else: 758 | cryptFilterName = parameters['/Name'].getValue() 759 | if cryptFilterName == 'Identity': 760 | return (0, stream) 761 | else: 762 | # TODO: algorithm is cryptFilterName, specified in the /CF dictionary 763 | return (-1, 'Crypt not supported yet') 764 | 765 | 766 | def decrypt(stream, parameters): 767 | ''' 768 | Method to decrypt streams using a PDF security handler (NOT IMPLEMENTED YET) 769 | 770 | @param stream: A PDF stream 771 | @return: A tuple (status,statusContent), where statusContent is the decrypted PDF stream in case status = 0 or an error in case status = -1 772 | ''' 773 | if parameters is None or parameters == {}: 774 | return (0, stream) 775 | else: 776 | if "/Name" not in parameters or parameters['/Name'] is None: 777 | return (0, stream) 778 | else: 779 | cryptFilterName = parameters['/Name'].getValue() 780 | if cryptFilterName == 'Identity': 781 | return (0, stream) 782 | else: 783 | # TODO: algorithm is cryptFilterName, specified in the /CF dictionary 784 | return (-1, 'Decrypt not supported yet') 785 | 786 | 787 | def dctDecode(stream, parameters): 788 | ''' 789 | Method to decode streams using a DCT technique based on the JPEG standard (NOT IMPLEMENTED YET) 790 | 791 | @param stream: A PDF stream 792 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 793 | ''' 794 | decodedStream = '' 795 | try: 796 | from PIL import Image 797 | import io 798 | except: 799 | return (-1, 'Python Imaging Library (PIL) not installed') 800 | # Quick implementation, assuming the library can detect the parameters 801 | try: 802 | im = Image.open(io.StringIO(stream)) 803 | decodedStream = im.tostring() 804 | return (0, decodedStream) 805 | except: 806 | return (-1, 'Error decompresing image data') 807 | 808 | 809 | def dctEncode(stream, parameters): 810 | ''' 811 | Method to encode streams using a DCT technique based on the JPEG standard (NOT IMPLEMENTED YET) 812 | 813 | @param stream: A PDF stream 814 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 815 | ''' 816 | return (-1, 'DctEncode not supported yet') 817 | 818 | 819 | def jbig2Decode(stream, parameters): 820 | ''' 821 | Method to decode streams using the JBIG2 standard (NOT IMPLEMENTED YET) 822 | 823 | @param stream: A PDF stream 824 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 825 | ''' 826 | return (-1, 'Jbig2Decode not supported yet') 827 | 828 | 829 | def jbig2Encode(stream, parameters): 830 | ''' 831 | Method to encode streams using the JBIG2 standard (NOT IMPLEMENTED YET) 832 | 833 | @param stream: A PDF stream 834 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 835 | ''' 836 | return (-1, 'Jbig2Encode not supported yet') 837 | 838 | 839 | def jpxDecode(stream): 840 | ''' 841 | Method to decode streams using the JPEG2000 standard (NOT IMPLEMENTED YET) 842 | 843 | @param stream: A PDF stream 844 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 845 | ''' 846 | return (-1, 'JpxDecode not supported yet') 847 | 848 | 849 | def jpxEncode(stream): 850 | ''' 851 | Method to encode streams using the JPEG2000 standard (NOT IMPLEMENTED YET) 852 | 853 | @param stream: A PDF stream 854 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 855 | ''' 856 | return (-1, 'JpxEncode not supported yet') 857 | -------------------------------------------------------------------------------- /peepdf/PDFUtils.py: -------------------------------------------------------------------------------- 1 | # 2 | # peepdf is a tool to analyse and modify PDF files 3 | # http://peepdf.eternal-todo.com 4 | # By Jose Miguel Esparza 5 | # 6 | # Copyright (C) 2011-2017 Jose Miguel Esparza 7 | # 8 | # This file is part of peepdf. 9 | # 10 | # peepdf is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # peepdf is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with peepdf. If not, see . 22 | # 23 | 24 | ''' 25 | Module with some misc functions 26 | ''' 27 | 28 | import os 29 | import re 30 | import html.entities 31 | 32 | def clearScreen(): 33 | ''' 34 | Simple method to clear the screen depending on the OS 35 | ''' 36 | if os.name == 'nt': 37 | os.system('cls') 38 | elif os.name == 'posix': 39 | os.system('reset') 40 | elif os.name == 'mac': 41 | os.system('clear') 42 | 43 | def countArrayElements(array): 44 | ''' 45 | Simple method to count the repetitions of elements in an array 46 | 47 | @param array: An array of elements 48 | @return: A tuple (elements,counters), where elements is a list with the distinct elements and counters is the list with the number of times they appear in the array 49 | ''' 50 | elements = [] 51 | counters = [] 52 | for element in array: 53 | if element in elements: 54 | indx = elements.index(element) 55 | counters[indx] += 1 56 | else: 57 | elements.append(element) 58 | counters.append(1) 59 | return elements, counters 60 | 61 | def countNonPrintableChars(string): 62 | ''' 63 | Simple method to return the non printable characters found in an string 64 | 65 | @param string: A string 66 | @return: Number of non printable characters in the string 67 | ''' 68 | counter = 0 69 | for i in range(len(string)): 70 | if ord(string[i]) <= 31 or ord(string[i]) > 127: 71 | counter += 1 72 | return counter 73 | 74 | def decodeName(name): 75 | ''' 76 | Decode the given PDF name 77 | 78 | @param name: A PDFName string to decode 79 | @return: A tuple (status,statusContent), where statusContent is the decoded PDF name in case status = 0 or an error in case status = -1 80 | ''' 81 | decodedName = name 82 | hexNumbers = re.findall('#([0-9a-f]{2})', name, re.DOTALL | re.IGNORECASE) 83 | for hexNumber in hexNumbers: 84 | try: 85 | decodedName = decodedName.replace('#'+hexNumber, chr(int(hexNumber, 16))) 86 | except: 87 | return (-1, 'Error decoding name') 88 | return (0, decodedName) 89 | 90 | def decodeString(string): 91 | ''' 92 | Decode the given PDF string 93 | 94 | @param string: A PDFString to decode 95 | @return A tuple (status,statusContent), where statusContent is the decoded PDF string in case status = 0 or an error in case status = -1 96 | ''' 97 | decodedString = string 98 | octalNumbers = re.findall('\\\\([0-7]{1-3})', decodedString, re.DOTALL) 99 | for octal in octalNumbers: 100 | try: 101 | decodedString = decodedString.replace('\\\\'+octal, chr(int(octal, 8))) 102 | except: 103 | return (-1, 'Error decoding string') 104 | return (0, decodedString) 105 | 106 | def encodeName(name): 107 | ''' 108 | Encode the given PDF name 109 | 110 | @param name: A PDFName string to encode 111 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF name in case status = 0 or an error in case status = -1 112 | ''' 113 | encodedName = '' 114 | if name[0] == '/': 115 | name = name[1:] 116 | for char in name: 117 | if char == '\0': 118 | encodedName += char 119 | else: 120 | try: 121 | hex = '%x' % ord(char) 122 | encodedName += '#'+hex 123 | except: 124 | return (-1, 'Error encoding name') 125 | return (0, '/'+encodedName) 126 | 127 | def encodeString(string): 128 | ''' 129 | Encode the given PDF string 130 | 131 | @param string: A PDFString to encode 132 | @return: A tuple (status,statusContent), where statusContent is the encoded PDF string in case status = 0 or an error in case status = -1 133 | ''' 134 | encodedString = '' 135 | try: 136 | for char in string: 137 | octal = '%o' % ord(char) 138 | encodedString += '\\'+(3-len(octal))*'0'+octal 139 | except: 140 | return (-1, 'Error encoding string') 141 | return (0, encodedString) 142 | 143 | def escapeRegExpString(string): 144 | ''' 145 | Escape the given string to include it as a regular expression 146 | 147 | @param string: A regular expression to be escaped 148 | @return: Escaped string 149 | ''' 150 | toEscapeChars = ['\\', '(', ')', '.', '|', '^', '$', '*', '+', '?', '[', ']'] 151 | escapedValue = '' 152 | for i in range(len(string)): 153 | if string[i] in toEscapeChars: 154 | escapedValue += '\\'+string[i] 155 | else: 156 | escapedValue += string[i] 157 | return escapedValue 158 | 159 | def escapeString(string): 160 | ''' 161 | Escape the given string 162 | 163 | @param string: A string to be escaped 164 | @return: Escaped string 165 | ''' 166 | toEscapeChars = ['\\', '(', ')'] 167 | escapedValue = '' 168 | for i in range(len(string)): 169 | if string[i] in toEscapeChars and (i == 0 or string[i-1] != '\\'): 170 | if string[i] == '\\': 171 | if len(string) > i+1 and re.match('[0-7]', string[i+1]): 172 | escapedValue += string[i] 173 | else: 174 | escapedValue += '\\'+string[i] 175 | else: 176 | escapedValue += '\\'+string[i] 177 | elif string[i] == '\r': 178 | escapedValue += '\\r' 179 | elif string[i] == '\n': 180 | escapedValue += '\\n' 181 | elif string[i] == '\t': 182 | escapedValue += '\\t' 183 | elif string[i] == '\b': 184 | escapedValue += '\\b' 185 | elif string[i] == '\f': 186 | escapedValue += '\\f' 187 | else: 188 | escapedValue += string[i] 189 | return escapedValue 190 | 191 | def getBitsFromNum(num, bitsPerComponent=8): 192 | ''' 193 | Makes the conversion between number and bits 194 | 195 | @param num: Number to be converted 196 | @param bitsPerComponent: Number of bits needed to represent a component 197 | @return: A tuple (status,statusContent), where statusContent is the string containing the resulting bits in case status = 0 or an error in case status = -1 198 | ''' 199 | if not isinstance(num, int): 200 | return (-1, 'num must be an integer') 201 | if not isinstance(bitsPerComponent, int): 202 | return (-1, 'bitsPerComponent must be an integer') 203 | try: 204 | bitsRepresentation = bin(num) 205 | bitsRepresentation = bitsRepresentation.replace('0b', '') 206 | mod = len(bitsRepresentation) % 8 207 | if mod != 0: 208 | bitsRepresentation = '0'*(8-mod) + bitsRepresentation 209 | bitsRepresentation = bitsRepresentation[-1*bitsPerComponent:] 210 | except: 211 | return (-1, 'Error in conversion from number to bits') 212 | return (0, bitsRepresentation) 213 | 214 | 215 | def getNumsFromBytes(bytes, bitsPerComponent=8): 216 | ''' 217 | Makes the conversion between bytes and numbers, depending on the number of bits used per component. 218 | 219 | @param bytes: String representing the bytes to be converted 220 | @param bitsPerComponent: Number of bits needed to represent a component 221 | @return: A tuple (status,statusContent), where statusContent is a list of numbers in case status = 0 or an error in case status = -1 222 | ''' 223 | if not isinstance(bytes, str): 224 | return (-1, 'bytes must be a string') 225 | if not isinstance(bitsPerComponent, int): 226 | return (-1, 'bitsPerComponent must be an integer') 227 | outputComponents = [] 228 | bitsStream = '' 229 | for byte in bytes: 230 | try: 231 | bitsRepresentation = bin(ord(byte)) 232 | bitsRepresentation = bitsRepresentation.replace('0b', '') 233 | bitsRepresentation = '0'*(8-len(bitsRepresentation)) + bitsRepresentation 234 | bitsStream += bitsRepresentation 235 | except: 236 | return (-1, 'Error in conversion from bytes to bits') 237 | 238 | try: 239 | for i in range(0, len(bitsStream), bitsPerComponent): 240 | bytes = '' 241 | bits = bitsStream[i:i+bitsPerComponent] 242 | num = int(bits, 2) 243 | outputComponents.append(num) 244 | except: 245 | return (-1, 'Error in conversion from bits to bytes') 246 | return (0, outputComponents) 247 | 248 | def getBytesFromBits(bitsStream): 249 | ''' 250 | Makes the conversion between bits and bytes. 251 | 252 | @param bitsStream: String representing a chain of bits 253 | @return: A tuple (status,statusContent), where statusContent is the string containing the resulting bytes in case status = 0 or an error in case status = -1 254 | ''' 255 | if not isinstance(bitsStream, str): 256 | return (-1, 'The bitsStream must be a string') 257 | bytes = '' 258 | if re.match('[01]*$', bitsStream): 259 | try: 260 | for i in range(0, len(bitsStream), 8): 261 | bits = bitsStream[i:i+8] 262 | byte = chr(int(bits, 2)) 263 | bytes += byte 264 | except: 265 | return (-1, 'Error in conversion from bits to bytes') 266 | return (0, bytes) 267 | else: 268 | return (-1, 'The format of the bit stream is not correct') 269 | 270 | def getBytesFromFile(filename, offset, numBytes): 271 | ''' 272 | Returns the number of bytes specified from a file, starting from the offset specified 273 | 274 | @param filename: Name of the file 275 | @param offset: Bytes offset 276 | @param numBytes: Number of bytes to retrieve 277 | @return: A tuple (status,statusContent), where statusContent is the bytes read in case status = 0 or an error in case status = -1 278 | ''' 279 | if not isinstance(offset, int) or not isinstance(numBytes, int): 280 | return (-1, 'The offset and the number of bytes must be integers') 281 | if os.path.exists(filename): 282 | fileSize = os.path.getsize(filename) 283 | bytesFile = open(filename, 'rb') 284 | bytesFile.seek(offset) 285 | if offset+numBytes > fileSize: 286 | bytes = bytesFile.read() 287 | else: 288 | bytes = bytesFile.read(numBytes) 289 | bytesFile.close() 290 | return (0, bytes) 291 | else: 292 | return (-1, 'File does not exist') 293 | 294 | def hexToString(hexString): 295 | ''' 296 | Simple method to convert an hexadecimal string to ascii string 297 | 298 | @param hexString: A string in hexadecimal format 299 | @return: A tuple (status,statusContent), where statusContent is an ascii string in case status = 0 or an error in case status = -1 300 | ''' 301 | string = '' 302 | if len(hexString) % 2 != 0: 303 | hexString = '0'+hexString 304 | try: 305 | for i in range(0, len(hexString), 2): 306 | string += chr(int(hexString[i]+hexString[i+1], 16)) 307 | except: 308 | return (-1, 'Error in hexadecimal conversion') 309 | return (0, string) 310 | 311 | def numToHex(num, numBytes): 312 | ''' 313 | Given a number returns its hexadecimal format with the specified length, adding '\0' if necessary 314 | 315 | @param num: A number (int) 316 | @param numBytes: Length of the output (int) 317 | @return: A tuple (status,statusContent), where statusContent is a number in hexadecimal format in case status = 0 or an error in case status = -1 318 | ''' 319 | hexString = '' 320 | if not isinstance(num, int): 321 | return (-1, 'Bad number') 322 | try: 323 | hexNumber = hex(num)[2:] 324 | if len(hexNumber) % 2 != 0: 325 | hexNumber = '0'+hexNumber 326 | for i in range(0, len(hexNumber)-1, 2): 327 | hexString += chr(int(hexNumber[i]+hexNumber[i+1], 16)) 328 | hexString = '\0'*(numBytes-len(hexString))+hexString 329 | except: 330 | return (-1, 'Error in hexadecimal conversion') 331 | return (0, hexString) 332 | 333 | def numToString(num, numDigits): 334 | ''' 335 | Given a number returns its string format with the specified length, adding '0' if necessary 336 | 337 | @param num: A number (int) 338 | @param numDigits: Length of the output string (int) 339 | @return: A tuple (status,statusContent), where statusContent is a number in string format in case status = 0 or an error in case status = -1 340 | ''' 341 | if not isinstance(num, int): 342 | return (-1, 'Bad number') 343 | strNum = str(num) 344 | if numDigits < len(strNum): 345 | return (-1, 'Bad digit number') 346 | for i in range(numDigits-len(strNum)): 347 | strNum = '0' + strNum 348 | return (0, strNum) 349 | 350 | def unescapeHTMLEntities(text): 351 | ''' 352 | Removes HTML or XML character references and entities from a text string. 353 | 354 | @param text The HTML (or XML) source text. 355 | @return The plain text, as a Unicode string, if necessary. 356 | 357 | Author: Fredrik Lundh 358 | Source: http://effbot.org/zone/re-sub.htm#unescape-html 359 | ''' 360 | def fixup(m): 361 | text = m.group(0) 362 | if text[:2] == "&#": 363 | # character reference 364 | try: 365 | if text[:3] == "&#x": 366 | return chr(int(text[3:-1], 16)) 367 | else: 368 | return chr(int(text[2:-1])) 369 | except ValueError: 370 | pass 371 | else: 372 | # named entity 373 | try: 374 | text = chr(html.entities.name2codepoint[text[1:-1]]) 375 | except KeyError: 376 | pass 377 | return text # leave as is 378 | return re.sub("&#?\w+;", fixup, text) 379 | 380 | def unescapeString(string): 381 | ''' 382 | Unescape the given string 383 | 384 | @param string: An escaped string 385 | @return: Unescaped string 386 | ''' 387 | toUnescapeChars = ['\\', '(', ')'] 388 | unescapedValue = '' 389 | i = 0 390 | while i < len(string): 391 | if string[i] == '\\' and i != len(string)-1: 392 | if string[i+1] in toUnescapeChars: 393 | if string[i+1] == '\\': 394 | unescapedValue += '\\' 395 | i += 1 396 | else: 397 | pass 398 | elif string[i+1] == 'r': 399 | i += 1 400 | unescapedValue += '\r' 401 | elif string[i+1] == 'n': 402 | i += 1 403 | unescapedValue += '\n' 404 | elif string[i+1] == 't': 405 | i += 1 406 | unescapedValue += '\t' 407 | elif string[i+1] == 'b': 408 | i += 1 409 | unescapedValue += '\b' 410 | elif string[i+1] == 'f': 411 | i += 1 412 | unescapedValue += '\f' 413 | else: 414 | unescapedValue += string[i] 415 | else: 416 | unescapedValue += string[i] 417 | i += 1 418 | return unescapedValue 419 | 420 | def vtcheck(md5, vtKey): 421 | ''' 422 | Function to check a hash on VirusTotal and get the report summary 423 | 424 | @param md5: The MD5 to check (hexdigest) 425 | @param vtKey: The VirusTotal API key needed to perform the request 426 | @return: A dictionary with the result of the request 427 | ''' 428 | vtUrl = 'https://www.virustotal.com/vtapi/v2/file/report' 429 | parameters = {'resource': md5, 'apikey': vtKey} 430 | try: 431 | data = urllib.parse.urlencode(parameters) 432 | req = urllib.request.Request(vtUrl, data) 433 | response = urllib.request.urlopen(req) 434 | jsonResponse = response.read() 435 | except: 436 | return (-1, 'The request to VirusTotal has not been successful') 437 | try: 438 | jsonDict = json.loads(jsonResponse) 439 | except: 440 | return (-1, 'An error has occurred while parsing the JSON response from VirusTotal') 441 | return (0, jsonDict) 442 | -------------------------------------------------------------------------------- /peepdf/__init__.py: -------------------------------------------------------------------------------- 1 | # peepdf is a tool to analyse and modify PDF files 2 | # http://peepdf.eternal-todo.com 3 | # By Jose Miguel Esparza 4 | # 5 | # Copyright (C) 2016 Jose Miguel Esparza 6 | # 7 | # This file is part of peepdf. 8 | # 9 | # peepdf is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # peepdf is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with peepdf. If not, see . 21 | 22 | from . import PDFConsole, PDFCore, PDFCrypto, PDFFilters, PDFUtils 23 | -------------------------------------------------------------------------------- /peepdf/aes.py: -------------------------------------------------------------------------------- 1 | # 2 | # peepdf is a tool to analyse and modify PDF files 3 | # http://peepdf.eternal-todo.com 4 | # By Jose Miguel Esparza 5 | # 6 | # Copyright (C) 2012-2014 Jose Miguel Esparza 7 | # 8 | # This file is part of peepdf. 9 | # 10 | # peepdf is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # peepdf is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with peepdf. If not, see . 22 | # 23 | 24 | """ 25 | Created from the demonstration of the pythonaes package. 26 | 27 | Copyright (c) 2010, Adam Newman http://www.caller9.com/ 28 | Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php 29 | """ 30 | 31 | import sys 32 | from aespython import key_expander, aes_cipher, cbc_mode 33 | 34 | def decryptData(data, password = None, keyLength = None, mode = 'CBC'): 35 | ''' 36 | Method added for peepdf 37 | ''' 38 | decryptedData = '' 39 | if keyLength == None: 40 | keyLength = len(password)*8 41 | if keyLength not in [128, 192, 256]: 42 | return (-1, 'Bad length key in AES decryption process') 43 | 44 | iv = list(map(ord, data[:16])) 45 | key = list(map(ord, password)) 46 | data = data[16:] 47 | if len(data) % 16 != 0: 48 | data = data[:-(len(data)%16)] 49 | keyExpander = key_expander.KeyExpander(keyLength) 50 | expandedKey = keyExpander.expand(key) 51 | aesCipher = aes_cipher.AESCipher(expandedKey) 52 | if mode == 'CBC': 53 | aesMode = cbc_mode.CBCMode(aesCipher, 16) 54 | aesMode.set_iv(iv) 55 | for i in range(0,len(data),16): 56 | ciphertext = list(map(ord,data[i:i+16])) 57 | decryptedBytes = aesMode.decrypt_block(ciphertext) 58 | for byte in decryptedBytes: 59 | decryptedData += chr(byte) 60 | return (0, decryptedData) 61 | -------------------------------------------------------------------------------- /peepdf/ccitt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | ccitt.py 6 | 7 | TODO 8 | http://tools.ietf.org/pdf/rfc804.pdf 9 | http://code.google.com/p/origami-pdf/source/browse/lib/origami/filters/ccitt.rb 10 | """ 11 | __author__ = 'Binjo' 12 | __version__ = '0.1' 13 | __date__ = '2012-04-08 14:30:05' 14 | 15 | class BitWriterException(Exception): 16 | pass 17 | 18 | class BitWriter(object): 19 | """ 20 | """ 21 | 22 | def __init__(self, ): 23 | """ 24 | """ 25 | self._data = '' 26 | self._last_byte = None 27 | self._bit_ptr = 0 28 | 29 | @property 30 | def data(self): 31 | """ 32 | """ 33 | return self._data 34 | 35 | def write(self, data, length): 36 | """ 37 | """ 38 | if not ( length >= 0 and (1 << length) > data ): 39 | raise BitWriterException("Invalid data length") 40 | 41 | if length == 8 and not self._last_byte and self._bit_ptr == 0: 42 | self._data += chr(data) 43 | return 44 | 45 | while length > 0: 46 | 47 | if length >= 8 - self._bit_ptr: 48 | length -= 8 - self._bit_ptr 49 | if not self._last_byte: 50 | self._last_byte = 0 51 | self._last_byte |= (data >> length) & ((1 << (8 - self._bit_ptr)) - 1) 52 | 53 | data &= (1 << length) - 1 54 | self._data += chr(self._last_byte) 55 | self._last_byte = None 56 | self._bit_ptr = 0 57 | else: 58 | if not self._last_byte: 59 | self._last_byte = 0 60 | self._last_byte |= (data & ((1 << length) - 1)) << (8 - self._bit_ptr - length) 61 | self._bit_ptr += length 62 | 63 | if self._bit_ptr == 8: 64 | self._data += chr(self._last_byte) 65 | self._last_byte = None 66 | self._bit_ptr = 0 67 | 68 | length = 0 69 | 70 | class BitReaderException(Exception): 71 | pass 72 | 73 | class BitReader(object): 74 | """ 75 | """ 76 | 77 | def __init__(self, data): 78 | """ 79 | """ 80 | self._data = data 81 | self._byte_ptr, self._bit_ptr = 0, 0 82 | 83 | def reset(self): 84 | """ 85 | """ 86 | self._byte_ptr, self._bit_ptr = 0, 0 87 | 88 | @property 89 | def eod_p(self): 90 | """ 91 | """ 92 | return self._byte_ptr >= len(self._data) 93 | 94 | @property 95 | def pos(self): 96 | """ 97 | """ 98 | return (self._byte_ptr << 3) + self._bit_ptr 99 | 100 | @property 101 | def size(self): 102 | """ 103 | """ 104 | return len(self._data) << 3 105 | 106 | @pos.setter 107 | def pos(self, bits): 108 | """ 109 | """ 110 | if bits > self.size: 111 | raise BitReaderException("Pointer position out of data") 112 | 113 | pbyte = bits >> 3 114 | pbit = bits - (pbyte <<3) 115 | self._byte_ptr, self._bit_ptr = pbyte, pbit 116 | 117 | def peek(self, length): 118 | """ 119 | """ 120 | if length <= 0: 121 | raise BitReaderException("Invalid read length") 122 | elif ( self.pos + length ) > self.size: 123 | raise BitReaderException("Insufficient data") 124 | 125 | n = 0 126 | byte_ptr, bit_ptr = self._byte_ptr, self._bit_ptr 127 | 128 | while length > 0: 129 | 130 | byte = ord( self._data[byte_ptr] ) 131 | 132 | if length > 8 - bit_ptr: 133 | length -= 8 - bit_ptr 134 | n |= ( byte & ((1 << (8 - bit_ptr)) - 1) ) << length 135 | 136 | byte_ptr += 1 137 | bit_ptr = 0 138 | else: 139 | n |= (byte >> (8 - bit_ptr - length)) & ((1 << length) - 1) 140 | length = 0 141 | 142 | return n 143 | 144 | def read(self, length): 145 | """ 146 | """ 147 | n = self.peek(length) 148 | self.pos += length 149 | 150 | return n 151 | 152 | def codeword(bits): 153 | """return tuple rather than list, since list is not hashable... 154 | """ 155 | return ( int(bits, 2), len(bits) ) 156 | 157 | class CCITTFax(object): 158 | """ 159 | """ 160 | 161 | EOL = codeword('000000000001') 162 | RTC = codeword('000000000001' * 6) 163 | 164 | WHITE_TERMINAL_ENCODE_TABLE = { 165 | 0 : codeword('00110101'), 166 | 1 : codeword('000111'), 167 | 2 : codeword('0111'), 168 | 3 : codeword('1000'), 169 | 4 : codeword('1011'), 170 | 5 : codeword('1100'), 171 | 6 : codeword('1110'), 172 | 7 : codeword('1111'), 173 | 8 : codeword('10011'), 174 | 9 : codeword('10100'), 175 | 10 : codeword('00111'), 176 | 11 : codeword('01000'), 177 | 12 : codeword('001000'), 178 | 13 : codeword('000011'), 179 | 14 : codeword('110100'), 180 | 15 : codeword('110101'), 181 | 16 : codeword('101010'), 182 | 17 : codeword('101011'), 183 | 18 : codeword('0100111'), 184 | 19 : codeword('0001100'), 185 | 20 : codeword('0001000'), 186 | 21 : codeword('0010111'), 187 | 22 : codeword('0000011'), 188 | 23 : codeword('0000100'), 189 | 24 : codeword('0101000'), 190 | 25 : codeword('0101011'), 191 | 26 : codeword('0010011'), 192 | 27 : codeword('0100100'), 193 | 28 : codeword('0011000'), 194 | 29 : codeword('00000010'), 195 | 30 : codeword('00000011'), 196 | 31 : codeword('00011010'), 197 | 32 : codeword('00011011'), 198 | 33 : codeword('00010010'), 199 | 34 : codeword('00010011'), 200 | 35 : codeword('00010100'), 201 | 36 : codeword('00010101'), 202 | 37 : codeword('00010110'), 203 | 38 : codeword('00010111'), 204 | 39 : codeword('00101000'), 205 | 40 : codeword('00101001'), 206 | 41 : codeword('00101010'), 207 | 42 : codeword('00101011'), 208 | 43 : codeword('00101100'), 209 | 44 : codeword('00101101'), 210 | 45 : codeword('00000100'), 211 | 46 : codeword('00000101'), 212 | 47 : codeword('00001010'), 213 | 48 : codeword('00001011'), 214 | 49 : codeword('01010010'), 215 | 50 : codeword('01010011'), 216 | 51 : codeword('01010100'), 217 | 52 : codeword('01010101'), 218 | 53 : codeword('00100100'), 219 | 54 : codeword('00100101'), 220 | 55 : codeword('01011000'), 221 | 56 : codeword('01011001'), 222 | 57 : codeword('01011010'), 223 | 58 : codeword('01011011'), 224 | 59 : codeword('01001010'), 225 | 60 : codeword('01001011'), 226 | 61 : codeword('00110010'), 227 | 62 : codeword('00110011'), 228 | 63 : codeword('00110100') 229 | } 230 | 231 | WHITE_TERMINAL_DECODE_TABLE = dict( (v, k) for k, v in WHITE_TERMINAL_ENCODE_TABLE.items() ) 232 | 233 | BLACK_TERMINAL_ENCODE_TABLE = { 234 | 0 : codeword('0000110111'), 235 | 1 : codeword('010'), 236 | 2 : codeword('11'), 237 | 3 : codeword('10'), 238 | 4 : codeword('011'), 239 | 5 : codeword('0011'), 240 | 6 : codeword('0010'), 241 | 7 : codeword('00011'), 242 | 8 : codeword('000101'), 243 | 9 : codeword('000100'), 244 | 10 : codeword('0000100'), 245 | 11 : codeword('0000101'), 246 | 12 : codeword('0000111'), 247 | 13 : codeword('00000100'), 248 | 14 : codeword('00000111'), 249 | 15 : codeword('000011000'), 250 | 16 : codeword('0000010111'), 251 | 17 : codeword('0000011000'), 252 | 18 : codeword('0000001000'), 253 | 19 : codeword('00001100111'), 254 | 20 : codeword('00001101000'), 255 | 21 : codeword('00001101100'), 256 | 22 : codeword('00000110111'), 257 | 23 : codeword('00000101000'), 258 | 24 : codeword('00000010111'), 259 | 25 : codeword('00000011000'), 260 | 26 : codeword('000011001010'), 261 | 27 : codeword('000011001011'), 262 | 28 : codeword('000011001100'), 263 | 29 : codeword('000011001101'), 264 | 30 : codeword('000001101000'), 265 | 31 : codeword('000001101001'), 266 | 32 : codeword('000001101010'), 267 | 33 : codeword('000001101011'), 268 | 34 : codeword('000011010010'), 269 | 35 : codeword('000011010011'), 270 | 36 : codeword('000011010100'), 271 | 37 : codeword('000011010101'), 272 | 38 : codeword('000011010110'), 273 | 39 : codeword('000011010111'), 274 | 40 : codeword('000001101100'), 275 | 41 : codeword('000001101101'), 276 | 42 : codeword('000011011010'), 277 | 43 : codeword('000011011011'), 278 | 44 : codeword('000001010100'), 279 | 45 : codeword('000001010101'), 280 | 46 : codeword('000001010110'), 281 | 47 : codeword('000001010111'), 282 | 48 : codeword('000001100100'), 283 | 49 : codeword('000001100101'), 284 | 50 : codeword('000001010010'), 285 | 51 : codeword('000001010011'), 286 | 52 : codeword('000000100100'), 287 | 53 : codeword('000000110111'), 288 | 54 : codeword('000000111000'), 289 | 55 : codeword('000000100111'), 290 | 56 : codeword('000000101000'), 291 | 57 : codeword('000001011000'), 292 | 58 : codeword('000001011001'), 293 | 59 : codeword('000000101011'), 294 | 60 : codeword('000000101100'), 295 | 61 : codeword('000001011010'), 296 | 62 : codeword('000001100110'), 297 | 63 : codeword('000001100111') 298 | } 299 | 300 | BLACK_TERMINAL_DECODE_TABLE = dict( (v, k) for k, v in BLACK_TERMINAL_ENCODE_TABLE.items() ) 301 | 302 | WHITE_CONFIGURATION_ENCODE_TABLE = { 303 | 64 : codeword('11011'), 304 | 128 : codeword('10010'), 305 | 192 : codeword('010111'), 306 | 256 : codeword('0110111'), 307 | 320 : codeword('00110110'), 308 | 384 : codeword('00110111'), 309 | 448 : codeword('01100100'), 310 | 512 : codeword('01100101'), 311 | 576 : codeword('01101000'), 312 | 640 : codeword('01100111'), 313 | 704 : codeword('011001100'), 314 | 768 : codeword('011001101'), 315 | 832 : codeword('011010010'), 316 | 896 : codeword('011010011'), 317 | 960 : codeword('011010100'), 318 | 1024 : codeword('011010101'), 319 | 1088 : codeword('011010110'), 320 | 1152 : codeword('011010111'), 321 | 1216 : codeword('011011000'), 322 | 1280 : codeword('011011001'), 323 | 1344 : codeword('011011010'), 324 | 1408 : codeword('011011011'), 325 | 1472 : codeword('010011000'), 326 | 1536 : codeword('010011001'), 327 | 1600 : codeword('010011010'), 328 | 1664 : codeword('011000'), 329 | 1728 : codeword('010011011'), 330 | 331 | 1792 : codeword('00000001000'), 332 | 1856 : codeword('00000001100'), 333 | 1920 : codeword('00000001001'), 334 | 1984 : codeword('000000010010'), 335 | 2048 : codeword('000000010011'), 336 | 2112 : codeword('000000010100'), 337 | 2176 : codeword('000000010101'), 338 | 2240 : codeword('000000010110'), 339 | 2340 : codeword('000000010111'), 340 | 2368 : codeword('000000011100'), 341 | 2432 : codeword('000000011101'), 342 | 2496 : codeword('000000011110'), 343 | 2560 : codeword('000000011111') 344 | } 345 | 346 | WHITE_CONFIGURATION_DECODE_TABLE = dict( (v, k) for k, v in WHITE_CONFIGURATION_ENCODE_TABLE.items() ) 347 | 348 | BLACK_CONFIGURATION_ENCODE_TABLE = { 349 | 64 : codeword('0000001111'), 350 | 128 : codeword('000011001000'), 351 | 192 : codeword('000011001001'), 352 | 256 : codeword('000001011011'), 353 | 320 : codeword('000000110011'), 354 | 384 : codeword('000000110100'), 355 | 448 : codeword('000000110101'), 356 | 512 : codeword('0000001101100'), 357 | 576 : codeword('0000001101101'), 358 | 640 : codeword('0000001001010'), 359 | 704 : codeword('0000001001011'), 360 | 768 : codeword('0000001001100'), 361 | 832 : codeword('0000001001101'), 362 | 896 : codeword('0000001110010'), 363 | 960 : codeword('0000001110011'), 364 | 1024 : codeword('0000001110100'), 365 | 1088 : codeword('0000001110101'), 366 | 1152 : codeword('0000001110110'), 367 | 1216 : codeword('0000001110111'), 368 | 1280 : codeword('0000001010010'), 369 | 1344 : codeword('0000001010011'), 370 | 1408 : codeword('0000001010100'), 371 | 1472 : codeword('0000001010101'), 372 | 1536 : codeword('0000001011010'), 373 | 1600 : codeword('0000001011011'), 374 | 1664 : codeword('0000001100100'), 375 | 1728 : codeword('0000001100101'), 376 | 377 | 1792 : codeword('00000001000'), 378 | 1856 : codeword('00000001100'), 379 | 1920 : codeword('00000001001'), 380 | 1984 : codeword('000000010010'), 381 | 2048 : codeword('000000010011'), 382 | 2112 : codeword('000000010100'), 383 | 2176 : codeword('000000010101'), 384 | 2240 : codeword('000000010110'), 385 | 2340 : codeword('000000010111'), 386 | 2368 : codeword('000000011100'), 387 | 2432 : codeword('000000011101'), 388 | 2496 : codeword('000000011110'), 389 | 2560 : codeword('000000011111') 390 | } 391 | 392 | BLACK_CONFIGURATION_DECODE_TABLE = dict( (v, k) for k, v in BLACK_CONFIGURATION_ENCODE_TABLE.items() ) 393 | 394 | def __init__(self, ): 395 | """ 396 | """ 397 | self._decoded = [] 398 | 399 | def decode(self, stream, k = 0, eol = False, byteAlign = False, columns = 1728, rows = 0, eob = True, blackIs1 = False, damagedRowsBeforeError = 0): 400 | """ 401 | """ 402 | # FIXME seems not stick to the spec? default is false, but if not set as true, it won't decode 6cc2a162e08836f7d50d461a9fc136fe correctly 403 | byteAlign = True 404 | 405 | if blackIs1: 406 | white, black = 0,1 407 | else: 408 | white, black = 1,0 409 | 410 | bitr = BitReader( stream ) 411 | bitw = BitWriter() 412 | 413 | while not ( bitr.eod_p or rows == 0 ): 414 | 415 | current_color = white 416 | if byteAlign and bitr.pos % 8 != 0: 417 | bitr.pos += 8 - (bitr.pos % 8) 418 | 419 | if eob and bitr.peek(self.RTC[1]) == self.RTC[0]: 420 | bitr.pos += RTC[1] 421 | break 422 | 423 | if bitr.peek(self.EOL[1]) != self.EOL[0]: 424 | if eol: 425 | raise Exception("No end-of-line pattern found (at bit pos %d/%d)" % (bitr.pos, bitr.size)) 426 | else: 427 | bitr.pos += self.EOL[1] 428 | 429 | line_length = 0 430 | while line_length < columns: 431 | if current_color == white: 432 | bit_length = self.get_white_bits(bitr) 433 | else: 434 | bit_length = self.get_black_bits(bitr) 435 | if bit_length == None: 436 | raise Exception("Unfinished line (at bit pos %d/%d), %s" % (bitr.pos, bitr.size, bitw.data)) 437 | 438 | line_length += bit_length 439 | if line_length > columns: 440 | raise Exception("Line is too long (at bit pos %d/%d)" % (bitr.pos, bitr.size)) 441 | 442 | bitw.write( (current_color << bit_length) - current_color, bit_length ) 443 | 444 | current_color ^= 1 445 | 446 | rows -= 1 447 | return bitw.data 448 | 449 | def get_white_bits(self, bitr): 450 | """ 451 | """ 452 | return self.get_color_bits( bitr, self.WHITE_CONFIGURATION_DECODE_TABLE, self.WHITE_TERMINAL_DECODE_TABLE ) 453 | 454 | def get_black_bits(self, bitr): 455 | """ 456 | """ 457 | return self.get_color_bits( bitr, self.BLACK_CONFIGURATION_DECODE_TABLE, self.BLACK_TERMINAL_DECODE_TABLE ) 458 | 459 | def get_color_bits(self, bitr, config_words, term_words): 460 | """ 461 | """ 462 | bits = 0 463 | check_conf = True 464 | 465 | while check_conf: 466 | check_conf = False 467 | 468 | for i in range(2, 14): 469 | codeword = bitr.peek(i) 470 | config_value = config_words.get((codeword, i), None) 471 | 472 | if config_value is not None: 473 | bitr.pos += i 474 | bits += config_value 475 | if config_value == 2560: 476 | check_conf = True 477 | break 478 | 479 | for i in range(2, 14): 480 | codeword = bitr.peek(i) 481 | term_value = term_words.get((codeword, i), None) 482 | 483 | if term_value is not None: 484 | bitr.pos += i 485 | bits += term_value 486 | 487 | return bits 488 | 489 | return None -------------------------------------------------------------------------------- /peepdf/jjdecode.py: -------------------------------------------------------------------------------- 1 | # 2 | # peepdf is a tool to analyse and modify PDF files 3 | # http://peepdf.eternal-todo.com 4 | # By Jose Miguel Esparza 5 | # 6 | # Copyright (C) 2014 Jose Miguel Esparza 7 | # 8 | # This file is part of peepdf. 9 | # 10 | # peepdf is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # peepdf is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with peepdf. If not, see . 22 | # 23 | 24 | # Python version of the jjdecode function written by Syed Zainudeen 25 | # http://csc.cs.utm.my/syed/images/files/jjdecode/jjdecode.html 26 | # +NCR/CRC! [ReVeRsEr] - crackinglandia@gmail.com 27 | # 28 | # The original algorithm was written in Javascript by Yosuke Hasegawa (http://utf-8.jp/public/jjencode.html) 29 | # 30 | # Modified to integrate it with peepdf 31 | 32 | import re, sys 33 | 34 | class JJDecoder(object): 35 | 36 | def __init__(self, jj_encoded_data): 37 | self.encoded_str = jj_encoded_data 38 | 39 | def clean(self): 40 | self.encoded_str = re.sub('^\s+|\s+$', '', self.encoded_str) 41 | 42 | def checkPalindrome(self): 43 | startpos = -1 44 | endpos = -1 45 | gv, gvl = -1, -1 46 | 47 | index = self.encoded_str.find('"\'\\"+\'+",') 48 | 49 | if index == 0: 50 | startpos = self.encoded_str.find('$$+"\\""+') + 8 51 | endpos = self.encoded_str.find('"\\"")())()') 52 | gv = self.encoded_str[index+9:self.encoded_str.find('=~[]')] 53 | gvl = len(gv) 54 | else: 55 | gv = self.encoded_str[0:self.encoded_str.find('=')] 56 | gvl = len(gv) 57 | startpos = self.encoded_str.find('"\\""+') + 5 58 | endpos = self.encoded_str.find('"\\"")())()') 59 | 60 | return (startpos, endpos, gv, gvl) 61 | 62 | def decode(self): 63 | 64 | self.clean() 65 | startpos, endpos, gv, gvl = self.checkPalindrome() 66 | 67 | if startpos == endpos: 68 | return (-1,'There is no data to decode') 69 | 70 | data = self.encoded_str[startpos:endpos] 71 | 72 | b = ['___+', '__$+', '_$_+', '_$$+', '$__+', '$_$+', '$$_+', '$$$+', '$___+', '$__$+', '$_$_+', '$_$$+', '$$__+', '$$_$+', '$$$_+', '$$$$+'] 73 | 74 | str_l = '(![]+"")[' + gv + '._$_]+' 75 | str_o = gv + '._$+' 76 | str_t = gv + '.__+' 77 | str_u = gv + '._+' 78 | 79 | str_hex = gv + '.' 80 | 81 | str_s = '"' 82 | gvsig = gv + '.' 83 | 84 | str_quote = '\\\\\\"' 85 | str_slash = '\\\\\\\\' 86 | 87 | str_lower = '\\\\"+' 88 | str_upper = '\\\\"+' + gv + '._+' 89 | 90 | str_end = '"+' 91 | 92 | out = '' 93 | while data != '': 94 | # l o t u 95 | if data.find(str_l) == 0: 96 | data = data[len(str_l):] 97 | out += 'l' 98 | continue 99 | elif data.find(str_o) == 0: 100 | data = data[len(str_o):] 101 | out += 'o' 102 | continue 103 | elif data.find(str_t) == 0: 104 | data = data[len(str_t):] 105 | out += 't' 106 | continue 107 | elif data.find(str_u) == 0: 108 | data = data[len(str_u):] 109 | out += 'u' 110 | continue 111 | 112 | # 0123456789abcdef 113 | if data.find(str_hex) == 0: 114 | data = data[len(str_hex):] 115 | 116 | for i in range(len(b)): 117 | if data.find(b[i]) == 0: 118 | data = data[len(b[i]):] 119 | out += '%x' % i 120 | break 121 | continue 122 | 123 | # start of s block 124 | if data.find(str_s) == 0: 125 | data = data[len(str_s):] 126 | 127 | # check if "R 128 | if data.find(str_upper) == 0: # r4 n >= 128 129 | data = data[len(str_upper):] # skip sig 130 | ch_str = '' 131 | for i in range(2): # shouldn't be more than 2 hex chars 132 | # gv + "."+b[ c ] 133 | if data.find(gvsig) == 0: 134 | data = data[len(gvsig):] 135 | for k in range(len(b)): # for every entry in b 136 | if data.find(b[k]) == 0: 137 | data = data[len(b[k]):] 138 | ch_str = '%x' % k 139 | break 140 | else: 141 | break 142 | 143 | out += chr(int(ch_str, 16)) 144 | continue 145 | 146 | elif data.find(str_lower) == 0: # r3 check if "R // n < 128 147 | data = data[len(str_lower):] # skip sig 148 | 149 | ch_str = '' 150 | ch_lotux = '' 151 | temp = '' 152 | b_checkR1 = 0 153 | for j in range(3): # shouldn't be more than 3 octal chars 154 | if j > 1: # lotu check 155 | if data.find(str_l) == 0: 156 | data = data[len(str_l):] 157 | ch_lotux = 'l' 158 | break 159 | elif data.find(str_o) == 0: 160 | data = data[len(str_o):] 161 | ch_lotux = 'o' 162 | break 163 | elif data.find(str_t) == 0: 164 | data = data[len(str_t):] 165 | ch_lotux = 't' 166 | break 167 | elif data.find(str_u) == 0: 168 | data = data[len(str_u):] 169 | ch_lotux = 'u' 170 | break 171 | 172 | # gv + "."+b[ c ] 173 | if data.find(gvsig) == 0: 174 | temp = data[len(gvsig):] 175 | for k in range(8): # for every entry in b octal 176 | if temp.find(b[k]) == 0: 177 | if int(ch_str + str(k), 8) > 128: 178 | b_checkR1 = 1 179 | break 180 | 181 | ch_str += str(k) 182 | data = data[len(gvsig):] # skip gvsig 183 | data = data[len(b[k]):] 184 | break 185 | 186 | if b_checkR1 == 1: 187 | if data.find(str_hex) == 0: # 0123456789abcdef 188 | data = data[len(str_hex):] 189 | # check every element of hex decode string for a match 190 | for i in range(len(b)): 191 | if data.find(b[i]) == 0: 192 | data = data[len(b[i]):] 193 | ch_lotux = '%x' % i 194 | break 195 | break 196 | else: 197 | break 198 | 199 | out += chr(int(ch_str,8)) + ch_lotux 200 | continue 201 | 202 | else: # "S ----> "SR or "S+ 203 | # if there is, loop s until R 0r + 204 | # if there is no matching s block, throw error 205 | 206 | match = 0; 207 | n = None 208 | 209 | # searching for matching pure s block 210 | while True: 211 | n = ord(data[0]) 212 | if data.find(str_quote) == 0: 213 | data = data[len(str_quote):] 214 | out += '"' 215 | match += 1 216 | continue 217 | elif data.find(str_slash) == 0: 218 | data = data[len(str_slash):] 219 | out += '\\' 220 | match += 1 221 | continue 222 | elif data.find(str_end) == 0: # reached end off S block ? + 223 | if match == 0: 224 | return (-1,'+ No match S block') 225 | data = data[len(str_end):] 226 | break # step out of the while loop 227 | elif data.find(str_upper) == 0: # r4 reached end off S block ? - check if "R n >= 128z 228 | if match == 0: 229 | return (-1,'No match S block n>128') 230 | data = data[len(str_upper):] # skip sig 231 | 232 | ch_str = '' 233 | ch_lotux = '' 234 | 235 | for j in range(10): # shouldn't be more than 10 hex chars 236 | if j > 1: # lotu check 237 | if data.find(str_l) == 0: 238 | data = data[len(str_l):] 239 | ch_lotux = 'l' 240 | break 241 | elif data.find(str_o) == 0: 242 | data = data[len(str_o):] 243 | ch_lotux = 'o' 244 | break 245 | elif data.find(str_t) == 0: 246 | data = data[len(str_t):] 247 | ch_lotux = 't' 248 | break 249 | elif data.find(str_u) == 0: 250 | data = data[len(str_u):] 251 | ch_lotux = 'u' 252 | break 253 | 254 | # gv + "."+b[ c ] 255 | if data.find(gvsig) == 0: 256 | data = data[len(gvsig):] # skip gvsig 257 | for k in range(len(b)): # for every entry in b 258 | if data.find(b[k]) == 0: 259 | data = data[len(b[k]):] 260 | ch_str += '%x' % k 261 | break 262 | else: 263 | break # done 264 | out += chr(int(ch_str, 16)) 265 | break # step out of the while loop 266 | elif data.find(str_lower) == 0: # r3 check if "R // n < 128 267 | if match == 0: 268 | return (-1,'No match S block n<128!!') 269 | 270 | data = data[len(str_lower):] # skip sig 271 | 272 | ch_str = '' 273 | ch_lotux = '' 274 | temp = '' 275 | b_checkR1 = 0 276 | 277 | for j in range(3): # shouldn't be more than 3 octal chars 278 | if j > 1: # lotu check 279 | if data.find(str_l) == 0: 280 | data = data[len(str_l):] 281 | ch_lotux = 'l' 282 | break 283 | elif data.find(str_o) == 0: 284 | data = data[len(str_o):] 285 | ch_lotux = 'o' 286 | break 287 | elif data.find(str_t) == 0: 288 | data = data[len(str_t):] 289 | ch_lotux = 't' 290 | break 291 | elif data.find(str_u) == 0: 292 | data = data[len(str_u):] 293 | ch_lotux = 'u' 294 | break 295 | 296 | # gv + "."+b[ c ] 297 | if data.find(gvsig) == 0: 298 | temp = data[len(gvsig):] 299 | for k in range(8): # for every entry in b octal 300 | if temp.find(b[k]) == 0: 301 | if int(ch_str + str(k), 8) > 128: 302 | b_checkR1 = 1 303 | break 304 | 305 | ch_str += str(k) 306 | data = data[len(gvsig):] # skip gvsig 307 | data = data[len(b[k]):] 308 | break 309 | 310 | if b_checkR1 == 1: 311 | if data.find(str_hex) == 0: # 0123456789abcdef 312 | data = data[len(str_hex):] 313 | # check every element of hex decode string for a match 314 | for i in range(len(b)): 315 | if data.find(b[i]) == 0: 316 | data = data[len(b[i]):] 317 | ch_lotux = '%x' % i 318 | break 319 | else: 320 | break 321 | out += chr(int(ch_str, 8)) + ch_lotux 322 | break # step out of the while loop 323 | elif (0x21 <= n and n <= 0x2f) or (0x3A <= n and n <= 0x40) or ( 0x5b <= n and n <= 0x60 ) or ( 0x7b <= n and n <= 0x7f ): 324 | out += data[0] 325 | data = data[1:] 326 | match += 1 327 | continue 328 | return (-1,'No match in the code!!') 329 | break 330 | return (0, out) -------------------------------------------------------------------------------- /peepdf/lzw.py: -------------------------------------------------------------------------------- 1 | # 2 | # peepdf is a tool to analyse and modify PDF files 3 | # http://peepdf.eternal-todo.com 4 | # By Jose Miguel Esparza 5 | # 6 | # Copyright (C) 2012-2014 Jose Miguel Esparza 7 | # 8 | # This file is part of peepdf. 9 | # 10 | # peepdf is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # peepdf is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with peepdf. If not, see . 22 | # 23 | 24 | ''' 25 | Library to encode/decode streams using the LZW algorithm. Mix of third party libraries (python-lzw and pdfminer) with some modifications. 26 | ''' 27 | 28 | """ 29 | A stream friendly, simple compression library, built around 30 | iterators. See L{compress} and L{decompress} for the easiest way to 31 | get started. 32 | 33 | After the TIFF implementation of LZW, as described at 34 | U{http://www.fileformat.info/format/tiff/corion-lzw.htm} 35 | 36 | 37 | In an even-nuttier-shell, lzw compresses input bytes with integer 38 | codes. Starting with codes 0-255 that code to themselves, and two 39 | control codes, we work our way through a stream of bytes. When we 40 | encounter a pair of codes c1,c2 we add another entry to our code table 41 | with the lowest available code and the value value(c1) + value(c2)[0] 42 | 43 | Of course, there are details :) 44 | 45 | The Details 46 | =========== 47 | 48 | Our control codes are 49 | 50 | - CLEAR_CODE (codepoint 256). When this code is encountered, we flush 51 | the codebook and start over. 52 | - END_OF_INFO_CODE (codepoint 257). This code is reserved for 53 | encoder/decoders over the integer codepoint stream (like the 54 | mechanical bit that unpacks bits into codepoints) 55 | 56 | When dealing with bytes, codes are emitted as variable 57 | length bit strings packed into the stream of bytes. 58 | 59 | codepoints are written with varying length 60 | - initially 9 bits 61 | - at 512 entries 10 bits 62 | - at 1025 entries at 11 bits 63 | - at 2048 entries 12 bits 64 | - with max of 4095 entries in a table (including Clear and EOI) 65 | 66 | code points are stored with their MSB in the most significant bit 67 | available in the output character. 68 | 69 | >>> import peepdf.lzw 70 | >>> 71 | >>> mybytes = lzw.readbytes("README.txt") 72 | >>> lessbytes = lzw.compress(mybytes) 73 | >>> newbytes = b"".join(lzw.decompress(lessbytes)) 74 | >>> oldbytes = b"".join(lzw.readbytes("README.txt")) 75 | >>> oldbytes == newbytes 76 | True 77 | 78 | __author__ = "Joe Bowers" 79 | __license__ = "MIT License" 80 | __version__ = "0.01.01" 81 | __status__ = "Development" 82 | __email__ = "joerbowers@gmail.com" 83 | __url__ = "http://www.joe-bowers.com/static/lzw" 84 | 85 | """ 86 | 87 | 88 | import struct 89 | import itertools 90 | 91 | 92 | CLEAR_CODE = 256 93 | END_OF_INFO_CODE = 257 94 | 95 | DEFAULT_MIN_BITS = 9 96 | DEFAULT_MAX_BITS = 12 97 | 98 | 99 | 100 | 101 | def compress(plaintext_bytes): 102 | """ 103 | Given an iterable of bytes, returns a (hopefully shorter) iterable 104 | of bytes that you can store in a file or pass over the network or 105 | what-have-you, and later use to get back your original bytes with 106 | L{decompress}. This is the best place to start using this module. 107 | """ 108 | encoder = ByteEncoder() 109 | return encoder.encodetobytes(plaintext_bytes) 110 | 111 | 112 | def decompress(compressed_bytes): 113 | """ 114 | Given an iterable of bytes that were the result of a call to 115 | L{compress}, returns an iterator over the uncompressed bytes. 116 | """ 117 | decoder = ByteDecoder() 118 | return decoder.decodefrombytes(compressed_bytes) 119 | 120 | 121 | 122 | 123 | 124 | class ByteEncoder(object): 125 | """ 126 | Takes a stream of uncompressed bytes and produces a stream of 127 | compressed bytes, usable by L{ByteDecoder}. Combines an L{Encoder} 128 | with a L{BitPacker}. 129 | 130 | 131 | >>> import peepdf.lzw 132 | >>> 133 | >>> enc = lzw.ByteEncoder(12) 134 | >>> bigstr = b"gabba gabba yo gabba gabba gabba yo gabba gabba gabba yo gabba gabba gabba yo" 135 | >>> encoding = enc.encodetobytes(bigstr) 136 | >>> encoded = b"".join( b for b in encoding ) 137 | >>> encoded 138 | '3\\x98LF#\\x08\\x82\\x05\\x04\\x83\\x1eM\\xf0x\\x1c\\x16\\x1b\\t\\x88C\\xe1q(4"\\x1f\\x17\\x85C#1X\\xec.\\x00' 139 | >>> 140 | >>> dec = lzw.ByteDecoder() 141 | >>> decoding = dec.decodefrombytes(encoded) 142 | >>> decoded = b"".join(decoding) 143 | >>> decoded == bigstr 144 | True 145 | 146 | """ 147 | 148 | def __init__(self, max_width=DEFAULT_MAX_BITS): 149 | """ 150 | max_width is the maximum width in bits we want to see in the 151 | output stream of codepoints. 152 | """ 153 | self._encoder = Encoder(max_code_size=2**max_width) 154 | self._packer = BitPacker(initial_code_size=self._encoder.code_size()) 155 | 156 | 157 | def encodetobytes(self, bytesource): 158 | """ 159 | Returns an iterator of bytes, adjusting our packed width 160 | between minwidth and maxwidth when it detects an overflow is 161 | about to occur. Dual of L{ByteDecoder.decodefrombytes}. 162 | """ 163 | codepoints = self._encoder.encode(bytesource) 164 | codebytes = self._packer.pack(codepoints) 165 | 166 | return codebytes 167 | 168 | 169 | class ByteDecoder(object): 170 | """ 171 | Decodes, combines bit-unpacking and interpreting a codepoint 172 | stream, suitable for use with bytes generated by 173 | L{ByteEncoder}. 174 | 175 | See L{ByteDecoder} for a usage example. 176 | """ 177 | def __init__(self): 178 | """ 179 | """ 180 | 181 | self._decoder = Decoder() 182 | self._unpacker = BitUnpacker(initial_code_size=self._decoder.code_size()) 183 | self.remaining = [] 184 | 185 | def decodefrombytes(self, bytesource): 186 | """ 187 | Given an iterator over BitPacked, Encoded bytes, Returns an 188 | iterator over the uncompressed bytes. Dual of 189 | L{ByteEncoder.encodetobytes}. See L{ByteEncoder} for an 190 | example of use. 191 | """ 192 | codepoints = self._unpacker.unpack(bytesource) 193 | clearbytes = self._decoder.decode(codepoints) 194 | 195 | return clearbytes 196 | 197 | 198 | class BitPacker(object): 199 | """ 200 | Translates a stream of lzw codepoints into a variable width packed 201 | stream of bytes, for use by L{BitUnpacker}. One of a (potential) 202 | set of encoders for a stream of LZW codepoints, intended to behave 203 | as closely to the TIFF variable-width encoding scheme as closely 204 | as possible. 205 | 206 | The inbound stream of integer lzw codepoints are packed into 207 | variable width bit fields, starting at the smallest number of bits 208 | it can and then increasing the bit width as it anticipates the LZW 209 | code size growing to overflow. 210 | 211 | This class knows all kinds of intimate things about how it's 212 | upstream codepoint processors work; it knows the control codes 213 | CLEAR_CODE and END_OF_INFO_CODE, and (more intimately still), it 214 | makes assumptions about the rate of growth of it's consumer's 215 | codebook. This is ok, as long as the underlying encoder/decoders 216 | don't know any intimate details about their BitPackers/Unpackers 217 | """ 218 | 219 | def __init__(self, initial_code_size): 220 | """ 221 | Takes an initial code book size (that is, the count of known 222 | codes at the beginning of encoding, or after a clear) 223 | """ 224 | self._initial_code_size = initial_code_size 225 | 226 | 227 | def pack(self, codepoints): 228 | """ 229 | Given an iterator of integer codepoints, returns an iterator 230 | over bytes containing the codepoints packed into varying 231 | lengths, with bit width growing to accomodate an input code 232 | that it assumes will grow by one entry per codepoint seen. 233 | 234 | Widths will be reset to the given initial_code_size when the 235 | LZW CLEAR_CODE or END_OF_INFO_CODE code appears in the input, 236 | and bytes following END_OF_INFO_CODE will be aligned to the 237 | next byte boundary. 238 | 239 | >>> import peepdf.lzw 240 | >>> pkr = lzw.BitPacker(258) 241 | >>> [ b for b in pkr.pack([ 1, 257]) ] == [ chr(0), chr(0xC0), chr(0x40) ] 242 | True 243 | """ 244 | tailbits = [] 245 | codesize = self._initial_code_size 246 | 247 | minwidth = 8 248 | while (1 << minwidth) < codesize: 249 | minwidth = minwidth + 1 250 | 251 | nextwidth = minwidth 252 | 253 | for pt in codepoints: 254 | 255 | newbits = inttobits(pt, nextwidth) 256 | tailbits = tailbits + newbits 257 | 258 | # PAY ATTENTION. This calculation should be driven by the 259 | # size of the upstream codebook, right now we're just trusting 260 | # that everybody intends to follow the TIFF spec. 261 | codesize = codesize + 1 262 | if pt == END_OF_INFO_CODE: 263 | while len(tailbits) % 8: 264 | tailbits.append(0) 265 | 266 | if pt in [ CLEAR_CODE, END_OF_INFO_CODE ]: 267 | nextwidth = minwidth 268 | codesize = self._initial_code_size 269 | elif codesize >= (2 ** nextwidth): 270 | nextwidth = nextwidth + 1 271 | 272 | while len(tailbits) > 8: 273 | nextbits = tailbits[:8] 274 | nextbytes = bitstobytes(nextbits) 275 | for bt in nextbytes: 276 | yield struct.pack("B", bt) 277 | 278 | tailbits = tailbits[8:] 279 | 280 | 281 | if tailbits: 282 | tail = bitstobytes(tailbits) 283 | for bt in tail: 284 | yield struct.pack("B", bt) 285 | 286 | 287 | 288 | 289 | class BitUnpacker(object): 290 | """ 291 | An adaptive-width bit unpacker, intended to decode streams written 292 | by L{BitPacker} into integer codepoints. Like L{BitPacker}, knows 293 | about code size changes and control codes. 294 | """ 295 | 296 | def __init__(self, initial_code_size): 297 | """ 298 | initial_code_size is the starting size of the codebook 299 | associated with the to-be-unpacked stream. 300 | """ 301 | self._initial_code_size = initial_code_size 302 | 303 | 304 | def unpack(self, bytesource): 305 | """ 306 | Given an iterator of bytes, returns an iterator of integer 307 | code points. Auto-magically adjusts point width when it sees 308 | an almost-overflow in the input stream, or an LZW CLEAR_CODE 309 | or END_OF_INFO_CODE 310 | 311 | Trailing bits at the end of the given iterator, after the last 312 | codepoint, will be dropped on the floor. 313 | 314 | At the end of the iteration, or when an END_OF_INFO_CODE seen 315 | the unpacker will ignore the bits after the code until it 316 | reaches the next aligned byte. END_OF_INFO_CODE will *not* 317 | stop the generator, just reset the alignment and the width 318 | 319 | 320 | >>> import peepdf.lzw 321 | >>> unpk = lzw.BitUnpacker(initial_code_size=258) 322 | >>> [ i for i in unpk.unpack([ chr(0), chr(0xC0), chr(0x40) ]) ] 323 | [1, 257] 324 | """ 325 | bits = [] 326 | offset = 0 327 | ignore = 0 328 | 329 | codesize = self._initial_code_size 330 | minwidth = 8 331 | while (1 << minwidth) < codesize: 332 | minwidth = minwidth + 1 333 | 334 | pointwidth = minwidth 335 | 336 | for nextbit in bytestobits(bytesource): 337 | 338 | offset = (offset + 1) % 8 339 | if ignore > 0: 340 | ignore = ignore - 1 341 | continue 342 | 343 | bits.append(nextbit) 344 | 345 | if len(bits) == pointwidth: 346 | codepoint = intfrombits(bits) 347 | bits = [] 348 | 349 | yield codepoint 350 | 351 | codesize = codesize + 1 352 | 353 | if codepoint in [ CLEAR_CODE, END_OF_INFO_CODE ]: 354 | codesize = self._initial_code_size 355 | pointwidth = minwidth 356 | else: 357 | # is this too late? 358 | while codesize >= (2 ** pointwidth): 359 | pointwidth = pointwidth + 1 360 | 361 | if codepoint == END_OF_INFO_CODE: 362 | ignore = (8 - offset) % 8 363 | 364 | 365 | 366 | class Decoder(object): 367 | """ 368 | Uncompresses a stream of lzw code points, as created by 369 | L{Encoder}. Given a list of integer code points, with all 370 | unpacking foolishness complete, turns that list of codepoints into 371 | a list of uncompressed bytes. See L{BitUnpacker} for what this 372 | doesn't do. 373 | """ 374 | def __init__(self): 375 | """ 376 | Creates a new Decoder. Decoders should not be reused for 377 | different streams. 378 | """ 379 | self._clear_codes() 380 | self.remainder = [] 381 | 382 | 383 | def code_size(self): 384 | """ 385 | Returns the current size of the Decoder's code book, that is, 386 | it's mapping of codepoints to byte strings. The return value of 387 | this method will change as the decode encounters more encoded 388 | input, or control codes. 389 | """ 390 | return len(self._codepoints) 391 | 392 | 393 | def decode(self, codepoints): 394 | """ 395 | Given an iterable of integer codepoints, yields the 396 | corresponding bytes, one at a time, as byte strings of length 397 | E{1}. Retains the state of the codebook from call to call, so 398 | if you have another stream, you'll likely need another 399 | decoder! 400 | 401 | Decoders will NOT handle END_OF_INFO_CODE (rather, they will 402 | handle the code by throwing an exception); END_OF_INFO should 403 | be handled by the upstream codepoint generator (see 404 | L{BitUnpacker}, for example) 405 | 406 | >>> import peepdf.lzw 407 | >>> dec = lzw.Decoder() 408 | >>> ''.join(dec.decode([103, 97, 98, 98, 97, 32, 258, 260, 262, 121, 111, 263, 259, 261, 256])) 409 | 'gabba gabba yo gabba' 410 | 411 | """ 412 | codepoints = [ cp for cp in codepoints ] 413 | 414 | for cp in codepoints: 415 | decoded = self._decode_codepoint(cp) 416 | for character in decoded: 417 | yield character 418 | 419 | 420 | 421 | def _decode_codepoint(self, codepoint): 422 | """ 423 | Will raise a ValueError if given an END_OF_INFORMATION 424 | code. EOI codes should be handled by callers if they're 425 | present in our source stream. 426 | 427 | >>> import peepdf.lzw 428 | >>> dec = lzw.Decoder() 429 | >>> beforesize = dec.code_size() 430 | >>> dec._decode_codepoint(0x80) 431 | '\\x80' 432 | >>> dec._decode_codepoint(0x81) 433 | '\\x81' 434 | >>> beforesize + 1 == dec.code_size() 435 | True 436 | >>> dec._decode_codepoint(256) 437 | '' 438 | >>> beforesize == dec.code_size() 439 | True 440 | """ 441 | 442 | ret = "" 443 | 444 | if codepoint == CLEAR_CODE: 445 | self._clear_codes() 446 | elif codepoint == END_OF_INFO_CODE: 447 | pass 448 | #raise ValueError("End of information code not supported directly by this Decoder") 449 | else: 450 | if codepoint in self._codepoints: 451 | ret = self._codepoints[ codepoint ] 452 | if None != self._prefix: 453 | self._codepoints[ len(self._codepoints) ] = self._prefix + ret[0] 454 | 455 | else: 456 | ret = self._prefix + self._prefix[0] 457 | self._codepoints[ len(self._codepoints) ] = ret 458 | 459 | self._prefix = ret 460 | 461 | return ret 462 | 463 | 464 | def _clear_codes(self): 465 | self._codepoints = dict( (pt, struct.pack("B", pt)) for pt in range(256) ) 466 | self._codepoints[CLEAR_CODE] = CLEAR_CODE 467 | self._codepoints[END_OF_INFO_CODE] = END_OF_INFO_CODE 468 | self._prefix = None 469 | 470 | 471 | class Encoder(object): 472 | """ 473 | Given an iterator of bytes, returns an iterator of integer 474 | codepoints, suitable for use by L{Decoder}. The core of the 475 | "compression" side of lzw compression/decompression. 476 | """ 477 | def __init__(self, max_code_size=(2**DEFAULT_MAX_BITS)): 478 | """ 479 | When the encoding codebook grows larger than max_code_size, 480 | the Encoder will clear its codebook and emit a CLEAR_CODE 481 | """ 482 | 483 | self.closed = False 484 | 485 | self._max_code_size = max_code_size 486 | self._buffer = '' 487 | self._clear_codes() 488 | 489 | if max_code_size < self.code_size(): 490 | raise ValueError("Max code size too small, (must be at least {0})".format(self.code_size())) 491 | 492 | 493 | def code_size(self): 494 | """ 495 | Returns a count of the known codes, including codes that are 496 | implicit in the data but have not yet been produced by the 497 | iterator. 498 | """ 499 | return len(self._prefixes) 500 | 501 | 502 | def flush(self): 503 | """ 504 | Yields any buffered codepoints, followed by a CLEAR_CODE, and 505 | clears the codebook as a side effect. 506 | """ 507 | 508 | flushed = [] 509 | 510 | if self._buffer: 511 | yield self._prefixes[ self._buffer ] 512 | self._buffer = '' 513 | 514 | yield CLEAR_CODE 515 | self._clear_codes() 516 | 517 | 518 | 519 | 520 | def encode(self, bytesource): 521 | """ 522 | Given an iterator over bytes, yields the 523 | corresponding stream of codepoints. 524 | Will clear the codes at the end of the stream. 525 | 526 | >>> import lzw 527 | >>> enc = lzw.Encoder() 528 | >>> [ cp for cp in enc.encode("gabba gabba yo gabba") ] 529 | [103, 97, 98, 98, 97, 32, 258, 260, 262, 121, 111, 263, 259, 261, 256] 530 | 531 | Modified by Jose Miguel Esparza to add support for PDF files encoding 532 | """ 533 | yield CLEAR_CODE 534 | for b in bytesource: 535 | for point in self._encode_byte(b): 536 | yield point 537 | 538 | if self.code_size() >= self._max_code_size: 539 | for pt in self.flush(): 540 | yield pt 541 | 542 | yield self._prefixes[self._buffer] 543 | yield END_OF_INFO_CODE 544 | 545 | 546 | def _encode_byte(self, byte): 547 | # Yields one or zero bytes, AND changes the internal state of 548 | # the codebook and prefix buffer. 549 | # 550 | # Unless you're in self.encode(), you almost certainly don't 551 | # want to call this. 552 | 553 | new_prefix = self._buffer 554 | 555 | if new_prefix + byte in self._prefixes: 556 | new_prefix = new_prefix + byte 557 | elif new_prefix: 558 | encoded = self._prefixes[ new_prefix ] 559 | self._add_code(new_prefix + byte) 560 | new_prefix = byte 561 | 562 | yield encoded 563 | 564 | self._buffer = new_prefix 565 | 566 | 567 | 568 | 569 | def _clear_codes(self): 570 | 571 | # Teensy hack, CLEAR_CODE and END_OF_INFO_CODE aren't 572 | # equal to any possible string. 573 | 574 | self._prefixes = dict( (struct.pack("B", codept), codept) for codept in range(256) ) 575 | self._prefixes[ CLEAR_CODE ] = CLEAR_CODE 576 | self._prefixes[ END_OF_INFO_CODE ] = END_OF_INFO_CODE 577 | 578 | 579 | def _add_code(self, newstring): 580 | self._prefixes[ newstring ] = len(self._prefixes) 581 | 582 | 583 | 584 | class PagingEncoder(object): 585 | """ 586 | UNTESTED. Handles encoding of multiple chunks or streams of encodable data, 587 | separated with control codes. Dual of PagingDecoder. 588 | """ 589 | def __init__(self, initial_code_size, max_code_size): 590 | self._initial_code_size = initial_code_size 591 | self._max_code_size = max_code_size 592 | 593 | 594 | def encodepages(self, pages): 595 | """ 596 | Given an iterator of iterators of bytes, produces a single 597 | iterator containing a delimited sequence of independantly 598 | compressed LZW sequences, all beginning on a byte-aligned 599 | spot, all beginning with a CLEAR code and all terminated with 600 | an END_OF_INFORMATION code (and zero to seven trailing junk 601 | bits.) 602 | 603 | The dual of PagingDecoder.decodepages 604 | 605 | >>> import peepdf.lzw 606 | >>> enc = lzw.PagingEncoder(257, 2**12) 607 | >>> coded = enc.encodepages([ "say hammer yo hammer mc hammer go hammer", 608 | ... "and the rest can go and play", 609 | ... "can't touch this" ]) 610 | ... 611 | >>> b"".join(coded) 612 | '\\x80\\x1c\\xcc\\'\\x91\\x01\\xa0\\xc2m6\\x99NB\\x03\\xc9\\xbe\\x0b\\x07\\x84\\xc2\\xcd\\xa68|"\\x14 3\\xc3\\xa0\\xd1c\\x94\\x02\\x02\\x80\\x18M\\xc6A\\x01\\xd0\\xd0e\\x10\\x1c\\x8c\\xa73\\xa0\\x80\\xc7\\x02\\x10\\x19\\xcd\\xe2\\x08\\x14\\x10\\xe0l0\\x9e`\\x10\\x10\\x80\\x18\\xcc&\\xe19\\xd0@t7\\x9dLf\\x889\\xa0\\xd2s\\x80@@' 613 | 614 | """ 615 | 616 | for page in pages: 617 | 618 | encoder = Encoder(max_code_size=self._max_code_size) 619 | codepoints = encoder.encode(page) 620 | codes_and_eoi = itertools.chain([ CLEAR_CODE ], codepoints, [ END_OF_INFO_CODE ]) 621 | 622 | packer = BitPacker(initial_code_size=encoder.code_size()) 623 | packed = packer.pack(codes_and_eoi) 624 | 625 | for byte in packed: 626 | yield byte 627 | 628 | 629 | 630 | 631 | class PagingDecoder(object): 632 | """ 633 | UNTESTED. Dual of PagingEncoder, knows how to handle independantly encoded, 634 | END_OF_INFO_CODE delimited chunks of an inbound byte stream 635 | """ 636 | 637 | def __init__(self, initial_code_size): 638 | self._initial_code_size = initial_code_size 639 | self._remains = [] 640 | 641 | def next_page(self, codepoints): 642 | """ 643 | Iterator over the next page of codepoints. 644 | """ 645 | self._remains = [] 646 | 647 | try: 648 | while 1: 649 | cp = next(codepoints) 650 | if cp != END_OF_INFO_CODE: 651 | yield cp 652 | else: 653 | self._remains = codepoints 654 | break 655 | 656 | except StopIteration: 657 | pass 658 | 659 | 660 | def decodepages(self, bytesource): 661 | """ 662 | Takes an iterator of bytes, returns an iterator of iterators 663 | of uncompressed data. Expects input to conform to the output 664 | conventions of PagingEncoder(), in particular that "pages" are 665 | separated with an END_OF_INFO_CODE and padding up to the next 666 | byte boundary. 667 | 668 | BUG: Dangling trailing page on decompression. 669 | 670 | >>> import peepdf.lzw 671 | >>> pgdec = lzw.PagingDecoder(initial_code_size=257) 672 | >>> pgdecoded = pgdec.decodepages( 673 | ... ''.join([ '\\x80\\x1c\\xcc\\'\\x91\\x01\\xa0\\xc2m6', 674 | ... '\\x99NB\\x03\\xc9\\xbe\\x0b\\x07\\x84\\xc2', 675 | ... '\\xcd\\xa68|"\\x14 3\\xc3\\xa0\\xd1c\\x94', 676 | ... '\\x02\\x02\\x80\\x18M\\xc6A\\x01\\xd0\\xd0e', 677 | ... '\\x10\\x1c\\x8c\\xa73\\xa0\\x80\\xc7\\x02\\x10', 678 | ... '\\x19\\xcd\\xe2\\x08\\x14\\x10\\xe0l0\\x9e`\\x10', 679 | ... '\\x10\\x80\\x18\\xcc&\\xe19\\xd0@t7\\x9dLf\\x889', 680 | ... '\\xa0\\xd2s\\x80@@' ]) 681 | ... ) 682 | >>> [ b"".join(pg) for pg in pgdecoded ] 683 | ['say hammer yo hammer mc hammer go hammer', 'and the rest can go and play', "can't touch this", ''] 684 | 685 | """ 686 | 687 | # TODO: WE NEED A CODE SIZE POLICY OBJECT THAT ISN'T THIS. 688 | # honestly, we should have a "codebook" object we need to pass 689 | # to bit packing/unpacking tools, etc, such that we don't have 690 | # to roll all of these code size assumptions everyplace. 691 | 692 | unpacker = BitUnpacker(initial_code_size=self._initial_code_size) 693 | codepoints = unpacker.unpack(bytesource) 694 | 695 | self._remains = codepoints 696 | while self._remains: 697 | nextpoints = self.next_page(self._remains) 698 | nextpoints = [ nx for nx in nextpoints ] 699 | 700 | decoder = Decoder() 701 | decoded = decoder.decode(nextpoints) 702 | decoded = [ dec for dec in decoded ] 703 | 704 | yield decoded 705 | 706 | 707 | 708 | ######################################### 709 | # Conveniences. 710 | 711 | 712 | # PYTHON V2 713 | def unpackbyte(b): 714 | """ 715 | Given a one-byte long byte string, returns an integer. Equivalent 716 | to struct.unpack("B", b) 717 | """ 718 | (ret,) = struct.unpack("B", b) 719 | return ret 720 | 721 | 722 | # PYTHON V3 723 | # def unpackbyte(b): return b 724 | 725 | 726 | def filebytes(fileobj, buffersize=1024): 727 | """ 728 | Convenience for iterating over the bytes in a file. Given a 729 | file-like object (with a read(int) method), returns an iterator 730 | over the bytes of that file. 731 | """ 732 | buff = fileobj.read(buffersize) 733 | while buff: 734 | for byte in buff: yield byte 735 | buff = fileobj.read(buffersize) 736 | 737 | 738 | def readbytes(filename, buffersize=1024): 739 | """ 740 | Opens a file named by filename and iterates over the L{filebytes} 741 | found therein. Will close the file when the bytes run out. 742 | """ 743 | infile = open(filename, "rb") 744 | for byte in filebytes(infile, buffersize): 745 | yield byte 746 | 747 | 748 | 749 | def writebytes(filename, bytesource): 750 | """ 751 | Convenience for emitting the bytes we generate to a file. Given a 752 | filename, opens and truncates the file, dumps the bytes 753 | from bytesource into it, and closes it 754 | """ 755 | 756 | outfile = open(filename, "wb") 757 | for bt in bytesource: 758 | outfile.write(bt) 759 | 760 | 761 | def inttobits(anint, width=None): 762 | """ 763 | Produces an array of booleans representing the given argument as 764 | an unsigned integer, MSB first. If width is given, will pad the 765 | MSBs to the given width (but will NOT truncate overflowing 766 | results) 767 | 768 | >>> import peepdf.lzw 769 | >>> lzw.inttobits(304, width=16) 770 | [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0] 771 | 772 | """ 773 | remains = anint 774 | retreverse = [] 775 | while remains: 776 | retreverse.append(remains & 1) 777 | remains = remains >> 1 778 | 779 | retreverse.reverse() 780 | 781 | ret = retreverse 782 | if None != width: 783 | ret_head = [ 0 ] * (width - len(ret)) 784 | ret = ret_head + ret 785 | 786 | return ret 787 | 788 | 789 | def intfrombits(bits): 790 | """ 791 | Given a list of boolean values, interprets them as a binary 792 | encoded, MSB-first unsigned integer (with True == 1 and False 793 | == 0) and returns the result. 794 | 795 | >>> import peepdf.lzw 796 | >>> lzw.intfrombits([ 1, 0, 0, 1, 1, 0, 0, 0, 0 ]) 797 | 304 798 | """ 799 | ret = 0 800 | lsb_first = [ b for b in bits ] 801 | lsb_first.reverse() 802 | 803 | for bit_index in range(len(lsb_first)): 804 | if lsb_first[ bit_index ]: 805 | ret = ret | (1 << bit_index) 806 | 807 | return ret 808 | 809 | 810 | def bytestobits(bytesource): 811 | """ 812 | Breaks a given iterable of bytes into an iterable of boolean 813 | values representing those bytes as unsigned integers. 814 | 815 | >>> import peepdf.lzw 816 | >>> [ x for x in lzw.bytestobits(b"\\x01\\x30") ] 817 | [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0] 818 | """ 819 | for b in bytesource: 820 | 821 | value = unpackbyte(b) 822 | 823 | for bitplusone in range(8, 0, -1): 824 | bitindex = bitplusone - 1 825 | nextbit = 1 & (value >> bitindex) 826 | yield nextbit 827 | 828 | 829 | def bitstobytes(bits): 830 | """ 831 | Interprets an indexable list of booleans as bits, MSB first, to be 832 | packed into a list of integers from 0 to 256, MSB first, with LSBs 833 | zero-padded. Note this padding behavior means that round-trips of 834 | bytestobits(bitstobytes(x, width=W)) may not yield what you expect 835 | them to if W % 8 != 0 836 | 837 | Does *NOT* pack the returned values into a bytearray or the like. 838 | 839 | >>> import peepdf.lzw 840 | >>> bitstobytes([0, 0, 0, 0, 0, 0, 0, 0, "Yes, I'm True"]) == [ 0x00, 0x80 ] 841 | True 842 | >>> bitstobytes([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0]) == [ 0x01, 0x30 ] 843 | True 844 | """ 845 | ret = [] 846 | nextbyte = 0 847 | nextbit = 7 848 | for bit in bits: 849 | if bit: 850 | nextbyte = nextbyte | (1 << nextbit) 851 | 852 | if nextbit: 853 | nextbit = nextbit - 1 854 | else: 855 | ret.append(nextbyte) 856 | nextbit = 7 857 | nextbyte = 0 858 | 859 | if nextbit < 7: ret.append(nextbyte) 860 | return ret 861 | 862 | 863 | 864 | 865 | ''' 866 | The code below is part of pdfminer (http://pypi.python.org/pypi/pdfminer/) 867 | 868 | Copyright (c) 2004-2010 Yusuke Shinyama 869 | 870 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 871 | 872 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 873 | 874 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 875 | ''' 876 | 877 | import sys 878 | 879 | from io import StringIO 880 | 881 | ## LZWDecoder 882 | ## 883 | class LZWDecoder(object): 884 | 885 | debug = 0 886 | 887 | def __init__(self, fp): 888 | self.fp = fp 889 | self.buff = 0 890 | self.bpos = 8 891 | self.nbits = 9 892 | self.table = None 893 | self.prevbuf = None 894 | return 895 | 896 | def readbits(self, bits): 897 | v = 0 898 | while 1: 899 | # the number of remaining bits we can get from the current buffer. 900 | r = 8-self.bpos 901 | if bits <= r: 902 | # |-----8-bits-----| 903 | # |-bpos-|-bits-| | 904 | # | |----r----| 905 | v = (v<>(r-bits)) & ((1<>> lzwdecode('\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01') 966 | '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42' 967 | """ 968 | fp = StringIO(data) 969 | return ''.join(LZWDecoder(fp).run()) 970 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name="peepdf", 5 | version="0.4.3", 6 | author="Jose Miguel Esparza", 7 | license="GNU GPLv3", 8 | url="http://eternal-todo.com", 9 | install_requires=[ 10 | "jsbeautifier==1.14.3", 11 | "colorama==0.4.4", 12 | "future>=0.18.2", 13 | "Pillow==9.1.0", 14 | "pythonaes==1.0", 15 | ], 16 | entry_points={ 17 | "console_scripts": [ 18 | "peepdf = peepdf.main:main", 19 | ], 20 | }, 21 | packages=[ 22 | "peepdf", 23 | ], 24 | ) 25 | -------------------------------------------------------------------------------- /tests/files/BB-1-Overview.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hatching/peepdf/f6428ac1acc922b7e5fe69a756e2306a059919c7/tests/files/BB-1-Overview.pdf -------------------------------------------------------------------------------- /tests/files/js_in_pdf.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hatching/peepdf/f6428ac1acc922b7e5fe69a756e2306a059919c7/tests/files/js_in_pdf.js -------------------------------------------------------------------------------- /tests/files/phishing0.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hatching/peepdf/f6428ac1acc922b7e5fe69a756e2306a059919c7/tests/files/phishing0.pdf -------------------------------------------------------------------------------- /tests/files/worldreport.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hatching/peepdf/f6428ac1acc922b7e5fe69a756e2306a059919c7/tests/files/worldreport.pdf -------------------------------------------------------------------------------- /tests/test_pee.py: -------------------------------------------------------------------------------- 1 | # peepdf is a tool to analyse and modify PDF files 2 | # http://peepdf.eternal-todo.com 3 | # By Jose Miguel Esparza 4 | # 5 | # Copyright (C) 2016 Jose Miguel Esparza 6 | # 7 | # This file is part of peepdf. 8 | # 9 | # peepdf is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # peepdf is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with peepdf. If not, see . 21 | # 22 | 23 | import mock 24 | import pytest 25 | import time 26 | 27 | import peepdf 28 | import peepdf.main 29 | 30 | def test_js_detect(): 31 | p = peepdf.PDFCore.PDFParser() 32 | r, f = p.parse( 33 | "tests/files/js_in_pdf.js", forceMode=True, 34 | looseMode=True, manualAnalysis=False 35 | ) 36 | assert not r 37 | 38 | for version in range(f.updates + 1): 39 | for obj in f.body[version].objects.values(): 40 | if isinstance(obj, peepdf.PDFCore.PDFIndirectObject): 41 | o = obj.getObject() 42 | if isinstance(o, peepdf.PDFCore.PDFStream): 43 | stream = o.decodedStream 44 | isJS = peepdf.JSAnalysis.isJavascript(stream) 45 | if "function docOpened()" in stream: 46 | assert isJS 47 | else: 48 | assert not isJS 49 | 50 | def test_whitespace_after_opening(): 51 | p = peepdf.PDFCore.PDFParser() 52 | r, f = p.parse( 53 | "tests/files/BB-1-Overview.pdf", 54 | forceMode=True, looseMode=True, manualAnalysis=False 55 | ) 56 | assert not r 57 | 58 | for obj in f.body[1].objects.values(): 59 | if obj.object.type == "stream": 60 | assert obj.object.errors != [ 61 | "Decoding error: Error decompressing string" 62 | ] 63 | 64 | def test_lxml_missing(): 65 | with mock.patch.dict(peepdf.main.__dict__, {"etree": None}): 66 | with pytest.raises(AssertionError) as e: 67 | peepdf.main.getPeepXML(None, None, None) 68 | e.match("lxml must be installed") 69 | 70 | def test_quickish_isjs(): 71 | t = time.time() 72 | peepdf.PDFCore.PDFParser().parse( 73 | "tests/files/phishing0.pdf", forceMode=True, 74 | looseMode=True, manualAnalysis=False 75 | ) 76 | # Should take no more than 2 seconds (in 0.3.5 this would take >5 seconds). 77 | assert time.time() - t < 2 78 | 79 | def test_ignore_ghostscript(): 80 | t = time.time() 81 | peepdf.PDFCore.PDFParser().parse( 82 | "tests/files/worldreport.pdf", forceMode=True, 83 | looseMode=True, manualAnalysis=False 84 | ) 85 | # Should take less than 20 seconds (in 0.4.1 this would take >1 minute). 86 | assert time.time() - t < 20 87 | --------------------------------------------------------------------------------