William Costa Rodrigues - Site Developer

Site pessoal, com postagens, desenhos, códigos, informações sobre ciências e tecnologia.

Home Novidades Postagens
Categoria
Códigos adicionados no site: 18
Temas para Código

Verificando cabeçalhos de segurança em seu site

Palavras-chaves: Python, Security, Header, Segurança | Python
Cadastro: 22/09/2025 18:15:19 | Atualização: 28/09/2025 20:01:23
import requests
import socket
import ssl
from urllib.parse import urlparse

def get_ssl_expiry_date(hostname):
    context = ssl.create_default_context()
    with socket.create_connection((hostname, 443)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            ssl_info = ssock.getpeercert()
            return ssl_info['notAfter']

def check_security_headers(headers):
    required_headers = [
        'Content-Security-Policy',
        'Strict-Transport-Security',
        'X-Content-Type-Options',
        'X-Frame-Options',
        'X-XSS-Protection',
        'Referrer-Policy',
        'Permissions-Policy'
    ]
    missing = [h for h in required_headers if h not in headers]
    return missing

def check_site_security(url):
    print(f"? Analisando: {url}")
    try:
        response = requests.get(url, timeout=10)
        parsed_url = urlparse(url)
        hostname = parsed_url.hostname
        ip = socket.gethostbyname(hostname)
        print(f"? IP: {ip}")
        print(f"? Status code: {response.status_code}")
        print(f"? Verificando SSL...")
        ssl_expiry = get_ssl_expiry_date(hostname)
        print(f"   ? Certificado SSL expira em: {ssl_expiry}")
        print("? Verificando headers de segurança...")
        missing_headers = check_security_headers(response.headers)
        if missing_headers:
            print("   ⚠ Headers de segurança ausentes:")
            for h in missing_headers:
                print(f"     - {h}")
        else:
            print("   ✅ Todos os principais headers de segurança estão presentes.")

        print("✅ Análise passiva concluída.")
    except Exception as e:
        print(f"❌ Erro na análise: {e}")

# Execute a análise
check_site_security("https://www.wcrodrigues.dev.br/")