You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/proxy/shadowsocks/protocol.go

404 lines
12 KiB

package shadowsocks
import (
"bytes"
"crypto/rand"
"io"
8 years ago
"v2ray.com/core/common"
"v2ray.com/core/common/bitmask"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
)
const (
Version = 1
RequestOptionOneTimeAuth bitmask.Byte = 0x01
AddrTypeIPv4 = 1
AddrTypeIPv6 = 4
AddrTypeDomain = 3
)
func ReadTCPSession(user *protocol.User, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) {
rawAccount, err := user.GetTypedAccount()
if err != nil {
return nil, nil, newError("failed to parse account").Base(err).AtError()
}
account := rawAccount.(*ShadowsocksAccount)
8 years ago
buffer := buf.NewLocal(512)
defer buffer.Release()
ivLen := account.Cipher.IVSize()
8 years ago
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, ivLen)); err != nil {
return nil, nil, newError("failed to read IV").Base(err)
}
8 years ago
iv := append([]byte(nil), buffer.BytesTo(ivLen)...)
r, err := account.Cipher.NewDecryptionReader(account.Key, iv, reader)
if err != nil {
return nil, nil, newError("failed to initialize decoding stream").Base(err).AtError()
}
br := buf.NewBufferedReader(r)
reader = nil
authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
request := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandTCP,
}
if err := buffer.Reset(buf.ReadFullFrom(br, 1)); err != nil {
return nil, nil, newError("failed to read address type").Base(err)
}
if !account.Cipher.IsAEAD() {
if (buffer.Byte(0) & 0x10) == 0x10 {
request.Option.Set(RequestOptionOneTimeAuth)
}
if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
return nil, nil, newError("rejecting connection with OTA enabled, while server disables OTA")
}
if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
return nil, nil, newError("rejecting connection with OTA disabled, while server enables OTA")
}
}
addrType := (buffer.Byte(0) & 0x0F)
switch addrType {
case AddrTypeIPv4:
if err := buffer.AppendSupplier(buf.ReadFullFrom(br, 4)); err != nil {
return nil, nil, newError("failed to read IPv4 address").Base(err)
}
request.Address = net.IPAddress(buffer.BytesFrom(-4))
case AddrTypeIPv6:
if err := buffer.AppendSupplier(buf.ReadFullFrom(br, 16)); err != nil {
return nil, nil, newError("failed to read IPv6 address").Base(err)
}
request.Address = net.IPAddress(buffer.BytesFrom(-16))
case AddrTypeDomain:
if err := buffer.AppendSupplier(buf.ReadFullFrom(br, 1)); err != nil {
return nil, nil, newError("failed to read domain lenth.").Base(err)
}
8 years ago
domainLength := int(buffer.BytesFrom(-1)[0])
err = buffer.AppendSupplier(buf.ReadFullFrom(br, domainLength))
if err != nil {
return nil, nil, newError("failed to read domain").Base(err)
}
request.Address = net.DomainAddress(string(buffer.BytesFrom(-domainLength)))
default:
// Check address validity after OTA verification.
}
err = buffer.AppendSupplier(buf.ReadFullFrom(br, 2))
if err != nil {
return nil, nil, newError("failed to read port").Base(err)
}
request.Port = net.PortFromBytes(buffer.BytesFrom(-2))
if request.Option.Has(RequestOptionOneTimeAuth) {
actualAuth := make([]byte, AuthSize)
authenticator.Authenticate(buffer.Bytes())(actualAuth)
8 years ago
err := buffer.AppendSupplier(buf.ReadFullFrom(br, AuthSize))
if err != nil {
return nil, nil, newError("Failed to read OTA").Base(err)
}
8 years ago
if !bytes.Equal(actualAuth, buffer.BytesFrom(-AuthSize)) {
return nil, nil, newError("invalid OTA")
}
}
if request.Address == nil {
return nil, nil, newError("invalid remote address.")
}
br.SetBuffered(false)
var chunkReader buf.Reader
if request.Option.Has(RequestOptionOneTimeAuth) {
chunkReader = NewChunkReader(br, NewAuthenticator(ChunkKeyGenerator(iv)))
} else {
chunkReader = buf.NewReader(br)
}
return request, chunkReader, nil
}
func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
user := request.User
rawAccount, err := user.GetTypedAccount()
if err != nil {
return nil, newError("failed to parse account").Base(err).AtError()
}
account := rawAccount.(*ShadowsocksAccount)
if account.Cipher.IsAEAD() {
request.Option.Clear(RequestOptionOneTimeAuth)
}
iv := make([]byte, account.Cipher.IVSize())
common.Must2(rand.Read(iv))
_, err = writer.Write(iv)
if err != nil {
return nil, newError("failed to write IV")
}
w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
if err != nil {
return nil, newError("failed to create encoding stream").Base(err).AtError()
}
8 years ago
header := buf.NewLocal(512)
switch request.Address.Family() {
case net.AddressFamilyIPv4:
header.AppendBytes(AddrTypeIPv4)
header.Append([]byte(request.Address.IP()))
case net.AddressFamilyIPv6:
header.AppendBytes(AddrTypeIPv6)
header.Append([]byte(request.Address.IP()))
case net.AddressFamilyDomain:
domain := request.Address.Domain()
if protocol.IsDomainTooLong(domain) {
return nil, newError("domain name too long: ", domain)
}
header.AppendBytes(AddrTypeDomain, byte(len(domain)))
common.Must(header.AppendSupplier(serial.WriteString(domain)))
default:
return nil, newError("unsupported address type: ", request.Address.Family())
}
common.Must(header.AppendSupplier(serial.WriteUint16(uint16(request.Port))))
if request.Option.Has(RequestOptionOneTimeAuth) {
8 years ago
header.SetByte(0, header.Byte(0)|0x10)
authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
common.Must(header.AppendSupplier(authenticator.Authenticate(header.Bytes())))
}
if err := w.WriteMultiBuffer(buf.NewMultiBufferValue(header)); err != nil {
return nil, newError("failed to write header").Base(err)
}
var chunkWriter buf.Writer
if request.Option.Has(RequestOptionOneTimeAuth) {
chunkWriter = NewChunkWriter(w.(io.Writer), NewAuthenticator(ChunkKeyGenerator(iv)))
} else {
chunkWriter = w
}
return chunkWriter, nil
}
func ReadTCPResponse(user *protocol.User, reader io.Reader) (buf.Reader, error) {
rawAccount, err := user.GetTypedAccount()
if err != nil {
return nil, newError("failed to parse account").Base(err).AtError()
}
account := rawAccount.(*ShadowsocksAccount)
iv := make([]byte, account.Cipher.IVSize())
_, err = io.ReadFull(reader, iv)
if err != nil {
return nil, newError("failed to read IV").Base(err)
}
return account.Cipher.NewDecryptionReader(account.Key, iv, reader)
}
func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
user := request.User
rawAccount, err := user.GetTypedAccount()
if err != nil {
return nil, newError("failed to parse account.").Base(err).AtError()
}
account := rawAccount.(*ShadowsocksAccount)
iv := make([]byte, account.Cipher.IVSize())
common.Must2(rand.Read(iv))
_, err = writer.Write(iv)
if err != nil {
return nil, newError("failed to write IV.").Base(err)
}
return account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
}
8 years ago
func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) {
user := request.User
rawAccount, err := user.GetTypedAccount()
if err != nil {
return nil, newError("failed to parse account.").Base(err).AtError()
}
account := rawAccount.(*ShadowsocksAccount)
buffer := buf.New()
ivLen := account.Cipher.IVSize()
7 years ago
common.Must(buffer.Reset(buf.ReadFullFrom(rand.Reader, ivLen)))
iv := buffer.Bytes()
7 years ago
payloadBuffer := buf.New()
defer payloadBuffer.Release()
switch request.Address.Family() {
case net.AddressFamilyIPv4:
payloadBuffer.AppendBytes(AddrTypeIPv4)
payloadBuffer.Append([]byte(request.Address.IP()))
case net.AddressFamilyIPv6:
payloadBuffer.AppendBytes(AddrTypeIPv6)
payloadBuffer.Append([]byte(request.Address.IP()))
case net.AddressFamilyDomain:
payloadBuffer.AppendBytes(AddrTypeDomain, byte(len(request.Address.Domain())))
payloadBuffer.Append([]byte(request.Address.Domain()))
default:
return nil, newError("unsupported address type: ", request.Address.Family()).AtError()
}
7 years ago
common.Must(payloadBuffer.AppendSupplier(serial.WriteUint16(uint16(request.Port))))
payloadBuffer.Append(payload)
7 years ago
if !account.Cipher.IsAEAD() && request.Option.Has(RequestOptionOneTimeAuth) {
authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
payloadBuffer.SetByte(0, payloadBuffer.Byte(0)|0x10)
7 years ago
common.Must(payloadBuffer.AppendSupplier(authenticator.Authenticate(payloadBuffer.Bytes())))
}
w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, buffer)
if err != nil {
return nil, newError("failed to create encoding stream").Base(err).AtError()
}
if err := w.WriteMultiBuffer(buf.NewMultiBufferValue(payloadBuffer)); err != nil {
return nil, newError("failed to encrypt UDP payload").Base(err).AtWarning()
}
return buffer, nil
}
func DecodeUDPPacket(user *protocol.User, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) {
rawAccount, err := user.GetTypedAccount()
if err != nil {
return nil, nil, newError("failed to parse account").Base(err).AtError()
}
account := rawAccount.(*ShadowsocksAccount)
ivLen := account.Cipher.IVSize()
7 years ago
iv := make([]byte, ivLen)
copy(iv, payload.BytesTo(ivLen))
payload.SliceFrom(ivLen)
r, err := account.Cipher.NewDecryptionReader(account.Key, iv, payload)
if err != nil {
return nil, nil, newError("failed to initialize decoding stream").Base(err).AtError()
}
mb, err := r.ReadMultiBuffer()
if err != nil {
return nil, nil, newError("failed to decrypt UDP payload").Base(err).AtWarning()
}
payload.Release()
payload = mb.SplitFirst()
mb.Release()
authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
request := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandUDP,
}
7 years ago
if !account.Cipher.IsAEAD() {
if (payload.Byte(0) & 0x10) == 0x10 {
request.Option |= RequestOptionOneTimeAuth
}
7 years ago
if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
return nil, nil, newError("rejecting packet with OTA enabled, while server disables OTA").AtWarning()
}
7 years ago
if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
return nil, nil, newError("rejecting packet with OTA disabled, while server enables OTA").AtWarning()
}
7 years ago
if request.Option.Has(RequestOptionOneTimeAuth) {
payloadLen := payload.Len() - AuthSize
authBytes := payload.BytesFrom(payloadLen)
7 years ago
actualAuth := make([]byte, AuthSize)
authenticator.Authenticate(payload.BytesTo(payloadLen))(actualAuth)
if !bytes.Equal(actualAuth, authBytes) {
return nil, nil, newError("invalid OTA")
}
7 years ago
payload.Slice(0, payloadLen)
}
}
7 years ago
addrType := (payload.Byte(0) & 0x0F)
payload.SliceFrom(1)
switch addrType {
case AddrTypeIPv4:
request.Address = net.IPAddress(payload.BytesTo(4))
payload.SliceFrom(4)
case AddrTypeIPv6:
request.Address = net.IPAddress(payload.BytesTo(16))
payload.SliceFrom(16)
case AddrTypeDomain:
domainLength := int(payload.Byte(0))
request.Address = net.DomainAddress(string(payload.BytesRange(1, 1+domainLength)))
payload.SliceFrom(1 + domainLength)
default:
return nil, nil, newError("unknown address type: ", addrType).AtError()
}
request.Port = net.PortFromBytes(payload.BytesTo(2))
payload.SliceFrom(2)
return request, payload, nil
}
type UDPReader struct {
Reader io.Reader
User *protocol.User
}
func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
buffer := buf.New()
8 years ago
err := buffer.AppendSupplier(buf.ReadFrom(v.Reader))
if err != nil {
buffer.Release()
return nil, err
}
8 years ago
_, payload, err := DecodeUDPPacket(v.User, buffer)
if err != nil {
buffer.Release()
return nil, err
}
8 years ago
return buf.NewMultiBufferValue(payload), nil
}
type UDPWriter struct {
Writer io.Writer
Request *protocol.RequestHeader
}
8 years ago
// Write implements io.Writer.
8 years ago
func (w *UDPWriter) Write(payload []byte) (int, error) {
packet, err := EncodeUDPPacket(w.Request, payload)
if err != nil {
8 years ago
return 0, err
}
8 years ago
_, err = w.Writer.Write(packet.Bytes())
packet.Release()
return len(payload), err
}