forked from digibib/tcpforward
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpforward.go
283 lines (257 loc) · 7.8 KB
/
tcpforward.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package main
import (
"flag"
"io"
"log"
"math/rand"
"net"
"net/http"
"os"
"strings"
"sync"
"tcpforward/Utils"
"time"
)
var (
localAddr string
remoteAddr string
prefix string
rejectReply string
rejectReplyFile string
debug bool
minConnectionCount int
connectionTimeout int64
trustTimeout float64
webpageRequestRequired bool
webpageSSL bool
webpagePort string
webpagePath string
webpageSSLPub string
webpageSSLKey string
)
func initFlags() {
flag.StringVar(&localAddr, "l", ":2081", "host:port to listen on")
flag.StringVar(&remoteAddr, "r", ":2080", "host:port to forward to")
flag.StringVar(&prefix, "p", "", "String to prefix log output")
flag.StringVar(&rejectReply, "jr", "none", "Send something before rejecting\n bin: random bytes\n text: random hex text\n file: send a file\n none: just close")
flag.StringVar(&rejectReplyFile, "jrf", "", "Path to file for reject reply")
flag.BoolVar(&debug, "debug", false, "more logs")
flag.IntVar(&minConnectionCount, "m", 10, "min accepted request")
flag.Int64Var(&connectionTimeout, "t", 500, "How long a client can take to create enough connections in ms")
flag.Float64Var(&trustTimeout, "tt", 60, "IP trust reset timer in minute")
flag.BoolVar(&webpageRequestRequired, "pr", false, "Request webpage is required")
flag.BoolVar(&webpageSSL, "ps", true, "SSL For webpage is enabled")
flag.StringVar(&webpagePort, "pp", ":2082", "host:port for webpage verify")
flag.StringVar(&webpagePath, "ppa", "/verify-mvacrw9khofxsd", "path for webpage verify")
flag.StringVar(&webpageSSLPub, "psp", "SelfSigned", "path to webpage SSL public cert")
flag.StringVar(&webpageSSLKey, "psk", "SelfSigned", "path to webpage SSL private key")
flag.Parse()
}
type IPConnection struct {
sync.Mutex
count int // 记录已接受的连接数
failedCount int
lastConnection time.Time // 记录最后一次连接时间
webpageRequested bool
failedWebpage bool
}
func webpageVerify(ip string, ipMap map[string]*IPConnection) {
// 如果未记录该IP,创建记录
if _, exist := ipMap[ip]; !exist {
ipMap[ip] = &IPConnection{
count: 1,
failedCount: 0,
lastConnection: time.Now(),
webpageRequested: true,
failedWebpage: false,
}
log.Printf("(Webpage) New IP address %v, waiting for more connections\n", ip)
} else if !ipMap[ip].webpageRequested {
// 如果已记录该IP,确定已访问网页
ipMap[ip].Lock()
ipMap[ip].webpageRequested = true
log.Printf("(Webpage) New IP address %v added\n", ip)
ipMap[ip].Unlock()
}
return
}
func forward(conn net.Conn, ipMap map[string]*IPConnection) {
// 获取连接方的IP地址
ip, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
// 如果未记录该IP,创建记录
if _, exist := ipMap[ip]; !exist {
ipMap[ip] = &IPConnection{
count: 1,
failedCount: 0,
lastConnection: time.Now(),
webpageRequested: false,
failedWebpage: false,
}
return
} else {
// 如果已记录该IP,判断是否达到最大连接数
ipMap[ip].Lock()
if ipMap[ip].count < minConnectionCount {
// 重置连接计数和最后一次连接时间
if time.Since(ipMap[ip].lastConnection).Milliseconds() >= connectionTimeout {
ipMap[ip].count = 0
ipMap[ip].lastConnection = time.Now()
}
ipMap[ip].count++
if ipMap[ip].failedCount < minConnectionCount*3 && ipMap[ip].count%3 == 0 || debug || minConnectionCount <= 3 || ipMap[ip].count < 2 {
log.Printf("Rejected connection from %v, %v Connections in %dms\n", ip, ipMap[ip].count, time.Since(ipMap[ip].lastConnection).Milliseconds())
ipMap[ip].failedCount++
}
ipMap[ip].Unlock()
switch strings.ToLower(rejectReply) {
case "bin":
conn.Write(Utils.RandomByte(rand.Intn(300) + 100))
case "text":
conn.Write([]byte(Utils.RandomString(rand.Intn(640) + 100)))
case "file":
{
//打开本地文件
file, err := os.Open("example.txt")
if err != nil {
log.Printf("ERROR: open file failed: %v", err)
conn.Close()
return
}
//复制到网络
_, err = io.Copy(conn, file)
if err != nil {
log.Printf("ERROR: reply file failed: %v", err)
conn.Close()
return
}
file.Close()
}
case "none":
{
} //skip
default:
log.Printf("Warning: Unexpected Rejected Reply: %s", rejectReply)
}
conn.Close()
return
} else {
if webpageRequestRequired {
if !ipMap[ip].webpageRequested {
if !ipMap[ip].failedWebpage || debug {
log.Printf("Rejected connection from %v, FAILED WEBPAGE VERIFY\n", ip)
ipMap[ip].count = 0
ipMap[ip].failedWebpage = true
}
conn.Close()
ipMap[ip].Unlock()
return
}
}
if ipMap[ip].count == minConnectionCount {
log.Printf("Accept connections from %v\n", ip)
ipMap[ip].count++
}
if time.Since(ipMap[ip].lastConnection).Minutes() >= trustTimeout {
ipMap[ip].count = -2
ipMap[ip].Unlock()
log.Printf("Reject %v (trust expired)\n", ip)
} else {
ipMap[ip].Unlock()
}
}
}
client, err := net.Dial("tcp", remoteAddr)
if err != nil {
log.Printf("ERROR: Dial failed: %v", err)
defer conn.Close()
return
}
if debug {
log.Printf("Forwarding from %v to %v\n", conn.LocalAddr(), client.RemoteAddr())
}
go func() {
defer client.Close()
defer conn.Close()
io.Copy(client, conn)
}()
go func() {
defer client.Close()
defer conn.Close()
io.Copy(conn, client)
}()
}
func main() {
initFlags()
Utils.InitRandSeed()
log.Printf("Client > %s > %s > Server\n", localAddr, remoteAddr)
log.SetPrefix(prefix)
log.Println(strings.Replace(`
TCPForward init, Tip:
### Block port from Internet ###
iptables -A INPUT -p tcp --dport <PORT_NUMBER> -s 127.0.0.1 -j ACCEPT
iptables -A INPUT -p tcp --dport <PORT_NUMBER> -j DROP
ip6tables -A INPUT -p tcp --dport <PORT_NUMBER> -s ::1 -j ACCEPT
ip6tables -A INPUT -p tcp --dport <PORT_NUMBER> -j DROP
or quickTables -port <PORT_NUMBER> block
### Delete rule ###
iptables -D INPUT -p tcp --dport <PORT_NUMBER> -j DROP
ip6tables -D INPUT -p tcp --dport <PORT_NUMBER> -j DROP
or quickTables -port <PORT_NUMBER> unblock
(execute with root privileges)
`, "<PORT_NUMBER>", localAddr, -1))
ipMap := make(map[string]*IPConnection)
if webpageRequestRequired {
if !webpageSSL {
go func() {
http.HandleFunc(webpagePath, func(w http.ResponseWriter, r *http.Request) {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
io.WriteString(w, ip)
webpageVerify(ip, ipMap)
})
err := http.ListenAndServe(webpagePort, nil)
if err != nil {
log.Printf("ERROR: failed to accept webpage verify: %v", err)
}
}()
} else {
go func() {
//Utils.RandomString(rand.Intn(28) + 10)+".cf",/
cert, err := Utils.GenerateSelfSignedCert()
if webpageSSLPub != "SelfSigned" || webpageSSLKey != "SelfSigned" {
cert, err = Utils.LoadCertFromFile(webpageSSLPub, webpageSSLKey)
}
if err != nil {
log.Fatalf("ERROR: failed to create cert: %v", err)
}
err = Utils.StartHTTPSPage(webpagePort, cert, func(ip string) {
webpageVerify(ip, ipMap)
}, webpagePath, true)
if err != nil {
log.Fatalf("ERROR: failed to accept webpage verify: %v", err)
}
}()
}
log.Printf("request webpage at %s%s to verify\n", webpagePort, webpagePath)
}
listener, err := net.Listen("tcp", localAddr)
if err != nil {
log.Fatalf("ERROR: Failed to setup listener: %v", err)
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("ERROR: failed to accept listener: %v", err)
continue
}
go forward(conn, ipMap)
}
}()
log.Println(" TCPForwarder ready")
select {}
}
func clearMap(m map[string]*IPConnection) {
for key := range m {
delete(m, key)
}
}