phishing defense

Implementing Google Workspace Phishing Protection

Configure Google Workspace advanced phishing and malware protection settings including pre-delivery scanning, attachment protection, spoofing detection, and Enhanced Safe Browsing.

admin-consoleanti-spoofingemail-securitygmailgoogle-workspacephishingsafe-browsing
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Google Workspace provides advanced phishing and malware protection through the Admin Console under Apps > Google Workspace > Gmail > Safety. Key features include Enhanced Pre-Delivery Scanning that examines messages more thoroughly before they reach inboxes, attachment and link protection that scans for malware and checks against known malicious sites, and spoofing detection for domain and employee name impersonation. Google's Advanced Protection Program (APP) provides the strongest account security for high-privilege users.

When to Use

  • When deploying or configuring implementing google workspace phishing protection capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Google Workspace Business Standard or higher license
  • Gmail Settings administrator privilege
  • Understanding of organizational email flow and third-party integrations
  • Access to Google Admin Console (admin.google.com)
  • DNS management access for SPF, DKIM, DMARC configuration

Workflow

Step 1: Configure Advanced Phishing Protection

  • Navigate to Admin Console > Apps > Google Workspace > Gmail > Safety
  • Enable "Protect against domain spoofing based on similar domain names"
  • Enable "Protect against spoofing of employee names"
  • Enable "Protect against inbound emails spoofing your domain"
  • Set action for detected spoofing: quarantine or move to spam with warning banner
  • Apply settings to all organizational units or specific high-risk groups

Step 2: Enable Enhanced Pre-Delivery Scanning

  • In Safety settings, enable "Enhanced pre-delivery message scanning"
  • This adds additional delay (seconds) to scan messages more thoroughly
  • Configure to detect phishing attempts that evade initial filters
  • Enable "Identify links behind shortened URLs"
  • Enable "Scan linked images" for image-based phishing detection

Step 3: Configure Attachment Protection

  • Enable "Protect against encrypted attachments from untrusted senders"
  • Enable "Protect against attachments with scripts from untrusted senders"
  • Enable "Protect against anomalous attachment types in emails"
  • Configure action: warn users, move to spam, or quarantine
  • Create exceptions for known legitimate encrypted file senders

Step 4: Enable Enhanced Safe Browsing

  • Navigate to Admin Console > Security > Gmail Enhanced Safe Browsing
  • Enable Enhanced Safe Browsing for the organization (off by default)
  • This provides real-time protection against phishing URLs in emails
  • Configure at organizational unit level for phased rollout
  • Monitor user feedback for false positive impact

Step 5: Enroll High-Risk Users in Advanced Protection Program

  • Identify high-privilege accounts: super admins, executives, finance leadership
  • Enroll users in Google's Advanced Protection Program (APP)
  • APP requires FIDO2 security keys for authentication
  • APP blocks third-party app access unless explicitly approved
  • APP provides enhanced scanning for Gmail and Drive downloads

Step 6: Configure Email Authentication

  • Publish SPF record: v=spf1 include:_spf.google.com ~all
  • Enable DKIM signing in Admin Console > Apps > Google Workspace > Gmail > Authenticate email
  • Configure DMARC with monitoring: v=DMARC1; p=none; rua=mailto:dmarc@company.com
  • Progress DMARC to enforcement per organizational readiness

Tools & Resources

  • Google Admin Console: Central management for all security settings
  • Google Workspace Security Investigation Tool: Threat analysis and response
  • Google Security Center: Security health recommendations and dashboard
  • Gmail Security Sandbox: Attachment detonation for enterprise licenses
  • Google Advanced Protection Program: Strongest account security

Validation

  • Spoofing protection blocks test email with lookalike domain
  • Pre-delivery scanning catches test phishing with delayed weaponization
  • Attachment protection warns on test encrypted attachment
  • Enhanced Safe Browsing blocks known phishing URL clicked in email
  • APP-enrolled accounts reject non-FIDO2 authentication attempts
  • SPF, DKIM, DMARC all pass for outbound messages
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.8 KB

API Reference: Implementing Google Workspace Phishing Protection

Admin Console Path

Admin Console > Apps > Google Workspace > Gmail > Safety

Gmail Safety Controls

