Log injection through unhandled line breaks

Log injection

Description

Python’s logging substitutes arguments into the message. A %s placeholder preserves carriage returns (\r) and line feeds (\n) in the supplied value, so a line-oriented collector may read one event as several.

Potential impact

Extra records can give a false impression of severity or sequence, disrupt SIEM alerts and delay an investigation.

Remediation

  • For text logs, replace CR and LF in untrusted messages and arguments before formatting. A fixed allow-list works for fields whose permitted values are all trusted, single-line literals. Length or format checks alone can leave delimiters intact.
  • For structured logs, choose a formatter that emits one record per event. With json.dumps, use trusted options and omit indent. The default encoder escapes control characters U+0000 through U+001F inside strings.
  • Render log values as text in a web viewer, or encode them for the HTML output context.

Examples

Before

python
import logging
from flask import Flask, request

app = Flask(__name__)

@app.route('/search')
def search():
    term = request.args.get('term', '')
    # CR/LF in term remains even with separate formatting arguments.
    logging.info("Search term: %s", term)
    return "ok"

After

CR/LF replacement

python
import logging
from flask import Flask, request

app = Flask(__name__)

@app.route('/search')
def search_safe():
    term = request.args.get('term', '')
    safe_term = term.replace("\r", " ").replace("\n", " ")
    logging.info("Search term: %s", safe_term)
    return "ok"

Compact JSON serialization

python
import json
import logging
from flask import request

def log_search():
    term = request.args.get('term', '')
    logging.info(json.dumps({"event": "search", "term": term}))

The text example replaces both delimiters in term with spaces. The JSON example serializes the event and term together on one line.

Usage considerations

Check the final handler and collector output to confirm that each search event occupies one record.

References