Exemple #1
1
func TestHubSocksOption(t *testing.T) {
	assert := assert.On(t)
	if os.Geteuid() != 0 {
		// This test case requires root permission.
		return
	}

	hub, err := ListenUDP(v2net.LocalHostIP, v2net.Port(0), ListenOption{
		Callback:            func(*buf.Buffer, *proxy.SessionInfo) {},
		ReceiveOriginalDest: true,
	})
	assert.Error(err).IsNil()
	conn := hub.Connection()

	fd, err := internal.GetSysFd(conn)
	assert.Error(err).IsNil()

	val, err := syscall.GetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT)
	assert.Error(err).IsNil()
	assert.Int(val).Equals(1)

	val, err = syscall.GetsockoptInt(fd, syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR)
	assert.Error(err).IsNil()
	assert.Int(val).Equals(1)
}
Exemple #2
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 #3
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 #4
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 #5
0
func TestSwitchAccount(t *testing.T) {
	assert := assert.On(t)

	sa := &protocol.CommandSwitchAccount{
		Port:     1234,
		ID:       uuid.New(),
		AlterIds: 1024,
		Level:    128,
		ValidMin: 16,
	}

	buffer := buf.New()
	err := MarshalCommand(sa, buffer)
	assert.Error(err).IsNil()

	cmd, err := UnmarshalCommand(1, buffer.BytesFrom(2))
	assert.Error(err).IsNil()

	sa2, ok := cmd.(*protocol.CommandSwitchAccount)
	assert.Bool(ok).IsTrue()
	assert.Pointer(sa.Host).IsNil()
	assert.Pointer(sa2.Host).IsNil()
	assert.Port(sa.Port).Equals(sa2.Port)
	assert.String(sa.ID.String()).Equals(sa2.ID.String())
	assert.Uint16(sa.AlterIds).Equals(sa2.AlterIds)
	assert.Byte(byte(sa.Level)).Equals(byte(sa2.Level))
	assert.Byte(sa.ValidMin).Equals(sa2.ValidMin)
}
Exemple #6
0
func TestNormalGetRequest(t *testing.T) {
	assert := assert.On(t)

	testPacketDispatcher := testdispatcher.NewTestPacketDispatcher(nil)

	port := v2net.Port(dice.Roll(20000) + 10000)
	httpProxy := NewServer(
		&Config{},
		testPacketDispatcher,
		&proxy.InboundHandlerMeta{
			Address: v2net.LocalHostIP,
			Port:    port,
			StreamSettings: &internet.StreamSettings{
				Type: internet.StreamConnectionTypeRawTCP,
			}})
	defer httpProxy.Close()

	err := httpProxy.Start()
	assert.Error(err).IsNil()
	assert.Port(port).Equals(httpProxy.Port())

	httpClient := &http.Client{}
	resp, err := httpClient.Get("http://127.0.0.1:" + port.String() + "/")
	assert.Error(err).IsNil()
	assert.Int(resp.StatusCode).Equals(400)
}
Exemple #7
0
func TestBufferedReader(t *testing.T) {
	assert := assert.On(t)

	content := buf.New()
	content.AppendSupplier(buf.ReadFrom(rand.Reader))

	len := content.Len()

	reader := NewReader(content)
	assert.Bool(reader.Cached()).IsTrue()

	payload := make([]byte, 16)

	nBytes, err := reader.Read(payload)
	assert.Int(nBytes).Equals(16)
	assert.Error(err).IsNil()

	len2 := content.Len()
	assert.Int(len - len2).GreaterThan(16)

	nBytes, err = reader.Read(payload)
	assert.Int(nBytes).Equals(16)
	assert.Error(err).IsNil()

	assert.Int(content.Len()).Equals(len2)
}
Exemple #8
0
func TestConfigTargetParsing(t *testing.T) {
	assert := assert.On(t)

	rawJson := `{
    "vnext": [{
      "address": "127.0.0.1",
      "port": 80,
      "users": [
        {
          "id": "e641f5ad-9397-41e3-bf1a-e8740dfed019",
          "email": "*****@*****.**",
          "level": 255
        }
      ]
    }]
  }`

	rawConfig := new(VMessOutboundConfig)
	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.(*outbound.Config)
	specPB := config.Receiver[0]
	spec := protocol.NewServerSpecFromPB(*specPB)
	assert.Destination(spec.Destination()).EqualsString("tcp:127.0.0.1:80")
}
Exemple #9
0
func TestSimpleRouter(t *testing.T) {
	assert := assert.On(t)

	config := &Config{
		Rule: []*RoutingRule{
			{
				Tag: "test",
				NetworkList: &v2net.NetworkList{
					Network: []v2net.Network{v2net.Network_TCP},
				},
			},
		},
	}

	space := app.NewSpace()
	space.BindApp(dns.APP_ID, dns.NewCacheServer(space, &dns.Config{}))
	space.BindApp(dispatcher.APP_ID, dispatchers.NewDefaultDispatcher(space))
	space.BindApp(proxyman.APP_ID_OUTBOUND_MANAGER, proxyman.NewDefaultOutboundHandlerManager())
	r := NewRouter(config, space)
	space.BindApp(APP_ID, r)
	assert.Error(space.Initialize()).IsNil()

	tag, err := r.TakeDetour(&proxy.SessionInfo{Destination: v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), 80)})
	assert.Error(err).IsNil()
	assert.String(tag).Equals("test")
}
Exemple #10
0
func TestSocksInboundConfig(t *testing.T) {
	assert := assert.On(t)

	rawJson := `{
    "auth": "password",
    "accounts": [
      {
        "user": "******",
        "pass": "******"
      }
    ],
    "udp": false,
    "ip": "127.0.0.1",
    "timeout": 5
  }`

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

	message, err := config.Build()
	assert.Error(err).IsNil()

	iConfig, err := message.GetInstance()
	assert.Error(err).IsNil()

	socksConfig := iConfig.(*socks.ServerConfig)
	assert.Bool(socksConfig.AuthType == socks.AuthType_PASSWORD).IsTrue()
	assert.Int(len(socksConfig.Accounts)).Equals(1)
	assert.String(socksConfig.Accounts["my-username"]).Equals("my-password")
	assert.Bool(socksConfig.UdpEnabled).IsFalse()
	assert.Address(socksConfig.Address.AsAddress()).Equals(net.LocalHostIP)
	assert.Uint32(socksConfig.Timeout).Equals(5)
}
Exemple #11
0
func TestHttpProxy(t *testing.T) {
	assert := assert.On(t)

	httpServer := &v2http.Server{
		Port:        v2net.Port(50042),
		PathHandler: make(map[string]http.HandlerFunc),
	}
	_, err := httpServer.Start()
	assert.Error(err).IsNil()
	defer httpServer.Close()

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

	transport := &http.Transport{
		Proxy: func(req *http.Request) (*url.URL, error) {
			return url.Parse("http://127.0.0.1:50040/")
		},
	}

	client := &http.Client{
		Transport: transport,
	}

	resp, err := client.Get("http://127.0.0.1:50042/")
	assert.Error(err).IsNil()
	assert.Int(resp.StatusCode).Equals(200)

	content, err := ioutil.ReadAll(resp.Body)
	assert.Error(err).IsNil()
	assert.String(string(content)).Equals("Home")

	CloseAllServers()
}
func TestBufferedReader(t *testing.T) {
	assert := assert.On(t)

	content := alloc.NewLargeBuffer()
	len := content.Len()

	reader := NewBufferedReader(content)
	assert.Bool(reader.Cached()).IsTrue()

	payload := make([]byte, 16)

	nBytes, err := reader.Read(payload)
	assert.Int(nBytes).Equals(16)
	assert.Error(err).IsNil()

	len2 := content.Len()
	assert.Int(len - len2).GreaterThan(16)

	nBytes, err = reader.Read(payload)
	assert.Int(nBytes).Equals(16)
	assert.Error(err).IsNil()

	assert.Int(content.Len()).Equals(len2)
	reader.SetCached(false)

	payload2 := alloc.NewBuffer()
	reader.Read(payload2.Value)

	assert.Int(content.Len()).Equals(len2)

	reader.Read(payload2.Value)
	assert.Int(content.Len()).LessThan(len2)
}
Exemple #13
0
func TestBlockHTTP(t *testing.T) {
	assert := assert.On(t)

	httpServer := &v2http.Server{
		Port:        net.Port(50042),
		PathHandler: make(map[string]http.HandlerFunc),
	}
	_, err := httpServer.Start()
	assert.Error(err).IsNil()
	defer httpServer.Close()

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

	transport := &http.Transport{
		Proxy: func(req *http.Request) (*url.URL, error) {
			return url.Parse("http://127.0.0.1:50040/")
		},
	}

	client := &http.Client{
		Transport: transport,
	}

	resp, err := client.Get("http://127.0.0.1:50049/")
	assert.Error(err).IsNil()
	assert.Int(resp.StatusCode).Equals(403)

	CloseAllServers()
}
Exemple #14
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 #15
0
func TestShadowsocksTCP(t *testing.T) {
	assert := assert.On(t)

	tcpServer := &tcp.Server{
		Port: v2net.Port(50052),
		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()
	defer tcpServer.Close()

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

	for i := 0; i < 1; i++ {
		conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
			IP:   []byte{127, 0, 0, 1},
			Port: 50050,
		})
		assert.Error(err).IsNil()

		payload := "dokodemo request."
		nBytes, err := conn.Write([]byte(payload))
		assert.Error(err).IsNil()
		assert.Int(nBytes).Equals(len(payload))

		//conn.CloseWrite()

		response := buf.New()
		finished := false
		expectedResponse := "Processed: " + payload
		for {
			err := response.AppendSupplier(buf.ReadFrom(conn))
			assert.Error(err).IsNil()
			if err != nil {
				break
			}
			if response.String() == expectedResponse {
				finished = true
				break
			}
			if response.Len() > len(expectedResponse) {
				fmt.Printf("Unexpected response: %v\n", response.Bytes())
				break
			}
		}
		assert.Bool(finished).IsTrue()

		conn.Close()
	}

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

	var portRange PortRange
	err := json.Unmarshal([]byte("70000"), &portRange)
	assert.Error(err).Equals(v2net.ErrInvalidPortRange)

	err = json.Unmarshal([]byte("-1"), &portRange)
	assert.Error(err).Equals(v2net.ErrInvalidPortRange)
}
Exemple #17
0
func TestBufferWrite(t *testing.T) {
	assert := assert.On(t)

	buffer := NewLocal(8)
	nBytes, err := buffer.Write([]byte("abcd"))
	assert.Error(err).IsNil()
	assert.Int(nBytes).Equals(4)
	nBytes, err = buffer.Write([]byte("abcde"))
	assert.Error(err).IsNil()
	assert.Int(nBytes).Equals(4)
	assert.String(buffer.String()).Equals("abcdabcd")
}
Exemple #18
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 #19
0
func TestParseBytes(t *testing.T) {
	assert := assert.On(t)

	str := "2418d087-648d-4990-86e8-19dca1d006d3"
	bytes := []byte{0x24, 0x18, 0xd0, 0x87, 0x64, 0x8d, 0x49, 0x90, 0x86, 0xe8, 0x19, 0xdc, 0xa1, 0xd0, 0x06, 0xd3}

	uuid, err := ParseBytes(bytes)
	assert.Error(err).IsNil()
	assert.String(uuid.String()).Equals(str)

	_, err = ParseBytes([]byte{1, 3, 2, 4})
	assert.Error(err).Equals(ErrInvalidID)
}
Exemple #20
0
func TestDialDomain(t *testing.T) {
	assert := assert.On(t)

	server := &tcp.Server{}
	dest, err := server.Start()
	assert.Error(err).IsNil()
	defer server.Close()

	conn, err := DialToDest(nil, v2net.TCPDestination(v2net.DomainAddress("local.v2ray.com"), dest.Port))
	assert.Error(err).IsNil()
	assert.String(conn.RemoteAddr().String()).Equals("127.0.0.1:" + dest.Port.String())
	conn.Close()
}
Exemple #21
0
func TestDialWithLocalAddr(t *testing.T) {
	assert := assert.On(t)

	server := &tcp.Server{}
	dest, err := server.Start()
	assert.Error(err).IsNil()
	defer server.Close()

	conn, err := DialToDest(v2net.LocalHostIP, v2net.TCPDestination(v2net.LocalHostIP, dest.Port))
	assert.Error(err).IsNil()
	assert.String(conn.RemoteAddr().String()).Equals("127.0.0.1:" + dest.Port.String())
	conn.Close()
}
func TestAllAuthenticatorLoadable(t *testing.T) {
	assert := assert.On(t)

	noopAuth, err := CreateAuthenticator("none", nil)
	assert.Error(err).IsNil()
	assert.Int(noopAuth.Overhead()).Equals(0)

	srtp, err := CreateAuthenticator("srtp", nil)
	assert.Error(err).IsNil()
	assert.Int(srtp.Overhead()).Equals(4)

	utp, err := CreateAuthenticator("utp", nil)
	assert.Error(err).IsNil()
	assert.Int(utp.Overhead()).Equals(4)
}
Exemple #23
0
func TestAllHeadersLoadable(t *testing.T) {
	assert := assert.On(t)

	noopAuth, err := CreatePacketHeader(serial.GetMessageType(new(noop.Config)), nil)
	assert.Error(err).IsNil()
	assert.Int(noopAuth.Size()).Equals(0)

	srtp, err := CreatePacketHeader(serial.GetMessageType(new(srtp.Config)), nil)
	assert.Error(err).IsNil()
	assert.Int(srtp.Size()).Equals(4)

	utp, err := CreatePacketHeader(serial.GetMessageType(new(utp.Config)), nil)
	assert.Error(err).IsNil()
	assert.Int(utp.Size()).Equals(4)
}
func TestAllAuthenticatorLoadable(t *testing.T) {
	assert := assert.On(t)

	noopAuth, err := CreateAuthenticator(loader.GetType(new(noop.Config)), nil)
	assert.Error(err).IsNil()
	assert.Int(noopAuth.Overhead()).Equals(0)

	srtp, err := CreateAuthenticator(loader.GetType(new(srtp.Config)), nil)
	assert.Error(err).IsNil()
	assert.Int(srtp.Overhead()).Equals(4)

	utp, err := CreateAuthenticator(loader.GetType(new(utp.Config)), nil)
	assert.Error(err).IsNil()
	assert.Int(utp.Overhead()).Equals(4)
}
Exemple #25
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())
}
Exemple #26
0
func TestAllHeadersLoadable(t *testing.T) {
	assert := assert.On(t)

	noopAuth, err := CreatePacketHeader((*noop.Config)(nil))
	assert.Error(err).IsNil()
	assert.Int(noopAuth.Size()).Equals(0)

	srtp, err := CreatePacketHeader((*srtp.Config)(nil))
	assert.Error(err).IsNil()
	assert.Int(srtp.Size()).Equals(4)

	utp, err := CreatePacketHeader((*utp.Config)(nil))
	assert.Error(err).IsNil()
	assert.Int(utp.Size()).Equals(4)
}
Exemple #27
0
func TestInvalidNetworkJson(t *testing.T) {
	assert := assert.On(t)

	var list NetworkList
	err := json.Unmarshal([]byte("0"), &list)
	assert.Error(err).IsNotNil()
}
Exemple #28
0
func TestInvalidUserJson(t *testing.T) {
	assert := assert.On(t)

	user := new(User)
	err := json.Unmarshal([]byte(`{"email": 1234}`), user)
	assert.Error(err).IsNotNil()
}
Exemple #29
0
func TestOverRangeStringPort(t *testing.T) {
	assert := assert.On(t)

	var portRange PortRange
	err := json.Unmarshal([]byte("\"65536\""), &portRange)
	assert.Error(err).Equals(v2net.ErrInvalidPortRange)

	err = json.Unmarshal([]byte("\"70000-80000\""), &portRange)
	assert.Error(err).Equals(v2net.ErrInvalidPortRange)

	err = json.Unmarshal([]byte("\"1-90000\""), &portRange)
	assert.Error(err).Equals(v2net.ErrInvalidPortRange)

	err = json.Unmarshal([]byte("\"700-600\""), &portRange)
	assert.Error(err).Equals(v2net.ErrInvalidPortRange)
}
Exemple #30
0
func TestWrongProtocolVersion(t *testing.T) {
	assert := assert.On(t)

	buffer := alloc.NewBuffer().Clear().AppendBytes(6, 1, 0)
	_, _, err := ReadAuthentication(buffer)
	assert.Error(err).Equals(proxy.ErrInvalidProtocolVersion)
}