This example uses the Tainting Checker to verify that user input does not contain SQL statements, thus preventing SQL injection.
To begin, load the personalblog-demo project into Eclipse. (Download it here.) The project has two warnings that can be ignored.
This example has already been annotated to prevent the SQL
injections. It does this by annotating
PersonalBlogService.executeQuery(String)
with
@Untainted
and providing a method,
ReadAction.validate(String)
, to validate the user
input.
Run the Tainting Checker on the entire src
folder.
The following warning will be produced.
incompatible types in argument. "where post.category like '%", category, found : @Tainted String required: @Untainted String PersonalBlogService.java
The checker issues an error for getPostsByCategory()
because the possibly-tainted string category
is used in
the query construction. This string could contain SQL statements
that could taint the database. The programmer must ensure that
category
does not contain malicious SQL code.
To correct this error, add @Untainted
to the
type of the category
parameter.
public List<?> getPostsByCategory(@Untainted String category) throws ServiceException {This forces clients to pass an
@Untainted
value, which
was the intention of the designer of the getPostsByCategory
method.
Run the Tainting Checker again.
incompatible types in argument. pblog.getPostsByCategory(reqCategory)); found : @Tainted String required: @Untainted String ReadAction.java
There is an error in ReadAction.executeSub()
, which
is a client of getPostsByCategory
. The
reqCategory
is accepted from the user (from request
object) without validation.
validate
method as shown below.
String reqCategory = validate(cleanNull(request.getParameter("cat")));
There should be no errors.
For a complete discussion of how to use the Tainting Checker, please read the Tainting Checker chapter in the Checker Framework manual.