Anti-CRLF Logging Formatter
logging-formatter-anticrlf is a Python logging Formatter designed to prevent CRLF Injection (CWE-93 / CWE-117) by sanitizing log messages. It ensures that newline characters and other control characters are properly escaped or removed, mitigating the risk of log forging attacks. The current version is 1.2.1, and it maintains a focused feature set with stable, infrequent releases.
Common errors
-
ModuleNotFoundError: No module named 'logging_formatter_anticrlf'
cause The `logging-formatter-anticrlf` library has not been installed in the current Python environment.fixInstall the package using pip: `pip install logging-formatter-anticrlf` -
AttributeError: module 'logging_formatter_anticrlf' has no attribute 'AntiCRLFFormatter'
cause Attempting to import the `AntiCRLFFormatter` class from an incorrect sub-module path.fixThe `AntiCRLFFormatter` class is directly available at the top-level package: `from logging_formatter_anticrlf import AntiCRLFFormatter`
Warnings
- gotcha The `AntiCRLFFormatter` primarily sanitizes the `message` field (and its arguments) that are processed by the formatter. If sensitive user input is directly included in other log record attributes (e.g., via the `extra` dict for custom fields) and those attributes are formatted directly by handlers or custom formatters, CRLF injection might still be possible.
- gotcha This formatter addresses CRLF injection on the *output* of log messages to a handler. It does not prevent other forms of log manipulation if the underlying logging system or storage mechanism is compromised, or if inputs are not properly validated *before* reaching the logger (e.g., if a database field storing log data already contains malicious content).
Install
-
pip install logging-formatter-anticrlf
Imports
- AntiCRLFFormatter
from logging_formatter_anticrlf.formatter import AntiCRLFFormatter
from logging_formatter_anticrlf import AntiCRLFFormatter
Quickstart
import logging
import sys
from logging_formatter_anticrlf import AntiCRLFFormatter
# Configure the logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Create a console handler
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
# Create an AntiCRLFFormatter and set it on the handler
# The formatter will sanitize the message before output
formatter = AntiCRLFFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Add the handler to the logger
logger.addHandler(handler)
# Test messages with potential CRLF injection
logger.info("This is a safe log message.")
logger.info("User input: %s", "username%0D%0Aevil_injection")
logger.warning("Another line for a multi-line attack: %s", "value\nmalicious")
# Expected output: Newlines and carriage returns will be replaced or escaped in the output.