Compare commits

..
42 Commits
Author SHA1 Message Date
刘河 0436a5163e 截图 2018-12-11 18:29:33 +08:00
刘河 184523b487 Web管理界面截图 2018-12-11 18:22:38 +08:00
he liu 10c7c49f4b Update .gitattributes 2018-12-11 16:54:21 +08:00
he liu e4ff7cdbf7 Create .gitattributes 2018-12-11 16:51:53 +08:00
he liu 61aab7340c Update README.md 2018-12-11 16:50:50 +08:00
刘河 abc30a9ad1 版本重构,加web管理方式 2018-12-11 16:37:12 +08:00
he liu 974f605ff6 Update README.md 2018-12-07 15:30:52 +08:00
he liu a8c539460c Update README.md 2018-12-07 15:29:18 +08:00
刘河 c35ce71e7c 客户端断线重连bug修复 2018-12-06 20:45:14 +08:00
he liu e6c2de7d9f Update README.md 2018-12-04 00:15:14 +08:00
刘河 34cb814d50 Udp隧道图 2018-12-03 23:28:13 +08:00
刘河 212d74bbc4 sock5验证加密、udp隧道、gzip、snnapy压缩 2018-12-03 23:03:25 +08:00
he liu 83eb8dcb3c Update README.md 2018-12-01 13:56:37 +08:00
he liu b61ff97681 Update README.md 2018-12-01 13:52:48 +08:00
刘河 ed694d1d1d 原理图 2018-12-01 13:48:46 +08:00
刘河 4994476af1 新增http代理模式 2018-12-01 02:38:29 +08:00
刘河 86deb2025f 连接bug修复 2018-11-30 01:13:41 +08:00
he liu a32010fcc0 Update README.md 2018-11-29 23:55:49 +08:00
he liu b220b5801c Update README.md 2018-11-29 23:51:16 +08:00
he liu 95e2db7a38 Update README.md 2018-11-29 23:38:42 +08:00
he liu 85366a87b4 Update README.md 2018-11-29 23:37:12 +08:00
he liu 311b298587 Update README.md 2018-11-29 23:36:22 +08:00
he liu 4cc550932b Update README.md 2018-11-29 23:05:43 +08:00
he liu a55df99199 Update README.md 2018-11-29 19:59:10 +08:00
刘河 3ea895feb5 添加多种模式 2018-11-29 19:55:24 +08:00
he liu 2463116b37 Update README.md 2018-11-27 16:50:23 +08:00
刘河 f0abcd98e4 添加gzip压缩 2018-11-27 16:49:13 +08:00
刘河 ef9bfa3290 修复转换bug 2018-11-09 00:14:58 +08:00
刘河 5f8df0d581 配置更改 2018-11-08 23:09:47 +08:00
cnlh 278292a51a Update README.md 2018-11-08 23:08:47 +08:00
cnlh d5e734d67e Update README.md 2018-11-08 20:02:58 +08:00
刘河 848c44b130 自动替换跨站点url 2018-11-08 19:53:30 +08:00
刘河 079d3dedad 客户端错误处理机制修改 2018-11-06 16:43:06 +08:00
cnlh 9ebb7c3209 Update README.md 2018-11-06 14:28:10 +08:00
刘河 d432e63eec 解决客户端内存泄漏问题 2018-11-05 20:39:31 +08:00
cnlh 2c9906e91c Update README.md 2018-11-05 01:40:56 +08:00
cnlh 9baddc51e1 Update README.md 2018-11-04 23:39:42 +08:00
cnlh a1ccbcde0e Update README.md 2018-11-04 23:27:06 +08:00
cnlh e0cab323ab Update README.md 2018-11-04 23:19:58 +08:00
刘河 ec7d181d5a 初始化 2018-11-04 23:19:22 +08:00
cnlh 952ffb0ddc Update README.md 2018-11-04 23:17:45 +08:00
cnlh f2d8678681 Update README.md 2018-11-04 22:54:27 +08:00
49 changed files with 21770 additions and 198 deletions
+3
View File
@@ -0,0 +1,3 @@
*.js linguist-language=golang
*.css linguist-language=golang
*.html linguist-language=golang
+17 -197
View File
@@ -1,201 +1,21 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
MIT License
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (c) 2018
1. Definitions.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+429 -1
View File
@@ -1,2 +1,430 @@
# easyProxy
简单、轻量级http代理服务器,主要应用于内网穿透
easyProxy是一款轻量级、高性能、功能最为强大的**内网穿透**代理服务器。目前支持**tcp、udp流量转发**,可支持任何tcp、udp上层协议(访问内网网站、本地支付接口调试、ssh访问、远程桌面,内网dns解析等等……),此外还**支持内网http代理、内网socks5代理**,可实现在非内网环境下如同使用vpn一样访问内网资源和设备的效果,同时**支持socks5验证,gzip、snnapy压缩(节省带宽和流量)**。
目前市面上提供类似服务的有花生壳、TeamView、GoToMyCloud等等,但要使用第三方的公网服务器就必须为第三方付费,并且这些服务都有各种各样的限制,此外,由于数据包会流经第三方,因此对数据安全也是一大隐患。
支持客户端与服务端连接中断自动重连,多路传输,大大的提高请求处理速度,go语言编写,无第三方依赖。
## 背景
![image](https://github.com/cnlh/easyProxy/blob/master/image/web.png?raw=true)
1. web管理模式,可配置多条tcp、udp隧道,多个域名代理等等----> [web管理模式](#web管理模式)
2. 内网多站点配合代理。----> [http反向代理请求](#http代理请求)
3. 想在外网通过ssh连接内网的机器,做云服务器到内网服务器端口的映射,或者做微信公众号开发、小程序开发等---->[tcp隧道模式](#tcp隧道模式)
4. 在非内网环境下使用内网dns,或者需要通过udp访问内网机器等---->[udp隧道模式](#udp隧道模式)
5. 在外网使用HTTP代理访问内网站点---->[http代理模式](#http代理模式)
6. 搭建一个内网穿透ss,在外网如同使用内网vpn一样访问内网资源或者设备----> [socks5代理模式](#socks5代理模式)
## 特点
- [x] 支持gzip、snappy压缩,减小传输过程流量消耗
- [x] 支持多站点配置,兼容多个内网网站,可处理相互之间的跳转包含关系
- [x] 断线自动重连
- [x] 支持多路传输,提高并发
- [x] 跨站自动匹配替换
- [x] 支持tcp隧道,提升访问效率
- [x] 支持udp隧道
- [x] 支持http代理
- [x] 支持内网穿透sock5代理,配合proxifer可达到vpn的效果,在外网访问内网资源或者设备,同时可以设置用户名和密码验证
- [x] 强大的web管理界面,可方便的设置的和管理隧道
- [x] 支持同时开多条tcp、udp隧道等等,且只需要开一个客户端和服务端
- [x] 支持一个服务端,多个客户端模式
## 目录
1. [安装](#安装)
2. [web管理模式](#web管理模式)(推荐)
3. [tcp隧道模式](#tcp隧道模式)
4. [udp隧道模式](#udp隧道模式)
5. [http反向代理请求](#http代理请求)
6. [socks5代理模式](#sock5代理模式)
7. [http代理模式](#http代理模式)
8. [数据压缩支持](#数据压缩支持)
9. [操作系统支持](#操作系统支持)
## 安装
1. release安装
> https://github.com/cnlh/easyProxy/releases
下载对应的系统版本即可(目前linux和windows只编译了64位的),服务端和客户端共用一个程序,go语言开发,无需任何第三方依赖
2. 源码安装
- 安装源码
> go get github.com/cnlh/easyProxy
- 编译(无第三方模块)
> go build
## web管理模式
![image](https://github.com/cnlh/easyProxy/blob/master/image/web2.png?raw=true)
### 介绍
可在网页上配置和管理各个tcp、udp隧道、内网站点代理等等,功能极为强大,操作也非常方便。
### 使用
**有两种模式:**
1、单客户端模式,所有的隧道流量均从这个单客户端转发。
- 服务端
```
./easyProxy -mode=webServer -tcpport=8284 -vkey=DKibZF5TXvic1g3kY
```
名称 | 含义
---|---
mode | 运行模式
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
- 客户端
```
./easyProxy -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
- 配置
进入web界面,公网ip:web界面端口(默认8080),密码为123
2、多客户端模式,不同的隧道流量均从不同的客户端转发。
- 服务端
```
./easyProxy -mode=webServer -tcpport=8284
```
名称 | 含义
---|---
mode | 运行模式
tcpport | 服务端与客户端通信端口
- 客户端
进入web管理界面,有详细的命令
- 配置
进入web界面,公网ip:web界面端口(默认8080),密码为123
### 配置文件/conf/app.conf
名称 | 含义
---|---
httpport | web管理端口
password | web界面管理密码
hostPort | 域名代理模式监听端口
## tcp隧道模式
### 场景及原理
较为适用于处理tcp连接,例如ssh,同时也适用于http等,访问服务端的8024端口相当于访问内网10.1.50.202机器的4000端口,构成如下所示的隧道。
![image](https://github.com/cnlh/easyProxy/blob/master/image/tcp.png?raw=true)
例如:
**背景:**
- 内网机器10.1.50.203提供了web服务80端口
- 有VPS一个,公网IP:123.206.77.88
**需求:**
在家里能够通过访问VPS的8024端口访问到内网机器A的80端口
### 使用
- 服务端
```
./easyProxy -mode=tunnelServer -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024 -target=10.1.50.203:80
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 外部访问端口
target | 目标地址,格式如上
- 客户端
```
./easyProxy -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
## udp隧道模式
### 场景及原理
**背景**
- 内网机器A提供了DNS解析服务,10.1.50.210:53端口
- 有VPS一个,公网IP:123.206.77.88
**需求:**
在家里能够通过设置本地dns为123.206.77.88,使用内网机器A进行域名解析服务.
访问vps的53端口相当于访问10.1.50.210的53端口,构成如下所示的隧道。
![image](https://github.com/cnlh/easyProxy/blob/master/image/udp.png?raw=true)
### 使用
- 服务端
```
./easyProxy -mode=udpServer -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=53 -target=10.1.50.210:53
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 公网vps的访问端口
target | 目标地址,格式如上
- 客户端
```
./easyProxy -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
## http代理请求
### 场景及原理
较为适用于http,也就是web站点的穿透,服务端与客户端之间建立连接,服务端收到http请求后,将请求发送到客户端,客户端再执行这个请求,并将结果返回给服务端,服务端收到后再返回。
<html>
<span style="color:red">特点:支持同时代理多个站点,不同站点之间有联系还可以实现匹配替换</span>
</html>
![image](https://github.com/cnlh/easyProxy/blob/master/image/http.png?raw=true)
**最终效果**:
- 访问a.server.com和访问10.1.50.203的80端口相同
- 访问b.server.com和访问10.1.50.202的80端口相同
- 访问c.server.com和访问10.1.50.201的80端口相同
### 使用
- 服务端
```
./easyProxy -mode=httpServer -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 代理的http端口(与nginx配合使用)
- 客户端
```
建立配置文件 config.json
```
```
./easyProxy -server=ip:port -config=config.json -vkey=DKibZF5TXvic1g3kY
```
名称 | 含义
---|---
config | 配置文件路径
### 配置文件config.json
```
{
"SiteList": [
{
"host": "a.ourcauc.com",
"url": "10.1.50.203",
"port": 80
},
{
"host": "b.ourcauc.com",
"url": "10.1.50.202",
"port": 80
},
{
"host": "c.ourcauc.com",
"url": "10.1.50.203",
"port": 80
}
],
"Replace": 0
}
```
名称 | 含义
---|---
SiteList | 本地解析的域名列表
host | 域名地址
url | 内网代理的地址
port | 内网代理的地址对应的端口
Replace | 是否自动匹配替换[(查看场景)](https://github.com/cnlh/easyProxy/issues/1)
### nginx代理配置示例
```
upstream nodejs {
server 127.0.0.1:8024;
keepalive 64;
}
server {
listen 80;
server_name a.ourcauc.com b.ourcauc.com c.ourcauc.com ;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://nodejs;
}
}
```
## 域名配置示例
> -a A 123.206.77.88
> -b A 123.206.77.88
> -c A 123.206.77.88
### 跨站自动匹配替换说明
例如,访问:a.ourcauc.com,该页面里面有一个超链接为10.1.50.202:80,将根据配置文件自动该将url替换为b.ourcauc.com,以达到跨站也可访问的效果,但需要提前在配置文件中配置这些站点。
如需开启,请加配置文件Replace值设置为1
>注意:开启可能导致不应该被替换的内容被替换,请谨慎开启
### 二级域名示范
[二级域名](https://github.com/cnlh/easyProxy/wiki/%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B)
## socks5代理模式
### 场景及原理
**原理**
主要用于socks5代理,也就是和ss类似,不过是代理内网。使用此模式时,可在非内网环境下配置本机的socks5代理(服务器ip、sock5代理端口),即可实现socks5代理,达到访问内网的网站的效果,配合proxifer等全局代理软件,即可如同使用内网vpn一样,访问内网网站,通过ssh连接内网机器等等……。
![image](https://github.com/cnlh/easyProxy/blob/master/image/sock5.png?raw=true)
### 使用
- 服务端
```
./easyProxy -mode=sock5ServerServer -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | 代理的http端口(socks5连接端口)
u | 验证的用户名
p | 验证的密码
**说明**:用户名和密码验证模式,仅部分socks5客户端支持,例如proxifer。
如需验证,在服务端命令后加上
```
-u=user -p=password
```
即可
- 客户端
```
./easyProxy -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
- 需要使用内网代理的机器
```
配置sock5代理即可,ip为外网服务器ip,端口为httpport,即可在外网环境使用内网啦!也可使用proxifer等全局代理软件。
```
如果设置了用户名和密码,记得填上用户名和密码
## http代理模式
### 场景及原理
主要用于HTTP代理,区别也就是HTTP代理和sock5代理的区别。使用此模式时,可在非内网环境下配置本机的HTTP代理(服务器ip、HTTP代理端口),即可实现HTTP代理,达到访问内网的网站的效果。
![image](https://github.com/cnlh/easyProxy/blob/master/image/httpProxy.png?raw=true)
### 使用
- 服务端
```
./easyProxy -mode=httpProxyServer -vkey=DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024
```
名称 | 含义
---|---
mode | 运行模式(client、server不写默认client)
vkey | 验证密钥
tcpport | 服务端与客户端通信端口
httpport | http代理连接端口
- 客户端
```
./easyProxy -server=ip:port -vkey=DKibZF5TXvic1g3kY
```
- 需要使用内网代理的机器
```
配置HTTP代理即可,ip为外网服务器ip,端口为httpport,即可在外网环境访问内网啦!
```
## 数据压缩支持
### 场景及原理
由于是内网穿透,内网客户端与服务端之间的隧道存在大量的数据交换,为节省流量,加快传输速度,由此本程序支持GZIP、SNNAPY两种形式的压缩,两者差异请自行选择。
### 注意点
- 所有模式均支持数据压缩
### 如何使用
**GZIP压缩**
- 在server端加上参数 -compress=gzip,例如在TCP隧道模式
```
./easyProxy -mode tunnelServer -vkey DKibZF5TXvic1g3kY -tcpport=8284 -httpport=8024 -target=10.1.50.203:80 -compress=gzip
```
**SNAPPY压缩**
将参数修改为snappy即可
## 操作系统支持
支持Windows、Linux、MacOSX等,无第三方依赖库。
Executable
+6
View File
@@ -0,0 +1,6 @@
appname = httpMonitor
httpport = 8080
runmode = dev
password=123
hostPort=8028
+3
View File
@@ -0,0 +1,3 @@
a.proxy.com,127.0.0.1:81,o2430bnq22jgnmcl
b.proxy.com,127.0.0.1:82,o2430bnq22jgnmcl
a.o.com,10.1.50.203:80,o2430bnq22jgnmcl
1 a.proxy.com 127.0.0.1:81 o2430bnq22jgnmcl
2 b.proxy.com 127.0.0.1:82 o2430bnq22jgnmcl
3 a.o.com 10.1.50.203:80 o2430bnq22jgnmcl
+8
View File
@@ -0,0 +1,8 @@
8021,tunnelServer,10.1.50.203:80,um80bbyvcaiw7n17,,,,1
8001,tunnelServer,10.1.50.101:22,h8vcpciko9lczxmb,,,gzip,0
8022,tunnelServer,10.1.50.196:4000,vcerzo01q16cdn9n,,,snappy,1
8002,udpServer,10.1.50.102:53,zcbsx5kp53cg5yqv,,,,0
8003,sock5Server,,9mq856pqq3jq05qv,,,snappy,1
8010,sock5Server,,0aj2xfec0mbkann5,test,test,gzip,0
8004,httpProxyServer,,y72zj8t074lslln0,,,gzip,0
0,hostServer,,o2430bnq22jgnmcl,,,,1
1 8021 tunnelServer 10.1.50.203:80 um80bbyvcaiw7n17 1
2 8001 tunnelServer 10.1.50.101:22 h8vcpciko9lczxmb gzip 0
3 8022 tunnelServer 10.1.50.196:4000 vcerzo01q16cdn9n snappy 1
4 8002 udpServer 10.1.50.102:53 zcbsx5kp53cg5yqv 0
5 8003 sock5Server 9mq856pqq3jq05qv snappy 1
6 8010 sock5Server 0aj2xfec0mbkann5 test test gzip 0
7 8004 httpProxyServer y72zj8t074lslln0 gzip 0
8 0 hostServer o2430bnq22jgnmcl 1
Executable
+20
View File
@@ -0,0 +1,20 @@
{
"Server": {
"ip": "123.206.77.88",
"tcp": 8224,
"vkey": "DKibZF5TXvic1g3kY",
"num": 10
},
"SiteList": [
{
"host": "a.server.ourcauc.com",
"url": "10.1.50.203",
"port": 80
},
{
"host": "b.server.ourcauc.com",
"url": "10.1.50.196",
"port": 4000
}
]
}
+117
View File
@@ -0,0 +1,117 @@
package controllers
import (
"github.com/astaxie/beego"
"github.com/cnlh/easyProxy/lib"
"strconv"
"strings"
)
type BaseController struct {
beego.Controller
controllerName string
actionName string
}
//初始化参数
func (s *BaseController) Prepare() {
controllerName, actionName := s.GetControllerAndAction()
s.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
s.actionName = strings.ToLower(actionName)
if s.GetSession("auth") != true {
s.Redirect("/login/index", 302)
}
}
//加载模板
func (s *BaseController) display(tpl ...string) {
var tplname string
if len(tpl) > 0 {
tplname = strings.Join([]string{tpl[0], "html"}, ".")
} else {
tplname = s.controllerName + "/" + s.actionName + ".html"
}
s.Data["menu"] = s.actionName
ip := s.Ctx.Request.Host
s.Data["ip"] = lib.Gethostbyname(ip[0:strings.LastIndex(ip, ":")])
s.Data["p"] = *lib.TcpPort
s.Data["proxyPort"] = beego.AppConfig.String("hostPort")
s.Layout = "public/layout.html"
s.TplName = tplname
}
//错误
func (s *BaseController) error() {
s.Layout = "public/layout.html"
s.TplName = "public/error.html"
}
//去掉没有err返回值的int
func (s *BaseController) GetIntNoErr(key string, def ...int) int {
strv := s.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
return def[0]
}
val, _ := strconv.Atoi(strv)
return val
}
//获取去掉错误的bool值
func (s *BaseController) GetBoolNoErr(key string, def ...bool) bool {
strv := s.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
return def[0]
}
val, _ := strconv.ParseBool(strv)
return val
}
//ajax正确返回
func (s *BaseController) AjaxOk(str string) {
s.Data["json"] = ajax(str, 1)
s.ServeJSON()
s.StopRun()
}
//ajax错误返回
func (s *BaseController) AjaxErr(str string) {
s.Data["json"] = ajax(str, 0)
s.ServeJSON()
s.StopRun()
}
//组装ajax
func ajax(str string, status int) (map[string]interface{}) {
json := make(map[string]interface{})
json["status"] = status
json["msg"] = str
return json
}
//ajax table返回
func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int) {
json := make(map[string]interface{})
json["data"] = list
json["draw"] = s.GetIntNoErr("draw")
json["err"] = ""
json["recordsTotal"] = recordsTotal
json["recordsFiltered"] = cnt
s.Data["json"] = json
s.ServeJSON()
s.StopRun()
}
//ajax table参数
func (s *BaseController) GetAjaxParams() (start, limit int) {
s.Ctx.Input.Bind(&start, "start")
s.Ctx.Input.Bind(&limit, "length")
return
}
func (s *BaseController) SetInfo(name string) {
s.Data["name"] = name
}
func (s *BaseController) SetType(name string) {
s.Data["type"] = name
}
+165
View File
@@ -0,0 +1,165 @@
package controllers
import (
"github.com/cnlh/easyProxy/lib"
)
type IndexController struct {
BaseController
}
func (s *IndexController) Index() {
s.SetInfo("使用说明")
s.display("index/index")
}
func (s *IndexController) Tcp() {
s.SetInfo("tcp隧道管理")
s.SetType("tunnelServer")
s.display("index/list")
}
func (s *IndexController) Udp() {
s.SetInfo("udp隧道管理")
s.SetType("udpServer")
s.display("index/list")
}
func (s *IndexController) Socks5() {
s.SetInfo("socks5管理")
s.SetType("sock5Server")
s.display("index/list")
}
func (s *IndexController) Http() {
s.SetInfo("http代理管理")
s.SetType("httpProxyServer")
s.display("index/list")
}
func (s *IndexController) Host() {
s.SetInfo("host模式管理")
s.SetType("hostServer")
s.display("index/list")
}
func (s *IndexController) GetTaskList() {
start, length := s.GetAjaxParams()
taskType := s.GetString("type")
list, cnt := lib.CsvDb.GetTaskList(start, length, taskType)
s.AjaxTable(list, cnt, cnt)
}
func (s *IndexController) Add() {
if s.Ctx.Request.Method == "GET" {
s.Data["type"] = s.GetString("type")
s.SetInfo("新增")
s.display()
} else {
t := &lib.TaskList{
TcpPort: s.GetIntNoErr("port"),
Mode: s.GetString("type"),
Target: s.GetString("target"),
VerifyKey: lib.GetRandomString(16),
U: s.GetString("u"),
P: s.GetString("p"),
Compress: s.GetString("compress"),
IsRun: 0,
}
lib.CsvDb.NewTask(t)
if err := lib.AddTask(t); err != nil {
s.AjaxErr(err.Error())
} else {
s.AjaxOk("添加成功")
}
}
}
func (s *IndexController) Edit() {
if s.Ctx.Request.Method == "GET" {
vKey := s.GetString("vKey")
if t, err := lib.CsvDb.GetTask(vKey); err != nil {
s.error()
} else {
s.Data["t"] = t
}
s.SetInfo("修改")
s.display()
} else {
vKey := s.GetString("vKey")
if t, err := lib.CsvDb.GetTask(vKey); err != nil {
s.error()
} else {
t.TcpPort = s.GetIntNoErr("port")
t.Mode = s.GetString("type")
t.Target = s.GetString("target")
t.U = s.GetString("u")
t.P = s.GetString("p")
t.Compress = s.GetString("compress")
lib.CsvDb.UpdateTask(t)
lib.StopServer(t.VerifyKey)
lib.StartTask(t.VerifyKey)
}
s.AjaxOk("修改成功")
}
}
func (s *IndexController) Stop() {
vKey := s.GetString("vKey")
if err := lib.StopServer(vKey); err != nil {
s.AjaxErr("停止失败")
}
s.AjaxOk("停止成功")
}
func (s *IndexController) Del() {
vKey := s.GetString("vKey")
if err := lib.DelTask(vKey); err != nil {
s.AjaxErr("删除失败")
}
s.AjaxOk("删除成功")
}
func (s *IndexController) Start() {
vKey := s.GetString("vKey")
if err := lib.StartTask(vKey); err != nil {
s.AjaxErr("开启失败")
}
s.AjaxOk("开启成功")
}
func (s *IndexController) HostList() {
if s.Ctx.Request.Method == "GET" {
s.Data["vkey"] = s.GetString("vkey")
s.SetInfo("域名列表")
s.display("index/hlist")
} else {
start, length := s.GetAjaxParams()
vkey := s.GetString("vkey")
list, cnt := lib.CsvDb.GetHostList(start, length, vkey)
s.AjaxTable(list, cnt, cnt)
}
}
func (s *IndexController) DelHost() {
host := s.GetString("host")
if err := lib.CsvDb.DelHost(host); err != nil {
s.AjaxErr("删除失败")
}
s.AjaxOk("删除成功")
}
func (s *IndexController) AddHost() {
if s.Ctx.Request.Method == "GET" {
s.Data["vkey"] = s.GetString("vkey")
s.SetInfo("新增")
s.display("index/hadd")
} else {
h := &lib.HostList{
Vkey: s.GetString("vkey"),
Host: s.GetString("host"),
Target: s.GetString("target"),
}
lib.CsvDb.NewHost(h)
s.AjaxOk("添加成功")
}
}
+27
View File
@@ -0,0 +1,27 @@
package controllers
import (
"github.com/astaxie/beego"
)
type LoginController struct {
beego.Controller
}
func (self *LoginController) Index() {
self.TplName = "login/index.html"
}
func (self *LoginController) Verify() {
if self.GetString("psd") == beego.AppConfig.String("password") {
self.SetSession("auth", true)
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "验证成功"}
self.ServeJSON()
} else {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "验证失败"}
self.ServeJSON()
}
}
func (self *LoginController) Out() {
self.SetSession("auth", false)
self.Redirect("/login/index", 302)
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Executable
+144
View File
@@ -0,0 +1,144 @@
package lib
import (
"errors"
"fmt"
"log"
"net"
"sync"
"time"
)
type TRPClient struct {
svrAddr string
tcpNum int
sync.Mutex
vKey string
}
func NewRPClient(svraddr string, tcpNum int, vKey string) *TRPClient {
c := new(TRPClient)
c.svrAddr = svraddr
c.tcpNum = tcpNum
c.vKey = vKey
return c
}
func (s *TRPClient) Start() error {
for i := 0; i < s.tcpNum; i++ {
go s.newConn()
}
return nil
}
//新建
func (s *TRPClient) newConn() error {
s.Lock()
conn, err := net.Dial("tcp", s.svrAddr)
if err != nil {
log.Println("连接服务端失败,五秒后将重连")
time.Sleep(time.Second * 5)
s.Unlock()
go s.newConn()
return err
}
s.Unlock()
return s.process(NewConn(conn))
}
func (s *TRPClient) process(c *Conn) error {
c.SetAlive()
if _, err := c.Write([]byte(getverifyval(s.vKey))); err != nil {
return err
}
c.wMain()
for {
flags, err := c.ReadFlag()
if err != nil {
log.Println("服务端断开,五秒后将重连", err)
time.Sleep(5 * time.Second)
go s.newConn()
break
}
switch flags {
case VERIFY_EER:
log.Fatalln("vkey:", s.vKey, "不正确,服务端拒绝连接,请检查")
case RES_SIGN: //代理请求模式
if err := s.dealHttp(c); err != nil {
log.Println(err)
return err
}
case WORK_CHAN: //隧道模式,每次开启10个,加快连接速度
for i := 0; i < 10; i++ {
go s.dealChan()
}
case RES_MSG:
log.Println("服务端返回错误。")
default:
log.Println("无法解析该错误。", flags)
}
}
return nil
}
//隧道模式处理
func (s *TRPClient) dealChan() error {
//创建一个tcp连接
conn, err := net.Dial("tcp", s.svrAddr)
if err != nil {
return err
}
//验证
if _, err := conn.Write([]byte(getverifyval(s.vKey))); err != nil {
return err
}
//默认长连接保持
c := NewConn(conn)
c.SetAlive()
//写标志
c.wChan()
//获取连接的host type(tcp or udp)
typeStr, host, en, de, err := c.GetHostFromConn()
if err != nil {
return err
}
//与目标建立连接
server, err := net.Dial(typeStr, host)
if err != nil {
log.Println(err)
return err
}
go relay(NewConn(server), c, de)
relay(c, NewConn(server), en)
return nil
}
//http模式处理
func (s *TRPClient) dealHttp(c *Conn) error {
buf := make([]byte, 1024*32)
en, de := c.GetCompressTypeFromConn()
n, err := c.ReadFromCompress(buf, de)
if err != nil {
c.wError()
return err
}
req, err := DecodeRequest(buf[:n])
if err != nil {
c.wError()
return err
}
respBytes, err := GetEncodeResponse(req)
if err != nil {
c.wError()
return err
}
c.wSign()
n, err = c.WriteCompress(respBytes, en)
if err != nil {
return err
}
if n != len(respBytes) {
return errors.New(fmt.Sprintf("发送数据长度错误,已经发送:%dbyte,总字节长:%dbyte\n", n, len(respBytes)))
}
return nil
}
Executable
+292
View File
@@ -0,0 +1,292 @@
package lib
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/binary"
"errors"
"fmt"
"github.com/golang/snappy"
"io"
"log"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type SnappyConn struct {
w *snappy.Writer
r *snappy.Reader
}
func NewSnappyConn(conn net.Conn) *SnappyConn {
c := new(SnappyConn)
c.w = snappy.NewBufferedWriter(conn)
c.r = snappy.NewReader(conn)
return c
}
func (s *SnappyConn) Write(b []byte) (n int, err error) {
if n, err = s.w.Write(b); err != nil {
return
}
err = s.w.Flush()
return
}
func (s *SnappyConn) Read(b []byte) (n int, err error) {
return s.r.Read(b)
}
type GzipConn struct {
w *gzip.Writer
r *gzip.Reader
}
func NewGzipConn(conn net.Conn) *GzipConn {
c := new(GzipConn)
c.w = gzip.NewWriter(conn)
c.r, err = gzip.NewReader(conn)
return c
}
func (s *GzipConn) Write(b []byte) (n int, err error) {
if n, err = s.w.Write(b); err != nil || err == io.EOF {
err = s.w.Flush()
s.w.Close()
return
}
err = s.w.Flush()
return
}
func (s *GzipConn) Read(b []byte) (n int, err error) {
return s.r.Read(b)
}
type Conn struct {
conn net.Conn
}
func NewConn(conn net.Conn) *Conn {
c := new(Conn)
c.conn = conn
return c
}
//读取指定内容长度
func (s *Conn) ReadLen(len int) ([]byte, error) {
raw := make([]byte, 0)
buff := make([]byte, 1024)
c := 0
for {
clen, err := s.Read(buff)
if err != nil && err != io.EOF {
return raw, err
}
raw = append(raw, buff[:clen]...)
if c += clen; c >= len {
break
}
}
if c != len {
return raw, errors.New(fmt.Sprintf("已读取长度错误,已读取%dbyte,需要读取%dbyte。", c, len))
}
return raw, nil
}
//获取长度
func (s *Conn) GetLen() (int, error) {
val := make([]byte, 4)
_, err := s.Read(val)
if err != nil {
return 0, err
}
nlen := binary.LittleEndian.Uint32(val)
if nlen <= 0 {
return 0, errors.New("数据长度错误")
}
return int(nlen), nil
}
//写入长度
func (s *Conn) WriteLen(buf []byte) (int, error) {
raw := bytes.NewBuffer([]byte{})
if err := binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
log.Println(err)
return 0, err
}
if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
log.Println(err)
return 0, err
}
return s.Write(raw.Bytes())
}
//读取flag
func (s *Conn) ReadFlag() (string, error) {
val := make([]byte, 4)
_, err := s.Read(val)
if err != nil {
return "", err
}
return string(val), err
}
//读取host 连接地址 压缩类型
func (s *Conn) GetHostFromConn() (typeStr string, host string, en, de int, err error) {
retry:
ltype := make([]byte, 3)
if _, err = s.Read(ltype); err != nil {
return
}
if typeStr = string(ltype); typeStr == TEST_FLAG {
en, de = s.GetCompressTypeFromConn()
goto retry
}
len, err := s.GetLen()
if err != nil {
return
}
hostByte := make([]byte, len)
if _, err = s.Read(hostByte); err != nil {
return
}
host = string(hostByte)
return
}
//写连接类型 和 host地址
func (s *Conn) WriteHost(ltype string, host string) (int, error) {
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, []byte(ltype))
binary.Write(raw, binary.LittleEndian, int32(len([]byte(host))))
binary.Write(raw, binary.LittleEndian, []byte(host))
return s.Write(raw.Bytes())
}
//设置连接为长连接
func (s *Conn) SetAlive() {
conn := s.conn.(*net.TCPConn)
conn.SetReadDeadline(time.Time{})
conn.SetKeepAlive(true)
conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
}
//从tcp报文中解析出host
func (s *Conn) GetHost() (method, address string, rb []byte, err error) {
var b [32 * 1024]byte
var n int
if n, err = s.Read(b[:]); err != nil {
return
}
rb = b[:n]
r, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
if err != nil {
log.Println("解析host出错:", err)
return
}
hostPortURL, err := url.Parse(r.Host)
if err != nil {
return
}
if hostPortURL.Opaque == "443" { //https访问
address = r.Host + ":443"
} else { //http访问
if strings.Index(hostPortURL.Host, ":") == -1 { //host不带端口, 默认80
address = r.Host + ":80"
} else {
address = r.Host
}
}
return
}
//压缩方式读
func (s *Conn) ReadFromCompress(b []byte, compress int) (int, error) {
switch compress {
case COMPRESS_GZIP_DECODE:
r, err := gzip.NewReader(s)
if err != nil {
return 0, err
}
return r.Read(b)
case COMPRESS_SNAPY_DECODE:
r := snappy.NewReader(s)
return r.Read(b)
case COMPRESS_NONE:
return s.Read(b)
}
return 0, nil
}
//压缩方式写
func (s *Conn) WriteCompress(b []byte, compress int) (n int, err error) {
switch compress {
case COMPRESS_GZIP_ENCODE:
w := gzip.NewWriter(s)
if n, err = w.Write(b); err == nil {
w.Flush()
}
err = w.Close()
case COMPRESS_SNAPY_ENCODE:
w := snappy.NewBufferedWriter(s)
if n, err = w.Write(b); err == nil {
w.Flush()
}
err = w.Close()
case COMPRESS_NONE:
n, err = s.Write(b)
}
return
}
//写压缩方式
func (s *Conn) WriteCompressType(en, de int) {
s.Write([]byte(strconv.Itoa(en) + strconv.Itoa(de)))
}
//获取压缩方式
func (s *Conn) GetCompressTypeFromConn() (en, de int) {
buf := make([]byte, 2)
s.Read(buf)
en, _ = strconv.Atoi(string(buf[0]))
de, _ = strconv.Atoi(string(buf[1]))
return
}
func (s *Conn) Close() error {
return s.conn.Close()
}
func (s *Conn) Write(b []byte) (int, error) {
return s.conn.Write(b)
}
func (s *Conn) Read(b []byte) (int, error) {
return s.conn.Read(b)
}
func (s *Conn) wError() (int, error) {
return s.Write([]byte(RES_MSG))
}
func (s *Conn) wSign() (int, error) {
return s.Write([]byte(RES_SIGN))
}
func (s *Conn) wMain() (int, error) {
return s.Write([]byte(WORK_MAIN))
}
func (s *Conn) wChan() (int, error) {
return s.Write([]byte(WORK_CHAN))
}
func (s *Conn) wTest() (int, error) {
return s.Write([]byte(TEST_FLAG))
}
+285
View File
@@ -0,0 +1,285 @@
package lib
import (
"encoding/csv"
"errors"
"log"
"os"
"strconv"
)
type TaskList struct {
TcpPort int //服务端与客户端通信端口
Mode string //启动方式
Target string //目标
VerifyKey string //flag
U string //socks5验证用户名
P string //socks5验证密码
Compress string //压缩方式
Start int //是否开启
IsRun int //是否在运行
ClientStatus int //客户端状态
}
type HostList struct {
Vkey string //服务端与客户端通信端口
Host string //启动方式
Target string //目标
}
func NewCsv(path string, bridge *Tunnel, runList map[string]interface{}) *Csv {
c := new(Csv)
c.Path = path
c.Bridge = bridge
c.RunList = runList
return c
}
type Csv struct {
Tasks []*TaskList
Path string
Bridge *Tunnel
RunList map[string]interface{}
Hosts []*HostList //域名列表
}
func (s *Csv) Init() {
s.LoadTaskFromCsv()
s.LoadHostFromCsv()
}
func (s *Csv) StoreTasksToCsv() {
// 创建文件
csvFile, err := os.Create(s.Path + "tasks.csv")
if err != nil {
log.Fatalf(err.Error())
}
defer csvFile.Close()
writer := csv.NewWriter(csvFile)
for _, task := range s.Tasks {
record := []string{
strconv.Itoa(task.TcpPort),
task.Mode,
task.Target,
task.VerifyKey,
task.U,
task.P,
task.Compress,
strconv.Itoa(task.Start),
}
err := writer.Write(record)
if err != nil {
log.Fatalf(err.Error())
}
}
writer.Flush()
}
func (s *Csv) LoadTaskFromCsv() {
// 打开文件
file, err := os.Open(s.Path + "tasks.csv")
if err != nil {
panic(err)
}
defer file.Close()
// 获取csv的reader
reader := csv.NewReader(file)
// 设置FieldsPerRecord为-1
reader.FieldsPerRecord = -1
// 读取文件中所有行保存到slice中
records, err := reader.ReadAll()
if err != nil {
panic(err)
}
var tasks []*TaskList
// 将每一行数据保存到内存slice中
for _, item := range records {
tcpPort, _ := strconv.Atoi(item[0])
Start, _ := strconv.Atoi(item[7])
post := &TaskList{
TcpPort: tcpPort,
Mode: item[1],
Target: item[2],
VerifyKey: item[3],
U: item[4],
P: item[5],
Compress: item[6],
Start: Start,
}
tasks = append(tasks, post)
}
s.Tasks = tasks
}
func (s *Csv) StoreHostToCsv() {
// 创建文件
csvFile, err := os.Create(s.Path + "hosts.csv")
if err != nil {
panic(err)
}
defer csvFile.Close()
// 获取csv的Writer
writer := csv.NewWriter(csvFile)
// 将map中的Post转换成slice,因为csv的Write需要slice参数
// 并写入csv文件
for _, host := range s.Hosts {
record := []string{
host.Host,
host.Target,
host.Vkey,
}
err1 := writer.Write(record)
if err1 != nil {
panic(err1)
}
}
// 确保所有内存数据刷到csv文件
writer.Flush()
}
func (s *Csv) LoadHostFromCsv() {
// 打开文件
file, err := os.Open(s.Path + "hosts.csv")
if err != nil {
panic(err)
}
defer file.Close()
// 获取csv的reader
reader := csv.NewReader(file)
// 设置FieldsPerRecord为-1
reader.FieldsPerRecord = -1
// 读取文件中所有行保存到slice中
records, err := reader.ReadAll()
if err != nil {
panic(err)
}
var hosts []*HostList
// 将每一行数据保存到内存slice中
for _, item := range records {
post := &HostList{
Vkey: item[2],
Host: item[0],
Target: item[1],
}
hosts = append(hosts, post)
}
s.Hosts = hosts
}
func (s *Csv) GetTaskList(start, length int, typeVal string) ([]*TaskList, int) {
list := make([]*TaskList, 0)
var cnt int
for _, v := range s.Tasks {
if v.Mode != typeVal {
continue
}
cnt++
if start--; start < 0 {
if length--; length > 0 {
if _, ok := s.RunList[v.VerifyKey]; ok {
v.IsRun = 1
} else {
v.IsRun = 0
}
if s, ok := s.Bridge.signalList[getverifyval(v.VerifyKey)]; ok {
if s.Len() > 0 {
v.ClientStatus = 1
} else {
v.ClientStatus = 0
}
} else {
v.ClientStatus = 0
}
list = append(list, v)
}
}
}
return list, cnt
}
func (s *Csv) NewTask(t *TaskList) {
s.Tasks = append(s.Tasks, t)
s.StoreTasksToCsv()
}
func (s *Csv) UpdateTask(t *TaskList) error {
for k, v := range s.Tasks {
if v.VerifyKey == t.VerifyKey {
s.Tasks = append(s.Tasks[:k], s.Tasks[k+1:]...)
s.Tasks = append(s.Tasks, t)
s.StoreTasksToCsv()
return nil
}
}
//TODO:待测试
return errors.New("不存在")
}
func (s *Csv) AddRunList(vKey string, svr interface{}) {
s.RunList[vKey] = svr
}
func (s *Csv) DelRunList(vKey string) {
delete(s.RunList, vKey)
}
func (s *Csv) DelTask(vKey string) error {
for k, v := range s.Tasks {
if v.VerifyKey == vKey {
s.Tasks = append(s.Tasks[:k], s.Tasks[k+1:]...)
s.StoreTasksToCsv()
return nil
}
}
return errors.New("不存在")
}
func (s *Csv) GetTask(vKey string) (v *TaskList, err error) {
for _, v = range s.Tasks {
if v.VerifyKey == vKey {
return
}
}
err = errors.New("未找到")
return
}
func (s *Csv) DelHost(host string) error {
for k, v := range s.Hosts {
if v.Host == host {
s.Hosts = append(s.Hosts[:k], s.Hosts[k+1:]...)
s.StoreHostToCsv()
return nil
}
}
return errors.New("不存在")
}
func (s *Csv) NewHost(t *HostList) {
s.Hosts = append(s.Hosts, t)
s.StoreHostToCsv()
}
func (s *Csv) GetHostList(start, length int, vKey string) ([]*HostList, int) {
list := make([]*HostList, 0)
var cnt int
for _, v := range s.Hosts {
if v.Vkey == vKey {
cnt++
if start--; start < 0 {
if length--; length > 0 {
list = append(list, v)
}
}
}
}
return list, cnt
}
+165
View File
@@ -0,0 +1,165 @@
package lib
import (
"errors"
"flag"
"log"
"reflect"
"strings"
"sync"
)
var (
configPath = flag.String("config", "config.json", "配置文件路径")
TcpPort = flag.Int("tcpport", 8284, "客户端与服务端通信端口")
httpPort = flag.Int("httpport", 8024, "对外监听的端口")
rpMode = flag.String("mode", "client", "启动模式")
tunnelTarget = flag.String("target", "10.1.50.203:80", "远程目标")
verifyKey = flag.String("vkey", "", "验证密钥")
u = flag.String("u", "", "socks5验证用户名")
p = flag.String("p", "", "socks5验证密码")
compress = flag.String("compress", "", "数据压缩方式(gzip|snappy)")
serverAddr = flag.String("server", "", "服务器地址ip:端口")
config Config
err error
RunList map[string]interface{} //运行中的任务
bridge *Tunnel
CsvDb *Csv
)
func init() {
RunList = make(map[string]interface{})
}
func InitMode() {
flag.Parse()
de, en := getCompressType(*compress)
if *rpMode == "client" {
JsonParse := NewJsonStruct()
if config, err = JsonParse.Load(*configPath); err != nil {
log.Println("配置文件加载失败")
}
stop := make(chan int)
for _, v := range strings.Split(*verifyKey, ",") {
log.Println("客户端启动,连接:", *serverAddr, " 验证令牌:", v)
go NewRPClient(*serverAddr, 2, v).Start()
}
<-stop
} else {
bridge = newTunnel(*TcpPort)
if err := bridge.StartTunnel(); err != nil {
log.Fatalln("服务端开启失败", err)
}
log.Println("服务端启动,监听tcp服务端端口:", *TcpPort)
if svr := newMode(*rpMode, bridge, *httpPort, *tunnelTarget, *u, *p, en, de, *verifyKey); svr != nil {
reflect.ValueOf(svr).MethodByName("Start").Call(nil)
} else {
log.Fatalln("启动模式不正确")
}
}
}
//从csv文件中恢复任务
func InitFromCsv() {
for _, v := range CsvDb.Tasks {
if v.Start == 1 {
log.Println(""+
"启动模式:", v.Mode, "监听端口:", v.TcpPort, "客户端令牌:", v.VerifyKey)
AddTask(v)
}
}
}
func newMode(mode string, bridge *Tunnel, httpPort int, tunnelTarget string, u string, p string, enCompress int, deCompress int, vkey string) interface{} {
switch mode {
case "httpServer":
return NewHttpModeServer(httpPort, bridge, enCompress, deCompress, vkey)
case "tunnelServer":
return NewTunnelModeServer(httpPort, tunnelTarget, ProcessTunnel, bridge, enCompress, deCompress, vkey)
case "sock5Server":
return NewSock5ModeServer(httpPort, u, p, bridge, enCompress, deCompress, vkey)
case "httpProxyServer":
return NewTunnelModeServer(httpPort, tunnelTarget, ProcessHttp, bridge, enCompress, deCompress, vkey)
case "udpServer":
return NewUdpModeServer(httpPort, tunnelTarget, bridge, enCompress, deCompress, vkey)
case "webServer":
InitCsvDb()
return NewWebServer(bridge)
case "hostServer":
return NewHostServer()
case "httpHostServer":
return NewTunnelModeServer(httpPort, tunnelTarget, ProcessHost, bridge, enCompress, deCompress, vkey)
}
return nil
}
func StopServer(cFlag string) error {
if v, ok := RunList[cFlag]; ok {
reflect.ValueOf(v).MethodByName("Close").Call(nil)
delete(RunList, cFlag)
if t := bridge.signalList[getverifyval(cFlag)]; t != nil {
if *verifyKey == "" { //多客户端模式重启相关隧道
for {
if t.Len() <= 0 {
break
}
t.Pop().Close()
}
delete(bridge.signalList, getverifyval(cFlag))
delete(bridge.tunnelList, getverifyval(cFlag))
}
}
if t, err := CsvDb.GetTask(cFlag); err != nil {
return err
} else {
t.Start = 0
CsvDb.UpdateTask(t)
}
return nil
}
return errors.New("未在运行中")
}
func AddTask(t *TaskList) error {
de, en := getCompressType(t.Compress)
if svr := newMode(t.Mode, bridge, t.TcpPort, t.Target, t.U, t.P, en, de, t.VerifyKey); svr != nil {
RunList[t.VerifyKey] = svr
go func() {
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
if err.Interface() != nil {
log.Println("客户端", t.VerifyKey, "启动失败,错误:", err)
delete(RunList, t.VerifyKey)
}
}()
} else {
return errors.New("启动模式不正确")
}
return nil
}
func StartTask(vKey string) error {
if t, err := CsvDb.GetTask(vKey); err != nil {
return err
} else {
AddTask(t)
t.Start = 1
CsvDb.UpdateTask(t)
}
return nil
}
func DelTask(vKey string) error {
if err := StopServer(vKey); err != nil {
return err
}
return CsvDb.DelTask(vKey)
}
func InitCsvDb() *Csv {
var once sync.Once
once.Do(func() {
CsvDb = NewCsv("./conf/", bridge, RunList)
CsvDb.Init()
})
return CsvDb
}
Executable
+290
View File
@@ -0,0 +1,290 @@
package lib
import (
"errors"
"fmt"
"github.com/astaxie/beego"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
)
const (
VERIFY_EER = "vkey"
WORK_MAIN = "main"
WORK_CHAN = "chan"
RES_SIGN = "sign"
RES_MSG = "msg0"
TEST_FLAG = "tst"
CONN_TCP = "tcp"
CONN_UDP = "udp"
)
type HttpModeServer struct {
bridge *Tunnel
httpPort int
enCompress int
deCompress int
vKey string
}
func NewHttpModeServer(httpPort int, bridge *Tunnel, enCompress int, deCompress int, vKey string) *HttpModeServer {
s := new(HttpModeServer)
s.bridge = bridge
s.httpPort = httpPort
s.enCompress = enCompress
s.deCompress = deCompress
s.vKey = vKey
return s
}
//开始
func (s *HttpModeServer) Start() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
retry:
err, conn := s.bridge.GetSignal(getverifyval(s.vKey))
if err != nil {
BadRequest(w)
}
if err := s.writeRequest(r, conn); err != nil {
log.Println(err)
conn.Close()
goto retry
return
}
err = s.writeResponse(w, conn)
if err != nil {
log.Println(err)
conn.Close()
goto retry
return
}
s.bridge.ReturnSignal(conn, getverifyval(s.vKey))
})
log.Fatalln(http.ListenAndServe(fmt.Sprintf(":%d", s.httpPort), nil))
}
//req转为bytes发送给client端
func (s *HttpModeServer) writeRequest(r *http.Request, conn *Conn) error {
raw, err := EncodeRequest(r)
if err != nil {
return err
}
conn.wSign()
conn.WriteCompressType(s.enCompress, s.deCompress)
c, err := conn.WriteCompress(raw, s.enCompress)
if err != nil {
return err
}
if c != len(raw) {
return errors.New("写出长度与字节长度不一致。")
}
return nil
}
//从client读取出Response
func (s *HttpModeServer) writeResponse(w http.ResponseWriter, c *Conn) error {
flags, err := c.ReadFlag()
if err != nil {
return err
}
switch flags {
case RES_SIGN:
buf := make([]byte, 1024*32)
n, err := c.ReadFromCompress(buf, s.deCompress)
if err != nil {
return err
}
resp, err := DecodeResponse(buf[:n])
if err != nil {
return err
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
for k, v := range resp.Header {
for _, v2 := range v {
w.Header().Set(k, v2)
}
}
w.WriteHeader(resp.StatusCode)
w.Write(bodyBytes)
case RES_MSG:
BadRequest(w)
return errors.New("客户端请求出错")
default:
BadRequest(w)
return errors.New("无法解析此错误")
}
return nil
}
type process func(c *Conn, s *TunnelModeServer) error
type TunnelModeServer struct {
httpPort int
tunnelTarget string
process process
bridge *Tunnel
listener *net.TCPListener
enCompress int
deCompress int
vKey string
}
func NewTunnelModeServer(httpPort int, tunnelTarget string, process process, bridge *Tunnel, enCompress int, deCompress int, vKey string) *TunnelModeServer {
s := new(TunnelModeServer)
s.httpPort = httpPort
s.bridge = bridge
s.tunnelTarget = tunnelTarget
s.process = process
s.enCompress = enCompress
s.deCompress = deCompress
s.vKey = vKey
return s
}
//开始
func (s *TunnelModeServer) Start() error {
s.listener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.httpPort, ""})
if err != nil {
return err
}
for {
conn, err := s.listener.AcceptTCP()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
break
}
log.Println(err)
continue
}
go s.process(NewConn(conn), s)
}
return nil
}
func (s *TunnelModeServer) Close() error {
return s.listener.Close()
}
//tcp隧道模式
func ProcessTunnel(c *Conn, s *TunnelModeServer) error {
link := s.bridge.GetTunnel(getverifyval(s.vKey), s.enCompress, s.deCompress)
if _, err := link.WriteHost(CONN_TCP, s.tunnelTarget); err != nil {
link.Close()
c.Close()
log.Println(err)
return err
}
go relay(link, c, s.enCompress)
relay(c, link, s.deCompress)
return nil
}
//http代理模式
func ProcessHttp(c *Conn, s *TunnelModeServer) error {
method, addr, rb, err := c.GetHost()
if err != nil {
c.Close()
return err
}
link := s.bridge.GetTunnel(getverifyval(s.vKey), s.enCompress, s.deCompress)
if _, err := link.WriteHost(CONN_TCP, addr); err != nil {
c.Close()
link.Close()
log.Println(err)
return err
}
if method == "CONNECT" {
fmt.Fprint(c, "HTTP/1.1 200 Connection established\r\n")
} else {
link.WriteCompress(rb, s.enCompress)
}
go relay(link, c, s.enCompress)
relay(c, link, s.deCompress)
return nil
}
//多客户端域名代理
func ProcessHost(c *Conn, s *TunnelModeServer) error {
method, addr, rb, err := c.GetHost()
if err != nil {
c.Close()
return err
}
host, task, err := getKeyByHost(addr)
if err != nil {
c.Close()
return err
}
de, en := getCompressType(task.Compress)
link := s.bridge.GetTunnel(getverifyval(host.Vkey), en, de)
if _, err := link.WriteHost(CONN_TCP, host.Target); err != nil {
c.Close()
link.Close()
log.Println(err)
return err
}
if method == "CONNECT" {
fmt.Fprint(c, "HTTP/1.1 200 Connection established\r\n")
} else {
link.WriteCompress(rb, en)
}
go relay(link, c, en)
relay(c, link, de)
return nil
}
//web管理方式
type WebServer struct {
bridge *Tunnel
}
//开始
func (s *WebServer) Start() {
InitFromCsv()
p, _ := beego.AppConfig.Int("hostPort")
t := &TaskList{
TcpPort: p,
Mode: "httpHostServer",
Target: "",
VerifyKey: "",
U: "",
P: "",
Compress: "",
Start: 1,
IsRun: 0,
ClientStatus: 0,
}
AddTask(t)
beego.BConfig.WebConfig.Session.SessionOn = true
log.Println("web管理启动,访问端口为",beego.AppConfig.String("httpport"))
beego.Run()
}
func NewWebServer(bridge *Tunnel) *WebServer {
s := new(WebServer)
s.bridge = bridge
return s
}
//host
type HostServer struct {
}
//开始
func (s *HostServer) Start() error {
return nil
}
func NewHostServer() *HostServer {
s := new(HostServer)
return s
}
func (s *HostServer) Close() error {
return nil
}
Executable
+303
View File
@@ -0,0 +1,303 @@
package lib
import (
"encoding/binary"
"errors"
"io"
"log"
"net"
"strconv"
"strings"
)
const (
ipV4 = 1
domainName = 3
ipV6 = 4
connectMethod = 1
bindMethod = 2
associateMethod = 3
// The maximum packet size of any udp Associate packet, based on ethernet's max size,
// minus the IP and UDP headers. IPv4 has a 20 byte header, UDP adds an
// additional 4 bytes. This is a total overhead of 24 bytes. Ethernet's
// max packet size is 1500 bytes, 1500 - 24 = 1476.
maxUDPPacketSize = 1476
)
const (
succeeded uint8 = iota
serverFailure
notAllowed
networkUnreachable
hostUnreachable
connectionRefused
ttlExpired
commandNotSupported
addrTypeNotSupported
)
const (
UserPassAuth = uint8(2)
userAuthVersion = uint8(1)
authSuccess = uint8(0)
authFailure = uint8(1)
)
type Sock5ModeServer struct {
bridge *Tunnel
httpPort int
u string //用户名
p string //密码
enCompress int
deCompress int
isVerify bool
listener net.Listener
vKey string
}
func (s *Sock5ModeServer) handleRequest(c net.Conn) {
/*
The SOCKS request is formed as follows:
+----+-----+-------+------+----------+----------+
|VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
*/
header := make([]byte, 3)
_, err := io.ReadFull(c, header)
if err != nil {
log.Println("illegal request", err)
c.Close()
return
}
switch header[1] {
case connectMethod:
s.handleConnect(c)
case bindMethod:
s.handleBind(c)
case associateMethod:
s.handleUDP(c)
default:
s.sendReply(c, commandNotSupported)
c.Close()
}
}
func (s *Sock5ModeServer) sendReply(c net.Conn, rep uint8) {
reply := []byte{
5,
rep,
0,
1,
}
localAddr := c.LocalAddr().String()
localHost, localPort, _ := net.SplitHostPort(localAddr)
ipBytes := net.ParseIP(localHost).To4()
nPort, _ := strconv.Atoi(localPort)
reply = append(reply, ipBytes...)
portBytes := make([]byte, 2)
binary.BigEndian.PutUint16(portBytes, uint16(nPort))
reply = append(reply, portBytes...)
c.Write(reply)
}
func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) (proxyConn *Conn, err error) {
addrType := make([]byte, 1)
c.Read(addrType)
var host string
switch addrType[0] {
case ipV4:
ipv4 := make(net.IP, net.IPv4len)
c.Read(ipv4)
host = ipv4.String()
case ipV6:
ipv6 := make(net.IP, net.IPv6len)
c.Read(ipv6)
host = ipv6.String()
case domainName:
var domainLen uint8
binary.Read(c, binary.BigEndian, &domainLen)
domain := make([]byte, domainLen)
c.Read(domain)
host = string(domain)
default:
s.sendReply(c, addrTypeNotSupported)
err = errors.New("Address type not supported")
return nil, err
}
var port uint16
binary.Read(c, binary.BigEndian, &port)
// connect to host
addr := net.JoinHostPort(host, strconv.Itoa(int(port)))
client := s.bridge.GetTunnel(getverifyval(s.vKey),s.enCompress,s.deCompress)
s.sendReply(c, succeeded)
var ltype string
if command == associateMethod {
ltype = CONN_UDP
} else {
ltype = CONN_TCP
}
_, err = client.WriteHost(ltype, addr)
return client, nil
}
func (s *Sock5ModeServer) handleConnect(c net.Conn) {
proxyConn, err := s.doConnect(c, connectMethod)
if err != nil {
log.Println(err)
c.Close()
} else {
go relay(proxyConn, NewConn(c), s.enCompress)
go relay(NewConn(c), proxyConn, s.deCompress)
}
}
// passive mode
func (s *Sock5ModeServer) handleBind(c net.Conn) {
}
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
log.Println("UDP Associate")
/*
+----+------+------+----------+----------+----------+
|RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
+----+------+------+----------+----------+----------+
| 2 | 1 | 1 | Variable | 2 | Variable |
+----+------+------+----------+----------+----------+
*/
buf := make([]byte, 3)
c.Read(buf)
// relay udp datagram silently, without any notification to the requesting client
if buf[2] != 0 {
// does not support fragmentation, drop it
log.Println("does not support fragmentation, drop")
dummy := make([]byte, maxUDPPacketSize)
c.Read(dummy)
}
proxyConn, err := s.doConnect(c, associateMethod)
if err != nil {
c.Close()
} else {
go relay(proxyConn, NewConn(c), s.enCompress)
go relay(NewConn(c), proxyConn, s.deCompress)
}
}
func (s *Sock5ModeServer) handleNewConn(c net.Conn) {
buf := make([]byte, 2)
if _, err := io.ReadFull(c, buf); err != nil {
log.Println("negotiation err", err)
c.Close()
return
}
if version := buf[0]; version != 5 {
log.Println("only support socks5, request from: ", c.RemoteAddr())
c.Close()
return
}
nMethods := buf[1]
methods := make([]byte, nMethods)
if len, err := c.Read(methods); len != int(nMethods) || err != nil {
log.Println("wrong method")
c.Close()
return
}
if s.isVerify {
buf[1] = UserPassAuth
c.Write(buf)
if err := s.Auth(c); err != nil {
c.Close()
log.Println("验证失败:", err)
return
}
} else {
buf[1] = 0
c.Write(buf)
}
s.handleRequest(c)
}
func (s *Sock5ModeServer) Auth(c net.Conn) error {
header := []byte{0, 0}
if _, err := io.ReadAtLeast(c, header, 2); err != nil {
return err
}
if header[0] != userAuthVersion {
return errors.New("验证方式不被支持")
}
userLen := int(header[1])
user := make([]byte, userLen)
if _, err := io.ReadAtLeast(c, user, userLen); err != nil {
return err
}
if _, err := c.Read(header[:1]); err != nil {
return errors.New("密码长度获取错误")
}
passLen := int(header[0])
pass := make([]byte, passLen)
if _, err := io.ReadAtLeast(c, pass, passLen); err != nil {
return err
}
if string(pass) == s.p && string(user) == s.u {
if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil {
return err
}
return nil
} else {
if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil {
return err
}
return errors.New("验证不通过")
}
return errors.New("未知错误")
}
func (s *Sock5ModeServer) Start() error {
s.listener, err = net.Listen("tcp", ":"+strconv.Itoa(s.httpPort))
if err != nil {
return err
}
for {
conn, err := s.listener.Accept()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
break
}
log.Fatal("accept error: ", err)
}
go s.handleNewConn(conn)
}
return nil
}
func (s *Sock5ModeServer) Close() error {
return s.listener.Close()
}
func NewSock5ModeServer(httpPort int, u, p string, brige *Tunnel, enCompress int, deCompress int, vKey string) *Sock5ModeServer {
s := new(Sock5ModeServer)
s.httpPort = httpPort
s.bridge = brige
if u != "" && p != "" {
s.isVerify = true
s.u = u
s.p = p
} else {
s.isVerify = false
}
s.enCompress = enCompress
s.deCompress = deCompress
s.vKey = vKey
return s
}
Executable
+184
View File
@@ -0,0 +1,184 @@
package lib
import (
"errors"
"log"
"net"
"sync"
"time"
)
type list struct {
connList chan *Conn
}
func (l *list) Add(c *Conn) {
l.connList <- c
}
func (l *list) Pop() *Conn {
return <-l.connList
}
func (l *list) Len() int {
return len(l.connList)
}
func newList() *list {
l := new(list)
l.connList = make(chan *Conn, 100)
return l
}
type Tunnel struct {
tunnelPort int //通信隧道端口
listener *net.TCPListener //server端监听
signalList map[string]*list //通信
tunnelList map[string]*list //隧道
sync.Mutex
}
func newTunnel(tunnelPort int) *Tunnel {
t := new(Tunnel)
t.tunnelPort = tunnelPort
t.signalList = make(map[string]*list)
t.tunnelList = make(map[string]*list)
return t
}
func (s *Tunnel) StartTunnel() error {
var err error
s.listener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.tunnelPort, ""})
if err != nil {
return err
}
go s.tunnelProcess()
return nil
}
//tcp server
func (s *Tunnel) tunnelProcess() error {
var err error
for {
conn, err := s.listener.Accept()
if err != nil {
log.Println(err)
continue
}
go s.cliProcess(NewConn(conn))
}
return err
}
//验证失败,返回错误验证flag,并且关闭连接
func (s *Tunnel) verifyError(c *Conn) {
c.conn.Write([]byte(VERIFY_EER))
c.conn.Close()
}
func (s *Tunnel) cliProcess(c *Conn) error {
c.conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(5) * time.Second))
vval := make([]byte, 32)
if _, err := c.conn.Read(vval); err != nil {
log.Println("客户端读超时。客户端地址为::", c.conn.RemoteAddr())
c.conn.Close()
return err
}
//TODO:暂时取消
if !verify(string(vval)) {
log.Println("当前客户端连接校验错误,关闭此客户端:", c.conn.RemoteAddr())
s.verifyError(c)
return err
}
c.conn.(*net.TCPConn).SetReadDeadline(time.Time{})
//做一个判断 添加到对应的channel里面以供使用
if flag, err := c.ReadFlag(); err != nil {
return err
} else {
return s.typeDeal(flag, c, string(vval))
}
}
//tcp连接类型区分
func (s *Tunnel) typeDeal(typeVal string, c *Conn, cFlag string) error {
switch typeVal {
case WORK_MAIN:
s.addList(s.signalList, c, cFlag)
case WORK_CHAN:
s.addList(s.tunnelList, c, cFlag)
default:
return errors.New("无法识别")
}
c.SetAlive()
return nil
}
//加到对应的list中
func (s *Tunnel) addList(m map[string]*list, c *Conn, cFlag string) {
s.Lock()
if v, ok := m[cFlag]; ok {
v.Add(c)
} else {
l := newList()
l.Add(c)
m[cFlag] = l
}
s.Unlock()
}
//新建隧道
func (s *Tunnel) newChan(cFlag string) {
s.wait(s.signalList, cFlag)
retry:
connPass := s.signalList[cFlag].Pop()
_, err := connPass.conn.Write([]byte("chan"))
if err != nil {
log.Println(err)
goto retry
}
s.signalList[cFlag].Add(connPass)
}
//得到一个tcp隧道
func (s *Tunnel) GetTunnel(cFlag string, en, de int) *Conn {
if v, ok := s.tunnelList[cFlag]; !ok || v.Len() < 10 { //新建通道
go s.newChan(cFlag)
}
retry:
s.wait(s.tunnelList, cFlag)
c := s.tunnelList[cFlag].Pop()
if _, err := c.wTest(); err != nil {
c.Close()
goto retry
}
c.WriteCompressType(en, de)
return c
}
//得到一个通信通道
func (s *Tunnel) GetSignal(cFlag string) (err error, conn *Conn) {
if v, ok := s.signalList[cFlag]; !ok || v.Len() == 0 {
err = errors.New("客户端未连接")
return
}
conn = s.signalList[cFlag].Pop()
return
}
//重回slice 复用
func (s *Tunnel) ReturnSignal(conn *Conn, cFlag string) {
if v, ok := s.signalList[cFlag]; ok {
v.Add(conn)
}
}
//等待
func (s *Tunnel) wait(m map[string]*list, cFlag string) {
ticker := time.NewTicker(time.Millisecond * 100)
for {
<-ticker.C
if _, ok := m[cFlag]; ok {
ticker.Stop()
break
}
}
}
Executable
+81
View File
@@ -0,0 +1,81 @@
package lib
import (
"fmt"
"io"
"log"
"net"
"strings"
"time"
)
type UdpModeServer struct {
bridge *Tunnel
udpPort int //监听的udp端口
tunnelTarget string //udp目标地址
listener *net.UDPConn
udpMap map[string]*Conn
enCompress int
deCompress int
vKey string
}
func NewUdpModeServer(udpPort int, tunnelTarget string, bridge *Tunnel, enCompress int, deCompress int, vKey string) *UdpModeServer {
s := new(UdpModeServer)
s.udpPort = udpPort
s.tunnelTarget = tunnelTarget
s.bridge = bridge
s.udpMap = make(map[string]*Conn)
s.enCompress = enCompress
s.deCompress = deCompress
s.vKey = vKey
return s
}
//开始
func (s *UdpModeServer) Start() error {
s.listener, err = net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), s.udpPort, ""})
if err != nil {
return err
}
data := make([]byte, 1472) //udp数据包大小
for {
n, addr, err := s.listener.ReadFromUDP(data)
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
break
}
log.Println(err)
continue
}
go s.process(addr, data[:n])
}
return nil
}
//TODO:效率问题有待解决
func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
fmt.Println(addr.String())
fmt.Println(string(data))
conn := s.bridge.GetTunnel(getverifyval(s.vKey),s.enCompress,s.deCompress)
if _, err := conn.WriteHost(CONN_UDP, s.tunnelTarget); err != nil {
conn.Close()
return
}
conn.WriteCompress(data, s.enCompress)
go func(addr *net.UDPAddr, conn *Conn) {
buf := make([]byte, 1024)
conn.conn.SetReadDeadline(time.Now().Add(time.Duration(time.Second * 3)))
n, err := conn.ReadFromCompress(buf, s.deCompress)
if err != nil || err == io.EOF {
conn.Close()
return
}
s.listener.WriteToUDP(buf[:n], addr)
conn.Close()
}(addr, conn)
}
func (s *UdpModeServer) Close() error {
return s.listener.Close()
}
Executable
+293
View File
@@ -0,0 +1,293 @@
package lib
import (
"bufio"
"bytes"
"compress/gzip"
"crypto/md5"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"strconv"
"strings"
"time"
)
var (
disabledRedirect = errors.New("disabled redirect.")
)
const (
COMPRESS_NONE = iota
COMPRESS_SNAPY_ENCODE
COMPRESS_SNAPY_DECODE
COMPRESS_GZIP_ENCODE
COMPRESS_GZIP_DECODE
)
func BadRequest(w http.ResponseWriter) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
}
//发送请求并转为bytes
func GetEncodeResponse(req *http.Request) ([]byte, error) {
var respBytes []byte
client := new(http.Client)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return disabledRedirect
}
resp, err := client.Do(req)
disRedirect := err != nil && strings.Contains(err.Error(), disabledRedirect.Error())
if err != nil && !disRedirect {
return respBytes, err
}
if !disRedirect {
defer resp.Body.Close()
} else {
resp.Body = nil
resp.ContentLength = 0
}
respBytes, err = EncodeResponse(resp)
return respBytes, nil
}
// 将request转为bytes
func EncodeRequest(r *http.Request) ([]byte, error) {
raw := bytes.NewBuffer([]byte{})
reqBytes, err := httputil.DumpRequest(r, true)
if err != nil {
return nil, err
}
binary.Write(raw, binary.LittleEndian, bool(r.URL.Scheme == "https"))
binary.Write(raw, binary.LittleEndian, reqBytes)
return raw.Bytes(), nil
}
// 将字节转为request
func DecodeRequest(data []byte) (*http.Request, error) {
req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(data[1:])))
if err != nil {
return nil, err
}
str := strings.Split(req.Host, ":")
req.Host, err = getHost(str[0])
if err != nil {
return nil, err
}
scheme := "http"
if data[0] == 1 {
scheme = "https"
}
req.URL, _ = url.Parse(fmt.Sprintf("%s://%s%s", scheme, req.Host, req.RequestURI))
req.RequestURI = ""
return req, nil
}
//// 将response转为字节
func EncodeResponse(r *http.Response) ([]byte, error) {
respBytes, err := httputil.DumpResponse(r, true)
if err != nil {
return nil, err
}
if config.Replace == 1 {
respBytes = replaceHost(respBytes)
}
return respBytes, nil
}
// 将字节转为response
func DecodeResponse(data []byte) (*http.Response, error) {
resp, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(data)), nil)
if err != nil {
return nil, err
}
return resp, nil
}
func getHost(str string) (string, error) {
for _, v := range config.SiteList {
if v.Host == str {
return v.Url + ":" + strconv.Itoa(v.Port), nil
}
}
return "", errors.New("没有找到解析的的host!")
}
func replaceHost(resp []byte) []byte {
str := string(resp)
for _, v := range config.SiteList {
str = strings.Replace(str, v.Url+":"+strconv.Itoa(v.Port), v.Host, -1)
str = strings.Replace(str, v.Url, v.Host, -1)
}
return []byte(str)
}
func relay(in, out *Conn, compressType int) {
buf := make([]byte, 32*1024)
switch compressType {
case COMPRESS_GZIP_ENCODE:
//TODO:GZIP压缩存在问题有待解决
w := gzip.NewWriter(in)
for {
n, err := out.Read(buf)
if err != nil || err == io.EOF {
break
}
if _, err = w.Write(buf[:n]); err != nil {
break
}
if err = w.Flush(); err != nil {
log.Println(err)
break
}
}
w.Close()
case COMPRESS_SNAPY_ENCODE:
io.Copy(NewSnappyConn(in.conn), out)
case COMPRESS_GZIP_DECODE:
io.Copy(in, NewGzipConn(out.conn))
case COMPRESS_SNAPY_DECODE:
io.Copy(in, NewSnappyConn(out.conn))
default:
io.Copy(in, out)
}
out.Close()
in.Close()
}
type Site struct {
Host string
Url string
Port int
}
type Config struct {
SiteList []Site
Replace int
}
type JsonStruct struct {
}
func NewJsonStruct() *JsonStruct {
return &JsonStruct{}
}
func (jst *JsonStruct) Load(filename string) (Config, error) {
data, err := ioutil.ReadFile(filename)
config := Config{}
if err != nil {
return config, errors.New("配置文件打开错误")
}
err = json.Unmarshal(data, &config)
if err != nil {
return config, errors.New("配置文件解析错误")
}
return config, nil
}
//判断压缩方式
func getCompressType(compress string) (int, int) {
switch compress {
case "":
return COMPRESS_NONE, COMPRESS_NONE
case "gzip":
return COMPRESS_GZIP_DECODE, COMPRESS_GZIP_ENCODE
case "snappy":
return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
default:
log.Fatalln("数据压缩格式错误")
}
return COMPRESS_NONE, COMPRESS_NONE
}
// 简单的一个校验值
func getverifyval(vkey string) string {
//单客户端模式
if *verifyKey != "" {
return Md5(*verifyKey)
}
return Md5(vkey)
}
func verify(verifyKeyMd5 string) bool {
if getverifyval(*verifyKey) == verifyKeyMd5 {
return true
}
if *verifyKey == "" {
for _, v := range CsvDb.Tasks {
if _, ok := RunList[v.VerifyKey]; getverifyval(v.VerifyKey) == verifyKeyMd5 && ok {
return true
}
}
}
return false
}
func getKeyByHost(host string) (h *HostList, t *TaskList, err error) {
for _, v := range CsvDb.Hosts {
if strings.Contains(host, v.Host) {
h = v
t, err = CsvDb.GetTask(v.Vkey)
if err != nil {
return
}
return
}
}
err = errors.New("未找到host对应的内网目标")
return
}
//生成32位md5字串
func Md5(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
//生成随机验证密钥
func GetRandomString(l int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyz"
bytes := []byte(str)
result := []byte{}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < l; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
return string(result)
}
func Gethostbyname(hostname string) string {
if !DomainCheck(hostname) {
return hostname
}
ips, _ := net.LookupIP(hostname)
if ips != nil {
for _, v := range ips {
if v.To4() != nil {
return v.String()
}
}
}
return ""
}
func DomainCheck(domain string) bool {
var match bool
IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
match, _ = regexp.MatchString(IsLine, domain)
if !match {
match, _ = regexp.MatchString(NotLine, domain)
}
return match
}
Executable
+10
View File
@@ -0,0 +1,10 @@
package main
import (
"github.com/cnlh/easyProxy/lib"
_ "github.com/cnlh/easyProxy/routers"
)
func main() {
lib.InitMode()
}
+12
View File
@@ -0,0 +1,12 @@
package routers
import (
"github.com/astaxie/beego"
"github.com/cnlh/easyProxy/controllers"
)
func init() {
beego.Router("/", &controllers.IndexController{}, "*:Index")
beego.AutoRouter(&controllers.IndexController{})
beego.AutoRouter(&controllers.LoginController{})
}
+4
View File
File diff suppressed because one or more lines are too long
+15240
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.
Binary file not shown.
+2671
View File
File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 434 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Vendored Executable
+194
View File
File diff suppressed because one or more lines are too long
+27
View File
@@ -0,0 +1,27 @@
(function () {
"use strict";
var treeviewMenu = $('.app-menu');
// Toggle Sidebar
$('[data-toggle="sidebar"]').click(function(event) {
event.preventDefault();
$('.app').toggleClass('sidenav-toggled');
});
// Activate sidebar treeview toggle
$("[data-toggle='treeview']").click(function(event) {
event.preventDefault();
if(!$(this).parent().hasClass('is-expanded')) {
treeviewMenu.find("[data-toggle='treeview']").parent().removeClass('is-expanded');
}
$(this).parent().toggleClass('is-expanded');
});
// Set initial active toggle
$("[data-toggle='treeview.'].is-expanded").parent().toggleClass('is-expanded');
//Activate bootstrip tooltips
// $("[data-toggle='tooltip']").tooltip();
})();
+99
View File
@@ -0,0 +1,99 @@
<div class="row tile">
<div class="col-lg-12">
<div class="bs-component">
<div class="alert alert-dismissible alert-success">
<button class="close" type="button" data-dismiss="alert">×</button>
<span id="info"></span>
</div>
</div>
</div>
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">添加</h3>
<div class="tile-body">
<form>
<div class="form-group">
<label class="control-label">模式</label>
<select class="form-control" name="type" id="type">
<option {{if eq "tunnelServer" .type}}selected{{end}} value="tunnelServer">tcp隧道</option>
<option {{if eq "udpServer" .type}}selected{{end}} value="udpServer">udp隧道</option>
<option {{if eq "sock5Server" .type}}selected{{end}} value="sock5Server">socks5代理</option>
<option {{if eq "httpProxyServer" .type}}selected{{end}} value="httpProxyServer">http代理
<option {{if eq "hostServer" .type}}selected{{end}} value="hostServer">host客户端</option>
</select>
</div>
<div class="form-group" id="port">
<label class="control-label">监听的端口</label>
<input class="form-control" type="text" name="port" placeholder="公网服务器对外访问端口,例如8024">
</div>
<div class="form-group" id="target">
<label class="control-label">内网目标(ip:端口)</label>
<input class="form-control" type="text" name="target" placeholder="内网代理地址,例如10.1.50.203:22">
</div>
<div class="form-group" id="compress">
<label class="control-label">数据压缩方式</label>
<select class="form-control" name="compress">
<option value="">不压缩</option>
<option value="gzip">gzip压缩</option>
<option value="snappy">snappy</option>
</select>
</div>
<div class="form-group" id="u">
<label class="control-label">socks5代理模式验证用户名</label>
<input class="form-control" type="text" name="u" placeholder="不填则无需验证">
</div>
<div class="form-group" id="p">
<label class="control-label">socks5代理模式验证密码</label>
<input class="form-control" type="text" name="p" placeholder="不填则无需验证">
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>添加
</button>
</div>
</div>
</div>
</div>
</main>
<script>
var arr = []
arr["all"] = ["type", "port", "compress", "u", "p", "target"]
arr["tunnelServer"] = ["type", "port", "target", "compress", "tcp隧道模式,提供一条tcp隧道,适用于ssh、远程桌面等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的目标端口"]
arr["udpServer"] = ["type", "port", "target", "compress", "udp隧道模式,提供一条udp隧道,适用于dns、内网dns访问等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的udp目标端口"]
arr["sock5Server"] = ["type", "port", "compress", "u", "p", "socks5代理模式,内网socks5代理,配合proxifer,可如同使用vpn一样访问内网设备或资源,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置socks5代理,即访问内网设备或者资源 "]
arr["httpProxyServer"] = ["type", "port", "compress", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
arr["hostServer"] = ["type", "compress", "域名分发模式,使用域名代理内网服务,适用于小程序开发、公众号开发、站点演示等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,使用nginx将请求反向代理到本程序,再进行域名配置,即可解析"]
function resetForm() {
for (var i = 0; i < arr["all"].length; i++) {
$("#" + arr["all"][i]).css("display", "none")
}
o = $("#type option:selected").val()
for (var i = 0; i < arr[o].length - 1; i++) {
$("#" + arr[o][i]).css("display", "block")
}
$("#info").html(arr[o][arr[o].length - 1])
}
$(function () {
resetForm()
$("#type").on("change", function () {
resetForm()
})
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/index/add",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+94
View File
@@ -0,0 +1,94 @@
<div class="row tile">
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">添加</h3>
<div class="tile-body">
<form>
<input type="hidden" name="vKey" value="{{.t.VerifyKey}}">
<div class="form-group">
<label class="control-label">模式</label>
<select class="form-control" name="type" id="type">
<option {{if eq "tunnelServer" .t.Mode}}selected{{end}} value="tunnelServer">tcp隧道</option>
<option {{if eq "udpServer" .t.Mode}}selected{{end}} value="udpServer">udp隧道</option>
<option {{if eq "sock5Server" .t.Mode}}selected{{end}} value="sock5Server">socks5代理</option>
<option {{if eq "httpProxyServer" .t.Mode}}selected{{end}} value="httpProxyServer">http代理
<option {{if eq "hostServer" .t.Mode}}selected{{end}} value="hostServer">host客户端</option>
</select>
</div>
<div class="form-group" id="port">
<label class="control-label">监听的端口</label>
<input class="form-control" value="{{.t.TcpPort}}" type="text" name="port"
placeholder="公网服务器对外访问端口,例如8024">
</div>
<div class="form-group" id="target">
<label class="control-label">内网目标(仅tcp、udp隧道模式需填写)</label>
<input class="form-control" value="{{.t.Target}}" type="text" name="target"
placeholder="内网隧道目标,例如10.1.50.203:22">
</div>
<div class="form-group" id="compress">
<label class="control-label">数据压缩方式(所有模式均支持)</label>
<select class="form-control" name="compress">
<option {{if eq "" .t.Compress}}selected{{end}} value="">不压缩</option>
<option {{if eq "gzip" .t.Compress}}selected{{end}} value="gzip">gzip压缩</option>
<option {{if eq "snappy" .t.Compress}}selected{{end}} value="snappy">snappy压缩</option>
</select>
</div>
<div class="form-group" id="u">
<label class="control-label">socks5代理模式验证用户名</label>
<input class="form-control" value="{{.t.U}}" type="text" name="u"
placeholder="不填则无需验证,非socks5模式不填">
</div>
<div class="form-group" id="p">
<label class="control-label">socks5代理模式验证密码</label>
<input class="form-control" value="{{.t.P}}" type="text" name="p"
placeholder="不填则无需验证,非socks5模式不填">
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>保存
</button>
</div>
</div>
</div>
</div>
</main>
<script>
var arr = []
arr["all"] = ["type", "port", "compress", "u", "p","target"]
arr["tunnelServer"] = ["type", "port", "target", "compress"]
arr["udpServer"] = ["type", "port", "target", "compress"]
arr["sock5Server"] = ["type", "port", "compress", "u", "p"]
arr["httpProxyServer"] = ["type", "port", "compress"]
arr["hostServer"] = ["type", "compress"]
function resetForm() {
for (var i = 0; i < arr["all"].length; i++) {
$("#" + arr["all"][i]).css("display", "none")
}
o = $("#type option:selected").val()
for (var i = 0; i < arr[o].length; i++) {
$("#" + arr[o][i]).css("display", "block")
}
}
$(function () {
resetForm()
$("#type").on("change", function () {
resetForm()
})
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/index/edit",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+43
View File
@@ -0,0 +1,43 @@
<div class="row tile">
<div class="col-md-6 col-md-auto">
<div>
<h3 class="tile-title">添加</h3>
<div class="tile-body">
<form>
<input type="hidden" name="vkey" value="{{.vkey}}">
<div class="form-group">
<label class="control-label">域名</label>
<input class="form-control" type="text" name="host" placeholder="域名">
</div>
<div class="form-group">
<label class="control-label">内网目标</label>
<input class="form-control" type="text" name="target" placeholder="内网隧道目标,例如10.1.50.203:22">
</div>
</form>
</div>
<div class="tile-footer">
&nbsp;&nbsp;<button class="btn btn-success" href="#" id="add"><i
class="fa fa-fw fa-lg fa-eye"></i>添加
</button>
</div>
</div>
</div>
</div>
</main>
<script>
$(function () {
$("#add").on("click", function () {
$.ajax({
type: "POST",
url: "/index/addhost",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
history.back(-1)
}
}
})
})
})
</script>
+81
View File
@@ -0,0 +1,81 @@
<div class="row">
<div class="col-md-12">
<div class="tile">
<div class="tile-body">
<table class="table table-hover table-bordered" id="sampleTable">
<thead>
<tr>
<th>客户端key</th>
<th>host</th>
<th>内网目标</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<script type="text/javascript">
function del(host) {
if (confirm("确定要删除数据吗?")) {
$.ajax({
type: "POST",
url: "/index/delhost",
data: {"host": host},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function add() {
window.location.href = "/index/addhost?vkey={{.vkey}}"
}
$(document).ready(function () {
var table = $('#sampleTable').DataTable({
dom: 'Bfrtip',
processing: true,
serverSide: true,
autoWidth: false,
ordering: false,
ajax: {
url: window.location,
type: 'POST'
},
dom: '<"top"fl><"toolbar">rt<"bottom"ip><"clear">',
columns: [ //这个是显示到界面上的个数据 格式为 {data:'显示的字段名'}
{data: 'Vkey'},
{data: 'Host'},
{data: 'Target'},
{data: 'Target'},
],
bFilter: false,
columnDefs: [{
targets: -1,
render: function (data, type, row, meta) {
return '<div class="btn-group" role="group" aria-label="..."> ' +
'<button onclick="del(\'' + row.Host + '\')" type="button" class="btn btn-danger btn-sm">删除</button>' +
' </div>'
}
}
],
buttons: []
});
$("#sampleTable_length").html('<button class="btn btn-primary" onclick="add()" type="button">新增</button>')
})
;
</script>
+152
View File
@@ -0,0 +1,152 @@
<div class="row">
<div class="col-md-12">
<div class="tile">
<iframe src="https://ghbtns.com/github-btn.html?user=cnlh&repo=easyProxy&type=star&count=true&size=large"
frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
<iframe src="https://ghbtns.com/github-btn.html?user=cnlh&repo=easyProxy&type=watch&count=true&size=large&v=2"
frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
<iframe src="https://ghbtns.com/github-btn.html?user=cnlh&repo=easyProxy&type=fork&count=true&size=large"
frameborder="0" scrolling="0" width="158px" height="30px"></iframe>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="tile">
<h3 class="tile-title">域名代理模式</h3>
<p>
<b>适用范围:</b> 小程序开发、微信公众号开发、产品演示
</p>
<p>
<b>假设场景:</b>
<li>有一个域名proxy.com,有一台公网机器ip为{{.ip}}</li>
<li>两个内网开发站点127.0.0.1:81,127.0.0.1:82</li>
<li>想通过a.proxy.com访问127.0.0.1:81,通过b.proxy.com访问127.0.0.1:82</li>
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>将a.proxy.com,b.proxy.com解析到公网服务器{{.ip}}</li>
<li>使用nginx监听这两个个域名,并配置ssl等……</li>
<li>在nginx配置中添加反向代理<br>
<pre><code>
server {
listen 80;
server_name a.proxy.com b.proxy.com;#也可以是泛解析*.proxy.com
#ssl等配置
<b>location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://127.0.0.1:{{.proxyPort}};
}</b>
}
</code></pre>
</li>
<li>在域名代理管理中添加一个客户端,选择压缩方式,保存。 <a href="/index/add?type=hostServer">立即添加</a></li>
{{/*<li>在域名代理管理中找到新加的客户端(查看其vkey或者客户端命令),任意内网机器执行客户端命令</li>*/}}
<li>点击该客户端的域名管理,添加两条规则规则:1、域名:a.proxy.com,内网目标:127.0.0.1:81,2、域名:b.proxy.com,内网目标:127.0.0.1:82</li>
<li>现在访问a.proxy.com,b.proxy.com即可成功</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认启动方式为单客户端模式,默认内网客户端已经启动</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">tcp隧道模式</h3>
<p>
<b>适用范围:</b> ssh、远程桌面等tcp连接场景
</p>
<p>
<b>假设场景:</b> 想通过访问公网服务器{{.ip}}的8001端口,连接内网机器10.1.50.101的22端口,实现ssh连接
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>在tcp隧道管理中添加一条隧道,填写监听的端口(8001)、内网目标ip和目标端口(10.1.50.101:22),选择压缩方式,保存。 <a
href="/index/add?type=tunnelServer">立即添加</a></li>
{{/*<li>在tcp管理列表中找到新加的隧道(查看其vkey或者客户端命令),任意内网机器执行客户端命令</li>*/}}
<li>访问公网服务器ip({{.ip}}):填写的监听端口(8001),相当于访问内网ip(10.1.50.101):目标端口(22),例如:ssh -p 8001 root@{{.ip}}</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认启动方式为单客户端模式,默认内网客户端已经启动</p>
</div>
</div>
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">udp隧道模式</h3>
<p>
<b>适用范围:</b> 内网dns解析等udp连接场景
</p>
<p>
<b>假设场景:</b> 内网有一台dns(10.1.50.102:53),在非内网环境下想使用该dns,公网服务器为{{.ip}}
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>在udp隧道管理中添加一条隧道,填写监听的端口(8002)、内网目标ip和目标端口(10.1.50.102:53),选择压缩方式,保存。 <a
href="/index/add?type=udpServer">立即添加</a></li>
{{/*<li>在udp管理列表中找到新加的隧道(查看其vkey或者客户端命令),任意内网机器执行客户端命令</li>*/}}
<li>修改本机dns为{{.ip}},则相当于使用10.1.50.202作为dns服务器</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认启动方式为单客户端模式,默认内网客户端已经启动</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">socks5代理模式</h3>
<p>
<b>适用范围:</b> 在外网环境下如同使用vpn一样访问内网设备或者资源
</p>
<p>
<b>假设场景:</b> 想将公网服务器{{.ip}}的8003端口作为socks5代理,达到访问内网任意设备或者资源的效果
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>在socks5隧道管理中添加一条隧道,填写监听的端口(8003),验证用户名和密码自行选择(建议先不填,部分客户端不支持,proxifer支持),选择压缩方式,保存。 <a
href="/index/add?type=sock5Server">立即添加</a></li>
{{/*<li>在socks5代理管理列表中找到新加的隧道(查看其vkey或者客户端命令),任意内网机器执行客户端命令</li>*/}}
<li>在外网环境的本机配置socks5代理,ip为公网服务器ip({{.ip}}),端口为填写的监听端口(8003),即可畅享内网了</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认启动方式为单客户端模式,默认内网客户端已经启动</p>
</div>
</div>
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">http代理模式</h3>
<p>
<b>适用范围:</b> 在外网环境下访问内网站点
</p>
<p>
<b>假设场景:</b> 想将公网服务器{{.ip}}的8004端口作为http代理,访问内网网站
</p>
<p><b>使用步骤:</b></p>
<ul>
<li>在http隧道管理中添加一条隧道,填写监听的端口(8004),选择压缩方式,保存。 <a
href="/index/add?type=httpProxyServer">立即添加</a></li>
<li>在http代理管理列表中找到新加的隧道(查看其vkey或者客户端命令),任意内网机器执行客户端命令</li>
<li>在外网环境的本机配置http代理,ip为公网服务器ip({{.ip}}),端口为填写的监听端口(8004),即可访问了</li>
</ul>
<p>注:上文中提到公网ip({{.ip}})为系统自动识别,如果是在测试环境中请自行对应,默认启动方式为单客户端模式,默认内网客户端已经启动</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="tile">
<p>
<b>多客户端模式:</b>
<li>服务端启动:./easyProxy -mode=webServer -tcpport=8284</li>
<li>客户端启动:./easyProxy -server={{.ip}}:{{.p}} -vkey=xxx(见管理列表的客户端启动模式)</li>
</p>
<p><b>支持客户端同时建立多条隧道,例如单个通道时命令为./easyProxy -server={{.ip}}:{{.p}} -vkey=ccc,如果要支持另外一个隧道,则对应的执行命令为./easyProxy
-server={{.ip}}:{{.p}} -vkey=ccc,ddd,即用逗号分隔开多个vkey,适用于所有模式!</b></p>
</div>
</div>
</div>
</main>
+174
View File
@@ -0,0 +1,174 @@
<div class="row">
<div class="col-md-12">
<div class="tile">
<div class="tile-body">
<table class="table table-hover table-bordered" id="sampleTable">
<thead>
<tr>
{{/*<th>模式</th>*/}}
<th>监听端口</th>
<th>内网目标</th>
<th>多客户端模式客户端执行命令</th>
<th>压缩方式</th>
<th>用户名</th>
<th>密码</th>
<th>客户端状态</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<script type="text/javascript">
function del(vKey) {
if (confirm("确定要删除数据吗?")) {
$.ajax({
type: "POST",
url: "/index/del",
data: {"vKey": vKey},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function start(vKey) {
if (confirm("确定要开始任务吗?")) {
$.ajax({
type: "POST",
url: "/index/start",
data: {"vKey": vKey},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function stop(vKey) {
if (confirm("确定要暂停吗?")) {
$.ajax({
type: "POST",
url: "/index/stop",
data: {"vKey": vKey},
success: function (res) {
alert(res.msg)
if (res.status) {
document.location.reload();
}
}
})
}
}
function edit(vKey) {
window.location.href = "/index/edit?vKey=" + vKey
}
function add() {
window.location.href = "/index/add?type=" +{{.type}}
}
function hostList(vkey) {
window.location.href = "/index/hostlist?vkey=" + vkey
}
$(document).ready(function () {
var table = $('#sampleTable').DataTable({
dom: 'Bfrtip',
processing: true,
serverSide: true,
autoWidth: false,
ordering: false,
ajax: {
url: '/index/gettasklist?type={{.type}}',
type: 'POST'
},
dom: '<"top"fl><"toolbar">rt<"bottom"ip><"clear">',
columns: [ //这个是显示到界面上的个数据 格式为 {data:'显示的字段名'}
// {data: 'Mode'},
{data: 'TcpPort'},
{data: 'Target'},
{data: 'VerifyKey'},
{data: 'Compress'},
{data: 'U'},
{data: 'P'},
{data: 'ClientStatus'},
{data: 'IsRun'},
{data: "Id"}
],
bFilter: false,
columnDefs: [{
targets: -1,
render: function (data, type, row, meta) {
if (row.IsRun == 1) {
btn = "<button onclick=\"stop('" + row.VerifyKey + "')\" class=\"btn btn-secondary btn-sm\" type=\"button\">关闭</button>"
} else {
btn = "<button onclick=\"start('" + row.VerifyKey + "')\" class=\"btn btn-success btn-sm\" type=\"button\">打开</button>"
}
btn_edit = '<button onclick="edit(\'' + row.VerifyKey + '\')" type="button" class="btn btn-primary btn-sm">查看编辑</button> '
if ({{.type}} == "hostServer"
)
{
btn_host = '<button onclick="hostList(\'' + row.VerifyKey + '\')" type="button" class="btn btn-info btn-sm">域名管理</button> '
}
else
{
btn_host = ""
}
return '<div class="btn-group" role="group" aria-label="..."> ' +
'<button onclick="del(\'' + row.VerifyKey + '\')" type="button" class="btn btn-danger btn-sm">删除</button>' +
btn_edit + btn + btn_host + ' </div>'
}
},
{
targets: -2,
render: function (data, type, row, meta) {
if (data == 0) {
return "<span class=\"badge badge-pill badge-secondary\">暂停</span>"
} else {
return "<span class=\"badge badge-pill badge-success\">正常</span>"
}
}
},
{
targets: 2,
render: function (data, type, row, meta) {
return "./easyProxy -server={{.ip}}:{{.p}} -vkey=" + data
// return data
}
},
{
targets: -3,
render: function (data, type, row, meta) {
if (data == 0) {
return "<span class=\"badge badge-pill badge-secondary\">离线</span>"
} else {
return "<span class=\"badge badge-pill badge-success\">在线</span>"
}
}
}
],
buttons: []
});
$("#sampleTable_length").html('<button class="btn btn-primary" onclick="add()" type="button">新增</button>')
})
;
</script>
+60
View File
@@ -0,0 +1,60 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/static/img/favicon.ico">
<!-- Main CSS-->
<link rel="stylesheet" type="text/css" href="/static/css/main.css">
<!-- Font-icon css-->
<link rel="stylesheet" type="text/css" href="/static/css/font-awesome.min.css">
<title>easyProxy内网穿透</title>
</head>
<body>
<section class="material-half-bg">
<div class="cover"></div>
</section>
<section class="login-content">
<div class="logo">
<h1></h1>
</div>
<div class="login-box">
<form class="login-form" onsubmit="return false">
<h3 class="login-head"><i class="fa fa-lg fa-fw fa-user"></i>内网穿透管理登陆</h3>
<div class="form-group">
<label class="control-label">密码</label>
<input class="form-control" name="psd" type="password" placeholder="" autofocus>
</div>
<div class="form-group btn-container">
<button onclick="login()" class="btn btn-primary btn-block"><i class="fa fa-sign-in fa-lg fa-fw"></i>登陆
</button>
</div>
</form>
</div>
</section>
<script type="text/javascript" src="/static/js/pdfmake.min.js"></script>
<script type="text/javascript" src="/static/js/vfs_fonts.js"></script>
<script type="text/javascript" src="/static/js/datatables.min.js"></script>
<script src="/static/js/main.js"></script>
<script type="text/javascript">
// Login Page Flipbox control
function login() {
$.ajax({
type: "POST",
url: "/login/verify",
data: $("form").serializeArray(),
success: function (res) {
if (res.status) {
window.location.href = "/index/index"
} else {
alert(res.msg)
}
}
})
return false
}
</script>
</body>
</html>
+5
View File
@@ -0,0 +1,5 @@
<div class="page-error tile">
<h1><i class="fa fa-exclamation-circle"></i> Error 404: Page not found</h1>
<p>The page you have requested is not found.</p>
<p><a class="btn btn-primary" href="javascript:window.history.back();">Go Back</a></p>
</div>
+72
View File
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="description"
content="Vali is a responsive and free admin theme built with Bootstrap 4, SASS and PUG.js. It's fully customizable and modular.">
<link rel="shortcut icon" href="/static/img/favicon.ico">
<title>easyProxy内网穿透</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Font-icon css-->
<link rel="stylesheet" type="text/css" href="/static/css/font-awesome.min.css">
<!-- Main CSS-->
<link rel="stylesheet" type="text/css" href="/static/css/main.css">
</head>
<body class="app sidebar-mini rtl">
<!-- Navbar-->
<header class="app-header">
<a class="app-header__logo" href="/"></a>
<!-- Sidebar toggle button--><a class="app-sidebar__toggle" href="#" data-toggle="sidebar"
aria-label="Hide Sidebar"></a>
<ul class="app-nav">
<!--Notification Menu-->
<!-- User Menu-->
<li class="dropdown"><a class="app-nav__item" href="/login/out" data-toggle="dropdown"
aria-label="Open Profile Menu"><i class="fa fa-sign-out fa-lg"></i>退出登陆</a>
</li>
</ul>
</header>
<!-- Sidebar menu-->
<div class="app-sidebar__overlay" data-toggle="sidebar"></div>
<aside class="app-sidebar">
<div class="app-sidebar__user"><img class="app-sidebar__user-avatar"
src="/static/img/48.jpg"
alt="User Image">
<div>
<p class="app-sidebar__user-name">System</p>
<p class="app-sidebar__user-designation">欢迎使用</p>
</div>
</div>
<ul class="app-menu">
<li><a class="app-menu__item {{if eq "index" .menu}}active{{end}}" href="/"><i
class="app-menu__icon fa fa-dashboard"></i><span class="app-menu__label">使用说明</span></a></li>
<li><a class="app-menu__item {{if eq "host" .menu}}active{{end}}" href="/index/host"><i
class="app-menu__icon fa fa-lemon-o"></i><span class="app-menu__label">域名代理</span></a></li>
<li><a class="app-menu__item {{if eq "tcp" .menu}}active{{end}}" href="/index/tcp"><i
class="app-menu__icon fa fa-life-buoy"></i><span class="app-menu__label">tcp隧道管理</span></a></li>
<li><a class="app-menu__item {{if eq "udp" .menu}}active{{end}}" href="/index/udp"><i
class="app-menu__icon fa fa-laptop"></i><span class="app-menu__label">udp隧道管理</span></a></li>
<li><a class="app-menu__item {{if eq "socks5" .menu}}active{{end}}" href="/index/socks5"><i
class="app-menu__icon fa fa-lightbulb-o"></i><span class="app-menu__label">socks5代理</span></a></li>
<li><a class="app-menu__item {{if eq "http" .menu}}active{{end}}" href="/index/http"><i
class="app-menu__icon fa fa-magic"></i><span class="app-menu__label">http代理</span></a></li>
</ul>
</aside>
<script type="text/javascript" src="/static/js/datatables.min.js"></script>
<script src="/static/js/main.js"></script>
<main class="app-content">
<div class="app-title">
<div>
<h1><i class="fa fa-th-list"></i> {{.name}}</h1>
<a href="javascript:history.back(-1);"><i class="fa fa-mail-reply"></i>返回</a>
</div>
</div>
{{.LayoutContent}}
</body>
</html>