实现一个TCP代理
1.简单描述:
就是再客户端和服务器中间,建立一个中间商。客户端把需要发给服务器的数据,先转发给中间商,然后中间商再转发给服务器。服务器再把响应信息发给中间商,中间商再转发给客户端。
2.实现代码proxy.py
import sys
import socket
import threading
HEX_FILTER=' '.join(
[(len(repr(chr(i)))==3) and chr(i) or '.' for i in range(256)]
)
"""
HEX_FILE:
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ . ] ^ _ `
a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ . ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º »
¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷
ø ù ú û ü ý þ ÿ
"""
def hexdump(src,length=16,show=True):
if isinstance(src,bytes):
src=src.decode()
result=list()
for i in range(0,len(src),length):
word=str(src[i:i+length])
printable=word.translate(HEX_FILTER)
hexa=' '.join([f'{ord(c):02X}' for c in word])
hexwide=length*3
result.append(f'{i:04x} {hexa:<{hexwide}} {printable}')
if show:
for line in result:
print(line)
else:
return result
#print(HEX_FILTER)
#print("-----------------------------")
#hexdump('python rocks\n and proxies roll\n')
def receive_from(connection):
buffer=b""
connection.settimeout(5)
try:
while True:
data=connection.recv(4096)
if not data:
break
buffer+=data
except Exception as e:
pass
return buffer
def request_handler(buffer):
#perform packer modifications
return buffer
def response_handler(buffer):
#perform packet modifications
return buffer
def proxy_handler(client_socket,remote_host,remote_port,receive_first):
remote_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
remote_socket.connect((remote_host,remote_port))
if receive_first:
remote_buffer=receive_from(remote_socket)
hexdump(remote_buffer)
remote_buffer=response_handler(remote_buffer)
if len(remote_buffer):
print("[<==] Sending %d bytes to localhost." %len(remote_buffer))
client_socket.send(remote_buffer)
while True:
local_buffer=receive_from(client_socket)
if len(local_buffer):
line=f"[==>] Received {len(local_buffer)}bytes from localhost."
print(line)
hexdump(local_buffer)
local_buffer=request_handler(local_buffer)
remote_socket.send(local_buffer)
print(f"[<==] Send to localhost .")
remote_buffer=receive_from(remote_socket)
if len(remote_buffer):
print(f"[<==] Received {len(remote_buffer)} bytes form remote")
hexdump(remote_buffer)
remote_buffer=response_handler(remote_buffer)
client_socket.send(remote_buffer)
print("[<==] Send to localhost.")
if not len(local_buffer) or not len(remote_buffer):
client_socket.close()
remote_socket.close()
print("[*] No more data. Closing connections.")
break
def server_loop(local_host,local_port,remote_host,remote_port,receive_first):
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
server.bind((local_host,local_port))
except Exception as e:
print('problem on bind :%r'%e)
print("[!!] Failed to listen on %s:%d"%(local_host,local_port))
print("[!!] Check for other listening sockets or correct permissions.")
sys.exit(0)
print("[*] Listening on %s:%d"%(local_host,local_port))
server.listen(5)
while True:
client_socket,addr= server.accept()
line="> Received incoming connection from %s:%d"%(addr[0],addr[1])
print(line)
proxy_thread=threading.Thread(target=proxy_handler,args=(client_socket,remote_host,remote_port,receive_first))
proxy_thread.start()
def main():
if len(sys.argv[1:]) !=5:
print("Usage: ./proxy.py [localhost][localport]",end="")
print("[remotehost][remoteport][receive_first]")
print("Example:./proxy.py 127.0.0.1 9000 10.12.132.1 9000 True")
local_host=sys.argv[1]
local_port=int(sys.argv[2])
remote_host=sys.argv[3]
remote_port=int(sys.argv[5])
receive_first=sys.argv[5]
if "True" in receive_first:
receive_first=True
else:
receive_first=False
server_loop(local_host,local_port,remote_host,remote_port,receive_first)
if __name__=="__main__":
main()
3.对代码的理解
代码的大致逻辑,分别和客户端与服务器端建立,两个socket连接,然后再将充当中间人的角色,传递客户端可服务器的信息。
从main()函数开始
主要是接收参数,参数有:local_host(客户端ip),local_port(客户端端口),remote_host(服务器ip),remote_port(服务器端口),receive_first(是否含有原理的缓存?)将参数传递给server_loop函数。
server_loop()函数
建立server socker,以及调用proxy——handel()函数
proxy()函数
完成代理的主要代码,实现两端的信息转发
request_handler(),response_handler()函数
发送请求数据和响应数据请求包的改写
receive_from()函数
接收数据
hexdump()函数
将内容转化成十六进制的形式
4.中间的小问题
使用gpt,发现参数赋值出现了错误
5.运行过程:
因为连接ftp.sun.ac.za 的用户名和密码是不知道的 ,使用anymous,密码为空,进行登录,但是可能是因为时延的关系,所以这里连接失败了。
后续的话自己搭建一个ftp服务器,应该可以连接成功。后续有时间再补充
6.参考链接
1.pytho黑帽子
2.poe
3.python渗透测试入门之TCP代理