Threat Intelligence & Detection

YARA Rules for Detecting Phishing Email Campaigns

Published 16 Sep 2026
11 min read
YARA Rules for Detecting Phishing Email Campaigns

Phishing remains one of the prime threats facing organizations, with ENISA classifying it among the top categories in its threat landscape analysis [1]. Building YARA rules for detecting phishing email campaigns gives your security team a pattern-matching engine that catches what signature-based gateways miss. This approach turns threat intelligence into executable detection logic you can version-control, peer-review, and deploy across your email pipeline. In this article, you will learn how to write, test, and operationalize YARA rules that target real phishing patterns. Whether you run a SOC, lead an incident response team, or are building your first detection rule, you will walk away with a reusable workflow for email threat detection.


Table of Contents

  1. What Is YARA for Email Analysis?
  2. Why Phishing Signature Rules Matter for Security Teams
  3. How to Build YARA Rules for Malicious Email Detection Step by Step
  4. Template: Phishing YARA Rule Skeleton
  5. Best Practices
  6. Tools Comparison
  7. Real-World Example (Illustrative Scenario)
  8. Common Pitfalls in Email Threat Detection
  9. FAQ
  10. Next Steps

What Is YARA for Email Analysis?

YARA is a pattern-matching tool originally designed for malware research. You write rules that describe text strings, byte patterns, or conditions, and YARA scans files to report matches. When applied to email security, YARA rules inspect message bodies, headers, and MIME-decoded attachments for indicators that characterize phishing campaigns.

In practice, this means you feed raw .eml files or extracted attachments into YARA, and it tells you which rules matched — functioning as a lightweight, customizable classification layer between your mail gateway and your analyst queue.

MITRE ATT&CK catalogues phishing under technique T1566 (Phishing), with sub-techniques T1566.001 (Spearphishing Attachment) and T1566.002 (Spearphishing Link) [2]. Your YARA rules map directly to these sub-techniques: one set targets attachment-borne payloads, another targets URL patterns in message bodies.

Why Phishing Signature Rules Matter for Security Teams

Commercial email gateways rely on vendor-curated signatures and reputation feeds. When a new campaign launches — often using fresh domains and polymorphic lure documents — there is a detection gap until the vendor updates. Custom phishing signature rules close that gap because you write detection logic from your own threat intelligence within hours, sometimes minutes.

CIS Controls v8.1 reinforces this approach: Control 9 (Email and Web Browser Protections) calls for technical controls on email security, while Control 13 (Network Monitoring and Defense) calls for operating processes to detect threats through monitoring and analysis [3]. YARA-based email scanning satisfies both by providing an automated, auditable detection mechanism.


How to Build YARA Rules for Malicious Email Detection Step by Step

Prerequisites and Setup

You need three things before writing your first rule:

Component Purpose Where to get it
YARA compiler (yarac) Validates and compiles rules Official YARA documentation on GitHub
Sample corpus Benign and malicious .eml files for testing Your quarantine, abuse mailbox, or public phishing feeds
Text editor with YARA syntax support Highlights strings and conditions VS Code with a YARA extension, or Vim with syntax files

Install YARA following the project's official build instructions. Confirm the installation by compiling a minimal rule against a test file.

Step 1 — Collect Campaign Indicators

Pull indicators from your most recent phishing reports: sender domains, subject-line patterns, embedded URLs, attachment hashes, and distinctive HTML or macro fragments. Group them by campaign. A single campaign typically shares at least two to three stable textual indicators — these become your YARA strings.

Step 2 — Write the Detection Rule

Start with a focused rule that targets one campaign's characteristics. The rule below detects a credential-harvesting phishing lure that impersonates a document-sharing notification and includes a suspicious URL pattern:

