-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect_test.go
189 lines (158 loc) · 4.54 KB
/
connect_test.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
package multiproxy
import (
"bufio"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func generateCertificate() ([]byte, []byte, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Test Co"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 180),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, nil, err
}
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
return certPEM, keyPEM, nil
}
func setupHTTPSServer(t *testing.T) (*httptest.Server, []byte) {
certPEM, keyPEM, err := generateCertificate()
require.NoError(t, err)
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
require.NoError(t, err)
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from HTTPS server")
}))
server.TLS = &tls.Config{Certificates: []tls.Certificate{tlsCert}}
server.StartTLS()
return server, certPEM
}
func setupConnectProxy(t *testing.T, username, password string) (string, func()) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
go func() {
for {
client, err := listener.Accept()
if err != nil {
return
}
go handleConnectProxy(t, client, username, password)
}
}()
return listener.Addr().String(), func() {
listener.Close()
}
}
func handleConnectProxy(t *testing.T, client net.Conn, username, password string) {
defer client.Close()
bufReader := bufio.NewReader(client)
req, err := http.ReadRequest(bufReader)
if err != nil {
t.Logf("Error reading request: %v", err)
return
}
t.Logf("Received request: %s %s", req.Method, req.URL)
if username != "" && password != "" {
auth := req.Header.Get("Proxy-Authorization")
expected := basicAuth(username, password)
if auth != expected {
t.Logf("Authentication failed")
client.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\n\r\n"))
return
}
}
if req.Method != "CONNECT" {
t.Logf("Expected CONNECT method, got: %s", req.Method)
client.Write([]byte("HTTP/1.1 405 Method Not Allowed\r\n\r\n"))
return
}
t.Logf("Attempting to connect to target: %s", req.URL.Host)
targetConn, err := net.Dial("tcp", req.URL.Host)
if err != nil {
t.Logf("Error connecting to target: %v", err)
client.Write([]byte("HTTP/1.1 502 Bad Gateway\r\n\r\n"))
return
}
defer targetConn.Close()
client.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
go io.Copy(targetConn, client)
io.Copy(client, targetConn)
}
func TestConnectProxyWithHTTPS(t *testing.T) {
httpsServer, _ := setupHTTPSServer(t)
if httpsServer == nil {
t.Fatal("Failed to set up HTTPS server")
}
defer httpsServer.Close()
proxyAddr, cleanup := setupConnectProxy(t, "user", "pass")
if proxyAddr == "" {
t.Fatal("Failed to set up CONNECT proxy")
}
defer cleanup()
proxyURL, err := url.Parse("http://" + proxyAddr)
if err != nil {
t.Fatalf("Failed to parse proxy URL: %v", err)
}
config := Config{
Proxies: []Proxy{
{
URL: proxyURL,
Auth: &ProxyAuth{Username: "user", Password: "pass"},
},
},
DialTimeout: 5 * time.Second,
InsecureSkipVerify: true,
RetryAttempts: 2,
RetryDelay: time.Second,
}
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
if client == nil {
t.Fatal("Client is nil")
}
t.Logf("HTTPS Server URL: %s", httpsServer.URL)
t.Logf("Proxy Address: %s", proxyAddr)
for i := 0; i < 3; i++ {
resp, err := client.Get(httpsServer.URL)
require.NoError(t, err, "Request %d failed", i)
require.Equal(t, http.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response %d: %s", i, string(body))
resp.Body.Close()
}
if len(client.states) == 0 {
t.Fatal("Client states is empty")
}
assert.Equal(t, 3, client.states[0].requestCount)
}