Forem Creators and Builders 🌱

Cover image for Digital Forensics Basics in Python
Mariah Dominique Rucker
Mariah Dominique Rucker

Posted on • Updated on

Digital Forensics Basics in Python

Digital forensics involve digital evidence whereby they are preserved and analyzed before they can be used to solve any crime. Digital Forensics, like casting advanced spells or performing incantations, is usually done utilizing Python because it provides flexibility and ample resources.

This tutorial will focus on several high-level spells and enchantments which may aid digital forensic tasks in Python.

Digital Forensics Process Illustration
Digital Forensics Process

Acquiring data:

Collecting data is similar to using of Obliviate on the Memory Charm and Python libraries are analogous to wands that will assist in casting the appropriate spells of gathering information from various sources.

Hermione & Obliviate Spell

As with Memory Charm, the Python libraries can also be exploited to delete or wipe out data from numerous sources and locations. Python has access to data from a disk image, forensic image, network traffic, and other sources using pytsk3, pyewf, volatility, and scapy respectively.

Read a disk image using pytsk3:

import pytsk3

# Open the disk image
image = pytsk3.Img_Info('disk_image.dd')

# Open the file system
fs_info = pytsk3.FS_Info(image)
file_system = fs_info.open_fs()

# Get the root directory
root_directory = file_system.open_dir('/')
Enter fullscreen mode Exit fullscreen mode

Analyzing data:

Data analysis is like a Harry Potter’s spell. The library is the spell, data analysis task is the magic effect and python is the wand in the Harry Potter movie setting.

Just like Accio, it brings all the required data analysis libraries at the fingertip of the Python programmer. Accio is a platform that makes it possible for the programmer to retrieve relevant libraries for their data analysis requirements without wasting more time on their search.

Harry Potter & Accio Charm

Among other libraries for data analysis are pandas, numpy, scipy, networkx and others. The collection can be utilized in activities such as, classifications, clustering, statistical computation, and also network analysis.

Analyze network traffic using scapy:

import scapy.all as scapy

# Read a packet capture file
packets = scapy.rdpcap('network_traffic.pcap')

# Extract IP addresses from the packets
ip_addresses = []
for packet in packets:
    if packet.haslayer('IP'):
        source_ip = packet['IP'].src
        destination_ip = packet['IP'].dst
        ip_addresses.append((source_ip, destination_ip))

# Create a network graph
import networkx as nx
G = nx.Graph(ip_addresses)

# Compute network metrics
print(nx.betweenness_centrality(G))
Enter fullscreen mode Exit fullscreen mode

Data visualization:

Data visualization has a similar spell to Accio. Similarly, just like Accio is used to give objects to the caster, data visualization brings patterns and anomalies out of the data.

Harry Potter & Accio Charm for Horcrux

A wizard uses “Accio” power to recover items quickly, whereas an analytics investigator leverages data visualization ability to detect unseen links in the data.

The following are some of the Python libraries (matplotlib, seaborn, bokeh, plotly, etc.) that can be used for the creation of data visualizations.

Create a timeline plot using plotly:

import plotly.express as px

# Load data into a pandas dataframe
df = pd.read_csv('timeline.csv')

# Create a timeline plot
fig = px.timeline(df, x_start='start_time', x_end='end_time', y='event', color='category')
fig.show()
Enter fullscreen mode Exit fullscreen mode

Presentation:

Like how Python libraries are used to make reports and presentations, so does the spell “Finite Incantatem”.

Luna & Finite Incantatem Spell on Harry Potter

The spell “Finite Incantatem” brings any situation back to its initial stage just as these python libraries produce reports and presentations of results to finalize a digital forensic analysis.

Create an HTML report using jinja2:

from jinja2 import Environment, FileSystemLoader

# Load the template
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('report_template.html')

# Render the template with the data
data = {'title': 'Digital Forensics Report', 'events': [{'name': 'Event 1', 'description': 'Lorem ipsum...'}]}
output = template.render(data)

# Save the output to a file
with open('report.html', 'w') as f:
    f.write(output)
Enter fullscreen mode Exit fullscreen mode

In digital forensics, python is similar to the powerful spell of Wingardium Leviosa because this kind of magic can do sophisticated activities such as making objects fly or move around without much difficulty. Similarly, a wand can perform the work of Wingardium Leviosa like python analyzes digital data and provides useful information for police investigation.

Image description

Some other useful libraries such as pycrypto, pyPdf, and pdfmining are also provided which could aid in carrying out intricate operations.

Cryptography:

The cryptography library is similar to the spell “Accio,” which can swiftly deliver desired outcomes. The cryptography library is just another case of how magic could be applied in practical situations. It can make a quick drawing of the encrypted data from a computer and decrypt it so that the digital forensic investigators can acquire the desired information.

Hashing, encryption and decryption tools are available in the library that makes it an ideal digital investigation equipment.

Cryptography Illustration

Hash a file using SHA-256:

import hashlib

# Open the file
with open('file.txt', 'rb') as f:
    # Read the file in chunks to prevent memory errors
    chunk_size = 4096
    hasher = hashlib.sha256()
    while True:
        chunk = f.read(chunk_size)
        if not chunk:
            break
        hasher.update(chunk)

# Get the hash value
hash_value = hasher.hexdigest()
Enter fullscreen mode Exit fullscreen mode

Malware analysis:

Malware analysis could be seen as an equivalent of spell Accio. The same way Accio summons objects at a distance; a digital forensics investigator is able to “summon” malware from distant computers by using malware analysis.

Accio Charm & Harry Potter

There are various libraries and tools for malware analysis provided by python like pefile, pydbg, pykd, etc.

Analyze a malware file using pefile:

import pefile

# Load the malware file
pe = pefile.PE('malware.exe')

# Get the imports
imports = []
for entry in pe.DIRECTORY_ENTRY_IMPORT:
    imports.append(entry.dll)
    for imp in entry.imports:
        imports.append(imp.name)

# Get the strings
strings = []
for s in pe.Strings:
    strings.append(s)

# Get the sections
sections = []
for section in pe.sections:
    sections.append(section.Name.decode('utf-8'))

# Print the results
print('Imports:', imports)
print('Strings:', strings)
print('Sections:', sections)
Enter fullscreen mode Exit fullscreen mode

Similarly, just as the powerful spell of Accio, the language of Python has a powerful meaning. Similarly, just like Accio can call for a thing, Python will also get data to come up and carry out some big jobs. Likewise, from data collection towards malware analysis become simpler and more accurate compared to past scenarios.

In this tutorial, you have been introduced to the fundamentals of digital forensics with python, the process of creating a digital forensic triage script in order to rapidly collect digital evidence from a system and reading and parsing files, use of Python libraries for decoding and analyzing data.

GitHub: github.com/mariahrucker
LinkedIn: linkedin.com/in/mariahrucker
Instagram: instagram.com/techmariah
Other: linktr.ee/mariahrucker

Top comments (0)