Sobes.tech
Junior — Middle

Can you explain how SQL Injection attacks are carried out and how they exploit vulnerabilities in databases?

sobes.tech AI

Answer from AI

SQL Injection is a type of attack on databases where an attacker inserts (injects) malicious SQL code into input fields or query parameters to alter the execution logic of the SQL query.

How it works:

  • The application constructs an SQL query by directly inserting user input into the query string without validation.
  • The attacker inputs special SQL code that changes the structure of the query.
  • As a result, unauthorized access to data can be gained, or data can be modified or deleted.

Example of vulnerable Java code:

String query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);

If the username field is entered as admin' --, the query becomes:

SELECT * FROM users WHERE username = 'admin' --' AND password = ''

-- is a comment in SQL, and the rest is ignored, bypassing password verification.

To protect against SQL Injection:

  • Use prepared statements with parameterized queries.
  • Validate and sanitize user input.
  • Limit database access rights.

Example of secure code:

String query = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
Can you explain how SQL Injection attacks are carried… - sobes.tech