Skip to content

Completed a Malware Analysis and Reverse Engineering project where I analyzed a malware sample in an isolated environment, monitored its behavior, extracted file metadata, and created custom YARA rules and IoCs. Automated reporting with Python streamlined the analysis and improved efficiency.

Notifications You must be signed in to change notification settings

jarif87/malware-analysis-and-reverse-engineering

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Malware Analysis and Reverse Engineering

Step 0 — Safety rules (read this first)

  • Never run malware on your host OS. Always use a VM.
  • Use Host‑Only networking (or internal network) so the VM has no direct Internet access.
  • Disable shared folders, drag&drop and clipboard in VirtualBox.
  • Always work from a non-root user inside the VM.
  • Keep all malware samples encrypted and never upload raw samples to the public internet.

Step 1 — Full commands & details you ran (and the revert command)

Below I’ve collected every command you ran on the Windows host during Step 1 plus short explanations and the commands to verify and revert the snapshot. Run these on the host (Windows) command prompt — not inside the Kali VM.

List all VMs (you ran this to get the exact VM names)

  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" list vms
  • What it does: prints all registered VMs and their names/UUIDs (you used this and saw names like "Kali Linux 2025" and "Kali Linux 2025 vbox").

Take snapshots (you created clean-base for two VMs)

  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025" take "clean-base" --description "Clean Kali base - no samples"
  • For Kali Linux 2025 vbox:
  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025 vbox" take "clean-base" --description "Clean Kali base - no samples"

  • What it does: creates a snapshot named clean-base capturing the VM’s current state. You ran both and VirtualBox returned Snapshot taken. UUID: ....

Verify the snapshot was created (you ran snapshot ... list)

  • For each VM:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025" list
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025 vbox" list
  • What it does / output: shows snapshot(s) for that VM. You saw:
Name: clean-base (UUID: ...) *
Description: Clean Kali base - no samples

How to revert (restore) to clean-base — the revert command

  • Important: Power off the VM before restoring.
  • To restore Kali Linux 2025 to clean-base:
  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025" restore "clean-base"
  • To restore Kali Linux 2025 vbox to clean-base:
  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025 vbox" restore "clean-base"
  • After restoring, you can start the VM from the GUI or with:
  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" startvm "Kali Linux 2025" --type headless
# or for normal GUI:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" startvm "Kali Linux 2025"

Helpful sanity commands

  • Power off a running VM (graceful via GUI is preferred):
    • Use VirtualBox Manager → Right-click VM → Close → Power off.
  • Force power off from host (if needed):
  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" controlvm "Kali Linux 2025" poweroff
  • (use only if VM is stuck; prefer guest shutdown)
  • Show VM info (to confirm paths / state)
  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" showvminfo "Kali Linux 2025"

Step 2 Static analysis Flow A

  • create analyst user
  • command run:
sudo adduser analyst
sudo usermod -aG sudo analyst
  • Prepare a single standard analysis folder under the analyst home and set permissions
  • command run:
sudo mkdir -p /home/analyst/analysis/samples
sudo chown -R analyst:analyst /home/analyst/analysis
sudo chmod -R 700 /home/analyst/analysis
ls -la /home/analyst/analysis
  • Switch into the analyst account
  • command run:
su - analyst
  • Create the safe EICAR test file (in the standard samples folder)
  • command run:
cd ~/analysis/samples
echo 'X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' > eicar.com
  • Inspect & hash the EICAR file
  • command run:
file eicar.com
sha256sum eicar.com
strings -a -n 6 eicar.com | sed -n '1,20p'
  • Install the single helper script quick_analyze.py (standard tool) and run it
  • create the script:
cat > ~/quick_analyze.py <<'PY'
#!/usr/bin/env python3
import sys,hashlib,json
try:
    import pefile
except:
    pefile=None

def sha256(f):
    h=hashlib.sha256()
    with open(f,'rb') as fh:
        for chunk in iter(lambda: fh.read(8192), b''):
            h.update(chunk)
    return h.hexdigest()

def strings_from_file(fn, minlen=6):
    res=[]
    with open(fn,'rb') as fh:
        data=fh.read()
    s=''
    for b in data:
        c=chr(b) if 32 <= b < 127 else ''
        if c:
            s+=c
        else:
            if len(s)>=minlen:
                res.append(s)
            s=''
    if len(s)>=minlen:
        res.append(s)
    return res

def entropy(data):
    from collections import Counter
    import math
    cnt=Counter(data)
    ln=len(data)
    ent=0.0
    for v in cnt.values():
        p=v/ln
        ent -= p*math.log2(p)
    return ent

if __name__=='__main__':
    if len(sys.argv)!=2:
        print("Usage: quick_analyze.py samplefile"); sys.exit(1)
    f=sys.argv[1]
    out={"file":f,"sha256":sha256(f)}
    with open(f,'rb') as fh:
        data=fh.read()
    out["size"]=len(data)
    out["entropy"]=entropy(data)
    out["strings"]=strings_from_file(f)[:50]
    if pefile:
        try:
            pe=pefile.PE(f)
            imports={}
            for entry in getattr(pe,'DIRECTORY_ENTRY_IMPORT',[]):
                imports[entry.dll.decode(errors='ignore')] = [imp.name.decode(errors='ignore') if imp.name else "" for imp in entry.imports]
            out["imports"]=imports
        except Exception as e:
            out["pe_error"]=str(e)
    print(json.dumps(out, indent=2))
PY
chmod +x ~/quick_analyze.py

  • command run:
python3 /home/kali/quick_analyze.py /home/kali/Desktop/analysis/samples/eicar.com

The script printed a JSON object showing:

  • sha256: 131f95c5... — the file hash (good to record as IOC/test value).
  • size: 69 bytes — EICAR is a tiny text file.
  • entropy: 4.91 — low/mid entropy (not packed).
  • strings: contains the EICAR test string.
  • pe_error: DOS Header magic not found. — expected (EICAR is not a PE executable), so the PE parser correctly failed.

run these as root one after another:

  • command run:
# 1) Ensure the script exists in /home/kali and is executable
mv /root/quick_analyze.py /home/kali/quick_analyze.py 2>/dev/null || true
chown kali:kali /home/kali/quick_analyze.py 2>/dev/null || true
chmod +x /home/kali/quick_analyze.py

# 2) Run analyzer and write report to existing analysis folder (correct path)
python3 /home/kali/quick_analyze.py /home/kali/Desktop/analysis/samples/eicar.com > /home/kali/Desktop/analysis/eicar_report.json

# 3) Verify the file was created and show its contents
ls -l /home/kali/Desktop/analysis/eicar_report.json
cat /home/kali/Desktop/analysis/eicar_report.json

Flow A — Final Note

Flow A demonstrates safe static malware analysis without risking the host system. A dedicated user analyst was created with a secure folder structure at ~/analysis/samples and permissions were restricted to protect files. The harmless EICAR test file was analyzed, revealing a size of 69 bytes, entropy of approximately 4.91 (low/mid randomness) and a unique SHA256 hash. The PE parser failed as expected since the file is not a PE executable, while strings were successfully extracted. The quick_analyze.py script generated a JSON report containing file hash, size, entropy, strings and PE information if applicable. This workflow verifies file information, hash and strings safely, reinforcing the importance of isolated folders, controlled permissions and testing tools on safe files before handling real malware.

Flow B — Safely move a real sample from Windows host → Kali (encrypted 7z inside an ISO)

  1. Create working folder and placeholder file:
  2. command run:
mkdir C:\temp
mkdir C:\temp\sample-to-move
echo This is a harmless placeholder. > C:\temp\sample-to-move\malware_sample.bin
dir C:\temp\sample-to-move
type C:\temp\sample-to-move\malware_sample.bin
  1. Create an encrypted 7z archive:
"C:\Program Files\7-Zip\7z.exe" a -p1433 -mhe=on C:\temp\sample.7z C:\temp\sample-to-move\malware_sample.bin

  1. Next Steps:
  • In ImgBurn, choose Create image file from files/folders.
  • Add C:\temp\sample.7z (the file you already made).
  • Set the output Destination to C:\temp\sample.iso.
  • Click Build.

Attach the ISO in VirtualBox

  • Open Oracle VM VirtualBox Manager on Windows.
  • Select the Kali Linux 2025 VM from the left-hand list.
  • Click Settings (gear icon) → Storage.
  • Under the Storage Tree, locate the optical drive (may show as “Empty” with a disc icon) and click it.
  • On the right, next to Optical Drive, click the small disc icon and select Choose a disk file…
  • Navigate to C:\temp\sample.iso, select it and click Open.
  • Verify that sample.iso appears under the optical drive in the Storage Tree.
  • Click OK to save settings.
  • Start the VM by clicking Start.
  1. Inside kali VM
  • command run:
# switch to analyst
su - analyst

# create mount point and mount (try /dev/cdrom then /dev/sr0)
sudo mkdir -p /mnt/sampleiso
sudo mount /dev/cdrom /mnt/sampleiso 2>/dev/null || sudo mount /dev/sr0 /mnt/sampleiso
ls -la /mnt/sampleiso
  1. Copy the encrypted .7z into your analysis folder and record SHA256
  • command run:
mkdir -p ~/analysis/samples
cp /mnt/sampleiso/sample.7z ~/analysis/samples/
chmod 600 ~/analysis/samples/sample.7z
sha256sum ~/analysis/samples/sample.7z | tee ~/analysis/samples/sample_archive_sha256.txt
  1. Extract the archive
  • command run:
sudo apt update
sudo apt install -y p7zip-full
cd ~/analysis/samples
7z x sample.7z
# enter the passphrase you used on Windows when prompted
ls -la
  1. Static analysis on the extracted file:
  • command run:
python3 quick_analyze.py malware_sample.bin > quick_report.json
cat quick_report.json
  • File analyzed: malware_sample.bin
  • SHA256: 4adf88267cac8b2e92310922ea54a85aa3f1b026e591bca4cfb2c81956a2a490
  • File size: 34 bytes (tiny placeholder file)
  • Entropy: 3.83 — low, expected for a simple text placeholder
  • Strings: "This is a harmless placeholder."
  • PE analysis: Failed (pe_error) — normal because this is not a real Windows executable

  1. Flow B — Safely Move a Real Sample from Windows Host to Kali VM Safely transfer a malware sample from a Windows host to an isolated Kali VM using an encrypted 7z archive inside an ISO, without risking accidental execution on the host system.

  2. Create Placeholder Sample on Windows Host

    • Folder created: C:\temp\sample-to-move
    • Placeholder file: malware_sample.bin with harmless content.
  3. Create Encrypted 7z Archive

  • command run:
"C:\Program Files\7-Zip\7z.exe" a -p1433 -mhe=on C:\temp\sample.7z C:\temp\sample-to-move\malware_sample.bin
  • Password: 1433
  • Filename encryption enabled (-mhe=on)
  • Verified archive exists: C:\temp\sample.7z
  1. Create ISO Containing the 7z Archive
  • Tool: ImgBurn
  • Output: C:\temp\sample.iso
  1. Attach ISO to Kali VM
  • VirtualBox → Kali Linux VM → Settings → Storage → Optical Drive → Attach sample.iso
  • VM network: Host-Only
  • Shared folders/clipboard/drag-drop: Disabled
  1. Mount ISO and Copy Archive in Kali VM
  • Mounted at /mnt/sampleiso
  • Copied to analyst workspace: ~/analysis/samples/sample.7z
  • Permissions set: chmod 600
  • SHA256 recorded in sample_archive_sha256.txt
  1. Extract Encrypted 7z Archive
  • Installed p7zip-full
  • Command: 7z x sample.7z
  • Password entered: 1433
  • Result: malware_sample.bin extracted
  1. Static Analysis on Extracted Sample
  • strings -a -n 6 malware_sample.bin | tee strings.txt
  • python3 quick_analyze.py malware_sample.bin > quick_report.json
  • Output:
    • SHA256: 4adf88267cac8b2e92310922ea54a85aa3f1b026e591bca4cfb2c81956a2a490
    • File size: 34 bytes
    • Entropy: 3.83 (low, as expected)
    • Strings: "This is a harmless placeholder."
    • PE analysis: Failed (normal for placeholder file)
  1. Safety Measures Followed
  • VM snapshot verified (clean-base)
  • Network isolation enforced
  • No extraction or execution on Windows host
  • ISO unmounted and detached after extraction

Conclusion:

Flow B successfully transferred and analyzed a malware sample safely in an isolated Kali VM environment. All artifacts, including the encrypted archive, extracted file, SHA256 hashes and analysis outputs, are stored securely in ~/analysis/samples/. This ensures that the sample never touched the host system and can now be used for further static or dynamic analysis within the VM.

Step 3

  • Preparation & snapshot (Host)
  • command run:
# create analysis folder on host
sudo su - analyst -c 'mkdir -p ~/analysis/captures && chmod 700 ~/analysis/captures && cd ~/analysis/captures'

# take VirtualBox snapshot (from Windows host, example)
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025" take "pre-capture" --description "Before Step 4 captures"

# verify snapshot list (Windows host)
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025" list

Run these diagnostics

# show dir perms/owner
ls -ld ~/analysis ~/analysis/captures

# full listing (show if anything odd)
ls -la ~/analysis/captures

# show filesystem and mount options for /home
mount | grep " on /home\| on / " || mount

# check attributes (immutable bit)
lsattr -d ~/analysis ~/analysis/captures 2>/dev/null || echo "lsattr not available"

# show ACLs if present
getfacl -p ~/analysis/captures 2>/dev/null || echo "getfacl not available"


# quick test: can root create and remove a file here?
sudo bash -c 'touch /home/analyst/analysis/captures/.root_write_test && echo OK && rm /home/analyst/analysis/captures/.root_write_test' || echo "root write test failed"

On Kali — create an EICAR ISO

  • Command run:
# create ISO stage and EICAR test file
mkdir -p /tmp/iso_stage
echo 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' > /tmp/iso_stage/malware_sample.exe

# install genisoimage if missing, then build ISO
sudo apt update
sudo apt install -y genisoimage
TS=$(date +%Y%m%d_%H%M%S)
ISO_NAME=eicar_${TS}.iso
genisoimage -o "/tmp/${ISO_NAME}" -V "SAMPLE_ISO" -r /tmp/iso_stage

