Skip to content

fjm1995/EmailSecurity

Repository files navigation

AI-Powered Email Security Validator

A next-generation Python CLI and web tool that validates email security records (SPF, DKIM, DMARC) using advanced AI threat intelligence and machine learning algorithms. This tool goes beyond basic validation to provide intelligent threat analysis, industry-specific recommendations, and attack likelihood predictions.

Why This Tool Exists

The Email Security Crisis

Email remains the primary attack vector in cybersecurity:

  • 91% of cyber attacks begin with a phishing email
  • Email spoofing enables attackers to impersonate trusted domains
  • Business Email Compromise (BEC) causes $43 billion in losses annually
  • Poor email authentication affects legitimate business communications and brand reputation

The AI-Powered Solution

This tool revolutionizes email security validation by combining traditional DNS analysis with artificial intelligence:

  1. SPF (Sender Policy Framework) - AI detects suspicious includes and policy bypass attempts
  2. DKIM (DomainKeys Identified Mail) - Machine learning identifies weak cryptography and deprecated algorithms
  3. DMARC (Domain-based Message Authentication) - Advanced pattern recognition spots evasion techniques
  4. AI Threat Intelligence - Predictive analysis for attack likelihood and threat assessment

Key Differentiators

AI-Powered Features

  • Threat Intelligence Analysis - Identifies potential security threats using pattern recognition
  • Attack Likelihood Predictions - Calculates probability of email spoofing, phishing, and BEC attacks
  • Industry-Specific Benchmarking - Tailored recommendations for different sectors
  • Intelligent Recommendations - AI-generated, prioritized action items with implementation timelines
  • Security Grading - Letter grades (A+ to F) based on comprehensive analysis
  • Domain Risk Assessment - Evaluates domain characteristics for potential impersonation

Technical Excellence

  • Docker Containerization - Easy deployment with Docker and Docker Compose
  • Modern Web Interface - Responsive design with real-time AI analysis
  • Comprehensive CLI - Full-featured command-line interface with AI options
  • JSON Export - Structured reporting for integration and documentation
  • Health Monitoring - Built-in health checks for production deployment

Quick Start with Docker

Prerequisites

  • Docker and Docker Compose installed
  • Internet connection for DNS lookups
  • OpenAI API key (optional, for AI features)

Launch with Docker Compose

# Clone the repository
git clone <repository-url>
cd EmailSecurity

# Start the application
docker-compose up -d

# Access the web interface
open http://localhost:5000

Enabling AI Features (Optional)

To enable AI-powered analysis and recommendations:

# Set your OpenAI API key
export OPENAI_API_KEY=your_openai_api_key_here

# Start with AI features enabled
docker-compose up -d

# Or run locally with AI
python email_security_validator.py example.com --ai

Note: AI features are completely optional. The tool works fully without an OpenAI API key, providing comprehensive email security validation. AI features enhance the analysis with:

  • Advanced threat intelligence
  • Industry-specific recommendations
  • Attack likelihood predictions
  • Enhanced security insights

Build and Run Manually

# Build the Docker image
docker build -t email-security-validator .

# Run the container
docker run -p 5000:5000 email-security-validator

# Access the application
open http://localhost:5000

Installation (Local Development)

Prerequisites

  • Python 3.7 or higher
  • pip package manager

Install Dependencies

pip install -r requirements.txt

Usage

Web Interface (Recommended)

Start the web server:

python web_interface.py

Then open your browser to http://localhost:5000 to access the AI-powered web interface.

Features:

  • Standard validation mode for basic analysis
  • AI Analysis mode for comprehensive threat intelligence
  • Industry selection for benchmarking
  • Real-time results with visual security scoring
  • Interactive threat intelligence display

Command Line Interface

Basic Validation

python email_security_validator.py example.com

AI-Powered Analysis

python email_security_validator.py example.com --ai --industry financial

Export Results

python email_security_validator.py example.com --ai --export json

Full Command Options

python email_security_validator.py --help
usage: email_security_validator.py [-h] [--export {json}] [--verbose] [--ai] 
                                   [--industry {financial,healthcare,government,education,retail,technology}] 
                                   domain

Email Security Validator - Check SPF, DKIM, and DMARC records

positional arguments:
  domain                Domain to validate

