Last active
June 28, 2018 10:44
-
-
Save zhangysh1995/168d5ca899c7292a17eb6766eb23ea22 to your computer and use it in GitHub Desktop.
Defense SQL Injection in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
these code are from WebGoat by OWASP: | |
Link: WebGoat/start.mvc#lesson/SqlInjectionMitigations.lesson/ | |
**/ | |
// parameterized queries | |
/** | |
First version | |
**/ | |
public static bool isUsernameValid(string username) { | |
RegEx r = new Regex("^[A-Za-z0-9]{16}$"); | |
return r.isMatch(username); | |
} | |
// java.sql.Connection conn is set elsewhere for brevity. | |
PreparedStatement ps = null; | |
RecordSet rs = null; | |
try { | |
pUserName = request.getParameter("UserName"); | |
if ( isUsernameValid (pUsername); | |
ps = conn.prepareStatement("SELECT * FROM user_table | |
WHERE username = ? "); | |
ps.setString(1, pUsername); | |
rs = ps.execute(); | |
if ( rs.next() ) { | |
// do the work of making the user record active in some way | |
} | |
} else { // handle invalid input } | |
} | |
catch (…) { // handle all exceptions … } | |
/** | |
Second version | |
**/ | |
public static String loadAccount() { | |
// Parser returns only valid string data | |
String accountID = getParser().getStringParameter(ACCT_ID, ""); | |
String data = null; | |
String query = "SELECT first_name, last_name, acct_id, balance FROM user_data WHERE acct_id = ?"; | |
try (Connection connection = null; | |
PreparedStatement statement = connection.prepareStatement(query)) { | |
statement.setString(1, accountID); | |
ResultSet results = statement.executeQuery(); | |
if (results != null && results.first()) { | |
results.last(); // Only one record should be returned for this query | |
if (results.getRow() <= 2) { | |
data = processAccount(results); | |
} else { | |
// Handle the error – Database integrity issue | |
} | |
} else { | |
// Handle the error – no records found } | |
} | |
} catch (SQLException sqle) { | |
// Log and handle the SQL Exception } | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment