func TestPassiveTCPConnection(t *testing.T) {
	assert := assert.On(t)

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

	assert.Error(InitializeServerSetOnce("test_1")).IsNil()

	socksPort := v2net.Port(50002)

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

	authRequest := socks5AuthMethodRequest(byte(0))
	nBytes, err := conn.Write(authRequest)
	assert.Int(nBytes).Equals(len(authRequest))
	assert.Error(err).IsNil()

	authResponse := make([]byte, 1024)
	nBytes, err = conn.Read(authResponse)
	assert.Error(err).IsNil()
	assert.Bytes(authResponse[:nBytes]).Equals([]byte{socks5Version, 0})

	connectRequest := socks5Request(byte(1), v2net.TCPDestination(v2net.IPAddress([]byte{127, 0, 0, 1}), tcpServer.Port))
	nBytes, err = conn.Write(connectRequest)
	assert.Int(nBytes).Equals(len(connectRequest))
	assert.Error(err).IsNil()

	connectResponse := make([]byte, 1024)
	nBytes, err = conn.Read(connectResponse)
	assert.Error(err).IsNil()
	assert.Bytes(connectResponse[:nBytes]).Equals([]byte{socks5Version, 0, 0, 1, 0, 0, 0, 0, 6, 181})

	actualResponse := make([]byte, 1024)
	nResponse, err := conn.Read(actualResponse)
	assert.Error(err).IsNil()

	assert.String(string(actualResponse[:nResponse])).Equals(string(tcpServer.SendFirst))

	conn.Close()

	CloseAllServers()
}
Exemple #2
0
func TestAuthenticationReaderWriterPartial(t *testing.T) {
	assert := assert.On(t)

	key := make([]byte, 16)
	rand.Read(key)
	block, err := aes.NewCipher(key)
	assert.Error(err).IsNil()

	aead, err := cipher.NewGCM(block)
	assert.Error(err).IsNil()

	payload := make([]byte, 8*1024)
	rand.Read(payload)

	cache := buf.NewLocal(16 * 1024)
	iv := make([]byte, 12)
	rand.Read(iv)

	writer := NewAuthenticationWriter(&AEADAuthenticator{
		AEAD: aead,
		NonceGenerator: &StaticBytesGenerator{
			Content: iv,
		},
		AdditionalDataGenerator: &NoOpBytesGenerator{},
	}, cache)

	nBytes, err := writer.Write(payload)
	assert.Error(err).IsNil()
	assert.Int(nBytes).Equals(len(payload))
	assert.Int(cache.Len()).GreaterThan(0)
	_, err = writer.Write([]byte{})
	assert.Error(err).IsNil()

	reader := NewAuthenticationReader(&AEADAuthenticator{
		AEAD: aead,
		NonceGenerator: &StaticBytesGenerator{
			Content: iv,
		},
		AdditionalDataGenerator: &NoOpBytesGenerator{},
	}, cache, false)

	actualPayload := make([]byte, 7*1024)
	nBytes, err = reader.Read(actualPayload)
	assert.Error(err).IsNil()
	assert.Int(nBytes).Equals(len(actualPayload))
	assert.Bytes(actualPayload[:nBytes]).Equals(payload[:nBytes])

	nBytes, err = reader.Read(actualPayload)
	assert.Error(err).IsNil()
	assert.Int(nBytes).Equals(len(payload) - len(actualPayload))
	assert.Bytes(actualPayload[:nBytes]).Equals(payload[7*1024:])

	_, err = reader.Read(actualPayload)
	assert.Error(err).Equals(io.EOF)
}
Exemple #3
0
func TestAuthenticate(t *testing.T) {
	assert := assert.On(t)

	buffer := alloc.NewBuffer().Clear()
	buffer.AppendBytes(1, 2, 3, 4)
	Authenticate(buffer)
	assert.Bytes(buffer.Value).Equals([]byte{0, 8, 87, 52, 168, 125, 1, 2, 3, 4})

	b2, err := NewAuthChunkReader(buffer).Read()
	assert.Error(err).IsNil()
	assert.Bytes(b2.Value).Equals([]byte{1, 2, 3, 4})
}
Exemple #4
0
func TestNormalChunkReading(t *testing.T) {
	assert := assert.On(t)

	buffer := alloc.NewBuffer().Clear().AppendBytes(
		0, 8, 39, 228, 69, 96, 133, 39, 254, 26, 201, 70, 11, 12, 13, 14, 15, 16, 17, 18)
	reader := NewChunkReader(buffer, NewAuthenticator(ChunkKeyGenerator(
		[]byte{21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36})))
	payload, err := reader.Read()
	assert.Error(err).IsNil()
	assert.Bytes(payload.Value).Equals([]byte{11, 12, 13, 14, 15, 16, 17, 18})

	payload.PrependBytes(3, 4)
	assert.Bytes(payload.Value).Equals([]byte{3, 4, 11, 12, 13, 14, 15, 16, 17, 18})
}
Exemple #5
0
func TestBufferPrepend(t *testing.T) {
	assert := assert.On(t)

	buffer := NewBuffer().Clear()
	defer buffer.Release()

	buffer.Append([]byte{'a', 'b', 'c'})
	buffer.Prepend([]byte{'x', 'y', 'z'})

	assert.Int(buffer.Len()).Equals(6)
	assert.Bytes(buffer.Value).Equals([]byte("xyzabc"))

	buffer.Prepend([]byte{'u', 'v', 'w'})
	assert.Bytes(buffer.Value).Equals([]byte("uvwxyzabc"))
}
Exemple #6
0
func TestTCPRequest(t *testing.T) {
	assert := assert.On(t)

	request := &protocol.RequestHeader{
		Version: Version,
		Command: protocol.RequestCommandTCP,
		Address: v2net.LocalHostIP,
		Option:  RequestOptionOneTimeAuth,
		Port:    1234,
		User: &protocol.User{
			Email: "*****@*****.**",
			Account: loader.NewTypedSettings(&Account{
				Password:   "******",
				CipherType: CipherType_CHACHA20,
			}),
		},
	}

	data := alloc.NewLocalBuffer(256).Clear().AppendString("test string")
	cache := alloc.NewBuffer().Clear()

	writer, err := WriteTCPRequest(request, cache)
	assert.Error(err).IsNil()

	writer.Write(data)

	decodedRequest, reader, err := ReadTCPSession(request.User, cache)
	assert.Error(err).IsNil()
	assert.Address(decodedRequest.Address).Equals(request.Address)
	assert.Port(decodedRequest.Port).Equals(request.Port)

	decodedData, err := reader.Read()
	assert.Error(err).IsNil()
	assert.Bytes(decodedData.Value).Equals([]byte("test string"))
}
Exemple #7
0
func TestUDPEncoding(t *testing.T) {
	assert := assert.On(t)

	request := &protocol.RequestHeader{
		Version: Version,
		Command: protocol.RequestCommandUDP,
		Address: v2net.LocalHostIP,
		Port:    1234,
		User: &protocol.User{
			Email: "*****@*****.**",
			Account: loader.NewTypedSettings(&Account{
				Password:   "******",
				CipherType: CipherType_AES_128_CFB,
				Ota:        Account_Disabled,
			}),
		},
	}

	data := alloc.NewLocalBuffer(256).Clear().AppendString("test string")
	encodedData, err := EncodeUDPPacket(request, data)
	assert.Error(err).IsNil()

	decodedRequest, decodedData, err := DecodeUDPPacket(request.User, encodedData)
	assert.Error(err).IsNil()
	assert.Bytes(decodedData.Value).Equals(data.Value)
	assert.Address(decodedRequest.Address).Equals(request.Address)
	assert.Port(decodedRequest.Port).Equals(request.Port)
}
Exemple #8
0
func TestUDPEncoding(t *testing.T) {
	assert := assert.On(t)

	request := &protocol.RequestHeader{
		Version: Version,
		Command: protocol.RequestCommandUDP,
		Address: v2net.LocalHostIP,
		Port:    1234,
		User: &protocol.User{
			Email: "*****@*****.**",
			Account: serial.ToTypedMessage(&Account{
				Password:   "******",
				CipherType: CipherType_AES_128_CFB,
				Ota:        Account_Disabled,
			}),
		},
	}

	data := buf.NewLocal(256)
	data.AppendSupplier(serial.WriteString("test string"))
	encodedData, err := EncodeUDPPacket(request, data)
	assert.Error(err).IsNil()

	decodedRequest, decodedData, err := DecodeUDPPacket(request.User, encodedData)
	assert.Error(err).IsNil()
	assert.Bytes(decodedData.Bytes()).Equals(data.Bytes())
	assert.Address(decodedRequest.Address).Equals(request.Address)
	assert.Port(decodedRequest.Port).Equals(request.Port)
}
Exemple #9
0
func TestShadowsocksServerConfigParsing(t *testing.T) {
	assert := assert.On(t)

	rawJson := `{
    "method": "aes-128-cfb",
    "password": "******"
  }`

	rawConfig := new(ShadowsocksServerConfig)
	err := json.Unmarshal([]byte(rawJson), rawConfig)
	assert.Error(err).IsNil()

	ts, err := rawConfig.Build()
	assert.Error(err).IsNil()
	iConfig, err := ts.GetInstance()
	assert.Error(err).IsNil()
	config := iConfig.(*shadowsocks.ServerConfig)

	rawAccount, err := config.User.GetTypedAccount()
	assert.Error(err).IsNil()

	account, ok := rawAccount.(*shadowsocks.ShadowsocksAccount)
	assert.Bool(ok).IsTrue()

	assert.Int(account.Cipher.KeySize()).Equals(16)
	assert.Bytes(account.Key).Equals([]byte{160, 224, 26, 2, 22, 110, 9, 80, 65, 52, 80, 20, 38, 243, 224, 241})
}
Exemple #10
0
func TestResponseWrite(t *testing.T) {
	assert := assert.On(t)

	response := Socks5Response{
		socksVersion,
		ErrorSuccess,
		AddrTypeIPv4,
		[4]byte{0x72, 0x72, 0x72, 0x72},
		"",
		[16]byte{},
		v2net.Port(53),
	}
	buffer := alloc.NewLocalBuffer(2048).Clear()
	defer buffer.Release()

	response.Write(buffer)
	expectedBytes := []byte{
		socksVersion,
		ErrorSuccess,
		byte(0x00),
		AddrTypeIPv4,
		0x72, 0x72, 0x72, 0x72,
		byte(0x00), byte(0x035),
	}
	assert.Bytes(buffer.Value).Equals(expectedBytes)
}
Exemple #11
0
func Test1ByteDataSegment(t *testing.T) {
	assert := assert.On(t)

	b := buf.NewLocal(512)
	b.AppendBytes('a')
	seg := &DataSegment{
		Conv:        1,
		Timestamp:   3,
		Number:      4,
		SendingNext: 5,
		Data:        b,
	}

	nBytes := seg.ByteSize()
	bytes := make([]byte, nBytes)
	seg.Bytes()(bytes)

	assert.Int(len(bytes)).Equals(nBytes)

	iseg, _ := ReadSegment(bytes)
	seg2 := iseg.(*DataSegment)
	assert.Uint16(seg2.Conv).Equals(seg.Conv)
	assert.Uint32(seg2.Timestamp).Equals(seg.Timestamp)
	assert.Uint32(seg2.SendingNext).Equals(seg.SendingNext)
	assert.Uint32(seg2.Number).Equals(seg.Number)
	assert.Bytes(seg2.Data.Bytes()).Equals(seg.Data.Bytes())
}
Exemple #12
0
func TestAuthenticationResponseWrite(t *testing.T) {
	assert := assert.On(t)

	response := NewAuthenticationResponse(byte(0x05))

	buffer := bytes.NewBuffer(make([]byte, 0, 10))
	WriteAuthentication(buffer, response)
	assert.Bytes(buffer.Bytes()).Equals([]byte{socksVersion, byte(0x05)})
}
Exemple #13
0
func TestIPParsing(t *testing.T) {
	assert := assert.On(t)

	rawJson := "\"8.8.8.8\""
	var address Address
	err := json.Unmarshal([]byte(rawJson), &address)
	assert.Error(err).IsNil()
	assert.Bytes([]byte(address.IP())).Equals([]byte{8, 8, 8, 8})
}
Exemple #14
0
func TestRandom(t *testing.T) {
	assert := assert.On(t)

	uuid := New()
	uuid2 := New()

	assert.String(uuid.String()).NotEquals(uuid2.String())
	assert.Bytes(uuid.Bytes()).NotEquals(uuid2.Bytes())
}
Exemple #15
0
func TestIPv6Request(t *testing.T) {
	assert := assert.On(t)

	request, err := ReadRequest(alloc.NewBuffer().Clear().AppendBytes(5, 1, 0, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0, 8))
	assert.Error(err).IsNil()
	assert.Byte(request.Command).Equals(1)
	assert.Bytes(request.IPv6[:]).Equals([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6})
	assert.Port(request.Port).Equals(8)
}
Exemple #16
0
func TestNewUUID(t *testing.T) {
	assert := assert.On(t)

	uuid := New()
	uuid2, err := ParseString(uuid.String())

	assert.Error(err).IsNil()
	assert.String(uuid.String()).Equals(uuid2.String())
	assert.Bytes(uuid.Bytes()).Equals(uuid2.Bytes())
}
Exemple #17
0
func TestSRTPOpenSeal(t *testing.T) {
	assert := assert.On(t)

	content := []byte{'a', 'b', 'c', 'd', 'e', 'f', 'g'}
	payload := alloc.NewLocalBuffer(2048).Clear().Append(content)
	srtp := SRTP{}
	srtp.Seal(payload)
	assert.Int(payload.Len()).GreaterThan(len(content))
	assert.Bool(srtp.Open(payload)).IsTrue()
	assert.Bytes(content).Equals(payload.Bytes())
}
Exemple #18
0
func TestNormalChunkWriting(t *testing.T) {
	assert := assert.On(t)

	buffer := alloc.NewLocalBuffer(512).Clear()
	writer := NewChunkWriter(buffer, NewAuthenticator(ChunkKeyGenerator(
		[]byte{21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36})))

	err := writer.Write(alloc.NewLocalBuffer(256).Clear().Append([]byte{11, 12, 13, 14, 15, 16, 17, 18}))
	assert.Error(err).IsNil()
	assert.Bytes(buffer.Value).Equals([]byte{0, 8, 39, 228, 69, 96, 133, 39, 254, 26, 201, 70, 11, 12, 13, 14, 15, 16, 17, 18})
}
Exemple #19
0
func TestSocks4AuthenticationResponseToBytes(t *testing.T) {
	assert := assert.On(t)

	response := NewSocks4AuthenticationResponse(byte(0x10), 443, []byte{1, 2, 3, 4})

	buffer := buf.NewLocal(2048)
	defer buffer.Release()

	response.Write(buffer)
	assert.Bytes(buffer.Bytes()).Equals([]byte{0x00, 0x10, 0x01, 0xBB, 0x01, 0x02, 0x03, 0x04})
}
Exemple #20
0
func TestSetDomain(t *testing.T) {
	assert := assert.On(t)

	response := NewSocks5Response()
	response.SetDomain("v2ray.com")

	buffer := alloc.NewLocalBuffer(2048).Clear()
	defer buffer.Release()
	response.Write(buffer)
	assert.Bytes(buffer.Value).Equals([]byte{
		socksVersion, 0, 0, AddrTypeDomain, 9, 118, 50, 114, 97, 121, 46, 99, 111, 109, 0, 0})
}
Exemple #21
0
func TestSetIPv6(t *testing.T) {
	assert := assert.On(t)

	response := NewSocks5Response()
	response.SetIPv6([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15})

	buffer := alloc.NewLocalBuffer(2048).Clear()
	defer buffer.Release()
	response.Write(buffer)
	assert.Bytes(buffer.Value).Equals([]byte{
		socksVersion, 0, 0, AddrTypeIPv6, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 0})
}
Exemple #22
0
func TestIPv4Address(t *testing.T) {
	assert := assert.On(t)

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

	assert.Address(addr).IsIPv4()
	assert.Address(addr).IsNotIPv6()
	assert.Address(addr).IsNotDomain()
	assert.Bytes(addr.IP()).Equals(ip)
	assert.Address(addr).EqualsString("1.2.3.4")
}
Exemple #23
0
func TestSimpleAuthenticator2(t *testing.T) {
	assert := assert.On(t)

	buffer := alloc.NewLocalBuffer(512).Clear()
	buffer.AppendBytes('1', '2')

	auth := NewSimpleAuthenticator()
	auth.Seal(buffer)

	assert.Bool(auth.Open(buffer)).IsTrue()
	assert.Bytes(buffer.Value).Equals([]byte{'1', '2'})
}
Exemple #24
0
func TestProxyDial(t *testing.T) {
	assert := assert.On(t)

	space := app.NewSpace()
	outboundManager := outbound.New()
	outboundManager.SetHandler("tag", freedom.NewFreedomConnection(&freedom.Config{}, space, &proxy.OutboundHandlerMeta{
		Tag: "tag",
		StreamSettings: &internet.StreamConfig{
			Network: v2net.Network_RawTCP,
		},
	}))
	space.BindApp(proxyman.APP_ID_OUTBOUND_MANAGER, outboundManager)

	proxy := NewOutboundProxy(space)
	space.BindApp(APP_ID, proxy)

	assert.Error(space.Initialize()).IsNil()

	xor := func(b []byte) []byte {
		for idx, x := range b {
			b[idx] = x ^ 'c'
		}
		return b
	}
	tcpServer := &tcp.Server{
		MsgProcessor: xor,
	}
	dest, err := tcpServer.Start()
	assert.Error(err).IsNil()

	conn, err := proxy.Dial(v2net.LocalHostIP, dest, internet.DialerOptions{
		Stream: &internet.StreamConfig{
			Network: v2net.Network_RawTCP,
		},
		Proxy: &internet.ProxyConfig{
			Tag: "tag",
		},
	})
	assert.Error(err).IsNil()

	_, err = conn.Write([]byte{'a', 'b', 'c', 'd'})
	assert.Error(err).IsNil()

	b := make([]byte, 10)
	nBytes, err := conn.Read(b)
	assert.Error(err).IsNil()

	assert.Bytes(xor(b[:nBytes])).Equals([]byte{'a', 'b', 'c', 'd'})

	conn.Close()
	tcpServer.Close()
}
Exemple #25
0
func TestReaderWriter(t *testing.T) {
	assert := assert.On(t)

	cache := alloc.NewBuffer()
	writer := NewHeaderWriter(alloc.NewLocalBuffer(256).Clear().AppendString("abcd" + ENDING))
	writer.Write(cache)
	cache.Write([]byte{'e', 'f', 'g'})

	reader := &HeaderReader{}
	buffer, err := reader.Read(cache)
	assert.Error(err).IsNil()
	assert.Bytes(buffer.Value).Equals([]byte{'e', 'f', 'g'})
}
Exemple #26
0
func TestAdaptiveWriter(t *testing.T) {
	assert := assert.On(t)

	lb := alloc.NewLargeBuffer()
	rand.Read(lb.Value)

	writeBuffer := make([]byte, 0, 1024*1024)

	writer := NewAdaptiveWriter(NewBufferedWriter(bytes.NewBuffer(writeBuffer)))
	err := writer.Write(lb)
	assert.Error(err).IsNil()
	assert.Bytes(lb.Bytes()).Equals(writeBuffer)
}
Exemple #27
0
func TestFnvAuth(t *testing.T) {
	assert := assert.On(t)
	fnvAuth := new(FnvAuthenticator)

	expectedText := make([]byte, 256)
	rand.Read(expectedText)

	buffer := make([]byte, 512)
	b := fnvAuth.Seal(buffer[:0], nil, expectedText, nil)
	b, err := fnvAuth.Open(buffer[:0], nil, b, nil)
	assert.Error(err).IsNil()
	assert.Int(len(b)).Equals(256)
	assert.Bytes(b).Equals(expectedText)
}
Exemple #28
0
func TestSingleIO(t *testing.T) {
	assert := assert.On(t)

	content := bytes.NewBuffer(make([]byte, 0, 1024*1024))

	writer := NewAuthChunkWriter(v2io.NewAdaptiveWriter(content))
	writer.Write(alloc.NewBuffer().Clear().AppendString("abcd"))
	writer.Write(alloc.NewBuffer().Clear())
	writer.Release()

	reader := NewAuthChunkReader(content)
	buffer, err := reader.Read()
	assert.Error(err).IsNil()
	assert.Bytes(buffer.Value).Equals([]byte("abcd"))
}
func TestConfigParsing(t *testing.T) {
	assert := assert.On(t)

	rawJson := `{
    "method": "aes-128-cfb",
    "password": "******"
  }`

	config := new(Config)
	err := json.Unmarshal([]byte(rawJson), config)
	assert.Error(err).IsNil()

	assert.Int(config.Cipher.KeySize()).Equals(16)
	assert.Bytes(config.Key).Equals([]byte{160, 224, 26, 2, 22, 110, 9, 80, 65, 52, 80, 20, 38, 243, 224, 241})
}
Exemple #30
0
func TestWriter(t *testing.T) {
	assert := assert.On(t)

	lb := New()
	assert.Error(lb.AppendSupplier(ReadFrom(rand.Reader))).IsNil()

	expectedBytes := append([]byte(nil), lb.Bytes()...)

	writeBuffer := bytes.NewBuffer(make([]byte, 0, 1024*1024))

	writer := NewWriter(bufio.NewWriter(writeBuffer))
	err := writer.Write(lb)
	assert.Error(err).IsNil()
	assert.Bytes(expectedBytes).Equals(writeBuffer.Bytes())
}