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"
|
|
|
|
)
|
|
|
|
|
|
|
|
type WebSocket struct {
|
|
|
|
Transport
|
|
|
|
}
|
|
|
|
|
2019-09-01 19:23:45 +00:00
|
|
|
func (*WebSocket) HasRecordLayer() bool { return false }
|
|
|
|
func (*WebSocket) UnitReadFunc() func(net.Conn, []byte) (int, error) { return util.ReadWebSocket }
|
|
|
|
|
|
|
|
func (WebSocket) PrepareConnection(sta *State, conn net.Conn) (preparedConn net.Conn, sessionKey []byte, err error) {
|
|
|
|
preparedConn = conn
|
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
|
|
|
|
}
|