问题
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?
回答1:
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!
回答2:
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.
来源:https://stackoverflow.com/questions/44086785/do-es6-template-literals-protect-against-sql-injection