Christian
Christian

Reputation: 942

Is calling shell with prefined string safe?

So, this question occurred to me while I was reading the documents of Subprocess in python. So let's just use example, because programmers understand code.

from Subprocess import Popen, PIPE

def connect_with_netCat(port, ip):
  Popen('nc %s %s' % (ip, port), shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)

My question; is this safe? I know netcat is a poor choose for example since it also leaves vulnerabilities for an attacker to call that function and connect somewhere, but it was the first package that came to my mind for an example, but just looking at the code - is it safe since there's the constant in it?

Or would this be a safer way of doing this?

def connect_with_netCat(port, ip):
  from Subprocess import Popen, PIPE
  Popen('nc %s %s' % (ip, port), shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)

Since it's outside the global scope. Just a curious question.

Upvotes: 0

Views: 28

Answers (1)

Barmar
Barmar

Reputation: 782130

If you're sure that the source of ip and port are safe, then the command should be safe.

To be a little safer, you could leave out shell=True, since you're not making use of any shell syntax in the command. That way, if there are shell operators in the command, they won't be interpreted.

You should also use %d instead of %s for the port, since that's required to be a number.

Upvotes: 1

Related Questions