Cloak/internal/client/websocket.go

66 lines
1.6 KiB
Go
Raw Normal View History

2019-08-31 17:01:39 +00:00
package client
import (
"encoding/base64"
"errors"
2019-09-01 00:33:34 +00:00
"fmt"
2020-04-08 23:39:40 +00:00
"github.com/cbeuw/Cloak/internal/common"
2019-08-31 17:01:39 +00:00
"github.com/cbeuw/Cloak/internal/util"
2019-09-01 00:33:34 +00:00
"github.com/gorilla/websocket"
2020-04-09 21:11:12 +00:00
utls "github.com/refraction-networking/utls"
2019-08-31 17:01:39 +00:00
"net"
"net/http"
"net/url"
)
2019-09-02 13:03:10 +00:00
type WSOverTLS struct {
2020-04-08 23:39:40 +00:00
*common.WebSocketConn
2020-04-06 12:07:16 +00:00
cdnDomainPort string
2019-08-31 17:01:39 +00:00
}
func (ws *WSOverTLS) Handshake(rawConn net.Conn, authInfo authInfo) (sessionKey [32]byte, err error) {
2019-09-02 13:03:10 +00:00
utlsConfig := &utls.Config{
2020-04-06 12:07:16 +00:00
ServerName: authInfo.MockDomain,
2019-09-02 13:03:10 +00:00
InsecureSkipVerify: true,
}
uconn := utls.UClient(rawConn, utlsConfig, utls.HelloChrome_Auto)
2019-09-02 13:03:10 +00:00
err = uconn.Handshake()
if err != nil {
return
}
2019-09-01 19:23:45 +00:00
2020-04-06 12:07:16 +00:00
u, err := url.Parse("ws://" + ws.cdnDomainPort)
2019-08-31 17:01:39 +00:00
if err != nil {
return sessionKey, fmt.Errorf("failed to parse ws url: %v", err)
2019-08-31 17:01:39 +00:00
}
2020-04-09 21:11:12 +00:00
payload, sharedSecret := makeAuthenticationPayload(authInfo)
2019-08-31 17:01:39 +00:00
header := http.Header{}
header.Add("hidden", base64.StdEncoding.EncodeToString(append(payload.randPubKey[:], payload.ciphertextWithTag[:]...)))
c, _, err := websocket.NewClient(uconn, u, header, 16480, 16480)
2019-08-31 17:01:39 +00:00
if err != nil {
return sessionKey, fmt.Errorf("failed to handshake: %v", err)
2019-08-31 17:01:39 +00:00
}
2020-04-08 23:39:40 +00:00
ws.WebSocketConn = &common.WebSocketConn{Conn: c}
2019-09-01 00:33:34 +00:00
buf := make([]byte, 128)
n, err := ws.Read(buf)
2019-08-31 17:01:39 +00:00
if err != nil {
return sessionKey, fmt.Errorf("failed to read reply: %v", err)
2019-08-31 17:01:39 +00:00
}
2019-09-01 00:33:34 +00:00
if n != 60 {
return sessionKey, errors.New("reply must be 60 bytes")
2019-08-31 17:01:39 +00:00
}
2019-09-01 00:33:34 +00:00
reply := buf[:60]
2020-04-07 20:15:28 +00:00
sessionKeySlice, err := util.AESGCMDecrypt(reply[:12], sharedSecret[:], reply[12:])
if err != nil {
return
}
copy(sessionKey[:], sessionKeySlice)
2019-08-31 17:01:39 +00:00
return
}