forked from projectdiscovery/proxify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
295 lines (262 loc) · 6.9 KB
/
socket.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
284
285
286
287
288
289
290
291
292
293
294
295
package proxify
import (
"bytes"
"crypto/tls"
"io"
"log"
"net"
"net/http"
"net/url"
"time"
"github.com/projectdiscovery/dsl"
"github.com/projectdiscovery/proxify/pkg/types"
)
// SocketProxy - connect two sockets with TLS inspection
type SocketProxy struct {
Listener net.Listener
options *SocketProxyOptions
}
// SocketConn represent the single full duplex pipe
type SocketConn struct {
// laddr, raddr net.Addr //nolint
lconn, rconn net.Conn
erred bool
errsig chan bool
httpclient *http.Client
HTTPServer string
sentBytes uint64
receivedBytes uint64
Verbosity types.Verbosity
OutputHex bool
Timeout time.Duration
RequestMatchReplaceDSL []string
ResponseMatchReplaceDSL []string
OnRequest func([]byte) []byte
OnResponse func([]byte) []byte
}
type SocketProxyOptions struct {
Protocol string
ListenAddress string
RemoteAddress string
HTTPProxy string
HTTPServer string
listenAddress net.TCPAddr
remoteAddress net.TCPAddr
TLSClientConfig *tls.Config
TLSClient bool
TLSServerConfig *tls.Config
TLSServer bool
Verbosity types.Verbosity
OutputHex bool
Timeout time.Duration
RequestMatchReplaceDSL []string
ResponseMatchReplaceDSL []string
OnRequest func([]byte) []byte
OnResponse func([]byte) []byte
}
func (so *SocketProxyOptions) Clone() SocketProxyOptions {
return SocketProxyOptions{
Protocol: so.Protocol,
ListenAddress: so.ListenAddress,
RemoteAddress: so.RemoteAddress,
HTTPProxy: so.HTTPProxy,
HTTPServer: so.HTTPServer,
listenAddress: so.listenAddress,
remoteAddress: so.remoteAddress,
TLSClientConfig: so.TLSClientConfig,
TLSClient: so.TLSClient,
TLSServerConfig: so.TLSServerConfig,
TLSServer: so.TLSServer,
OnRequest: so.OnRequest,
OnResponse: so.OnResponse,
RequestMatchReplaceDSL: so.RequestMatchReplaceDSL,
ResponseMatchReplaceDSL: so.ResponseMatchReplaceDSL,
}
}
func NewSocketProxy(options *SocketProxyOptions) *SocketProxy {
return &SocketProxy{options: options}
}
func (p *SocketProxy) Run() error {
var (
listener net.Listener
err error
)
if p.options.TLSServer {
config := &tls.Config{InsecureSkipVerify: true}
if p.options.TLSServerConfig != nil {
config = p.options.TLSServerConfig
}
listener, err = tls.Listen(p.options.Protocol, p.options.ListenAddress, config)
} else {
listener, err = net.Listen(p.options.Protocol, p.options.ListenAddress)
}
if err != nil {
return err
}
for {
conn, err := listener.Accept()
if err != nil {
log.Println(err)
return err
}
go p.Proxy(conn) //nolint
}
}
func (p *SocketProxy) Proxy(conn net.Conn) error {
var (
socketConn SocketConn
err error
)
socketConn.Timeout = p.options.Timeout
socketConn.Verbosity = p.options.Verbosity
socketConn.OutputHex = p.options.OutputHex
socketConn.lconn = conn
defer socketConn.lconn.Close()
if p.options.TLSClient {
config := &tls.Config{
InsecureSkipVerify: true,
}
if p.options.TLSClientConfig != nil {
config = p.options.TLSClientConfig
}
socketConn.rconn, err = tls.Dial("tcp", p.options.RemoteAddress, config)
} else {
socketConn.rconn, err = net.Dial("tcp", p.options.RemoteAddress)
}
if err != nil {
log.Println(err)
return nil
}
defer socketConn.rconn.Close()
if p.options.HTTPProxy != "" {
proxyURL, err := url.Parse(p.options.HTTPProxy)
if err != nil {
return nil
}
socketConn.httpclient = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
socketConn.HTTPServer = p.options.HTTPServer
}
socketConn.OnRequest = p.options.OnRequest
socketConn.OnResponse = p.options.OnResponse
socketConn.RequestMatchReplaceDSL = p.options.RequestMatchReplaceDSL
socketConn.ResponseMatchReplaceDSL = p.options.ResponseMatchReplaceDSL
socketConn.errsig = make(chan bool)
socketConn.fullduplex()
return nil
}
func (p *SocketConn) err(s string, err error) {
log.Println(err)
if p.erred {
return
}
if err != io.EOF {
log.Printf(s, err)
}
p.errsig <- true
p.erred = true
}
func (p *SocketConn) fullduplex() {
//bidirectional copy
log.Printf("Opened %s >>> %s", p.lconn.LocalAddr(), p.rconn.RemoteAddr())
go p.pipe(p.lconn, p.rconn)
go p.pipe(p.rconn, p.lconn)
if p.Timeout > 0 {
p.lconn.SetDeadline(time.Now().Add(p.Timeout)) //nolint
p.rconn.SetDeadline(time.Now().Add(p.Timeout)) //nolint
}
//wait for close...
<-p.errsig
log.Printf("Closed (%d bytes sent, %d bytes received)", p.sentBytes, p.receivedBytes)
}
func (p *SocketConn) pipe(src, dst io.ReadWriter) {
islocal := src == p.lconn
var dataDirection string
if islocal {
dataDirection = ">>> %d bytes sent%s"
} else {
dataDirection = "<<< %d bytes received%s"
}
byteFormat := "%s"
if p.OutputHex {
byteFormat = "%x"
}
//directional copy (64k buffer)
buff := make([]byte, 0xffff)
for {
n, err := src.Read(buff)
if err != nil {
p.err("Read failed: %s\n", err)
return
}
b := buff[:n]
// Client => Proxy => Destination
if islocal {
// DSL
for _, expr := range p.RequestMatchReplaceDSL {
args := make(map[string]interface{})
args["data"] = b
newB, err := dsl.EvalExpr(expr, args)
// In case of error use the original value
if err != nil {
log.Printf("%s\n", err)
} else {
// otherwise replace it
b = newB.([]byte)
}
}
// Custom callback
if p.OnRequest != nil {
b = p.OnRequest(b)
}
} else { // Destination => Proxy => Client
// DSL
for _, expr := range p.ResponseMatchReplaceDSL {
args := make(map[string]interface{})
args["data"] = b
newB, err := dsl.EvalExpr(expr, args)
// In case of error use the original value
if err != nil {
log.Printf("%s\n", err)
} else {
// otherwise replace it
b = newB.([]byte)
}
}
// Custom callback
if p.OnResponse != nil {
b = p.OnResponse(b)
}
}
// show output
log.Printf(dataDirection, n, "")
log.Printf(byteFormat, b)
// something custom
if bytes.HasPrefix(b, []byte{0x16, 0x03}) {
print("[!] SSL/TLS handshake detected, provide a server cert and key to enable interception.")
}
if p.httpclient != nil {
resp, err := p.httpclient.Post(p.HTTPServer, "", bytes.NewReader(b))
if err != nil {
log.Println(err)
} else {
b, _ = io.ReadAll(resp.Body)
resp.Body.Close()
}
}
// write out result
n, err = dst.Write(b)
if err != nil {
p.err("Write failed: %s\n", err)
return
}
if islocal {
p.sentBytes += uint64(n)
} else {
p.receivedBytes += uint64(n)
}
}
}