rule Phishing_DocShare_Lure : phishing credential_harvest
{
    meta:
        author      = "SOC Team"
        description = "Detects credential-harvesting phishing lure impersonating document-sharing services"
        date        = "2025-06-15"
        reference   = "internal case #4812"
        mitre_att   = "T1566.002"

    strings:
        $subject1   = "You have a new shared document" ascii nocase
        $subject2   = "Action required: review document" ascii nocase
        $url_pattern = /https?:\/\/[a-z0-9\-]{4,30}\.(click|top|xyz|buzz)\/[a-z0-9]{8,}/ ascii nocase
        $urgency1   = "expires in 24 hours" ascii nocase
        $urgency2   = "immediate action required" ascii nocase
        $brand1     = "OneDrive" ascii nocase
        $brand2     = "SharePoint" ascii nocase

    condition:
        any of ($subject*) and
        $url_pattern and
        any of ($urgency*) and
        any of ($brand*)
}

This rule requires a match across four indicator categories — subject line, URL pattern, urgency language, and brand impersonation — which keeps false positives low while catching variations of the same campaign.

Step 3 — Validate and Test

Compile the rule to catch syntax errors, then scan your sample corpus. Measure two metrics:

Metric Target How to measure
True-positive rate Matches confirmed phishing samples from the target campaign Scan your quarantine samples
False-positive rate Fewer than one false hit per thousand benign messages Scan a representative benign corpus

Tune strings and conditions iteratively. Broadening a regex catches more variants but increases false-positive risk — this is the fundamental trade-off in phishing detection rule writing.

Step 4 — Deploy to Your Email Pipeline

Integrate YARA scanning at one or more points in your mail flow. Common integration points include the post-gateway quarantine inspection, the abuse-mailbox triage automation, and the attachment sandbox pre-analysis stage. Configure your SOAR or automation platform to call YARA against incoming .eml files and route matches to the analyst queue with the rule name and matched strings attached.

Four-step YARA phishing rule build workflow: Collect Indicators, Write Rule, Validate & Test, Deploy to Pipeline, glassmorphism style
This infographic visualizes the four-step process for building YARA rules for phishing email detection as described in the article. Each step is displayed as a frosted glass card with a clean icon and concise label, arranged in a horizontal numbered flow with arrows. Key actions and targets from each step are called out beneath each card.

Template: Phishing YARA Rule Skeleton

Use this skeleton as a starting point for every new phishing campaign rule. Replace the placeholder values with your campaign-specific indicators, then compile and test before deployment.

Field Placeholder Guidance
rule name Phishing_<CampaignName>_<Variant> Use snake_case; include the campaign family name
meta: author "Your Team Name" Identifies the rule owner for review cycles
meta: mitre_att "T1566.001" or "T1566.002" Map to the correct ATT&CK sub-technique
$subject* strings Campaign-specific subject lines Use ascii nocase; add 2-3 variants
$url_pattern Regex matching campaign domain pattern Keep the TLD list short to limit false positives
$payload* strings Macro keywords, JS snippets, or file magic bytes Target the attachment type the campaign uses
condition Combine categories with and Require matches from at least 3 indicator categories

How to adapt it: Start by filling in the $subject* strings from your latest abuse-mailbox samples. Add the $url_pattern regex based on the domain registration pattern you observe. If the campaign uses attachments, add $payload* strings targeting macro calls or embedded scripts. Adjust the condition to require the combination that produces zero false positives against your benign corpus before promoting the rule to production.


Best Practices

Version-control your rules. Store YARA rules in a Git repository. Tag each rule with the campaign identifier, creation date, and the analyst who wrote it. Peer-review rule changes through pull requests — the same workflow you use for detection-as-code with Sigma rules.

Namespace by campaign family. Group rules into files by threat actor or campaign type. This makes bulk enable/disable straightforward when a campaign goes dormant.

Set metadata fields consistently. Include author, description, date, reference, and mitre_att in the meta section of every rule. This metadata feeds your detection coverage dashboard and supports the CSF 2.0 category DE.AE (Adverse Event Analysis) by linking detections to adversary techniques [4].

Combine YARA with header analysis. YARA excels at content matching but does not natively parse SMTP headers. Pair it with SPF, DKIM, and DMARC validation in your mail pipeline so authentication failures and content matches reinforce each other.

Schedule rule reviews. Phishing campaigns evolve. Review your active rule set monthly. Archive rules that have not matched in 90 days — they add scanning overhead without detection value.


Tools Comparison

Tool Role in Email Pipeline YARA Integration Strengths
YARA (standalone) Rule compilation, ad-hoc scanning Native Full control, scriptable, lightweight
Elastic Security SIEM correlation, alert management Supports YARA via integration modules Correlates YARA matches with log telemetry
TheHive + Cortex Incident response case management Cortex analyzers call YARA on observables Automates triage, links matches to cases
ClamAV Mail gateway antivirus scanning Loads YARA rules as a signature format Integrates directly with MTAs (Postfix, Sendmail)
Wazuh Host-based detection and response Active-response module triggers YARA scans Combines file-integrity monitoring with YARA

In practice, this means most teams do not choose one tool exclusively. A typical deployment uses ClamAV or a commercial gateway for inline scanning and a SIEM such as Elastic Security for post-delivery correlation.

Comparison table of five tools for YARA-based phishing email detection including YARA standalone, Elastic, TheHive, ClamAV, Wazuh, glassmorphism
This infographic presents a structured comparison of five tools used in YARA-based phishing email detection pipelines, drawn directly from the article's tools comparison section. Displayed as a five-row frosted glass table with columns for tool name, pipeline role, YARA integration method, and key strength. The layout helps security teams quickly evaluate which tools fit their environment.

Real-World Example (Illustrative Scenario)

⚠️ Disclaimer: The following scenario is an illustrative example based on typical industry patterns. The specific metrics are hypothetical estimates designed to demonstrate realistic outcomes, not measured data from a documented project. They should not be cited as factual benchmarks.

Context: A mid-sized financial services firm with a five-person SOC receives approximately 200 user-reported phishing emails per week. Analysts manually inspect each report, averaging twelve minutes per message.

Challenge: A sustained credential-harvesting campaign impersonating the firm's document-sharing platform evaded the commercial email gateway for several days before analysts identified the pattern. Manual triage created a backlog that delayed response to other security events.

Solution: The SOC wrote three YARA rules targeting the campaign's subject-line patterns, URL structure, and HTML form elements. They integrated the rules into their abuse-mailbox automation using Cortex analyzers, enabling automatic classification of incoming reports. Rules were stored in Git with mandatory peer review.

Results (illustrative estimates):

  • Automated pre-triage classification of phishing reports reduced manual analysis time by roughly 65% (illustrative)
  • Mean time from campaign launch to first detection rule deployment dropped to under four hours (illustrative)
  • False-positive rate held below one report per five hundred scanned messages (illustrative)

Key Takeaways: Writing targeted YARA rules and integrating them into an automated triage pipeline frees analyst capacity for higher-value investigation. Peer review and version control reduce the risk of deploying a rule that floods the queue with false positives.


Common Pitfalls in Email Threat Detection

1. Writing rules that are too broad. A rule matching a single common word like "invoice" without additional conditions triggers on legitimate business email. Require matches across multiple indicator categories in your condition block.

2. Neglecting case sensitivity. Phishing lures vary capitalization. Omitting nocase on string definitions causes missed detections on mixed-case variants like "URGENT: Review Document."

3. Skipping the benign corpus test. If you test only against known-malicious samples, you have no visibility into your false-positive rate. Scan at least a thousand representative benign messages before promoting a rule to production.

4. Ignoring rule maintenance. Deploying rules without a review cycle means your rule set accumulates stale entries. Stale rules increase scan time and can match on legitimate content that happens to reuse patterns from retired campaigns.

5. Hardcoding IOCs instead of patterns. Embedding a specific domain or hash catches exactly one variant. Prefer regex patterns that capture the campaign's domain-generation or URL structure logic — this detects the next wave, not just the current one.

6. Scanning only attachments. Many credential-harvesting campaigns carry no attachment. Their payload is a URL embedded in the HTML body. Ensure your pipeline scans the full .eml file, not just extracted attachments.


Next Steps

  1. Export your last ten confirmed phishing cases from your abuse mailbox and extract shared textual indicators (subject patterns, URL structures, HTML snippets).
  2. Write your first campaign-specific rule using the skeleton template above. Compile it, scan your benign corpus, and measure the false-positive rate.
  3. Integrate YARA scanning into your abuse-mailbox triage automation. Start with a "tag and alert" mode before enabling automated quarantine.
  4. Map your rules to MITRE ATT&CK sub-techniques T1566.001 and T1566.002 [2] and update your detection coverage dashboard.
  5. Schedule a monthly rule review — archive dormant rules, tune active ones against the latest campaign samples, and document changes in your Git repository.

Sources

[1] ENISA, "ENISA Threat Landscape 2025," European Union Agency for Cybersecurity, 2025. [Online]. Available: https://www.enisa.europa.eu/publications/enisa-threat-landscape-2025

[2] MITRE, "T1566 Phishing," MITRE ATT&CK. [Online]. Available: https://attack.mitre.org/

[3] Center for Internet Security, "CIS Critical Security Controls Version 8.1," 2024. [Online]. Available: https://www.cisecurity.org/controls/v8-1

[4] S. Rose, O. Borchert, S. Mitchell, and S. Connelly, "The NIST Cybersecurity Framework (CSF) 2.0," NIST CSWP 29, National Institute of Standards and Technology, 2024. [Online]. Available: https://csrc.nist.gov/pubs/cswp/29/the-nist-cybersecurity-framework-csf-20/final

[5] NIST, "Guide to Cyber Threat Information Sharing," NIST Special Publication 800-150, National Institute of Standards and Technology, 2016. [Online]. Available: https://csrc.nist.gov/pubs/sp/800/150/final

FAQ

How do YARA rules detect phishing emails? +

YARA rules define string patterns and logical conditions that describe phishing characteristics — subject lines, URL structures, urgency phrases, brand impersonation terms, or malicious macro code. When an email file matches the condition, YARA flags it for analyst review or automated quarantine.

Is detecting phishing with YARA effective against zero-day campaigns? +

YARA detects pattern-based indicators, so it is most effective when you can extract at least two to three stable textual features from early campaign samples. Against a genuinely novel campaign with no shared indicators to prior activity, YARA alone may not trigger until an analyst identifies the first samples and writes a rule. Combining YARA with behavioral analysis and URL reputation improves coverage.

How does YARA fit into email security alongside gateway products? +

YARA complements — rather than replaces — your email gateway. Gateways handle volume-based filtering, reputation checks, and SPF/DKIM/DMARC validation. YARA adds a customizable content-inspection layer for campaigns that bypass those controls. NIST SP 800-150 encourages sharing structured threat information across the organization to improve detection [5], and YARA rules are an effective vehicle for operationalizing that shared intelligence.

What is the best approach to phishing campaign YARA detection at scale? +

Organize rules by campaign family, store them in version control, and deploy them through automation (SOAR playbook or Cortex analyzer). Monitor match rates and false-positive rates weekly. Retire rules that no longer match active campaigns, and prioritize rules for campaigns targeting your industry or your organization's brand.

Can YARA rules replace dedicated phishing signature rules in a SIEM? +

YARA and SIEM detection rules (such as Sigma rules) serve different layers. YARA inspects file content at the binary and text level. SIEM rules correlate log events — authentication failures, mail-flow metadata, endpoint telemetry. Use both: YARA for content-level malicious email detection, and Sigma for behavioral correlation across your log sources.