Node.js 执行命令

2021-06-01 09:50 更新

1.2.1 【必须】使用child_process执行系统命令,应限定或校验命令和参数的内容

  • 适用场景包括:child_process.exec, child_process.execSync, child_process.spawn, child_process.spawnSync, child_process.execFile, child_process.execFileSync

  • 调用上述函数,应首先考虑限定范围,供用户选择。

  • 使用child_process.execchild_process.execSync时,如果可枚举输入的参数内容或者格式,则应限定白名单。如果无法枚举命令或参数,则必须过滤或者转义指定符号,包括:|;&$()><`!

  • 使用child_process.spawnchild_process.execFile时,应校验传入的命令和参数在可控列表内。

  1. const Router = require("express").Router();
  2. const validator = require("validator");
  3. const { exec } = require('child_process');
  4. // bad:未限定或过滤,直接执行命令
  5. Router.get("/vul_cmd_inject", (req, res) => {
  6. const txt = req.query.txt || "echo 1";
  7. exec(txt, (err, stdout, stderr) => {
  8. if (err) { res.send({ err: 1 }) }
  9. res.send({stdout, stderr});
  10. });
  11. });
  12. // good:通过白名单,限定外部可执行命令范围
  13. Router.get("/not_vul_cmd_inject", (req, res) => {
  14. const txt = req.query.txt || "echo 1";
  15. const phone = req.query.phone || "";
  16. const cmdList = {
  17. sendmsg: "./sendmsg "
  18. };
  19. if (txt in cmdList && validator.isMobilePhone(phone)) {
  20. exec(cmdList[txt] + phone, (err, stdout, stderr) => {
  21. if (err) { res.send({ err: 1 }) };
  22. res.send({stdout, stderr});
  23. });
  24. } else {
  25. res.send({
  26. err: 1,
  27. tips: `you can use '${Object.keys(cmdList)}'`,
  28. });
  29. }
  30. });
  31. // good:执行命令前,过滤/转义指定符号
  32. Router.get("/not_vul_cmd_inject", (req, res) => {
  33. const txt = req.query.txt || "echo 1";
  34. let phone = req.query.phone || "";
  35. const cmdList = {
  36. sendmsg: "./sendmsg "
  37. };
  38. phone = phone.replace(/(\||;|&|\$\(|\(|\)|>|<|\`|!)/gi,"");
  39. if (txt in cmdList) {
  40. exec(cmdList[txt] + phone, (err, stdout, stderr) => {
  41. if (err) { res.send({ err: 1 }) };
  42. res.send({stdout, stderr});
  43. });
  44. } else {
  45. res.send({
  46. err: 1,
  47. tips: `you can use '${Object.keys(cmdList)}'`,
  48. });
  49. }
  50. });

关联漏洞:高风险 - 任意命令执行

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号