Node.js 執(zhí)行命令

2021-06-01 09:50 更新

1.2.1 【必須】使用child_process執(zhí)行系統(tǒng)命令,應限定或校驗命令和參數的內容

  • 適用場景包括: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:未限定或過濾,直接執(zhí)行命令
  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:通過白名單,限定外部可執(zhí)行命令范圍
  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:執(zhí)行命令前,過濾/轉義指定符號
  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. });

關聯漏洞:高風險 - 任意命令執(zhí)行

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號