Skip to main content

logging Formatter to sanitize CRLF errors (CWE-93, some forms of CWE-117)

This class is a drop-in replacement for logging.Formatter, and has the exact same construction arguments. However, as a final step of formatting a log line, it escapes carriage returns (\r) and linefeeds (\n).

By default, these are replaced with their escaped equivalents (see Examples), but the replacements dictionary can be modified to change this behavior.

This sanitization should solve CWE-93 errors and CRLF-based versions of CWE-117. Some CWE-117 errors are concerns about e.g. XSS flaws in logs that are likely to be viewed in a browser; this formatter can’t handle every form of CWE-117.

Installation

pip install logging-formatter-anticrlf

Examples

import sys
import logging
import anticrlf

handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(anticrlf.LogFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

logger.info("Example text with a newline\nhere")

This results in:

2017-02-03 08:43:52,557 - __main__ - INFO - Example text with a newline\nhere

Whereas with the default Formatter, it would be:

2017-02-03 08:43:52,557 - __main__ - INFO - Example text with a newline
here

If you wanted newlines to be replaced with \x0A instead, you could:

formatter = anticrlf.LogFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter.replacements["\n"] = "\\x0A"  # Note the double backslash for literal!
handler.setFormatter(formatter)

Changing Replacements

The replacements field of the formatter is a SubstitutionMap object that behaves like a dict with a few exceptions designed to help developers avoid making insecure mistakes.

Specifically:

  • an “empty” SubstitutionMap object will contain the default mappings for CR and LF chars

  • calling del on either the CR or LF key will reset the value rather than delete the key

  • any attempt to create a key-value pair that results in any value containing any of the keys will raise an UnsafeSubstitutionError

The rationale for the last item is that the keys of the replacements field are strings that are considered unsafe. Replacing one unsafe string with another defeats the purpose of using this module.

Additionally, if you assign a regular dict to the replacements field, and try to log something using that configuration, anticrlf.LogFormatter will reset the replacements field to its default value and issue a UserWarning to that effect.

That means the following:

formatter.replacements["\n"] = "\\x0A"  # replace LF chars with '\x0A'
del formatter.replacements["\n"]        # return to replacing LF with '\n'
formatter.replacements["\t"] = "\\t"    # replace tabs with '\t'
formatter.replacements["\n"] = "<\t>"   # raises UnsafeSubstitutionError

The last occurs because the value <\t> contains \t, which was previously created as a key.

And:

formatter.replacements = { "\n": "\r" }  # this is a mistake!
logger.info("example")

Will result, if that logger is using that formatter, in replacements being returned to its safe default value and a UserWarning about that being issued.

Metadata

Release files for logging-formatter-anticrlf 1.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for logging-formatter-anticrlf 1.2.1
File Size Uploaded Provenance
logging-formatter-anticrlf-1.2.1.tar.gz 7.2 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for logging-formatter-anticrlf 1.2.1
File Interpreter ABI Platform
logging_formatter_anticrlf-1.2.1-py3-none-any.whl Python 3 none any Details

Total release size: 14.8 kB

Release files / logging-formatter-anticrlf-1.2.1.tar.gz

Download URL logging-formatter-anticrlf-1.2.1.tar.gz
Size 7.2 kB
Tags Source
SHA-256 checksum
How to use checksums
3323445c7f2a159cae7ec8395fc3f9838954314b737dd25d790e8ae2847bd2b5
BLAKE2b-256 checksum
How to use checksums
e592e0f174775f91bbfa81ee12f495e5e32495712bb2382589bfa7dbf8278250
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.5

Release files / logging_formatter_anticrlf-1.2.1-py3-none-any.whl

Download URL logging_formatter_anticrlf-1.2.1-py3-none-any.whl
Size 7.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cafaaeeb9b2a9e5dbf41b3b9d594ab10a83844afafabeebf34b17b505ca62536
BLAKE2b-256 checksum
How to use checksums
f69fad0d7783f98fa50ca17eb335acc59a4e49a11314e1d534112b1217f4b6ed
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.5

Security for logging-formatter-anticrlf 1.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page