这个 JavaScript 是否容易受到 SQL 注入攻击?

问题描述 投票:0回答:1

我正在使用node-postgres库。

  const sql = `
  SELECT * 
  FROM "Employees"
  where employee_id = '${employee_id}' ; 
  `;
  console.log(`Query formatted: ${sql}`);
  const result = await this.db.run(sql)

// DB Run 方法如下所示

async run(sql) {
    let retVal = "";
    let client;
    try {
      await this.init();
      console.log(`Connecting to ${this.connection.host}`);
      client = new pg.Client(this.connection);
      await client.connect();
      console.log(`inner sql:  ${sql}`);
      const res = await client.query(sql);
      
      retVal = res.rows;
 
      client.end();
    } catch (e) {
      console.log(`ERROR: ${e}`);
      retVal = e;
      client.end();
    }
    return retVal;
  }

employee_id 通过用户输入作为 POST 调用传递。

SQLMAP 告诉我这很容易受到攻击,但我尝试了不同的输入,例如

employee_id = "123';从员工中选择*;'"

但它似乎总是一起执行查询告诉我没有找到结果。

  1. 我将对查询进行参数化,但想知道当前的漏洞级别是什么?
  2. 对于参数化,如果我的代码中很多不同的地方都有上面相同的 3 个语句,我将如何处理?每个查询的形状都不同,因此不太确定我可以将它们转移到通用方法中。相反,我将不得不重构所有地方?
javascript postgresql sql-injection node-postgres sqlmap
1个回答
0
投票

JavaScript 不会自动清理输入,据我所知,Node 也不会,所以这理论上很容易受到攻击,而且比遗憾更安全。

可以通过“isValid”变量来实现一些基本的输入清理。这可以通过添加按键事件监听器并检查当前字符以验证它是否是有效字符来实现,并且如果用户提供包含无效字符或短语的字符串则不允许提交。

您需要

npm i keypress
安装按键事件,因为它们对于避免输入中的转义(无论是否无辜)至关重要,例如“字符。

示例:

var keypress = require('keypress');
keypress(process.stdin);
var allowed = true;

process.stdin.on('keypress', (str, key) => {
    switch (key) {
        case "'":
            console.log("\(') is not allowed.");
            allowed = false;
            break;
        case '"':
            console.log('\n(") is not allowed.');
            allowed = false;
            break;
       // these are examples, please add more if you decide to use this
    }
});
if (!allowed) {
    if (employee_id.includes('"' || employee_id.includes("'")) {//dont forget to expand on conditions
        console.log("\nPlease rewrite your output, as it still includes one or more disallowed letters.");
        // Get input again
    } else {
        break;
    }
}

以上是检查输入的原始方式。我会推荐一种更有效的方法来清理输入。

© www.soinside.com 2019 - 2024. All rights reserved.