# Python - SECURE: SSL/TLS server with strong cryptographic configuration
import ssl
import socket
import threading
import secrets
import os
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtensionOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa, ec
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import datetime
import ipaddress
class SecureSSLServer:
def __init__(self, host='localhost', port=8443):
self.host = host
self.port = port
self.cert_file = 'secure_server.crt'
self.key_file = 'secure_server.key'
# Generate strong certificate and key
self.generate_secure_certificate()
def generate_secure_certificate(self, key_type='rsa', rsa_key_size=3072):
"""SECURE: Generate certificate with strong cryptographic keys"""
if key_type == 'rsa':
if rsa_key_size < 2048:
raise ValueError("RSA key size must be at least 2048 bits")
# SECURE: Generate strong RSA key (3072+ bits)
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=rsa_key_size,
)
print(f"Generated {rsa_key_size}-bit RSA key")
elif key_type == 'ecdsa':
# SECURE: Use strong elliptic curve (P-384)
private_key = ec.generate_private_key(ec.SECP384R1())
print("Generated ECDSA key with P-384 curve")
else:
raise ValueError("Unsupported key type")
# Create comprehensive certificate with security extensions
subject = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"State"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"City"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Secure Org"),
x509.NameAttribute(NameOID.COMMON_NAME, self.host),
])
# Create certificate with security best practices
cert_builder = x509.CertificateBuilder().subject_name(
subject
).issuer_name(
subject # Self-signed
).public_key(
private_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=365)
)
# Add security extensions
cert_builder = cert_builder.add_extension(
x509.SubjectAlternativeName([
x509.DNSName(self.host),
x509.DNSName("*." + self.host),
x509.IPAddress(ipaddress.IPv4Address('127.0.0.1')),
]),
critical=False,
).add_extension(
x509.KeyUsage(
digital_signature=True,
key_encipherment=True,
content_commitment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=False
),
critical=True,
).add_extension(
x509.ExtendedKeyUsage([
x509.oid.ExtendedKeyUsageOID.SERVER_AUTH,
x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH,
]),
critical=True,
)
# Sign with strong hash algorithm
cert = cert_builder.sign(private_key, hashes.SHA256())
# Save certificate and private key securely
with open(self.cert_file, 'wb') as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
# Save private key with secure permissions
with open(self.key_file, 'wb') as f:
f.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
# Set secure file permissions (Unix-like systems)
try:
os.chmod(self.key_file, 0o600) # Read/write for owner only
os.chmod(self.cert_file, 0o644) # Read for all, write for owner
except:
pass # Permissions not available on all systems
def create_secure_ssl_context(self):
"""SECURE: SSL context with strong configuration"""
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
# SECURE: Require strong TLS versions only
context.minimum_version = ssl.TLSVersion.TLSv1_2 # TLS 1.2 minimum
context.maximum_version = ssl.TLSVersion.TLSv1_3 # TLS 1.3 preferred
# SECURE: Configure strong cipher suites only
# Prefer AEAD ciphers, strong key exchange, and forward secrecy
strong_ciphers = ':'.join([
'ECDHE+AESGCM',
'ECDHE+CHACHA20',
'DHE+AESGCM',
'DHE+CHACHA20',
'!aNULL',
'!eNULL',
'!EXPORT',
'!DES',
'!RC4',
'!MD5',
'!PSK',
'!SRP',
'!CAMELLIA',
'!SEED'
])
context.set_ciphers(strong_ciphers)
# Load strong certificate
context.load_cert_chain(self.cert_file, self.key_file)
# SECURE: Enable security features
context.check_hostname = False # Self-signed cert
context.verify_mode = ssl.CERT_NONE # For demo - use CERT_REQUIRED in production
# Enable perfect forward secrecy
context.options |= ssl.OP_SINGLE_DH_USE
context.options |= ssl.OP_SINGLE_ECDH_USE
# Disable compression (CRIME attack prevention)
context.options |= ssl.OP_NO_COMPRESSION
# Set secure DH parameters
try:
context.load_dh_params('dhparam.pem') # Generate with: openssl dhparam -out dhparam.pem 2048
except:
pass # Will use default DH parameters
return context
def handle_client(self, conn, addr):
"""Handle client connection with security monitoring"""
try:
print(f"Secure connection from {addr}")
# Get and validate cipher info
cipher = conn.cipher()
if cipher:
cipher_name, tls_version, key_bits = cipher
print(f"Negotiated cipher: {cipher_name}")
print(f"TLS version: {tls_version}")
print(f"Key strength: {key_bits} bits")
# Validate minimum security requirements
if key_bits < 128:
print("WARNING: Weak cipher negotiated!")
conn.close()
return
if 'TLSv1.' not in tls_version or tls_version in ['TLSv1.0', 'TLSv1.1']:
print("WARNING: Weak TLS version!")
conn.close()
return
# Get certificate information
peer_cert = conn.getpeercert()
if peer_cert:
print(f"Client certificate: {peer_cert.get('subject', 'None')}")
# Secure HTTP response with security headers
response = (
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 150\r\n"
"Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n"
"X-Content-Type-Options: nosniff\r\n"
"X-Frame-Options: DENY\r\n"
"Content-Security-Policy: default-src 'self'\r\n"
"\r\n"
"<html><body><h1>Secure SSL Server</h1>"
f"<p>Connected with {cipher_name} ({key_bits} bits)</p>"
"<p>Using strong cryptographic keys!</p></body></html>"
)
conn.send(response.encode())
except ssl.SSLError as e:
print(f"SSL error: {e}")
except Exception as e:
print(f"Error handling client: {e}")
finally:
conn.close()
def start_server(self):
"""Start the secure SSL server"""
context = self.create_secure_ssl_context()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((self.host, self.port))
sock.listen(5)
print(f"Secure SSL server listening on {self.host}:{self.port}")
print("Using strong cryptographic configuration:")
print("- TLS 1.2+ only")
print("- Strong cipher suites")
print("- Perfect Forward Secrecy")
print("- 3072-bit RSA or ECDSA P-384")
with context.wrap_socket(sock, server_side=True) as ssock:
while True:
try:
conn, addr = ssock.accept()
client_thread = threading.Thread(
target=self.handle_client,
args=(conn, addr)
)
client_thread.daemon = True
client_thread.start()
except KeyboardInterrupt:
print("\nShutting down secure server...")
break
except Exception as e:
print(f"Server error: {e}")
class SecureSSLClient:
def __init__(self):
self.min_key_bits = 128 # Minimum acceptable key strength
self.allowed_protocols = ['TLSv1.2', 'TLSv1.3']
def create_secure_context(self):
"""Create secure SSL context for client"""
context = ssl.create_default_context()
# SECURE: Require strong protocols
context.minimum_version = ssl.TLSVersion.TLSv1_2
# SECURE: Use strong cipher suites
strong_ciphers = ':'.join([
'ECDHE+AESGCM',
'ECDHE+CHACHA20',
'DHE+AESGCM',
'DHE+CHACHA20',
'!aNULL',
'!eNULL',
'!EXPORT',
'!DES',
'!RC4',
'!MD5'
])
context.set_ciphers(strong_ciphers)
# For demo with self-signed cert
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
return context
def connect_with_security_validation(self, host, port):
"""Connect with comprehensive security validation"""
context = self.create_secure_context()
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
with context.wrap_socket(sock, server_hostname=host) as ssock:
ssock.connect((host, port))
print(f"Securely connected to {host}:{port}")
# Validate connection security
cipher = ssock.cipher()
if cipher:
cipher_name, tls_version, key_bits = cipher
print(f"Cipher Suite: {cipher_name}")
print(f"Protocol: {tls_version}")
print(f"Key Strength: {key_bits} bits")
# Security validation
if key_bits < self.min_key_bits:
raise ssl.SSLError(f"Insufficient key strength: {key_bits} bits")
if tls_version not in self.allowed_protocols:
raise ssl.SSLError(f"Weak protocol: {tls_version}")
# Check for perfect forward secrecy
if 'ECDHE' in cipher_name or 'DHE' in cipher_name:
print("✓ Perfect Forward Secrecy enabled")
else:
print("⚠ No Perfect Forward Secrecy")
# Check for authenticated encryption
if 'GCM' in cipher_name or 'CHACHA20' in cipher_name:
print("✓ Authenticated encryption enabled")
else:
print("⚠ No authenticated encryption")
# Send secure HTTP request
request = (
"GET / HTTP/1.1\r\n"
"Host: " + host + "\r\n"
"User-Agent: SecureClient/1.0\r\n"
"Connection: close\r\n"
"\r\n"
)
ssock.send(request.encode())
# Receive response
response = ssock.recv(4096).decode()
print("\nServer Response:")
print(response.split('\r\n\r\n')[0]) # Headers only
except ssl.SSLError as e:
print(f"SSL security validation failed: {e}")
except Exception as e:
print(f"Connection error: {e}")
# Secure key generation utilities
class SecureKeyGeneration:
@staticmethod
def generate_secure_rsa_keys():
"""Generate strong RSA keys with different security levels"""
secure_sizes = [2048, 3072, 4096] # All secure
for size in secure_sizes:
print(f"Generating {size}-bit RSA key (SECURE)")
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=size
)
# Save secure keys
key_filename = f'secure_rsa_{size}.pem'
with open(key_filename, 'wb') as f:
f.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
# Set secure permissions
try:
os.chmod(key_filename, 0o600)
except:
pass
print(f"Saved secure {size}-bit key to {key_filename}")
@staticmethod
def generate_secure_elliptic_curve_keys():
"""Generate secure elliptic curve keys"""
secure_curves = {
'secp256r1': ec.SECP256R1(),
'secp384r1': ec.SECP384R1(),
'secp521r1': ec.SECP521R1(),
}
for curve_name, curve_obj in secure_curves.items():
print(f"Generating ECDSA key with {curve_name} curve")
private_key = ec.generate_private_key(curve_obj)
key_filename = f'secure_ecdsa_{curve_name}.pem'
with open(key_filename, 'wb') as f:
f.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
try:
os.chmod(key_filename, 0o600)
except:
pass
print(f"Saved secure ECDSA key to {key_filename}")
@staticmethod
def generate_secure_symmetric_keys():
"""Generate strong symmetric keys"""
secure_key_configs = {
'aes256': 32, # 256-bit AES
'hmac_sha256': 32, # 256-bit HMAC key
'chacha20': 32, # 256-bit ChaCha20
}
for name, size in secure_key_configs.items():
key = secrets.token_bytes(size)
print(f"Generated {name} key: {size} bytes ({size * 8} bits)")
key_filename = f'secure_{name}_key.bin'
with open(key_filename, 'wb') as f:
f.write(key)
try:
os.chmod(key_filename, 0o600)
except:
pass
@staticmethod
def demonstrate_aes_gcm():
"""Demonstrate AES-256-GCM authenticated encryption"""
print("\nDemonstrating AES-256-GCM encryption:")
# Generate 256-bit key
key = secrets.token_bytes(32)
# Create AES-GCM cipher
aesgcm = AESGCM(key)
# Encrypt data
plaintext = b"Sensitive data requiring strong protection"
nonce = secrets.token_bytes(12) # 96-bit nonce
ciphertext = aesgcm.encrypt(nonce, plaintext, None)
print(f"Plaintext: {len(plaintext)} bytes")
print(f"Ciphertext: {len(ciphertext)} bytes")
print(f"Key size: {len(key) * 8} bits")
print(f"Nonce size: {len(nonce) * 8} bits")
# Decrypt to verify
decrypted = aesgcm.decrypt(nonce, ciphertext, None)
print(f"Decryption successful: {decrypted == plaintext}")
if __name__ == '__main__':
print("Generating secure cryptographic keys...")
# Generate all types of secure keys
SecureKeyGeneration.generate_secure_rsa_keys()
SecureKeyGeneration.generate_secure_elliptic_curve_keys()
SecureKeyGeneration.generate_secure_symmetric_keys()
SecureKeyGeneration.demonstrate_aes_gcm()
print("\nStarting secure SSL server demonstration...")
# Create server with different key types
print("\n1. Creating server with 3072-bit RSA key:")
server_rsa = SecureSSLServer()
print("\n2. Creating server with ECDSA P-384 key:")
server_ecdsa = SecureSSLServer()
server_ecdsa.cert_file = 'secure_ecdsa_server.crt'
server_ecdsa.key_file = 'secure_ecdsa_server.key'
server_ecdsa.generate_secure_certificate(key_type='ecdsa')
# Uncomment to start server:
# server_rsa.start_server()
print("\nSecure SSL configuration complete!")
print("All keys use cryptographically strong parameters:")
print("- RSA: 2048+ bits (3072+ recommended)")
print("- ECDSA: P-256, P-384, or P-521 curves")
print("- AES: 256-bit keys with GCM mode")
print("- TLS: Version 1.2+ with strong cipher suites")