-
Notifications
You must be signed in to change notification settings - Fork 43
/
is_tls.go
330 lines (300 loc) · 9.6 KB
/
is_tls.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package utils
import (
"bufio"
"context"
"crypto/tls"
"fmt"
"github.com/ReneKroon/ttlcache"
"github.com/davecgh/go-spew/spew"
"github.com/yaklang/yaklang/common/gmsm/gmtls"
"github.com/yaklang/yaklang/common/log"
"github.com/yaklang/yaklang/common/utils/socksproxy"
"github.com/yaklang/yaklang/common/yak/yaklib/codec"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var isTlsCached = ttlcache.NewCache()
func IsTLSService(addr string, proxies ...string) bool {
result, ok := isTlsCached.Get(addr)
if ok {
return result.(bool)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
conn, err := GetAutoProxyConn(addr, strings.Join(proxies, ","), 5*time.Second)
if err == nil {
defer conn.Close()
host, _, _ := ParseStringToHostPort(addr)
tlsConn := tls.Client(conn, &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionSSL30, ServerName: host})
if err = tlsConn.HandshakeContext(ctx); err != nil {
isTlsCached.SetWithTTL(addr, false, 30*time.Second)
return false
}
isTlsCached.SetWithTTL(addr, true, 30*time.Second)
return true
}
return false
}
var proxyDailer = net.Dialer{Timeout: 5 * time.Second}
func GetProxyConn(target string, proxy string, connectTimeout time.Duration) (net.Conn, error) {
return getProxyConn(target, proxy, connectTimeout)
}
func GetProxyConnWithContext(ctx context.Context, target string, proxy string, connectTimeout time.Duration) (net.Conn, error) {
return getProxyConnWithContext(ctx, target, proxy, connectTimeout)
}
func GetAutoProxyConn(target string, proxy string, connectTimeout time.Duration) (net.Conn, error) {
if proxy != "" {
return getProxyConn(target, proxy, connectTimeout)
}
proxy = GetProxyFromEnv()
if proxy != "" {
return getProxyConn(target, proxy, connectTimeout)
}
return net.DialTimeout("tcp", target, connectTimeout)
}
func GetAutoProxyConnEx(target string, proxies []string, connectTimeout time.Duration) (net.Conn, error) {
if len(proxies) <= 0 {
return GetAutoProxyConn(target, "", connectTimeout)
}
for _, proxy := range proxies {
conn, err := GetAutoProxyConn(target, proxy, connectTimeout)
if err != nil {
log.Infof("peek proxy [%v] to connect [%v] failed: %s", proxy, target, err)
continue
}
return conn, nil
}
return nil, fmt.Errorf("all proxies[%v] failed", spew.Sdump(proxies))
}
func GetAutoProxyConnWithTLS(target string, proxy string, connectTimeout time.Duration, c *tls.Config) (net.Conn, error) {
if c == nil {
c = NewDefaultTLSConfig()
}
if proxy != "" {
return getProxyConnTLS(target, proxy, connectTimeout, c)
}
proxy = GetProxyFromEnv()
if proxy != "" {
return getProxyConnTLS(target, proxy, connectTimeout, c)
}
d := &net.Dialer{Timeout: connectTimeout}
return tls.DialWithDialer(d, "tcp", target, c)
}
func GetAutoProxyConnWithGMTLS(target string, proxy string, connectTimeout time.Duration, c *gmtls.Config) (net.Conn, error) {
if c == nil {
c = NewDefaultGMTLSConfig()
}
if proxy != "" {
return getProxyConnGMTLS(target, proxy, connectTimeout, c)
}
proxy = GetProxyFromEnv()
if proxy != "" {
return getProxyConnGMTLS(target, proxy, connectTimeout, c)
}
d := &net.Dialer{Timeout: connectTimeout}
return gmtls.DialWithDialer(d, "tcp", target, c)
}
func FixProxy(i string) string {
if i == "" {
return ""
}
if !strings.Contains(i, "://") {
var host, port, _ = ParseStringToHostPort(i)
host = strings.Trim(host, `"' \r\n:`)
if host != "" && port > 0 {
return fmt.Sprintf("http://%v:%v", host, port)
}
}
return i
}
func GetProxyFromEnv() string {
for _, k := range []string{
"YAK_PROXY", "yak_proxy",
"HTTP_PROXY", "http_proxy",
"HTTPS_PROXY", "https_proxy",
"all_proxy", "all_proxy",
"proxy", "proxy",
} {
if p := strings.Trim(os.Getenv(k), `"`); p != "" {
return FixProxy(p)
}
}
return ""
}
func DisableProxyFromCurrentEnv() {
for _, k := range []string{
"HTTP_PROXY", "http_proxy",
"HTTPS_PROXY", "https_proxy",
"all_proxy", "all_proxy",
"proxy", "proxy",
} {
os.Setenv(k, "")
}
}
func TCPConnect(target string, timeout time.Duration, proxies ...string) (net.Conn, error) {
dialer := &net.Dialer{Timeout: timeout}
if len(proxies) <= 0 {
return dialer.Dial("tcp", target)
}
for _, proxy := range proxies {
conn, err := getProxyConn(target, proxy, timeout)
if err != nil {
log.Errorf("proxy conn failed: %s", err)
continue
}
return conn, nil
}
return nil, Errorf("connect: %v failed: no proxy available", target)
}
func getProxyConnTLS(target string, proxy string, connectTimeout time.Duration, tlsConfig *tls.Config) (net.Conn, error) {
conn, err := getProxyConn(target, proxy, connectTimeout)
if err != nil {
return nil, err
}
var tlsConn = tls.Client(conn, tlsConfig)
timeoutCtx, cancel := context.WithTimeout(context.Background(), connectTimeout)
defer cancel()
err = tlsConn.HandshakeContext(timeoutCtx)
if err != nil {
return nil, err
}
return tlsConn, nil
}
func getProxyConnGMTLS(target string, proxy string, connectTimeout time.Duration, tlsConfig *gmtls.Config) (net.Conn, error) {
conn, err := getProxyConn(target, proxy, connectTimeout)
if err != nil {
return nil, err
}
var tlsConn = gmtls.Client(conn, tlsConfig)
timeoutCtx, cancel := context.WithTimeout(context.Background(), connectTimeout)
defer cancel()
err = tlsConn.HandshakeContext(timeoutCtx)
if err != nil {
return nil, err
}
return tlsConn, nil
}
func getProxyConn(target string, proxy string, connectTimeout time.Duration) (net.Conn, error) {
return getProxyConnWithContext(context.Background(), target, proxy, connectTimeout)
}
func getProxyConnWithContext(ctx context.Context, target string, proxy string, connectTimeout time.Duration) (net.Conn, error) {
if ctx == nil {
ctx = context.Background()
}
tcpDailer := &net.Dialer{Timeout: connectTimeout}
proxy = strings.ToLower(proxy)
host, port, _ := ParseStringToHostPort(proxy)
if host == "" || port <= 0 {
return nil, Errorf("proxy need host:port... at least[%v]", proxy)
}
proxyAddr := HostPort(host, port)
switch true {
case strings.HasPrefix(proxy, "https://"):
urlIns, err := url.Parse(proxy)
if err != nil {
return nil, Errorf("parse proxy url failed: %s", err)
}
conn, err := tcpDailer.DialContext(ctx, "tcp", proxyAddr)
if err != nil {
return nil, err
}
conn = tls.Client(conn, NewDefaultTLSConfig())
if urlIns.User != nil && urlIns.User.String() != "" {
// 有密码
_, _ = conn.Write(generateHTTPProxyConnectWithCredential(target, urlIns.User.String()))
} else {
// 无密码
_, _ = conn.Write(generateHTTPProxyConnect(target))
}
if readHTTP200(conn) {
return conn, nil
}
return nil, Errorf("connect proxy(https) [%s] failed", proxy)
case strings.HasPrefix(proxy, "socks://"):
fallthrough
case strings.HasPrefix(proxy, "socks5://"):
fallthrough
case strings.HasPrefix(proxy, "s5://"):
username, password := parseProxyCredential(proxy)
conn, err := socksproxy.DialSocksProxy(socksproxy.SOCKS5, proxyAddr, username, password)("tcp", target)
if err != nil {
return nil, err
}
return conn, nil
case strings.HasPrefix(proxy, "s4://") || strings.HasPrefix(proxy, "socks4://"):
username, password := parseProxyCredential(proxy)
conn, err := socksproxy.DialSocksProxy(socksproxy.SOCKS4, proxyAddr, username, password)("tcp", target)
if err != nil {
return nil, err
}
return conn, nil
case strings.HasPrefix(proxy, "s4a://") || strings.HasPrefix(proxy, "socks4a://"):
username, password := parseProxyCredential(proxy)
conn, err := socksproxy.DialSocksProxy(socksproxy.SOCKS4A, proxyAddr, username, password)("tcp", target)
if err != nil {
return nil, err
}
return conn, nil
case strings.HasPrefix(proxy, "http://"):
fallthrough
default:
urlIns, err := url.Parse(proxy)
if err != nil {
return nil, Errorf("parse proxy url failed: %s", err)
}
conn, err := tcpDailer.DialContext(ctx, "tcp", proxyAddr)
if err != nil {
return nil, err
}
if urlIns.User != nil && urlIns.User.String() != "" {
_, err = conn.Write(generateHTTPProxyConnectWithCredential(target, urlIns.User.String()))
} else {
_, err = conn.Write(generateHTTPProxyConnect(target))
}
if readHTTP200(conn) {
return conn, nil
}
if err != nil {
return nil, Errorf("connect proxy(http) [%s] failed: %s", proxy, err)
}
return nil, Errorf("connect proxy(http) [%s] failed", proxy)
}
}
func parseProxyCredential(proxyURL string) (string, string) {
urlIns, err := url.Parse(proxyURL)
if err != nil {
return "", ""
}
username := urlIns.User.Username()
password, _ := urlIns.User.Password()
return username, password
}
func readHTTP200(c net.Conn) bool {
//rspBytes := StableReaderEx(c, 5*time.Second, 4096)
//rsp, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(rspBytes)), nil)
rsp, err := http.ReadResponse(bufio.NewReader(c), nil)
if err != nil {
log.Debugf("read response(readHTTP200) failed: %s", err)
return false
}
return rsp.StatusCode >= 200 && rsp.StatusCode < 400
}
func generateHTTPProxyConnect(target string) []byte {
return []byte(fmt.Sprintf(
"CONNECT %v HTTP/1.1\r\nHost: %v\r\nUser-Agent: %v\r\nConnection: keep-alive\r\nProxy-Connection: keep-alive\r\n\r\n",
target, target, userAgent,
))
}
func generateHTTPProxyConnectWithCredential(target string, cred string) []byte {
return []byte(fmt.Sprintf(
"CONNECT %v HTTP/1.1\r\nHost: %v\r\nUser-Agent: %v\r\n"+
fmt.Sprintf("Proxy-Authorization: Basic %v\r\n", codec.EncodeBase64(cred))+
"Connection: keep-alive\r\nProxy-Connection: keep-alive\r\n\r\n",
target, target, userAgent,
))
}
var userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"