Digital Forensics · Topic 11 of 11

Python for Digital Forensics

Use Python for forensic hashing, acquisition, Windows and Linux artifacts, malware, web, cloud, email, mobile, IoT and multimedia analysis, for CHFI v11.

  • 6 min
In a nutshell
  • Use hashlib for integrity, pefile for PE files, yara-python for rule matching.
  • python-registry reads hives, python-evtx reads event logs.
  • pytsk3 and pyewf read file systems and E01 images.

What it is

Python is the common scripting language in forensics because it parses binary formats, talks to APIs and automates repetitive checks. Scripts do not replace validated tools. They fill gaps, process large volumes and make results repeatable.

The exam expects you to know which library fits which job and how a script should respect evidence integrity.

Evidence copyread onlyPython scriptlibrary per formatParsed outputCSV or JSONVerifysecond tool and hashReport

How it works

Python digital forensics basics

Good practice for forensic scripts:

  • Open evidence read only ("rb"), and work on a copy.
  • Read large files in chunks so memory is not exhausted.
  • Log what was run, the script version and the input hash.
  • Convert times to UTC and state the time zone.
  • Test scripts against known data before relying on them.
LibraryPurpose
hashlibMD5, SHA-1, SHA-256 hashing
os, pathlib, shutilFile system access and metadata
structDecode binary structures
rePattern search in logs and text
datetimeTime conversion
sqlite3, plistlibSQLite databases and property lists
csv, jsonReports

A standard hash function reads in blocks:

import hashlib

def sha256_file(path, chunk=1024 * 1024):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(chunk), b""):
            h.update(block)
    return h.hexdigest()

Data acquisition using Python

Libraries such as pytsk3 (bindings to The Sleuth Kit) and pyewf (bindings to libewf for E01 images) let a script read disk images and walk file systems without altering them. A script that copies a device must hash the source and the copy and compare them.

Remember the limits. A script on a live system does not provide write blocking, and imaging a physical device needs administrator rights. For formal acquisition, use a validated imager or a hardware write blocker, and use Python to verify or process the result.

Windows and Linux forensics using Python

TaskLibrary or method
Registry hives (NTUSER.DAT, SYSTEM)python-registry
Event logs (.evtx)python-evtx
LNK filesLnkParse3
Linux logsre on /var/log/auth.log and /var/log/syslog
File times and ownershipos.stat, pwd

For example, a script can count Failed password lines per source address in auth.log using re and collections.Counter. The same approach counts event ID 4625 records in an exported Security log.

Malware forensics using Python

TaskLibrary
Hashing sampleshashlib
Reading PE headers, imports and sectionspefile
Matching YARA rulesyara-python
Extracting stringsre on the raw bytes
Document analysisoletools (olevba), pdfid
import pefile

pe = pefile.PE("sample.exe")
for entry in pe.DIRECTORY_ENTRY_IMPORT:
    print(entry.dll.decode())

This lists imported DLLs, which hints at behavior such as networking or process injection. Run it only inside an analysis lab, and note that analysis of a file does not execute it.

Web application and cloud forensics using Python

Scripts parse web access logs with re to find injection strings, spikes by address and response codes. For cloud work, official SDKs query provider APIs: boto3 for AWS, the Azure SDK for Python and the Google Cloud client libraries.

import boto3

ct = boto3.client("cloudtrail")
resp = ct.lookup_events(
    LookupAttributes=[{"AttributeKey": "EventName", "AttributeValue": "ConsoleLogin"}],
    MaxResults=10,
)
for e in resp["Events"]:
    print(e["EventTime"], e.get("Username"))

Use read only credentials, paginate results and save the raw API responses with a hash as evidence.

Email forensics using Python

The email package parses messages and the mailbox module reads MBOX files. A script can list headers, pull out Received lines, extract attachments and hash them.

from email import policy
from email.parser import BytesParser

with open("message.eml", "rb") as f:
    msg = BytesParser(policy=policy.default).parse(f)
print(msg["From"], msg["Subject"])
for line in msg.get_all("Received", []):
    print(line)

PST files need a dedicated library or a conversion tool first.

Mobile device and IoT forensics using Python

Mobile data sits in SQLite databases and plist files, which sqlite3 and plistlib read directly. Open a copy read only:

import sqlite3

con = sqlite3.connect("file:sms_copy.db?mode=ro", uri=True)
for row in con.execute("SELECT name FROM sqlite_master WHERE type='table'"):
    print(row[0])

Convert timestamps to UTC, remembering the epoch differs: Unix 1970 (Android), 2001 (iOS and macOS Cocoa) and 1601 (Chromium browsers and Windows FILETIME). For Android, a script can call the Android Debug Bridge through subprocess. IoT work often parses exported JSON from companion apps or cloud APIs.

Multimedia forensics using Python

Images, audio and video hold metadata and can be altered. Scripts can read EXIF with Pillow (Image.open(path).getexif()), compare files by hash, compute perceptual hashes to find near duplicates, check that a file's header matches its extension, and run ffprobe through subprocess for container details. Differences in compression levels or metadata can indicate editing, but are leads, not proof.

A worked example

An examiner has 50,000 JPEG files and needs the ones taken with a particular camera between two dates. A script walks the folder, hashes each file, reads EXIF make, model and date, and writes a CSV.

Files with no EXIF are listed separately and not discarded. The examiner then checks a sample by hand in a forensic suite to validate the script.

How the exam asks about this

  • "Which Python library parses Windows PE headers?" -> pefile.
  • "Which module computes hashes for evidence integrity?" -> hashlib.
  • "A script opens a SQLite evidence file directly for editing. What is the problem?" -> It can modify the evidence, so work on a hashed copy opened read only.

What to remember for the exam

  • Use hashlib for integrity, pefile for PE files, yara-python for rule matching.
  • python-registry reads hives, python-evtx reads event logs.
  • pytsk3 and pyewf read file systems and E01 images.
  • boto3 queries AWS APIs such as CloudTrail.
  • Scripts must read evidence read only, hash inputs and outputs, and be validated.
Watch out

Python alone gives no write protection. Opening evidence in write mode, or running scripts on the original, can change it and break the chain of custody.

Common mistakes

Loading a whole image into memory. Read in chunks.

Trusting an unvalidated script. Test it against known data and compare with a validated tool.

Forgetting time zones. Convert all times to UTC and state the epoch used.

Check yourself

  • Which library reads Windows event log files in Python?

    python-evtx.

  • Why should a forensic script open files in "rb" mode?

    It reads without changing the content and handles binary data correctly.

  • What must you do before relying on a custom script's output?

    Validate it against known data or a trusted tool, and document the result.

Topic 11 of 11 in Digital Forensics

Test yourself on Digital Forensics

The full EC-Council 312-49 question bank has 900 questions, with timed practice exams and an explanation for every answer.

This study guide is independent and is not affiliated with, endorsed by, or sponsored by EC-Council. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.