├── Apache-1.1-Impacket.txt ├── BitsParser.py ├── LICENSE ├── README.md ├── advapi32.py ├── ese ├── LICENSE ├── ese.py └── structure.py └── requirements.txt /Apache-1.1-Impacket.txt: -------------------------------------------------------------------------------- 1 | ---- Impacket (https://github.com/SecureAuthCorp/impacket) ---- 2 | 3 | We provide this software under a slightly modified version of the 4 | Apache Software License. The only changes to the document were the 5 | replacement of "Apache" with "Impacket" and "Apache Software Foundation" 6 | with "SecureAuth Corporation". Feel free to compare the resulting 7 | document to the official Apache license. 8 | 9 | The `Apache Software License' is an Open Source Initiative Approved 10 | License. 11 | 12 | 13 | The Apache Software License, Version 1.1 14 | Modifications by SecureAuth Corporation (see above) 15 | 16 | Copyright (c) 2000 The Apache Software Foundation. All rights 17 | reserved. 18 | 19 | Redistribution and use in source and binary forms, with or without 20 | modification, are permitted provided that the following conditions 21 | are met: 22 | 23 | 1. Redistributions of source code must retain the above copyright 24 | notice, this list of conditions and the following disclaimer. 25 | 26 | 2. Redistributions in binary form must reproduce the above copyright 27 | notice, this list of conditions and the following disclaimer in 28 | the documentation and/or other materials provided with the 29 | distribution. 30 | 31 | 3. The end-user documentation included with the redistribution, 32 | if any, must include the following acknowledgment: 33 | "This product includes software developed by 34 | SecureAuth Corporation (https://www.secureauth.com/)." 35 | Alternately, this acknowledgment may appear in the software itself, 36 | if and wherever such third-party acknowledgments normally appear. 37 | 38 | 4. The names "Impacket", "SecureAuth Corporation" must 39 | not be used to endorse or promote products derived from this 40 | software without prior written permission. For written 41 | permission, please contact oss@secureauth.com. 42 | 43 | 5. Products derived from this software may not be called "Impacket", 44 | nor may "Impacket" appear in their name, without prior written 45 | permission of SecureAuth Corporation. 46 | 47 | THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED 48 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 49 | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 50 | DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR 51 | ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 52 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 53 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 54 | USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 55 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 56 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 57 | OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 58 | SUCH DAMAGE. 59 | -------------------------------------------------------------------------------- /BitsParser.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 FireEye, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 4 | # the License. You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 9 | # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 10 | # specific language governing permissions and limitations under the License. 11 | 12 | 13 | import os 14 | import sys 15 | import json 16 | import string 17 | import struct 18 | import hashlib 19 | import argparse 20 | import datetime 21 | import traceback 22 | 23 | from ese.ese import ESENT_DB 24 | 25 | # On Windows advapi32 will be used to resolve SIDs 26 | try: 27 | import advapi32 28 | except Exception: 29 | pass 30 | 31 | import bits 32 | from bits.structs import FILE, CONTROL, JOB 33 | 34 | 35 | # XFER_HEADER defined as bytes 36 | XFER_HEADER = b'\x36\xDA\x56\x77\x6F\x51\x5A\x43\xAC\xAC\x44\xA2\x48\xFF\xF3\x4D' 37 | 38 | 39 | # File and job delimiter constants for Windows 10 40 | WIN10_FILE_DELIMITER = b'\xE4\xCF\x9E\x51\x46\xD9\x97\x43\xB7\x3E\x26\x85\x13\x05\x1A\xB2' 41 | WIN10_JOB_DELIMITERS = [ 42 | b'\xA1\x56\x09\xE1\x43\xAF\xC9\x42\x92\xE6\x6F\x98\x56\xEB\xA7\xF6', 43 | b'\x9F\x95\xD4\x4C\x64\x70\xF2\x4B\x84\xD7\x47\x6A\x7E\x62\x69\x9F', 44 | b'\xF1\x19\x26\xA9\x32\x03\xBF\x4C\x94\x27\x89\x88\x18\x95\x88\x31', 45 | b'\xC1\x33\xBC\xDD\xFB\x5A\xAF\x4D\xB8\xA1\x22\x68\xB3\x9D\x01\xAD', 46 | b'\xd0\x57\x56\x8f\x2c\x01\x3e\x4e\xad\x2c\xf4\xa5\xd7\x65\x6f\xaf', 47 | b'\x50\x67\x41\x94\x57\x03\x1d\x46\xa4\xcc\x5d\xd9\x99\x07\x06\xe4' 48 | ] 49 | 50 | 51 | class BitsParser: 52 | 53 | def __init__(self, queue_dir, carve_db, carve_all, out_file): 54 | 55 | self.queue_dir = queue_dir 56 | self.carve_db_files = carve_db 57 | self.carve_all_files = carve_all 58 | self.out_file = out_file 59 | 60 | self.sid_user_cache = {} 61 | self.visited_jobs = set() 62 | # Assume files are from Windows 10 by default -- will be verified later 63 | self.is_win_10 = True 64 | 65 | 66 | def get_username_from_sid(self, sid): 67 | """ Returns the username associated with the given SID by calling LookupAccountSid """ 68 | 69 | # Cache usernames to improve efficiency with repeated lookups 70 | if sid in self.sid_user_cache: 71 | return self.sid_user_cache[sid] 72 | try: 73 | name, domain, _ = advapi32.LookupAccountSid(advapi32.ConvertStringSidToSid(sid)) 74 | username = domain+"\\"+name 75 | self.sid_user_cache[sid] = username 76 | return username 77 | except Exception as e: 78 | print(f'Failed to resolve sid {sid}: ' + str(e), file=sys.stderr) 79 | self.sid_user_cache[sid] = None 80 | return None 81 | 82 | 83 | def is_qmgr_database(file_data): 84 | """ Attempts to locate pattern at 0x10 found in qmgr databases (prior to Windows 10) """ 85 | if file_data[0x10:0x20] == b'\x13\xf7\x2b\xc8\x40\x99\x12\x4a\x9f\x1a\x3a\xae\xbd\x89\x4e\xea': 86 | return True 87 | return False 88 | 89 | 90 | def is_qmgr10_database(file_data): 91 | """ Attempts to locate ESE database magic number found in Windows 10 qmgr databases """ 92 | if file_data[4:8] == b'\xEF\xCD\xAB\x89': 93 | return True 94 | return False 95 | 96 | 97 | def load_qmgr_jobs(self, file_path): 98 | """ Processes the given qmgr database file with ANSSI-FR, parses jobs (possibly carves jobs), and returns a list of discovered jobs. """ 99 | 100 | jobs = [] 101 | analyzer = bits.Bits.load_file(file_path) 102 | if self.carve_db_files or self.carve_all_files: 103 | for job in analyzer: 104 | jobs.append(BitsJob(job, self)) 105 | else: 106 | for job in analyzer.parse(): 107 | jobs.append(BitsJob(job, self)) 108 | return jobs 109 | 110 | 111 | def load_non_qmgr_jobs(self, file_data): 112 | """ Attempts to "carve" jobs from non-qmgr files (sometimes job remnants can be found in other files) """ 113 | 114 | jobs = [] 115 | analyzer = bits.Bits() 116 | # Search for the XFER header and get 2KB of data around it 117 | for sample in bits.sample_disk(file_data, XFER_HEADER, 2048): 118 | analyzer.append_data(sample) 119 | # Attempt to parse jobs from memory block 120 | analyzer.guess_info() 121 | for job in analyzer: 122 | jobs.append(BitsJob(job, self)) 123 | return jobs 124 | 125 | 126 | def parse_qmgr10_job(self, job_data): 127 | """Attempt to parse job data from the Win10 qmgr database""" 128 | # Skip small entires that are not valid 129 | if len(job_data) < 128: 130 | return None 131 | try: 132 | 133 | # Because it can be expensive to parse a JOB structure if the data is not valid, 134 | # do a simple check to see if the job name length is valid 135 | name_length = struct.unpack_from(" len(job_data): 137 | return None 138 | 139 | # Parse as a JOB 140 | try: 141 | parsed_job = JOB.parse(job_data) 142 | except Exception: 143 | # If it fails to parse as a JOB, at least try to parse as a CONTROL struct 144 | try: 145 | parsed_job = CONTROL.parse(job_data) 146 | except Exception: 147 | return None 148 | 149 | try: 150 | # Following the JOB entry, there are usually XFER refs to FILE GUIDs 151 | parsed_job['files'] = [] 152 | xfer_parts = job_data.split(XFER_HEADER) 153 | file_ref_data = xfer_parts[1] 154 | num_file_refs = struct.unpack_from(" len(file_ref_data): 157 | return None 158 | for i in range(0, num_file_refs): 159 | # Parse the GUID and attempt to find correlated FILE 160 | cur_guid = file_ref_data[4+i*16:4+(i+1)*16] 161 | file_job = self.file_entries.pop(cur_guid, None) 162 | if file_job: 163 | parsed_job['files'].extend(file_job['files']) 164 | except Exception: 165 | pass 166 | 167 | # Build a BitsJob for the job entry 168 | new_job = BitsJob(parsed_job, self) 169 | return new_job 170 | except Exception: 171 | print(f'Exception occurred parsing job: ' + traceback.format_exc(), file=sys.stderr) 172 | return None 173 | 174 | 175 | def parse_qmgr10_file(self, file_data, suppress_duplicates): 176 | """Attempt to parse file data from the Win10 qmgr database""" 177 | 178 | # Skip small entires that are not valid 179 | if len(file_data) < 256: 180 | return None 181 | try: 182 | # Because it can be expensive to parse a FILE structure if the data is not valid, 183 | # do a simple check to see if the filename length is valid 184 | filename_length = struct.unpack_from(" len(file_data): 186 | return None 187 | 188 | # Parse the FILE 189 | parsed_file = FILE.parse(file_data) 190 | 191 | # Build a BitsJob for the file entry (set entry as files list) 192 | cur_job = {} 193 | cur_job['files'] = [parsed_file] 194 | 195 | # There is usually a timestamp 29 bytes into the file structure, which appears to correlate to creation time 196 | filetime = struct.unpack_from(" 16: 230 | yield guid, val[16:] 231 | except Exception: 232 | pass 233 | 234 | 235 | def load_qmgr10_db(self, file_data): 236 | """Loads the qmgr.db and attempts to enumerate the Jobs and Files tables to parse records""" 237 | jobs = [] 238 | self.file_entries = {} 239 | 240 | # Parse the database 241 | ese = ESENT_DB(file_data) 242 | 243 | # Enumerate files, store file entries to file_entries mapping 244 | files_table = ese.openTable("Files") 245 | while True: 246 | file_record = ese.getNextRow(files_table) 247 | if file_record is None: 248 | break 249 | guid = file_record.get(b'Id') 250 | new_job = self.parse_qmgr10_file(file_record.get(b'Blob', b''), False) 251 | if guid and new_job: 252 | self.file_entries[guid] = new_job 253 | 254 | # Enumerate jobs (and correlate to files) 255 | jobs_table = ese.openTable("Jobs") 256 | while True: 257 | job_record = ese.getNextRow(jobs_table) 258 | if job_record is None: 259 | break 260 | guid = job_record.get(b'Id') 261 | job_data = job_record.get(b'Blob', b'')[16:] 262 | new_job = self.parse_qmgr10_job(job_data) 263 | if guid and new_job: 264 | jobs.append(new_job) 265 | 266 | # If any file records were not correlated to JOBs just add them as their own jobs 267 | for guid, file_job in self.file_entries.items(): 268 | jobs.append(BitsJob(file_job, self)) 269 | 270 | return jobs 271 | 272 | 273 | def carve_qmgr10_records(self, file_data): 274 | """ Attempts to carve jobs from a qmgr database file using expected file and job GUIDs""" 275 | jobs = [] 276 | self.file_entries = {} 277 | 278 | # Carve file entries from the database, store to file_entries mapping 279 | cur_offset = file_data.find(WIN10_FILE_DELIMITER) 280 | while cur_offset > 0: 281 | next_offset = file_data.find(WIN10_FILE_DELIMITER, cur_offset+len(WIN10_FILE_DELIMITER)) 282 | if next_offset > 0: 283 | file_job = self.parse_qmgr10_file(file_data[cur_offset+16:next_offset], True) 284 | else: 285 | file_job = self.parse_qmgr10_file(file_data[cur_offset+16:], True) 286 | if file_job: 287 | guid = file_data[cur_offset-22:cur_offset-6] 288 | self.file_entries[guid] = file_job 289 | cur_offset = next_offset 290 | 291 | # Carve jobs from the database (note that there are multiple potential job delimiters) 292 | for job_delimiter in WIN10_JOB_DELIMITERS: 293 | carved_jobs = file_data.split(job_delimiter) 294 | if len(carved_jobs) == 1: 295 | continue 296 | for i in range(1, len(carved_jobs)): 297 | new_job = self.parse_qmgr10_job(carved_jobs[i]) 298 | if new_job: 299 | new_job.job_dict['Carved'] = True 300 | jobs.append(new_job) 301 | 302 | # If any file records were not correlated to JOBs just add them as their own jobs 303 | for guid, carved_job in self.file_entries.items(): 304 | file_job = BitsJob(carved_job, self) 305 | file_job.job_dict['Carved'] = True 306 | jobs.append(file_job) 307 | 308 | return jobs 309 | 310 | 311 | def load_qmgr10_jobs(self, file_data): 312 | """ 313 | Attempt to parse Windows 10 qmgr jobs by carving JOB and FILE records out of the database using record identifiers. 314 | Unfortunately there is not a way to correlate job and file entries in Win10 qmgr databases, so we have to create separate entries for each. 315 | """ 316 | 317 | # Parse active job and file records in the database 318 | jobs = self.load_qmgr10_db(file_data) 319 | 320 | # Carve deleted job and file entires if requested 321 | if self.carve_db_files or self.carve_all_files: 322 | jobs.extend(self.carve_qmgr10_records(file_data)) 323 | 324 | return jobs 325 | 326 | 327 | def output_jobs(self, file_path, jobs): 328 | """Cleans up and outputs the parsed jobs from the qmgr database files""" 329 | 330 | # If an output file is specified, open it and use it instead of stdout 331 | if self.out_file: 332 | orig_stdout = sys.stdout 333 | sys.stdout = open(self.out_file, "w") 334 | 335 | try: 336 | for job in jobs: 337 | # Skip incomplete carved jobs as they do not contain useful info 338 | if job.is_carved() and not job.is_useful_for_analysis(): 339 | continue 340 | 341 | # Output unique jobs 342 | if job.hash not in self.visited_jobs: 343 | formatted_job = json.dumps(job.job_dict, indent=4) 344 | print(formatted_job) 345 | 346 | self.visited_jobs.add(job.hash) 347 | finally: 348 | if self.out_file: 349 | sys.stdout.close() 350 | sys.stdout = orig_stdout 351 | 352 | 353 | def process_file(self, file_path): 354 | """ Processes the given BITS file. Attempts to find/parse jobs. """ 355 | 356 | try: 357 | # Read the file (may need to raw read) 358 | print("Processing file "+file_path, file=sys.stderr) 359 | file_data = None 360 | with open(file_path, "rb") as f: 361 | file_data = f.read() 362 | 363 | # Parse as a qmgr database (support old and Win10 formats) 364 | jobs = [] 365 | if BitsParser.is_qmgr_database(file_data): 366 | jobs = self.load_qmgr_jobs(file_path) 367 | elif BitsParser.is_qmgr10_database(file_data): 368 | jobs = self.load_qmgr10_jobs(file_data) 369 | 370 | # Try to "carve" jobs if the file is not a qmgr database (and carving is enabled) 371 | elif self.carve_all_files: 372 | if self.is_win_10: 373 | jobs = self.carve_qmgr10_records(file_data) 374 | else: 375 | jobs = self.load_non_qmgr_jobs(file_data) 376 | 377 | self.output_jobs(file_path, jobs) 378 | 379 | except Exception: 380 | print(f'Exception occurred processing file {file_path}: ' + traceback.format_exc(), file=sys.stderr) 381 | 382 | 383 | def determine_directory_architecture(self, path): 384 | """ Determines if the files within the directory suggest it came from a Windows 10 system or an older system """ 385 | if os.path.exists(path + os.sep + "qmgr.db"): 386 | self.is_win_10 = True 387 | elif os.path.exists(path + os.sep + "qmgr0.dat"): 388 | self.is_win_10 = False 389 | 390 | 391 | def run(self): 392 | """ Finds and processes BITS database files """ 393 | 394 | # If the queue "directory" is a file, just process the file 395 | if os.path.isfile(self.queue_dir): 396 | self.process_file(self.queue_dir) 397 | return 398 | 399 | # Determine if the directory appears to belong to a Windows 10 system or an older system for carving 400 | self.determine_directory_architecture(self.queue_dir) 401 | 402 | # List files in the queue directory and process 403 | for f in os.listdir(self.queue_dir): 404 | cur_path = self.queue_dir + os.sep + f 405 | if not os.path.isfile(cur_path): 406 | continue 407 | self.process_file(cur_path) 408 | 409 | 410 | class BitsJob: 411 | """ 412 | Provides methods for reformatting parsed jobs from the ANSSI-FR library 413 | """ 414 | 415 | # Mappings between types returned by ANSSI-FR library and our output fields 416 | FILE_MAP = dict( 417 | src_fn="SourceURL", 418 | dest_fn="DestFile", 419 | tmp_fn="TmpFile", 420 | download_size="DownloadByteSize", 421 | transfer_size="TransferByteSize", 422 | vol_guid="VolumeGUID" 423 | ) 424 | 425 | JOB_MAP = dict( 426 | job_id="JobId", 427 | type="JobType", 428 | priority="JobPriority", 429 | state="JobState", 430 | name="JobName", 431 | desc="JobDesc", 432 | cmd="CommandExecuted", 433 | args="CommandArguments", 434 | sid="OwnerSID", 435 | ctime="CreationTime", 436 | mtime="ModifiedTime", 437 | carved="Carved", 438 | files="Files", 439 | queue_path="QueuePath" 440 | ) 441 | 442 | 443 | def __init__(self, job, bits_parser): 444 | """ Initialize a BitsJob with a parsed job dictionary and a reference to BitsParser """ 445 | self.job = job 446 | self.bits_parser = bits_parser 447 | self.hash = None 448 | 449 | self.job_dict = {} 450 | if bits_parser.carve_db_files or bits_parser.carve_all_files: 451 | self.job_dict = {'Carved': False} 452 | 453 | self.parse() 454 | 455 | 456 | def is_useful_for_analysis(self, cur_dict=None): 457 | """ Returns True if the job contains at least one "useful" field (discards useless "carved" entries) and the ctime field exists """ 458 | useful_fields = ['SourceURL', 'DestFile', 'TmpFile', 'JobId', 'JobState', 'CommandExecuted', 'CommandArguments'] 459 | 460 | if not cur_dict: 461 | cur_dict = self.job_dict 462 | 463 | for k, v in cur_dict.items(): 464 | if k in useful_fields and v: 465 | return True 466 | # Handle lists of dicts, like we have for the Files field 467 | if isinstance(v, list): 468 | for d in v: 469 | if self.is_useful_for_analysis(d): 470 | return True 471 | return False 472 | 473 | 474 | def is_carved(self): 475 | """ Simple function returns True if the job was carved """ 476 | return self.job_dict.get('Carved') is True 477 | 478 | 479 | @staticmethod 480 | def escape(input_str): 481 | """ Simple escape function to eliminating non-printable characters from strings """ 482 | if not isinstance(input_str, str) or input_str.isprintable(): 483 | return input_str 484 | return ''.join(filter(lambda x: x in string.printable, input_str)) 485 | 486 | 487 | def parse(self): 488 | """ 489 | Converts the fields in self.job into format used for output and separates file entries. 490 | Does some formatting and type conversion. Also computes a hash of the job for quick comparison. 491 | """ 492 | 493 | file_fields = ['args', 'cmd', 'dest_fn', 'tmp_fn'] 494 | job_hash = hashlib.md5() 495 | for k, v in self.job.items(): 496 | # Map the attribute name, skip empty or unmapped values 497 | alias = self.JOB_MAP.get(k) 498 | if not alias: 499 | continue 500 | elif not v or str(v).strip() == '': 501 | continue 502 | 503 | # Convert timestamps into normal isoformat 504 | elif isinstance(v, datetime.datetime): 505 | self.job_dict[alias] = v.replace(microsecond=0).isoformat() + 'Z' 506 | 507 | # Convert boolean values to lowercase 508 | elif isinstance(v, bool): 509 | self.job_dict[alias] = str(v).lower() 510 | 511 | # If this is a SID, convert to username and set owner 512 | elif alias == self.JOB_MAP['sid']: 513 | self.job_dict[alias] = str(v) 514 | owner = self.bits_parser.get_username_from_sid(v) 515 | if owner: 516 | self.job_dict["Owner"] = owner 517 | 518 | # The files field contains a list of files -- perform attribute mapping and environment variable resolution 519 | elif alias == self.JOB_MAP['files']: 520 | files_list = [] 521 | for file in v: 522 | file_dict = {} 523 | for k1, v1 in file.items(): 524 | 525 | # Map the transaction attribute name, skip empty, unmapped, or invalid values 526 | t_alias = self.FILE_MAP.get(k1) 527 | if not t_alias: 528 | continue 529 | elif v1 is None or str(v1).strip() == '' or not str(v1).isprintable(): 530 | continue 531 | 532 | # Skip certain invalid values (if there is no value or if the value is -1 (DWORD64)) 533 | if v1 is None or v1 == 0xFFFFFFFFFFFFFFFF: 534 | continue 535 | 536 | # If this is a file field, resolve and add to the list of files 537 | if k1 in file_fields: 538 | file_dict[t_alias] = os.path.expandvars(v1) 539 | else: 540 | file_dict[t_alias] = v1 541 | 542 | # Update the object hash 543 | job_hash.update(str(file_dict[t_alias]).encode('utf-8')) 544 | files_list.append(file_dict) 545 | 546 | self.job_dict['Files'] = files_list 547 | else: 548 | self.job_dict[alias] = v 549 | 550 | # Escape non-printable chars if appropriate 551 | self.job_dict[alias] = self.escape(self.job_dict[alias]) 552 | 553 | # Update the object hash 554 | if type(v) is not 'Dict': 555 | job_hash.update(str(v).encode('utf-8')) 556 | 557 | self.hash = job_hash.hexdigest() 558 | 559 | 560 | if __name__ == '__main__': 561 | 562 | parser = argparse.ArgumentParser() 563 | parser.add_argument('--input', '-i', default='%ALLUSERSPROFILE%\\Microsoft\\Network\\Downloader', help='Optionally specify the directory containing QMGR databases or the path to a file to process.') 564 | parser.add_argument('--output', '-o', help='Optionally specify a file for JSON output. If not specified the output will be printed to stdout.') 565 | parser.add_argument('--carvedb', action='store_true', help='Carve deleted records from database files') 566 | parser.add_argument('--carveall', action='store_true', help='Carve deleted records from all other files') 567 | parsed_args = parser.parse_args() 568 | 569 | queue_dir = os.path.expandvars(parsed_args.input) 570 | bits_parser = BitsParser(queue_dir, parsed_args.carvedb, parsed_args.carveall, parsed_args.output) 571 | bits_parser.run() 572 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2021 FireEye, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BitsParser 2 | 3 | A python tool to parse Windows Background Intelligent Transfer Service database files. 4 | 5 | 6 | ## Intro 7 | 8 | BitsParser is a Python 3 script that can parse Windows Background Intelligent Transfer Service database files and extract job and file information. It supports both the original custom database format as well as the ESE database format used on Windows 10 systems. 9 | 10 | 11 | ## Installation 12 | 13 | BitsParser is written in Python 3. It will run on any platform Python supports, though SID resolution will only work on Windows. 14 | 15 | Before running the tool, you will have to install required packages defined in requirements.txt. To do this, run the following command (may require administrator-level privileges): 16 | 17 | `pip install -r requirements.txt` 18 | 19 | ## Usage 20 | 21 | To use BitsPaser, simply run BitsParser.py with Python 3. There are some options that can be specified to control carving, inputs, and outputs. 22 | 23 | ``` 24 | usage: BitsParser.py [-h] [--input INPUT] [--output OUTPUT] [--carvedb] 25 | [--carveall] 26 | 27 | optional arguments: 28 | -h, --help show this help message and exit 29 | --input INPUT Optionally specify the directory containing QMGR databases 30 | or the path to a file to process. 31 | --output OUTPUT Optionally specify a file for JSON output. If not specified 32 | the output will be printed to stdout. 33 | --carvedb Carve deleted records from database files 34 | --carveall Carve deleted records from all other files 35 | ``` 36 | 37 | By default BitsParser will process files in the `%ALLUSERSPROFILE%\Microsoft\Network\Downloader`. Use the `-i` option to specify an alternate file or directory. The script can be used with offline files from alternate operating systems. 38 | 39 | By default BitsParser will output the parsing results in JSON format to stdout. To direct the output to a file, use the `-o` option. 40 | 41 | By default BitsParser will only parse and output active jobs and files. To carve deleted entries from the database use `--carvedb`. To carve entries from all file types, including transaction logs, use `--carveall`. 42 | 43 | ## Example 44 | 45 | Below is a simple example showing how the BitsParser tool is run and what the output looks like: 46 | 47 | ``` 48 | > python BitsParser.py -i qmgr.db 49 | Processing file qmgr.db 50 | { 51 | "JobType": "download", 52 | "JobPriority": "normal", 53 | "JobState": "suspended", 54 | "JobId": "b733e5e1-12ad-463e-a125-ade26cc1fab6", 55 | "JobName": "SpeechModelDownloadJob", 56 | "OwnerSID": "S-1-5-20", 57 | "Owner": "NT AUTHORITY\\NETWORK SERVICE", 58 | "CreationTime": "2021-01-25T11:52:05Z", 59 | "ModifiedTime": "2021-01-25T12:45:21Z" 60 | } 61 | ``` 62 | 63 | ## Acknowledgments 64 | 65 | This product includes a portion of the Impacket software developed by SecureAuth Corporation (https://www.secureauth.com/). 66 | This product also makes use of ANSSI-FR bits_parser Python library (https://github.com/ANSSI-FR/bits_parser). 67 | -------------------------------------------------------------------------------- /advapi32.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 FireEye, Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 4 | # the License. You may obtain a copy of the License at 5 | # 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # 8 | # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 9 | # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 10 | # specific language governing permissions and limitations under the License. 11 | 12 | import ctypes 13 | from ctypes import wintypes 14 | 15 | advapi32 = ctypes.windll.advapi32 16 | 17 | _In_ = 1 # Specifies an input parameter to the function. 18 | _Out_ = 2 # Output parameter. The foreign function fills in a value. 19 | 20 | 21 | PSID = ctypes.POINTER(wintypes.BYTE) 22 | UNLEN = 256 23 | 24 | 25 | def errcheckBOOL(result, func, args): 26 | """Callback for APIs that return type BOOL.""" 27 | if result == 0: 28 | raise ctypes.WinError() 29 | return args 30 | 31 | 32 | def ConvertStringSidToSid(strsid): 33 | prototype = ctypes.WINFUNCTYPE( 34 | wintypes.BOOL, # return type 35 | wintypes.LPCWSTR, 36 | ctypes.POINTER(wintypes.PBYTE), 37 | ) 38 | 39 | paramflags = ( 40 | (_In_, 'StringSid'), 41 | (_Out_, 'Sid') 42 | ) 43 | 44 | _ConvertStringSidToSid_ = prototype(('ConvertStringSidToSidW', advapi32), paramflags) 45 | _ConvertStringSidToSid_.errcheck = errcheckBOOL 46 | return _ConvertStringSidToSid_(strsid) 47 | 48 | 49 | def LookupAccountSid(sid, machine=None): 50 | prototype = ctypes.WINFUNCTYPE( 51 | wintypes.BOOL, # return value 52 | wintypes.LPCWSTR, 53 | PSID, 54 | wintypes.LPCWSTR, 55 | wintypes.LPDWORD, 56 | wintypes.LPCWSTR, 57 | wintypes.LPDWORD, 58 | wintypes.LPDWORD 59 | ) 60 | paramflags = ( 61 | (_In_, 'lpSystemName'), 62 | (_In_, 'lpSid'), 63 | (_Out_, 'lpName', ctypes.create_unicode_buffer(UNLEN)), 64 | (_In_, 'cchName', ctypes.byref(wintypes.DWORD(UNLEN))), 65 | (_Out_, 'lpReferencedDomainName', ctypes.create_unicode_buffer(UNLEN)), 66 | (_In_, 'cchReferencedDomainName', ctypes.byref(wintypes.DWORD(UNLEN))), 67 | (_Out_, 'peUse') 68 | ) 69 | _LookupAccountSid = prototype(('LookupAccountSidW', advapi32), paramflags) 70 | _LookupAccountSid.errcheck = errcheckBOOL 71 | lpname, lprefdn, peuse = _LookupAccountSid(machine, sid) 72 | return (lpname.value, lprefdn.value, peuse) 73 | -------------------------------------------------------------------------------- /ese/LICENSE: -------------------------------------------------------------------------------- 1 | ---- Impacket (https://github.com/SecureAuthCorp/impacket) ---- 2 | 3 | We provide this software under a slightly modified version of the 4 | Apache Software License. The only changes to the document were the 5 | replacement of "Apache" with "Impacket" and "Apache Software Foundation" 6 | with "SecureAuth Corporation". Feel free to compare the resulting 7 | document to the official Apache license. 8 | 9 | The `Apache Software License' is an Open Source Initiative Approved 10 | License. 11 | 12 | 13 | The Apache Software License, Version 1.1 14 | Modifications by SecureAuth Corporation (see above) 15 | 16 | Copyright (c) 2000 The Apache Software Foundation. All rights 17 | reserved. 18 | 19 | Redistribution and use in source and binary forms, with or without 20 | modification, are permitted provided that the following conditions 21 | are met: 22 | 23 | 1. Redistributions of source code must retain the above copyright 24 | notice, this list of conditions and the following disclaimer. 25 | 26 | 2. Redistributions in binary form must reproduce the above copyright 27 | notice, this list of conditions and the following disclaimer in 28 | the documentation and/or other materials provided with the 29 | distribution. 30 | 31 | 3. The end-user documentation included with the redistribution, 32 | if any, must include the following acknowledgment: 33 | "This product includes software developed by 34 | SecureAuth Corporation (https://www.secureauth.com/)." 35 | Alternately, this acknowledgment may appear in the software itself, 36 | if and wherever such third-party acknowledgments normally appear. 37 | 38 | 4. The names "Impacket", "SecureAuth Corporation" must 39 | not be used to endorse or promote products derived from this 40 | software without prior written permission. For written 41 | permission, please contact oss@secureauth.com. 42 | 43 | 5. Products derived from this software may not be called "Impacket", 44 | nor may "Impacket" appear in their name, without prior written 45 | permission of SecureAuth Corporation. 46 | 47 | THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED 48 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 49 | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 50 | DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR 51 | ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 52 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 53 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 54 | USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 55 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 56 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 57 | OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 58 | SUCH DAMAGE. 59 | -------------------------------------------------------------------------------- /ese/ese.py: -------------------------------------------------------------------------------- 1 | # SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. 2 | # 3 | # This software is provided under under a slightly modified version 4 | # of the Apache Software License. See the accompanying LICENSE file 5 | # for more information. 6 | # 7 | # Description: Microsoft Extensible Storage Engine parser 8 | # Author: Alberto Solino (@agsolino) 9 | 10 | from collections import OrderedDict 11 | from ese.structure import Structure 12 | from struct import unpack, pack 13 | 14 | # Constants 15 | 16 | FILE_TYPE_DATABASE = 0 17 | FILE_TYPE_STREAMING_FILE = 1 18 | 19 | # Database state 20 | JET_dbstateJustCreated = 1 21 | JET_dbstateDirtyShutdown = 2 22 | JET_dbstateCleanShutdown = 3 23 | JET_dbstateBeingConverted = 4 24 | JET_dbstateForceDetach = 5 25 | 26 | # Page Flags 27 | FLAGS_ROOT = 1 28 | FLAGS_LEAF = 2 29 | FLAGS_PARENT = 4 30 | FLAGS_EMPTY = 8 31 | FLAGS_SPACE_TREE = 0x20 32 | FLAGS_INDEX = 0x40 33 | FLAGS_LONG_VALUE = 0x80 34 | FLAGS_NEW_FORMAT = 0x2000 35 | FLAGS_NEW_CHECKSUM = 0x2000 36 | 37 | # Tag Flags 38 | TAG_UNKNOWN = 0x1 39 | TAG_DEFUNCT = 0x2 40 | TAG_COMMON = 0x4 41 | 42 | # Fixed Page Numbers 43 | DATABASE_PAGE_NUMBER = 1 44 | CATALOG_PAGE_NUMBER = 4 45 | CATALOG_BACKUP_PAGE_NUMBER = 24 46 | 47 | # Fixed FatherDataPages 48 | DATABASE_FDP = 1 49 | CATALOG_FDP = 2 50 | CATALOG_BACKUP_FDP = 3 51 | 52 | # Catalog Types 53 | CATALOG_TYPE_TABLE = 1 54 | CATALOG_TYPE_COLUMN = 2 55 | CATALOG_TYPE_INDEX = 3 56 | CATALOG_TYPE_LONG_VALUE = 4 57 | CATALOG_TYPE_CALLBACK = 5 58 | 59 | # Column Types 60 | JET_coltypNil = 0 61 | JET_coltypBit = 1 62 | JET_coltypUnsignedByte = 2 63 | JET_coltypShort = 3 64 | JET_coltypLong = 4 65 | JET_coltypCurrency = 5 66 | JET_coltypIEEESingle = 6 67 | JET_coltypIEEEDouble = 7 68 | JET_coltypDateTime = 8 69 | JET_coltypBinary = 9 70 | JET_coltypText = 10 71 | JET_coltypLongBinary = 11 72 | JET_coltypLongText = 12 73 | JET_coltypSLV = 13 74 | JET_coltypUnsignedLong = 14 75 | JET_coltypLongLong = 15 76 | JET_coltypGUID = 16 77 | JET_coltypUnsignedShort= 17 78 | JET_coltypMax = 18 79 | 80 | ColumnTypeToName = { 81 | JET_coltypNil : 'NULL', 82 | JET_coltypBit : 'Boolean', 83 | JET_coltypUnsignedByte : 'Signed byte', 84 | JET_coltypShort : 'Signed short', 85 | JET_coltypLong : 'Signed long', 86 | JET_coltypCurrency : 'Currency', 87 | JET_coltypIEEESingle : 'Single precision FP', 88 | JET_coltypIEEEDouble : 'Double precision FP', 89 | JET_coltypDateTime : 'DateTime', 90 | JET_coltypBinary : 'Binary', 91 | JET_coltypText : 'Text', 92 | JET_coltypLongBinary : 'Long Binary', 93 | JET_coltypLongText : 'Long Text', 94 | JET_coltypSLV : 'Obsolete', 95 | JET_coltypUnsignedLong : 'Unsigned long', 96 | JET_coltypLongLong : 'Long long', 97 | JET_coltypGUID : 'GUID', 98 | JET_coltypUnsignedShort: 'Unsigned short', 99 | JET_coltypMax : 'Max', 100 | } 101 | 102 | ColumnTypeSize = { 103 | JET_coltypNil : None, 104 | JET_coltypBit : (1,'B'), 105 | JET_coltypUnsignedByte : (1,'B'), 106 | JET_coltypShort : (2,' 8192: 259 | self.structure += self.extended_win7 260 | 261 | Structure.__init__(self,data) 262 | 263 | class ESENT_ROOT_HEADER(Structure): 264 | structure = ( 265 | ('InitialNumberOfPages',' 0: 288 | self.structure = self.common + self.structure 289 | Structure.__init__(self,data) 290 | 291 | class ESENT_LEAF_HEADER(Structure): 292 | structure = ( 293 | ('CommonPageKey',':'), 294 | ) 295 | 296 | class ESENT_LEAF_ENTRY(Structure): 297 | common = ( 298 | ('CommonPageKeySize',' 0: 308 | self.structure = self.common + self.structure 309 | Structure.__init__(self,data) 310 | 311 | class ESENT_SPACE_TREE_HEADER(Structure): 312 | structure = ( 313 | ('Unknown','= self.record['FirstAvailablePageTag']: 405 | raise Exception(f'Requested tag number 0x{tagNum:X} exceeds page limit') 406 | 407 | # The tags are in an array at the end of the page (4 bytes each) 408 | if tagNum == 0: 409 | tag = self.data[-4:] 410 | else: 411 | tag = self.data[-4*(tagNum+1):-4*tagNum] 412 | 413 | # Offsets are relative to the ESENT_PAGE struct 414 | baseOffset = len(self.record) 415 | 416 | # New database format uses 15-bit numbers for size and offset 417 | if self.__DBHeader['Version'] == 0x620 and self.__DBHeader['FileFormatRevision'] >= 17 and self.__DBHeader['PageSize'] > 8192: 418 | valueSize = unpack('> 5 422 | tmpData[1] = tmpData[1] & 0x1f 423 | tagData = bytes(tmpData) 424 | else: 425 | valueSize = unpack('> 13 427 | valueOffset = unpack(' 127: 474 | numEntries = dataDefinitionHeader['LastVariableDataType'] - 127 475 | else: 476 | numEntries = dataDefinitionHeader['LastVariableDataType'] 477 | 478 | itemLen = unpack(' len(data): 517 | continue 518 | 519 | # If there is common key data defined, prepend it to the current key data 520 | if common_key_data: 521 | key_data = common_key_data + data[cur_offset:cur_offset+key_size] 522 | else: 523 | key_data = data[cur_offset:cur_offset+key_size] 524 | 525 | cur_offset += key_size 526 | # The value contains all data in the tag after the key 527 | value_size = len(data) - cur_offset 528 | value_data = data[cur_offset:cur_offset+value_size] 529 | longValues[key_data] = value_data 530 | 531 | return longValues 532 | 533 | def getLongValue(self, cursor, data): 534 | """Gets the long value for the given data by looking up references in the already-parsed long values table""" 535 | try: 536 | # For some reason the ID is stored big endian 537 | data_be = data[::-1] 538 | long_data = cursor['LongValues'].get(data_be) 539 | # The initial long entry contains an unknown value and total long data size 540 | _, long_data_size = unpack("I", cur_offset) 548 | cur_data = cursor['LongValues'].get(cur_key) 549 | # If there was no more data but we still had some data, return it 550 | if not cur_data and len(combined_data) > 0: 551 | return bytes(combined_data) 552 | 553 | combined_data.extend(cur_data) 554 | cur_offset += len(cur_data) 555 | 556 | # Return the combined long data as bytes 557 | return bytes(combined_data) 558 | 559 | # If an exception occurs, just return the original data 560 | except Exception: 561 | return data 562 | 563 | def parsePage(self, page): 564 | """Parses a catalog page and adds relevant information to the table structures""" 565 | 566 | # Safety check to exclude page types that should not be in the catalog 567 | if page.record['PageFlags'] & (FLAGS_LEAF | FLAGS_SPACE_TREE | FLAGS_INDEX | FLAGS_LONG_VALUE) == 0: 568 | return 569 | 570 | # Enumerate tags in the page 571 | for tagNum in range(1,page.record['FirstAvailablePageTag']): 572 | flags, data = page.getTag(tagNum) 573 | leafEntry = ESENT_LEAF_ENTRY(flags, data) 574 | self.__addItem(leafEntry) 575 | 576 | def parseCatalog(self, pageNum): 577 | """Parse all the catalog pages starting at pageNum and adds relevant information to the table structures""" 578 | page = self.getPage(pageNum) 579 | self.parsePage(page) 580 | 581 | # Recursively process referenced pages from branch page tags 582 | if page.record['PageFlags'] & FLAGS_LEAF == 0: 583 | for i in range(1, page.record['FirstAvailablePageTag']): 584 | flags, data = page.getTag(i) 585 | branchEntry = ESENT_BRANCH_ENTRY(flags, data) 586 | self.parseCatalog(branchEntry['ChildPageNumber']) 587 | 588 | def getPage(self, pageNum): 589 | """Reads the specified page and parses headers (except on the root page)""" 590 | offset = (pageNum+1)*self.__pageSize 591 | data = self.__fileData[offset:offset+self.__pageSize] 592 | 593 | # Special case for the first page 594 | if pageNum <= 0: 595 | return data 596 | else: 597 | return ESENT_PAGE(self.__DBHeader, data) 598 | 599 | def openTable(self, tableName): 600 | """Opens and retunrs a cursor to enumerate entries in the specified table""" 601 | 602 | if not isinstance(tableName, bytes): 603 | tableName = tableName.encode("latin-1") 604 | 605 | # Get the cached table object 606 | cur_table = self.__tables.get(tableName) 607 | if not cur_table: 608 | return None 609 | 610 | entry = cur_table['TableEntry'] 611 | dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(entry['EntryData']) 612 | catalogEntry = ESENT_CATALOG_DATA_DEFINITION_ENTRY(entry['EntryData'][len(dataDefinitionHeader):]) 613 | 614 | # Find the first leaf node 615 | pageNum = catalogEntry['FatherDataPageNumber'] 616 | done = False 617 | while not done: 618 | page = self.getPage(pageNum) 619 | # If there are no records, return the first page 620 | if page.record['FirstAvailablePageTag'] <= 1: 621 | done = True 622 | 623 | # Enumerate tags for the current page 624 | for i in range(1, page.record['FirstAvailablePageTag']): 625 | flags, data = page.getTag(i) 626 | 627 | # If this is a branch node, check child page 628 | if page.record['PageFlags'] & FLAGS_LEAF == 0: 629 | branchEntry = ESENT_BRANCH_ENTRY(flags, data) 630 | pageNum = branchEntry['ChildPageNumber'] 631 | break 632 | # Otherwise, stop 633 | else: 634 | done = True 635 | break 636 | 637 | cursor = TABLE_CURSOR 638 | cursor['TableData'] = self.__tables[tableName] 639 | cursor['FatherDataPageNumber'] = catalogEntry['FatherDataPageNumber'] 640 | cursor['CurrentPageData'] = page 641 | cursor['CurrentTag'] = 0 642 | 643 | # Create a mapping of the long values tree 644 | cursor['LongValues'] = self.__getLongValues(cursor['TableData']['LongValues']['FatherDataPageNumber']) 645 | 646 | return cursor 647 | 648 | def __getNextTag(self, cursor): 649 | """ 650 | Given a cursor, finds the next valid tag in the page. Returns None when the end of the tags are reached for the 651 | current page or if the current page is not a leaf since the tags are actually branches. 652 | """ 653 | page = cursor['CurrentPageData'] 654 | 655 | # If this isn't a leaf page, move to the next page 656 | if page.record['PageFlags'] & FLAGS_LEAF == 0: 657 | return None 658 | 659 | # Find the next non-defunct tag 660 | tag_flags = None 661 | tag_data = None 662 | while cursor['CurrentTag'] < page.record['FirstAvailablePageTag']: 663 | tag_flags, tag_data = page.getTag(cursor['CurrentTag']) 664 | if tag_flags & TAG_DEFUNCT: 665 | cursor['CurrentTag'] += 1 666 | continue 667 | else: 668 | break 669 | 670 | # If we have reached the last tag of this page, return None to move to the next page 671 | if cursor['CurrentTag'] >= page.record['FirstAvailablePageTag']: 672 | return None 673 | 674 | # Check for unexpected page flags 675 | if page.record['PageFlags'] & FLAGS_SPACE_TREE > 0: 676 | raise Exception('FLAGS_SPACE_TREE > 0') 677 | elif page.record['PageFlags'] & FLAGS_INDEX > 0: 678 | raise Exception('FLAGS_INDEX > 0') 679 | elif page.record['PageFlags'] & FLAGS_LONG_VALUE > 0: 680 | raise Exception('FLAGS_LONG_VALUE > 0') 681 | 682 | # Return the tag entry 683 | leafEntry = ESENT_LEAF_ENTRY(tag_flags, tag_data) 684 | return leafEntry 685 | 686 | def getNextRow(self, cursor): 687 | """Retrieves the next row (aka tag) for the given cursor position in the table""" 688 | 689 | # Increment the tag number and get the next valid tag from the current page 690 | cursor['CurrentTag'] += 1 691 | tag = self.__getNextTag(cursor) 692 | 693 | # If there are no more tags on this page, try the next page 694 | if tag is None: 695 | page = cursor['CurrentPageData'] 696 | if page.record['NextPageNumber'] == 0: 697 | return None 698 | else: 699 | cursor['CurrentPageData'] = self.getPage(page.record['NextPageNumber']) 700 | cursor['CurrentTag'] = 0 701 | return self.getNextRow(cursor) 702 | 703 | # Otherwise, parse the current tag data into a record (resolving columns, long values, etc.) 704 | else: 705 | return self.__tagToRecord(cursor, tag['EntryData']) 706 | 707 | def __tagToRecord(self, cursor, tag): 708 | # So my brain doesn't forget, the data record is composed of: 709 | # Header 710 | # Fixed Size Data (ID < 127) 711 | # The easiest to parse. Their size is fixed in the record. You can get its size 712 | # from the Column Record, field SpaceUsage 713 | # Variable Size Data (127 < ID < 255) 714 | # At VariableSizeOffset you get an array of two bytes per variable entry, pointing 715 | # to the length of the value. Values start at: 716 | # numEntries = LastVariableDataType - 127 717 | # VariableSizeOffset + numEntries * 2 (bytes) 718 | # Tagged Data ( > 255 ) 719 | # After the Variable Size Value, there's more data for the tagged values. 720 | # Right at the beginning there's another array (taggedItems), pointing to the 721 | # values, size. 722 | # 723 | # The interesting thing about this DB records is there's no need for all the columns to be there, hence 724 | # saving space. That's why I got over all the columns, and if I find data (of any type), i assign it. If 725 | # not, the column's empty. 726 | 727 | record = OrderedDict() 728 | taggedItems = OrderedDict() 729 | taggedItemsParsed = False 730 | 731 | dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(tag) 732 | variableDataBytesProcessed = (dataDefinitionHeader['LastVariableDataType'] - 127) * 2 733 | prevItemLen = 0 734 | tagLen = len(tag) 735 | fixedSizeOffset = len(dataDefinitionHeader) 736 | variableSizeOffset = dataDefinitionHeader['VariableSizeOffset'] 737 | 738 | columns = cursor['TableData']['Columns'] 739 | 740 | for column in list(columns.keys()): 741 | columnRecord = columns[column]['Record'] 742 | if columnRecord['Identifier'] <= dataDefinitionHeader['LastFixedSize']: 743 | # Fixed Size column data type, still available data 744 | record[column] = tag[fixedSizeOffset:][:columnRecord['SpaceUsage']] 745 | fixedSizeOffset += columnRecord['SpaceUsage'] 746 | 747 | elif 127 < columnRecord['Identifier'] <= dataDefinitionHeader['LastVariableDataType']: 748 | # Variable data type 749 | index = columnRecord['Identifier'] - 127 - 1 750 | itemLen = unpack(' 255: 766 | # Have we parsed the tagged items already? 767 | if taggedItemsParsed is False and (variableDataBytesProcessed+variableSizeOffset) < tagLen: 768 | index = variableDataBytesProcessed+variableSizeOffset 769 | endOfVS = self.__pageSize 770 | firstOffsetTag = (unpack('= 17 and self.__DBHeader['PageSize'] > 8192: 777 | flagsPresent = 1 778 | else: 779 | flagsPresent = (unpack('= firstOffsetTag: 785 | # We reached the end of the variable size array 786 | break 787 | 788 | # Calculate length of variable items 789 | prevKey = list(taggedItems.keys())[0] 790 | for i in range(1,len(taggedItems)): 791 | offset0, length, flags = taggedItems[prevKey] 792 | offset, _, _ = list(taggedItems.items())[i][1] 793 | taggedItems[prevKey] = (offset0, offset-offset0, flags) 794 | prevKey = list(taggedItems.keys())[i] 795 | taggedItemsParsed = True 796 | 797 | # Tagged data type 798 | if columnRecord['Identifier'] in taggedItems: 799 | offsetItem = variableDataBytesProcessed + variableSizeOffset + taggedItems[columnRecord['Identifier']][0] 800 | itemSize = taggedItems[columnRecord['Identifier']][1] 801 | # If the item has flags, get them and adjust offset 802 | if taggedItems[columnRecord['Identifier']][2] > 0: 803 | itemFlag = ord(tag[offsetItem:offsetItem+1]) 804 | record.flags = itemFlag 805 | offsetItem += 1 806 | itemSize -= 1 807 | else: 808 | itemFlag = 0 809 | 810 | # Compressed data not currently handled 811 | if itemFlag & (TAGGED_DATA_TYPE_COMPRESSED ): 812 | record[column] = None 813 | # Long values 814 | elif itemFlag & TAGGED_DATA_TYPE_STORED: 815 | data = tag[offsetItem:offsetItem+itemSize] 816 | record[column] = self.getLongValue(cursor, data) 817 | 818 | elif itemFlag & TAGGED_DATA_TYPE_MULTI_VALUE: 819 | record[column] = (tag[offsetItem:offsetItem+itemSize],) 820 | else: 821 | record[column] = tag[offsetItem:offsetItem+itemSize] 822 | 823 | else: 824 | record[column] = None 825 | else: 826 | record[column] = None 827 | 828 | # If we understand the data type, we unpack it and cast it accordingly otherwise, we just encode it in hex 829 | if type(record[column]) is tuple: 830 | # Not decoding multi value data 831 | record[column] = record[column][0] 832 | elif columnRecord['ColumnType'] == JET_coltypText or columnRecord['ColumnType'] == JET_coltypLongText: 833 | # Strings 834 | if record[column] is not None: 835 | if columnRecord['CodePage'] not in StringCodePages: 836 | raise Exception('Unknown codepage 0x%x'% columnRecord['CodePage']) 837 | stringDecoder = StringCodePages[columnRecord['CodePage']] 838 | 839 | try: 840 | record[column] = record[column].decode(stringDecoder) 841 | except Exception: 842 | record[column] = record[column].decode(stringDecoder, "replace") 843 | pass 844 | else: 845 | unpackData = ColumnTypeSize[columnRecord['ColumnType']] 846 | if record[column] is not None and unpackData is not None: 847 | unpackStr = unpackData[1] 848 | record[column] = unpack(unpackStr, record[column])[0] 849 | 850 | return record 851 | -------------------------------------------------------------------------------- /ese/structure.py: -------------------------------------------------------------------------------- 1 | # SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. 2 | # 3 | # This software is provided under under a slightly modified version 4 | # of the Apache Software License. See the accompanying LICENSE file 5 | # for more information. 6 | # 7 | 8 | from struct import pack, unpack, calcsize 9 | 10 | class Structure: 11 | """ sublcasses can define commonHdr and/or structure. 12 | each of them is an tuple of either two: (fieldName, format) or three: (fieldName, ':', class) fields. 13 | [it can't be a dictionary, because order is important] 14 | 15 | where format specifies how the data in the field will be converted to/from bytes (string) 16 | class is the class to use when unpacking ':' fields. 17 | 18 | each field can only contain one value (or an array of values for *) 19 | i.e. struct.pack('Hl',1,2) is valid, but format specifier 'Hl' is not (you must use 2 dfferent fields) 20 | 21 | format specifiers: 22 | specifiers from module pack can be used with the same format 23 | see struct.__doc__ (pack/unpack is finally called) 24 | x [padding byte] 25 | c [character] 26 | b [signed byte] 27 | B [unsigned byte] 28 | h [signed short] 29 | H [unsigned short] 30 | l [signed long] 31 | L [unsigned long] 32 | i [signed integer] 33 | I [unsigned integer] 34 | q [signed long long (quad)] 35 | Q [unsigned long long (quad)] 36 | s [string (array of chars), must be preceded with length in format specifier, padded with zeros] 37 | p [pascal string (includes byte count), must be preceded with length in format specifier, padded with zeros] 38 | f [float] 39 | d [double] 40 | = [native byte ordering, size and alignment] 41 | @ [native byte ordering, standard size and alignment] 42 | ! [network byte ordering] 43 | < [little endian] 44 | > [big endian] 45 | 46 | usual printf like specifiers can be used (if started with %) 47 | [not recommended, there is no way to unpack this] 48 | 49 | %08x will output an 8 bytes hex 50 | %s will output a string 51 | %s\\x00 will output a NUL terminated string 52 | %d%d will output 2 decimal digits (against the very same specification of Structure) 53 | ... 54 | 55 | some additional format specifiers: 56 | : just copy the bytes from the field into the output string (input may be string, other structure, or anything responding to __str__()) (for unpacking, all what's left is returned) 57 | z same as :, but adds a NUL byte at the end (asciiz) (for unpacking the first NUL byte is used as terminator) [asciiz string] 58 | u same as z, but adds two NUL bytes at the end (after padding to an even size with NULs). (same for unpacking) [unicode string] 59 | w DCE-RPC/NDR string (it's a macro for [ ' 2: 135 | dataClassOrCode = field[2] 136 | try: 137 | self[field[0]] = self.unpack(field[1], data[:size], dataClassOrCode = dataClassOrCode, field = field[0]) 138 | except Exception as e: 139 | e.args += ("When unpacking field '%s | %s | %r[:%d]'" % (field[0], field[1], data, size),) 140 | raise 141 | 142 | size = self.calcPackSize(field[1], self[field[0]], field[0]) 143 | if self.alignment and size % self.alignment: 144 | size += self.alignment - (size % self.alignment) 145 | data = data[size:] 146 | 147 | return self 148 | 149 | def __setitem__(self, key, value): 150 | self.fields[key] = value 151 | self.data = None # force recompute 152 | 153 | def __getitem__(self, key): 154 | return self.fields[key] 155 | 156 | def __delitem__(self, key): 157 | del self.fields[key] 158 | 159 | def __str__(self): 160 | return self.getData() 161 | 162 | def __len__(self): 163 | # XXX: improve 164 | return len(self.getData()) 165 | 166 | def pack(self, format, data, field = None): 167 | 168 | if field: 169 | addressField = self.findAddressFieldFor(field) 170 | if (addressField is not None) and (data is None): 171 | return b'' 172 | 173 | # void specifier 174 | if format[:1] == '_': 175 | return b'' 176 | 177 | # quote specifier 178 | if format[:1] == "'" or format[:1] == '"': 179 | return format[1:].encode("latin-1") 180 | 181 | # code specifier 182 | two = format.split('=') 183 | if len(two) >= 2: 184 | try: 185 | return self.pack(two[0], data) 186 | except: 187 | fields = {'self':self} 188 | fields.update(self.fields) 189 | return self.pack(two[0], eval(two[1], {}, fields)) 190 | 191 | # address specifier 192 | two = format.split('&') 193 | if len(two) == 2: 194 | try: 195 | return self.pack(two[0], data) 196 | except: 197 | if (two[1] in self.fields) and (self[two[1]] is not None): 198 | return self.pack(two[0], id(self[two[1]]) & ((1<<(calcsize(two[0])*8))-1) ) 199 | else: 200 | return self.pack(two[0], 0) 201 | 202 | # length specifier 203 | two = format.split('-') 204 | if len(two) == 2: 205 | try: 206 | return self.pack(two[0],data) 207 | except: 208 | return self.pack(two[0], self.calcPackFieldSize(two[1])) 209 | 210 | # array specifier 211 | two = format.split('*') 212 | if len(two) == 2: 213 | answer = bytes() 214 | for each in data: 215 | answer += self.pack(two[1], each) 216 | if two[0]: 217 | if two[0].isdigit(): 218 | if int(two[0]) != len(data): 219 | raise Exception("Array field has a constant size, and it doesn't match the actual value") 220 | else: 221 | return self.pack(two[0], len(data))+answer 222 | return answer 223 | 224 | # "printf" string specifier 225 | if format[:1] == '%': 226 | # format string like specifier 227 | return (format % data).encode("latin-1") 228 | 229 | # asciiz specifier 230 | if format[:1] == 'z': 231 | if isinstance(data,bytes): 232 | return data + b'\0' 233 | return bytes(data)+b'\0' 234 | 235 | # unicode specifier 236 | if format[:1] == 'u': 237 | return bytes(data+b'\0\0' + (len(data) & 1 and b'\0' or b'')) 238 | 239 | # DCE-RPC/NDR string specifier 240 | if format[:1] == 'w': 241 | if len(data) == 0: 242 | data = b'\0\0' 243 | elif len(data) % 2: 244 | data = data.encode("latin-1") + b'\0' 245 | l = pack('= 2: 307 | return self.unpack(two[0],data) 308 | 309 | # length specifier 310 | two = format.split('-') 311 | if len(two) == 2: 312 | return self.unpack(two[0],data) 313 | 314 | # array specifier 315 | two = format.split('*') 316 | if len(two) == 2: 317 | answer = [] 318 | sofar = 0 319 | if two[0].isdigit(): 320 | number = int(two[0]) 321 | elif two[0]: 322 | sofar += self.calcUnpackSize(two[0], data) 323 | number = self.unpack(two[0], data[:sofar]) 324 | else: 325 | number = -1 326 | 327 | while number and sofar < len(data): 328 | nsofar = sofar + self.calcUnpackSize(two[1],data[sofar:]) 329 | answer.append(self.unpack(two[1], data[sofar:nsofar], dataClassOrCode)) 330 | number -= 1 331 | sofar = nsofar 332 | return answer 333 | 334 | # "printf" string specifier 335 | if format[:1] == '%': 336 | # format string like specifier 337 | return format % data 338 | 339 | # asciiz specifier 340 | if format == 'z': 341 | if data[-1:] != b'\x00': 342 | raise Exception("%s 'z' field is not NUL terminated: %r" % (field, data)) 343 | if PY3: 344 | return data[:-1].decode('latin-1') 345 | else: 346 | return data[:-1] 347 | 348 | # unicode specifier 349 | if format == 'u': 350 | if data[-2:] != b'\x00\x00': 351 | raise Exception("%s 'u' field is not NUL-NUL terminated: %r" % (field, data)) 352 | return data[:-2] # remove trailing NUL 353 | 354 | # DCE-RPC/NDR string specifier 355 | if format == 'w': 356 | l = unpack('= 2: 391 | return self.calcPackSize(two[0], data) 392 | 393 | # length specifier 394 | two = format.split('-') 395 | if len(two) == 2: 396 | return self.calcPackSize(two[0], data) 397 | 398 | # array specifier 399 | two = format.split('*') 400 | if len(two) == 2: 401 | answer = 0 402 | if two[0].isdigit(): 403 | if int(two[0]) != len(data): 404 | raise Exception("Array field has a constant size, and it doesn't match the actual value") 405 | elif two[0]: 406 | answer += self.calcPackSize(two[0], len(data)) 407 | 408 | for each in data: 409 | answer += self.calcPackSize(two[1], each) 410 | return answer 411 | 412 | # "printf" string specifier 413 | if format[:1] == '%': 414 | # format string like specifier 415 | return len(format % data) 416 | 417 | # asciiz specifier 418 | if format[:1] == 'z': 419 | return len(data)+1 420 | 421 | # asciiz specifier 422 | if format[:1] == 'u': 423 | l = len(data) 424 | return l + (l & 1 and 3 or 2) 425 | 426 | # DCE-RPC/NDR string specifier 427 | if format[:1] == 'w': 428 | l = len(data) 429 | return 12+l+l % 2 430 | 431 | # literal specifier 432 | if format[:1] == ':': 433 | return len(data) 434 | 435 | # struct like specifier 436 | return calcsize(format) 437 | 438 | def calcUnpackSize(self, format, data, field = None): 439 | 440 | # void specifier 441 | if format[:1] == '_': 442 | return 0 443 | 444 | addressField = self.findAddressFieldFor(field) 445 | if addressField is not None: 446 | if not self[addressField]: 447 | return 0 448 | 449 | try: 450 | lengthField = self.findLengthFieldFor(field) 451 | return int(self[lengthField]) 452 | except Exception: 453 | pass 454 | 455 | # XXX: Try to match to actual values, raise if no match 456 | 457 | # quote specifier 458 | if format[:1] == "'" or format[:1] == '"': 459 | return len(format)-1 460 | 461 | # address specifier 462 | two = format.split('&') 463 | if len(two) == 2: 464 | return self.calcUnpackSize(two[0], data) 465 | 466 | # code specifier 467 | two = format.split('=') 468 | if len(two) >= 2: 469 | return self.calcUnpackSize(two[0], data) 470 | 471 | # length specifier 472 | two = format.split('-') 473 | if len(two) == 2: 474 | return self.calcUnpackSize(two[0], data) 475 | 476 | # array specifier 477 | two = format.split('*') 478 | if len(two) == 2: 479 | answer = 0 480 | if two[0]: 481 | if two[0].isdigit(): 482 | number = int(two[0]) 483 | else: 484 | answer += self.calcUnpackSize(two[0], data) 485 | number = self.unpack(two[0], data[:answer]) 486 | 487 | while number: 488 | number -= 1 489 | answer += self.calcUnpackSize(two[1], data[answer:]) 490 | else: 491 | while answer < len(data): 492 | answer += self.calcUnpackSize(two[1], data[answer:]) 493 | return answer 494 | 495 | # "printf" string specifier 496 | if format[:1] == '%': 497 | raise Exception("Can't guess the size of a printf like specifier for unpacking") 498 | 499 | # asciiz specifier 500 | if format[:1] == 'z': 501 | return data.index(b'\x00')+1 502 | 503 | # asciiz specifier 504 | if format[:1] == 'u': 505 | l = data.index(b'\x00\x00') 506 | return l + (l & 1 and 3 or 2) 507 | 508 | # DCE-RPC/NDR string specifier 509 | if format[:1] == 'w': 510 | l = unpack('?@[\\]^_`{|}~ ': 572 | return chr(x) 573 | else: 574 | return u'.' 575 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | bits_parser 2 | --------------------------------------------------------------------------------