SQL query cleaning macro

Just for a bit of fun I was trying to write something in rust that would sanitize input for an SQL query. I was trying to write it like the format macro like this.

let my_query: String = query!("SELECT * FROM user WHERE id = {} AND username = {} ",some_i32, some_String);

Is it possible to write a macro_rules! called query that can depending on the type passed to it run a function to make sure that type has been sanitized. If it is possible can someone point me at how to do it for one type ?

Can

I believe this fits your requirements. It even uses a query! macro :smiley:

2 Likes

Not sure what you mean by "making sure that the type has been sanitized".

  • Do you want to typecheck SQL queries? That's a hard problem – not even DBMSs do that. You'll need to parse the SQL, resolve the underlying schema, and write a full type checker.
  • Do you want to prevent SQL injection? Then don't try to "sanitize" anything, it doesn't work. Use prepared statements and parameter placeholders instead.
1 Like

I'm not trying to type check an already generated sql query I'm trying to create an API that isn't possible to write queries that are vulnerable to sql injection,

So my example here

let my_query: String = query!("SELECT * FROM user WHERE id = {} AND username = {} ",some_i32, some_String);

I have 2 types that get passed in possibly from a user an i32 and a String. In theory the i32 cant be used for sql injection. The string can be dangerous so needs to be sanitize, which is gernally just escape single quotes with another single quote.

Currently have a largish code base in C++ with stuff like this. If we forget to use the sanitize() on the string types we are vulnerable but there is no way to enforce it. What I would like to do is try and show an API that is completely impossible to get wrong as the default behaviour is safe.

let my_query: String = query!("SELECT * FROM user WHERE id = {} AND username = {} ", some_i32, sanitize(some_String));

It's more for a bit of fun learning how i would write this. @Deaths-Door looks very much like what i want. Now just need to learn how it works.

As already pointed out by others you want to use prepared statements for this. They essentially "just" send the query parameters as separate thing to the database, which in turn sidesteps any possible injection problems as that just cannot happen anymore.

See the corresponding OWASP page for details.

2 Likes

The API you're looking for are prepared statements.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.