Lesson 09 Social Engineering & Phishing with AI
Theme:

Theory

Reading time: ~20 minutes  ·  Social engineering fundamentals, phishing anatomy, AI-assisted attacks, and defensive awareness

LEGAL WARNING — READ BEFORE PROCEEDING: Social engineering attacks against individuals or organizations without explicit written authorization are illegal in virtually every jurisdiction. Unauthorized phishing, pretexting, vishing, and related techniques violate laws including the Computer Fraud and Abuse Act (US), the Computer Misuse Act (UK), and equivalent statutes worldwide. Penalties include criminal prosecution, imprisonment, and civil liability. The material in this lesson is provided strictly for authorized security testing, red team engagements with signed rules of engagement, and security awareness training. If you do not have written authorization from the target organization, do not proceed. You are solely responsible for ensuring your activities comply with all applicable laws.

1. Why Social Engineering Still Works

Despite billions spent on firewalls, intrusion detection systems, and endpoint protection, the most reliable attack vector remains the human being. Social engineering exploits the predictable patterns of human psychology rather than software vulnerabilities. A perfectly patched system is still compromised when a privileged user hands over their credentials voluntarily.

The reason is straightforward: humans are wired to trust, cooperate, and respond to authority. These traits are evolutionary advantages in social life but become exploitable weaknesses in a security context. Attackers do not need to find a zero-day when they can simply ask someone for access and receive it.

Studies consistently show that social engineering is involved in the majority of successful breaches. Verizon's annual Data Breach Investigations Report attributes a significant share of incidents to phishing and pretexting. The human element is not a bug in the system — it is the system.

2. Cialdini's Six Principles of Influence

Robert Cialdini's research on persuasion identified six principles that explain why people comply with requests. Every social engineering attack leverages one or more of these principles.

2.1 Reciprocity

People feel obligated to return favors. An attacker who provides something first — a helpful document, a small gift, technical assistance — creates a psychological debt. The target feels compelled to reciprocate, often by complying with a subsequent request they would otherwise refuse.

2.2 Commitment and Consistency

Once someone commits to a position or action, they feel pressure to behave consistently with that commitment. An attacker who gets a target to agree to a small, harmless request can escalate to larger requests. The target's desire to appear consistent overrides their suspicion.

2.3 Social Proof

People look to others' behavior to determine what is correct. Phishing emails that claim "Your colleagues have already completed this security update" exploit social proof. If everyone else is doing it, it must be legitimate.

2.4 Authority

People defer to perceived authority figures. An email appearing to come from the CEO, the IT department, or a law enforcement agency triggers automatic compliance. The target does not question the request because they believe they are not in a position to question authority.

2.5 Liking

People are more likely to comply with requests from people they like. Attackers build rapport, find common interests, use flattery, and mirror the target's communication style. In spear-phishing, personalized messages that reference the target's hobbies or recent activities exploit the liking principle.

2.6 Scarcity

People assign more value to things that are scarce or time-limited. Urgency is the most common trigger in phishing: "Your account will be locked in 24 hours," "Act now to claim your prize," "Immediate action required." Scarcity short-circuits rational analysis and drives impulsive action.

3. Types of Social Engineering Attacks

3.1 Phishing

Mass-distributed emails impersonating legitimate entities (banks, service providers, internal IT). Phishing casts a wide net, relying on volume to catch a small percentage of targets. The messages are generic but convincing enough to fool inattentive recipients.

3.2 Spear-Phishing

Targeted phishing aimed at specific individuals or organizations. The attacker researches the target, customizes the message, and references real people, projects, or events. Spear-phishing has a dramatically higher success rate than generic phishing because the personalization makes the message appear legitimate.

3.3 Vishing (Voice Phishing)

Phone-based social engineering. The attacker impersonates technical support, a bank representative, or a government official. Voice communication adds urgency and makes it harder for the target to verify claims. Caller ID spoofing makes the call appear to originate from a legitimate number.

3.4 Smishing (SMS Phishing)

Phishing via text messages. SMS messages have extremely high open rates compared to email, and the small screen makes it difficult to inspect URLs. Messages typically impersonate delivery services, banks, or two-factor authentication systems.

3.5 Pretexting

Creating a fabricated scenario (pretext) to extract information. The attacker assumes a false identity — a vendor, auditor, new employee, or IT contractor — and uses the pretext to justify their requests. Pretexting often involves multiple interactions over time to build trust before the actual extraction.

3.6 Baiting

Leaving infected physical media (USB drives, CDs) or enticing digital downloads in locations where targets will find them. Curiosity drives the target to plug in the device or open the file, executing the attacker's payload.

4. Anatomy of a Phishing Attack

A well-crafted phishing campaign has several distinct components, each designed to bypass both technical controls and human judgment.

4.1 Sender Spoofing

SMTP does not inherently verify sender identity. Attackers forge the From: header to display a trusted sender address. Without proper SPF, DKIM, and DMARC records, receiving mail servers cannot distinguish spoofed messages from legitimate ones.

4.2 Lookalike Domains

Attackers register domains that visually resemble legitimate ones: g00gle.com, microso1t.com, arnazon.com. Internationalized domain names (IDN) enable homograph attacks using characters from different scripts that appear identical to Latin letters (e.g., Cyrillic "a" vs. Latin "a").

4.3 Urgency Triggers

The message creates time pressure: account suspension, security breach, payment deadline. Urgency engages the amygdala (fight-or-flight) and suppresses the prefrontal cortex (rational analysis). The target acts before they think.

4.4 Credential Harvesting

The phishing link directs to a cloned login page that captures credentials. Modern phishing kits include real-time proxy capabilities (e.g., Evilginx, Modlishka) that intercept session tokens and bypass multi-factor authentication.

5. AI-Assisted Social Engineering

Large language models have fundamentally changed the social engineering landscape. Tasks that previously required significant manual effort can now be partially automated and dramatically improved in quality.

5.1 Crafting Convincing Pretexts

LLMs can generate grammatically perfect, contextually appropriate messages in any language. The telltale signs of traditional phishing — poor grammar, awkward phrasing, generic greetings — are eliminated. An attacker can prompt an LLM to write a message in the exact tone and style of a specific organization's communications.

5.2 Personalizing at Scale

Given OSINT data about a target (LinkedIn profile, social media posts, published articles), an LLM can generate highly personalized spear-phishing messages for thousands of targets simultaneously. What previously required hours of manual research per target can be reduced to seconds.

5.3 Analyzing Target Profiles

LLMs can process large volumes of publicly available information about a target and identify the most effective attack angles: their interests, professional concerns, communication patterns, and likely psychological vulnerabilities.

5.4 Multilingual Attacks

Traditional phishing campaigns were limited by the attacker's language skills. LLMs enable fluent, culturally appropriate messages in any language, expanding the potential target population globally.

Ethical Boundary: While understanding these capabilities is essential for defense, using AI to craft actual phishing attacks without authorization is illegal. Red team engagements must have signed authorization, defined scope, and agreed-upon rules of engagement before any AI-assisted social engineering techniques are employed.

6. Technical Indicators of Phishing

Defenders must understand the technical artifacts that distinguish phishing from legitimate email. Email authentication protocols are the first line of defense.

6.1 Email Header Analysis

Email headers contain a wealth of forensic information. The following Python script parses key headers from a raw email message.

import email
from email import policy

def analyze_email_headers(raw_email: str) -> dict:
    """Parse and analyze email headers for phishing indicators."""
    msg = email.message_from_string(raw_email, policy=policy.default)

    analysis = {
        "from": msg["From"],
        "reply_to": msg["Reply-To"],
        "return_path": msg["Return-Path"],
        "received_chain": [],
        "authentication_results": msg["Authentication-Results"],
        "spf_result": None,
        "dkim_result": None,
        "dmarc_result": None,
    }

    # Extract the Received chain (bottom-up = oldest first)
    for header in msg.get_all("Received", []):
        analysis["received_chain"].append(header.strip())

    # Parse Authentication-Results for SPF, DKIM, DMARC
    auth = analysis["authentication_results"] or ""
    for line in auth.split(";"):
        line = line.strip().lower()
        if line.startswith("spf="):
            analysis["spf_result"] = line
        elif line.startswith("dkim="):
            analysis["dkim_result"] = line
        elif line.startswith("dmarc="):
            analysis["dmarc_result"] = line

    # Flag mismatches between From and Return-Path
    if analysis["return_path"] and analysis["from"]:
        from_domain = analysis["from"].split("@")[-1].rstrip(">")
        return_domain = analysis["return_path"].split("@")[-1].rstrip(">")
        analysis["domain_mismatch"] = from_domain.lower() != return_domain.lower()

    return analysis

6.2 SPF Record Checking

Sender Policy Framework (SPF) records specify which mail servers are authorized to send email for a domain. Checking SPF records helps determine whether a sender is legitimate.

import dns.resolver

def check_spf_record(domain: str) -> dict:
    """Query and analyze SPF record for a domain."""
    result = {"domain": domain, "spf_record": None, "mechanisms": [], "policy": None}

    try:
        answers = dns.resolver.resolve(domain, "TXT")
        for rdata in answers:
            txt = rdata.to_text().strip('"')
            if txt.startswith("v=spf1"):
                result["spf_record"] = txt
                parts = txt.split()
                for part in parts[1:]:
                    if part in ("-all", "~all", "?all", "+all"):
                        result["policy"] = part
                    else:
                        result["mechanisms"].append(part)
                break
    except dns.resolver.NoAnswer:
        result["error"] = "No TXT records found"
    except dns.resolver.NXDOMAIN:
        result["error"] = "Domain does not exist"

    return result

