Can input written to a file be maliciously tampered?

后端 未结 6 1518
野趣味
野趣味 2021-01-12 23:42

Uber simple example to illustrate the point:

$message = $_POST[\'message\'];

$fp = fopen(\"log.txt\", \"a\");
fwrite($fp, $message);

fclose($fp);
         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-13 00:06

    • You append to a file in the current directory - this seems to be downloadable via browser, so you're creating a security hole. Place the file outside of the document root (best), or protect it via .htaccess.
    • You should sanitize all user input. Always. What this means depends on how you use this data. You seem to write to a text logfile, so you would want to let only printable and whitespace-class chars through. Sanitize defensively: do NOT specify bad charcodes and let everything else through, but define a list/classes of "good" chars and just let these good chars through.
    • Depending on your use case, you may want to flock() the log file, to prevent multiple parallel requests from mixing up in your file:

      $logtext = sanitizeLog($_POST[Message']); $fd = fopen( "/path/to/log.txt", "a"); if(flock($fd, LOCK_EX)) { fseek($fd, 0, SEEK_END); fwrite($fd, $logtext); flock($fd, LOCK_UN); } fclose($fd);

    I've omitted checks for fopen() results...

提交回复
热议问题