2019-08-31 17:01:39 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"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
|
|
|
}
|
|
|
|
|
|
|
|
hd, sharedSecret := makeHiddenData(sta)
|
|
|
|
header := http.Header{}
|
2019-09-01 00:33:34 +00:00
|
|
|
header.Add("hidden", base64.StdEncoding.EncodeToString(hd.fullRaw))
|
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
|
|
|
|
}
|