Search code examples
phpsecuritypreg-replacecsrfbbcode

Images with BBcode (php, preg_replace). Security question


Bbcode question. This:

$text = preg_replace("@\[img\](.*)\[\/img\]@si",
"<img src=\"$1\" border=\"0\" />", $text);

works fine, but at the same time it's a big security problem, for example:

[img]http://www.domain.com/delete-account/[/img]

or

[img]http://www.domain.com/logout/[/img]

Any ideas how to control this so that only image links which ends with .jpg are being converted into html?

[img]http://www.domain.com/image.jpg[/img]

Thanks.


Solution

  • According to the HTTP1.1 standard, requesting URLs with GET (the method used to acquire images) should not result in any actions, such as logout. Therefore, you don't need to restrict to URLs with a .jpg at the end, and in general, it is a bad idea because there are other image formats, and the URL is in general unrelated to its content type.

    More to the point, if requesting a URL does change a state of a server vulnerable.net, this Cross Site Request Forgery Vulnerability can be exploited anyway by setting up a custom server that 302-redirects http://evil.com/img.jpg to http://vulnerable.net/logout.

    FYI, if you really wanted to replace only URLs ending with .jpg, you can just insert it in the group:

    $text = preg_replace("@\[img\](.*\.jpg)\[\/img\]@si",
                         "<img src=\"$1\" border=\"0\" />", $text);
    

    But this is not a security mechanism, and fails if the browser (or a aggressively caching proxy, or a virus scanner, or ...) prefetches URLs. GET requests should not result in any action.