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.
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
This tool revolutionizes email security validation by combining traditional DNS analysis with artificial intelligence:
- SPF (Sender Policy Framework) - AI detects suspicious includes and policy bypass attempts
- DKIM (DomainKeys Identified Mail) - Machine learning identifies weak cryptography and deprecated algorithms
- DMARC (Domain-based Message Authentication) - Advanced pattern recognition spots evasion techniques
- AI Threat Intelligence - Predictive analysis for attack likelihood and threat assessment
- 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
- 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
- Docker and Docker Compose installed
- Internet connection for DNS lookups
- OpenAI API key (optional, for AI features)
# Clone the repository
git clone <repository-url>
cd EmailSecurity
# Start the application
docker-compose up -d
# Access the web interface
open http://localhost:5000To 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 --aiNote: 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 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- Python 3.7 or higher
- pip package manager
pip install -r requirements.txtStart the web server:
python web_interface.pyThen 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
python email_security_validator.py example.compython email_security_validator.py example.com --ai --industry financialpython email_security_validator.py example.com --ai --export jsonpython email_security_validator.py --helpusage: 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
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
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
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
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
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%)
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:The application includes built-in health checks:
# Check application health
curl http://localhost:5000/health
# Response
{
"status": "healthy",
"service": "email-security-validator"
}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 balancingPOST /validate
Content-Type: application/json
{
"domain": "example.com"
}POST /validate-ai
Content-Type: application/json
{
"domain": "example.com",
"industry": "financial"
}GET /health- Brand Protection - Prevent attackers from impersonating your domain
- Customer Trust - Protect customers from phishing attacks using your brand
- Email Deliverability - Improve inbox placement rates and sender reputation
- Regulatory Compliance - Meet industry requirements for email security
- Business Continuity - Prevent email-based attacks that disrupt operations
- Financial Protection - Avoid costs associated with email security breaches
- 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
- Start with Monitoring - Begin with
p=noneDMARC policy to gather data - Gradual Enforcement - Move to
p=quarantinethenp=rejectover time - Monitor AI Reports - Regularly review threat intelligence and recommendations
- Industry Compliance - Follow sector-specific security requirements
- Continuous Improvement - Use AI insights for ongoing security enhancement
- 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
- 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
- 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
- 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
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"
}
}- 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
- 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
We welcome contributions to enhance the AI capabilities and security features!
- Clone the repository
- Install dependencies:
pip install -r requirements.txt - Run tests:
python -m pytest(when available) - Follow PEP 8 style guidelines
- Submit pull requests with detailed descriptions
- Contribute threat patterns and indicators
- Improve attack likelihood algorithms
- Add new industry benchmarks
- Enhance recommendation engines
This project is open source and available under the MIT License.
- Check the troubleshooting section below
- Review the comprehensive documentation
- Submit issues with detailed information
- Join our community discussions
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
--verboseflag for detailed timing information - Consider implementing Redis caching for production use
- Monitor container resource usage
- 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
- 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
- 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
- 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
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.