sqlrestsql-injection

Prevent SQL injection when SQL is supplied from the request


The company I am working at uses a REST API for database accesses. So basically, you just provide a SQL statement string and the REST API returns a Datatable. Now I am unsure as to how to prevent an SQL injection as I cannot generate the SQL command using parameters (as I normally would) since I have to provide a SQL statement string for the REST API.


Solution

  • The only way to make this safe is to define an allowlist a specific list of SQL queries that are pre-vetted. The REST API would compare the input to the whitelist. If the SQL query is one of the known queries in the whitelist, then it can run. Otherwise, the API returns an error status (I'd use 400 BAD REQUEST).

    But I suppose the purpose of the API is to run any SQL statement the client inputs, verbatim. This is literally an SQL injection vulnerability by design. There is no way to make that not SQL injection.

    Besides that, the API really goes against the conventions of a RESTful web service.

    You don't have a REST API. You have a web service with no specific interface.

    The presence of a "query anything" API should be a huge red flag. It's probably a sign that the project isn't specified well in other ways.