28.10.2014 Views

SQL Injection Attacks and Defense - 2009

SQL Injection Attacks and Defense - 2009

SQL Injection Attacks and Defense - 2009

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Code-Level <strong>Defense</strong>s • Chapter 8 355<br />

You can use a number of functions in PHP as the basic building blocks for building<br />

input validation, including the following:<br />

■■<br />

preg_match(regex, matchstring) Do a regular expression match with matchstring<br />

using the regular expression regex.<br />

■ ■ is_(input) Check whether the input is ; for example, is_numeric().<br />

■ ■ strlen(input) Check the length of the input.<br />

An example of using preg_match to validate a form parameter could be as follows:<br />

$username = $_POST['username'];<br />

if (!preg_match("/^[a-zA-Z]{8,12}$/D", $username) {<br />

// h<strong>and</strong>le failed validation<br />

}<br />

Encoding Output<br />

In addition to validating input received by the application, it is often necessary to also<br />

encode what is passed between different modules or parts of the application. In the context<br />

of <strong>SQL</strong> injection, this is applied as requirements to encode, or “quote,” content that is sent<br />

to the database to ensure that it is not treated inappropriately. However, this is not the only<br />

situation in which encoding may be necessary.<br />

An often-unconsidered situation is encoding information that comes from the database,<br />

especially in cases where the data being consumed may not have been strictly validated or<br />

sanitized, or may come from a third-party source. In these cases, although not strictly related<br />

to <strong>SQL</strong> injection, it is advisable that you consider implementing a similar encoding approach<br />

to prevent other security issues from being presented, such as XSS.<br />

Encoding to the Database<br />

Even in situations where whitelist input validation is used, sometimes content may not<br />

be safe to send to the database, especially if it is to be used in dynamic <strong>SQL</strong>. For example,<br />

a last name such as O’Boyle is valid, <strong>and</strong> should be allowed through whitelist input<br />

validation. This name, however, could cause significant problems in situations where this<br />

input is used to dynamically generate an <strong>SQL</strong> query, such as the following:<br />

String sql = "INSERT INTO names VALUES ('" + fname + "','" + lname + "');"<br />

Additionally, malicious input into the first name field, such as:<br />

',''); DROP TABLE names--<br />

could be used to alter the <strong>SQL</strong> executed to the following:<br />

INSERT INTO names VALUES ('',''); DROP TABLE names--','');

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!