# confirm ISO created and save its sha256 to captures
ls -lh /tmp/${ISO_NAME}
mkdir -p ~/analysis/captures
sha256sum /tmp/${ISO_NAME} | tee ~/analysis/captures/${ISO_NAME}.sha256

Copy all the creted files to /home/analyst/analysis/captures

  • command run:
cd ~/analysis/captures

# move tcpdump files if still in /tmp
mv /tmp/sample_net_* . 2>/dev/null

# move ISO if not yet copied
cp -n /tmp/eicar_20250929_085754.iso . 2>/dev/null

# set ownership
sudo chown -R analyst:analyst .

# generate SHA256 manifest
sha256sum * > manifest.sha256

# quick check
ls -lh
head -n 20 manifest.sha256

start apache server so that download all the files in windows

  • command run:

sudo systemctl start apache2  

extract malware.exe from .iso file usinf 7ZIP

On Windows (PowerShell as Administrator)

$ANALYSIS="C:\Users\User\Downloads\analysis"

# show files
Get-ChildItem $ANALYSIS | Format-Table Name,Length,LastWriteTime -AutoSize

# compute SHA256 of the exe and save
Get-FileHash "$ANALYSIS\malware_sample.exe" -Algorithm SHA256 | Format-List | Out-File "$ANALYSIS\sample_sha256_vm.txt"

# show the saved hash
Get-Content "$ANALYSIS\sample_sha256_vm.txt"

Onkali start tcpdump and save the PID

  • command run:
# on Kali
ts=$(date +%Y%m%d_%H%M%S)
sudo tcpdump -i any -s 0 -w /tmp/sample_net_${ts}.pcap -C 100 -W 10 > /tmp/tcpdump_${ts}.log 2>&1 &
echo $! > /tmp/tcpdump_${ts}.pid
echo "tcpdump started, ts=${ts}, pid=$(cat /tmp/tcpdump_${ts}.pid)"

Confirm Procmon is running & capturing

  • Pre‑run snapshots (Windows PowerShell — Run as Administrator)
$ANALYSIS="C:\Users\User\Downloads\analysis"

tasklist /v > "$ANALYSIS\pre_tasklist.txt"
wmic process get ProcessId,ExecutablePath,CommandLine /format:list > "$ANALYSIS\pre_process_list.txt"
netstat -ano > "$ANALYSIS\pre_netstat.txt"
ipconfig /all > "$ANALYSIS\ipconfig.txt"
"PRE $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
  • Execute hello.bat under Procmon (Windows PowerShell)
$ANALYSIS="C:\Users\User\Downloads\analysis"

"START $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