# Example usage
spf = check_spf_record("example.com")
print(f"SPF Record: {spf['spf_record']}")
print(f"Policy: {spf['policy']}")
# -all = hard fail (reject), ~all = soft fail (mark), ?all = neutral

6.3 DKIM and DMARC

DKIM (DomainKeys Identified Mail) adds a cryptographic signature to outgoing messages. The receiving server verifies the signature against the public key published in the sender's DNS. A failed DKIM check indicates the message was modified in transit or the sender is not authorized.

DMARC (Domain-based Message Authentication, Reporting & Conformance) ties SPF and DKIM together and specifies what to do when both fail: none (monitor), quarantine (spam folder), or reject (drop the message). Checking the DMARC record reveals the domain owner's enforcement posture.

def check_dmarc_record(domain: str) -> dict:
    """Query DMARC record for a domain."""
    dmarc_domain = f"_dmarc.{domain}"
    result = {"domain": domain, "dmarc_record": None, "policy": None}

    try:
        answers = dns.resolver.resolve(dmarc_domain, "TXT")
        for rdata in answers:
            txt = rdata.to_text().strip('"')
            if txt.startswith("v=DMARC1"):
                result["dmarc_record"] = txt
                for tag in txt.split(";"):
                    tag = tag.strip()
                    if tag.startswith("p="):
                        result["policy"] = tag.split("=")[1]
                break
    except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
        result["error"] = "No DMARC record found — domain is vulnerable to spoofing"

    return result

7. GoPhish: Authorized Phishing Simulations

GoPhish is an open-source phishing simulation framework used by security teams to test organizational resilience against phishing attacks. It provides campaign management, email templating, landing page cloning, and detailed reporting.

7.1 Key Capabilities

7.2 Typical Workflow

  1. Obtain written authorization from organizational leadership
  2. Define the scope: which departments, which employees, what types of simulated attacks
  3. Configure the GoPhish server and sending profile (SMTP relay)
  4. Create email templates that reflect realistic threat scenarios
  5. Build landing pages that capture interaction data without storing real credentials
  6. Launch the campaign and monitor results
  7. Analyze results and deliver awareness training based on findings
# Download and run GoPhish (Linux/macOS)
wget https://github.com/gophish/gophish/releases/latest/download/gophish-v0.12.1-linux-64bit.zip
unzip gophish-v0.12.1-linux-64bit.zip -d gophish
cd gophish

# Edit config.json to set listen URL and admin credentials
# Default admin interface: https://127.0.0.1:3333
# Default phishing server: http://0.0.0.0:80

./gophish

7.3 GoPhish API Integration

GoPhish exposes a REST API that enables programmatic campaign management. This is useful for integrating phishing simulations into automated security testing pipelines.

import requests

GOPHISH_API = "https://localhost:3333/api"
API_KEY = "your-api-key-here"
HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

def get_campaign_results(campaign_id: int) -> dict:
    """Retrieve results for a GoPhish campaign."""
    resp = requests.get(
        f"{GOPHISH_API}/campaigns/{campaign_id}/results",
        headers=HEADERS,
        verify=False,  # self-signed cert in lab environments
    )
    resp.raise_for_status()
    data = resp.json()

    summary = {
        "total_targets": len(data.get("results", [])),
        "emails_sent": 0,
        "emails_opened": 0,
        "links_clicked": 0,
        "credentials_submitted": 0,
    }

    for r in data.get("results", []):
        status = r.get("status", "")
        if status in ("Sending", "Sent", "Email Opened", "Clicked Link", "Submitted Data"):
            summary["emails_sent"] += 1
        if status in ("Email Opened", "Clicked Link", "Submitted Data"):
            summary["emails_opened"] += 1
        if status in ("Clicked Link", "Submitted Data"):
            summary["links_clicked"] += 1
        if status == "Submitted Data":
            summary["credentials_submitted"] += 1

    return summary

8. Defense Awareness: Recognizing Social Engineering

The most effective defense against social engineering is a trained, skeptical workforce. Technical controls reduce exposure, but human judgment is the final barrier.

8.1 Red Flags to Watch For

8.2 Verification Procedures

9. Summary

Social engineering remains the most effective attack vector because it targets the one component that cannot be patched: human psychology. Understanding Cialdini's principles of influence, the mechanics of phishing, and the capabilities of AI-assisted attacks is essential for both red team operators and defenders.

Key takeaways:

Download Files

These files contain synthetic data for the social engineering challenges. All files are plain text (.txt) and safe to open.