Node.js 執(zhí)行命令

2021-06-01 09:50 更新

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

  • 適用場(chǎng)景包括:child_process.exec, child_process.execSync, child_process.spawn, child_process.spawnSync, child_process.execFile, child_process.execFileSync

  • 調(diào)用上述函數(shù),應(yīng)首先考慮限定范圍,供用戶選擇。

  • 使用child_process.execchild_process.execSync時(shí),如果可枚舉輸入的參數(shù)內(nèi)容或者格式,則應(yīng)限定白名單。如果無(wú)法枚舉命令或參數(shù),則必須過(guò)濾或者轉(zhuǎn)義指定符號(hào),包括:|;&$()><`!

  • 使用child_process.spawnchild_process.execFile時(shí),應(yīng)校驗(yàn)傳入的命令和參數(shù)在可控列表內(nèi)。

  1. const Router = require("express").Router();
  2. const validator = require("validator");
  3. const { exec } = require('child_process');
  4. // bad:未限定或過(guò)濾,直接執(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:通過(guò)白名單,限定外部可執(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í)行命令前,過(guò)濾/轉(zhuǎn)義指定符號(hào)
  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. });

關(guān)聯(lián)漏洞:高風(fēng)險(xiǎn) - 任意命令執(zhí)行

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)