Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitize $_GET parameters to avoid XSS and other attacks

I have a website in php that does include() to embed the content into a template. The page to load is given in a get parameter, I add ".php" to the end of the parameter and include that page. I need to do some security check to avoid XSS or other stuff (not mysql injection since we do not have a database). What I've come up with is the following.

$page = $_GET['page'];

if(!strpos(strtolower($page), 'http') || !strpos($page, '/') ||
    !strpos($page, '\\') || !strpos($page, '..')) {
        //append ".php" to $page and include the page

Is there any other thing I can do to furtherly sanitize my input?

like image 546
Federico klez Culloca Avatar asked Oct 19 '09 09:10

Federico klez Culloca


People also ask

Why we need sanitize the input to protect from XSS?

Why do we need Input Sanitization? Hackers use RFI (Remote File Inclusion) and injection attacks like Cross-Site Script (XSS) and SQL Injection (SQLi) to exploit the connection between websites and servers. They can execute unauthorized actions that can compromise security.

What is sanitization XSS?

HTML sanitization is an OWASP-recommended strategy to prevent XSS vulnerabilities in web applications. HTML sanitization offers a security mechanism to remove unsafe (and potentially malicious) content from untrusted raw HTML strings before presenting them to the user.

Is Htmlentities enough to prevent XSS?

htmlentities vs htmlspecialcharsBoth will prevent XSS attacks. The difference is in the characters each encodes. htmlentities will encode ANY character that has an HTML entity equivalent. htmlspecialchars ONLY encodes a small set of the most problematic characters.


2 Answers

$page = preg_replace('/[^-a-zA-Z0-9_]/', '', $_GET['page']);

Is probably the quickest way to sanitize this, this will take anything and make sure that it only contains letters, numbers, underscores or dashes.

like image 132
Mez Avatar answered Oct 06 '22 01:10

Mez


Don't "sanitize" - Attacks are specific to the use of data, not the source. Escape values as you output them instead. See also my answer to What’s the best method for sanitizing user input with PHP?

like image 21
troelskn Avatar answered Oct 06 '22 00:10

troelskn