Control Category Severity if Missing
Protect against similar domain spoofing Spoofing HIGH
Protect against employee name spoofing Spoofing HIGH
Protect against inbound domain spoofing Spoofing CRITICAL
Enhanced pre-delivery scanning Scanning HIGH
Attachment protection (encrypted/scripts) Attachments HIGH
Identify links behind shortened URLs Links MEDIUM
Show warning for unauthenticated email Warnings MEDIUM
Enhanced Safe Browsing Browsing HIGH

Admin SDK Directory API (GAM)

# List Gmail settings
gam print gmailsettings domain example.com
# List users with Advanced Protection
gam print users query "isAdvancedProtectionProgram=true"

Google Workspace Alert Center API

from google.oauth2 import service_account
from googleapiclient.discovery import build
creds = service_account.Credentials.from_service_account_file("sa.json",
    scopes=["https://www.googleapis.com/auth/apps.alerts"])
service = build("alertcenter", "v1beta1", credentials=creds)
alerts = service.alerts().list().execute()

Recommended Actions for Spoofing

Detection Action
Similar domain spoofing Quarantine
Employee name spoofing Show warning + move to spam
Inbound domain spoofing Quarantine
Unauthenticated email Show warning banner

References

standards.md1.3 KB

Standards & References: Google Workspace Phishing Protection

Google Workspace Security Settings Path

  • Admin Console > Apps > Google Workspace > Gmail > Safety
  • Admin Console > Security > Gmail Enhanced Safe Browsing
  • Admin Console > Apps > Google Workspace > Gmail > Authenticate email

MITRE ATT&CK References

  • T1566.001: Phishing: Spearphishing Attachment
  • T1566.002: Phishing: Spearphishing Link
  • T1656: Impersonation
  • T1586.002: Compromise Accounts: Email Accounts

Key Protection Settings

Setting Location Default Recommended
Domain spoofing protection Safety Off On - Quarantine
Employee name spoofing Safety Off On - Warning
Pre-delivery scanning Safety On On (enhanced)
Attachment protection Safety Partial Full - all options
Enhanced Safe Browsing Security Off On
Gmail Security Sandbox Safety Off On (Enterprise)

Google Workspace License Requirements

Feature Business Starter Business Standard Enterprise
Basic phishing protection Yes Yes Yes
Enhanced pre-delivery scanning Yes Yes Yes
Gmail Security Sandbox No No Yes
Security Investigation Tool No Partial Yes
Advanced Protection Program Yes Yes Yes
workflows.md1.4 KB

Workflows: Google Workspace Phishing Protection

Workflow 1: Gmail Inbound Protection Pipeline

Inbound email arrives at Gmail
  |
  v
[Connection-level checks]
  +-- IP reputation
  +-- SPF validation
  +-- DKIM verification
  +-- DMARC evaluation
  |
  v
[Enhanced Pre-Delivery Scanning]
  +-- Content analysis for phishing indicators
  +-- URL expansion (shortened URLs)
  +-- Image scanning for embedded phishing
  +-- NLP analysis for social engineering
  |
  v
[Attachment Protection]
  +-- File type analysis
  +-- Script detection in attachments
  +-- Encrypted attachment from untrusted sender check
  +-- Security Sandbox detonation (Enterprise)
  |
  v
[Spoofing Detection]
  +-- Domain name similarity check
  +-- Employee name impersonation check
  +-- Internal domain spoofing check
  |
  v
[Delivery decision]
  +-- DELIVER: Clean message to inbox
  +-- WARN: Deliver with yellow warning banner
  +-- SPAM: Route to spam folder
  +-- QUARANTINE: Hold for admin review
  +-- REJECT: Block delivery entirely

Workflow 2: Safe Browsing URL Protection

User clicks URL in Gmail
  |
  v
[Enhanced Safe Browsing check]
  +-- Real-time URL reputation lookup
  +-- Check against known phishing database
  +-- Dynamic page analysis
  |
  v
[Decision]
  +-- SAFE: Allow navigation
  +-- DANGEROUS: Display full-page warning
  +-- SUSPICIOUS: Display interstitial warning

Scripts 2

