Ok, I have a some command wich MUST be executed in shell=True mode.
os.system or subprocess.Popen(..., shell=True)
And this command contain string substitution like: cmd = "some_secret_command {0}".format(string_from_user)
I want escape string_from_user variable to prevent ANY injections.
Simple wrong answers:
- Use
shlex.quote- incorrect
print(shlex.quote('file.txxt; &ls . #')) -> 'file.txxt; &ls . #' (injection)
Example:
> python -c "import sys; print(sys.argv[1])" 'file.txxt; &ls . #'
secret.txt
secret2.txt
- Use escape
^- incorrect
Example:
import os
CMD = '''string with spaces'''.replace('', '^').replace('^"', '')
os.system('python -c "import sys; print(sys.argv[1])" {0}'.format(CMD))
Now I can use (space) and inject more then one argument.
- Use
^and"or'- incorrect
Example:
import os
CMD = '''some arg with spaces'''.replace('', '^').replace('^"', '')
os.system('python -c "import sys; print(sys.argv[1])" "{0}"'.format(CMD))
print ^s^o^m^e^ ^a^r^g^ ^w^i^t^h^ ^s^p^a^c^e^s^
and if '
import os
CMD = '''some spaces'''.replace('', '^').replace('^\'', '')
os.system('python -c "import sys; print(sys.argv[1])" \'{0}\''.format(CMD))
print 'some
I now about shell=False but this is incorrect for me.