# PYTHON-LANG-SEC-105: Logger Credential Leak Risk

> **Severity:** MEDIUM | **CWE:** CWE-532 | **OWASP:** A09:2021

- **Language:** Python
- **Category:** Python Core
- **URL:** https://codepathfinder.dev/registry/python/lang/PYTHON-LANG-SEC-105
- **Detection:** `pathfinder scan --ruleset python/PYTHON-LANG-SEC-105 --project .`

## Description

This rule flags calls to logging.info(), logging.debug(), logging.warning(),
logging.error(), logging.critical(), logging.exception(), and logging.log() as
audit items. Log statements are a common vector for accidentally exposing
passwords, API keys, session tokens, database connection strings, and other
secrets.

Developers often add verbose logging during debugging and forget to remove it
before shipping. A single logging.debug(f"Connecting with password={password}")
can expose credentials to anyone with access to log files, log aggregation
services, or error tracking tools.

The rule operates at audit level because most logging calls are harmless. Review
each flagged call to ensure no sensitive data appears in the format string or
arguments.


## Vulnerable Code

```python
import uuid
import os
import re
import logging
import logging.config

# SEC-105: logger credential leak
logging.info("User logged in with password: %s", password)
logging.debug("API key: %s", api_key)
```

## Secure Code

```python
import logging

logger = logging.getLogger(__name__)

# SECURE: Log the action, not the credentials
logger.info("User %s authenticated successfully", user.username)

# SECURE: Redact sensitive fields
logger.debug("Database connection established to %s", db_host)

# NEVER do this:
# logger.debug("Connecting with password=%s", password)
# logger.info("API key: %s", api_key)

```

## Detection Rule (Python SDK)

```python
from rules.python_decorators import python_rule
from codepathfinder import calls, QueryType

class LoggingModule(QueryType):
    fqns = ["logging"]


@python_rule(
    id="PYTHON-LANG-SEC-105",
    name="Logger Credential Leak Risk",
    severity="MEDIUM",
    category="lang",
    cwe="CWE-532",
    tags="python,logging,credentials,information-disclosure,CWE-532",
    message="Logging call detected. Audit log statements for credential/secret leakage.",
    owasp="A09:2021",
)
def detect_logger_cred_leak():
    """Detects logging calls — audit for credential leakage."""
    return LoggingModule.method("info", "debug", "warning", "error", "critical", "exception", "log")
```

## How to Fix

- Never log passwords, API keys, session tokens, or database connection strings
- Use structured logging with explicit field names so sensitive fields can be filtered by log pipelines
- Implement a log redaction layer that scrubs known secret patterns (Bearer tokens, AWS keys, passwords) before output
- Set production log level to INFO or WARNING to prevent debug-level credential logs from reaching production
- Review logging statements in code review with the same scrutiny as security-sensitive code

## Security Implications

- **Credential Exposure in Log Files:** Passwords, API keys, and tokens logged in plaintext persist in log files,
log aggregation services (ELK, Datadog, Splunk), and error tracking tools
(Sentry). Anyone with access to logs can extract credentials without
accessing the application database or config.

- **Compliance Violations:** PCI DSS explicitly prohibits logging authentication credentials (Requirement
8.5). GDPR and HIPAA require protecting personal data in all storage
locations including logs. A single logged password can result in a
compliance finding.

- **Lateral Movement via Log Access:** In cloud environments, log storage (CloudWatch, GCP Logging, Azure Monitor)
is often accessible to broader teams than application secrets. A credential
in a log file has a larger blast radius than one in a secrets manager.


## FAQ

**Q: Does this rule flag every logging call as a vulnerability?**

No. This is an audit rule. Most logging calls are harmless. It flags all
logging calls so you can review them for sensitive data. If the log message
only contains operational information (request IDs, timing, status codes),
it's fine.


**Q: How do I prevent credentials from appearing in logs?**

Use structured logging with explicit fields. Never interpolate secrets
into log messages. Implement a log filter that redacts patterns like
password=, Bearer, sk-, AKIA (AWS keys), etc.


**Q: What about exception logging that includes stack traces?**

Stack traces can expose local variable values, including secrets passed
as function arguments. Use logging.exception() carefully and consider a
custom exception handler that redacts sensitive variables.


**Q: Why is this MEDIUM severity?**

Logging credential exposure requires access to log files to exploit.
It's not directly exploitable from the network. However, in environments
with centralized logging (which is most production systems), the blast
radius can be significant.


**Q: How do I run this rule in CI/CD?**

Run: pathfinder ci --ruleset python/lang --project .


## References

- [CWE-532: Insertion of Sensitive Information into Log File](https://cwe.mitre.org/data/definitions/532.html)
- [OWASP Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html)
- [OWASP A09:2021 Security Logging and Monitoring Failures](https://owasp.org/Top10/A09_2021-Security_Logging_and_Monitoring_Failures/)
- [Python logging module documentation](https://docs.python.org/3/library/logging.html)

---

Source: https://codepathfinder.dev/registry/python/lang/PYTHON-LANG-SEC-105
Code Pathfinder — Open source, type-aware SAST with cross-file dataflow analysis