# Run the batch (non-blocking)
$proc = Start-Process -FilePath "C:\Windows\System32\cmd.exe" -ArgumentList "/c `"$ANALYSIS\hello.bat`"" -PassThru
"$($proc.Id) started at $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

# wait a short time so Procmon can log actions
Start-Sleep -Seconds 5

"END $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
  • Post‑run snapshots (Windows PowerShell)
$ANALYSIS="C:\Users\User\Downloads\analysis"

tasklist /v > "$ANALYSIS\post_tasklist.txt"
wmic process get ProcessId,ExecutablePath,CommandLine /format:list > "$ANALYSIS\post_process_list.txt"
netstat -ano > "$ANALYSIS\post_netstat.txt"
"POST $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

File → Save → Save native PML as

safely view the first few bytes of file in hex:

$ANALYSIS="C:\Users\User\Downloads\analysis"
# Read first 16 bytes as a single array
[byte[]]$bytes = Get-Content "$ANALYSIS\malware_sample.exe" -Encoding Byte -TotalCount 16
# Format as hex
$bytes | Format-Hex

Confirm Defender/AV status & scan the file (Windows PowerShell — Admin)

$ANALYSIS="C:\Users\User\Downloads\analysis"

# 1.1 show file listing & size (verify file exists)
Get-ChildItem $ANALYSIS | Format-Table Name,Length,LastWriteTime -AutoSize

# 1.2 quick Defender status
Get-MpComputerStatus | Select-Object AMServiceEnabled,AntispywareEnabled,AntivirusEnabled,RealTimeProtectionEnabled,QuickScanAge

# 1.3 run custom scan of the file (this will log detection to Windows Defender)
Start-MpScan -ScanType Custom -ScanPath "$ANALYSIS\malware_sample.exe"

# 1.4 after scan, check recent detections
Get-MpThreat | Select-Object ThreatID,Resources,ActionSuccess,DetectionTime,ThreatName | Format-Table -AutoSize

# 1.5 append results to run_log
"DEFENDER-STATUS $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
Get-MpComputerStatus | Out-String | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
Get-MpThreat | Out-String | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

Remove existing file so we can re-download (Windows PowerShell — Admin)

$ANALYSIS="C:\Users\User\Downloads\analysis"
# 2.1 remove the file (so download will recreate it and trigger events)
Remove-Item "$ANALYSIS\malware_sample.exe" -Force -ErrorAction SilentlyContinue

# 2.2 log removal
"REMOVED-EXISTING-FILE $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

# 2.3 verify gone
Get-ChildItem $ANALYSIS | Format-Table Name,Length,LastWriteTime -AutoSize | Out-String | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

Stop existing tcpdump process

sudo pkill -SIGINT tcpdump
# give it a second, then confirm none are running
sleep 1
pgrep -a tcpdump || echo "tcpdump not running"

Move existing /tmp pcaps into captures directory and fix ownership

sudo mkdir -p /home/analyst/analysis/captures

# move /tmp pcaps to captures (safe)
sudo mv /tmp/sample_net_* /home/analyst/analysis/captures/ 2>/dev/null || true

# make analyst the owner of moved files
sudo chown analyst:analyst /home/analyst/analysis/captures/sample_net_* 2>/dev/null || true

# show what we moved
ls -lh /home/analyst/analysis/captures/ | sed -n '1,200p'

Remove stale pid/log files and ensure /tmp perms are standard

# remove tcpdump pid/log so root can recreate them cleanly
sudo rm -f /tmp/tcpdump_pid.txt /tmp/tcpdump_start.log

# ensure /tmp is sticky world-writable
sudo chmod 1777 /tmp
ls -ld /tmp

Ensure captures dir ownership & perms are correct

sudo chown -R analyst:analyst /home/analyst/analysis/captures
sudo chmod 700 /home/analyst/analysis/captures
ls -ld /home/analyst/analysis/captures
ls -lh /home/analyst/analysis/captures | sed -n '1,200p'

Start tcpdump correctly as root (nohup + root writes PID)

sudo bash -c 'nohup tcpdump -i any -s 0 -w /home/analyst/analysis/captures/sample_net_$(date +%Y%m%d_%H%M%S).pcap -C 100 -W 10 > /tmp/tcpdump_start.log 2>&1 & echo $! > /tmp/tcpdump_pid.txt'

Windows Guest Pre‑Execution

$ANALYSIS="C:\Users\User\Downloads\analysis"
# Create folder if it doesn't exist
New-Item -ItemType Directory -Force -Path $ANALYSIS | Out-Null

# Baseline process list
tasklist /v > "$ANALYSIS\pre_tasklist.txt"
wmic process get ProcessId,ExecutablePath,CommandLine /format:list > "$ANALYSIS\pre_process_list.txt"

# Baseline network info
netstat -ano > "$ANALYSIS\pre_netstat.txt"
ipconfig /all > "$ANALYSIS\ipconfig_pre.txt"

# Optional: loaded processes with paths
Get-Process | Select-Object Id, ProcessName, Path | Out-File "$ANALYSIS\pre_getprocess.txt"

# Log timestamp
"PRE $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

Start Procmon with filters

  • Run Procmon.exe as Administrator.
  • Accept EULA.
  • Go Filter → Filter..., then Add these filters one by one:
  • Filter condition
Filter Condition Action
Process Name is malware_sample.exe Include
Process Name is procmon.exe Exclude
Path contains C:\Users\User\Downloads\analysis Include
Operation is RegSetValue Include
Operation is RegCreateKey Include
Operation is CreateFile Include
Operation is CreateProcess Include
Operation is WriteFile Include
Operation is DeleteFile Include

Compute malware SHA256

Get-FileHash "$ANALYSIS\malware_sample.exe" -Algorithm SHA256 | Out-File "$ANALYSIS\sample_sha256_vm.txt"
Get-Content "$ANALYSIS\sample_sha256_vm.txt" | Out-File "$ANALYSIS\run_log.txt" -Append

Title: malware_sample.exe execution attempt — analysis note

Summary: The attempt to execute C:\Users\User\Downloads\analysis\malware_sample.exe failed because the file is not a Windows PE binary. Inspection shows the file is 69 bytes in length and its contents match the standard EICAR antivirus test string. When PowerShell attempted to start the file it returned the error “The specified executable is not a valid application for this OS platform,” which is expected because EICAR is a benign ASCII test string meant to trigger AV detections, not a runnable program. No process was created as a result of the launch attempt, so Procmon filters that target a process name for this file produced no events. Evidence saved to the analysis folder includes the hex header, the textual contents showing the EICAR string, and the computed SHA256 hash 131F95C51CC819465FA1797F6CCACF9D494AAAFF46FA3EAC73AE63FFBDFD8267. Because this artifact is EICAR, it should be treated as an AV test file only; it does not indicate executable malware nor does it produce runtime behavior to capture.

Recreation of the same EICAR file (safe) on the Windows guest: run the following PowerShell commands to create an identical file and record its hash in your analysis folder. This is for reproducibility and reporting.

$ANALYSIS="C:\Users\User\Downloads\analysis"
New-Item -ItemType Directory -Force -Path $ANALYSIS | Out-Null
'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' > "$ANALYSIS\malware_sample.exe"
Get-FileHash "$ANALYSIS\malware_sample.exe" -Algorithm SHA256 | Out-File "$ANALYSIS\sample_sha256_vm.txt"
Get-Content "$ANALYSIS\sample_sha256_vm.txt" | Out-File "$ANALYSIS\run_log.txt" -Append

Creating a benign test executable you can run under Procmon and tcpdump to validate your monitoring pipeline: the following PowerShell snippet compiles a tiny console program (prints “hello”) and saves it into your analysis folder. Running this test program exercises process creation, file and registry events and is safe for validating capture tooling.

$ANALYSIS="C:\Users\User\Downloads\analysis"
$code = @'
using System;
class P { static void Main() { Console.WriteLine("hello"); } }
'@
Add-Type -TypeDefinition $code -Language CSharp -OutputAssembly "$ANALYSIS\testprog.exe"
Get-FileHash "$ANALYSIS\testprog.exe" -Algorithm SHA256 | Out-File "$ANALYSIS\testprog_sha256.txt"

To run the test program under monitoring and collect a short trace, start Procmon as Administrator with the single filter Path contains C:\Users\User\Downloads\analysis and capture enabled, then in an elevated PowerShell run these commands to launch the test program for 15 seconds, stop it, and record start/end timestamps to your run log:

"START $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
$proc = Start-Process -FilePath "$ANALYSIS\testprog.exe" -PassThru
"LAUNCHED PID=$($proc.Id) AT $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
Start-Sleep -Seconds 15
Stop-Process -Id $proc.Id -ErrorAction SilentlyContinue
"END $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

Report note for inclusion: the file initially labeled malware_sample.exe is the EICAR test string and therefore cannot execute as a Windows application; this prevented any runtime behavior and resulted in no Procmon process events for that filename. I recreated the EICAR file and recorded its SHA256 for traceability and created a benign test executable to validate the capture pipeline. If you plan to analyze a real malware binary later, only do so in a fully isolated VM with a fresh pre-capture snapshot and follow the project's safety checklist; I can provide step-by-step transfer and execution instructions for that scenario.

Start New — Create user and analysis folder

Summary: Created a dedicated non-privileged account analyst for malware analysis and a secured workspace /home/analyst/analysis/captures for collecting evidence (pcaps, Procmon logs, memory dumps, ISOs). Ownership and permissions were set to prevent accidental access from other users.

  • command run:
# create user (interactive)
sudo adduser analyst

# (optional) give sudo if required for lab tasks
sudo usermod -aG sudo analyst

# create analysis captures folder and subfolders
mkdir -p /home/analyst/analysis/captures
mkdir -p /home/analyst/analysis/captures/{pcaps,procmon,memory,isos}

# set ownership and restrictive permissions
sudo chown -R analyst:analyst /home/analyst/analysis
sudo chmod -R 700 /home/analyst/analysis

# verification
id analyst
ls -ld /home/analyst/analysis /home/analyst/analysis/captures
  1. Create a test “malware.exe” (EICAR file)
  • command run:
mkdir -p /tmp/iso_stage
echo 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' > malware_sample.exe
sha256sum malware_sample.exe > malware_sample.exe.sha256
ls -lh /tmp/iso_stage/malware.exe   # should show 68 or 69 bytes
  1. Pack into an ISO
# Generate timestamp-based ISO name
TS=$(date +%Y%m%d_%H%M%S)
ISO_NAME="test_iso_${TS}.iso"

# Create the ISO from current folder
genisoimage -o "/home/analyst/analysis/captures/${ISO_NAME}" -V "EICAR_ISO" -r .
  1. start server cause cannot copy files to var/www/html/ directly so i had to start server
  • command run:
python3 -m http.server 8000 --bind 127.0.0.1 --directory . 
  1. download all the files in kali and copy to /var/www/html/ so that i can download them from kali in windows machine

  2. Verify files & hashes (Windows — PowerShell)

$ANALYSIS = "C:\Users\User\Downloads\analysis"

# list files
Get-ChildItem $ANALYSIS | Format-Table Name,Length,LastWriteTime -AutoSize

# compute SHA256 of the exe and show
Get-FileHash "$ANALYSIS\malware_sample.exe" -Algorithm SHA256 | Format-List

# show provided sha256 text for comparison
Get-Content "$ANALYSIS\malware_sample.exe.sha256"
  1. Take/confirm VM snapshot
& "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025" take "pre-exec-$(Get-Date -Format yyyyMMdd_HHmmss)" --description "Pre execution snapshot
  1. On Kali host — start network capture (tcpdump)
# on Kali host
ts=$(date +%Y%m%d_%H%M%S)
sudo nohup tcpdump -i any -s 0 -w /home/analyst/analysis/captures/pcaps/sample_net_${ts}.pcap -C 100 -W 10 > /tmp/tcpdump_${ts}.log 2>&1 &
echo $! | sudo tee /tmp/tcpdump_${ts}.pid
echo "tcpdump started, pid=$(cat /tmp/tcpdump_${ts}.pid), ts=${ts}"
  1. On Windows VM — start Procmon and set filters (GUI steps)
  • Run Procmon.exe as Administrator inside the VM.
  • Accept the EULA.
  • Apply these filters (Filter → Filter... → Add then Apply):
Path contains C:\Users\User\Downloads\analysis → Include

Operation is RegSetValue → Include

Operation is RegCreateKey → Include

Operation is CreateFile → Include

Operation is CreateProcess → Include

Operation is WriteFile → Include

Process Name is procmon.exe → Exclude

Start capture (Ctrl+E). Keep Procmon visible so you can watch events live.
  1. On Windows VM — collect pre-run baselines & start run_log
$ANALYSIS="C:\Users\User\Downloads\analysis"

# ensure folder exists
New-Item -ItemType Directory -Force -Path $ANALYSIS | Out-Null

# pre-run baselines
tasklist /v > "$ANALYSIS\pre_tasklist.txt"
wmic process get ProcessId,ExecutablePath,CommandLine /format:list > "$ANALYSIS\pre_process_list.txt"
netstat -ano > "$ANALYSIS\pre_netstat.txt"
ipconfig /all > "$ANALYSIS\ipconfig_pre.txt"

# add PRE timestamp to run_log
"PRE $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

The supplied malware_sample.exe did not execute in the analysis VM because it is the EICAR test string (69 bytes) and not a valid Windows PE executable; Windows/Defender treats it as a detection artifact rather than a runnable sample. For safety and legality, no real malicious binaries were obtained or executed. To validate the capture pipeline (process creation, file writes, registry changes and network callbacks) I compiled and ran a benign simulator (test_mal_sim.exe) inside the isolated Windows VM. The simulator is safe: it writes a runtime log, creates a registry key, spawns a child process, and performs an HTTP GET to a controlled Kali HTTP sink, producing the same telemetry we need to verify Procmon, tcpdump, and collection workflows. All activity was performed against a pre‑execution VM snapshot in an isolated host‑only network; network traffic was captured on the Kali host with tcpdump and endpoint activity was captured on the VM with Procmon. Artifacts were hashed and recorded in a manifest for chain‑of‑custody. This approach validates the monitoring and evidence-collection process without the legal or safety risks of handling real malware; once the pipeline is confirmed, the same steps may be applied to authorized samples under appropriate approvals.

  1. Edit & run the simulator (PowerShell in the VM)
$ANALYSIS="C:\Users\User\Downloads\analysis"
New-Item -ItemType Directory -Force -Path $ANALYSIS | Out-Null

$code = @'
using System;
using System.IO;
using Microsoft.Win32;
using System.Net;
using System.Diagnostics;
public class TestSim {
  public static int Main(string[] args) {
    try {
      string outp = @"C:\Users\User\Downloads\analysis\sim_output.txt";
      File.AppendAllText(outp, "START " + DateTime.Now.ToString("o") + Environment.NewLine);
      using (var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\TestMalSim")) {
        key.SetValue("LastRun", DateTime.Now.ToString("o"));
      }
      Process p = new Process();
      p.StartInfo.FileName = "cmd.exe";
      p.StartInfo.Arguments = "/c echo child process ran >> \"" + outp + "\"";
      p.Start();
      p.WaitForExit(5000);
      try {
        using (var wc = new WebClient()) {
          string result = wc.DownloadString("http://192.168.0.105:8000/ping");
          File.AppendAllText(outp, "HTTP_OK: " + (result ?? "") + Environment.NewLine);
        }
      } catch { File.AppendAllText(outp, "HTTP_FAIL" + Environment.NewLine); }
      File.AppendAllText(outp, "END " + DateTime.Now.ToString("o") + Environment.NewLine);
    } catch (Exception ex) {
      try { File.AppendAllText(@"C:\Users\User\Downloads\analysis\sim_error.txt", ex.ToString()); } catch {}
    }
    return 0;
  }
}
'@

$src = Join-Path $ANALYSIS "TestSim.cs"
$code | Out-File -FilePath $src -Encoding utf8

# compile (Add-Type usually works)
Add-Type -TypeDefinition $code -Language CSharp -OutputAssembly (Join-Path $ANALYSIS "test_mal_sim.exe")

# run the simulator
& "$ANALYSIS\test_mal_sim.exe"

# show results
Write-Host "----- sim_output.txt -----"
Get-Content "$ANALYSIS\sim_output.txt" -Raw
Write-Host "----- registry key -----"
reg query "HKCU\Software\TestMalSim" /v LastRun

  1. python3 -m http.server 8000 --bind 0.0.0.0 --directory .
  • start server
  • test connectivity again
Test-NetConnection -ComputerName 192.168.0.105 -Port 8000

its failing to connect Next

  1. Remove the existing rule and recreate it
& "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" controlvm "Kali Linux 2025" natpf1 delete "httpfwd"
& "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" controlvm "Kali Linux 2025" natpf1 "httpfwd,tcp,127.0.0.1,8100,,8000"
  1. Just use the existing rule
& "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" showvminfo "Kali Linux 2025" --details
  1. Run the malware simulator in the Windows VM (PowerShell)
$ANALYSIS="C:\Users\User\Downloads\analysis"
& "$ANALYSIS\test_mal_sim.exe"

  1. Check results:
# Option A — using the variable you already set
$ANALYSIS="C:\Users\User\Downloads\analysis"
& "$ANALYSIS\test_mal_sim.exe"

# show last 20 lines of the simulator log
Get-Content "C:\Users\User\Downloads\analysis\sim_output.txt" -Tail 20

# show the registry value set by the simulator
reg query "HKCU\Software\TestMalSim" /v LastRun

Before executing the malware simulation, the network connectivity between the Windows analysis VM and the Kali host was verified. Although the TCP connection on port 8000 was successful (TcpTestSucceeded: True), the simulator repeatedly logged HTTP_FAIL because it attempted to access the /ping endpoint on the HTTP server, which did not exist at that time. The Python HTTP server on Kali was serving only static files from its working directory, so the requested path returned a 404 error.

To resolve this, a simple text file named ping containing the response string (e.g., pong) was created in the HTTP server directory, ensuring that the simulator could successfully retrieve content from the expected endpoint. After this adjustment, re-running the simulator allows it to log HTTP_OK when the connection succeeds, accurately simulating network activity for analysis.

  1. On Kali, in the directory you started the HTTP server:
echo "pong" > ping
  1. Now, /ping exists. Re-run the simulator on Windows:
& "$ANALYSIS\test_mal_sim.exe"
Get-Content "$ANALYSIS\sim_output.txt" -Tail 20
  1. Save post‑run baselines (Windows PowerShell — Admin)
$ANALYSIS="C:\Users\User\Downloads\analysis"
tasklist /v > "$ANALYSIS\post_tasklist.txt"
wmic process get ProcessId,ExecutablePath,CommandLine /format:list > "$ANALYSIS\post_process_list.txt"
netstat -ano > "$ANALYSIS\post_netstat.txt"
"POST $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
  1. Copy Windows artifacts into Kali captures
scp user@windows-ip:"C:/Users/User/Downloads/analysis/*" /home/analyst/analysis/captures/

In this step, I established a controlled malware analysis environment, created baseline captures, and validated the monitoring pipeline using a safe simulator. A dedicated non-privileged user (analyst) was created on the Kali host, with a secured workspace /home/analyst/analysis/captures to collect all artifacts including network captures, Procmon logs, ISOs, and hashes. Permissions and ownership were configured to ensure isolation and prevent accidental interference.

A benign EICAR test file (malware_sample.exe) was generated and packed into an ISO to simulate a malware sample safely. This allowed verification of hash computation, file transfer, and artifact collection workflows without legal or security risks. Network captures were performed using tcpdump on the Kali host and endpoint activity was monitored via Procmon on the Windows analysis VM. A benign simulator executable (test_mal_sim.exe) was compiled to generate process creation, registry, file, and network activity, confirming that the monitoring and evidence collection pipeline functioned as expected.

During the simulation, I encountered a connectivity issue: the simulator’s HTTP requests to the Kali host initially failed because the /ping endpoint did not exist on the Python HTTP server. After creating a simple ping file to respond with pong, the simulator successfully logged HTTP_OK, demonstrating that network activity could be captured and correlated with the Windows VM execution.

All artifacts, including network captures, registry snapshots, process lists and simulator logs, were hashed and stored in the captures directory. This step validated the full workflow for malware analysis—starting from pre-execution setup, artifact collection and monitoring, to post-execution baselines—without exposing the environment to real malicious code. Key learnings include the importance of verifying file types before execution, confirming network connectivity and server endpoints, and ensuring all capture tools are correctly configured prior to running any analysis.

Overall, this step reinforced the importance of meticulous pre-execution preparation and validated that the capture and monitoring infrastructure is operational and reliable for safe malware analysis in a fully isolated virtual environment.

Lessons Learned and Pitfalls

During Step 3, several important lessons emerged. First, validating file formats before execution is crucial: the EICAR test file is not a Windows PE binary and attempting to run it produces no process events, emphasizing the need to differentiate between detection artifacts and executable malware. Second, network connectivity and endpoint availability must be confirmed before simulation; initially, the simulator’s HTTP requests failed due to a missing /ping endpoint, highlighting the importance of ensuring all expected services are correctly configured. Third, pre-execution snapshots and baseline captures are essential for reliable comparisons of system state and proper ownership and permission management prevent accidental data corruption. Finally, automating the collection of logs, hashes and artifacts ensures reproducibility and traceability, while validating the pipeline with a safe simulator provides confidence in monitoring tools before handling any real malware. Careful attention to these details mitigates risks, streamlines analysis and strengthens overall process reliability.

Step 4 Perform Dynamic Analysis

  • Create more realistic but still 100% safe dummy executables that look and behave like malware
#include <winsock2.h>   // Include this first
#include <windows.h>
#include <winreg.h>
#include <stdio.h>

int main() {
    // 1. Write to file
    FILE *f = fopen("C:\\Users\\Public\\testfile.txt", "w");
    if (f) {
        fputs("Fake malware wrote this\n", f);
        fclose(f);
    }

    // 2. Write registry key
    HKEY hKey;
    RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\FakeMalware", 0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL);
    const char *data = "HelloWorld";
    RegSetValueEx(hKey, "TestValue", 0, REG_SZ, (BYTE*)data, strlen(data)+1);
    RegCloseKey(hKey);

    // 3. Spawn a process
    system("cmd.exe /c echo FakeMalware child process > C:\\Users\\Public\\child.txt");

    // 4. Attempt socket connection
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2), &wsaData);
    SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock != INVALID_SOCKET) {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(4444);
        server.sin_addr.s_addr = inet_addr("127.0.0.1");
        connect(sock, (struct sockaddr*)&server, sizeof(server));
        closesocket(sock);
    }
    WSACleanup();

    MessageBoxA(NULL, "Fake Malware executed (safe demo)", "Training Sample", MB_OK);
    return 0;
}

malware_sample.exe is a deliberately benign training binary created to exercise endpoint and network monitoring during dynamic analysis. When executed it: creates a file under C:\Users\Public, writes a registry key under HKCU\Software\FakeMalware, spawns a child process, attempts a TCP connection to 127.0.0.1:4444 and displays a dialog box. These actions generate observable Procmon events, process creation traces, file writes and (attempted) network traffic for testing capture pipelines without risking malware.

  1. Run in Host (cmd.exe) to confirm VM name and snapshot list:
  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" list vms
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025" list
  1. Take a fresh pre-run snapshot (Host)
  • command run:
"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" snapshot "Kali Linux 2025" take "pre-dynamic" --description "Before dynamic analysis"
  1. Start full network capture (Kali)
  • command run:
# Start tcpdump (background), saves PID to /tmp/tcpdump_pid.txt
sudo bash -c 'nohup tcpdump -i any -s 0 -w /home/analyst/analysis/captures/sample_net_$(date +%Y%m%d_%H%M%S).pcap -C 100 -W 10 > /tmp/tcpdump_start.log 2>&1 & echo $! > /tmp/tcpdump_pid.txt'
# Quick check:
sleep 1
cat /tmp/tcpdump_pid.txt
ps -p $(cat /tmp/tcpdump_pid.txt) -o pid,cmd
  1. Start full network capture (Kali)
  • Where: Kali terminal (analyst account)
  • Start tcpdump in background and save PID:
# Start tcpdump (background), saves PID to /tmp/tcpdump_pid.txt
sudo bash -c 'nohup tcpdump -i any -s 0 -w /home/analyst/analysis/captures/sample_net_$(date +%Y%m%d_%H%M%S).pcap -C 100 -W 10 > /tmp/tcpdump_start.log 2>&1 & echo $! > /tmp/tcpdump_pid.txt'
# Quick check:
sleep 1
cat /tmp/tcpdump_pid.txt
ps -p $(cat /tmp/tcpdump_pid.txt) -o pid,cmd
  1. Start full network capture (kali)
  • command run:
sudo bash -c 'nohup tcpdump -i any -s 0 -w /home/analyst/analysis/captures/sample_net_$(date +%Y%m%d_%H%M%S).pcap -C 100 -W 10 > /tmp/tcpdump_start.log 2>&1 & echo $! > /tmp/tcpdump_pid.txt'
  1. Prepare Procmon (Windows guest)
  • Start Procmon.exe as Administrator.
  • Apply filters: Filter → Filter... and add:
Path contains C:\Users\User\Downloads\analysis → Include

Operation is RegSetValue → Include

Operation is RegCreateKey → Include

Operation is CreateFile → Include

Operation is CreateProcess → Include

Process Name is procmon.exe → Exclude
  1. Launch the sample under Procmon capture (Windows PowerShell, Admin)
$ANALYSIS="C:\Users\User\Downloads\analysis"
$proc = Start-Process -FilePath "$ANALYSIS\malware_sample.exe" -PassThru
"LAUNCHED PID=$($proc.Id) AT $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
Start-Sleep -Seconds 30
Stop-Process -Id $proc.Id -ErrorAction SilentlyContinue
"END $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append
  1. Save Procmon capture to file (Windows GUI)
  • Stop capture if you want (Ctrl+E) or leave on until save.
  • File → Save…
    • Save: Events displayed using current filter
    • Select Native Process Monitor format (PML) (and optionally CSV)
    • Save to C:\Users\User\Downloads\analysis\malware_run.pml (and malware_run.csv if chosen).
    • Confirm file exists in the analysis folder.
  1. Run these in an Admin PowerShell on the Windows VM.
  • command run:
Get-ChildItem -Path $ANALYSIS\LogFile.*

  1. Print last lines of run_log:
Get-Content "$ANALYSIS\run_log.txt" -Tail 50
  1. Ensure files created by sample are present and capture values exist:
Get-Item "C:\Users\Public\testfile.txt" -ErrorAction SilentlyContinue
Get-Content "C:\Users\Public\testfile.txt" -ErrorAction SilentlyContinue
reg query "HKCU\Software\FakeMalware" /v TestValue

  1. Transfer Procmon PML/CSV & binary from Windows → Kali
  • open terminal where .CSV and .PML and .exe files are store and start server
  • command run:
python -m http.server 8000 --bind 192.168.01.100 # windows ip address
  • download all three files in kali:

# download the logs
wget http://192.168.0.100:8000/Logfile.CSV -O ~/analysis/captures/Logfile.CSV
wget http://192.168.0.100:8000/Logfile.PML -O ~/analysis/captures/Logfile.PML

# optional: download binary sample
wget http://192.168.0.100:8000/malware_sample.exe -O ~/analysis/samples/malware_sample.exe
wget http://192.168.0.100:8000/static.CSV -O ~/analysis/captures/static.CSV
  1. Stop tcpdump & hash PCAPs (Kali)
  • Run on Kali:
# stop tcpdump gracefully if you started it earlier (PID file path used earlier)
if [ -f /tmp/tcpdump_pid.txt ]; then
  sudo kill -SIGINT "$(cat /tmp/tcpdump_pid.txt)" || true
  sleep 1
fi

# confirm stopped
pgrep -a tcpdump || echo "tcpdump not running"
  1. Quick checks — confirm files and show first lines
# from ~/analysis/captures
ls -l Logfile.CSV static.CSV malware_sample.exe malware_sample.exe.sha256

echo "--- procmon (first 8 lines) ---"
head -n 8 Logfile.CSV

echo "--- network (first 8 lines) ---"
head -n 8 static.CSV
  1. Correlate script
#!/usr/bin/env python3
# correlate_my_files.py
import csv, argparse
from dateutil import parser as dateparser
from bisect import bisect_left

PROC="~/analysis/captures/Logfile.CSV".replace("~", "/home/analyst")
NET="~/analysis/captures/static.CSV".replace("~", "/home/analyst")
OUT="~/analysis/reports/correlation_results.csv".replace("~", "/home/analyst")

TOL=2.0  # seconds

def read_network(netfile):
    rows=[]
    with open(netfile,newline='') as f:
        r=csv.DictReader(f)
        headers=r.fieldnames
        # try common epoch column names:
        epoch_col=None
        for cand in ("frame.time_epoch","frame.time","time_epoch","time"):
            if cand in headers:
                epoch_col=cand; break
        for row in r:
            if epoch_col:
                try:
                    epoch=float(row.get(epoch_col,0.0))
                except:
                    epoch=0.0
            else:
                # try parse any timestamp-like column
                epoch=0.0
                for h in headers:
                    val=row.get(h,"")
                    try:
                        dt=dateparser.parse(val)
                        epoch=dt.timestamp(); break
                    except: pass
            rows.append((epoch,row))
    rows.sort(key=lambda x:x[0])
    times=[r[0] for r in rows]
    return times, rows

def read_proc(procfile):
    rows=[]
    with open(procfile,newline='',encoding='utf-8',errors='replace') as f:
        r=csv.DictReader(f)
        headers=r.fieldnames
        # find likely time column
        ts_col=None
        for cand in ("Time of Day","Time","Date & Time","Date/Time","Time of Day (UTC)"):
            if cand in headers:
                ts_col=cand; break
        if ts_col is None:
            ts_col=headers[0]
        for row in r:
            ts=row.get(ts_col,"")
            epoch=0.0
            try:
                epoch=float(ts)  # maybe already epoch
            except:
                try:
                    dt=dateparser.parse(ts)
                    epoch=dt.timestamp()
                except:
                    epoch=0.0
            rows.append((epoch,row))
    rows.sort(key=lambda x:x[0])
    return rows, ts_col

def find_nearest(net_times, net_rows, t, tol):
    if not net_times: return None
    i=bisect_left(net_times,t)
    cand=[]
    if i<len(net_times): cand.append((abs(net_times[i]-t),i))
    if i-1>=0: cand.append((abs(net_times[i-1]-t),i-1))
    cand.sort()
    if cand and cand[0][0]<=tol:
        return net_rows[cand[0][1]][1]
    return None

def main():
    net_times, net_rows = read_network(NET)
    proc_rows, ts_col = read_proc(PROC)
    import os
    os.makedirs("/home/analyst/analysis/reports", exist_ok=True)
    outfh=open(OUT,'w',newline='',encoding='utf-8')
    fieldnames=['proc_epoch','proc_time_str','proc_ProcessName','proc_PID','proc_Operation','proc_Path',
                'net_epoch','net_ip_src','net_ip_dst','net_sport','net_dport']
    writer=csv.DictWriter(outfh, fieldnames=fieldnames)
    writer.writeheader()
    for epoch, prow in proc_rows:
        net = find_nearest(net_times, net_rows, epoch, TOL)
        out={
            'proc_epoch': epoch,
            'proc_time_str': prow.get(ts_col,""),
            'proc_ProcessName': prow.get('Process Name', prow.get('Process','')),
            'proc_PID': prow.get('PID',''),
            'proc_Operation': prow.get('Operation',''),
            'proc_Path': prow.get('Path',''),
            'net_epoch':'','net_ip_src':'','net_ip_dst':'','net_sport':'','net_dport':''
        }
        if net:
            out['net_epoch']=net.get('frame.time_epoch', net.get('time', ''))
            out['net_ip_src']=net.get('ip.src','')
            out['net_ip_dst']=net.get('ip.dst','')
            out['net_sport']=net.get('tcp.srcport','')
            out['net_dport']=net.get('tcp.dstport','')
        writer.writerow(out)
    outfh.close()
    print("Wrote", OUT)

if __name__=="__main__":
    main()
  1. command run:
chmod +x ~/analysis/captures/correlate_my_files.py
  • run program for generate report:
python3 correlate_my_files.py

Next copy report file from analyst user to kali user so that doenload it from kali in windows machine

  • command run:
mkdir -p /home/kali/analysis/captures
sudo cp /home/analyst/analysis/reports/correlation_results.csv /home/kali/analysis/captures/
  1. Compute sample SHA256 (Windows or Kali)
  • command run:
sha256sum ~/analysis/captures/malware_sample.exe 2>/dev/null || sha256sum ~/analysis/samples/malware_sample.exe
  1. On Windows PowerShell:
  • command run:
Get-FileHash "C:\Users\User\Downloads\analysis\malware_sample.exe" -Algorithm SHA256

Step 4, Dynamic Analysis, is fully complete. The benign training binary malware_sample.exe was executed on the Windows VM under Procmon capture. During its execution, the sample created files in C:\Users\Public\ such as testfile.txt, as well as run artifacts in the analysis folder including run_log.txt, post_netstat.txt, post_process_list.txt and test_mal_sim.exe. It also wrote a registry key under HKCU\Software\FakeMalware with the value TestValue=HelloWorld, spawned a child process that created child.txt, attempted a TCP connection to the local loopback address 127.0.0.1:4444 and displayed a message box confirming benign execution.

Procmon captured these activities, saving them in both native PML (Logfile.PML) and filtered CSV format (Logfile.CSV). Network traffic was captured using tcpdump on the Kali analyst host, producing PCAP files (sample_net_*.pcap) and CSV logs (static.CSV). The correlation script correlate_my_files.py was run, producing correlation_results.csv which aligns process events with network events within a specified tolerance. SHA256 checksums of the sample binary were computed on both Kali and Windows to ensure integrity.

The Procmon logs show high-frequency file system activity by Explorer.EXE in the monitored folder, confirming that the sample’s actions were observable. Network attempts targeting loopback were captured but do not appear in external traffic logs, demonstrating that safe testing can exercise endpoint and network monitoring without exposing the lab environment. The correlation output contains many process events with no matched network events, which is expected for operations limited to file and registry activity or when network events occur outside the correlation window.

All expected artifacts were generated, validated and collected. Environment snapshots were taken before execution, ensuring reproducibility. This step confirmed that the monitoring pipeline effectively captures file creation, registry writes, process spawns and network attempts, even when using a safe training binary. The results are ready for packaging into a final analysis report and archival for documentation and future reference.

Step 5 Develop Mitigation (create IoCs / YARA / firewall rules)

  1. Start creating a YARA rule file
  • command run:
cat > ioc_yara.yara <<'YARA'
rule FakeMalware_Observed {
  meta:
    description = "Training sample observed during dynamic analysis"
    author = "analyst"
    date = "2025-10-01"
  strings:
    $s1 = "Fake malware wrote this" ascii wide
  condition:
    $s1
}
YARA

  1. Test the rule against the sample executable:
  • command run:
yara ioc_yara.yara malware_sample.exe > yara_hits.txt || true
  1. Check the hits:
  • command run:
cat yara_hits.txt
  1. Compute SHA256 of the sample:
  • command run:
sha256sum malware_sample.exe > malware_sample.exe.sha256
  1. Append YARA rule and SHA256 to a final report (create one here in captures):
  • command run:
echo -e "YARA string-rule (ioc_yara.yara):\n" > analysis_report.md
cat ioc_yara.yara >> analysis_report.md
echo -e "\nSHA256:\n" >> analysis_report.md
cat malware_sample.exe.sha256 >> analysis_report.md

You have successfully created a minimal YARA rule (ioc_yara.yara) that detects your safe training sample based on a unique string it writes to the system. Running this rule against malware_sample.exe produced a positive hit (yara_hits.txt), confirming that the rule works as intended. You also saved the SHA256 hash of the sample (malware_sample.exe.sha256), providing a precise fingerprint of the file. Together, the YARA rule and hash form your initial Indicators of Compromise (IoCs), which can be used to automatically identify this sample in future analyses or on other systems. This step demonstrates how to generate actionable detection rules for safe malware testing.

Step 6 Automate Analysis / Parsing (optional but recommended)

  1. create quick_analyze.py python script
#!/usr/bin/env python3
import sys
import hashlib
import os

def sha256sum(filename):
    h = hashlib.sha256()
    with open(filename, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            h.update(chunk)
    return h.hexdigest()

def basic_info(filename):
    size = os.path.getsize(filename)
    name = os.path.basename(filename)
    return {"name": name, "size_bytes": size, "sha256": sha256sum(filename)}

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 quick_analyze.py <file>")
        sys.exit(1)
    
    file_path = sys.argv[1]
    info = basic_info(file_path)
    print(info)
  1. Run quick_analyze on the malware sample
  • run command:
python3 ~/analysis/captures/quick_analyze.py ~/analysis/captures/malware_sample.exe > ~/analysis/captures/quick_report_$(date +%Y%m%d_%H%M%S).json

  1. Parse PCAP files to CSV
  • run command:
sudo tshark -r ~/analysis/captures/sample_net_*.pcap -T fields -e frame.time_epoch -e ip.src -e ip.dst -e tcp.srcport -e tcp.dstport -E header=y -E separator=, > ~/analysis/captures/network_events.csv
  1. View the JSON report
  • command run:
cat ~/analysis/captures/quick_report_*.json

  1. On the Windows VM (as Administrator), start Procmon, apply your filters, then launch the sample under Procmon capture. Run this in an elevated PowerShell window:
  • run command:
# Start the sample under Procmon capture and let it run ~30s
$ANALYSIS="C:\Users\User\Downloads\analysis"
$proc = Start-Process -FilePath "$ANALYSIS\malware_sample.exe" -PassThru; "LAUNCHED PID=$($proc.Id) AT $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append; Start-Sleep -Seconds 30; Stop-Process -Id $proc.Id -ErrorAction SilentlyContinue; "END $(Get-Date -Format o)" | Out-File -FilePath "$ANALYSIS\run_log.txt" -Append

Leave Procmon capturing while this runs, then export/save the Procmon PML/CSV (Logfile_auto.PML / Logfile_auto.CSV) to C:\Users\User\Downloads\analysis\ from the Procmon GUI (File → Save… → Native Process Monitor (PML) and CSV).

  1. Back on Kali (where tcpdump is running), stop the tcpdump when the Windows run is finished. If you started tcpdump in a terminal and can use Ctrl+C there, do that. Otherwise run:
  • command run:
# gracefully stop all running tcpdump processes (use if you don't have the original terminal)
sudo pkill -2 tcpdump || true
  1. confirm PCAP(s) file exist:
  • command run:
ls -l ~/analysis/captures/sample_net_*.pcap
  1. Parse the PCAP(s) to CSV (this creates network_events.csv in the same folder):
  • command run:
sudo tshark -r ~/analysis/captures/sample_net_*.pcap -T fields -e frame.time_epoch -e ip.src -e ip.dst -e tcp.srcport -e tcp.dstport -E header=y -E separator=, > ~/analysis/captures/network_events.csv
  1. Regenerate the correlation CSV so Procmon events link to network events (run in your captures folder):
  • command run:
python3 ~/analysis/captures/correlate_my_files.py

In this step I successfully captured the network activity generated while executing the malware sample. By running tcpdump on Kali during the analysis window, I was able to record all traffic into a pcap file and then convert it into a readable CSV using tshark. The resulting file contains timestamps, source and destination IPs, and port numbers, which give me clear visibility into both normal background traffic and potential malicious connections initiated by the sample. What I learned here is that network captures are a crucial part of malware analysis because they reveal external communication attempts, possible command-and-control servers, and data exfiltration behavior that would not be visible through static analysis alone. This step helped me understand how to bridge system-level activity with network-level evidence, which I will use later for correlation with process monitoring events.

About

Completed a Malware Analysis and Reverse Engineering project where I analyzed a malware sample in an isolated environment, monitored its behavior, extracted file metadata, and created custom YARA rules and IoCs. Automated reporting with Python streamlined the analysis and improved efficiency.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages