21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

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.

Finally, if you are using the LIKE keyword in a WHERE clause, you may wish to prevent<br />

input from containing wildcard characters. In fact, it is a good idea to prevent<br />

wildcard characters in most circumstances. Wildcard characters include the<br />

percent symbol, underscore, and square brackets.<br />

You can use the function spc_escape_sql( ), shown at the end of this section, to<br />

escape all of the characters that we’ve mentioned. As a convenience (and partly due<br />

to necessity), the function will also surround the escaped string with the quote character<br />

of your choice. The return from the function will be the quoted and escaped<br />

version of the input string. If an error occurs (e.g., out of memory, or an invalid quoting<br />

character chosen), the return will be NULL.<br />

spc_escape_sql( ) requires three arguments:<br />

input<br />

The string that is to be escaped.<br />

quote<br />

The quote character to use. It must be either a single or double quote. Any other<br />

character will cause spc_escape_sql( ) to return failure.<br />

wildcards<br />

If this argument is specified as 0, wildcard characters recognized by the LIKE<br />

operator in a WHERE clause will not be escaped; otherwise, they will be. You<br />

should only escape wildcards when you are going to be using the escaped string<br />

as the right-hand side for the LIKE operator.<br />

#include <br />

#include <br />

char *spc_escape_sql(const char *input, char quote, int wildcards) {<br />

char *out, *ptr;<br />

const char *c;<br />

/* If every character in the input needs to be escaped, the resulting string<br />

* would at most double in size. Also, include room for the surrounding<br />

* quotes.<br />

*/<br />

if (quote != '\'' && quote != '\"') return 0;<br />

if (!(out = ptr = (char *)malloc(strlen(input) * 2 + 2 + 1))) return 0;<br />

*ptr++ = quote;<br />

for (c = input; *c; c++) {<br />

switch (*c) {<br />

case '\'': case '\"':<br />

if (quote == *c) *ptr++ = *c;<br />

*ptr++ = *c;<br />

break;<br />

case '%': case '_': case '[': case ']':<br />

if (wildcards) *ptr++ = '\\';<br />

*ptr++ = *c;<br />

break;<br />

case '\\': *ptr++ = '\\'; *ptr++ = '\\'; break;<br />

Preventing SQL Injection Attacks | 109<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!