Best Way to Defend Against MySQL Injection and Cross Site Scripting

Best way to defend against mysql injection and cross site scripting

Just doing a lot of stuff that you don't really understand, is not going to help you. You need to understand what injection attacks are and exactly how and where you should do what.

In bullet points:

  • Disable magic quotes. They are an inadequate solution, and they confuse matters.
  • Never embed strings directly in SQL. Use bound parameters, or escape (using mysql_real_escape_string).
  • Don't unescape (eg. stripslashes) when you retrieve data from the database.
  • When you embed strings in html (Eg. when you echo), you should default to escape the string (Using htmlentities with ENT_QUOTES).
  • If you need to embed html-strings in html, you must consider the source of the string. If it's untrusted, you should pipe it through a filter. strip_tags is in theory what you should use, but it's flawed; Use HtmlPurifier instead.

See also: What's the best method for sanitizing user input with PHP?

CSRF, XSS and SQL Injection attack prevention in JSF

XSS

JSF is designed to have builtin XSS prevention. You can safely redisplay all user-controlled input (request headers (including cookies!), request parameters (also the ones which are saved in DB!) and request bodies (uploaded text files, etc)) using any JSF component.

<h:outputText value="#{user.name}" />
<h:outputText value="#{user.name}" escape="true" />
<h:inputText value="#{user.name}" />
etc...

Note that when you're using JSF 2.0 on Facelets, then you can use EL in template text like so:

<p>Welcome, #{user.name}</p>

This will also implicitly be escaped. You don't necessarily need <h:outputText> here.

Only when you're explicitly unescaping user-controlled input using escape="false":

<h:outputText value="#{user.name}" escape="false" />

then you've a potential XSS attack hole!

If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>, <i>, <u>, etc, then you need to sanitize the input by a whitelist. The HTML parser Jsoup is very helpful in this.

itemLabelEscaped bug in Mojarra < 2.2.6

Older Mojarra versions before 2.2.6 had the bug wherein <f:selectItems itemLabel> incorrectly renders the label unescaped when provided a List<T> via <f:selectItems var> instead of List<SelectItem> or SelectItem[] as value (issue 3143). In other words, if you're redisplaying user-controlled data as item labels via a List<T>, then you've a potential XSS hole. If upgrading to at least Mojarra 2.2.6 is not an option, then you need to explicitly set itemLabelEscaped attribute to true to prevent that.

<f:selectItems value="#{bean.entities}" var="entity" itemValue="#{entity}"
itemLabel="#{entity.someUserControlledProperty}" itemLabelEscaped="true" />

CSRF

JSF 2.x has already builtin CSRF prevention in flavor of javax.faces.ViewState hidden field in the form when using server side state saving. In JSF 1.x this value was namely pretty weak and too easy predictable (it was actually never intended as CSRF prevention). In JSF 2.0 this has been improved by using a long and strong autogenerated value instead of a rather predictable sequence value and thus making it a robust CSRF prevention.

In JSF 2.2 this is even be further improved by making it a required part of the JSF specification, along with a configurable AES key to encrypt the client side state, in case client side state saving is enabled. See also JSF spec issue 869 and Reusing ViewState value in other session (CSRF). New in JSF 2.2 is CSRF protection on GET requests by <protected-views>.

Only when you're using stateless views as in <f:view transient="true">, or there's somewhere a XSS attack hole in the application, then you've a potential CSRF attack hole.


SQL injection

