2

I have a variable $filename that should be considered user input.

I use this $filename in the following:

header('Content-Disposition: inline; filename="' . $filename . '"');

How would one need to encode this to render $filename safe even when containing a payload?

Edit: From what I have been able to find so far, and what is provided by OWASP here, I may just need to filter all newline and form-feed characters? Looking for confirmation or additional info. Those being the only requirements, the following should be sufficient:

preg_replace('/[\f\r\n]/', '', $filename);

Edit: For this question assume validation has already been performed but a payload has made it through this without being rejected.

FamousAv8er
  • 2,345
  • 2
  • 9
  • 27
  • Ideally you should pre-check the filename, and if it doesn't conform to spec you reject it outright and fail the request. Less-ideally you delete the CR/LF chars from the string. – Sammitch Oct 09 '20 at 19:44
  • validate it for new lines, and/or replace whitespace with space, `-` or `_` etc, unless you're making a file manager where the user authenticates then you should make stricture filenames – Lawrence Cherone Oct 09 '20 at 19:45
  • @Sammitch wouldn't `preg_replace()` be preferred for matching the characters described? And is your comment a confirmation that this is all that is necessary? – FamousAv8er Oct 09 '20 at 19:45
  • There's no reason to use regular expressions for simple string/character matching. – Sammitch Oct 09 '20 at 19:46
  • @LawrenceCherone validation has been done when first accepting the `$filename`. If the validation was bypassed on the first run, it would happen here too so I am looking for encoding/sanitization options – FamousAv8er Oct 09 '20 at 19:46
  • If the validation has been bypassed then there's even _more_ reason to reject/fail at this point. Second-order injections exist, among many other security problems. When you assume that your data is safe is when you make mistakes and security holes. – Sammitch Oct 09 '20 at 19:48
  • @Sammitch I have not yet been able to bypass the validation. I am in the habit (what I feel is good practice) to encode/sanitize even validated user input when it is returned to the client. This is for in the event someone finds a way past the validation. – FamousAv8er Oct 09 '20 at 19:51
  • @Sammitch *not past validation but through the validation while still containing a payload – FamousAv8er Oct 09 '20 at 19:52
  • 1
    This RFC might give you some hints: https://tools.ietf.org/html/rfc6266. Also this one: https://tools.ietf.org/html/rfc5987 – Zoli Szabó Oct 09 '20 at 20:16
  • 1
    Also you can check popular projects that deal with HTTP header, for example here: https://github.com/amphp/http/blob/dfd33554b82a7d8f18cced56352bcc8270318dfe/src/Message.php#L214 – Zoli Szabó Oct 09 '20 at 20:31

0 Answers0