agent.py7.6 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for auditing Google Workspace phishing and malware protection settings."""

import json
import argparse
import subprocess
from datetime import datetime
from collections import Counter


def gam_command(args_list):
    """Run a GAM (Google Apps Manager) command."""
    cmd = ["gam"] + args_list
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    return result.stdout.strip(), result.stderr.strip(), result.returncode


def get_gmail_safety_settings(domain):
    """Retrieve Gmail safety settings via Admin SDK (simulated via GAM)."""
    stdout, stderr, rc = gam_command(["print", "gmailsettings", "domain", domain])
    if rc != 0:
        return {"error": stderr}
    return {"raw_settings": stdout}


def audit_phishing_protection(config_path):
    """Audit Google Workspace phishing protection configuration."""
    with open(config_path) as f:
        config = json.load(f)
    findings = []
    safety = config.get("gmail_safety", config.get("safety_settings", {}))

    checks = {
        "spoofing_similar_domains": {
            "key": "protect_against_similar_domain_spoofing",
            "description": "Protect against domain spoofing (similar names)",
            "severity": "HIGH",
        },
        "employee_name_spoofing": {
            "key": "protect_against_employee_name_spoofing",
            "description": "Protect against employee name spoofing",
            "severity": "HIGH",
        },
        "inbound_domain_spoofing": {
            "key": "protect_against_inbound_domain_spoofing",
            "description": "Protect against inbound domain spoofing",
            "severity": "CRITICAL",
        },
        "enhanced_pre_delivery_scanning": {
            "key": "enhanced_pre_delivery_scanning",
            "description": "Enhanced pre-delivery message scanning",
            "severity": "HIGH",
        },
        "attachment_protection": {
            "key": "attachment_protection_enabled",
            "description": "Attachment protection (encrypted/scripts)",
            "severity": "HIGH",
        },
        "links_and_external_images": {
            "key": "identify_links_behind_shortened_urls",
            "description": "Identify links behind shortened URLs",
            "severity": "MEDIUM",
        },
        "unauthenticated_email_warning": {
            "key": "show_warning_for_unauthenticated_email",
            "description": "Show warning for unauthenticated emails",
            "severity": "MEDIUM",
        },
        "safe_browsing_enhanced": {
            "key": "enhanced_safe_browsing",
            "description": "Enhanced Safe Browsing enabled",
            "severity": "HIGH",
        },
    }

    for check_name, check_info in checks.items():
        enabled = safety.get(check_info["key"], False)
        findings.append({
            "control": check_info["description"],
            "enabled": enabled,
            "status": "COMPLIANT" if enabled else "NON_COMPLIANT",
            "severity": "INFO" if enabled else check_info["severity"],
        })

    quarantine = safety.get("quarantine_action", "")
    if quarantine not in ("quarantine", "reject"):
        findings.append({
            "control": "Quarantine action for detected threats",
            "current": quarantine or "not configured",
            "status": "NON_COMPLIANT",
            "severity": "HIGH",
            "recommendation": "Set action to quarantine or reject",
        })

    return findings


def audit_dmarc_alignment(dmarc_report_path):
    """Analyze DMARC aggregate report for alignment issues."""
    with open(dmarc_report_path) as f:
        report = json.load(f)
    records = report if isinstance(report, list) else report.get("records", [])
    total = len(records)
    aligned = sum(1 for r in records if r.get("dkim_aligned") and r.get("spf_aligned"))
    failures = [r for r in records if not r.get("dkim_aligned") or not r.get("spf_aligned")]
    return {
        "total_records": total,
        "aligned": aligned,
        "alignment_rate": round(aligned / total * 100, 1) if total else 0,
        "top_failures": failures[:10],
    }


def analyze_phishing_incidents(incident_log_path):
    """Analyze phishing incident log for patterns."""
    with open(incident_log_path) as f:
        incidents = json.load(f)
    items = incidents if isinstance(incidents, list) else incidents.get("incidents", [])
    by_type = Counter(i.get("type", "unknown") for i in items)
    by_action = Counter(i.get("action_taken", "unknown") for i in items)
    clicked = sum(1 for i in items if i.get("user_clicked", False))
    reported = sum(1 for i in items if i.get("user_reported", False))
    return {
        "total_incidents": len(items),
        "by_type": dict(by_type),
        "by_action": dict(by_action),
        "click_rate": round(clicked / len(items) * 100, 1) if items else 0,
        "report_rate": round(reported / len(items) * 100, 1) if items else 0,
    }


def generate_recommended_settings():
    """Generate recommended Google Workspace phishing protection settings."""
    return {
        "gmail_safety": {
            "protect_against_similar_domain_spoofing": True,
            "protect_against_employee_name_spoofing": True,
            "protect_against_inbound_domain_spoofing": True,
            "enhanced_pre_delivery_scanning": True,
            "attachment_protection_enabled": True,
            "identify_links_behind_shortened_urls": True,
            "scan_linked_images": True,
            "show_warning_for_unauthenticated_email": True,
            "enhanced_safe_browsing": True,
            "quarantine_action": "quarantine",
            "move_to_spam_on_spoofing": True,
        },
        "advanced_protection_program": {
            "enabled_for_high_privilege_users": True,
            "target_groups": ["executives", "finance", "it-admins"],
        },
    }


def main():
    parser = argparse.ArgumentParser(description="Google Workspace Phishing Protection Agent")
    parser.add_argument("--config", help="Workspace safety config JSON to audit")
    parser.add_argument("--dmarc-report", help="DMARC aggregate report JSON")
    parser.add_argument("--incidents", help="Phishing incident log JSON")
    parser.add_argument("--action", choices=["audit", "dmarc", "incidents",
                                              "recommend", "full"], default="full")
    parser.add_argument("--output", default="gws_phishing_report.json")
    args = parser.parse_args()

    report = {"generated_at": datetime.utcnow().isoformat(), "results": {}}

    if args.action in ("audit", "full") and args.config:
        findings = audit_phishing_protection(args.config)
        report["results"]["audit"] = findings
        non_comp = sum(1 for f in findings if f.get("status") == "NON_COMPLIANT")
        print(f"[+] Audit: {len(findings)} controls, {non_comp} non-compliant")

    if args.action in ("dmarc", "full") and args.dmarc_report:
        result = audit_dmarc_alignment(args.dmarc_report)
        report["results"]["dmarc"] = result
        print(f"[+] DMARC alignment: {result['alignment_rate']}%")

    if args.action in ("incidents", "full") and args.incidents:
        result = analyze_phishing_incidents(args.incidents)
        report["results"]["incidents"] = result
        print(f"[+] Incidents: {result['total_incidents']}, click rate: {result['click_rate']}%")

    if args.action in ("recommend", "full"):
        settings = generate_recommended_settings()
        report["results"]["recommended"] = settings
        print("[+] Recommended settings generated")

    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    print(f"[+] Report saved to {args.output}")


if __name__ == "__main__":
    main()
process.py7.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Google Workspace Phishing Protection Auditor

Audits Google Workspace Gmail safety settings configuration
and generates compliance recommendations.

Usage:
    python process.py audit --config-file gws_config.json
    python process.py check-auth --domain example.com
"""

