-
Notifications
You must be signed in to change notification settings - Fork 43
/
rclient.go
458 lines (406 loc) · 12 KB
/
rclient.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package main
import (
"crypto/tls"
"fmt"
"log"
"net"
"errors"
"context"
"net/url"
"bufio"
"bytes"
"encoding/base64"
socks5 "github.com/armon/go-socks5"
"github.com/hashicorp/yamux"
"io/ioutil"
"net/http"
"strings"
"time"
ntlmssp "github.com/kost/go-ntlmssp"
"nhooyr.io/websocket"
)
var encBase64 = base64.StdEncoding.EncodeToString
var decBase64 = base64.StdEncoding.DecodeString
var username string
var domain string
var password string
var connectproxystring string
var useragent string
var proxytimeout = time.Millisecond * 1000 //timeout for proxyserver response
func GetSystemProxy(method string, urlstr string) (*url.URL, error) {
req, err := http.NewRequest(method, urlstr, nil)
if err != nil {
return nil, err
}
// Get the proxy URL from the environment
proxyURL, err := http.ProxyFromEnvironment(req)
if err != nil {
return nil, err
}
return proxyURL, nil
}
func WSconnectForSocks(verify bool, address string, proxy string) error {
// Define the proxy URL and WebSocket endpoint URL
proxyURL := proxy // Change this to your proxy URL
wsURL := address // Change this to your WebSocket endpoint
server, err := socks5.New(&socks5.Config{})
if err != nil {
log.Printf("Error setting up socks server: %v", err)
return err
}
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: !verify},
},
}
if proxyURL != "" {
ntlmssp.NewNegotiateMessage(domain, "")
// Create an HTTP client that authenticates via NTLMSSP
negmsg, err := ntlmssp.NewNegotiateMessage(domain, "")
if err != nil {
log.Printf("Error getting domain negotiate message: %v", err)
return err
}
tsproxy := http.ProxyURL(mustParseURL(proxyURL))
if proxyURL == "." {
tsproxy = http.ProxyFromEnvironment
}
httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: !verify},
Proxy: tsproxy,
ProxyConnectHeader: http.Header{
"Proxy-Authorization": []string{string(negmsg)},
},
},
}
// resp, err := http.Get(wsURL)
// resp, err := httpClient.Get(wsURL)
req, err := http.NewRequest("GET", wsURL, nil)
if err != nil {
log.Printf("error creating http request to %s: %s\n", wsURL, err)
return err
}
req.Header.Set("User-Agent", useragent)
resp, err := httpClient.Do(req)
if err != nil {
log.Printf("error making http request to %s: %s\n", wsURL, err)
return err
}
if resp.StatusCode == 200 {
log.Printf("No proxy auth required. Will make standard request")
} else if resp.StatusCode == 407 {
ntlmchall := resp.Header.Get("Proxy-Authenticate")
log.Printf("Got following challenge: %s", ntlmchall)
if strings.Contains(ntlmchall, "NTLM") {
ntlmchall = ntlmchall[5:]
challengeMessage, errb := base64.StdEncoding.DecodeString(ntlmchall)
if errb != nil {
log.Printf("Error getting base64 decode of challengde: %v", errb)
return errb
}
authenticateMessage, erra := ntlmssp.ProcessChallenge(challengeMessage, username, password)
if erra != nil {
log.Printf("Error getting auth message for challenge: %v", erra)
}
authMessage := fmt.Sprintf("NTLM %s", base64.StdEncoding.EncodeToString(authenticateMessage))
httpClient = &http.Client{
Transport: &http.Transport{
Proxy: tsproxy,
ProxyConnectHeader: http.Header{
"Proxy-Authorization": []string{string(authMessage)},
},
},
}
} else if strings.Contains(ntlmchall, "Basic") {
authCombo := fmt.Sprintf("%s:%s", username, password)
authMessage := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(authCombo)))
httpClient = &http.Client{
Transport: &http.Transport{
Proxy: tsproxy,
ProxyConnectHeader: http.Header{
"Proxy-Authorization": []string{authMessage},
},
},
}
} else {
log.Printf("Unknown proxy challenge: %s", ntlmchall)
return errors.New("Unknown proxy challenge")
}
} else {
log.Printf("Unknown http response code: %d", resp.StatusCode)
}
}
// Connect to the WebSocket endpoint via the proxy
wconn, _, err := websocket.Dial(context.Background(), wsURL, &websocket.DialOptions{
HTTPClient: httpClient,
HTTPHeader: http.Header{"User-Agent": []string{useragent}, "Accept-Language": []string{agentpassword}, "Sec-WebSocket-Protocol": []string{"chat"}},
Subprotocols: []string{"chat"},
})
if err != nil {
fmt.Println("Error connecting to the WebSocket:", err)
return err
}
defer wconn.Close(websocket.StatusInternalError, "Connection closed")
nc_over_ws := websocket.NetConn(context.Background(), wconn, websocket.MessageBinary)
session, erry := yamux.Server(nc_over_ws, nil)
if erry != nil {
fmt.Println("Error creating yamux server:", err)
return erry
}
for {
stream, err := session.Accept()
if err != nil {
fmt.Println("Error accepting stream:", err)
continue
}
log.Println("Accepted stream")
go func() {
err = server.ServeConn(stream)
if err != nil {
log.Printf("Error serving: %v", err)
}
}()
}
return nil
}
func mustParseURL(u string) *url.URL {
parsedURL, err := url.Parse(u)
if err != nil {
panic(err)
}
return parsedURL
}
func connectviaproxy(tlsenable bool, proxyaddress string, connectaddr string) net.Conn {
var proxyurl *url.URL
socksdebug := CurOptions.debug
connectproxystring = ""
proxyurl = nil
proxyaddr := proxyaddress
if proxyaddress == "." {
prefixstr := "https://" // always https since CONNECT is needed
sysproxy, err := GetSystemProxy("POST", prefixstr+connectaddr)
if err != nil {
log.Printf("Error getting system proxy for %s: %v", prefixstr+connectaddr, err)
return nil
}
proxyurl = sysproxy
proxyaddr = sysproxy.Host
}
if (username != "") && (password != "") && (domain != "") {
negotiateMessage, errn := ntlmssp.NewNegotiateMessage(domain, "")
if errn != nil {
log.Println("NEG error")
log.Println(errn)
// return nil
}
log.Print(negotiateMessage)
negheader := fmt.Sprintf("NTLM %s", base64.StdEncoding.EncodeToString(negotiateMessage))
connectproxystring = "CONNECT " + connectaddr + " HTTP/1.1" + "\r\nHost: " + connectaddr +
"\r\nUser-Agent: " + useragent +
"\r\nProxy-Authorization: " + negheader +
"\r\nProxy-Connection: Keep-Alive" +
"\r\n\r\n"
} else {
connectproxystring = "CONNECT " + connectaddr + " HTTP/1.1" + "\r\nHost: " + connectaddr +
"\r\nUser-Agent: " + useragent +
"\r\nProxy-Connection: Keep-Alive" +
"\r\n\r\n"
}
if socksdebug {
log.Print(connectproxystring)
}
conn, err := net.Dial("tcp", proxyaddr)
if err != nil {
// handle error
log.Printf("Error connect to %s: %v", proxyaddr, err)
}
conn.Write([]byte(connectproxystring))
time.Sleep(proxytimeout) //Because socket does not close - we need to sleep for full response from proxy
resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"})
status := resp.Status
if socksdebug {
log.Print(status)
log.Print(resp)
}
if (resp.StatusCode == 200) || (strings.Contains(status, "HTTP/1.1 200 ")) ||
(strings.Contains(status, "HTTP/1.0 200 ")) {
log.Print("Connected via proxy. No auth required")
return conn
}
if socksdebug {
log.Print("Checking proxy auth")
}
if resp.StatusCode == 407 {
log.Print("Got Proxy status code (407)")
ntlmchall := resp.Header.Get("Proxy-Authenticate")
log.Print(ntlmchall)
if strings.Contains(ntlmchall, "NTLM") {
if socksdebug {
log.Print("Got NTLM challenge:")
log.Print(ntlmchall)
}
/*
negstring:= fmt.Sprintf("NTLM %s", base64.StdEncoding.EncodeToString(negotiateMessage))
connectproxystring = "CONNECT " + connectaddr + " HTTP/1.1" + "\r\nHost: " + connectaddr +
"\r\nUser-Agent: "+useragent+
"\r\nProxy-Authorization: " + negstring +
"\r\nProxy-Connection: Keep-Alive" +
"\r\n\r\n"
*/
ntlmchall = ntlmchall[5:]
if socksdebug {
log.Print("NTLM challenge:")
log.Print(ntlmchall)
}
challengeMessage, errb := decBase64(ntlmchall)
if errb != nil {
log.Println("BASE64 Decode error")
log.Println(errb)
return nil
}
user := ""
pass := ""
if proxyaddress == "." {
user = proxyurl.User.Username()
p, pset := proxyurl.User.Password()
if pset {
pass = p
}
}
if (username != "") && (password != "") {
user = username
pass = password
}
authenticateMessage, erra := ntlmssp.ProcessChallenge(challengeMessage, user, pass)
if erra != nil {
log.Println("Process challenge error")
log.Println(erra)
return nil
}
authMessage := fmt.Sprintf("NTLM %s", base64.StdEncoding.EncodeToString(authenticateMessage))
//log.Print(authenticate)
connectproxystring = "CONNECT " + connectaddr + " HTTP/1.1" + "\r\nHost: " + connectaddr +
"\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko" +
"\r\nProxy-Authorization: " + authMessage +
"\r\nProxy-Connection: Keep-Alive" +
"\r\n\r\n"
} else if strings.Contains(ntlmchall, "Basic") {
if socksdebug {
log.Print("Got Basic challenge:")
}
var authbuffer bytes.Buffer
if (username != "") && (password != "") {
authbuffer.WriteString(username)
authbuffer.WriteString(":")
authbuffer.WriteString(password)
} else if proxyaddress == "." {
authbuffer.WriteString(proxyurl.User.String())
}
basicauth := encBase64(authbuffer.Bytes())
//log.Print(authenticate)
connectproxystring = "CONNECT " + connectaddr + " HTTP/1.1" + "\r\nHost: " + connectaddr +
"\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko" +
"\r\nProxy-Authorization: Basic " + basicauth +
"\r\nProxy-Connection: Keep-Alive" +
"\r\n\r\n"
} else {
log.Print("Unknown authentication")
return nil
}
log.Print("Connecting to proxy")
log.Print(connectproxystring)
conn.Write([]byte(connectproxystring))
//read response
bufReader := bufio.NewReader(conn)
conn.SetReadDeadline(time.Now().Add(proxytimeout))
statusb, _ := ioutil.ReadAll(bufReader)
status = string(statusb)
//disable socket read timeouts
conn.SetReadDeadline(time.Now().Add(100 * time.Hour))
if resp.StatusCode == 200 || strings.Contains(status, "HTTP/1.1 200 ") ||
strings.Contains(status, "HTTP/1.0 200 ") {
log.Print("Connected via proxy")
return conn
}
log.Printf("Not Connected via proxy. Status:%v", status)
return nil
}
log.Print("Not connected via proxy")
conn.Close()
return nil
}
func connectForSocks(tlsenable bool, verify bool, address string, proxy string) error {
var session *yamux.Session
server, err := socks5.New(&socks5.Config{})
if err != nil {
return err
}
conf := &tls.Config{
InsecureSkipVerify: !verify,
}
var conn net.Conn
var connp net.Conn
var newconn net.Conn
//var conntls tls.Conn
//var conn tls.Conn
if proxy == "" {
log.Println("Connecting to far end")
if tlsenable {
conn, err = tls.Dial("tcp", address, conf)
} else {
conn, err = net.Dial("tcp", address)
}
if err != nil {
return err
}
} else {
log.Println("Connecting to proxy ...")
connp = connectviaproxy(tlsenable, proxy, address)
if connp != nil {
log.Println("Proxy successfull. Connecting to far end")
if tlsenable {
conntls := tls.Client(connp, conf)
err := conntls.Handshake()
if err != nil {
log.Printf("Error connect: %v", err)
return err
}
newconn = net.Conn(conntls)
} else {
newconn = connp
}
} else {
log.Println("Proxy NOT successfull. Exiting")
return nil
}
}
log.Println("Starting client")
if proxy == "" {
conn.Write([]byte(agentpassword))
//time.Sleep(time.Second * 1)
session, err = yamux.Server(conn, nil)
} else {
//log.Print(conntls)
newconn.Write([]byte(agentpassword))
time.Sleep(time.Second * 1)
session, err = yamux.Server(newconn, nil)
}
if err != nil {
return err
}
for {
stream, err := session.Accept()
log.Println("Accepting stream")
if err != nil {
return err
}
log.Println("Passing off to socks5")
go func() {
err = server.ServeConn(stream)
if err != nil {
log.Println(err)
}
}()
}
}