我在Python中有一个服务器/客户机套接字对。服务器接收特定的命令,然后准备响应并将其发送到客户端。在
在这个问题中,我关心的只是代码中的可能的注入:如果可以要求服务器对第二个参数做一些奇怪的事情——如果对命令内容的控制不足以避免不希望发生的行为。在
编辑:根据收到的建议
在windows上调用check_output时添加了参数shell=True。不应该是危险的,因为命令是一个普通的'dir'。在
一。在self.client, address = self.sock.accept()
...
cmd = bytes.decode(self.client.recv(4096))
ls:执行系统命令,但只读取目录的内容。在
^{pr2}$
cd:只调用os.chdir。在elif cmd.startswith('cd '):
path = cmd.split(' ')[1].strip()
if not os.path.isdir(path):
self.client.send(b'is not path')
else:
os.chdir(path)
self.client.send( os.getcwd().encode() )
get:将文件内容发送到客户端。在elif cmd.startswith('get '):
file = cmd.split(' ')[1].strip()
if not os.path.isfile(file):
self.client.send(b'ERR: is not a file')
else:
try:
with open(file) as f: contents = f.read()
except IOError as er:
res = "ERR: " + er.strerror
self.client.send(res.encode())
continue
... (send the file contents)