Cloak/internal/client/websocket.go

66 lines
1.7 KiB
Go
Raw Normal View History

2019-08-31 17:01:39 +00:00
package client
import (
"crypto/rand"
2019-08-31 17:01:39 +00:00
"encoding/base64"
"errors"
2019-09-01 00:33:34 +00:00
"fmt"
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"
2019-08-31 17:01:39 +00:00
"net"
"net/http"
"net/url"
2019-09-02 13:03:10 +00:00
utls "github.com/refraction-networking/utls"
2019-08-31 17:01:39 +00:00
)
2019-09-02 13:03:10 +00:00
type WSOverTLS struct {
2019-08-31 17:01:39 +00:00
Transport
}
2019-09-02 13:03:10 +00:00
func (WSOverTLS) HasRecordLayer() bool { return false }
func (WSOverTLS) UnitReadFunc() func(net.Conn, []byte) (int, error) { return util.ReadWebSocket }
func (WSOverTLS) PrepareConnection(sta *State, conn net.Conn) (preparedConn net.Conn, sessionKey []byte, err error) {
utlsConfig := &utls.Config{
ServerName: sta.ServerName,
InsecureSkipVerify: true,
}
uconn := utls.UClient(conn, utlsConfig, utls.HelloChrome_Auto)
err = uconn.Handshake()
preparedConn = uconn
if err != nil {
return
}
2019-09-01 19:23:45 +00:00
2019-08-31 17:01:39 +00:00
u, err := url.Parse("ws://" + sta.RemoteHost + ":" + sta.RemotePort) //TODO IPv6
if err != nil {
2019-09-01 19:23:45 +00:00
return preparedConn, nil, fmt.Errorf("failed to parse ws url: %v", err)
2019-08-31 17:01:39 +00:00
}
payload, sharedSecret := makeAuthenticationPayload(sta, rand.Reader)
2019-08-31 17:01:39 +00:00
header := http.Header{}
header.Add("hidden", base64.StdEncoding.EncodeToString(append(payload.randPubKey[:], payload.ciphertextWithTag[:]...)))
2019-09-01 19:23:45 +00:00
c, _, err := websocket.NewClient(preparedConn, u, header, 16480, 16480)
2019-08-31 17:01:39 +00:00
if err != nil {
2019-09-01 19:23:45 +00:00
return preparedConn, nil, fmt.Errorf("failed to handshake: %v", err)
2019-08-31 17:01:39 +00:00
}
2019-09-01 19:23:45 +00:00
preparedConn = &util.WebSocketConn{Conn: c}
2019-09-01 00:33:34 +00:00
buf := make([]byte, 128)
2019-09-01 19:23:45 +00:00
n, err := preparedConn.Read(buf)
2019-08-31 17:01:39 +00:00
if err != nil {
2019-09-01 19:23:45 +00:00
return preparedConn, nil, 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 {
2019-09-01 19:23:45 +00:00
return preparedConn, nil, 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]
2019-08-31 17:01:39 +00:00
sessionKey, err = util.AESGCMDecrypt(reply[:12], sharedSecret, reply[12:])
return
}