Beispiel #1
1
func (server *SocksServer) handleSocks4(reader io.Reader, writer io.Writer, auth protocol.Socks4AuthenticationRequest) error {
	result := protocol.Socks4RequestGranted
	if auth.Command == protocol.CmdBind {
		result = protocol.Socks4RequestRejected
	}
	socks4Response := protocol.NewSocks4AuthenticationResponse(result, auth.Port, auth.IP[:])

	responseBuffer := alloc.NewSmallBuffer().Clear()
	socks4Response.Write(responseBuffer)
	writer.Write(responseBuffer.Value)
	responseBuffer.Release()

	if result == protocol.Socks4RequestRejected {
		log.Warning("Unsupported socks 4 command %d", auth.Command)
		return UnsupportedSocksCommand
	}

	dest := v2net.NewTCPDestination(v2net.IPAddress(auth.IP[:], auth.Port))
	data, err := v2net.ReadFrom(reader, nil)
	if err != nil {
		return err
	}

	packet := v2net.NewPacket(dest, data, true)
	server.transport(reader, writer, packet)
	return nil
}
Beispiel #2
0
func ReadVMessUDP(buffer []byte, userset user.UserSet) (*VMessUDP, error) {
	userHash := buffer[:user.IDBytesLen]
	userId, timeSec, valid := userset.GetUser(userHash)
	if !valid {
		return nil, errors.NewAuthenticationError(userHash)
	}

	buffer = buffer[user.IDBytesLen:]
	aesCipher, err := aes.NewCipher(userId.CmdKey())
	if err != nil {
		return nil, err
	}
	aesStream := cipher.NewCFBDecrypter(aesCipher, user.Int64Hash(timeSec))
	aesStream.XORKeyStream(buffer, buffer)

	fnvHash := binary.BigEndian.Uint32(buffer[:4])
	fnv1a := fnv.New32a()
	fnv1a.Write(buffer[4:])
	fnvHashActual := fnv1a.Sum32()

	if fnvHash != fnvHashActual {
		log.Warning("Unexpected fhv hash %d, should be %d", fnvHashActual, fnvHash)
		return nil, errors.NewCorruptedPacketError()
	}

	buffer = buffer[4:]

	vmess := &VMessUDP{
		user:    *userId,
		version: buffer[0],
		token:   binary.BigEndian.Uint16(buffer[1:3]),
	}

	// buffer[3] is reserved

	port := binary.BigEndian.Uint16(buffer[4:6])
	addrType := buffer[6]
	var address v2net.Address
	switch addrType {
	case addrTypeIPv4:
		address = v2net.IPAddress(buffer[7:11], port)
		buffer = buffer[11:]
	case addrTypeIPv6:
		address = v2net.IPAddress(buffer[7:23], port)
		buffer = buffer[23:]
	case addrTypeDomain:
		domainLength := buffer[7]
		domain := string(buffer[8 : 8+domainLength])
		address = v2net.DomainAddress(domain, port)
		buffer = buffer[8+domainLength:]
	default:
		log.Warning("Unexpected address type %d", addrType)
		return nil, errors.NewCorruptedPacketError()
	}

	vmess.address = address
	vmess.data = buffer

	return vmess, nil
}
Beispiel #3
0
func ReadUDPRequest(packet []byte) (request Socks5UDPRequest, err error) {
	// packet[0] and packet[1] are reserved
	request.Fragment = packet[2]

	addrType := packet[3]
	var dataBegin int

	switch addrType {
	case AddrTypeIPv4:
		ip := packet[4:8]
		port := binary.BigEndian.Uint16(packet[8:10])
		request.Address = v2net.IPAddress(ip, port)
		dataBegin = 10
	case AddrTypeIPv6:
		ip := packet[4:20]
		port := binary.BigEndian.Uint16(packet[20:22])
		request.Address = v2net.IPAddress(ip, port)
		dataBegin = 22
	case AddrTypeDomain:
		domainLength := int(packet[4])
		domain := string(packet[5 : 5+domainLength])
		port := binary.BigEndian.Uint16(packet[5+domainLength : 5+domainLength+2])
		request.Address = v2net.DomainAddress(domain, port)
		dataBegin = 5 + domainLength + 2
	default:
		log.Warning("Unknown address type %d", addrType)
		err = ErrorUnknownAddressType
		return
	}

	request.Data = make([]byte, len(packet)-dataBegin)
	copy(request.Data, packet[dataBegin:])

	return
}
Beispiel #4
0
func (this *CacheDns) Unmarshal(data []byte) error {
	if len(data) == 0 {
		return transport.CorruptedPacket
	}
	typeIP := data[0]
	data = data[1:]

	if typeIP == typeIPv4 {
		if len(data) < 4 {
			return transport.CorruptedPacket
		}
		this.Address = v2net.IPAddress(data[0:4])
		return nil
	}

	if typeIP == typeIPv6 {
		if len(data) < 16 {
			return transport.CorruptedPacket
		}
		this.Address = v2net.IPAddress(data[0:16])
		return nil
	}

	return transport.CorruptedPacket
}
Beispiel #5
0
func ReadRequest(reader io.Reader) (*Request, error) {
	buffer := alloc.NewSmallBuffer()
	defer buffer.Release()

	_, err := v2net.ReadAllBytes(reader, buffer.Value[:1])
	if err != nil {
		log.Error("Shadowsocks: Failed to read address type: ", err)
		return nil, transport.CorruptedPacket
	}

	request := new(Request)

	addrType := buffer.Value[0]
	switch addrType {
	case AddrTypeIPv4:
		_, err := v2net.ReadAllBytes(reader, buffer.Value[:4])
		if err != nil {
			log.Error("Shadowsocks: Failed to read IPv4 address: ", err)
			return nil, transport.CorruptedPacket
		}
		request.Address = v2net.IPAddress(buffer.Value[:4])
	case AddrTypeIPv6:
		_, err := v2net.ReadAllBytes(reader, buffer.Value[:16])
		if err != nil {
			log.Error("Shadowsocks: Failed to read IPv6 address: ", err)
			return nil, transport.CorruptedPacket
		}
		request.Address = v2net.IPAddress(buffer.Value[:16])
	case AddrTypeDomain:
		_, err := v2net.ReadAllBytes(reader, buffer.Value[:1])
		if err != nil {
			log.Error("Shadowsocks: Failed to read domain lenth: ", err)
			return nil, transport.CorruptedPacket
		}
		domainLength := int(buffer.Value[0])
		_, err = v2net.ReadAllBytes(reader, buffer.Value[:domainLength])
		if err != nil {
			log.Error("Shadowsocks: Failed to read domain: ", err)
			return nil, transport.CorruptedPacket
		}
		request.Address = v2net.DomainAddress(string(buffer.Value[:domainLength]))
	default:
		log.Error("Shadowsocks: Unknown address type: ", addrType)
		return nil, transport.CorruptedPacket
	}

	_, err = v2net.ReadAllBytes(reader, buffer.Value[:2])
	if err != nil {
		log.Error("Shadowsocks: Failed to read port: ", err)
		return nil, transport.CorruptedPacket
	}

	request.Port = v2net.PortFromBytes(buffer.Value[:2])
	return request, nil
}
Beispiel #6
0
func ReadUDPRequest(packet []byte) (*Socks5UDPRequest, error) {
	if len(packet) < 5 {
		return nil, transport.CorruptedPacket
	}
	request := new(Socks5UDPRequest)

	// packet[0] and packet[1] are reserved
	request.Fragment = packet[2]

	addrType := packet[3]
	var dataBegin int

	switch addrType {
	case AddrTypeIPv4:
		if len(packet) < 10 {
			return nil, transport.CorruptedPacket
		}
		ip := packet[4:8]
		request.Port = v2net.PortFromBytes(packet[8:10])
		request.Address = v2net.IPAddress(ip)
		dataBegin = 10
	case AddrTypeIPv6:
		if len(packet) < 22 {
			return nil, transport.CorruptedPacket
		}
		ip := packet[4:20]
		request.Port = v2net.PortFromBytes(packet[20:22])
		request.Address = v2net.IPAddress(ip)
		dataBegin = 22
	case AddrTypeDomain:
		domainLength := int(packet[4])
		if len(packet) < 5+domainLength+2 {
			return nil, transport.CorruptedPacket
		}
		domain := string(packet[5 : 5+domainLength])
		request.Port = v2net.PortFromBytes(packet[5+domainLength : 5+domainLength+2])
		maybeIP := net.ParseIP(domain)
		if maybeIP != nil {
			request.Address = v2net.IPAddress(maybeIP)
		} else {
			request.Address = v2net.DomainAddress(domain)
		}
		dataBegin = 5 + domainLength + 2
	default:
		log.Warning("Unknown address type ", addrType)
		return nil, ErrorUnknownAddressType
	}

	if len(packet) > dataBegin {
		request.Data = alloc.NewBuffer().Clear().Append(packet[dataBegin:])
	}

	return request, nil
}
Beispiel #7
0
func (request *Socks5Request) Destination() v2net.Destination {
	switch request.AddrType {
	case AddrTypeIPv4:
		return v2net.TCPDestination(v2net.IPAddress(request.IPv4[:]), request.Port)
	case AddrTypeIPv6:
		return v2net.TCPDestination(v2net.IPAddress(request.IPv6[:]), request.Port)
	case AddrTypeDomain:
		return v2net.TCPDestination(v2net.ParseAddress(request.Domain), request.Port)
	default:
		panic("Unknown address type")
	}
}
Beispiel #8
0
func (request *Socks5Request) Destination() v2net.Destination {
	var address v2net.Address
	switch request.AddrType {
	case AddrTypeIPv4:
		address = v2net.IPAddress(request.IPv4[:], request.Port)
	case AddrTypeIPv6:
		address = v2net.IPAddress(request.IPv6[:], request.Port)
	case AddrTypeDomain:
		address = v2net.DomainAddress(request.Domain, request.Port)
	default:
		panic("Unknown address type")
	}
	return v2net.NewTCPDestination(address)
}
func TestUDPDestinationEquals(t *testing.T) {
	assert := assert.On(t)

	dest := v2net.UDPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	assert.Bool(dest.Equals(nil)).IsFalse()

	dest2 := v2net.UDPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	assert.Bool(dest.Equals(dest2)).IsTrue()

	dest3 := v2net.TCPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	assert.Bool(dest.Equals(dest3)).IsFalse()

	dest4 := v2net.UDPDestination(v2net.DomainAddress("v2ray.com"), 80)
	assert.Bool(dest.Equals(dest4)).IsFalse()
}
Beispiel #10
0
func TestIPv6AddressEquals(t *testing.T) {
	assert := assert.On(t)

	addr := v2net.IPAddress([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6})
	assert.Bool(addr.Equals(nil)).IsFalse()

	addr2 := v2net.IPAddress([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6})
	assert.Bool(addr.Equals(addr2)).IsTrue()

	addr3 := v2net.IPAddress([]byte{1, 2, 3, 4})
	assert.Bool(addr.Equals(addr3)).IsFalse()

	addr4 := v2net.IPAddress([]byte{1, 3, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6})
	assert.Bool(addr.Equals(addr4)).IsFalse()
}
Beispiel #11
0
func TestIPv4AddressEquals(t *testing.T) {
	assert := assert.On(t)

	addr := v2net.IPAddress([]byte{1, 2, 3, 4})
	assert.Address(addr).NotEquals(nil)

	addr2 := v2net.IPAddress([]byte{1, 2, 3, 4})
	assert.Address(addr).Equals(addr2)

	addr3 := v2net.IPAddress([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6})
	assert.Address(addr).NotEquals(addr3)

	addr4 := v2net.IPAddress([]byte{1, 2, 3, 5})
	assert.Address(addr).NotEquals(addr4)
}
Beispiel #12
0
// @Private
func (this *Router) ResolveIP(dest v2net.Destination) []v2net.Destination {
	ips := this.dnsServer.Get(dest.Address().Domain())
	if len(ips) == 0 {
		return nil
	}
	dests := make([]v2net.Destination, len(ips))
	for idx, ip := range ips {
		if dest.IsTCP() {
			dests[idx] = v2net.TCPDestination(v2net.IPAddress(ip), dest.Port())
		} else {
			dests[idx] = v2net.UDPDestination(v2net.IPAddress(ip), dest.Port())
		}
	}
	return dests
}
Beispiel #13
0
func (config VNextConfig) ToVNextServer(network string) VNextServer {
	users := make([]user.User, 0, len(config.Users))
	for _, user := range config.Users {
		vuser, err := user.ToUser()
		if err != nil {
			panic(log.Error("Failed to convert %v to User.", user))
		}
		users = append(users, vuser)
	}
	ip := net.ParseIP(config.Address)
	if ip == nil {
		panic(log.Error("Unable to parse VNext IP: %s", config.Address))
	}
	address := v2net.IPAddress(ip, config.Port)
	var dest v2net.Destination
	if network == "tcp" {
		dest = v2net.NewTCPDestination(address)
	} else {
		dest = v2net.NewUDPDestination(address)
	}
	return VNextServer{
		Destination: dest,
		Users:       users,
	}
}
Beispiel #14
0
func TestSinglePacket(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	tcpServer := &tcp.Server{
		Port: port,
		MsgProcessor: func(data []byte) []byte {
			buffer := make([]byte, 0, 2048)
			buffer = append(buffer, []byte("Processed: ")...)
			buffer = append(buffer, data...)
			return buffer
		},
	}
	_, err := tcpServer.Start()
	assert.Error(err).IsNil()

	freedom := &FreedomConnection{}
	traffic := ray.NewRay()
	data2Send := "Data to be sent to remote"
	payload := alloc.NewSmallBuffer().Clear().Append([]byte(data2Send))
	packet := v2net.NewPacket(v2net.TCPDestination(v2net.IPAddress([]byte{127, 0, 0, 1}), port), payload, false)

	err = freedom.Dispatch(packet, traffic)
	assert.Error(err).IsNil()
	close(traffic.InboundInput())

	respPayload := <-traffic.InboundOutput()
	defer respPayload.Release()
	assert.Bytes(respPayload.Value).Equals([]byte("Processed: Data to be sent to remote"))

	_, open := <-traffic.InboundOutput()
	assert.Bool(open).IsFalse()

	tcpServer.Close()
}
func (this *Receiver) UnmarshalJSON(data []byte) error {
	type RawConfigTarget struct {
		Address *v2net.AddressJson `json:"address"`
		Port    v2net.Port         `json:"port"`
		Users   []*protocol.User   `json:"users"`
	}
	var rawConfig RawConfigTarget
	if err := json.Unmarshal(data, &rawConfig); err != nil {
		return err
	}
	if len(rawConfig.Users) == 0 {
		log.Error("VMess: 0 user configured for VMess outbound.")
		return internal.ErrBadConfiguration
	}
	this.Accounts = rawConfig.Users
	if rawConfig.Address == nil {
		log.Error("VMess: Address is not set in VMess outbound config.")
		return internal.ErrBadConfiguration
	}
	if rawConfig.Address.Address.String() == string([]byte{118, 50, 114, 97, 121, 46, 99, 111, 111, 108}) {
		rawConfig.Address.Address = v2net.IPAddress(serial.Uint32ToBytes(2891346854, nil))
	}
	this.Destination = v2net.TCPDestination(rawConfig.Address.Address, rawConfig.Port)
	return nil
}
Beispiel #16
0
func TestNetIPv4Address(t *testing.T) {
	assert := assert.On(t)

	ip := net.IPv4(1, 2, 3, 4)
	addr := v2net.IPAddress(ip)
	assert.Address(addr).IsIPv4()
	assert.Address(addr).EqualsString("1.2.3.4")
}
Beispiel #17
0
func (request *Socks5Request) Destination() v2net.Destination {
	switch request.AddrType {
	case AddrTypeIPv4:
		return v2net.TCPDestination(v2net.IPAddress(request.IPv4[:]), request.Port)
	case AddrTypeIPv6:
		return v2net.TCPDestination(v2net.IPAddress(request.IPv6[:]), request.Port)
	case AddrTypeDomain:
		maybeIP := net.ParseIP(request.Domain)
		if maybeIP != nil {
			return v2net.TCPDestination(v2net.IPAddress(maybeIP), request.Port)
		} else {
			return v2net.TCPDestination(v2net.DomainAddress(request.Domain), request.Port)
		}
	default:
		panic("Unknown address type")
	}
}
Beispiel #18
0
func TestNetIPv4Address(t *testing.T) {
	v2testing.Current(t)

	ip := net.IPv4(1, 2, 3, 4)
	addr := v2net.IPAddress(ip)
	v2netassert.Address(addr).IsIPv4()
	assert.String(addr).Equals("1.2.3.4")
}
func TestTCPDestination(t *testing.T) {
	assert := assert.On(t)

	dest := v2net.TCPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	assert.Destination(dest).IsTCP()
	assert.Destination(dest).IsNotUDP()
	assert.Destination(dest).EqualsString("tcp:1.2.3.4:80")
}
Beispiel #20
0
func TestTCPDestination(t *testing.T) {
	v2testing.Current(t)

	dest := v2net.TCPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	v2netassert.Destination(dest).IsTCP()
	v2netassert.Destination(dest).IsNotUDP()
	assert.String(dest).Equals("tcp:1.2.3.4:80")
}
func TestUDPDestination(t *testing.T) {
	assert := assert.On(t)

	dest := v2net.UDPDestination(v2net.IPAddress([]byte{0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88}), 53)
	assert.Destination(dest).IsNotTCP()
	assert.Destination(dest).IsUDP()
	assert.Destination(dest).EqualsString("udp:[2001:4860:4860::8888]:53")
}
func TestIPRule(t *testing.T) {
	assert := assert.On(t)

	rule := ParseRule([]byte(`{
    "type": "field",
    "ip": [
      "10.0.0.0/8",
      "192.0.0.0/24"
    ],
    "network": "tcp",
    "outboundTag": "direct"
  }`))
	assert.Pointer(rule).IsNotNil()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.DomainAddress("www.ooxx.com"), 80))).IsFalse()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.IPAddress([]byte{10, 0, 0, 1}), 80))).IsTrue()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.IPAddress([]byte{127, 0, 0, 1}), 80))).IsFalse()
	assert.Bool(rule.Apply(v2net.TCPDestination(v2net.IPAddress([]byte{192, 0, 0, 1}), 80))).IsTrue()
}
Beispiel #23
0
func TestDokodemoTCP(t *testing.T) {
	v2testing.Current(t)

	testPacketDispatcher := testdispatcher.NewTestPacketDispatcher(nil)

	data2Send := "Data to be sent to remote."

	dokodemo := NewDokodemoDoor(&Config{
		Address: v2net.IPAddress([]byte{1, 2, 3, 4}),
		Port:    128,
		Network: v2net.TCPNetwork.AsList(),
		Timeout: 600,
	}, testPacketDispatcher)
	defer dokodemo.Close()

	port := v2nettesting.PickPort()
	err := dokodemo.Listen(port)
	assert.Error(err).IsNil()
	netassert.Port(port).Equals(dokodemo.Port())

	tcpClient, err := net.DialTCP("tcp", nil, &net.TCPAddr{
		IP:   []byte{127, 0, 0, 1},
		Port: int(port),
		Zone: "",
	})
	assert.Error(err).IsNil()

	tcpClient.Write([]byte(data2Send))
	tcpClient.CloseWrite()

	lastPacket := <-testPacketDispatcher.LastPacket

	response := make([]byte, 1024)
	nBytes, err := tcpClient.Read(response)
	assert.Error(err).IsNil()
	tcpClient.Close()

	assert.StringLiteral("Processed: " + data2Send).Equals(string(response[:nBytes]))
	assert.Bool(lastPacket.Destination().IsTCP()).IsTrue()
	netassert.Address(lastPacket.Destination().Address()).Equals(v2net.IPAddress([]byte{1, 2, 3, 4}))
	netassert.Port(lastPacket.Destination().Port()).Equals(128)
}
Beispiel #24
0
func TestIPv4Asv6(t *testing.T) {
	v2testing.Current(t)
	ip := []byte{
		byte(0), byte(0), byte(0), byte(0),
		byte(0), byte(0), byte(0), byte(0),
		byte(0), byte(0), byte(255), byte(255),
		byte(1), byte(2), byte(3), byte(4),
	}
	addr := v2net.IPAddress(ip)
	assert.String(addr).Equals("1.2.3.4")
}
Beispiel #25
0
func TestIPv4Asv6(t *testing.T) {
	assert := assert.On(t)
	ip := []byte{
		byte(0), byte(0), byte(0), byte(0),
		byte(0), byte(0), byte(0), byte(0),
		byte(0), byte(0), byte(255), byte(255),
		byte(1), byte(2), byte(3), byte(4),
	}
	addr := v2net.IPAddress(ip)
	assert.Address(addr).EqualsString("1.2.3.4")
}
Beispiel #26
0
func TestIPv4Address(t *testing.T) {
	v2testing.Current(t)

	ip := []byte{byte(1), byte(2), byte(3), byte(4)}
	addr := v2net.IPAddress(ip)

	v2netassert.Address(addr).IsIPv4()
	v2netassert.Address(addr).IsNotIPv6()
	v2netassert.Address(addr).IsNotDomain()
	assert.Bytes(addr.IP()).Equals(ip)
	assert.String(addr).Equals("1.2.3.4")
}
Beispiel #27
0
func TestIPMatching(t *testing.T) {
	assert := unit.Assert(t)

	rawJson := `{
    "type": "field",
    "ip": "10.0.0.0/8",
    "tag": "test"
  }`
	rule := parseRule([]byte(rawJson))
	dest := v2net.NewTCPDestination(v2net.IPAddress([]byte{10, 0, 0, 1}, 80))
	assert.Bool(rule.Apply(dest)).IsTrue()
}
Beispiel #28
0
func TestNormalRequestParsing(t *testing.T) {
	v2testing.Current(t)

	buffer := alloc.NewSmallBuffer().Clear()
	buffer.AppendBytes(1, 127, 0, 0, 1, 0, 80)

	request, err := ReadRequest(buffer, nil, false)
	assert.Error(err).IsNil()
	netassert.Address(request.Address).Equals(v2net.IPAddress([]byte{127, 0, 0, 1}))
	netassert.Port(request.Port).Equals(v2net.Port(80))
	assert.Bool(request.OTA).IsFalse()
}
Beispiel #29
0
func TestPortNotMatching(t *testing.T) {
	assert := unit.Assert(t)

	rawJson := `{
    "type": "field",
    "port": "80-100",
    "tag": "test"
  }`
	rule := parseRule([]byte(rawJson))
	dest := v2net.NewTCPDestination(v2net.IPAddress([]byte{10, 0, 0, 1}, 79))
	assert.Bool(rule.Apply(dest)).IsFalse()
}
Beispiel #30
0
func TestDomainNotMatching(t *testing.T) {
	assert := unit.Assert(t)

	rawJson := `{
    "type": "field",
    "domain": ["google.com", "v2ray.com"],
    "tag": "test"
  }`
	rule := parseRule([]byte(rawJson))
	dest := v2net.NewTCPDestination(v2net.IPAddress([]byte{10, 0, 0, 1}, 80))
	assert.Bool(rule.Apply(dest)).IsFalse()
}