CodeExpress
CodeExpress

Reputation: 2232

Safe way to execute commands on linux server when part of command is from a user input

I am reviewing a web application which exposes a functionality for the user to change his unix password via a web interface. An authenticated web user gives his unix username and his desired password. Command injection is an obvious attack vector here.

The input is validated and sanitized by mandating usernames to be only in:
/^[a-zA-Z0-9]+$/

Thereafter it does something like (in python):

p = os.popen("/usr/bin/passwd " + username, "w")

and so on and so forth.

If they didn't have that regex, a username like jon; rm -rf would be catastrophic for system or popen.

I wan't something more fundamental that won't allow me to harm myself even if bad input like that makes way to the system/popen call. (For eg. subprocess )

Is there a more secure way of doing this or validation of input remains to be the only defense ? I was looking for something safer than system/popen or a different approach altogether if there is a standard way of executing commands where part of command comes from a user input.

Upvotes: 3

Views: 3090

Answers (2)

Niklas B.
Niklas B.

Reputation: 95328

You could quote the input yourself:

import pipes
p = os.popen("/usr/bin/passwd " + pipes.quote(username), 'w')

os.popen is however deprecated and pipes.quote is an undocumented function, so you'd be much better off just using the subprocess module:

import subprocess
p = subprocess.Popen(["/usr/bin/passwd", username])

Upvotes: 3

Related Questions