SQL injection (SQLi) is a simple yet dangerous vulnerability.

It’s simple because it’s easily preventable.

It’s dangerous because your data will be stolen, your database will be dropped, and your job will be lost.

Any app that uses a SQL database, which is the majority of them, could be vulnerable to it.

SQLi

To interact with a SQL database, you write queries.

Many of them aren’t fixed.

They depend on user inputs.

For example, this query depends on two variables: username and password.

They are user inputs that usually come from the frontend.

Like a login page.

A flow typical flow is:

  1. User fills in the form

  1. Frontend sends that data to the backend

  1. Backend creates a SQL query

Okay. What if we put something weird in the form?

Like an extra quote after the password (1234’):

A syntax error occurs.

So we can change the SQL query with our input.

How can we exploit that?

If you put something like this in the form.

It will create a query that always returns true:

You can now log in to anyone’s account without knowing their password.

Preventing SQLi

To prevent the vulnerability, you need to know what went wrong.

Usually, SQLi occurs when the developer creates a raw SQL query using string concatenation, like this:

const query = "SELECT * FROM USERS " +
"WHERE username = '" + username + "' " +
"AND password = '" + password + "'";

Or this:

const query = `SELECT * FROM USERS
WHERE username = ${username}
AND password = ${password}`

Bad idea. Instead, use a prepared statement.

A prepared statement is like a function parameter.

You pass arguments into the SQL query when it’s run, which looks like this:

By doing that, the database will be able to interpret the values as literal data rather than SQL code.

Fee from Anime Coders

Login or Subscribe to participate

Keep Reading

No posts found