optional arguments:
  -h, --help            show this help message and exit
  --export {json}       Export results to file
  --verbose, -v         Verbose output
  --ai                  Enable AI-powered analysis and recommendations
  --industry            Industry type for benchmarking (default: default)

Examples:
  python email_security_validator.py example.com
  python email_security_validator.py example.com --ai --industry financial
  python email_security_validator.py example.com --ai --export json

AI Analysis Examples

CLI Output - AI-Powered Analysis

Email Security Validator
Comprehensive SPF, DKIM, and DMARC Analysis

Analyzing email security for: example-bank.com
============================================================

Checking SPF record...
Checking DMARC record...
Checking DKIM configuration...

SECURITY ASSESSMENT SUMMARY
============================================================

[SECURE] SPF Record - Score: 95/100
   Record: v=spf1 include:_spf.google.com include:mailgun.org -all
   Suggestions:
   • Excellent SPF configuration with strict policy

[SECURE] DMARC Record - Score: 100/100
   Record: v=DMARC1; p=reject; rua=mailto:dmarc@example-bank.com; sp=reject
   
[SECURE] DKIM Record - Score: 100/100
   Record: Found 2 DKIM record(s): default, google

OVERALL SECURITY SCORE: 98/100
[SECURE] Excellent email security posture!

AI-POWERED SECURITY ANALYSIS
============================================================

THREAT INTELLIGENCE:
[MEDIUM] authentication_weakness: Domain uses strong authentication but could benefit from additional DKIM selectors
   Confidence: 75%
   Mitigation: Consider implementing multiple DKIM selectors for redundancy

AI RECOMMENDATIONS:
1. [MEDIUM] Implement Additional Email Security Measures
   Consider implementing advanced email security protocols
   Impact: Enhanced brand protection and security visibility
   Time: 2-4 weeks

2. [LOW] DKIM Selector Redundancy
   Add backup DKIM selectors for improved resilience
   Impact: Improved email authentication reliability
   Time: 1-2 days

ATTACK LIKELIHOOD PREDICTIONS:
Email Spoofing: 5% (low)
Phishing Attacks: 8% (low)
Business Email Compromise: 3% (low)

SECURITY GRADE: A+
Industry Benchmark: 90/100
Compliance Status: ✓ Compliant

Web Interface Features

The AI-powered web interface provides:

  • Dual Analysis Modes: Standard and AI-powered validation
  • Industry Selection: Tailored benchmarking for different sectors
  • Visual Threat Intelligence: Color-coded threat levels and confidence scores
  • Interactive Recommendations: Prioritized action items with implementation details
  • Attack Predictions: Real-time risk assessment with visual indicators
  • Security Grading: Letter grades with industry compliance status
  • Responsive Design: Works seamlessly on desktop and mobile devices

AI Threat Intelligence

Threat Detection Capabilities

The AI engine analyzes multiple threat vectors:

SPF Threats:

  • Suspicious include domains (malicious TLDs, Tor domains)
  • Policy bypass attempts (+all mechanisms)
  • DNS lookup abuse (>10 lookups)
  • Deprecated mechanisms (ptr:)

DKIM Threats:

  • Weak cryptographic keys (<2048 bits)
  • Deprecated algorithms (SHA-1)
  • Testing mode in production
  • Invalid key formats

DMARC Threats:

  • Policy evasion techniques (pct=0, sp=none)
  • Missing enforcement policies
  • Incomplete reporting configuration
  • Subdomain policy gaps

Cross-Protocol Analysis:

  • Domain impersonation patterns
  • Authentication consistency issues
  • Brand protection vulnerabilities

Industry Benchmarking

AI recommendations are tailored to industry standards:

  • Financial Services: 90+ score required, strict DMARC reject policy
  • Healthcare: 85+ score required, DMARC reject policy
  • Government: 95+ score required, maximum security protocols
  • Education: 80+ score required, DMARC quarantine minimum
  • Retail: 85+ score required, customer protection focus
  • Technology: 90+ score required, advanced security measures

Attack Likelihood Predictions

The AI engine calculates attack probabilities using weighted algorithms:

  • Email Spoofing: Based on SPF (40%) + DMARC (40%) + Domain Risk (20%)
  • Phishing Attacks: Based on DMARC (50%) + SPF (30%) + Domain Risk (20%)
  • Business Email Compromise: Based on DMARC (60%) + SPF (20%) + DKIM (20%)

