### JavaScript Functions for Host History Navigation and Data Display
Source: https://github.com/dfxml-working-group/dfxml_python/blob/main/demos/vmstats/vmstats_json.html
Provides JavaScript functions to handle page navigation (next/previous), update the displayed statistics (start time, CPU/memory utilization), and render the process list for a specific time point. It also includes event listeners for button clicks and keyboard input to control the navigation.
```javascript
function click_next(event) { var n = parseInt($('#page_number').text()) + 1; set_page(n); }
function click_prev(event) { var n = parseInt($('#page_number').text()) - 1; set_page(n); }
function set_page(n) { if (n<0 || n>=data.length) return;
$('#page_number').text( n );
$('#start_time').text( data[n]['stats']['start_time'] );
$('#cpu_percent').text( data[n]['stats']['cpu_percent'] );
$('#mem_percent').text( data[n]['stats']['mem_percent'] );
var plist = [];
for(var i=0; i < data[n]['processes'].length; i++){
p = data[n]['processes'][i];
plist.push("
| " + p['pid'] + " | " + p['name'] + " | " + p['user'] + " | " + p['system'] + " | " + p['rss'] + " |
")
}
$("#process_list > tbody:last-child").html( plist.join("\n"));
}
$(document).ready(function() {
$('#next').on('click', click_next);
$('#prev').on('click', click_prev);
$(document).keydown(function(e) {
switch(e.which) {
case 37: // left
click_prev(e);
break;
case 38: // up
break;
case 39: // right
click_next(e);
break;
case 40: // down
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
```
--------------------------------
### DFXML Time Object Handling in Python
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Work with specialized time objects provided by the dfxml library, which handle automatic format conversion. Examples include parsing ISO8601 timestamps, converting to Unix timestamps and datetime objects, creating time objects from Unix timestamps, and comparing timestamps.
```python
import dfxml
# Parse ISO8601 timestamp
timestamp = dfxml.dftime("2024-01-15T10:30:45Z")
# Convert to different formats
print(f"ISO8601: {timestamp.iso8601()}")
print(f"Unix timestamp: {timestamp.timestamp()}")
print(f"Datetime object: {timestamp.datetime()}")
# Create from Unix timestamp
unix_time = dfxml.dftime(1705317045.0)
print(f"From Unix time: {unix_time.iso8601()}")
# Compare timestamps
time1 = dfxml.dftime("2024-01-15T10:30:45Z")
time2 = dfxml.dftime("2024-01-16T10:30:45Z")
if time1 < time2:
print("time1 is earlier than time2")
```
--------------------------------
### Filtering Files by Forensic Criteria in Python
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Extract specific files from DFXML based on forensic criteria such as allocation status, file type, or hash values. This example demonstrates how to identify deleted files and executable files, storing their details in separate lists.
```python
import dfxml
deleted_files = []
suspicious_files = []
def filter_files(fileobject):
"""Filter files by forensic criteria"""
# Find deleted files
if not fileobject.allocated():
deleted_files.append({
'filename': fileobject.filename(),
'size': fileobject.filesize(),
'md5': fileobject.md5()
})
# Find executable files
if fileobject.ext() in ['exe', 'dll', 'sys']:
suspicious_files.append({
'filename': fileobject.filename(),
'size': fileobject.filesize(),
'sha256': fileobject.sha256()
})
# Process DFXML
with open('forensic_image.xml', 'rb') as xmlfile:
dfxml.read_dfxml(xmlfile=xmlfile, callback=filter_files)
```
--------------------------------
### Read DFXML with Callbacks (Python)
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Processes DFXML files using an event-driven approach with callbacks. It takes an XML file and a callback function as input, processing each file object encountered and passing it to the callback for further action. Dependencies include the 'dfxml' library.
```python
import dfxml
def process_file(fileobject):
"""Callback function to process each file object"""
print(f"File: {fileobject.filename()}")
print(f" Size: {fileobject.filesize()} bytes")
print(f" MD5: {fileobject.md5()}")
print(f" Modified: {fileobject.mtime()}")
print(f" Allocated: {fileobject.allocated()}")
# Process DFXML file with callback
with open('forensic_image.xml', 'rb') as xmlfile:
dfxml.read_dfxml(xmlfile=xmlfile, callback=process_file)
```
--------------------------------
### Generating DFXML with Fiwalk in Python
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Generate DFXML output from a disk image by executing Fiwalk as a subprocess. This function takes the image path and an output XML file name, then saves the generated DFXML. It utilizes the dfxml.fiwalk module.
```python
from dfxml import fiwalk
import io
def analyze_disk_image(image_path, output_xml):
"""Generate DFXML from disk image using Fiwalk"""
# Generate DFXML from disk image
with open(image_path, 'rb') as image_file:
dfxml_buffer = fiwalk.fiwalk_xml_stream(imagefile=image_file)
dfxml_output = dfxml_buffer.read()
# Save to file
with open(output_xml, 'wb') as outfile:
outfile.write(dfxml_output)
print(f"Generated DFXML: {output_xml}")
# Example usage
analyze_disk_image('evidence.dd', 'evidence.xml')
```
--------------------------------
### Programmatic DFXML Document Creation in Python
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Create DFXML documents from scratch using the dfxml.objects API. This allows for building structured forensic data programmatically, including adding source information, volume details, and file objects with their attributes like filename, size, and MD5 hash.
```python
import dfxml.objects as Objects
# Create a new DFXML document
doc = Objects.DFXMLObject(
program="MyForensicTool",
program_version="1.0.0"
)
# Add source information
doc.sources.append("/path/to/image.dd")
# Create a volume object
volume = Objects.VolumeObject()
volume.ftype_str = "ntfs"
volume.block_size = 4096
volume.block_count = 1048576
doc.append(volume)
# Create file objects
for i in range(3):
fileobj = Objects.FileObject()
fileobj.filename = f"/Documents/file{i}.txt"
fileobj.filesize = 1024 * (i + 1)
fileobj.alloc = True
fileobj.md5 = f"abc123def456{'0' * 24}"
volume.append(fileobj)
# Write to file
with open('output.xml', 'w') as outfile:
doc.print_dfxml(outfile)
```
--------------------------------
### Compare File Systems using Differential DFXML
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
This script compares two DFXML file system snapshots (before and after) to identify new, modified, and deleted files. It parses both XML files, builds a lookup dictionary for the original files, and then iterates through the current files to detect changes. Modifications are identified by comparing file hashes (MD5). The output includes counts and lists of the first 10 files in each category.
```python
import dfxml.objects as Objects
# Parse original and new file system snapshots
original = Objects.parse('snapshot_before.xml')
current = Objects.parse('snapshot_after.xml')
# Build lookup dictionary for original files
original_files = {}
for fileobj in original.files:
if fileobj.filename:
original_files[fileobj.filename] = fileobj
# Compare and identify changes
new_files = []
modified_files = []
deleted_files = set(original_files.keys())
for fileobj in current.files:
filename = fileobj.filename
if filename in original_files:
deleted_files.remove(filename)
orig = original_files[filename]
# Compare hashes to detect modifications
if fileobj.md5 and orig.md5() and fileobj.md5 != orig.md5():
modified_files.append({
'filename': filename,
'old_size': orig.filesize(),
'new_size': fileobj.filesize,
'old_mtime': orig.mtime(),
'new_mtime': fileobj.mtime
})
else:
new_files.append(filename)
# Report results
print(f"New files: {len(new_files)}")
for f in new_files[:10]:
print(f" + {f}")
print(f"\nModified files: {len(modified_files)}")
for f in modified_files[:10]:
print(f" M {f['filename']}")
print(f"\nDeleted files: {len(deleted_files)}")
for f in list(deleted_files)[:10]:
print(f" - {f}")
```
--------------------------------
### Analyzing File Fragmentation with Byte Runs in Python
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Analyze file fragmentation by examining byte runs, which represent the physical layout of file data on disk. This function prints details about each fragment, including disk offset and length. It uses the dfxml.read_dfxml function with a callback.
```python
import dfxml
def analyze_fragmentation(fileobject):
"""Analyze file fragmentation using byte runs"""
filename = fileobject.filename()
byte_runs = fileobject.byte_runs()
if len(byte_runs) > 1:
print(f"{filename} is fragmented:")
print(f" Number of fragments: {len(byte_runs)}")
total_size = 0
for i, run in enumerate(byte_runs):
print(f" Fragment {i+1}:")
print(f" Disk offset: {run.img_offset}")
print(f" Length: {run.len} bytes")
total_size += run.len
print(f" Total size: {total_size} bytes")
# Process DFXML file
with open('forensic_image.xml', 'rb') as xmlfile:
dfxml.read_dfxml(xmlfile=xmlfile, callback=analyze_fragmentation)
```
--------------------------------
### Type-Safe Parsing with Objects API (Python)
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Utilizes the Objects module for a modern, type-safe way to parse DFXML documents into memory. It provides direct property access to DFXML elements like version, program details, volumes, files, timestamps, and hashes. Requires the 'dfxml.objects' module.
```python
import dfxml.objects as Objects
# Parse entire DFXML document into memory
dfxml_doc = Objects.parse('forensic_image.xml')
print(f"DFXML Version: {dfxml_doc.version}")
print(f"Creator: {dfxml_doc.program} {dfxml_doc.program_version}")
# Iterate through volumes
for volume in dfxml_doc.volumes:
print(f"\nVolume: {volume.ftype_str}")
print(f" Block size: {volume.block_size}")
print(f" Block count: {volume.block_count}")
# Iterate through files in volume
for fileobj in volume.files:
if fileobj.filename and fileobj.filesize:
print(f" File: {fileobj.filename} ({fileobj.filesize} bytes)")
# Access timestamps as properties
if fileobj.mtime:
print(f" Modified: {fileobj.mtime}")
# Access hash values
if fileobj.sha256:
print(f" SHA-256: {fileobj.sha256}")
```
--------------------------------
### Extract File Content from Disk Images using DFXML Byte Runs
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
This function extracts the content of a file from a disk image by utilizing the byte run information stored within a DFXML file object. It requires the DFXML file object, the path to the disk image, and the desired output path for the extracted file. It handles cases where no byte runs are available.
```python
import dfxml
import dfxml.objects as Objects
def extract_file_content(fileobject, image_path, output_path):
"""Extract file content using byte runs"""
if not fileobject.byte_runs():
print("No byte runs available")
return
with open(image_path, 'rb') as disk_image:
with open(output_path, 'wb') as output_file:
for byte_run in fileobject.byte_runs():
if byte_run.img_offset and byte_run.len:
# Seek to location on disk
disk_image.seek(byte_run.img_offset)
# Read and write data
data = disk_image.read(byte_run.len)
output_file.write(data)
print(f"Extracted {fileobject.filename()} to {output_path}")
# Example: Extract a specific file
with open('forensic_image.xml', 'rb') as xmlfile:
for fileobject in dfxml.iter_dfxml(xmlfile):
if fileobject.filename() == '/important/document.pdf':
extract_file_content(fileobject, 'image.dd', 'extracted_document.pdf')
break
```
--------------------------------
### Create MAC Timeline (Python)
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Extracts and sorts Modified, Accessed, Changed, and Created timestamps from DFXML data to generate a forensic timeline. It uses a callback function to collect timestamps from file objects and then sorts them chronologically. Requires the 'dfxml' library.
```python
import dfxml
timeline = []
def collect_times(fileobject):
"""Collect all timestamps from file objects"""
filename = fileobject.filename()
if fileobject.mtime():
timeline.append([fileobject.mtime(), filename, "modified"])
if fileobject.atime():
timeline.append([fileobject.atime(), filename, "accessed"])
if fileobject.ctime():
timeline.append([fileobject.ctime(), filename, "changed"])
if fileobject.crtime():
timeline.append([fileobject.crtime(), filename, "created"])
# Process DFXML file
with open('forensic_image.xml', 'rb') as xmlfile:
dfxml.read_dfxml(xmlfile=xmlfile, callback=collect_times)
# Sort and display timeline
timeline.sort()
for timestamp, filename, action in timeline:
print(f"{timestamp}\t{filename}\t{action}")
```
--------------------------------
### Validate DFXML Documents with Python
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
This function validates a DFXML file to ensure it conforms to the schema and contains valid data. It parses the DFXML document and performs basic checks, such as verifying the DFXML version and creator program. It also iterates through file objects to count files, check for the presence of hashes (MD5, SHA1, SHA256), and report any missing filenames. The function returns True if no errors are found, and False otherwise.
```python
import dfxml.objects as Objects
def validate_dfxml(filename):
"""Validate DFXML file structure and content"""
try:
doc = Objects.parse(filename)
# Basic validation
print(f"DFXML version: {doc.version}")
print(f"Creator: {doc.program}")
file_count = 0
hash_count = 0
error_count = 0
# Validate file objects
for volume in doc.volumes:
for fileobj in volume.files:
file_count += 1
# Check for required fields
if not fileobj.filename:
print(f"Warning: File object missing filename")
error_count += 1
# Check hash presence
if fileobj.md5 or fileobj.sha1 or fileobj.sha256:
hash_count += 1
print(f"\nValidation results:")
print(f" Total files: {file_count}")
print(f" Files with hashes: {hash_count}")
print(f" Errors: {error_count}")
return error_count == 0
except Exception as e:
print(f"Validation failed: {e}")
return False
# Validate DFXML file
is_valid = validate_dfxml('forensic_image.xml')
print(f"DFXML valid: {is_valid}")
```
--------------------------------
### Iterate Over File Objects (Python)
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Provides memory-efficient iteration over file objects within large DFXML files. It returns an iterator, allowing for sequential processing without loading the entire file into memory. Useful for filtering and extracting specific file details like timestamps and extensions. Requires the 'dfxml' library.
```python
import dfxml
# Iterate through file objects in a DFXML file
for fileobject in dfxml.iter_dfxml(xmlfile=open('forensic_image.xml', 'rb')):
if fileobject.is_file() and fileobject.allocated():
print(f"{fileobject.filename()}: {fileobject.filesize()} bytes")
# Access file times
if fileobject.mtime():
print(f" Modified: {fileobject.mtime().iso8601()}")
if fileobject.atime():
print(f" Accessed: {fileobject.atime().iso8601()}")
# Check for specific file extensions
if fileobject.ext() == 'pdf':
print(f" Found PDF: {fileobject.filename()}")
```
--------------------------------
### Iterative Parsing with Objects API (Python)
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Enables memory-efficient parsing of DFXML files by yielding objects as they are encountered in the XML stream, rather than loading the entire document. This approach is suitable for very large files where memory is a concern. Requires the 'dfxml.objects' module.
```python
import dfxml.objects as Objects
# This code snippet is incomplete in the provided text and only demonstrates the import.
```
--------------------------------
### Iterative DFXML Processing with Python
Source: https://context7.com/dfxml-working-group/dfxml_python/llms.txt
Process a DFXML file iteratively to extract information about volumes and files. It handles large files and checks for compression or encryption. This method uses the Objects.iterparse function for efficient parsing.
```python
from dfxml import objects as Objects
# Process DFXML file iteratively
for event, obj in Objects.iterparse('forensic_image.xml', events=('start', 'end')):
if event == 'start' and isinstance(obj, Objects.VolumeObject):
print(f"Starting volume: {obj.ftype_str}")
elif event == 'end' and isinstance(obj, Objects.FileObject):
# Process file objects as they complete
if obj.allocated_inode and obj.filesize and obj.filesize > 1048576:
print(f"Large file: {obj.filename} ({obj.filesize} bytes)")
# Check for suspicious characteristics
if obj.compressed:
print(f" Compressed: True")
if obj.encrypted:
print(f" Encrypted: True")
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.