SQL injections in URLs and ways to avoid them

SQL injection is the process of attacking a database with malicious scripts. If we are not careful while writing secure URL routes, there may be an opportunity for SQL injection. These attacks usually happen for the POST, PUT, and DELETE HTTP verbs. For example, if we are allowing the client to pass variables to the server, then there is a chance for an attacker to append a string to those variables. If we are inserting those users sending parameters directly into an SQL query, then it could be injectable. The right way to talk to DB is to allow driver functions to check the parameters before inserting the string and executing it in the database:

username := r.Form.Get("id")
password := r.Form.Get("category")
sql := "SELECT * FROM article WHERE id='" + username + "' AND category='" + password + "'"
Db.Exec(sql)

In this snippet, we are trying to get information about an article by id and category. We are executing an SQL query. But since we are appending the values directly, we may include malicious SQL statements like (--) comments and (ORDER BY n) range clauses in the query:

?category=books&id=10 ORDER BY 10--

This will leak information about columns the table has. We can change the number and see the breaking point where we get an error message from the database saying:

Unknown column '10' in 'order clause'

 We will see more about this in our upcoming chapters, where we build full-fledged REST services with other methods, like POST, PUT, and so on:

Now, how to avoid these injections. There are a few ways:

  • Set the user level permissions to various tables
  • While using URL parameters, carefully observe the pattern
  • Use the HTMLEscapeString function from Go's text/template package to escape special characters in the API parameters, like body and path 
  • Use a driver program instead of executing raw SQL queries
  • Stop database debug messages getting relayed back to the client
  • Use security tools like sqlmap to find out vulnerabilities
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.117.214