Cloak/internal/util/obfs.go

69 lines
2.0 KiB
Go
Raw Normal View History

2018-10-07 17:09:45 +00:00
package util
import (
"encoding/binary"
2018-10-20 20:41:01 +00:00
xxhash "github.com/OneOfOne/xxhash"
2018-10-07 17:09:45 +00:00
mux "github.com/cbeuw/Cloak/internal/multiplex"
)
2018-10-23 19:47:58 +00:00
// For each frame, the three parts of the header is xored with three keys.
// The keys are generated from the SID and the payload of the frame.
2018-11-07 21:16:13 +00:00
// FIXME: this code will panic if len(data)<18.
func genXorKeys(secret []byte, data []byte) (i uint32, ii uint32, iii uint32) {
2018-10-20 20:41:01 +00:00
h := xxhash.New32()
ret := make([]uint32, 3)
preHash := make([]byte, 16)
for j := 0; j < 3; j++ {
2018-11-07 21:16:13 +00:00
copy(preHash[0:10], secret[j*10:j*10+10])
2018-10-20 20:41:01 +00:00
copy(preHash[10:16], data[j*6:j*6+6])
h.Write(preHash)
ret[j] = h.Sum32()
}
return ret[0], ret[1], ret[2]
2018-10-07 17:09:45 +00:00
}
func MakeObfs(key []byte) func(*mux.Frame) []byte {
obfs := func(f *mux.Frame) []byte {
2018-10-20 20:41:01 +00:00
obfsedHeader := make([]byte, 12)
2018-10-27 22:35:46 +00:00
// header: [StreamID 4 bytes][Seq 4 bytes][Closing 4 bytes]
2018-10-20 20:41:01 +00:00
i, ii, iii := genXorKeys(key, f.Payload[0:18])
binary.BigEndian.PutUint32(obfsedHeader[0:4], f.StreamID^i)
binary.BigEndian.PutUint32(obfsedHeader[4:8], f.Seq^ii)
2018-10-27 22:35:46 +00:00
binary.BigEndian.PutUint32(obfsedHeader[8:12], f.Closing^iii)
2018-10-20 16:03:39 +00:00
// Composing final obfsed message
// We don't use util.AddRecordLayer here to avoid unnecessary malloc
2018-10-20 20:41:01 +00:00
obfsed := make([]byte, 5+12+len(f.Payload))
2018-10-20 16:03:39 +00:00
obfsed[0] = 0x17
obfsed[1] = 0x03
obfsed[2] = 0x03
2018-10-20 20:41:01 +00:00
binary.BigEndian.PutUint16(obfsed[3:5], uint16(12+len(f.Payload)))
copy(obfsed[5:17], obfsedHeader)
copy(obfsed[17:], f.Payload)
// obfsed: [record layer 5 bytes][cipherheader 12 bytes][payload]
2018-10-20 16:03:39 +00:00
return obfsed
2018-10-07 17:09:45 +00:00
}
return obfs
}
func MakeDeobfs(key []byte) func([]byte) *mux.Frame {
deobfs := func(in []byte) *mux.Frame {
2018-10-20 16:03:39 +00:00
peeled := in[5:]
2018-10-20 20:41:01 +00:00
i, ii, iii := genXorKeys(key, peeled[12:30])
streamID := binary.BigEndian.Uint32(peeled[0:4]) ^ i
seq := binary.BigEndian.Uint32(peeled[4:8]) ^ ii
2018-10-27 22:35:46 +00:00
closing := binary.BigEndian.Uint32(peeled[8:12]) ^ iii
2018-10-20 20:41:01 +00:00
payload := make([]byte, len(peeled)-12)
copy(payload, peeled[12:])
2018-10-07 17:09:45 +00:00
ret := &mux.Frame{
2018-10-27 22:35:46 +00:00
StreamID: streamID,
Seq: seq,
Closing: closing,
Payload: payload,
2018-10-07 17:09:45 +00:00
}
return ret
}
return deobfs
}