# Log Injection
**Log injection** is a type of *injection attack*. Injection attacks occur when maliciously crafted inputs are submitted by an attacker, causing an application to perform an unintended action. Log injection attacks occur when an attacker tricks the application into writing spurious or malicious entries in your log files.
Log files are important tool for seeing what an application is doing at runtime, reviewing events, and recording errors. Much of the data written to log files will come from untrusted sources – log entries will contain URLs accessed on the server or parameters passed in an HTTP request, for example. This affords an attacker an opportunity to inject spurious log entries (if newline characters are not handled appropriately) or inject malicious code that may prove harmful when the logs are viewed. Log injection is often used in tandem with other attacks as a way of disguising malicious activity on the server.
## Log Injection in Python
In Python, writing to the standard console log will not escape new line characters. That means that if you execute the following:
“`python print(“Hello\nworld”) “` |
…you will get two lines of output. Attackers will try to make use of this by inserting new line characters into the parameters in their HTTP requests to add extra lines of logging. They might, for instance, make HTTP requests to the URL `/login?\nUser+logged+out`, so that any code that logs the URL also prints the line `User logged out`. This can be helpful for an attacker if they want to disguise their tracks.
The best way to defuse log injection attacks is to use a logging module that will prefix each log line with extra meta-data like timestamp, process ID and hostname. These packages also have a multitude of other advantages: the verbosity of the logging can be set by configuration, and logs can be written in a structured format like JSON for easy processing by log management tools like Splunk and Logstash.
The built-in Python `logging` module can be used to achieve this end:
“`python import logging# Will print “WARNING:root:Watch out!” to the console. logging.warning(‘Warning message’) # Configure the logs to include the time and date. # Will prefix a timestamp with format “2010-12-12 11:41:42,612” to the log. |
## Malicious Content in Logs
An attacker can always control what is written to the logs by manipulating the HTTP request. A common attack vector is to inject HTML into log entries, in the hope that an administrator views the log files in a web application that does not properly escape HTML characters. If you make use of a tool to view logs or error reports, treat the contents of log files as untrusted input as you would the original HTTP request – or you could fall-foul of cross-site scripting attacks aimed at hijacking admin accounts.
## CWEs
* [CWE-117](https://cwe.mitre.org/data/definitions/117.html)