【问题标题】:How to fix security issue in python?如何解决python中的安全问题?
【发布时间】:2017-08-28 05:09:33
【问题描述】:

我在运行脚本时使用os.system('cls' if os.name == 'nt' else 'clear') 来清除输出,但在 codacy 上我遇到了一个安全问题

使用 shell 启动进程,检测到可能的注入,安全问题。

如何解决问题?

脚本链接:https://www.codacy.com/app/vaibhavsingh97/StalkPy/file/9458582870/issues/source?bid=5189215&fileBranchId=5189215#l43

【问题讨论】:

  • 干脆别用os.system
  • @Nabin 如何在 python 中清除终端输出?
  • 你能说出你想清屏的场景吗?
  • 有些终端的回滚可能是无限的——想要窥探的用户可以简单地回滚终端日志。
  • 就像我每次运行脚本一样,它应该清除以前的输出。

标签: python python-2.7 python-3.x security


【解决方案1】:

当您使用来自用户的参数运行函数时,它会出现安全问题。例如:

import os
def do_clear(command): # Notice command is sent as argument from outside world and hence this makes it vulnerable
    os.system(command)

如果用例子调用方法

do_clear('rm -f */*')

那么它可能会删除当前目录的所有文件。但是如果直接使用'clear'命令,你不必担心安全问题,因为在所有条件下都只运行'clear'。所以下面的函数就足够安全了。

def do_clear(): # Notice command is not sent as argument from outside world
    os.system('cls' if os.name == 'nt' else 'clear') # This is not risky as os.system takes clear/cls command always.

【讨论】:

    【解决方案2】:

    来自os.system

    子进程模块为生成提供了更强大的工具 新流程并检索其结果;使用该模块是 最好使用此功能。请参阅替换旧函数 使用子流程文档中的子流程模块部分 一些有用的食谱。

    我建议使用 subprocess 之一作为参数传递 shell=False 进行测试,看看它是否适用于 codacy。 subprocess.run(['clear']) 在我本地的 Python 解释器中工作,您必须在 codacy 上对其进行测试。

    如果是Python 2.x,可以试试:

    subprocess.call(['clear'])
    

    【讨论】:

    • 是的。给出一个等价物,你可以使用subprocess.run(['cls'] if os.name == 'nt' else ['clear'])
    • subprocess.run() 仅适用于python 3.5 及以上,因此不支持python 2.7
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2022-06-15
    • 2011-06-20
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多