#!/usr/bin/env python3 """ Enhanced Security Module for Bitcoin Private Key Management Comprehensive security validation and handling for sensitive operations """ import hashlib import secrets import string import re from typing import Dict, List, Any, Optional, Tuple from dataclasses import dataclass from enum import Enum from multi_network_wallet import BitcoinNetwork class SecurityLevel(Enum): """Security classification levels""" LOW = "low" MEDIUM = "medium" HIGH = "high" CRITICAL = "critical" @dataclass class SecurityAudit: """Security audit result""" passed: bool level: SecurityLevel issues: List[str] recommendations: List[str] audit_timestamp: str class PrivateKeySecurityValidator: """Advanced private key security validation""" def __init__(self): self.weak_passwords = [ "password", "123456", "qwerty", "abc123", "letmein", "welcome", "monkey", "dragon", "master", "hello" ] self.suspicious_patterns = [ r'12345', r'qwerty', r'abcde', r'password', r'admin' ] def validate_private_key_security(self, private_key: str, context: str = "import") -> Dict[str, Any]: """Comprehensive private key security validation""" result = { "valid": False, "security_level": SecurityLevel.LOW.value, "issues": [], "warnings": [], "recommendations": [], "entropy_score": 0.0 } # Basic format validation if not self._validate_wif_format(private_key): result["issues"].append("Invalid WIF format") return result # Check for known compromised patterns if self._is_known_compromised(private_key): result["issues"].append("Private key matches known compromised patterns") return result # Calculate entropy entropy = self._calculate_entropy(private_key) result["entropy_score"] = entropy if entropy < 3.0: result["issues"].append("Private key has insufficient entropy") result["security_level"] = SecurityLevel.LOW.value elif entropy < 4.5: result["warnings"].append("Private key entropy could be higher") result["security_level"] = SecurityLevel.MEDIUM.value else: result["security_level"] = SecurityLevel.HIGH.value # Context-specific checks context_check = self._validate_context_security(private_key, context) result["issues"].extend(context_check["issues"]) result["warnings"].extend(context_check["warnings"]) result["recommendations"].extend(context_check["recommendations"]) # Overall validation result["valid"] = len(result["issues"]) == 0 return result def validate_wallet_encryption(self, passphrase: str) -> Dict[str, Any]: """Validate wallet encryption passphrase""" result = { "valid": False, "strength_score": 0, "security_level": SecurityLevel.LOW.value, "issues": [], "recommendations": [] } # Length check if len(passphrase) < 12: result["issues"].append("Passphrase too short (minimum 12 characters)") elif len(passphrase) < 20: result["recommendations"].append("Use passphrase of 20+ characters for better security") # Character variety has_upper = any(c.isupper() for c in passphrase) has_lower = any(c.islower() for c in passphrase) has_digit = any(c.isdigit() for c in passphrase) has_special = any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in passphrase) char_variety = sum([has_upper, has_lower, has_digit, has_special]) result["strength_score"] = char_variety * 25 # Check for common passwords if passphrase.lower() in self.weak_passwords: result["issues"].append("Passphrase is too common") result["strength_score"] = 0 # Check for repeating patterns if self._has_repeating_patterns(passphrase): result["issues"].append("Passphrase contains repeating patterns") result["strength_score"] = max(0, result["strength_score"] - 50) # Dictionary words check common_words = ["bitcoin", "crypto", "wallet", "money", "cash"] if any(word in passphrase.lower() for word in common_words): result["recommendations"].append("Avoid common cryptocurrency-related words") result["strength_score"] = max(0, result["strength_score"] - 15) # Determine security level if result["strength_score"] >= 75: result["security_level"] = SecurityLevel.HIGH.value elif result["strength_score"] >= 50: result["security_level"] = SecurityLevel.MEDIUM.value else: result["security_level"] = SecurityLevel.LOW.value result["valid"] = len(result["issues"]) == 0 and result["strength_score"] >= 50 return result def secure_random_bytes(self, length: int = 32) -> bytes: """Generate cryptographically secure random bytes""" return secrets.token_bytes(length) def generate_secure_wallet_passphrase(self, length: int = 24) -> str: """Generate secure wallet passphrase""" # Use cryptographically secure random generation alphabet = string.ascii_letters + string.digits + "!@#$%^&*()_+-=[]{}|;:,.<>?" return ''.join(secrets.choice(alphabet) for _ in range(length)) def _validate_wif_format(self, private_key: str) -> bool: """Validate Wallet Import Format (WIF)""" if not private_key or len(private_key) < 30 or len(private_key) > 52: return False # Base58 character check base58_chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' for char in private_key: if char not in base58_chars: return False return True def _is_known_compromised(self, private_key: str) -> bool: """Check against known compromised private keys""" # This would integrate with a database of known compromised keys # For demo purposes, check some obvious patterns compromised_patterns = [ "111111111111111111111111111111111111111111111111", "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreBo9Wqt", "5KWzdyYQR9eEWQbn3UgCHwGmQtP5EYNSMjvL5Xo1CKvboe2Mi1m" ] return private_key in compromised_patterns def _calculate_entropy(self, data: str) -> float: """Calculate Shannon entropy of data""" if not data: return 0.0 # Count character frequencies char_counts = {} for char in data: char_counts[char] = char_counts.get(char, 0) + 1 # Calculate entropy entropy = 0.0 data_len = len(data) for count in char_counts.values(): probability = count / data_len if probability > 0: entropy -= probability * math.log2(probability) return entropy def _validate_context_security(self, private_key: str, context: str) -> Dict[str, Any]: """Context-specific security validation""" result = {"issues": [], "warnings": [], "recommendations": []} if context == "import": result["recommendations"].append("Verify source of imported private key") result["recommendations"].append("Consider creating a new wallet instead") elif context == "backup": result["recommendations"].append("Store backup securely offline") result["recommendations"].append("Consider using a hardware wallet") elif context == "recovery": result["warnings"].append("Recovering from private key exposes it to memory") result["recommendations"].append("Clear memory after recovery process") return result def _has_repeating_patterns(self, text: str) -> bool: """Check for repeating character patterns""" if len(text) < 3: return False # Check for 3+ consecutive identical characters for i in range(len(text) - 2): if text[i] == text[i+1] == text[i+2]: return True # Check for common repeating patterns patterns = ['123', 'abc', 'qwe'] for pattern in patterns: if pattern in text.lower(): return True return False import math class SecurityAuditor: """Comprehensive security auditor for Bitcoin operations""" def __init__(self): self.key_validator = PrivateKeySecurityValidator() self.audit_log = [] def audit_wallet_creation(self, wallet_name: str, passphrase: Optional[str], network: BitcoinNetwork) -> SecurityAudit: """Audit wallet creation for security compliance""" issues = [] recommendations = [] # Wallet name security if len(wallet_name) < 8: recommendations.append("Use longer wallet names for better identification") if re.search(r'[<>:"/\\|?*]', wallet_name): issues.append("Wallet name contains invalid characters") # Network-specific security if network == BitcoinNetwork.MAINNET and not passphrase: recommendations.append("Mainnet wallets should always be encrypted") # Passphrase security if passphrase: pass_validation = self.key_validator.validate_wallet_encryption(passphrase) if not pass_validation["valid"]: issues.extend(pass_validation["issues"]) # Determine security level if len(issues) == 0: level = SecurityLevel.HIGH elif len(issues) <= 2: level = SecurityLevel.MEDIUM else: level = SecurityLevel.LOW audit_result = SecurityAudit( passed=len(issues) == 0, level=level, issues=issues, recommendations=recommendations, audit_timestamp=datetime.datetime.now().isoformat() ) self.audit_log.append(audit_result) return audit_result def audit_private_key_operation(self, operation: str, private_key: str, context: str) -> SecurityAudit: """Audit private key operations""" key_validation = self.key_validator.validate_private_key_security(private_key, context) issues = key_validation["issues"] recommendations = key_validation["recommendations"] # Operation-specific checks if operation == "import": recommendations.append("Consider using hardware wallet for better security") elif operation == "export": issues.append("Private key export is high-risk operation") security_level = SecurityLevel.HIGH if key_validation["security_level"] == SecurityLevel.LOW.value: security_level = SecurityLevel.CRITICAL elif key_validation["security_level"] == SecurityLevel.MEDIUM.value: security_level = SecurityLevel.MEDIUM audit_result = SecurityAudit( passed=len(issues) == 0, level=security_level, issues=issues, recommendations=recommendations, audit_timestamp=datetime.datetime.now().isoformat() ) self.audit_log.append(audit_result) return audit_result import datetime def demo_security_validation(): """Demonstrate security validation capabilities""" print("=== Bitcoin Security Validation Demo ===\n") validator = PrivateKeySecurityValidator() auditor = SecurityAuditor() # Test private key validation test_keys = [ "L5EZftvrYaSudioKJRm4iWfJNPZzmFTQqYq9R5dGGKZBUs7j4Mt9", # Valid example "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreBo9Wqt", # Compromised "1234567890123456789012345678901234567890" # Invalid format ] for i, key in enumerate(test_keys): print(f"--- Testing Private Key {i+1} ---") validation = validator.validate_private_key_security(key) print(f"Valid: {validation['valid']}") print(f"Security Level: {validation['security_level']}") print(f"Entropy Score: {validation['entropy_score']:.2f}") if validation['issues']: print("Issues:") for issue in validation['issues']: print(f" ❌ {issue}") print() # Test passphrase validation test_passphrases = [ "weak123", "BetterPassphrase123!", "VerySecurePassphrase!@#$%^&*()_+2024" ] for passphrase in test_passphrases: print(f"--- Testing Passphrase: {passphrase[:10]}... ---") pass_validation = validator.validate_wallet_encryption(passphrase) print(f"Valid: {pass_validation['valid']}") print(f"Strength Score: {pass_validation['strength_score']}") print(f"Security Level: {pass_validation['security_level']}") if pass_validation['issues']: print("Issues:") for issue in pass_validation['issues']: print(f" ❌ {issue}") print() # Generate secure passphrase secure_pass = validator.generate_secure_wallet_passphrase() print(f"Generated Secure Passphrase: {secure_pass}") # Security audit example audit = auditor.audit_wallet_creation("test_wallet", secure_pass, BitcoinNetwork.MAINNET) print(f"\n--- Security Audit Results ---") print(f"Audit Passed: {audit.passed}") print(f"Security Level: {audit.level.value}") if audit.recommendations: print("Recommendations:") for rec in audit.recommendations: print(f" 💡 {rec}") if __name__ == "__main__": demo_security_validation()