v2ray-core/proxy/socks/protocol.go

509 lines
13 KiB
Go
Raw Normal View History

2017-01-03 23:43:13 +00:00
package socks
import (
"io"
"v2ray.com/core/common"
2017-01-03 23:43:13 +00:00
"v2ray.com/core/common/buf"
"v2ray.com/core/common/net"
2017-01-03 23:43:13 +00:00
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
)
const (
socks5Version = 0x05
socks4Version = 0x04
cmdTCPConnect = 0x01
cmdTCPBind = 0x02
cmdUDPPort = 0x03
socks4RequestGranted = 90
socks4RequestRejected = 91
2017-01-08 22:31:45 +00:00
authNotRequired = 0x00
//authGssAPI = 0x01
2017-01-03 23:43:13 +00:00
authPassword = 0x02
authNoMatchingMethod = 0xFF
addrTypeIPv4 = 0x01
addrTypeIPv6 = 0x04
addrTypeDomain = 0x03
statusSuccess = 0x00
statusCmdNotSupport = 0x07
)
type ServerSession struct {
config *ServerConfig
port net.Port
2017-01-03 23:43:13 +00:00
}
func (s *ServerSession) Handshake(reader io.Reader, writer io.Writer) (*protocol.RequestHeader, error) {
buffer := buf.NewLocal(512)
request := new(protocol.RequestHeader)
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 2)); err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("insufficient header").Base(err)
2017-01-03 23:43:13 +00:00
}
version := buffer.Byte(0)
if version == socks4Version {
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 6)); err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("insufficient header").Base(err)
2017-01-03 23:43:13 +00:00
}
port := net.PortFromBytes(buffer.BytesRange(2, 4))
address := net.IPAddress(buffer.BytesRange(4, 8))
2017-01-03 23:43:13 +00:00
_, err := readUntilNull(reader) // user id
if err != nil {
return nil, err
}
if address.IP()[0] == 0x00 {
domain, err := readUntilNull(reader)
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read domain for socks 4a").Base(err)
2017-01-03 23:43:13 +00:00
}
address = net.DomainAddress(domain)
2017-01-03 23:43:13 +00:00
}
switch buffer.Byte(1) {
case cmdTCPConnect:
request.Command = protocol.RequestCommandTCP
request.Address = address
request.Port = port
request.Version = socks4Version
if err := writeSocks4Response(writer, socks4RequestGranted, net.AnyIP, net.Port(0)); err != nil {
2017-01-03 23:43:13 +00:00
return nil, err
}
return request, nil
default:
writeSocks4Response(writer, socks4RequestRejected, net.AnyIP, net.Port(0))
2017-04-09 11:30:46 +00:00
return nil, newError("unsupported command: ", buffer.Byte(1))
2017-01-03 23:43:13 +00:00
}
}
if version == socks5Version {
nMethod := int(buffer.Byte(1))
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, nMethod)); err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read auth methods").Base(err)
2017-01-03 23:43:13 +00:00
}
var expectedAuth byte = authNotRequired
2017-01-08 00:06:35 +00:00
if s.config.AuthType == AuthType_PASSWORD {
2017-01-03 23:43:13 +00:00
expectedAuth = authPassword
}
if !hasAuthMethod(expectedAuth, buffer.BytesRange(2, 2+nMethod)) {
2017-01-29 07:25:01 +00:00
writeSocks5AuthenticationResponse(writer, socks5Version, authNoMatchingMethod)
2017-04-08 23:43:25 +00:00
return nil, newError("no matching auth method")
2017-01-03 23:43:13 +00:00
}
2017-01-29 07:25:01 +00:00
if err := writeSocks5AuthenticationResponse(writer, socks5Version, expectedAuth); err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to write auth response").Base(err)
2017-01-08 00:06:35 +00:00
}
2017-01-03 23:43:13 +00:00
if expectedAuth == authPassword {
username, password, err := readUsernamePassword(reader)
2017-01-17 09:22:18 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read username and password for authentication").Base(err)
2017-01-17 09:22:18 +00:00
}
if !s.config.HasAccount(username, password) {
2017-01-29 07:25:01 +00:00
writeSocks5AuthenticationResponse(writer, 0x01, 0xFF)
2017-04-08 23:43:25 +00:00
return nil, newError("invalid username or password")
2017-01-03 23:43:13 +00:00
}
2017-01-29 07:25:01 +00:00
if err := writeSocks5AuthenticationResponse(writer, 0x01, 0x00); err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to write auth response").Base(err)
2017-01-08 00:06:35 +00:00
}
2017-01-03 23:43:13 +00:00
}
2017-04-18 20:36:43 +00:00
if err := buffer.Reset(buf.ReadFullFrom(reader, 4)); err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read request").Base(err)
2017-01-03 23:43:13 +00:00
}
cmd := buffer.Byte(1)
if cmd == cmdTCPBind || (cmd == cmdUDPPort && !s.config.UdpEnabled) {
writeSocks5Response(writer, statusCmdNotSupport, net.AnyIP, net.Port(0))
2017-04-08 23:43:25 +00:00
return nil, newError("unsupported command: ", cmd)
2017-01-03 23:43:13 +00:00
}
switch cmd {
case cmdTCPConnect:
request.Command = protocol.RequestCommandTCP
case cmdUDPPort:
request.Command = protocol.RequestCommandUDP
}
addrType := buffer.Byte(3)
buffer.Clear()
request.Version = socks5Version
switch addrType {
case addrTypeIPv4:
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 4)); err != nil {
return nil, err
}
request.Address = net.IPAddress(buffer.Bytes())
2017-01-03 23:43:13 +00:00
case addrTypeIPv6:
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 16)); err != nil {
return nil, err
}
request.Address = net.IPAddress(buffer.Bytes())
2017-01-03 23:43:13 +00:00
case addrTypeDomain:
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 1)); err != nil {
return nil, err
}
domainLength := int(buffer.Byte(0))
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, domainLength)); err != nil {
return nil, err
}
request.Address = net.ParseAddress(string(buffer.BytesFrom(-domainLength)))
2017-01-03 23:43:13 +00:00
default:
2017-04-08 23:43:25 +00:00
return nil, newError("Unknown address type: ", addrType)
2017-01-03 23:43:13 +00:00
}
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 2)); err != nil {
return nil, err
}
request.Port = net.PortFromBytes(buffer.BytesFrom(-2))
2017-01-03 23:43:13 +00:00
responseAddress := net.AnyIP
responsePort := net.Port(1717)
2017-01-03 23:43:13 +00:00
if request.Command == protocol.RequestCommandUDP {
addr := s.config.Address.AsAddress()
if addr == nil {
addr = net.LocalHostIP
2017-01-03 23:43:13 +00:00
}
responseAddress = addr
responsePort = s.port
2017-01-03 23:43:13 +00:00
}
if err := writeSocks5Response(writer, statusSuccess, responseAddress, responsePort); err != nil {
return nil, err
}
return request, nil
}
2017-04-08 23:43:25 +00:00
return nil, newError("unknown Socks version: ", version)
2017-01-03 23:43:13 +00:00
}
func readUsernamePassword(reader io.Reader) (string, string, error) {
buffer := buf.NewLocal(512)
defer buffer.Release()
2017-04-18 20:36:43 +00:00
if err := buffer.Reset(buf.ReadFullFrom(reader, 2)); err != nil {
2017-01-03 23:43:13 +00:00
return "", "", err
}
nUsername := int(buffer.Byte(1))
2017-04-18 20:36:43 +00:00
if err := buffer.Reset(buf.ReadFullFrom(reader, nUsername)); err != nil {
2017-01-03 23:43:13 +00:00
return "", "", err
}
username := buffer.String()
2017-04-18 20:36:43 +00:00
if err := buffer.Reset(buf.ReadFullFrom(reader, 1)); err != nil {
2017-01-03 23:43:13 +00:00
return "", "", err
}
nPassword := int(buffer.Byte(0))
2017-04-18 20:36:43 +00:00
if err := buffer.Reset(buf.ReadFullFrom(reader, nPassword)); err != nil {
2017-01-03 23:43:13 +00:00
return "", "", err
}
password := buffer.String()
return username, password, nil
}
func readUntilNull(reader io.Reader) (string, error) {
var b [256]byte
size := 0
for {
_, err := reader.Read(b[size : size+1])
if err != nil {
return "", err
}
if b[size] == 0x00 {
return string(b[:size]), nil
}
size++
if size == 256 {
2017-04-08 23:43:25 +00:00
return "", newError("buffer overrun")
2017-01-03 23:43:13 +00:00
}
}
}
func hasAuthMethod(expectedAuth byte, authCandidates []byte) bool {
for _, a := range authCandidates {
if a == expectedAuth {
return true
}
}
return false
}
2017-01-29 07:25:01 +00:00
func writeSocks5AuthenticationResponse(writer io.Writer, version byte, auth byte) error {
_, err := writer.Write([]byte{version, auth})
2017-01-03 23:43:13 +00:00
return err
}
2017-12-03 23:55:34 +00:00
// AppendAddress appends Socks address into the given buffer.
func AppendAddress(buffer *buf.Buffer, address net.Address, port net.Port) error {
2017-01-03 23:43:13 +00:00
switch address.Family() {
case net.AddressFamilyIPv4:
2017-12-03 23:55:34 +00:00
buffer.AppendBytes(addrTypeIPv4)
2017-01-03 23:43:13 +00:00
buffer.Append(address.IP())
case net.AddressFamilyIPv6:
2017-12-03 23:55:34 +00:00
buffer.AppendBytes(addrTypeIPv6)
2017-01-03 23:43:13 +00:00
buffer.Append(address.IP())
case net.AddressFamilyDomain:
if protocol.IsDomainTooLong(address.Domain()) {
return newError("Super long domain is not supported in Socks protocol: ", address.Domain())
2017-09-18 23:39:33 +00:00
}
2017-12-03 23:55:34 +00:00
buffer.AppendBytes(addrTypeDomain, byte(len(address.Domain())))
common.Must(buffer.AppendSupplier(serial.WriteString(address.Domain())))
2017-01-03 23:43:13 +00:00
}
common.Must(buffer.AppendSupplier(serial.WriteUint16(port.Value())))
2017-09-18 23:39:33 +00:00
return nil
2017-01-08 00:06:35 +00:00
}
func writeSocks5Response(writer io.Writer, errCode byte, address net.Address, port net.Port) error {
2017-01-08 00:06:35 +00:00
buffer := buf.NewLocal(64)
buffer.AppendBytes(socks5Version, errCode, 0x00 /* reserved */)
2017-12-03 23:55:34 +00:00
if err := AppendAddress(buffer, address, port); err != nil {
2017-09-18 23:39:33 +00:00
return err
}
2017-01-03 23:43:13 +00:00
_, err := writer.Write(buffer.Bytes())
return err
}
func writeSocks4Response(writer io.Writer, errCode byte, address net.Address, port net.Port) error {
2017-01-03 23:43:13 +00:00
buffer := buf.NewLocal(32)
buffer.AppendBytes(0x00, errCode)
buffer.AppendSupplier(serial.WriteUint16(port.Value()))
buffer.Append(address.IP())
_, err := writer.Write(buffer.Bytes())
return err
}
2017-01-07 20:57:24 +00:00
func DecodeUDPPacket(packet []byte) (*protocol.RequestHeader, []byte, error) {
if len(packet) < 5 {
2017-04-09 11:30:46 +00:00
return nil, nil, newError("insufficient length of packet.")
2017-01-07 20:57:24 +00:00
}
request := &protocol.RequestHeader{
Version: socks5Version,
Command: protocol.RequestCommandUDP,
}
// packet[0] and packet[1] are reserved
if packet[2] != 0 /* fragments */ {
2017-04-09 11:30:46 +00:00
return nil, nil, newError("discarding fragmented payload.")
2017-01-07 20:57:24 +00:00
}
addrType := packet[3]
var dataBegin int
switch addrType {
case addrTypeIPv4:
if len(packet) < 10 {
2017-04-09 11:30:46 +00:00
return nil, nil, newError("insufficient length of packet")
2017-01-07 20:57:24 +00:00
}
ip := packet[4:8]
request.Port = net.PortFromBytes(packet[8:10])
request.Address = net.IPAddress(ip)
2017-01-07 20:57:24 +00:00
dataBegin = 10
case addrTypeIPv6:
if len(packet) < 22 {
2017-04-09 11:30:46 +00:00
return nil, nil, newError("insufficient length of packet")
2017-01-07 20:57:24 +00:00
}
ip := packet[4:20]
request.Port = net.PortFromBytes(packet[20:22])
request.Address = net.IPAddress(ip)
2017-01-07 20:57:24 +00:00
dataBegin = 22
case addrTypeDomain:
domainLength := int(packet[4])
if len(packet) < 5+domainLength+2 {
2017-04-09 11:30:46 +00:00
return nil, nil, newError("insufficient length of packet")
2017-01-07 20:57:24 +00:00
}
domain := string(packet[5 : 5+domainLength])
request.Port = net.PortFromBytes(packet[5+domainLength : 5+domainLength+2])
request.Address = net.ParseAddress(domain)
2017-01-07 20:57:24 +00:00
dataBegin = 5 + domainLength + 2
default:
2017-04-09 11:30:46 +00:00
return nil, nil, newError("unknown address type ", addrType)
2017-01-07 20:57:24 +00:00
}
return request, packet[dataBegin:], nil
}
2017-09-18 23:39:33 +00:00
func EncodeUDPPacket(request *protocol.RequestHeader, data []byte) (*buf.Buffer, error) {
2017-04-15 19:19:21 +00:00
b := buf.New()
2017-01-07 20:57:24 +00:00
b.AppendBytes(0, 0, 0 /* Fragment */)
2017-12-03 23:55:34 +00:00
if err := AppendAddress(b, request.Address, request.Port); err != nil {
2017-09-18 23:39:33 +00:00
return nil, err
}
2017-01-07 20:57:24 +00:00
b.Append(data)
2017-09-18 23:39:33 +00:00
return b, nil
2017-01-07 20:57:24 +00:00
}
2017-01-08 00:06:35 +00:00
type UDPReader struct {
reader io.Reader
}
2017-01-08 15:31:28 +00:00
func NewUDPReader(reader io.Reader) *UDPReader {
return &UDPReader{reader: reader}
}
2017-11-09 21:33:15 +00:00
func (r *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
2017-04-15 19:19:21 +00:00
b := buf.New()
2017-01-08 00:06:35 +00:00
if err := b.AppendSupplier(buf.ReadFrom(r.reader)); err != nil {
return nil, err
}
_, data, err := DecodeUDPPacket(b.Bytes())
if err != nil {
return nil, err
}
b.Clear()
b.Append(data)
2017-04-16 11:17:35 +00:00
return buf.NewMultiBufferValue(b), nil
2017-01-08 00:06:35 +00:00
}
type UDPWriter struct {
request *protocol.RequestHeader
writer io.Writer
}
2017-01-08 15:31:28 +00:00
func NewUDPWriter(request *protocol.RequestHeader, writer io.Writer) *UDPWriter {
return &UDPWriter{
request: request,
writer: writer,
}
}
2017-04-21 13:36:05 +00:00
// Write implements io.Writer.
2017-04-21 12:51:09 +00:00
func (w *UDPWriter) Write(b []byte) (int, error) {
2017-09-18 23:39:33 +00:00
eb, err := EncodeUDPPacket(w.request, b)
if err != nil {
return 0, err
}
2017-04-21 12:51:09 +00:00
defer eb.Release()
if _, err := w.writer.Write(eb.Bytes()); err != nil {
return 0, err
2017-01-08 00:06:35 +00:00
}
2017-04-21 12:51:09 +00:00
return len(b), nil
2017-01-08 00:06:35 +00:00
}
func ClientHandshake(request *protocol.RequestHeader, reader io.Reader, writer io.Writer) (*protocol.RequestHeader, error) {
authByte := byte(authNotRequired)
if request.User != nil {
authByte = byte(authPassword)
}
authRequest := []byte{socks5Version, 0x01, authByte}
if _, err := writer.Write(authRequest); err != nil {
return nil, err
}
2017-09-07 20:58:04 +00:00
b := buf.NewLocal(512)
2017-01-08 00:06:35 +00:00
if err := b.AppendSupplier(buf.ReadFullFrom(reader, 2)); err != nil {
return nil, err
}
if b.Byte(0) != socks5Version {
2017-04-09 11:30:46 +00:00
return nil, newError("unexpected server version: ", b.Byte(0)).AtWarning()
2017-01-08 00:06:35 +00:00
}
if b.Byte(1) != authByte {
2017-04-09 11:30:46 +00:00
return nil, newError("auth method not supported.").AtWarning()
2017-01-08 00:06:35 +00:00
}
if authByte == authPassword {
rawAccount, err := request.User.GetTypedAccount()
if err != nil {
return nil, err
}
account := rawAccount.(*Account)
b.Clear()
b.AppendBytes(socks5Version, byte(len(account.Username)))
b.Append([]byte(account.Username))
b.AppendBytes(byte(len(account.Password)))
b.Append([]byte(account.Password))
if _, err := writer.Write(b.Bytes()); err != nil {
return nil, err
}
b.Clear()
if err := b.AppendSupplier(buf.ReadFullFrom(reader, 2)); err != nil {
return nil, err
}
if b.Byte(1) != 0x00 {
2017-04-09 11:30:46 +00:00
return nil, newError("server rejects account: ", b.Byte(1))
2017-01-08 00:06:35 +00:00
}
}
b.Clear()
command := byte(cmdTCPConnect)
if request.Command == protocol.RequestCommandUDP {
command = byte(cmdUDPPort)
}
b.AppendBytes(socks5Version, command, 0x00 /* reserved */)
2017-12-03 23:55:34 +00:00
AppendAddress(b, request.Address, request.Port)
2017-01-08 00:06:35 +00:00
if _, err := writer.Write(b.Bytes()); err != nil {
return nil, err
}
b.Clear()
if err := b.AppendSupplier(buf.ReadFullFrom(reader, 4)); err != nil {
return nil, err
}
resp := b.Byte(1)
if resp != 0x00 {
2017-04-09 11:30:46 +00:00
return nil, newError("server rejects request: ", resp)
2017-01-08 00:06:35 +00:00
}
addrType := b.Byte(3)
b.Clear()
var address net.Address
2017-01-08 00:06:35 +00:00
switch addrType {
case addrTypeIPv4:
if err := b.AppendSupplier(buf.ReadFullFrom(reader, 4)); err != nil {
return nil, err
}
address = net.IPAddress(b.Bytes())
2017-01-08 00:06:35 +00:00
case addrTypeIPv6:
if err := b.AppendSupplier(buf.ReadFullFrom(reader, 16)); err != nil {
return nil, err
}
address = net.IPAddress(b.Bytes())
2017-01-08 00:06:35 +00:00
case addrTypeDomain:
if err := b.AppendSupplier(buf.ReadFullFrom(reader, 1)); err != nil {
return nil, err
}
domainLength := int(b.Byte(0))
if err := b.AppendSupplier(buf.ReadFullFrom(reader, domainLength)); err != nil {
return nil, err
}
address = net.DomainAddress(string(b.BytesFrom(-domainLength)))
2017-01-08 00:06:35 +00:00
default:
2017-04-09 11:30:46 +00:00
return nil, newError("unknown address type: ", addrType)
2017-01-08 00:06:35 +00:00
}
if err := b.AppendSupplier(buf.ReadFullFrom(reader, 2)); err != nil {
return nil, err
}
port := net.PortFromBytes(b.BytesFrom(-2))
2017-01-08 00:06:35 +00:00
if request.Command == protocol.RequestCommandUDP {
udpRequest := &protocol.RequestHeader{
Version: socks5Version,
Command: protocol.RequestCommandUDP,
Address: address,
Port: port,
}
return udpRequest, nil
}
return nil, nil
}