├── README.md ├── pdf_obj_hash.py ├── LICENSE ├── pdf_param_parser.py └── pdf_lib.py /README.md: -------------------------------------------------------------------------------- 1 | # pdf-tools 2 | PDF tools and libraries 3 | 4 | 5 | Starting with a generic python library. I wanted this to help streamline creating rules and identifying what is weird about a PDF. 6 | 7 | ## pdf_obj_hash.py 8 | Command line tool to generate the PDF object hash of a given PDF. Also supports scanning an entire directory. 9 | 10 | ``` 11 | usage: pdf_obj_hash_v2.py [-h] [-f FILE] [-d DIR] [--ftrace] [--debug] [--time-trace] [--print-hash-string] [--hunt-string HUNT_STRING] [--print-info] 12 | 13 | Generate a PDF Object Hash of the provided file or files. 14 | 15 | options: 16 | -h, --help show this help message and exit 17 | -f FILE, --file FILE file to parse 18 | -d DIR, --dir DIR directory to scan for PDFs 19 | --ftrace DEBUG: prints functions as they're called 20 | --debug DEBUG: prints mid-function debug info 21 | --time-trace DEBUG: time the individual regex scans in the run. 22 | --print-hash-string print the hash string instead of the obj hash 23 | --hunt-string HUNT_STRING 24 | hunt for a complete or partial hash string ("Catalog|Producer|Pages|Page|None|Length") 25 | --print-info kinda debug, print object and object number 26 | 27 | 28 | ``` 29 | 30 | ## What is a PDF Object Hash? 31 | PDF Object Hash is a way to identifying similarities between PDFs without relying on the _content_ of the document. With object hashing we can identify the structure or skeleton of the document. Think of this as similar to an imphash or a ja3 hash. We extract out the object type and hash those to generate the hash. This allows us to quickly cluster similar documents and helps with identifying overlaps in disparate files. 32 | 33 | Recent updates to `pdf_obj_hash.py` and `pdf_lib.py` change how we parse objects, which should allow for better and more accurate parsing. This should (and in testing does) give us better results when dealing with "weird" pdfs (such as invalid xref entries). 34 | 35 | ## pdf_lib.py 36 | This is a python library for analyzing PDFs. 37 | 38 | Current features: 39 | - parse xref table, xref streams, objects, stream objects, etc. 40 | - extract stream content 41 | - search object by object number, type, or some parameters 42 | 43 | Wish list: 44 | - can we follow a chain of objects/ref objects? I don't remember if I added that or not. -------------------------------------------------------------------------------- /pdf_obj_hash.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from pdf_lib import pdf_object as po 4 | import argparse 5 | import glob 6 | import os 7 | import time 8 | import hashlib 9 | 10 | class pdf_tester(): 11 | def __init__(self): 12 | self.args = pdf_tester.parse_arguments() 13 | self.pdf_object = None 14 | 15 | def generate_file_list(self): 16 | file_list = [] 17 | if self.args.dir and self.args.file: 18 | print("[-] ERROR: Cannot set both --dir and --file") 19 | if self.args.file: 20 | return [self.args.file] 21 | if self.args.dir: 22 | if self.args.dir == ".": 23 | flist = glob.glob('*') 24 | elif self.args.dir[-1] != "/": 25 | flist = glob.glob(self.args.dir + "/*") 26 | else: 27 | flist = glob.glob(self.args.dir + "*") 28 | if flist: 29 | for f in flist: 30 | if os.path.isfile(f): 31 | self.pdf_object = po(f) 32 | if self.pdf_object.check_pdf_header(): 33 | file_list.append(f) 34 | return file_list 35 | 36 | @staticmethod 37 | def parse_arguments(): 38 | argparser = argparse.ArgumentParser(description="Generate a PDF Object Hash of the provided file or files.") 39 | argparser.add_argument("-f", "--file", help = "file to parse") 40 | argparser.add_argument("-d", "--dir", help = "directory to scan for PDFs") 41 | argparser.add_argument("--ftrace", help="DEBUG: prints functions as they're called", dest="ftrace", action="store_true") 42 | argparser.add_argument("--debug", help="DEBUG: prints mid-function debug info", dest="debug", action="store_true") 43 | argparser.add_argument("--time-trace", help="DEBUG: time the individual regex scans in the run.", dest="timedebug", action="store_true") 44 | argparser.add_argument("--print-hash-string", help="print the hash string instead of the obj hash", dest="print_hash_string", action="store_true") 45 | argparser.add_argument("--hunt-string", help="hunt for a complete or partial hash string (\"Catalog|Producer|Pages|Page|None|Length\")", type=str, dest="hunt_string", action="store") 46 | argparser.add_argument("--print-info", dest='info', help="kinda debug, print object and object number", action="store_true") 47 | args = argparser.parse_args() 48 | return args 49 | 50 | 51 | 52 | if __name__ == "__main__": 53 | pdf = pdf_tester() 54 | file_list = pdf.generate_file_list() 55 | for f in file_list: 56 | start = time.time() 57 | #print(f"------ Parsing {f} ------") 58 | pdf.pdf_object = po(f) 59 | if pdf.args.ftrace: 60 | pdf.pdf_object.func_trace = True 61 | if pdf.args.debug: 62 | pdf.pdf_object.debug = True 63 | if pdf.args.timedebug: 64 | pdf.pdf_object.timedbg = True 65 | # starting the pdf lib process: 66 | pdf.pdf_object.check_pdf_header() 67 | pdf.pdf_object.trailer_process() 68 | pdf.pdf_object.start_object_parsing() 69 | pdf.pdf_object.pull_objects_xref_aware() 70 | runtime = time.time() - start 71 | obj_hash_str = "" 72 | file_ordered_objects = pdf.pdf_object.get_objects_by_file_order(in_use_only=True) 73 | for item in file_ordered_objects: 74 | #for item in pdf.pdf_object.obj_dicts: 75 | obj_hash_str += item["object_type"] + "|" 76 | if pdf.args.info: 77 | print(item) 78 | #print(f"{item['object_number']} - {item['object_type']}") 79 | if pdf.args.hunt_string: 80 | if pdf.args.hunt_string == obj_hash_str: 81 | print(f"[100% match]:{pdf.pdf_object.sha256},{obj_hash_str}") 82 | elif pdf.args.hunt_string in obj_hash_str: 83 | print(f"[partial match]:{pdf.pdf_object.sha256},{obj_hash_str}") 84 | elif pdf.args.print_hash_string: 85 | print(f"{pdf.pdf_object.sha256},{obj_hash_str},{runtime}") 86 | else: 87 | obj_hash = hashlib.md5(obj_hash_str.encode()).hexdigest() 88 | print(f"{pdf.pdf_object.sha256},{obj_hash},{runtime}") 89 | if pdf.args.debug: 90 | print(f"Object Count: {len(pdf.pdf_object.object_offset_list)} // runtime: {runtime}") 91 | print(f"xref entries: {pdf.pdf_object.xref_entries}") 92 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /pdf_param_parser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | windsurf helped with this code, testing it out. 4 | """ 5 | 6 | 7 | class pdf_param_parser: 8 | def __init__(self, data): 9 | self.data = data 10 | self.pos = 0 11 | self.length = len(data) 12 | 13 | def skip_whitespace(self): 14 | """Skip whitespace characters""" 15 | while self.pos < self.length and self.data[self.pos] in b' \t\n\r\f\0': 16 | self.pos += 1 17 | 18 | def get_current_char(self): 19 | """Get current character or None if at end""" 20 | if self.pos < self.length: 21 | return self.data[self.pos] 22 | return None 23 | 24 | def parse_name(self): 25 | """Parse a PDF name object (starts with /)""" 26 | if self.get_current_char() != ord(b'/'): 27 | return None 28 | 29 | self.pos += 1 # Skip the '/' 30 | start = self.pos 31 | 32 | while self.pos < self.length: 33 | c = self.data[self.pos] 34 | # End of name on delimiter 35 | if c in b' \t\n\r\f\0()<>[]{}/%': 36 | break 37 | # Handle #-escaped characters 38 | if c == ord(b'#'): 39 | if self.pos + 2 >= self.length: 40 | break 41 | self.pos += 3 # Skip the # and two hex digits 42 | continue 43 | self.pos += 1 44 | 45 | return self.data[start:self.pos].decode('latin-1') 46 | 47 | def parse_value(self): 48 | """Parse a PDF value (dictionary, array, string, number, name, boolean, null)""" 49 | self.skip_whitespace() 50 | if self.pos >= self.length: 51 | return None 52 | 53 | c = self.get_current_char() 54 | 55 | # Dictionary 56 | if c == ord(b'<') and self.pos + 1 < self.length and self.data[self.pos + 1] == ord(b'<'): 57 | return self.parse_dictionary() 58 | # Array 59 | elif c == ord(b'['): 60 | return self.parse_array() 61 | # String (hex) 62 | elif c == ord(b'<'): 63 | return self.parse_hex_string() 64 | # String (literal) 65 | elif c == ord(b'('): 66 | return self.parse_literal_string() 67 | # Name 68 | elif c == ord(b'/'): 69 | return self.parse_name() 70 | # Number or boolean/null 71 | elif c in b'-+0123456789.': 72 | return self.parse_number_or_ref() 73 | # Boolean or null 74 | elif c in b'tfn': 75 | return self.parse_keyword() 76 | 77 | return None 78 | 79 | def parse_dictionary(self): 80 | """Parse a PDF dictionary""" 81 | if self.data[self.pos:self.pos+2] != b'<<': 82 | return None 83 | 84 | self.pos += 2 85 | result = {} 86 | 87 | while True: 88 | self.skip_whitespace() 89 | if self.pos >= self.length: 90 | break 91 | 92 | # Check for end of dictionary 93 | if self.data[self.pos:self.pos+2] == b'>>': 94 | self.pos += 2 95 | break 96 | 97 | # Parse key (must be a name) 98 | key = self.parse_name() 99 | if key is None: 100 | break 101 | 102 | # Parse value 103 | value = self.parse_value() 104 | if value is not None: 105 | result[key] = value 106 | 107 | return result 108 | 109 | def parse_array(self): 110 | """Parse a PDF array""" 111 | if self.get_current_char() != ord(b'['): 112 | return None 113 | 114 | self.pos += 1 115 | result = [] 116 | 117 | while True: 118 | self.skip_whitespace() 119 | if self.pos >= self.length: 120 | break 121 | 122 | # Check for end of array 123 | if self.get_current_char() == ord(b']'): 124 | self.pos += 1 125 | break 126 | 127 | # Parse array element 128 | value = self.parse_value() 129 | if value is not None: 130 | result.append(value) 131 | else: 132 | break 133 | 134 | return result 135 | 136 | def parse_literal_string(self): 137 | """Parse a literal string (enclosed in parentheses)""" 138 | if self.get_current_char() != ord(b'('): 139 | return None 140 | 141 | self.pos += 1 142 | depth = 1 143 | start = self.pos 144 | result = [] 145 | 146 | while self.pos < self.length: 147 | c = self.get_current_char() 148 | 149 | if c == ord(b'\\'): # Escape sequence 150 | self.pos += 1 151 | if self.pos < self.length: 152 | # Handle escape sequences (simplified) 153 | esc = self.data[self.pos] 154 | if esc in b'nrtbf()\\': 155 | result.append(self.data[start:self.pos-1]) 156 | # Handle common escape sequences 157 | if esc == ord(b'n'): 158 | result.append(b'\n') 159 | elif esc == ord(b'r'): 160 | result.append(b'\r') 161 | elif esc == ord(b't'): 162 | result.append(b'\t') 163 | elif esc == ord(b'b'): 164 | result.append(b'\b') 165 | elif esc == ord('f'): 166 | result.append(b'\f') 167 | else: 168 | result.append(bytes([esc])) 169 | start = self.pos + 1 170 | # Handle octal escape sequences 171 | elif ord(b'0') <= esc <= ord('7'): 172 | # Parse up to 3 octal digits 173 | val = 0 174 | count = 0 175 | while (count < 3 and 176 | self.pos < self.length and 177 | ord(b'0') <= self.data[self.pos] <= ord('7')): 178 | val = (val << 3) + (self.data[self.pos] - ord(b'0')) 179 | self.pos += 1 180 | count += 1 181 | result.append(self.data[start:self.pos-count-1]) 182 | result.append(bytes([val])) 183 | start = self.pos 184 | continue 185 | self.pos += 1 186 | elif c == ord(b'('): 187 | depth += 1 188 | self.pos += 1 189 | elif c == ord(b')'): 190 | depth -= 1 191 | if depth == 0: 192 | result.append(self.data[start:self.pos]) 193 | self.pos += 1 194 | break 195 | self.pos += 1 196 | else: 197 | self.pos += 1 198 | 199 | return b''.join(result).decode('latin-1', errors='replace') 200 | 201 | def parse_hex_string(self): 202 | """Parse a hex string (enclosed in angle brackets)""" 203 | if self.get_current_char() != ord(b'<'): 204 | return None 205 | 206 | self.pos += 1 207 | start = self.pos 208 | hex_digits = b'0123456789ABCDEFabcdef' 209 | 210 | while (self.pos < self.length and 211 | self.data[self.pos] != ord(b'>') and 212 | self.data[self.pos] in hex_digits + b' \t\n\r\f\0'): 213 | self.pos += 1 214 | 215 | if self.pos >= self.length or self.data[self.pos] != ord(b'>'): 216 | return None 217 | 218 | hex_str = self.data[start:self.pos].translate(None, b' \t\n\r\f\0') 219 | self.pos += 1 # Skip the '>' 220 | 221 | # Convert hex string to bytes 222 | try: 223 | return bytes.fromhex(hex_str.decode('ascii')).decode('latin-1', errors='replace') 224 | except: 225 | return None 226 | 227 | def parse_number_or_ref(self): 228 | """Parse a number or object reference""" 229 | start = self.pos 230 | 231 | # Handle sign 232 | if self.get_current_char() in b'+-': 233 | self.pos += 1 234 | 235 | # Parse integer part 236 | while (self.pos < self.length and 237 | ord(b'0') <= self.data[self.pos] <= ord('9')): 238 | self.pos += 1 239 | 240 | # Parse decimal part 241 | if (self.pos < self.length and 242 | self.data[self.pos] == ord(b'.')): 243 | self.pos += 1 244 | while (self.pos < self.length and 245 | ord(b'0') <= self.data[self.pos] <= ord('9')): 246 | self.pos += 1 247 | 248 | # Check if this is an object reference (number number R) 249 | saved_pos = self.pos 250 | self.skip_whitespace() 251 | 252 | if (self.pos + 1 < self.length and 253 | ord(b'0') <= self.data[self.pos] <= ord('9')): 254 | # Parse second number 255 | start2 = self.pos 256 | while (self.pos < self.length and 257 | ord(b'0') <= self.data[self.pos] <= ord('9')): 258 | self.pos += 1 259 | 260 | self.skip_whitespace() 261 | 262 | if (self.pos < self.length and 263 | self.data[self.pos] == ord(b'R')): 264 | # It's a reference 265 | obj_num = int(self.data[start:start2]) 266 | gen_num = int(self.data[start2:self.pos]) 267 | self.pos += 1 268 | return {'type': 'reference', 'obj_num': obj_num, 'gen_num': gen_num} 269 | 270 | # Not a reference, just a number 271 | self.pos = saved_pos 272 | return float(self.data[start:self.pos].decode('ascii')) 273 | 274 | def parse_keyword(self): 275 | """Parse boolean or null keywords""" 276 | if self.data.startswith(b'true', self.pos): 277 | self.pos += 4 278 | return True 279 | elif self.data.startswith(b'false', self.pos): 280 | self.pos += 5 281 | return False 282 | elif self.data.startswith(b'null', self.pos): 283 | self.pos += 4 284 | return None 285 | return None 286 | 287 | def find_dict_end(data, start_pos): 288 | """Find the matching '>>' for a '<<' at start_pos, handling nesting.""" 289 | if not data.startswith(b'<<', start_pos): 290 | return -1 291 | 292 | depth = 1 293 | pos = start_pos + 2 # Skip the opening '<<' 294 | length = len(data) 295 | 296 | while pos < length - 1: # Need at least 2 bytes left for '>>' 297 | if data.startswith(b'<<', pos): 298 | depth += 1 299 | pos += 2 300 | elif data.startswith(b'>>', pos): 301 | depth -= 1 302 | if depth == 0: 303 | return pos + 2 # Return position after the closing '>>' 304 | pos += 2 305 | else: 306 | pos += 1 307 | 308 | return -1 # No matching '>>' found 309 | 310 | def parse_pdf_parameters(data): 311 | """Parse PDF parameters from binary data into a structured dictionary""" 312 | if not data: 313 | return {} 314 | 315 | # Look for dictionary pattern 316 | dict_start = data.find(b'<<') 317 | if dict_start >= 0: 318 | dict_end = find_dict_end(data, dict_start) 319 | if dict_end > dict_start: 320 | # Create a new parser with just the dictionary content 321 | parser = pdf_param_parser(b'<<' + data[dict_start+2:dict_end] + b'>>') 322 | return parser.parse_dictionary() or {} 323 | 324 | # If no dictionary found or error, try parsing as is 325 | parser = pdf_param_parser(data) 326 | return parser.parse_dictionary() or {} 327 | -------------------------------------------------------------------------------- /pdf_lib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import re 3 | import hashlib 4 | import zlib 5 | import time 6 | from pdf_param_parser import parse_pdf_parameters 7 | 8 | """ 9 | 10 | version 2 of the pdf lib 11 | i think we have to parse xref entry, then xref stream, then stream objects and store them with the other objects 12 | 13 | I would alos like it if we could be getting more grainular information from the PDFs we pass through... 14 | 15 | 16 | still need to get the pdf obj hashing (and overall parsing to work) 17 | I think it would make more sense to keep the std and stream objects separate in terms of parsing the object 18 | data into the hash, but for searching for URIs and MediaBox values we def need to parse both. 19 | 20 | Should we add to the seek functions so we can search the raw objects and the stream/decoded objects, or split that into separate functions? 21 | 22 | 23 | 24 | I think we need a "follow" function. You pass an object and if it's a ref object it will pull that object, and keep doing so until it finds the actual objects. 25 | 26 | we need a function to parse out any ref objects found in an object's parameters, so that it can be appended to the obj_dict/obj_data in that parse_params object. 27 | 28 | - we need to be able to pass in a stream object (not objstm) and decode it and look through the content for a 29 | - we need to be able to properly parse objstm objects, and then parse out the objects within those objects. I thought we were doing that already but I guess not. 30 | 31 | """ 32 | 33 | 34 | class pdf_object(): 35 | def __init__(self, fname): 36 | self.fname = fname 37 | self.fdata = open(fname, 'rb').read() 38 | self.sha256 = hashlib.sha256(self.fdata).hexdigest() 39 | # data and objects 40 | self.start_list = [] 41 | self.revision_id_pairs = [] 42 | self.object_offset_list = [] 43 | self.xref_entries = { 44 | "std": [], 45 | "stream": [], 46 | } 47 | self.obj_dicts = [] 48 | self.temp = None 49 | self.stream_objects = [] 50 | self.cur_ws = None 51 | self.current_obj_number = None 52 | self.object_registry = {} 53 | self.current_objects = {} 54 | # regex patterns 55 | self.trailer_pattern = re.compile(b'trailer(?P.*?)[\x00\x09\x0a\x0c\x0d\x20]{1,}%%EOF', re.MULTILINE+re.DOTALL) 56 | self.revision_id = re.compile(b'\/ID[\x00\x09\x0a\x0c\x0d\x20]*\[<(?P[A-Za-z0-9]{32})><(?P[A-Za-z0-9]{32})', re.MULTILINE) 57 | self.trailer_pattern2 = re.compile(b'(startxref.*?%%EOF)', re.MULTILINE+re.DOTALL) 58 | self.startxref_pattern = re.compile(b'startxref[\x00\x09\x0a\x0c\x0d\x20]{1,}([0-9]{1,})[\x00\x09\x0a\x0c\x0d\x20]{1,}') 59 | self.xref_pattern = re.compile(b'xref(?P[\x00\x09\x0a\x0c\x0d\x20]{1,})(?P[0-9]{1,}.*?)trailer', re.MULTILINE+re.DOTALL) 60 | self.prev_xref = re.compile(b'/Prev[\x00\x09\x0a\x0c\x0d\x20]{1,}([0-9]{1,})', re.MULTILINE+re.DOTALL) 61 | self.stream_pattern2 = re.compile(b'(?P[0-9]{1,}) (?P[0-9]{1,}) obj[\x00\x09\x0a\x0c\x0d\x20]{1,}(?P.*?)(?Pstream[\x0d\x0a].*?[\x0d\x0a]endstream)', re.MULTILINE+re.DOTALL) 62 | self.params_decode = re.compile(b'/DecodeParms[\x00\x09\x0a\x0c\x0d\x20]*?<<(?P.*?)>>', re.MULTILINE+re.DOTALL) 63 | self.params_w = re.compile(b'/W[\x00\x09\x0a\x0c\x0d\x20]*?\[(?P.*?)\]') 64 | self.objstm_pattern = re.compile(b'(?P[0-9]{1,}) (?P[0-9]{1,}) obj[\x00\x09\x0a\x0c\x0d\x20]*?<<(?P.*?)>>[\x00\x09\x0a\x0c\x0d\x20]*?stream([\x0d\x0a]*)(?P.*?)\3endstream', re.MULTILINE+re.DOTALL) 65 | self.n_extract = re.compile(b'/N[\x00\x09\x0a\x0c\x0d\x20]*?(?P[0-9]{1,})', re.DOTALL) 66 | self.first_extract = re.compile(b'/First[\x00\x09\x0a\x0c\x0d\x20]*?(?P[0-9]{1,})', re.DOTALL) 67 | self.object_pattern = re.compile(b'(?P[0-9]{1,}) (?P[0-9]{1,}) obj[\x00\x09\x0a\x0c\x0d\x20]{1,}(?P.*>>)[\x00\x09\x0a\x0c\x0d\x20]?(stream(?P.*?)endstream)?.*?endobj', re.MULTILINE+re.DOTALL) 68 | self.object_pattern_big = re.compile(b'(?P[0-9]{1,}) [0-9]{1,} obj(?P[\x00\x09\x0a\x0c\x0d\x20]{1,})(?P.*?)[\x00\x09\x0a\x0c\x0d\x20]{1,}endobj', re.MULTILINE+re.DOTALL) 69 | #self.obj_params_pattern = re.compile(b'\<\<(?P.*)\>\>', re.MULTILINE+re.DOTALL) 70 | self.obj_params_pattern = re.compile(b'(?P<<.*>>)stream|(?P<<.*>>)', re.MULTILINE+re.DOTALL) 71 | self.obj_stream_pattern = re.compile(b'stream([\x0d\x0a]*)(?P.*?)\1endstream', re.MULTILINE+re.DOTALL) 72 | self.params_key_location = re.compile(b'/(?P[a-zA-Z0-9#]{1,})[\x00\x09\x0a\x0c\x0d\x20]*', re.MULTILINE+re.DOTALL) 73 | self.param_kv_pair = re.compile(b'/(?P[a-zA-Z0-9#]{1,})[\x00\x09\x0a\x0c\x0d\x20]*(?P.*?)/', re.MULTILINE+re.DOTALL) 74 | self.obj_type_pattern = re.compile(b'(?P/Type[\x00\x0a\x0c\x0d\x20\x09]*/.*?)[\x00\x0a\x0c\x0d\x20\x09/>]', re.MULTILINE+re.DOTALL) 75 | self.obj_subtype_pattern = re.compile(b'(?P/Subtype[\x00\x0a\x0c\x0d\x20\x09]*/.*?)[\x00\x0a\x0c\x0d\x20\x09/>]', re.MULTILINE+re.DOTALL) 76 | # debug 77 | self.func_trace = False 78 | self.debug = False 79 | self.timedbg = False 80 | self.start_time = time.time() 81 | 82 | 83 | def check_pdf_header(self): 84 | if self.func_trace: 85 | print(f"function: check_pdf_header") 86 | if not self.fdata[0:4] == b'%PDF': 87 | return False 88 | return True 89 | 90 | def check_trailer_content(self, trailer_data): 91 | if self.func_trace: 92 | print(f"function: check_trailer_content") 93 | if b'/ID' in trailer_data: 94 | rev_match = self.revision_id.search(trailer_data) 95 | if rev_match: 96 | current_id = rev_match.group('current_id') 97 | original_id = rev_match.group('original_id') 98 | self.revision_id_pairs.append([current_id, original_id]) 99 | 100 | def run_regex_xref_scan(self): 101 | if self.func_trace: 102 | print(f"function: run_regex_scan") 103 | offset_list = [] 104 | xref_regex = re.compile(b'[\x00\x09\x0a\x0c\x0d\x20]xref[\x00\x09\x0a\x0c\x0d\x20]{1,}.*?[\x00\x09\x0a\x0c\x0d\x20]{1,}trailer', re.MULTILINE+re.DOTALL) 105 | for match in xref_regex.finditer(self.fdata): 106 | if self.debug: 107 | print(f"--> xref match found: {match}") 108 | # need to add 1 here because the regex includes a whitespace character. 109 | offset_list.append(match.start() + 1) 110 | if self.timedbg: 111 | print(f"Timer: {time.time() - self.start_time}") 112 | xrefstream_regex = re.compile(b'[0-9]{1,} [0-9]{1,} obj[\x00\x09\x0a\x0c\x0d\x20]{1,}.*?\/XRef') 113 | for match in xrefstream_regex.finditer(self.fdata): 114 | if self.debug: 115 | print(f"--> xref stream match found: {match}") 116 | offset_list.append(match.start()) 117 | if self.timedbg: 118 | print(f"Timer: {time.time() - self.start_time}") 119 | if offset_list: 120 | for entry in offset_list: 121 | self.start_list.append(entry) 122 | else: 123 | return False 124 | 125 | def trailer_params(self, trailer_match): 126 | if self.func_trace: 127 | print(f"function: trailer_params") 128 | offset_list = [] 129 | if b'/Prev' in trailer_match: 130 | offset = int(trailer_match.split(b'/Prev ')[1].split(b'/')[0].split(b'>')[0]) 131 | offset_list.append(offset) 132 | if b'/XRefStm' in trailer_match: 133 | offset = int(trailer_match.split(b'/XRefStm ')[1].split(b'/')[0].split(b'>')[0]) 134 | offset_list.append(offset) 135 | return offset_list 136 | 137 | def uniq_list(self, in_list): 138 | if self.func_trace: 139 | print(f"function: uniq_list") 140 | out = [] 141 | for i in in_list: 142 | if i not in out: 143 | out.append(i) 144 | return out 145 | 146 | def trailer_process(self): 147 | """ 148 | trailer_process kicks off the whole chain of events required 149 | to grab the complete xref table contents (self.xref_entries) as well 150 | as the object_offset_list, which finds "IN_USE" objects and where they are located. 151 | 152 | We know that some PDFs have incorrect offsets, so we might need some flexibility here... 153 | maybe it's a regex that runs against the whole file, im not sure. 154 | """ 155 | if self.func_trace: 156 | print(f"function: trailer_process") 157 | trailer_matches = [] 158 | if self.trailer_pattern.search(self.fdata): 159 | for trailer in self.trailer_pattern.finditer(self.fdata): 160 | trailer_matches.append(trailer) 161 | trailer_data = trailer.group('trailer_content') 162 | if trailer_data: 163 | self.check_trailer_content(trailer_data) 164 | if self.trailer_pattern2.search(self.fdata): 165 | for trailer in self.trailer_pattern2.finditer(self.fdata): 166 | trailer_matches.append(trailer) 167 | if not trailer_matches: 168 | self.run_regex = True 169 | self.run_regex_xref_scan() 170 | for i in range(len(trailer_matches), 0, -1): 171 | offset_list = self.trailer_params(trailer_matches[i-1].group()) 172 | start_xref_pos = None 173 | start_pos = self.startxref_pattern.search(trailer_matches[i-1].group()) 174 | if start_pos: 175 | start_xref_pos = start_pos.groups()[0].decode() 176 | if start_xref_pos: 177 | if start_xref_pos not in self.start_list: 178 | self.start_list.append(int(start_xref_pos)) 179 | if offset_list: 180 | for offset in offset_list: 181 | self.start_list.append(offset) 182 | self.start_list = self.uniq_list(self.start_list) 183 | if self.timedbg: 184 | print(f"Timer: {time.time() - self.start_time}") 185 | for item in self.start_list: 186 | if self.debug: 187 | print(f"--> start list item: {item}") 188 | self.prev_row = None 189 | try: 190 | self.parse_xref_table(item) 191 | except UnboundLocalError: 192 | print(f"(trailer_process) EXCEPTION: {self.fname} - {item}") 193 | if not self.object_offset_list: 194 | self.seek_obj_fallback() 195 | 196 | def parse_xref_table(self, start_pos): 197 | """ 198 | with this we want to 1. parse the xref table (and xref stream) 199 | but also get the data from the parsed objects and store them in a dict, or list or whatever 200 | so that we can call and reference them later on. 201 | 202 | idk something like this? 203 | 204 | self.xref_entries = { 205 | "stream" : [], 206 | "std" : [], 207 | } 208 | """ 209 | if self.func_trace: 210 | print(f"function: parse_xref_table") 211 | xref_data = self.xref_pattern.match(self.fdata[start_pos:]) 212 | if xref_data: 213 | split_char = xref_data.group('split_char').decode() 214 | xref_content = xref_data.group('xref_data').decode() 215 | xref_list = xref_content.split(split_char) 216 | cur_xref_table = [] 217 | for i in xref_list: 218 | entry_list = [x for x in i.split(' ') if x] 219 | if len(entry_list) == 2: 220 | start, count = entry_list 221 | start = int(start) 222 | count = int(count) 223 | elif len(entry_list) == 3: 224 | object_offset, generation_id, free_in_use = entry_list 225 | object_offset = int(object_offset) 226 | generation_id = int(generation_id) 227 | if len(free_in_use) > 1: 228 | free_in_use = free_in_use[0:1] 229 | if free_in_use == "n": 230 | free_in_use = "in-use" 231 | else: 232 | free_in_use = "free" 233 | start += 1 234 | if free_in_use == "in-use" and (object_offset not in self.object_offset_list): 235 | self.object_offset_list.append(object_offset) 236 | cur_xref_table.append([object_offset, generation_id, free_in_use]) 237 | self.register_object_from_xref(start-1, generation_id, object_offset, free_in_use) 238 | if len(cur_xref_table) > 1: 239 | self.xref_entries["std"].append(cur_xref_table) 240 | else: 241 | obj_data = self.stream_pattern2.match(self.fdata[start_pos:]) 242 | if obj_data: 243 | cur_xref_table = [] 244 | if obj_data.group('unk_data'): 245 | param_data = obj_data.group('unk_data') 246 | if obj_data.group('stream_data'): 247 | stream_data = obj_data.group('stream_data') 248 | if b'/Type/XRef' in param_data.replace(b' ', b''): 249 | if b'/Prev' in param_data: 250 | value = int(param_data.split(b'/Prev ')[1].split(b'/')[0].decode()) 251 | if value not in self.start_list: 252 | self.start_list.append(value) 253 | params = self.params_extract(param_data) 254 | if self.debug: 255 | print(params) 256 | if params: 257 | self.decode_xref_stream(stream_data, params) 258 | if self.temp: 259 | self.xref_entries["stream"].append(self.temp) 260 | self.temp = None 261 | else: 262 | print(f"(parse_xref) Unexpected Data in xref stream regex - {self.fname}") 263 | print(obj_data.group('unk_data')) 264 | else: 265 | self.run_regex_xref_scan() 266 | 267 | def seek_obj_fallback(self): 268 | """ 269 | fallback method for finding objects when there is no xref entries. 270 | """ 271 | object_start_positions = [] 272 | pos = -1 273 | obj_pattern = b' obj' 274 | while True: 275 | pos = self.fdata.find(obj_pattern, pos + 1) 276 | if pos == -1: 277 | break 278 | start = pos - 1 279 | while start >= 0 and self.fdata[start] in b'01234567890 ': 280 | start -= 1 281 | 282 | object_start_positions.append(start) 283 | if object_start_positions: 284 | self.object_offset_list = object_start_positions 285 | 286 | def params_extract(self, param_data): 287 | """ 288 | this really only extracts params needed to decode the xref stream entry. 289 | should we add the rest of param extraction here, or is that overkill? 290 | Would we eventually need or like this? 291 | """ 292 | if self.func_trace: 293 | print(f"function: params_extract") 294 | params = {} 295 | match_decode = self.params_decode.search(param_data) 296 | if match_decode: 297 | decode_params = match_decode.group('decode_params') 298 | if self.debug: 299 | print(decode_params) 300 | for kv in decode_params.split(b'/'): 301 | if kv not in {b'', b'\n'}: 302 | try: 303 | kv = [x for x in kv.split(b' ') if x] 304 | if self.debug: 305 | print(f"--> kv: {kv}") 306 | if kv: 307 | k, v = kv 308 | params[k.decode()] = v.replace(b'\n', b'').decode() 309 | except ValueError: 310 | print("[!] exception: params_extract >> kv") 311 | if self.debug: 312 | print(kv) 313 | print(type(kv)) 314 | print(f"file: {self.fname}") 315 | match_w = self.params_w.search(param_data) 316 | if match_w: 317 | w_array = match_w.group('w_array') 318 | w_values = w_array.decode().split(' ') 319 | w_values = [x for x in w_values if x] 320 | if len(w_values) != 3: 321 | w_values = None 322 | else: 323 | params["W"] = w_values 324 | if params: 325 | return params 326 | 327 | def decode_xref_stream(self, stream_bytes, param_dict): 328 | """ 329 | decodes the xref stream object 330 | """ 331 | if self.func_trace: 332 | print(f"function: decode_xref_stream") 333 | w_array = param_dict["W"] 334 | predictor = int(param_dict.get("Predictor", 0)) 335 | predictor_add = 0 336 | if predictor > 1: 337 | predictor_add = 1 338 | width = 0 339 | w = [] 340 | if predictor_add: 341 | w.append(1) 342 | else: 343 | w.append(0) 344 | for i in w_array: 345 | width += int(i) 346 | w.append(int(i)) 347 | data = stream_bytes.replace(b'stream\x0d\x0a', b'').replace(b'\x0d\x0aendstream',b'').replace(b'stream\x0a', b'').replace(b'\x0aendstream',b'').replace(b'stream\x0d', b'').replace(b'\x0dendstream',b'') 348 | try: 349 | decompressed = zlib.decompress(data) 350 | except zlib.error as z: 351 | if len(data) % (width + predictor_add) == 0: 352 | decompressed = data 353 | else: 354 | print(f"[-] zlib fail -- failed with file {self.fname}") 355 | if self.debug: 356 | print(z) 357 | fp = open('zlib_error.bin','wb') 358 | fp.write(data) 359 | fp.close() 360 | exit() 361 | stream_list = [] 362 | if len(decompressed) % (width + predictor_add) == 0: 363 | off = width + predictor_add 364 | for i in range(0, len(decompressed), off): 365 | row = decompressed[i:i+off] 366 | stream_list.append(self.clean_row(row, w)) 367 | else: 368 | print(self.fname) 369 | if self.debug: 370 | print(f"--> decode_xref_stream: stream_list: {stream_list}") 371 | self.stream_list_parse(stream_list) 372 | 373 | def stream_list_parse(self, stream_list): 374 | """ 375 | This adds to the object_offset_list (fills in the missing object offsets) 376 | stores the data in a temp storage and then we can use it in the calling 377 | decode_xref_stream function. 378 | 379 | looks like we're only handling some of the entry types. 380 | """ 381 | if self.func_trace: 382 | print("function: stream_list_parse") 383 | parsed_data = [] 384 | for line in stream_list: 385 | entry_type = int.from_bytes(line[0], 'big') 386 | if isinstance(line[1], int): 387 | val2 = line[1] 388 | else: 389 | val2 = int.from_bytes(line[1], 'big') 390 | val3 = int.from_bytes(line[2], 'big') 391 | # Add after line 388 (after val3 = int.from_bytes(line[2], 'big')): 392 | obj_num = len(parsed_data) # Current object number 393 | 394 | if entry_type == 1: # Normal object 395 | # Existing code for object_offset_list 396 | self.register_object_from_xref(obj_num, val3, val2, "in-use") 397 | if val2 not in self.object_offset_list: 398 | self.object_offset_list.append(val2) 399 | elif entry_type == 0: # Free object 400 | self.register_object_from_xref(obj_num, val3, 0, "free") 401 | elif entry_type == 2: # Compressed object 402 | self.register_object_from_xref(obj_num, 0, val2, "compressed") 403 | parsed_data.append([entry_type, val2, val3]) 404 | self.temp = parsed_data 405 | return True 406 | 407 | def predictor_process(self, row): 408 | """ 409 | predictor process is only used as part of decoding xref stream objects 410 | """ 411 | if self.func_trace: 412 | print('function: predictor_process') 413 | pred_value = row[0:1] 414 | data = row[1:] 415 | l = len(row) 416 | if self.prev_row == None: 417 | self.prev_row = b'\x00' * l 418 | if pred_value == b'\x02': 419 | new_row = [0, ] * (l - 1) 420 | for i in range(0, len(data)): 421 | try: 422 | new_byte = (data[i] + self.prev_row[i]) % 256 423 | new_row[i] = new_byte 424 | except Exception as e: 425 | print(f"i: {i} \ndata: {data} \nprev_row: {self.prev_row}") 426 | print(f"l:{l}\nl-1:{l-1}") 427 | print(e) 428 | print(type(e).__name__) 429 | exit() 430 | self.prev_row = new_row 431 | b = bytes(new_row) 432 | return b 433 | else: 434 | print("[!] weird predictor value found in xref stream:") 435 | print(data) 436 | print(self.fname) 437 | 438 | def clean_row(self, row, w_array): 439 | """ 440 | this is only used to clean up the w array values and do that "math" 441 | """ 442 | if self.func_trace: 443 | print("function: clean_row") 444 | pred_size = w_array[0] 445 | entry_type_size = w_array[1] 446 | size2 = w_array[2] 447 | size3 = w_array[3] 448 | pred = row[0:pred_size] 449 | entry_val = row[pred_size:pred_size+entry_type_size] 450 | val2 = row[pred_size+entry_type_size:pred_size+entry_type_size+size2] 451 | val3 = row[pred_size+entry_type_size+size2:pred_size+entry_type_size+size2+size3] 452 | val2 = int.from_bytes(val2, 'big') 453 | if pred: 454 | new_bytes = self.predictor_process(row) 455 | if self.debug: 456 | print(f"--> clean_row: new bytes: {new_bytes}") 457 | new_entry = new_bytes[0:entry_type_size] 458 | new_val2 = new_bytes[entry_type_size:entry_type_size + size2] 459 | new_val3 = new_bytes[entry_type_size+size2:] 460 | return [new_entry, new_val2, new_val3] 461 | else: 462 | return [entry_val, val2, val3] 463 | 464 | # object stream parsing 465 | def start_object_parsing(self): 466 | """ 467 | kicks off the process for getting the stream objects, so we can include 468 | those in the parsed objects as well (searching for URIs with this, 469 | finding ref objects, stuff like that 470 | 471 | Object Streaw parsing is not working correctly. See the weird 0x1d adp 2025/60 PDF for example. 472 | """ 473 | if self.func_trace: 474 | print("function: start_object_parsing") 475 | obj_stms = self.seek_object_name(b'/ObjStm') 476 | if self.timedbg: 477 | print(f"Timer: {time.time() - self.start_time}") 478 | for obj in obj_stms: 479 | if self.debug: 480 | print(obj) 481 | match = self.objstm_pattern.search(obj) 482 | if match: 483 | if self.timedbg: 484 | print(f"Timer: {time.time() - self.start_time}") 485 | if match.group('params'): 486 | n_val, first_val = self.parse_stream_obj_params(match.group('params')) 487 | if match.group('stream') and n_val and first_val: 488 | try: 489 | if self.timedbg: 490 | print(f"Timer: {time.time() - self.start_time}") 491 | decode_data = zlib.decompress(match.group('stream')) 492 | except zlib.error as e: 493 | print(f'ZLIB ERROR {e}') 494 | print(obj) 495 | print(match.group('stream')) 496 | exit() 497 | if decode_data: 498 | if self.timedbg: 499 | print(f"Timer: {time.time() - self.start_time}") 500 | decoded_stream = self.parse_decomp_obj(n_val, first_val, decode_data) 501 | self.stream_objects.append(decoded_stream) 502 | 503 | def parse_decomp_obj(self, n, first, data): 504 | """ 505 | returns the parsed data from the decompressed object stream data 506 | """ 507 | if self.func_trace: 508 | print("function: parse_decomp_obj") 509 | output = [] 510 | object_index = data[0:first] 511 | object_index_parsed = [] 512 | object_data = data[first:] 513 | obj_list = object_index.split(b' ') 514 | for i in range(0, len(obj_list), 2): 515 | try: 516 | obj_number = int(obj_list[i].decode()) 517 | start_pos = int(obj_list[i+1].decode()) 518 | object_index_parsed.append([obj_number, start_pos]) 519 | except IndexError: 520 | pass 521 | except ValueError: 522 | pass 523 | if n != len(object_index_parsed): 524 | return False 525 | for i in range(0, len(object_index_parsed)): 526 | pair = object_index_parsed[i] 527 | if i + 1 > n-1: 528 | next_pos = len(object_data) 529 | else: 530 | next_pair = object_index_parsed[i+1] 531 | next_obj, next_pos = next_pair 532 | obj, pos = pair 533 | data = { 534 | "object_number": obj, 535 | "start": pos, 536 | "end": next_pos, 537 | "raw_data": object_data[pos:next_pos], 538 | } 539 | output.append(data) 540 | if self.timedbg: 541 | print(f"Timer: {time.time() - self.start_time}") 542 | return output 543 | 544 | def parse_stream_obj_params(self, param): 545 | """ 546 | parses the parameters for the stream objects 547 | """ 548 | if self.func_trace: 549 | print("function: parse_stream_obj_params") 550 | mn = self.n_extract.search(param) 551 | mf = self.first_extract.search(param) 552 | if mn: 553 | n_val = int(mn.group('n_param').decode()) 554 | if mf: 555 | f_val = int(mf.group('first_param').decode()) 556 | if self.timedbg: 557 | print(f"Timer: {time.time() - self.start_time}") 558 | if n_val and f_val: 559 | return n_val, f_val 560 | 561 | # searching functions 562 | def seek_object_number(self, number): 563 | """ 564 | searches object_offset_list for an obj_number and returns that object 565 | expects a binary string: b'17' 566 | 567 | 568 | What happens with searching for b'10' and when we see object 100? 569 | does that match when it should not? 570 | 571 | IT MIGHT be better to search some other structure instead of object_offset_list 572 | or at least note that we'll only get standard/raw objects and not anything compressed. 573 | 574 | we SHOULD be able to seek out an object from an OBJECT STREAM for things like URIs. 575 | """ 576 | if self.func_trace: 577 | print("function: seek_object_number") 578 | for offset in self.object_offset_list: 579 | start = offset 580 | end = self.fdata.find(b'endobj', start+1) 581 | obj_data = self.fdata[start:end] 582 | num_data = obj_data[0:obj_data.find(b'obj')] 583 | obj_number = num_data.split(b' ')[0] 584 | if number == obj_number: 585 | if self.timedbg: 586 | print(f"Timer: {time.time() - self.start_time}") 587 | return obj_data 588 | 589 | def seek_object_name(self, name): 590 | """ 591 | returns object that matches the "name" pattern 592 | >> expects binary string, such as: b'Link' 593 | -- we might want to actually return the whole object and from there 594 | -- take the time to parse out the rect/mediabox values and that way 595 | -- we can loop back in on the object number associated with the mess. 596 | -- if we want to find the URI this is probably what we NEED to do. 597 | """ 598 | if self.func_trace: 599 | print("function: seek_object_name") 600 | objects = [] 601 | for offset in self.object_offset_list: 602 | start = offset 603 | end = self.fdata.find(b'endobj', start + 1) 604 | obj_data = self.fdata[start:end] 605 | if name in obj_data: 606 | objects.append(obj_data) 607 | if self.timedbg: 608 | print(f"Timer: {time.time() - self.start_time}") 609 | return objects 610 | 611 | def seek_obj_dict_by_number(self, number): 612 | """ 613 | Trying a different process, looking over only the obj dict that we create 614 | 615 | it might be better to not do it this way, but I'll need to see if the param parsing happens 616 | separate from the other processing / object offset creation. 617 | """ 618 | for o in self.obj_dicts: 619 | if int(o["object_number"]) == number: 620 | return o 621 | 622 | # searching the param dict for a specific key name? 623 | def seek_param_key(self, key, d=None, current_path=None, results=None): 624 | """ 625 | search the provided dict for a key and return that, looping 626 | over nested dicts if need be. 627 | """ 628 | if results is None: 629 | results = [] 630 | if current_path is None: 631 | current_path = [] 632 | 633 | if d is None: 634 | for obj in self.obj_dicts: 635 | if obj.get("object_params", ""): 636 | obj_num = obj.get("object_number", "unknown").decode() 637 | self.seek_param_key(key, obj["object_params"], current_path=[obj_num], results=results) 638 | return results 639 | 640 | for k, v in d.items(): 641 | path = current_path + [k] 642 | if k == key: 643 | results.append(( 644 | current_path[0] if current_path else None, # object Number 645 | ".".join(str(p) for p in path), # path to key 646 | v, #value 647 | )) 648 | 649 | if isinstance(v, dict): 650 | self.seek_param_key(key, v, path, results) 651 | 652 | return results 653 | 654 | def seek_param_value(self, key, d=None, current_path=None, results=None): 655 | """ 656 | search the provided dict for a value, and return that value, looping as needed. 657 | """ 658 | if results is None: 659 | results = [] 660 | if current_path is None: 661 | current_path = [] 662 | 663 | if d is None: 664 | for obj in self.obj_dicts: 665 | if obj.get("object_params", ""): 666 | obj_num = obj.get("object_number", "unknown").decode() 667 | self.seek_param_value(key, obj["object_params"], current_path = [obj_num], results = results) 668 | return results 669 | 670 | for k, v in d.items(): 671 | path = current_path + [k] 672 | if key in v: 673 | results.append(( 674 | current_path[0] if current_path else None, 675 | ".".join(str(p) for p in path), 676 | v, 677 | )) 678 | else: 679 | print(v) 680 | 681 | if isinstance(v, dict): 682 | self.seek_param_value(key, v, path, results) 683 | 684 | return results 685 | 686 | #std object parsing 687 | def pull_objects(self): 688 | """ 689 | grabs each object from the offset list and 690 | parses it 691 | """ 692 | if self.func_trace: 693 | print("function: pull_objects") 694 | for item in self.object_offset_list: 695 | self.parse_pdf_object(item) 696 | 697 | # temp function 698 | def search_obj(self, start_pos): 699 | end = b'endobj' 700 | end_pos = self.fdata.find(end, start_pos) 701 | if b'/Type/Sig' in self.fdata[start_pos:end_pos+len(end)]: 702 | return False 703 | if self.timedbg: 704 | print(f"start Timer: {time.time() - self.start_time}") 705 | match = self.object_pattern_big.search(self.fdata[start_pos:end_pos+len(end)]) 706 | if self.timedbg: 707 | print(f"end Timer: {time.time() - self.start_time}") 708 | if match: 709 | obj_number = match.group('obj_number') 710 | unparsed = match.group('unparsed') 711 | s = unparsed.find(b'endstream') 712 | if s: 713 | if b'<<' in unparsed[s:]: 714 | print(f"{self.fname} --- found werid stream object at {obj_number}//{start_pos}") 715 | 716 | def parse_params(self, params): 717 | """ 718 | parse the parameters of the object, we'll need some level of recurssion I think. 719 | 720 | let's start by looking for the TYPE which is the main thing we want here. 721 | - /TYPE 722 | - /URI, /A, /S, /ANNOTS, /RECT, etc. 723 | 724 | i think we want the output of the "type" query to be either "/Type/Pages" or "/Subtype/Image" that kind of thing. 725 | I think knowing it's a type or a subtype is cool. 726 | 727 | the spec mentions EOL (\x0a, \x0d and then two of them, maybe we use that? ) 728 | 729 | when we iterate over the results, things with << at the end and >> at the end could be treated as if they are related... idk how but I think we can do that. Or is it even needed. Does it matter that things are nested or is it really treated the same? 730 | 731 | maybe we ignore it for now. 732 | 733 | we could maybe to a new regex just for extracting the type. not sure if that would be better than the messy thing we have now or not. 734 | """ 735 | if self.func_trace: 736 | print("function: parse_params") 737 | data = parse_pdf_parameters(params) 738 | return data 739 | 740 | def parse_pdf_object(self, start_pos): 741 | """ 742 | parses the object starting at start_pos 743 | 744 | Instead of directly copying the original version, i'm working 745 | on an update that should be a little simplier. 746 | 747 | The idea is we parse out the object, and then from there, parse out the subsequent pieces: 748 | - object number 749 | - parameters 750 | - stream_data (if present) 751 | and then from parameters, we should be able to extract the TYPE (which is what we really need) 752 | 753 | Would it be better to have to the TYPE slam case, or do we keep case? 754 | have we seen different case, i don't think so... that might be a spec standard that MUST be followed 755 | 756 | remember to implement the Type/Sig check to stop these slow downs on the regex. 757 | 758 | """ 759 | if self.func_trace: 760 | print("function: parse_pdf_object") 761 | end = b'endobj' 762 | end_pos = self.fdata.find(end, start_pos) 763 | obj_data = { 764 | 'object_number': None, 765 | 'object_type': None, 766 | 'ref_objs': [], 767 | 'object_params': None, 768 | 'object_start': start_pos, 769 | 'object_end': end_pos, 770 | 'stream': False, 771 | 772 | } 773 | if b'/Type/Sig' in self.fdata[start_pos:end_pos+len(end)]: 774 | return False 775 | if b'stream' in self.fdata[start_pos:end_pos+len(end)] and b'endstream' in self.fdata[start_pos:end_pos+len(end)]: 776 | obj_data["stream"] = True 777 | # changes here 778 | stm_start = self.fdata[start_pos:end_pos+len(end)].find(b'stream') 779 | stm_end = self.fdata[start_pos:end_pos+len(end)].find(b'endstream') 780 | obj_data["stream_start_offset"] = stm_start + start_pos + 6 781 | obj_data["stream_end_offset"] = stm_end + start_pos 782 | match = self.object_pattern_big.search(self.fdata[start_pos:end_pos+len(end)]) 783 | if match: 784 | if self.debug: 785 | print(f"--> parse_pdf_object // object_pattern_big regex|| {start_pos}") 786 | object_number = match.group('obj_number') 787 | # if object_number == None we need something to re-parse this. 788 | obj_data["object_number"] = object_number 789 | self.cur_ws = match.group('ws') 790 | unparsed_data = match.group('unparsed') 791 | stream_match = self.obj_stream_pattern.search(unparsed_data) 792 | params_match = self.obj_params_pattern.search(unparsed_data) 793 | if params_match: 794 | if params_match.group('params'): 795 | param_data = params_match.group('params') 796 | elif params_match.group('params2'): 797 | param_data = params_match.group('params2') 798 | else: 799 | print('hmmmm') 800 | print(object_number) 801 | print(params_match) 802 | param_dict = self.parse_params(param_data) 803 | if param_dict: 804 | obj_data["object_params"] = param_dict 805 | if param_dict.get("Subtype", "") and param_dict.get("Type", ""): 806 | obj_data["object_type"] = param_dict["Type"] + "/" + param_dict["Subtype"] 807 | elif param_dict.get("Type", ""): 808 | obj_data["object_type"] = param_dict["Type"] 809 | else: 810 | obj_data["object_type"] = next(iter(param_dict)) 811 | if obj_data["object_type"] == None: 812 | obj_data["object_type"] = "None" 813 | #print(obj_data["object_type"]) 814 | self.obj_dicts.append(obj_data) 815 | 816 | # sorting objects 817 | 818 | def sort_obj_by_offset(self): 819 | return sorted(self.obj_dicts, key=lambda obj: obj['object_start']) 820 | 821 | def sort_obj_by_number(self): 822 | return sorted(self.obj_dicts, key=lambda obj: obj['object_number']) 823 | 824 | # testing this out 825 | 826 | def register_object_from_xref(self, obj_num, generation_id, object_offset, free_in_use): 827 | """ 828 | Register an object from the xref table with proper revision handling. 829 | Uses generation numbers to track object versions - higher generation = newer version. 830 | """ 831 | if self.func_trace: 832 | print(f"function: register_object_from_xref") 833 | if self.debug: 834 | print(f"Registering object {obj_num} gen {generation_id} status {free_in_use}") 835 | 836 | # Create object key using (object_number, generation) 837 | obj_key = (obj_num, generation_id) 838 | 839 | # Store in registry with full xref info 840 | self.object_registry[obj_key] = { 841 | 'object_number': obj_num, 842 | 'generation_id': generation_id, 843 | 'object_offset': object_offset, 844 | 'free_in_use': free_in_use, 845 | 'file_position': object_offset 846 | } 847 | 848 | # Track current (active) version of each object number 849 | if free_in_use == "in-use": 850 | if obj_num not in self.current_objects: 851 | # First time seeing this object number 852 | self.current_objects[obj_num] = obj_key 853 | else: 854 | # Compare generations - higher generation wins 855 | current_key = self.current_objects[obj_num] 856 | current_gen = current_key[1] 857 | if generation_id > current_gen: 858 | self.current_objects[obj_num] = obj_key 859 | if self.debug: 860 | print(f"Object {obj_num}: updated from gen {current_gen} to gen {generation_id}") 861 | 862 | def get_current_object_offsets(self): 863 | """ 864 | Returns file offsets for only the current (active) version of each object. 865 | This eliminates duplicates by using xref generation numbers. 866 | """ 867 | current_offsets = [] 868 | for obj_num, obj_key in self.current_objects.items(): 869 | if obj_key in self.object_registry: 870 | obj_info = self.object_registry[obj_key] 871 | if obj_info['free_in_use'] == "in-use": 872 | current_offsets.append(obj_info['object_offset']) 873 | 874 | return sorted(current_offsets) # Return in file order 875 | 876 | def get_revision_statistics(self): 877 | """ 878 | Returns statistics about object revisions found in xref tables. 879 | """ 880 | total_entries = len(self.object_registry) 881 | current_objects = len(self.current_objects) 882 | revised_objects = [] 883 | 884 | # Find objects with multiple generations 885 | obj_generations = {} 886 | for (obj_num, gen_id), obj_info in self.object_registry.items(): 887 | if obj_num not in obj_generations: 888 | obj_generations[obj_num] = [] 889 | obj_generations[obj_num].append(gen_id) 890 | 891 | for obj_num, generations in obj_generations.items(): 892 | if len(generations) > 1: 893 | revised_objects.append({ 894 | 'object_number': obj_num, 895 | 'generations': sorted(generations), 896 | 'current_generation': max(generations) 897 | }) 898 | 899 | return { 900 | 'total_xref_entries': total_entries, 901 | 'unique_objects': current_objects, 902 | 'revised_objects': len(revised_objects), 903 | 'revision_details': revised_objects 904 | } 905 | 906 | def pull_objects_xref_aware(self): 907 | """ 908 | Parse objects using xref-aware approach that handles revisions properly. 909 | Only processes the current (highest generation) version of each object. 910 | """ 911 | if self.func_trace: 912 | print("function: pull_objects_xref_aware") 913 | 914 | # Get offsets for current objects only 915 | current_offsets = self.get_current_object_offsets() 916 | 917 | if self.debug: 918 | print(f"Processing {len(current_offsets)} current objects (out of {len(self.object_registry)} total xref entries)") 919 | 920 | # Parse only current objects 921 | for offset in current_offsets: 922 | self.parse_pdf_object(offset) 923 | 924 | def search_all_object_streams_for_object(self, target_obj_num): 925 | """ 926 | Search all object streams for a specific object number 927 | """ 928 | results = [] 929 | 930 | # Get all ObjStm objects 931 | objstm_objects = [] 932 | for obj in self.obj_dicts: 933 | if obj.get("object_type") == "ObjStm" or ( 934 | obj.get("object_params") and 935 | obj["object_params"].get("Type") == "ObjStm" 936 | ): 937 | objstm_objects.append(obj) 938 | 939 | # Search each object stream 940 | for objstm in objstm_objects: 941 | # Parse the object stream if not already done 942 | if "stream_data" in objstm: 943 | # Extract N and First parameters 944 | params = objstm.get("object_params", {}) 945 | n_val = params.get("N") 946 | first_val = params.get("First") 947 | 948 | if n_val and first_val: 949 | # Parse the object index 950 | stream_data = objstm["stream_data"] 951 | try: 952 | decompressed = zlib.decompress(stream_data) 953 | index_data = decompressed[:first_val] 954 | 955 | # Parse object numbers from index 956 | tokens = index_data.split() 957 | for i in range(0, len(tokens), 2): 958 | try: 959 | obj_num = int(tokens[i]) 960 | if obj_num == target_obj_num: 961 | offset = int(tokens[i+1]) 962 | results.append({ 963 | 'found_in_objstm': objstm['object_number'], 964 | 'object_number': obj_num, 965 | 'offset_in_stream': offset 966 | }) 967 | except (ValueError, IndexError): 968 | continue 969 | 970 | except zlib.error: 971 | continue 972 | 973 | return results 974 | 975 | def get_objects_by_file_order(self, in_use_only=False): 976 | """ 977 | return the objects in the order they appear in the file 978 | instead of the object order (which is how we're doing it currently) 979 | 980 | current-only flag is optional to see if we want only the "in-use" files. 981 | """ 982 | if in_use_only: 983 | current_offsets = self.get_current_object_offsets() 984 | file_ordered_objects = [] 985 | for offset in current_offsets: 986 | for obj in self.obj_dicts: 987 | if obj.get('object_start') == offset: 988 | file_ordered_objects.append(obj) 989 | break 990 | return file_ordered_objects 991 | else: 992 | valid_objects = [obj for obj in self.obj_dicts if obj.get('object_start') is not None] 993 | return sorted(valid_objects, key=lambda obj: obj['object_start']) --------------------------------------------------------------------------------