Skip to content

Instantly share code, notes, and snippets.

@SVilgelm
Last active July 22, 2019 13:16
Show Gist options
  • Save SVilgelm/ea459b4b195cee16c54d882f9f83c020 to your computer and use it in GitHub Desktop.
Save SVilgelm/ea459b4b195cee16c54d882f9f83c020 to your computer and use it in GitHub Desktop.
Shell sanitizing, quoting parameters
  • Old code
    exec_cmd('ping {ip}'.format(ip=ip))
    Rewritten code
    exec_cmd(format_cmd('ping {ip}', ip=ip))
    Examples
    format_cmd('ping {ip}', ip="$(rm -rf /)")
    $ ping '$(rm -rf /)'
    ping: cannot resolve $(rm -rf /): Unknown host 
    format_cmd('ping {ip}', ip='$(rm -rf '/')')
    $ ping '$(rm -rf '"'"'/'"'"')'
    ping: cannot resolve $(rm -rf '/'): Unknown host
  • Old code
    exec_cmd("python -c'print(\"{arg}\")'".format(arg=arg))
    Rewritten code
    exec_cmd(format_cmd("python -c'import sys; print(sys.argv[1])' {arg}", arg=arg))
    Examples
    format_cmd("python -c'import sys; print(sys.argv[1])' {arg}", arg="'$(rm -rf /)'")
    $ python -c'import sys; print(sys.argv[1])' ''"'"'$(rm -rf /)'"'"''
    '$(rm -rf /)'
try: # py3
from shlex import quote # noqa
except ImportError: # py2
from pipes import quote # noqa
def format_cmd(cmd, *args, **kwargs):
return cmd.format(*[quote(str(i)) for i in args],
**{k: quote(str(v)) for k, v in kwargs.items()})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment