当前位置: 首页 > 面试题库 >

如何在Windows上安全地转义cmd.exe Shell的命令行参数?

许俊晤
2023-03-14
问题内容

好的,我有一些命令必须在shell=True模式下执行。

os.system 要么 subprocess.Popen(..., shell=True)

并且此命令包含字符串替换,例如: cmd = "some_secret_command {0}".format(string_from_user)

我想要转义string_from_user变量以防止任何注入。

简单的错误答案:

  1. 使用shlex.quote-不正确

print(shlex.quote('file.txxt; &ls . #'))-> 'file.txxt; &ls . #'(注射)

例:

> python -c "import sys; print(sys.argv[1])" 'file.txxt; &ls . #'
secret.txt
secret2.txt
  1. 使用转义^-不正确

例:

import os

CMD = '''string with spaces'''.replace('', '^').replace('^"', '')
os.system('python -c "import sys; print(sys.argv[1])" {0}'.format(CMD))

现在,我可以使用``(空格)并注入多个参数。

  1. 使用^"'-错误

例:

import os

CMD = '''some arg with spaces'''.replace('', '^').replace('^"', '')
os.system('python -c "import sys; print(sys.argv[1])" "{0}"'.format(CMD))

打印 ^s^o^m^e^ ^a^r^g^ ^w^i^t^h^ ^s^p^a^c^e^s^

而如果 '

import os

CMD = '''some spaces'''.replace('', '^').replace('^\'', '')
os.system('python -c "import sys; print(sys.argv[1])" \'{0}\''.format(CMD))

打印 'some

我现在大约,shell=False但这对我来说是不正确的。


问题答案:

引用Windows命令行的问题在于,有两个受引用影响的分层解析引擎。首先,有cmd.exe解释某些特殊字符的Shell(例如)。然后,有一个调用程序解析命令行。CommandLineToArgvWWindows提供的功能经常会发生这种情况,但并非总是如此。

就是说,对于一般情况,例如,使用cmd.exe与程序一起解析其命令行的程序CommandLineToArgvW,您可以使用Daniel
Colascione在《每个人都用错误的方式引号命令行参数》中描述的技术。我最初尝试将其适应Ruby,现在尝试将其转换为python。

import re

def escape_argument(arg):
    # Escape the argument for the cmd.exe shell.
    # See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
    #
    # First we escape the quote chars to produce a argument suitable for
    # CommandLineToArgvW. We don't need to do this for simple arguments.

    if not arg or re.search(r'(["\s])', arg):
        arg = '"' + arg.replace('"', r'\"') + '"'

    return escape_for_cmd_exe(arg)

def escape_for_cmd_exe(arg):
    # Escape an argument string to be suitable to be passed to
    # cmd.exe on Windows
    #
    # This method takes an argument that is expected to already be properly
    # escaped for the receiving program to be properly parsed. This argument
    # will be further escaped to pass the interpolation performed by cmd.exe
    # unchanged.
    #
    # Any meta-characters will be escaped, removing the ability to e.g. use
    # redirects or variables.
    #
    # @param arg [String] a single command line argument to escape for cmd.exe
    # @return [String] an escaped string suitable to be passed as a program
    #   argument to cmd.exe

    meta_chars = '()%!^"<>&|'
    meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
    meta_map = { char: "^%s" % char for char in meta_chars }

    def escape_meta_chars(m):
        char = m.group(1)
        return meta_map[char]

    return meta_re.sub(escape_meta_chars, arg)

应用此代码,您应该能够成功转义cmd.exe Shell的参数。

print escape_argument('''some arg with spaces''')
# ^"some arg with spaces^"

请注意,该方法应引用单个完整参数。如果要从多个来源收集参数,例如,通过构建一串python代码以传递给python命令,则必须在将其传递给之前对其进行汇编escape_argument

import os

CMD = '''string with spaces and &weird^ charcters!'''
os.system('python -c "import sys; print(sys.argv[1])" {0}'.format(escape_argument(CMD)))
# string with spaces and &weird^ charcters!


 类似资料:
  • 问题内容: 我在Windows 7计算机上运行Xampp,想知道是否以及如何通过命令行运行xampp命令。像php phpfile.php这样的命令 任何意见,将不胜感激。 问题答案: 您可以按照其他答案中的说明设置 环境变量 (如此处) 要么 您可以以管理员身份打开“ 开始” >“ CMD ”并编写

  • 在linux中,您可以使用命令

  • 文件夹结构是正确的--也就是说,我有一个与node_modules/karma/bin匹配的嵌套文件夹结构,并且我在那个位置有一个名为karma的文件。 我在两个例子中都是从同一个位置开始的。在Visual Studio代码终端或windows命令提示符中运行此命令时,会出现以下错误:“'node_modules'未被识别为内部或外部命令、可操作程序或批处理文件。” 但在GitBash,它工作得很

  • 我已经在Windows7机器上安装了msysGit 1.7.10。我需要知道的是我是否还可以从命令行使用Git? 当我现在在命令行中尝试命令时,我看到: “git”不能识别为内部或外部命令、可操作程序或批处理文件。 有什么方法可以启用Git命令行吗?

  • 问题内容: 我正在尝试从命令行运行.class文件。当我手动移动到存储目录时,它会起作用,但是当我尝试这样的操作时: 它说找不到主班。除了制作.jar文件(我知道.jar是最好的解决方案,但现在不是我正在寻找的解决方案)之外,还有其他解决方案吗? 问题答案: 在Java应用程序启动(又名或干脆)预计最多支持四个不同的方式来指定要启动(取决于Java版本使用)的东西。 指定 类名 是最基本的方法。注

  • 问题内容: 我正在尝试从Windows中的命令行执行Java程序。这是我的代码: 我不确定如何执行程序-有帮助吗?在Windows上可以吗?为什么它不同于另一个环境(我以为JVM只写一次,可以在任何地方运行)? 问题答案: 假设你的文件位于 运行命令提示符 这使C:\ mywork成为当前目录。 这将显示目录内容。你应该在文件中看到。 这告诉系统在哪里可以找到JDK程序。 这将运行编译器。除了下一

  • 我正试图在Windows中从命令行执行一个Java程序。下面是我的代码: 我不确定如何执行程序-有什么帮助吗?这在Windows上可能吗?为什么它和另一个环境不同(我以为JVM是编写一次,运行任何地方)?