Log all auth/authz events with structured JSON, ship to SIEM, and create detection rules for anomalies.
SIEM and Security Logging
# What to log (security-relevant events)
# Authentication: login, logout, failed attempts, MFA events
# Authorisation: access denied, privilege escalation
# Data access: sensitive data reads, exports, deletions
# Configuration changes: user creation, role changes
# Network: unusual outbound connections, new services
# Structured security log format
import structlog, uuid
from datetime import datetime, timezone
log = structlog.get_logger()
def log_auth_event(event_type: str, user_id: int, ip: str, success: bool):
log.info(
"auth_event",
event_type=event_type, # login_attempt, mfa_failed
user_id=user_id,
ip_address=ip,
success=success,
timestamp=datetime.now(timezone.utc).isoformat(),
session_id=str(uuid.uuid4())
)
# SIEM tools
# Elastic Security (ELK + detection rules)
# Splunk (enterprise, expensive)
# Graylog (open source)
# Wazuh (open source, SIEM + EDR)
# Detection rule example (Elastic)
# Alert: 5+ failed logins for same user in 60s
{
"query": "event.type:failure AND event.action:user-login",
"threshold": {"field":["user.name"],"value":5,"cardinality":[]},
"window_size": "1m"
}