Cloak/internal/client/websocket.go
2020-04-09 22:11:12 +01:00

66 lines
1.6 KiB
Go

package client
import (
"encoding/base64"
"errors"
"fmt"
"github.com/cbeuw/Cloak/internal/common"
"github.com/cbeuw/Cloak/internal/util"
"github.com/gorilla/websocket"
utls "github.com/refraction-networking/utls"
"net"
"net/http"
"net/url"
)
type WSOverTLS struct {
*common.WebSocketConn
cdnDomainPort string
}
func (ws *WSOverTLS) Handshake(rawConn net.Conn, authInfo authInfo) (sessionKey [32]byte, err error) {
utlsConfig := &utls.Config{
ServerName: authInfo.MockDomain,
InsecureSkipVerify: true,
}
uconn := utls.UClient(rawConn, utlsConfig, utls.HelloChrome_Auto)
err = uconn.Handshake()
if err != nil {
return
}
u, err := url.Parse("ws://" + ws.cdnDomainPort)
if err != nil {
return sessionKey, fmt.Errorf("failed to parse ws url: %v", err)
}
payload, sharedSecret := makeAuthenticationPayload(authInfo)
header := http.Header{}
header.Add("hidden", base64.StdEncoding.EncodeToString(append(payload.randPubKey[:], payload.ciphertextWithTag[:]...)))
c, _, err := websocket.NewClient(uconn, u, header, 16480, 16480)
if err != nil {
return sessionKey, fmt.Errorf("failed to handshake: %v", err)
}
ws.WebSocketConn = &common.WebSocketConn{Conn: c}
buf := make([]byte, 128)
n, err := ws.Read(buf)
if err != nil {
return sessionKey, fmt.Errorf("failed to read reply: %v", err)
}
if n != 60 {
return sessionKey, errors.New("reply must be 60 bytes")
}
reply := buf[:60]
sessionKeySlice, err := util.AESGCMDecrypt(reply[:12], sharedSecret[:], reply[12:])
if err != nil {
return
}
copy(sessionKey[:], sessionKeySlice)
return
}