- Published on
Java Security - Part 14: Preventing common security vulnerabilities in Java (SQL injection, cross-site scripting)
- Authors
- Name
- Gary Huynh
- @huynhthienthach
Arr matey! Strap yourself to the mast, 'cause we're about to brave the stormy seas of common security vulnerabilities in Java
. We've got two notorious scoundrels on our hands: SQL injection
and cross-site scripting (XSS)
. These two be as infamous in the coding world as Blackbeard and Captain Kidd be in the high seas!
First up, SQL Injection
, the bane of databases across the Seven Seas! This happens when you create a SQL query
by concatenating user input directly into the query. Like this:
String query = "SELECT * FROM users WHERE username = '" + userInput + "'";
If someone enters ' OR '1'='1
, that turns the query into SELECT * FROM users WHERE username = '' OR '1'='1'
, which returns all users. Yarrr, that be a disaster!
Instead, use a PreparedStatement
. This be like making your parrot deliver the message instead of shouting it out for the whole crew to hear:
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, userInput);
ResultSet results = pstmt.executeQuery();
The '?' in the query is a placeholder, and we're setting its value using setString()
. This way, no matter what the user input be, it can't change the structure of the query.
Now, let's set our spyglass on Cross-Site Scripting (XSS)
. This be when someone tricks your site into running malicious JavaScript. Let's say you have a comment section on your site and you display comments like this:
out.println("<h2>" + userComment + "</h2>");
If some scurvy dog enters <script>/* bad stuff */</script>
as their comment, you're in for a nasty surprise! To prevent this, escape user input before displaying it. Most modern Java web frameworks
do this for you, but if you're writing your own HTML:
out.println("<h2>" + escapeHtml(userComment) + "</h2>");
This will replace <
with <
, >
with >
, and so on. The trick is to treat all user input as untrustworthy - assume it's a mutinous crew member waiting for the right moment to pounce!
Keep these lessons in mind, and you'll ward off the threats of SQL injection and XSS
like a seasoned sea dog fending off a kraken. Yarrr!