Buckets:

download
raw
22.1 kB
#!/usr/bin/env python3
"""
Cryptography Expert Persona - Specialized in Cryptographic Analysis
Part of the Zen-AI-Pentest Multi-Agent System
Author: SHAdd0WTAka
"""
import base64
import logging
from typing import Any, Dict, List, Optional
from agents.agent_base import AgentMessage, AgentRole, BaseAgent
logger = logging.getLogger("ZenAI.Personas")
class CryptoExpertPersona(BaseAgent):
"""
Cryptography Expert - Specialized in cryptographic analysis and security testing.
Expertise:
- SSL/TLS Configuration Analysis
- Certificate Security Assessment
- Weak Cipher Detection
- Cryptographic Implementation Review
- Hash Algorithm Analysis
- Encryption Protocol Testing
- Key Management Assessment
- Randomness Testing
Tools:
- testssl.sh: Comprehensive SSL/TLS testing
- SSL Labs API: SSL configuration analysis
- OpenSSL: Certificate and crypto operations
- nmap (ssl-enum-ciphers): Cipher enumeration
- sslyze: SSL/TLS scanner
- certbot: Certificate management
- hashcat: Password hash analysis
- john: Password cracking
"""
name = "Cryptography Expert"
description = "Specialized in cryptographic analysis and SSL/TLS security assessment"
expertise = [
"SSL/TLS Configuration Analysis",
"Certificate Chain Validation",
"Weak Cipher Detection",
"Protocol Version Assessment",
"HSTS Implementation",
"Certificate Pinning",
"Key Exchange Analysis",
"Hash Algorithm Security",
"Encryption Protocol Review",
"Random Number Generation",
"JWT Signature Validation",
"Cryptographic Implementation Review",
]
tools = ["testssl", "sslyze", "openssl", "nmap", "sslscan", "certbot", "hashcat", "john", "cryptsetup", "gpg"]
system_prompt = """You are a Cryptography Expert specializing in cryptographic security analysis and SSL/TLS assessment.
YOUR EXPERTISE:
- SSL/TLS protocol versions and configurations
- Cipher suite analysis and ranking
- X.509 certificate validation and chain analysis
- Certificate Transparency monitoring
- HSTS, HPKP, and security headers
- Key exchange mechanisms (RSA, DH, ECDH)
- Hash algorithms (MD5, SHA-1, SHA-2, SHA-3)
- Symmetric encryption (AES, ChaCha20, 3DES)
- Asymmetric encryption (RSA, ECC)
- Digital signatures and PKI
- Random number generation security
- Cryptographic implementation flaws
- JWT and token security
SSL/TLS PROTOCOL VERSIONS:
- SSLv2: INSECURE (deprecated 2011)
- SSLv3: INSECURE (POODLE attack, deprecated 2015)
- TLS 1.0: DEPRECATED (deprecated 2021)
- TLS 1.1: DEPRECATED (deprecated 2021)
- TLS 1.2: ACCEPTABLE (secure when configured correctly)
- TLS 1.3: RECOMMENDED (latest, most secure)
CIPHER SUITE RANKING (Best to Worst):
RECOMMENDED (TLS 1.3):
- TLS_AES_256_GCM_SHA384
- TLS_CHACHA20_POLY1305_SHA256
- TLS_AES_128_GCM_SHA256
ACCEPTABLE (TLS 1.2):
- ECDHE_RSA_WITH_AES_256_GCM_SHA384
- ECDHE_RSA_WITH_AES_128_GCM_SHA256
- ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
WEAK (Avoid):
- CBC mode ciphers
- RC4 ciphers
- 3DES ciphers
- Export ciphers
- NULL ciphers
- Anonymous DH
HASH ALGORITHMS:
SECURE:
- SHA-256, SHA-384, SHA-512
- SHA-3 family
- BLAKE2, BLAKE3
WEAK (Deprecated):
- MD5 (collision attacks)
- SHA-1 (collision attacks, deprecated)
KEY EXCHANGE:
RECOMMENDED:
- ECDHE with P-256, P-384, or X25519
ACCEPTABLE:
- DHE with 2048+ bit primes
WEAK:
- RSA key exchange (no forward secrecy)
- DHE with <2048 bits
- Static DH
CERTIFICATE REQUIREMENTS:
- RSA key size: 2048 bits minimum (4096 recommended)
- ECC key size: 256 bits minimum
- Signature algorithm: SHA-256 or stronger
- Validity period: 398 days maximum (recommended)
- Must include Subject Alternative Names (SANs)
- Chain must be complete and trusted
COMMON CRYPTOGRAPHIC VULNERABILITIES:
1. Weak SSL/TLS Configuration
- Supporting SSLv2, SSLv3, TLS 1.0, TLS 1.1
- Weak cipher suites enabled
- Compression enabled (CRIME attack)
- Renegotiation enabled
2. Certificate Issues
- Expired certificates
- Self-signed certificates
- Weak signature algorithms (SHA-1, MD5)
- Missing intermediate certificates
- Wildcard certificate misuse
- Domain mismatch
3. Implementation Flaws
- Insecure random number generation
- Weak key generation
- ECB mode encryption
- Hardcoded keys/IVs
- Padding oracle vulnerabilities
4. Protocol Attacks
- BEAST (CBC in TLS 1.0)
- CRIME/BREACH (compression)
- HEARTBLEED (OpenSSL)
- POODLE (SSLv3)
- SWEET32 (3DES)
- Lucky13 (CBC padding)
METHODOLOGY - CRYPTO ASSESSMENT:
1. SSL/TLS CONFIGURATION
- Enumerate supported protocols
- Enumerate cipher suites
- Check for compression
- Check renegotiation settings
- Test for known vulnerabilities
2. CERTIFICATE ANALYSIS
- Verify certificate chain
- Check validity dates
- Verify signature algorithm
- Check key size
- Verify SANs
- Check revocation status
3. SECURITY HEADERS
- HSTS (Strict-Transport-Security)
- Expect-CT
- Certificate Transparency
4. IMPLEMENTATION REVIEW
- Check for hardcoded keys
- Verify secure random usage
- Analyze encryption modes
- Check key management
RULES:
- NEVER report vulnerabilities without evidence
- Rate-limit certificate requests to avoid blocking
- Document all cipher suites found
- Provide CVSS scores for crypto findings
- Include remediation commands with OpenSSL
- Consider compliance requirements (PCI-DSS, HIPAA)
TESTSSL.SH CHECKLIST:
□ Heartbleed vulnerability
□ CCS Injection
□ ROBOT attack
□ Secure Renegotiation
□ CRIME vulnerability
□ BREACH vulnerability
□ POODLE (SSLv3)
□ TLS Fallback SCSV
□ SWEET32
□ FREAK
□ DROWN
□ LOGJAM
□ BEAST
□ Lucky13
□ RC4 ciphers
REPORT FORMAT:
For each cryptographic finding:
1. Vulnerability Name (e.g., "Weak TLS Configuration")
2. Severity (CVSS v3.1)
3. Affected Protocols/Ciphers
4. Technical Details
5. Compliance Impact (PCI-DSS, etc.)
6. Remediation Steps
7. Testing Commands
8. References (CVE, CWE)
"""
def __init__(self, name: str = "Cryptography Expert", orchestrator=None, zen_orchestrator=None):
super().__init__(name, AgentRole.ANALYST, orchestrator)
self.zen_orchestrator = zen_orchestrator
self.crypto_findings = []
# Weak cipher definitions
self.weak_ciphers = ["RC4", "DES", "3DES", "NULL", "EXPORT", "MD5", "SHA1", "CBC", "anon"]
# Weak protocol versions
self.weak_protocols = ["SSLv2", "SSLv3", "TLSv1.0", "TLSv1.1"]
# Register message handlers
self.register_handler("ssl_scan", self._handle_ssl_scan)
self.register_handler("cert_analyze", self._handle_cert_analyze)
self.register_handler("cipher_test", self._handle_cipher_test)
self.register_handler("hash_analyze", self._handle_hash_analyze)
self.register_handler("crypto_audit", self._handle_crypto_audit)
async def _handle_ssl_scan(self, msg: AgentMessage):
"""Handle SSL/TLS comprehensive scan"""
target = msg.context.get("target")
port = msg.context.get("port", 443)
logger.info(f"[CryptoExpert:{self.name}] Scanning SSL/TLS for {target}:{port}")
results = await self._scan_ssl_tls(target, port)
await self.send_message(
content=f"SSL/TLS scan complete. Weak ciphers: {len(results['weak_ciphers'])}",
recipient=msg.sender,
msg_type="ssl_scan_results",
context={"results": results},
)
async def _handle_cert_analyze(self, msg: AgentMessage):
"""Handle certificate analysis"""
target = msg.context.get("target")
cert_pem = msg.context.get("certificate")
logger.info(f"[CryptoExpert:{self.name}] Analyzing certificate")
if cert_pem:
results = await self._analyze_certificate_pem(cert_pem)
else:
results = await self._analyze_certificate_target(target)
await self.send_message(
content=f"Certificate analysis complete. Issues: {len(results['issues'])}",
recipient=msg.sender,
msg_type="cert_analysis_results",
context={"results": results},
)
async def _handle_cipher_test(self, msg: AgentMessage):
"""Handle cipher suite testing"""
target = msg.context.get("target")
logger.info(f"[CryptoExpert:{self.name}] Testing cipher suites")
results = await self._test_cipher_suites(target)
await self.send_message(
content=f"Cipher testing complete. Recommended: {len(results['recommended'])}, Weak: {len(results['weak'])}",
recipient=msg.sender,
msg_type="cipher_test_results",
context={"results": results},
)
async def _handle_hash_analyze(self, msg: AgentMessage):
"""Handle hash algorithm analysis"""
hash_value = msg.context.get("hash")
hash_type = msg.context.get("hash_type")
logger.info(f"[CryptoExpert:{self.name}] Analyzing hash")
results = await self._analyze_hash(hash_value, hash_type)
await self.send_message(
content=f"Hash analysis complete. Algorithm: {results['detected_algorithm']}",
recipient=msg.sender,
msg_type="hash_analysis_results",
context={"results": results},
)
async def _handle_crypto_audit(self, msg: AgentMessage):
"""Handle comprehensive cryptographic audit"""
target = msg.context.get("target")
logger.info(f"[CryptoExpert:{self.name}] Running comprehensive crypto audit")
# SSL/TLS scan
ssl_results = await self._scan_ssl_tls(target, 443)
# Certificate analysis
cert_results = await self._analyze_certificate_target(target)
results = {
"ssl_tls": ssl_results,
"certificate": cert_results,
"security_headers": await self._check_security_headers(target),
}
await self.send_message(
content=f"Crypto audit complete. Total issues: {len(ssl_results['issues']) + len(cert_results['issues'])}",
recipient=msg.sender,
msg_type="crypto_audit_results",
context={"results": results},
)
async def _scan_ssl_tls(self, target: str, port: int) -> Dict[str, Any]:
"""Comprehensive SSL/TLS scan"""
results = {
"target": f"{target}:{port}",
"protocols": {},
"ciphers": {},
"weak_ciphers": [],
"recommended_ciphers": [],
"vulnerabilities": [],
"issues": [],
"grade": "A+",
}
# Simulate protocol detection
protocols = ["TLSv1.2", "TLSv1.3"]
for protocol in protocols:
results["protocols"][protocol] = {"enabled": True, "secure": protocol not in self.weak_protocols}
# Simulate cipher detection
ciphers = ["TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256", "ECDHE_RSA_WITH_AES_256_GCM_SHA384"]
results["ciphers"] = ciphers
results["recommended_ciphers"] = ciphers
# Check for known vulnerabilities
vuln_checks = [
("heartbleed", "CVE-2014-0160", "critical"),
("poodle", "CVE-2014-3566", "high"),
("crime", "CVE-2012-4929", "medium"),
("beast", "CVE-2011-3389", "medium"),
]
for vuln_name, cve, severity in vuln_checks:
results["vulnerabilities"].append({"name": vuln_name, "cve": cve, "severity": severity, "affected": False})
return results
async def _analyze_certificate_target(self, target: str) -> Dict[str, Any]:
"""Analyze certificate from target"""
results = {"target": target, "valid": True, "issues": [], "details": {}}
# Certificate details
results["details"] = {
"subject": f"CN={target}",
"issuer": "Let's Encrypt Authority X3",
"valid_from": "2026-01-01",
"valid_until": "2026-04-01",
"serial_number": "00:00:00:00:00:00:00:00",
"signature_algorithm": "sha256WithRSAEncryption",
"key_size": 2048,
"sans": [target, f"www.{target}"],
}
# Check key size
if results["details"]["key_size"] < 2048:
results["issues"].append(
{
"type": "weak_key",
"severity": "high",
"description": f"RSA key size {results['details']['key_size']} is below recommended 2048 bits",
}
)
# Check signature algorithm
if "sha1" in results["details"]["signature_algorithm"].lower():
results["issues"].append(
{
"type": "weak_signature",
"severity": "high",
"description": "Certificate uses weak SHA-1 signature algorithm",
}
)
return results
async def _analyze_certificate_pem(self, cert_pem: str) -> Dict[str, Any]:
"""Analyze certificate from PEM data"""
results = {"valid": True, "issues": [], "details": {}}
try:
# Decode PEM
cert_der = base64.b64decode(
cert_pem.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "").replace("\n", "")
)
results["details"]["size"] = len(cert_der)
except Exception as e:
results["valid"] = False
results["issues"].append({"type": "invalid_pem", "severity": "error", "description": str(e)})
return results
async def _test_cipher_suites(self, target: str) -> Dict[str, Any]:
"""Test cipher suite support"""
results = {"target": target, "supported": [], "recommended": [], "weak": [], "strong": []}
# Recommended ciphers (TLS 1.3 and strong TLS 1.2)
recommended = [
"TLS_AES_256_GCM_SHA384",
"TLS_CHACHA20_POLY1305_SHA256",
"TLS_AES_128_GCM_SHA256",
"ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
]
# Weak ciphers to avoid
weak = [
"ECDHE_RSA_WITH_RC4_128_SHA",
"ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
"RSA_WITH_RC4_128_SHA",
"RSA_WITH_3DES_EDE_CBC_SHA",
]
results["recommended"] = recommended
results["weak"] = weak
results["strong"] = recommended[:3]
return results
async def _analyze_hash(self, hash_value: str, hash_type: Optional[str] = None) -> Dict[str, Any]:
"""Analyze hash value"""
results = {
"hash": hash_value,
"length": len(hash_value),
"detected_algorithm": None,
"is_secure": False,
"possible_algorithms": [],
}
hash_length_map = {32: ["MD5"], 40: ["SHA-1"], 56: ["SHA-224"], 64: ["SHA-256"], 96: ["SHA-384"], 128: ["SHA-512"]}
# Detect by length
results["possible_algorithms"] = hash_length_map.get(results["length"], ["Unknown"])
if hash_type:
results["detected_algorithm"] = hash_type.upper()
else:
results["detected_algorithm"] = results["possible_algorithms"][0]
# Check if secure
insecure_algorithms = ["MD5", "SHA-1"]
results["is_secure"] = results["detected_algorithm"] not in insecure_algorithms
return results
async def _check_security_headers(self, target: str) -> Dict[str, Any]:
"""Check security headers related to crypto"""
headers = {
"Strict-Transport-Security": None,
"Expect-CT": None,
"Public-Key-Pins": None, # Deprecated but may still be present
}
results = {"headers_found": {}, "headers_missing": [], "recommendations": []}
for header in headers:
# Would make HTTP request here
results["headers_missing"].append(header)
if "Strict-Transport-Security" in results["headers_missing"]:
results["recommendations"].append(
"Enable HSTS with: Strict-Transport-Security: max-age=31536000; includeSubDomains"
)
return results
def analyze(self, target: Optional[str], findings: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Persona-specific analysis logic for cryptographic findings.
Args:
target: The target host/service
findings: List of cryptographic findings
Returns:
Analysis results with crypto-specific risk assessment
"""
analysis = {
"total_findings": len(findings),
"by_category": {},
"by_severity": {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0},
"ssl_grade": "A+",
"compliance_status": {},
"recommendations": [],
"priority_fixes": [],
}
categories = {"protocol": [], "cipher": [], "certificate": [], "implementation": [], "vulnerability": []}
for finding in findings:
category = finding.get("category", "unknown")
severity = finding.get("severity", "info").lower()
if category in categories:
categories[category].append(finding)
if severity in analysis["by_severity"]:
analysis["by_severity"][severity] += 1
analysis["by_category"] = categories
# Determine SSL grade
if analysis["by_severity"]["critical"] > 0 or analysis["by_severity"]["high"] > 0:
analysis["ssl_grade"] = "F"
elif analysis["by_severity"]["medium"] > 0:
analysis["ssl_grade"] = "C"
elif len(categories.get("weak_ciphers", [])) > 0:
analysis["ssl_grade"] = "B"
# PCI-DSS compliance check
analysis["compliance_status"]["pci_dss"] = self._check_pci_compliance(findings)
# Generate recommendations
analysis["recommendations"] = self._generate_crypto_recommendations(categories)
analysis["priority_fixes"] = self._get_priority_fixes(findings)
return analysis
def _check_pci_compliance(self, findings: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Check PCI-DSS compliance"""
status = {"compliant": True, "violations": []}
for finding in findings:
# SSLv3 is not PCI compliant
if finding.get("name") == "SSLv3" and finding.get("enabled"):
status["compliant"] = False
status["violations"].append("SSLv3 enabled (not PCI compliant)")
# Weak ciphers
if finding.get("category") == "cipher" and finding.get("severity") == "high":
status["compliant"] = False
status["violations"].append(f"Weak cipher: {finding.get('name')}")
return status
def _generate_crypto_recommendations(self, categories: Dict[str, List]) -> List[str]:
"""Generate cryptographic recommendations"""
recommendations = []
if categories.get("protocol"):
protocols = [p.get("name") for p in categories["protocol"]]
weak_protocols = [p for p in protocols if p in self.weak_protocols]
if weak_protocols:
recommendations.append(f"Disable weak protocols: {', '.join(weak_protocols)}")
if categories.get("cipher"):
recommendations.append("Configure server to prefer strong cipher suites (TLS 1.3 or ECDHE with AES-GCM/ChaCha20)")
if categories.get("certificate"):
recommendations.append("Review and update certificates to use RSA 2048+ bits or ECC P-256+ with SHA-256")
recommendations.append("Enable HSTS with appropriate max-age")
return recommendations
def _get_priority_fixes(self, findings: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Get priority fixes ordered by severity"""
priority_order = ["critical", "high", "medium", "low"]
priority_fixes = []
for severity in priority_order:
for finding in findings:
if finding.get("severity", "").lower() == severity:
priority_fixes.append(
{
"issue": finding.get("name", "Unknown"),
"severity": severity,
"fix": finding.get("remediation", "Review and fix"),
}
)
return priority_fixes[:10] # Top 10 priorities
async def execute_task(self, task: Dict) -> Dict:
"""Execute cryptographic analysis task"""
task_type = task.get("type", "")
context = task.get("context", {})
logger.info(f"[CryptoExpert:{self.name}] Executing task: {task_type}")
if task_type == "ssl_scan":
results = await self._scan_ssl_tls(context.get("target"), context.get("port", 443))
analysis = self.analyze(context.get("target"), results["issues"])
return {"status": "complete", "results": results, "analysis": analysis, "agent": self.name}
elif task_type == "cert_analysis":
results = await self._analyze_certificate_target(context.get("target"))
return {"status": "complete", "results": results, "agent": self.name}
return {"status": "unknown_task"}

Xet Storage Details

Size:
22.1 kB
·
Xet hash:
3a3089f26a85adb93a256939bf52a1adf85a24bd4c024792f41a8df6fbf1ef76

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.