import argparse
import json
import sys
from dataclasses import dataclass, field, asdict

try:
    import dns.resolver
    HAS_DNS = True
except ImportError:
    HAS_DNS = False


@dataclass
class GWSSecurityAudit:
    """Google Workspace security configuration audit."""
    domain: str = ""
    spoofing_protection: bool = False
    employee_name_spoofing: bool = False
    enhanced_predelivery: bool = False
    attachment_protection: dict = field(default_factory=dict)
    enhanced_safe_browsing: bool = False
    security_sandbox: bool = False
    app_enrolled_users: int = 0
    spf_configured: bool = False
    dkim_configured: bool = False
    dmarc_configured: bool = False
    dmarc_policy: str = ""
    score: int = 0
    max_score: int = 100
    findings: list = field(default_factory=list)
    recommendations: list = field(default_factory=list)


def audit_gws_config(config: dict) -> GWSSecurityAudit:
    """Audit Google Workspace Gmail safety configuration."""
    audit = GWSSecurityAudit()
    audit.domain = config.get("domain", "")

    safety = config.get("safety_settings", {})

    # Spoofing protection
    audit.spoofing_protection = safety.get("domain_spoofing_protection", False)
    if audit.spoofing_protection:
        audit.score += 15
    else:
        audit.findings.append("Domain spoofing protection not enabled")
        audit.recommendations.append(
            "Enable 'Protect against domain spoofing based on similar domain names'"
        )

    audit.employee_name_spoofing = safety.get("employee_name_spoofing", False)
    if audit.employee_name_spoofing:
        audit.score += 10
    else:
        audit.findings.append("Employee name spoofing protection not enabled")
        audit.recommendations.append(
            "Enable 'Protect against spoofing of employee names'"
        )

    # Pre-delivery scanning
    audit.enhanced_predelivery = safety.get("enhanced_predelivery_scanning", False)
    if audit.enhanced_predelivery:
        audit.score += 15
    else:
        audit.findings.append("Enhanced pre-delivery scanning not enabled")

    # Attachment protection
    att = safety.get("attachment_protection", {})
    audit.attachment_protection = att
    att_score = 0
    if att.get("encrypted_attachments", False):
        att_score += 5
    if att.get("script_attachments", False):
        att_score += 5
    if att.get("anomalous_types", False):
        att_score += 5
    audit.score += att_score
    if att_score < 15:
        audit.findings.append("Not all attachment protection options enabled")

    # Enhanced Safe Browsing
    audit.enhanced_safe_browsing = safety.get("enhanced_safe_browsing", False)
    if audit.enhanced_safe_browsing:
        audit.score += 10
    else:
        audit.findings.append("Enhanced Safe Browsing not enabled (off by default)")
        audit.recommendations.append(
            "Enable Enhanced Safe Browsing in Admin Console > Security"
        )

    # Security Sandbox
    audit.security_sandbox = safety.get("security_sandbox", False)
    if audit.security_sandbox:
        audit.score += 10
    else:
        audit.findings.append("Gmail Security Sandbox not enabled (requires Enterprise license)")

    # Advanced Protection Program
    audit.app_enrolled_users = config.get("app_enrolled_users", 0)
    if audit.app_enrolled_users > 0:
        audit.score += 10
    else:
        audit.recommendations.append(
            "Enroll super admins and executives in Advanced Protection Program"
        )

    # Authentication
    auth = config.get("authentication", {})
    audit.spf_configured = auth.get("spf", False)
    audit.dkim_configured = auth.get("dkim", False)
    audit.dmarc_configured = auth.get("dmarc", False)
    audit.dmarc_policy = auth.get("dmarc_policy", "none")

    if audit.spf_configured:
        audit.score += 5
    if audit.dkim_configured:
        audit.score += 5
    if audit.dmarc_configured:
        audit.score += 5
        if audit.dmarc_policy == "reject":
            audit.score += 10
        elif audit.dmarc_policy == "quarantine":
            audit.score += 5

    return audit


def check_google_auth(domain: str) -> dict:
    """Check SPF, DKIM, DMARC for Google Workspace domain."""
    result = {"domain": domain, "spf": False, "dkim": False, "dmarc": False, "issues": []}

    if not HAS_DNS:
        result["issues"].append("dnspython not installed")
        return result

    # SPF
    try:
        answers = dns.resolver.resolve(domain, 'TXT')
        for rdata in answers:
            txt = str(rdata).strip('"')
            if 'v=spf1' in txt and '_spf.google.com' in txt:
                result["spf"] = True
                break
        if not result["spf"]:
            result["issues"].append("SPF does not include _spf.google.com")
    except Exception:
        result["issues"].append("No SPF record found")

    # DKIM (Google default selector)
    try:
        dns.resolver.resolve(f"google._domainkey.{domain}", 'TXT')
        result["dkim"] = True
    except Exception:
        result["issues"].append("DKIM not configured for 'google' selector")

    # DMARC
    try:
        answers = dns.resolver.resolve(f"_dmarc.{domain}", 'TXT')
        for rdata in answers:
            txt = str(rdata).strip('"')
            if 'v=DMARC1' in txt:
                result["dmarc"] = True
                import re
                policy = re.search(r'p=(\w+)', txt)
                result["dmarc_policy"] = policy.group(1) if policy else "unknown"
                break
    except Exception:
        result["issues"].append("No DMARC record found")

    return result


def main():
    parser = argparse.ArgumentParser(description="Google Workspace Phishing Protection Auditor")
    subparsers = parser.add_subparsers(dest="command")

    audit_parser = subparsers.add_parser("audit", help="Audit GWS security config")
    audit_parser.add_argument("--config-file", required=True)

    auth_parser = subparsers.add_parser("check-auth", help="Check email authentication")
    auth_parser.add_argument("--domain", required=True)

    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    if args.command == "audit":
        with open(args.config_file) as f:
            config = json.load(f)
        result = audit_gws_config(config)
        if args.json:
            print(json.dumps(asdict(result), indent=2))
        else:
            print(f"Security Score: {result.score}/{result.max_score}")
            if result.findings:
                print(f"\nFindings ({len(result.findings)}):")
                for i, f_item in enumerate(result.findings, 1):
                    print(f"  {i}. {f_item}")
            if result.recommendations:
                print(f"\nRecommendations ({len(result.recommendations)}):")
                for i, rec in enumerate(result.recommendations, 1):
                    print(f"  {i}. {rec}")

    elif args.command == "check-auth":
        result = check_google_auth(args.domain)
        print(json.dumps(result, indent=2))

    else:
        parser.print_help()


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 0.8 KB
Keep exploring