Skip to main content

Lesson 10 of 10

Practice & Quiz - Incident Response & Forensics

Test your DFIR knowledge: incident response phases, memory forensics, log analysis, malware triage, and chain of custody with a practical Python forensics script and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Incident Response Triage Automation

Practical Exercise - Incident Response Triage Automation
#!/usr/bin/env python3
"""
Incident Response Triage Script
Collects volatile and non-volatile forensic artifacts from a live system.
Run ASAP after incident detection - volatile data (RAM, connections) is lost on reboot.
"""
import subprocess, json, hashlib, datetime, platform, socket, os
from pathlib import Path
from collections import defaultdict

CASE_DIR = Path(f'IR_case_{datetime.datetime.now().strftime("%Y%m%d_%H%M%S")}')
CASE_DIR.mkdir()

def run_cmd(cmd: list[str]) -> str:
    try:
        return subprocess.check_output(cmd, stderr=subprocess.DEVNULL, text=True)
    except Exception as e:
        return f'ERROR: {e}'

def collect_volatile_data() -> dict:
    """Volatile data: MUST collect before any remediation action or reboot."""
    data = {
        'timestamp': datetime.datetime.utcnow().isoformat() + 'Z',
        'hostname': socket.gethostname(),
        'os': platform.platform(),
    }

    if platform.system() == 'Linux':
        # Network connections - who is the host talking to?
        data['netstat'] = run_cmd(['ss', '-tulpn'])
        # Running processes - any suspicious names, paths, or parent processes?
        data['processes'] = run_cmd(['ps', 'auxf'])
        # Logged in users
        data['who'] = run_cmd(['who'])
        # Recent logins
        data['last'] = run_cmd(['last', '-n', '20'])
        # Scheduled tasks - common persistence mechanism
        data['crontabs'] = run_cmd(['cat', '/etc/crontab'])
        # Loaded kernel modules - rootkit detection
        data['lsmod'] = run_cmd(['lsmod'])
        # Open files - find C2 connections or suspicious file handles
        data['lsof_net'] = run_cmd(['lsof', '-i', '-n', '-P'])

    json.dump(data, open(CASE_DIR / 'volatile.json', 'w'), indent=2)
    print(f'✓ Volatile data collected: {CASE_DIR / "volatile.json"}')
    return data

def collect_logs() -> dict:
    """Parse system logs for indicators of compromise."""
    log_findings = defaultdict(list)

    # Auth log: failed SSH, sudo usage, su attempts
    auth_log_paths = ['/var/log/auth.log', '/var/log/secure']
    for log_path in auth_log_paths:
        if Path(log_path).exists():
            with open(log_path) as f:
                for line in f:
                    if 'Failed password' in line or 'Invalid user' in line:
                        log_findings['failed_ssh'].append(line.strip())
                    if 'sudo' in line and 'COMMAND' in line:
                        log_findings['sudo_usage'].append(line.strip())
                    if 'Accepted publickey' in line or 'Accepted password' in line:
                        log_findings['successful_auth'].append(line.strip())

    # Summarize SSH brute force
    from collections import Counter
    import re
    if log_findings['failed_ssh']:
        ips = Counter(re.findall(r'from (\S+)', '\n'.join(log_findings['failed_ssh'])))
        print(f'\n🚨 Top SSH brute-force IPs:')
        for ip, count in ips.most_common(5):
            print(f'   {ip}: {count} failures')

    json.dump(dict(log_findings), open(CASE_DIR / 'log_findings.json', 'w'), indent=2)
    return dict(log_findings)

def hash_suspicious_files(paths: list[str]) -> dict:
    """Hash files for malware analysis and threat intel lookup."""
    hashes = {}
    for path_str in paths:
        path = Path(path_str)
        if path.exists() and path.is_file():
            sha256 = hashlib.sha256()
            md5    = hashlib.md5()
            with open(path, 'rb') as f:
                for chunk in iter(lambda: f.read(8192), b''):
                    sha256.update(chunk)
                    md5.update(chunk)
            hashes[str(path)] = {
                'sha256': sha256.hexdigest(),
                'md5': md5.hexdigest(),
                'size': path.stat().st_size,
                'modified': datetime.datetime.fromtimestamp(path.stat().st_mtime).isoformat(),
            }
            print(f'  {path.name}: SHA256={sha256.hexdigest()[:16]}...')
            # In practice: submit to VirusTotal API
            # https://www.virustotal.com/vtapi/v2/file/report?apikey=KEY&resource=SHA256

    json.dump(hashes, open(CASE_DIR / 'file_hashes.json', 'w'), indent=2)
    return hashes

def create_timeline():
    """Generate chronological timeline of events for analysis."""
    print(f'\n=== IR Case Timeline ===')
    print(f'Case directory: {CASE_DIR}')
    print(f'Evidence files:')
    for f in sorted(CASE_DIR.iterdir()):
        print(f'  {f.name} ({f.stat().st_size} bytes)')

# Run triage
print('=== Incident Response Triage ===')
volatile = collect_volatile_data()
logs = collect_logs()
# Hash suspicious binaries found during investigation
hash_suspicious_files(['/usr/bin/wget', '/tmp/suspicious.sh'])
create_timeline()

print(f'\n✅ Triage complete. Evidence preserved in: {CASE_DIR}')
print('Next steps: memory dump (avml), disk image (dd/dcfldd), SIEM correlation')

Module Quiz

Module Quiz
Question 1 of 5

What are the 6 phases of the NIST Incident Response lifecycle?

Tip

Tip

Practice Practice Quiz Incident Response Forensics in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Incident Response Forensics from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz Incident Response Forensics is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done