Do es6 template literals, when used to construct queries, protect against SQL injection? Can you provide some examples of common attacks and how they would be mitigated?
More specifically, I plan to use the mssql module in a node project. In their documentation under the template literals section it says "All values are automatically sanitized against SQL injection". Is this true purely because of how ES6 template literals work?
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.
Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.
A prepared statement is a parameterized and reusable SQL query which forces the developer to write the SQL command and the user-provided data separately. The SQL command is executed safely, preventing SQL Injection vulnerabilities.
Using the template literal for the HTML is definitely more readable by reducing the annoyance. Your string can span multiple lines. You don't have to escape quotation characters. You don't have to use the plus operator.
No, ES6 template literals are just another way to build strings and don't protect you against SQL injections if you were to use them to build raw SQL queries from supplied user input without additional filtering / escaping:
let name = "Robert'; DROP TABLE Students;--"; // user supplied input
let sql = `SELECT * FROM Students WHERE name = '${name}'`; // build query...
console.log(sql); // Injected SQL!
Yes, but only if you use an appropriate tag. When you use tags, it's called a Tagged Template Literal though. The tag goes right before the first backtick.
You can use sql.query
by node-mssql as a tag or https://github.com/TehShrike/sql-tagged-template-literal
const SQL = require('sql-template-strings');
let name = "Robert'; DROP TABLE Students;--"; // user supplied input
let sql = SQL`SELECT * FROM Students WHERE name = '${name}'`; // build query...
console.log(sql); // Non-injected SQL!
// SELECT * FROM Students WHERE name = 'Robert''; DROP TABLE Students;--'
Tip! editors may automatically syntax highlight the SQL inside the template literal if it uses the sql
tag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With