Risk levels are categorized as: Critical (80%+), High (60-79%), Medium (40-59%), Low (<40%)

Docker Deployment

Production Deployment

version: '3.8'

services:
  email-security-validator:
    build: .
    ports:
      - "5000:5000"
    environment:
      - FLASK_ENV=production
      - FLASK_HOST=0.0.0.0
      - FLASK_PORT=5000
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:5000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    command: redis-server --appendonly yes
    volumes:
      - redis_data:/data

volumes:
  redis_data:

Health Monitoring

The application includes built-in health checks:

# Check application health
curl http://localhost:5000/health

# Response
{
  "status": "healthy",
  "service": "email-security-validator"
}

Scaling and Load Balancing

For high-traffic deployments:

# Scale the application
docker-compose up -d --scale email-security-validator=3

# Use with nginx load balancer
# Configure nginx upstream for load balancing

API Endpoints

Standard Validation

POST /validate
Content-Type: application/json

{
  "domain": "example.com"
}

AI-Powered Validation

POST /validate-ai
Content-Type: application/json

{
  "domain": "example.com",
  "industry": "financial"
}

Health Check

GET /health

Security Context

Why Email Security Matters

  1. Brand Protection - Prevent attackers from impersonating your domain
  2. Customer Trust - Protect customers from phishing attacks using your brand
  3. Email Deliverability - Improve inbox placement rates and sender reputation
  4. Regulatory Compliance - Meet industry requirements for email security
  5. Business Continuity - Prevent email-based attacks that disrupt operations
  6. Financial Protection - Avoid costs associated with email security breaches

Attack Scenarios Prevented

  • Email Spoofing - Attackers sending emails that appear to come from your domain
  • Phishing Campaigns - Malicious emails targeting your customers or employees
  • Business Email Compromise - Attackers impersonating executives or vendors
  • Domain Reputation Damage - Your domain being blacklisted due to abuse
  • Brand Impersonation - Criminals using similar domains to deceive victims

Implementation Best Practices

  1. Start with Monitoring - Begin with p=none DMARC policy to gather data
  2. Gradual Enforcement - Move to p=quarantine then p=reject over time
  3. Monitor AI Reports - Regularly review threat intelligence and recommendations
  4. Industry Compliance - Follow sector-specific security requirements
  5. Continuous Improvement - Use AI insights for ongoing security enhancement

Use Cases

For Security Teams

  • Comprehensive Audits - AI-powered assessment of email security posture
  • Threat Intelligence - Advanced threat detection and risk analysis
  • Compliance Reporting - Industry-specific compliance validation
  • Incident Response - Rapid identification of email security gaps

For IT Administrators

  • Domain Migration - Verify email security during domain transfers
  • Email Deliverability - Troubleshoot delivery issues with AI insights
  • Vendor Assessment - Evaluate third-party email security configurations
  • Continuous Monitoring - Automated security posture assessment

For Developers

  • CI/CD Integration - Automate email security checks in deployment pipelines
  • API Integration - Programmatic access to AI-powered validation
  • Custom Dashboards - Build security monitoring dashboards
  • Automated Reporting - Generate regular security assessments

For Compliance Officers

  • Regulatory Compliance - Industry-specific security validation
  • Risk Assessment - Quantified risk analysis with AI predictions
  • Audit Documentation - Comprehensive security reports
  • Policy Enforcement - Validate email security policy implementation

Advanced Features

JSON Export Format

AI-enhanced reports include comprehensive data:

{
  "domain": "example.com",
  "analysis_timestamp": "2024-01-15T10:30:45.123456",
  "overall_security_score": 95,
  "industry_benchmark": 90,
  "security_grade": "A",
  "threat_intelligence": [
    {
      "threat_level": "medium",
      "threat_type": "authentication_weakness",
      "description": "Missing DKIM reduces email authentication strength",
      "confidence_score": 0.75,
      "mitigation_steps": ["Implement DKIM signing", "Generate 2048-bit RSA keys"]
    }
  ],
  "ai_recommendations": [
    {
      "priority": "high",
      "category": "dmarc",
      "title": "DMARC Policy Implementation",
      "description": "DMARC policy needs implementation or strengthening",
      "expected_impact": "Provides policy enforcement and visibility",
      "time_to_implement": "2-4 weeks",
      "confidence_score": 0.92
    }
  ],
  "attack_likelihood_predictions": {
    "email_spoofing": {
      "likelihood": 0.15,
      "risk_level": "low",
      "factors": ["SPF configuration", "DMARC policy", "Domain reputation"]
    }
  },
  "compliance_status": {
    "industry_compliant": true,
    "required_dmarc_policy": "reject",
    "current_dmarc_policy": "reject"
  }
}

