在本科做毕设的时候就接触到TCP代理这东西,当时需要使用代理来对发送和收到的数据做修改,同时使用代理也让我对HTTP协议有了更深的了解。

TCP Proxy用到的一个主要的东西就是socket。proxy通过socket分别对localhost和remotehost做连接,然后可以对通过proxy的流量和数据进行分析。

 __author__ = 'seven'
import sys
import socket
import threading def hexdump(src, length=16):
result = []
digits = 4 if isinstance(src, unicode) else 2 for i in xrange(0, len(src), length):
s = src[i:i + length]
hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s])
text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
result.append(b"%04X %-*s %s" % (i, length * (digits + 1), hexa, text)) print b'\n'.join(result) def receive_from(connection):
buffer = "" # We set a 2 second time out depending on your target this may need to be adjusted
connection.settimeout(2) try:
while True:
data = connection.recv(4096)
if not data:
break
buffer += data
except:
pass return buffer def request_handler(buffer):
# perform packet mofifications
return buffer def response_handler(buffer):
# perform pakect 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):
print "[==>] Received %d bytes from localhost." % len(local_buffer)
hexdump(local_buffer)
local_buffer = request_handler(local_buffer)
remote_socket.send(local_buffer)
print "[==>] Sent to remote."
remote_buffer = receive_from(remote_socket)
if len(remote_buffer):
print "[<==] Received %d bytes from remote." % len(remote_buffer)
hexdump(remote_buffer)
remote_buffer = response_handler(remote_buffer)
client_socket.send(remote_buffer)
print "[<==] Sent 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:
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()
print "[==>] Received incoming connection from %s:%d" % (addr[0], addr[1])
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: ./tcp proxy.py [localhost] [localport] [remotehost] [remoteport] [receive_first]"
print "Example: ./tcp proxy.py 127.0.0.1 9000 10.12.132.1 9000 True"
sys.exit(0) local_host = sys.argv[1]
local_port = int(sys.argv[2]) remote_host = sys.argv[3]
remote_port = int(sys.argv[4]) 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) main()

在request_handler和response_handler函数中就可以对收到的数据进行修改。

高大上的hexdump函数来自http://code.activestate.com/recipes/142812-hex-dumper/,表示不怎么看得懂..如果有看得懂的朋友欢迎和我交流

Black Hat Python之#2:TCP代理的更多相关文章

  1. 结合python实现的netcat与python实现的tcp代理,建立一个流量隧道

    在proxy中 python2 proxy.py 127.0.0.1 3334 192.158.1.111 80 true 作为服务器在本地3334端口进行监听, 作为客户端连接远程web服务器192 ...

  2. 一个简单的tcp代理实现

    There are a number of reasons to have a TCP proxy in your tool belt, bothfor forwarding traffic to b ...

  3. nginx TCP 代理& windows傻瓜式安装

    一.下载nginx Windows http://nginx.org/en/download.html 二.解压到目录 三.进入目录并start nginx.exe即可启动 cd d:/java/ng ...

  4. python socket之tcp服务器与客户端demo

    python socket之tcp服务器与客户端demo 作者:vpoet mails:vpoet_sir@163.com server: # -*- coding: cp936 -*- ''' 建立 ...

  5. nginx : TCP代理和负载均衡的stream模块

    一直以来,Nginx 并不支持tcp协议,所以后台的一些基于TCP的业务就只能通过其他高可用负载软件来完成了,比如Haproxy. 这算是一个nginx比较明显的缺憾.不过,在1.90发布后这个认知将 ...

  6. python 单例模式获取IP代理

    python 单例模式获取IP代理 tags:python python单例模式 python获取ip代理 引言:最近在学习python,先说一下我学Python得原因,一个是因为它足够好用,完成同样 ...

  7. iOS进阶之TCP代理鉴权过程

    这段时间接触了网络代理,而自己的任务是完成TCP和UDP的网络代理,所以在这里写些自己的理解吧. 这篇文章先介绍一下TCP代理的鉴权过程(采用的是用户名和密码鉴权),下一篇文章再介绍UDP代理的鉴权过 ...

  8. 早期nginx tcp代理(基于patch实现)

    nginx tcp代理功能由nginx_tcp_proxy_module模块提供,同时监测后端主机状态.该模块包括的模块有: ngx_tcp_module, ngx_tcp_core_module, ...

  9. python小练习---TCP服务器端

    针对于上一篇分享python小练习---TCP客户端 http://www.cnblogs.com/zhaijiahui/p/6926197.html我继续按书中内容,向下进行这里需要强调一个事py3 ...

随机推荐

  1. 不可错过的java面试博客之java集合篇

    1. List List 是有序的 Collection.Java List 一共三个实现类: 分别是 ArrayList.Vector 和 LinkedList ArrayList ArrayLis ...

  2. ASP.NET Core 包管理工具(4)

    之前忘记介绍ASP.NET Core静态文件wwwroot了.再来补充一下.步骤比较简单在项目上右击添加文件夹输入文件名称 wwwroot就搞定了.这个文件主要是放置一些静态文件的,比如css.js. ...

  3. SpringBoot系列(十三)统一日志处理,logback+slf4j AOP+自定义注解,走起!

    往期精彩推荐 SpringBoot系列(一)idea新建Springboot项目 SpringBoot系列(二)入门知识 springBoot系列(三)配置文件详解 SpringBoot系列(四)we ...

  4. HC32F003C4PA GPIO Output

    1.打开启动文件,找到并跳转至SystemInit函数 void SystemInit(void) { stc_clk_systickcfg_t stcCfg; // TODO load trim f ...

  5. 【HDU4991】树状数组

    http://acm.hdu.edu.cn/showproblem.php?pid=4991 用f[i][j] 表示 前i个数以第i个数结尾的合法子序列的个数,则递推式不难写出: f[i][j] = ...

  6. markdonwn 测试1

    标题测试 ## 二级标题 ### 三级标题 二级标题 三级标题 段落格式 换行 末尾两个空格 第一行第一行第一行第一行第一行第一行第一行第一行 第二行第二行第二行第二行第二行第二行第二行第二行 第一行 ...

  7. (Redis基础教程之六)如何使用Redis中的List

    如何在ubuntu18.04上安装和保护redis 如何连接到Redis数据库 如何管理Redis数据库和Keys 如何在Redis中管理副本和客户端 如何在Redis中管理字符串 如何在Redis中 ...

  8. Elasticsearch URI search 查询语法整理

    Elasticsearch URI search 一.请求体查询与空查询 1. 请求体查询(request body search) 简单查询语句(lite)是一种有效的命令行adhoc查询.但是,如 ...

  9. 「雕爷学编程」Arduino动手做(20)—水银开关模块

    37款传感器与模块的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止37种的.鉴于本人手头积累了一些传感器和模块,依照实践出真知(一定要动手做)的理念,以学习和交流为目的,这里 ...

  10. Python PIL Image图片显示系列

    1. PIL Image图片显示 在使用PIL函数中的Image方法读取图片时,对于图片的shape,可能有不少宝宝存在疑惑.是什么疑惑了?就是image = Image.open(image_pat ...