tool-dev:一个简单tcp代理工具

0x01 介绍

一个简单的基于tcp 的代理。

功能:监听本地端口,接收本地连接,将数据传入远端服务器,并将服务器的返回信息回传给连接本地的连接

思路:

tool-dev:一个简单tcp代理工具_第1张图片

0x02 代码实现

# 一个简单的tcp代理
# 监听本地端口,将连接到本地端口的流量转发到远端

import socket
import sys
import threading

def usage():
    print("Usage: python tcpsocks.py [localhost] [localport] [remotehost] [remoteport]")
    print("Example: python tcpsocks.py 127.0.0.1 9000 x.x.x.x 9000")
    sys.exit(0)

def lc_waiter_handler(local_waiter, localhost, localport, remotehost, remoteport):
    # 创建一个连接远端服务的socket
    inner_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        inner_socket.connect((remotehost, int(remoteport)))
    except Exception as err:
        print(err)
        print("connect to the remote server {}: {}".format(remotehost, remoteport))
        local_waiter.close()
        sys.exit(0)
    
    # 此处假设是发送数据到服务端
    while True:
        local_buffer = receive_from(local_waiter)
        if len(local_buffer):
            print("[*] Received {} bytes from localhost.".format(len(local_buffer)))
            # 将数据发送到远端服务器
            inner_socket.send(local_buffer.encode('utf-8'))
            print("[==>] Sent to remote.")

        remote_buffer = receive_from(inner_socket)
        if len(remote_buffer):
            print("[<==] Received {} bytes from remote.".format(len(remote_buffer)))
            # 将数据发送到连接过来的socket
            local_waiter.send(remote_buffer.encode('utf-8'))
            print("[<==] Sent to localhost.")

        # 如果两边都没有数据关闭连接
        if not len(local_buffer) or not len(remote_buffer):
            local_waiter.close()
            inner_socket.close()
            print("[*] No more data. Closing connections.")
            break


# 从connection获取数据   
def receive_from(connection):
    buffer = ""
    connection.settimeout(2) # 设置2秒超时
    try:
        # 持续从缓存中获取数据
        while True:
            data = connection.recv(4096).decode('utf-8')
            if not data:
                break
            buffer += data
    except Exception as err:
        print(err)
    return buffer

if __name__ == "__main__":
    if len(sys.argv[1:]) != 4:
        usage()

    # 创建一个本地监听服务器
    local_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        local_server.bind((sys.argv[1], int(sys.argv[2])))
    except Exception as err:
        print(err)
        print("Failed to bind on {}: {}".format(sys.argv[1], sys.argv[2]))
        sys.exit(0)

    local_server.listen(5) # 5条监听连接 

    while True:
        local_waiter, client_addr = local_server.accept()
        local_waiter_threading = threading.Thread(target=lc_waiter_handler, args=(local_waiter, sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]), ))
        local_waiter_threading.start()




0x03 运行截图

tool-dev:一个简单tcp代理工具_第2张图片

0x04 后记

可以添加功能:按需处理中转流量。

你可能感兴趣的:(安全分析,安全)