Performance Optimization

  • DNS Caching - Intelligent caching for repeated domain checks
  • Parallel Processing - Concurrent validation of multiple protocols
  • Rate Limiting - Built-in protection against DNS abuse
  • Error Handling - Robust error recovery and reporting

Monitoring and Alerting

  • Health Checks - Built-in application health monitoring
  • Performance Metrics - Response time and success rate tracking
  • Error Logging - Comprehensive error tracking and analysis
  • Security Monitoring - Detection of unusual usage patterns

Contributing

We welcome contributions to enhance the AI capabilities and security features!

Development Setup

  1. Clone the repository
  2. Install dependencies: pip install -r requirements.txt
  3. Run tests: python -m pytest (when available)
  4. Follow PEP 8 style guidelines
  5. Submit pull requests with detailed descriptions

AI Model Enhancement

  • Contribute threat patterns and indicators
  • Improve attack likelihood algorithms
  • Add new industry benchmarks
  • Enhance recommendation engines

License

This project is open source and available under the MIT License.

Support and Documentation

Getting Help

  1. Check the troubleshooting section below
  2. Review the comprehensive documentation
  3. Submit issues with detailed information
  4. Join our community discussions

Troubleshooting

DNS Resolution Errors

Error: DNS lookup failed: [Errno -2] Name or service not known
  • Verify the domain name is correct
  • Check your internet connection
  • Ensure Docker container has network access

Docker Issues

docker: Error response from daemon: port is already allocated
  • Stop existing containers: docker-compose down
  • Check port usage: netstat -tulpn | grep :5000
  • Modify port in docker-compose.yml if needed

AI Analysis Errors

AI validation failed: module 'ai_analyzer' has no attribute
  • Ensure all dependencies are installed
  • Verify Python version compatibility (3.7+)
  • Check AI analyzer module integrity

Performance Issues

  • DNS lookups may take several seconds for complex configurations
  • Use --verbose flag for detailed timing information
  • Consider implementing Redis caching for production use
  • Monitor container resource usage

Production Considerations

  • Resource Requirements: 512MB RAM minimum, 1GB recommended
  • Network Access: Requires outbound DNS access (port 53)
  • Security: Run as non-root user (implemented in Docker)
  • Monitoring: Use health checks and log monitoring
  • Backup: Export critical configurations and reports

Future Enhancements

Planned AI Features

  • Machine Learning Models - Enhanced threat detection with trained models
  • Real-time Threat Feeds - Integration with live threat intelligence
  • Behavioral Analysis - Pattern recognition for anomaly detection
  • Predictive Analytics - Advanced forecasting of security trends

Additional Protocols

  • BIMI (Brand Indicators for Message Identification) - Visual brand verification
  • MTA-STS (Mail Transfer Agent Strict Transport Security) - Transport encryption
  • TLS-RPT (TLS Reporting) - Transport security reporting
  • ARC (Authenticated Received Chain) - Email forwarding authentication

Integration Capabilities

  • SIEM Integration - Security Information and Event Management
  • API Gateway - Enterprise API management
  • Webhook Support - Real-time notifications and alerts
  • Dashboard Analytics - Advanced reporting and visualization

Project Structure

EmailSecurity/
├── email_security_validator.py    # Main CLI application with AI features
├── ai_analyzer.py                 # AI threat intelligence engine
├── web_interface.py               # Flask web application with AI endpoints
├── requirements.txt               # Python dependencies
├── Dockerfile                     # Container configuration
├── docker-compose.yml             # Multi-service deployment
├── README.md                     # This comprehensive documentation
└── templates/
    └── index.html                # AI-powered web interface

Powered by AI for Next-Generation Email Security

Transform your email security posture with intelligent threat analysis, predictive risk assessment, and industry-leading recommendations. Deploy in minutes with Docker, scale with confidence, and protect your organization with AI-powered insights.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors