[SOLVED] How to allow newline characters but still prevent CRLF attack?

Issue

I’ve run a security scan at my server and got some CRLF exploitation warning.

So, as recommended, I’ve sanitized all my query parameter inputs like below.

var encodedStringSafeFromCRLF = Server.UrlDecode(Request.QueryString["address"])
                         .Replace("\r", string.Empty)
                         .Replace("%0d", string.Empty)
                         .Replace("%0D", string.Empty)
                         .Replace("\n", string.Empty)
                         .Replace("%0a", string.Empty)
                         .Replace("%0A", string.Empty);

Let’s say, a genuine user is sending an address to me via "address" query parameter.

Example –

https://mywebsite.com/details?instId=151711&address=24%20House%20Road%0aSomePlace%0aCountry

Since "%0A" will be stripped from the above string, the address would now become
’24HouseRoadSomePlaceCountry’ which was not my expectation.

How should I handle this ?
If I make code changes for CRLF this changes how the input is intrepreted.
If input string is not sanitized, then it would open my server for CRLF attack.

Any suggestions here ?

Solution

If you really need the user to supply data with CRLF sequences, then I would not filter those. As always, never trust user-supplied data in any way: do not use it to generate HTTP headers, responses or write to log files.

In general, it’s safer to filter the other way around: specify all the characters you are willing to accept, and filter out everything else.

If you need to write the data to a log, you could for example URL encode the data first, so that "naked" CR LF are never written there.

I might internally specify that I use just \n as the newline, and convert all \r, \n, and \r\n into just one representation \n internally. So the rest of the code does not have to handle all versions.

Answered By – Mikael Suokas

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *