Sanitize user queries before logging them to console
13 try {
14 const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/contributors`);
15 if (!response.ok) {
16 console.error('Failed to fetch contributors:', response.statusText);17 return;
18 }
19 const data = await response.json();
Description
Logs serve as important records that are used by monitoring services and developers to investigate incidents. Logging unsanitized user input to the server allows the user to forge custom server logs.
In some more serious scenarios, it opens the application up to attacks like spoofing. The attacker may insert a line break in the request object, and make the second line of their log look like a log from a different user, or an info message displayed by the server.
Bad Practice
import http from "http"
import url from "url"
http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true)
// Vulnerable! user can inject special characters in the terminal
console.log(parsedUrl.query.username);
})
Recommended
import http from "http"
import url from "url"
http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true)
// NOTE: Ideally, stronger sanitization functions should be used.
// String#replace is only used as an example.
const username = parsedUrl.query.username.replace(/\n|\r/g, "")
console.log(parsedUrl.username);
})