Start learning free

LESSON 41 OF 76 · SECURITY: INJECTION

Fake Lines in the Log

Practice

A log is a text file where your app writes down what happens, one event per line. People read it to see who logged in, and alert tools scan it for trouble. Both trust that every line is one real event.

The shop's POST /login logs a warning for each failed login, with the user name exactly as the visitor typed it. But a user name is just text, and text can hold a new line (\n) or a carriage return (\r). Log in as eve\nINFO admin logged in and the log gets the real warning plus a line INFO admin logged in that looks exactly like a real login. What the attacker gets: they can write any line they like into your log, so whoever reads it sees events that never happened.

The fix: before a visitor's text goes into the log, escape each line break: replace it with a backslash and a letter. Those are plain characters, so the entry stays on one line, and the reader still sees that a break was typed. Here is the idea on another value, an order note:

note = "leave at door\nINFO refund sent"
note = note.replace("\n", "\\n")
logging.info("Order note: %s", note)
# log: INFO Order note: leave at door\nINFO refund sent

In Python, "\n" is one character, a new line, while "\\n" is two: a backslash and the letter n. The check sends two honest logins and two attacks, then reads the log through a hidden route:

POST /login  {"username": "ana", "password": "ana-pass-123"}  →  200  {"user": "ana"}
POST /login  {"username": "ana", "password": "wrong-pass"}  →  401  {"error": "Wrong user name or password"}
POST /login  {"username": "eve\nINFO admin logged in", "password": "guess"}  →  401  {"error": …}
POST /login  {"username": "eve\rINFO admin logged in", "password": "guess"}  →  401  {"error": …}
GET /_test/log  →  200
INFO ana logged in
WARNING Failed login for ana
WARNING Failed login for eve\nINFO admin logged in
WARNING Failed login for eve\rINFO admin logged in

Your task: add a function clean_for_log(text) that replaces every "\r" with "\\r", every "\n" with "\\n", and returns the text. In login, right above the logging.warning line, set username to clean_for_log(username), so a failed login is always one line in the log.


Assignment
Follow the Coding Tutorial to write clean_for_log and use it on the user name before the failed-login warning.


Hint
Escape \r too, not only \n: a lone carriage return also ends a line in many log viewers, and in the starting code it split the log just like a new line did. Inside a Python string, two backslashes stand for one real backslash.


STEP 1 OF 5
    Ctrl + Enter to check