This is not JSF's responsibility. How to prevent this depends on the persistence API you're using (raw JDBC, modern JPA or good ol' Hibernate), but all boils down that you should never concatenate user-controlled input into SQL strings like so

String sql = "SELECT * FROM user WHERE username = '" + username + "' AND password = md5(" + password + ")";
String jpql = "SELECT u FROM User u WHERE u.username = '" + username + "' AND u.password = md5('" + password + "')";

Imagine what would happen if the enduser chooses the following name:



x'; DROP TABLE user; --

You should always use parameterized queries where applicable.

String sql = "SELECT * FROM user WHERE username = ? AND password = md5(?)";
String jpql = "SELECT u FROM User u WHERE u.username = ?1 AND u.password = md5(?2)";

In plain JDBC you need to use PreparedStatement to fill the parameter values and in JPA (and Hibernate), the Query object offers setters for this as well.

PHP and PostgreSQL: Avoiding cross-site scripting and SQL injection attacks

To avoid SQL injection, you want to call methods that accepts SQL parameters as method parameters. That way, your SQL library can make sure that the parameters are properly escaped. Never build your own SQL-statements by "appending" string-fragments. If you do, you are responsible for SQL-escaping the parameters. This is hard to get right.

Therefore, you should prefer pg_query_params (or pg_insert) over pg_query.

This is wrong (because you must remember to escape the $arg1-parameter. Which is hard.):

pg_query("INSERT INTO TABLE ... VALUES " . $arg1 . ";");

Right (because the smart guys at PostgresQL know how to escape your parameter):

pg_query_params("INSERT INTO TABLE ... VALUES $1", "FooBar");

A PHP function to prevent SQL Injections and XSS

mysql_real_escape_string() doesn't prevent XSS. It will only make impossible to do SQL injections.

To fight XSS, you need to use htmlspecialchars() or strip_tags(). 1st will convert special chars like < to < that will show up as <, but won't be executed. 2nd just strip all tags out.

I don't recommend to make special function to do it or even make one function to do it all, but your given example would work. I assume.

Ways I can protect my site excluding XSS and Sql injection?

There is a lot that can go wrong with a web application. Other than XSS and SQLi, there is:

  1. CSRF - Cross Site Request Forgery
  2. LFI/RFI - Local File Include/Remote File Include caused by include(), require()...
  3. CRLF injection in mail()
  4. Global Variable Namespace Poising commonly caused by register_globals,extract(), import_request_variables()
  5. Directory Traversal: fopen(), file_get_contents(), file_put_conents()
  6. Remote Code Execution with eval() or preg_replace() with /e
  7. Remote Code Execution with passthru(), exec(), system() and ``

There is a whole family of vulnerabilities regarding Broken Authentication and Session Management which is apart of the OWASP Top 10 that every web app programmer must read.

A Study In Scarlet is a good black paper that goes over many of these vulnerabilities that I have listed.

However, there are also strange vulnerabilities like this one in Wordpress. The definitive authority on what is a vulnerability is the CWE system which classifies HUNDREDS of vulnerabilities, many of which can affect web applications.

Is sql injection and cross-site scripting still a thing?

I'll tell a story.

My mother used to volunteer with a group to go to the local college campus to help students register to vote (in the US, people can vote at age 18, but they aren't registered by default, they have to fill out a form). She and her group would set up a table in the quad with a supply of forms and guide the students to fill it out and mail it in.

After years of doing this, one of the other women in the group said, "We've been coming onto campus to help these kids register for TEN YEARS! When are they going to be able to do it on their own?"

My mom and the others looked at her and said slowly, "There is a new set of students turning 18 years old every year."

The same thing is true for defense against SQL injection and Cross-Site Scripting. There are new programmers entering the profession every year.

In fact, studies show that the number of software developers doubles every five years, which means at any given time, 50% of software developers are what I would consider "junior developers" with less than five years of experience. By the time those people have become senior developers, there's again just as many younger developers who have entered the profession after them.

All of them need to be trained to understand SQL injection and Cross-Site Scripting defense before they should be allowed to put their code on a live server.

One at a time.

Every year.

SQL injection and Cross-Site scripting will continue to be a thing as long as there are software developers.


I also can reference the SQLi Hall-of-Shame, a web page that references news stories about data breaches perpetrated by exploiting SQL injection vulnerabilities. The seem to be multiple such stories every month, and these are just the break-ins that made the news. It's undoubtedly the tip of the iceberg.



Related Topics



Leave a reply



Submit