Beispiel #1
0
func TestReceiverUser(t *testing.T) {
	assert := assert.On(t)

	id := protocol.NewID(uuid.New())
	alters := protocol.NewAlterIDs(id, 100)
	account := &protocol.VMessAccount{
		ID:       id,
		AlterIDs: alters,
	}
	user := protocol.NewUser(account, protocol.UserLevel(0), "")
	rec := NewReceiver(v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), 80), user)
	assert.Bool(rec.HasUser(user)).IsTrue()
	assert.Int(len(rec.Accounts)).Equals(1)

	id2 := protocol.NewID(uuid.New())
	alters2 := protocol.NewAlterIDs(id2, 100)
	account2 := &protocol.VMessAccount{
		ID:       id2,
		AlterIDs: alters2,
	}
	user2 := protocol.NewUser(account2, protocol.UserLevel(0), "")
	assert.Bool(rec.HasUser(user2)).IsFalse()

	rec.AddUser(user2)
	assert.Bool(rec.HasUser(user2)).IsTrue()
	assert.Int(len(rec.Accounts)).Equals(2)
}
Beispiel #2
0
func TestRequestSerialization(t *testing.T) {
	v2testing.Current(t)

	user := protocol.NewUser(
		protocol.NewID(uuid.New()),
		protocol.UserLevelUntrusted,
		0,
		"*****@*****.**")

	expectedRequest := &protocol.RequestHeader{
		Version: 1,
		User:    user,
		Command: protocol.RequestCommandTCP,
		Option:  protocol.RequestOption(0),
		Address: v2net.DomainAddress("www.v2ray.com"),
		Port:    v2net.Port(443),
	}

	buffer := alloc.NewBuffer().Clear()
	client := NewClientSession(protocol.DefaultIDHash)
	client.EncodeRequestHeader(expectedRequest, buffer)

	userValidator := protocol.NewTimedUserValidator(protocol.DefaultIDHash)
	userValidator.Add(user)

	server := NewServerSession(userValidator)
	actualRequest, err := server.DecodeRequestHeader(buffer)
	assert.Error(err).IsNil()

	assert.Byte(expectedRequest.Version).Equals(actualRequest.Version)
	assert.Byte(byte(expectedRequest.Command)).Equals(byte(actualRequest.Command))
	assert.Byte(byte(expectedRequest.Option)).Equals(byte(actualRequest.Option))
	netassert.Address(expectedRequest.Address).Equals(actualRequest.Address)
	netassert.Port(expectedRequest.Port).Equals(actualRequest.Port)
}
Beispiel #3
0
func BenchmarkVMessRequestWriting(b *testing.B) {
	id, err := uuid.ParseString("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")
	assert.Error(err).IsNil()

	userId := proto.NewID(id)
	userSet := protocoltesting.MockUserSet{[]*proto.User{}, make(map[string]int), make(map[string]Timestamp)}

	testUser := &proto.User{
		ID: userId,
	}
	userSet.AddUser(testUser)

	request := new(VMessRequest)
	request.Version = byte(0x01)
	request.User = testUser

	randBytes := make([]byte, 36)
	rand.Read(randBytes)
	request.RequestIV = randBytes[:16]
	request.RequestKey = randBytes[16:32]
	request.ResponseHeader = randBytes[32]

	request.Command = byte(0x01)
	request.Address = v2net.DomainAddress("v2ray.com")
	request.Port = v2net.Port(80)

	for i := 0; i < b.N; i++ {
		request.ToBytes(NewRandomTimestampGenerator(Timestamp(time.Now().Unix()), 30), nil)
	}
}
Beispiel #4
0
func TestReceiverUser(t *testing.T) {
	v2testing.Current(t)

	id := proto.NewID(uuid.New())
	user := proto.NewUser(id, proto.UserLevel(0), 100, "")
	rec := NewReceiver(v2net.TCPDestination(v2net.DomainAddress("v2ray.com"), 80), user)
	assert.Bool(rec.HasUser(user)).IsTrue()
	assert.Int(len(rec.Accounts)).Equals(1)

	id2 := proto.NewID(uuid.New())
	user2 := proto.NewUser(id2, proto.UserLevel(0), 100, "")
	assert.Bool(rec.HasUser(user2)).IsFalse()

	rec.AddUser(user2)
	assert.Bool(rec.HasUser(user2)).IsTrue()
	assert.Int(len(rec.Accounts)).Equals(2)
}
Beispiel #5
0
func TestVMessSerialization(t *testing.T) {
	v2testing.Current(t)

	id, err := uuid.ParseString("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")
	assert.Error(err).IsNil()

	userId := proto.NewID(id)

	testUser := &proto.User{
		ID: userId,
	}

	userSet := protocoltesting.MockUserSet{[]*proto.User{}, make(map[string]int), make(map[string]Timestamp)}
	userSet.AddUser(testUser)

	request := new(VMessRequest)
	request.Version = byte(0x01)
	request.User = testUser

	randBytes := make([]byte, 36)
	_, err = rand.Read(randBytes)
	assert.Error(err).IsNil()
	request.RequestIV = randBytes[:16]
	request.RequestKey = randBytes[16:32]
	request.ResponseHeader = randBytes[32]

	request.Command = byte(0x01)
	request.Address = v2net.DomainAddress("v2ray.com")
	request.Port = v2net.Port(80)

	mockTime := Timestamp(1823730)

	buffer, err := request.ToBytes(&FakeTimestampGenerator{timestamp: mockTime}, nil)
	if err != nil {
		t.Fatal(err)
	}

	userSet.UserHashes[string(buffer.Value[:16])] = 0
	userSet.Timestamps[string(buffer.Value[:16])] = mockTime

	requestReader := NewVMessRequestReader(&userSet)
	actualRequest, err := requestReader.Read(bytes.NewReader(buffer.Value))
	if err != nil {
		t.Fatal(err)
	}

	assert.Byte(actualRequest.Version).Named("Version").Equals(byte(0x01))
	assert.String(actualRequest.User.ID).Named("UserId").Equals(request.User.ID.String())
	assert.Bytes(actualRequest.RequestIV).Named("RequestIV").Equals(request.RequestIV[:])
	assert.Bytes(actualRequest.RequestKey).Named("RequestKey").Equals(request.RequestKey[:])
	assert.Byte(actualRequest.ResponseHeader).Named("ResponseHeader").Equals(request.ResponseHeader)
	assert.Byte(actualRequest.Command).Named("Command").Equals(request.Command)
	assert.String(actualRequest.Address).Named("Address").Equals(request.Address.String())
}
Beispiel #6
0
func (this *VMessOutboundHandler) handleSwitchAccount(cmd *protocol.CommandSwitchAccount) {
	primary := protocol.NewID(cmd.ID)
	alters := protocol.NewAlterIDs(primary, cmd.AlterIds)
	account := &protocol.VMessAccount{
		ID:       primary,
		AlterIDs: alters,
	}
	user := protocol.NewUser(account, cmd.Level, "")
	dest := v2net.TCPDestination(cmd.Host, cmd.Port)
	this.receiverManager.AddDetour(NewReceiver(dest, user), cmd.ValidMin)
}
Beispiel #7
0
func (this *VMessOutboundHandler) handleSwitchAccount(cmd *protocol.CommandSwitchAccount) {
	primary := protocol.NewID(cmd.ID)
	alters := protocol.NewAlterIDs(primary, cmd.AlterIds)
	account := &vmess.Account{
		ID:       primary,
		AlterIDs: alters,
	}
	user := protocol.NewUser(cmd.Level, "")
	user.Account = account
	dest := v2net.TCPDestination(cmd.Host, cmd.Port)
	until := time.Now().Add(time.Duration(cmd.ValidMin) * time.Minute)
	this.serverList.AddServer(protocol.NewServerSpec(dest, protocol.BeforeTime(until), user))
}
Beispiel #8
0
func (this *userByEmail) Get(email string) (*proto.User, bool) {
	var user *proto.User
	var found bool
	this.RLock()
	user, found = this.cache[email]
	this.RUnlock()
	if !found {
		this.Lock()
		user, found = this.cache[email]
		if !found {
			id := proto.NewID(uuid.New())
			user = proto.NewUser(id, this.defaultLevel, this.defaultAlterIDs, email)
			this.cache[email] = user
		}
		this.Unlock()
	}
	return user, found
}
Beispiel #9
0
func (u *Account) UnmarshalJSON(data []byte) error {
	type JsonConfig struct {
		ID       string `json:"id"`
		AlterIds uint16 `json:"alterId"`
	}
	var rawConfig JsonConfig
	if err := json.Unmarshal(data, &rawConfig); err != nil {
		return err
	}
	id, err := uuid.ParseString(rawConfig.ID)
	if err != nil {
		log.Error("VMess: Failed to parse ID: ", err)
		return err
	}
	u.ID = protocol.NewID(id)
	u.AlterIDs = protocol.NewAlterIDs(u.ID, rawConfig.AlterIds)

	return nil
}
Beispiel #10
0
func (this *userByEmail) Get(email string) (*protocol.User, bool) {
	var user *protocol.User
	var found bool
	this.RLock()
	user, found = this.cache[email]
	this.RUnlock()
	if !found {
		this.Lock()
		user, found = this.cache[email]
		if !found {
			id := protocol.NewID(uuid.New())
			alterIDs := protocol.NewAlterIDs(id, this.defaultAlterIDs)
			account := &protocol.VMessAccount{
				ID:       id,
				AlterIDs: alterIDs,
			}
			user = protocol.NewUser(account, this.defaultLevel, email)
			this.cache[email] = user
		}
		this.Unlock()
	}
	return user, found
}
Beispiel #11
0
func TestVMessInAndOut(t *testing.T) {
	v2testing.Current(t)

	id, err := uuid.ParseString("ad937d9d-6e23-4a5a-ba23-bce5092a7c51")
	assert.Error(err).IsNil()

	testAccount := proto.NewID(id)

	portA := v2nettesting.PickPort()
	portB := v2nettesting.PickPort()

	ichConnInput := []byte("The data to be send to outbound server.")
	ichConnOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	ich := &proxymocks.InboundConnectionHandler{
		ConnInput:  bytes.NewReader(ichConnInput),
		ConnOutput: ichConnOutput,
	}

	protocol, err := proxytesting.RegisterInboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (proxy.InboundHandler, error) {
		ich.PacketDispatcher = space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
		return ich, nil
	})
	assert.Error(err).IsNil()

	configA := &point.Config{
		Port: portA,
		InboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: "vmess",
			Settings: []byte(`{
        "vnext": [
          {
            "address": "127.0.0.1",
            "port": ` + portB.String() + `,
            "users": [
              {"id": "` + testAccount.String() + `"}
            ]
          }
        ]
      }`),
		},
	}

	pointA, err := point.NewPoint(configA)
	assert.Error(err).IsNil()

	err = pointA.Start()
	assert.Error(err).IsNil()

	ochConnInput := []byte("The data to be returned to inbound server.")
	ochConnOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(ochConnInput),
		ConnOutput: ochConnOutput,
	}

	protocol, err = proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	configB := &point.Config{
		Port: portB,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "vmess",
			Settings: []byte(`{
        "clients": [
          {"id": "` + testAccount.String() + `"}
        ]
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	pointB, err := point.NewPoint(configB)
	assert.Error(err).IsNil()

	err = pointB.Start()
	assert.Error(err).IsNil()

	dest := v2net.TCPDestination(v2net.IPAddress([]byte{1, 2, 3, 4}), 80)
	ich.Communicate(v2net.NewPacket(dest, nil, true))
	assert.Bytes(ichConnInput).Equals(ochConnOutput.Bytes())
	assert.Bytes(ichConnOutput.Bytes()).Equals(ochConnInput)
}
Beispiel #12
0
func (this *VMessOutboundHandler) handleSwitchAccount(cmd *command.SwitchAccount) {
	user := proto.NewUser(proto.NewID(cmd.ID), cmd.Level, cmd.AlterIds.Value())
	dest := v2net.TCPDestination(cmd.Host, cmd.Port)
	this.receiverManager.AddDetour(NewReceiver(dest, user), cmd.ValidMin)
}
Beispiel #13
0
func (us *StaticUserSet) GetUser(userhash []byte) (*proto.User, protocol.Timestamp, bool) {
	id, _ := uuid.ParseString("703e9102-eb57-499c-8b59-faf4f371bb21")
	return &proto.User{
		ID: proto.NewID(id),
	}, 0, true
}