v2fly/proxy/shadowsocks/protocol.go

404 lines
12 KiB
Go
Raw Normal View History

2016-01-28 11:33:58 +00:00
package shadowsocks
import (
2016-05-24 20:09:22 +00:00
"bytes"
2016-10-31 14:24:28 +00:00
"crypto/rand"
2016-01-28 11:33:58 +00:00
"io"
2016-12-09 11:08:25 +00:00
"v2ray.com/core/common"
2017-10-21 19:04:24 +00:00
"v2ray.com/core/common/bitmask"
2016-12-09 10:35:27 +00:00
"v2ray.com/core/common/buf"
"v2ray.com/core/common/net"
2016-10-31 14:24:28 +00:00
"v2ray.com/core/common/protocol"
2016-12-06 10:03:42 +00:00
"v2ray.com/core/common/serial"
2016-01-28 11:33:58 +00:00
)
const (
2017-10-21 19:04:24 +00:00
Version = 1
RequestOptionOneTimeAuth bitmask.Byte = 0x01
2016-10-31 14:24:28 +00:00
2016-01-28 11:33:58 +00:00
AddrTypeIPv4 = 1
AddrTypeIPv6 = 4
AddrTypeDomain = 3
)
2016-12-09 12:17:34 +00:00
func ReadTCPSession(user *protocol.User, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) {
2016-10-31 14:24:28 +00:00
rawAccount, err := user.GetTypedAccount()
if err != nil {
2017-04-23 18:41:45 +00:00
return nil, nil, newError("failed to parse account").Base(err).AtError()
2016-05-01 15:18:02 +00:00
}
2017-11-29 21:57:18 +00:00
account := rawAccount.(*MemoryAccount)
2016-05-01 15:18:02 +00:00
2016-12-09 11:08:25 +00:00
buffer := buf.NewLocal(512)
2016-01-28 11:33:58 +00:00
defer buffer.Release()
2016-10-31 14:24:28 +00:00
ivLen := account.Cipher.IVSize()
2017-11-29 21:19:04 +00:00
var iv []byte
if ivLen > 0 {
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, ivLen)); err != nil {
return nil, nil, newError("failed to read IV").Base(err)
}
2016-01-28 11:33:58 +00:00
2017-11-29 21:19:04 +00:00
iv = append([]byte(nil), buffer.BytesTo(ivLen)...)
}
2016-10-31 14:24:28 +00:00
2017-11-25 23:51:54 +00:00
r, err := account.Cipher.NewDecryptionReader(account.Key, iv, reader)
2016-10-31 14:24:28 +00:00
if err != nil {
2017-04-26 22:09:01 +00:00
return nil, nil, newError("failed to initialize decoding stream").Base(err).AtError()
2016-10-31 14:24:28 +00:00
}
2017-11-26 15:56:01 +00:00
br := buf.NewBufferedReader(r)
reader = nil
2016-10-31 14:24:28 +00:00
authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
request := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandTCP,
}
2017-11-26 15:56:01 +00:00
if err := buffer.Reset(buf.ReadFullFrom(br, 1)); err != nil {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("failed to read address type").Base(err)
2016-10-31 14:24:28 +00:00
}
2016-01-28 11:33:58 +00:00
2017-11-26 00:02:10 +00:00
if !account.Cipher.IsAEAD() {
if (buffer.Byte(0) & 0x10) == 0x10 {
request.Option.Set(RequestOptionOneTimeAuth)
}
2016-10-31 14:24:28 +00:00
2017-11-26 00:02:10 +00:00
if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
return nil, nil, newError("rejecting connection with OTA enabled, while server disables OTA")
}
2017-11-26 00:02:10 +00:00
if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
return nil, nil, newError("rejecting connection with OTA disabled, while server enables OTA")
}
}
2017-11-26 00:02:10 +00:00
addrType := (buffer.Byte(0) & 0x0F)
2016-01-28 11:33:58 +00:00
switch addrType {
case AddrTypeIPv4:
2017-11-26 15:56:01 +00:00
if err := buffer.AppendSupplier(buf.ReadFullFrom(br, 4)); err != nil {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("failed to read IPv4 address").Base(err)
2016-01-28 11:33:58 +00:00
}
request.Address = net.IPAddress(buffer.BytesFrom(-4))
2016-01-28 11:33:58 +00:00
case AddrTypeIPv6:
2017-11-26 15:56:01 +00:00
if err := buffer.AppendSupplier(buf.ReadFullFrom(br, 16)); err != nil {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("failed to read IPv6 address").Base(err)
2016-01-28 11:33:58 +00:00
}
request.Address = net.IPAddress(buffer.BytesFrom(-16))
2016-01-28 11:33:58 +00:00
case AddrTypeDomain:
2017-11-26 15:56:01 +00:00
if err := buffer.AppendSupplier(buf.ReadFullFrom(br, 1)); err != nil {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("failed to read domain lenth.").Base(err)
2016-01-28 11:33:58 +00:00
}
2016-12-05 16:05:47 +00:00
domainLength := int(buffer.BytesFrom(-1)[0])
2017-11-26 15:56:01 +00:00
err = buffer.AppendSupplier(buf.ReadFullFrom(br, domainLength))
2016-01-28 11:33:58 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("failed to read domain").Base(err)
2016-01-28 11:33:58 +00:00
}
request.Address = net.DomainAddress(string(buffer.BytesFrom(-domainLength)))
2016-01-28 11:33:58 +00:00
default:
2016-12-13 08:17:39 +00:00
// Check address validity after OTA verification.
2016-01-28 11:33:58 +00:00
}
2017-11-26 15:56:01 +00:00
err = buffer.AppendSupplier(buf.ReadFullFrom(br, 2))
2016-01-28 11:33:58 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("failed to read port").Base(err)
2016-01-28 11:33:58 +00:00
}
request.Port = net.PortFromBytes(buffer.BytesFrom(-2))
2016-10-31 14:24:28 +00:00
if request.Option.Has(RequestOptionOneTimeAuth) {
2016-12-06 10:03:42 +00:00
actualAuth := make([]byte, AuthSize)
authenticator.Authenticate(buffer.Bytes())(actualAuth)
2016-12-05 16:05:47 +00:00
2017-11-26 15:56:01 +00:00
err := buffer.AppendSupplier(buf.ReadFullFrom(br, AuthSize))
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("Failed to read OTA").Base(err)
2016-01-29 20:55:42 +00:00
}
2016-10-31 14:24:28 +00:00
2016-12-05 16:05:47 +00:00
if !bytes.Equal(actualAuth, buffer.BytesFrom(-AuthSize)) {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("invalid OTA")
}
2016-10-31 14:24:28 +00:00
}
2016-12-13 08:17:39 +00:00
if request.Address == nil {
2017-04-08 23:43:25 +00:00
return nil, nil, newError("invalid remote address.")
2016-12-13 08:17:39 +00:00
}
2017-11-26 15:56:01 +00:00
br.SetBuffered(false)
2016-12-09 12:17:34 +00:00
var chunkReader buf.Reader
2016-10-31 14:24:28 +00:00
if request.Option.Has(RequestOptionOneTimeAuth) {
2017-11-26 15:56:01 +00:00
chunkReader = NewChunkReader(br, NewAuthenticator(ChunkKeyGenerator(iv)))
2016-01-29 20:55:42 +00:00
} else {
2017-11-26 15:56:01 +00:00
chunkReader = buf.NewReader(br)
2016-10-31 14:24:28 +00:00
}
return request, chunkReader, nil
}
2016-12-09 12:17:34 +00:00
func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
2016-10-31 14:24:28 +00:00
user := request.User
rawAccount, err := user.GetTypedAccount()
if err != nil {
2017-04-23 18:41:45 +00:00
return nil, newError("failed to parse account").Base(err).AtError()
2016-10-31 14:24:28 +00:00
}
2017-11-29 21:57:18 +00:00
account := rawAccount.(*MemoryAccount)
2016-10-31 14:24:28 +00:00
2017-11-25 23:58:57 +00:00
if account.Cipher.IsAEAD() {
request.Option.Clear(RequestOptionOneTimeAuth)
}
2017-11-29 21:19:04 +00:00
var iv []byte
if account.Cipher.IVSize() > 0 {
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")
}
2016-10-31 14:24:28 +00:00
}
2017-11-25 23:51:54 +00:00
w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
2016-10-31 14:24:28 +00:00
if err != nil {
2017-04-26 22:09:01 +00:00
return nil, newError("failed to create encoding stream").Base(err).AtError()
2016-10-31 14:24:28 +00:00
}
2016-12-09 11:08:25 +00:00
header := buf.NewLocal(512)
2016-10-31 14:24:28 +00:00
switch request.Address.Family() {
case net.AddressFamilyIPv4:
2016-10-31 14:24:28 +00:00
header.AppendBytes(AddrTypeIPv4)
header.Append([]byte(request.Address.IP()))
case net.AddressFamilyIPv6:
2016-10-31 14:24:28 +00:00
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)))
2016-10-31 14:24:28 +00:00
default:
2017-04-09 11:30:46 +00:00
return nil, newError("unsupported address type: ", request.Address.Family())
2016-10-31 14:24:28 +00:00
}
common.Must(header.AppendSupplier(serial.WriteUint16(uint16(request.Port))))
2016-10-31 14:24:28 +00:00
if request.Option.Has(RequestOptionOneTimeAuth) {
2016-12-06 10:31:19 +00:00
header.SetByte(0, header.Byte(0)|0x10)
2016-10-31 14:24:28 +00:00
authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
common.Must(header.AppendSupplier(authenticator.Authenticate(header.Bytes())))
2016-10-31 14:24:28 +00:00
}
2017-11-26 15:56:01 +00:00
if err := w.WriteMultiBuffer(buf.NewMultiBufferValue(header)); err != nil {
2017-04-09 11:30:46 +00:00
return nil, newError("failed to write header").Base(err)
2016-10-31 14:24:28 +00:00
}
2016-12-09 12:17:34 +00:00
var chunkWriter buf.Writer
2016-10-31 14:24:28 +00:00
if request.Option.Has(RequestOptionOneTimeAuth) {
2017-11-26 15:56:01 +00:00
chunkWriter = NewChunkWriter(w.(io.Writer), NewAuthenticator(ChunkKeyGenerator(iv)))
2016-10-31 14:24:28 +00:00
} else {
2017-11-26 15:56:01 +00:00
chunkWriter = w
2016-10-31 14:24:28 +00:00
}
return chunkWriter, nil
}
2016-12-09 12:17:34 +00:00
func ReadTCPResponse(user *protocol.User, reader io.Reader) (buf.Reader, error) {
2016-10-31 14:24:28 +00:00
rawAccount, err := user.GetTypedAccount()
if err != nil {
2017-04-09 11:30:46 +00:00
return nil, newError("failed to parse account").Base(err).AtError()
2016-01-29 20:55:42 +00:00
}
2017-11-29 21:57:18 +00:00
account := rawAccount.(*MemoryAccount)
2017-11-29 21:19:04 +00:00
var iv []byte
if account.Cipher.IVSize() > 0 {
iv = make([]byte, account.Cipher.IVSize())
_, err = io.ReadFull(reader, iv)
if err != nil {
return nil, newError("failed to read IV").Base(err)
}
2016-10-31 14:24:28 +00:00
}
2017-11-25 23:51:54 +00:00
return account.Cipher.NewDecryptionReader(account.Key, iv, reader)
2016-10-31 14:24:28 +00:00
}
2016-12-09 12:17:34 +00:00
func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
2016-10-31 14:24:28 +00:00
user := request.User
rawAccount, err := user.GetTypedAccount()
if err != nil {
2017-04-09 11:30:46 +00:00
return nil, newError("failed to parse account.").Base(err).AtError()
2016-10-31 14:24:28 +00:00
}
2017-11-29 21:57:18 +00:00
account := rawAccount.(*MemoryAccount)
2016-10-31 14:24:28 +00:00
2017-11-29 21:19:04 +00:00
var iv []byte
if account.Cipher.IVSize() > 0 {
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)
}
2016-10-31 14:24:28 +00:00
}
2017-11-25 23:51:54 +00:00
return account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
2016-10-31 14:24:28 +00:00
}
2017-04-21 12:51:09 +00:00
func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) {
2016-10-31 14:24:28 +00:00
user := request.User
rawAccount, err := user.GetTypedAccount()
if err != nil {
2017-04-09 11:30:46 +00:00
return nil, newError("failed to parse account.").Base(err).AtError()
2016-10-31 14:24:28 +00:00
}
2017-11-29 21:57:18 +00:00
account := rawAccount.(*MemoryAccount)
2016-10-31 14:24:28 +00:00
2017-04-15 19:19:21 +00:00
buffer := buf.New()
2016-10-31 14:24:28 +00:00
ivLen := account.Cipher.IVSize()
2017-11-29 21:19:04 +00:00
if ivLen > 0 {
common.Must(buffer.Reset(buf.ReadFullFrom(rand.Reader, ivLen)))
}
2016-12-06 10:03:42 +00:00
iv := buffer.Bytes()
2016-10-31 14:24:28 +00:00
switch request.Address.Family() {
case net.AddressFamilyIPv4:
2017-11-26 20:51:30 +00:00
buffer.AppendBytes(AddrTypeIPv4)
buffer.Append([]byte(request.Address.IP()))
case net.AddressFamilyIPv6:
2017-11-26 20:51:30 +00:00
buffer.AppendBytes(AddrTypeIPv6)
buffer.Append([]byte(request.Address.IP()))
case net.AddressFamilyDomain:
2017-11-26 20:51:30 +00:00
buffer.AppendBytes(AddrTypeDomain, byte(len(request.Address.Domain())))
buffer.Append([]byte(request.Address.Domain()))
2016-10-31 14:24:28 +00:00
default:
2017-04-26 22:09:01 +00:00
return nil, newError("unsupported address type: ", request.Address.Family()).AtError()
2016-10-31 14:24:28 +00:00
}
2017-11-26 20:51:30 +00:00
common.Must(buffer.AppendSupplier(serial.WriteUint16(uint16(request.Port))))
buffer.Append(payload)
2016-10-31 14:24:28 +00:00
2017-11-26 13:18:23 +00:00
if !account.Cipher.IsAEAD() && request.Option.Has(RequestOptionOneTimeAuth) {
2016-10-31 14:24:28 +00:00
authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
2017-11-26 20:51:30 +00:00
buffer.SetByte(ivLen, buffer.Byte(ivLen)|0x10)
2016-10-31 14:24:28 +00:00
2017-11-26 20:51:30 +00:00
common.Must(buffer.AppendSupplier(authenticator.Authenticate(buffer.BytesFrom(ivLen))))
2016-10-31 14:24:28 +00:00
}
2017-11-26 20:51:30 +00:00
if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil {
return nil, newError("failed to encrypt UDP payload").Base(err)
2017-11-25 23:51:54 +00:00
}
2016-10-31 14:24:28 +00:00
return buffer, nil
}
2016-12-09 10:35:27 +00:00
func DecodeUDPPacket(user *protocol.User, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) {
2016-10-31 14:24:28 +00:00
rawAccount, err := user.GetTypedAccount()
if err != nil {
2017-04-09 11:30:46 +00:00
return nil, nil, newError("failed to parse account").Base(err).AtError()
2016-10-31 14:24:28 +00:00
}
2017-11-29 21:57:18 +00:00
account := rawAccount.(*MemoryAccount)
2016-10-31 14:24:28 +00:00
2017-11-27 09:42:51 +00:00
var iv []byte
2017-11-29 21:19:04 +00:00
if !account.Cipher.IsAEAD() && account.Cipher.IVSize() > 0 {
2017-11-27 09:42:51 +00:00
// Keep track of IV as it gets removed from payload in DecodePacket.
iv = make([]byte, account.Cipher.IVSize())
copy(iv, payload.BytesTo(account.Cipher.IVSize()))
2016-10-31 14:24:28 +00:00
}
2017-11-26 20:51:30 +00:00
if err := account.Cipher.DecodePacket(account.Key, payload); err != nil {
return nil, nil, newError("failed to decrypt UDP payload").Base(err)
2017-11-25 23:51:54 +00:00
}
2016-10-31 14:24:28 +00:00
request := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandUDP,
}
2017-11-26 13:18:23 +00:00
if !account.Cipher.IsAEAD() {
if (payload.Byte(0) & 0x10) == 0x10 {
request.Option |= RequestOptionOneTimeAuth
}
2016-10-31 14:24:28 +00:00
2017-11-26 13:18:23 +00:00
if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
return nil, nil, newError("rejecting packet with OTA enabled, while server disables OTA").AtWarning()
}
2017-11-26 13:18:23 +00:00
if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
return nil, nil, newError("rejecting packet with OTA disabled, while server enables OTA").AtWarning()
}
2017-11-26 13:18:23 +00:00
if request.Option.Has(RequestOptionOneTimeAuth) {
payloadLen := payload.Len() - AuthSize
authBytes := payload.BytesFrom(payloadLen)
2016-10-31 14:24:28 +00:00
2017-11-29 22:08:02 +00:00
authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
2017-11-26 13:18:23 +00:00
actualAuth := make([]byte, AuthSize)
authenticator.Authenticate(payload.BytesTo(payloadLen))(actualAuth)
if !bytes.Equal(actualAuth, authBytes) {
return nil, nil, newError("invalid OTA")
}
2016-10-31 14:24:28 +00:00
2017-11-26 13:18:23 +00:00
payload.Slice(0, payloadLen)
}
2016-10-31 14:24:28 +00:00
}
2017-11-26 13:18:23 +00:00
addrType := (payload.Byte(0) & 0x0F)
2016-10-31 14:24:28 +00:00
payload.SliceFrom(1)
switch addrType {
case AddrTypeIPv4:
request.Address = net.IPAddress(payload.BytesTo(4))
2016-10-31 14:24:28 +00:00
payload.SliceFrom(4)
case AddrTypeIPv6:
request.Address = net.IPAddress(payload.BytesTo(16))
2016-10-31 14:24:28 +00:00
payload.SliceFrom(16)
case AddrTypeDomain:
2016-12-06 10:03:42 +00:00
domainLength := int(payload.Byte(0))
request.Address = net.DomainAddress(string(payload.BytesRange(1, 1+domainLength)))
2016-10-31 14:24:28 +00:00
payload.SliceFrom(1 + domainLength)
default:
2017-04-26 22:09:01 +00:00
return nil, nil, newError("unknown address type: ", addrType).AtError()
}
request.Port = net.PortFromBytes(payload.BytesTo(2))
2016-10-31 14:24:28 +00:00
payload.SliceFrom(2)
return request, payload, nil
2016-01-28 11:33:58 +00:00
}
2016-10-31 15:35:18 +00:00
type UDPReader struct {
Reader io.Reader
User *protocol.User
}
2017-11-09 21:33:15 +00:00
func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
2017-04-15 19:19:21 +00:00
buffer := buf.New()
2016-12-09 11:08:25 +00:00
err := buffer.AppendSupplier(buf.ReadFrom(v.Reader))
2016-10-31 15:35:18 +00:00
if err != nil {
buffer.Release()
return nil, err
}
2016-11-27 20:39:09 +00:00
_, payload, err := DecodeUDPPacket(v.User, buffer)
2016-10-31 15:35:18 +00:00
if err != nil {
buffer.Release()
return nil, err
}
2017-04-16 11:17:35 +00:00
return buf.NewMultiBufferValue(payload), nil
2016-10-31 15:35:18 +00:00
}
type UDPWriter struct {
Writer io.Writer
Request *protocol.RequestHeader
}
2017-04-21 13:36:05 +00:00
// Write implements io.Writer.
2017-04-21 12:51:09 +00:00
func (w *UDPWriter) Write(payload []byte) (int, error) {
packet, err := EncodeUDPPacket(w.Request, payload)
2016-10-31 15:35:18 +00:00
if err != nil {
2017-04-21 12:51:09 +00:00
return 0, err
2016-10-31 15:35:18 +00:00
}
2017-04-21 12:51:09 +00:00
_, err = w.Writer.Write(packet.Bytes())
packet.Release()
return len(payload), err
2016-10-31 15:35:18 +00:00
}