Bladeren bron

feat(vpn): allocate client ip addresses dynamically and statically

Closes #17.
Mustafa Arici 8 jaren geleden
bovenliggende
commit
ae162139cc
6 gewijzigde bestanden met toevoegingen van 233 en 43 verwijderingen
  1. 7 2
      api/rpc.go
  2. 44 2
      cmd/ovpm/main.go
  3. 15 1
      net.go
  4. 55 30
      pb/user.pb.go
  5. 3 0
      pb/user.proto
  6. 109 8
      user.go

+ 7 - 2
api/rpc.go

@@ -29,6 +29,7 @@ func (s *UserService) List(ctx context.Context, req *pb.UserListRequest) (*pb.Us
 			CreatedAt:          user.GetCreatedAt(),
 			IPNet:              user.GetIPNet(),
 			NoGW:               user.IsNoGW(),
+			HostID:             user.GetHostID(),
 		})
 	}
 
@@ -38,7 +39,7 @@ func (s *UserService) List(ctx context.Context, req *pb.UserListRequest) (*pb.Us
 func (s *UserService) Create(ctx context.Context, req *pb.UserCreateRequest) (*pb.UserResponse, error) {
 	logrus.Debugf("rpc call: user create: %s", req.Username)
 	var ut []*pb.UserResponse_User
-	user, err := ovpm.CreateNewUser(req.Username, req.Password, req.NoGW)
+	user, err := ovpm.CreateNewUser(req.Username, req.Password, req.NoGW, req.HostID)
 	if err != nil {
 		return nil, err
 	}
@@ -47,6 +48,7 @@ func (s *UserService) Create(ctx context.Context, req *pb.UserCreateRequest) (*p
 		Username:           user.GetUsername(),
 		ServerSerialNumber: user.GetServerSerialNumber(),
 		NoGW:               user.IsNoGW(),
+		HostID:             user.GetHostID(),
 	}
 	ut = append(ut, &pbUser)
 
@@ -72,11 +74,12 @@ func (s *UserService) Update(ctx context.Context, req *pb.UserUpdateRequest) (*p
 
 	}
 
-	user.Update(req.Password, noGW)
+	user.Update(req.Password, noGW, req.HostID)
 	pbUser := pb.UserResponse_User{
 		Username:           user.GetUsername(),
 		ServerSerialNumber: user.GetServerSerialNumber(),
 		NoGW:               user.IsNoGW(),
+		HostID:             user.GetHostID(),
 	}
 
 	ut = append(ut, &pbUser)
@@ -95,6 +98,7 @@ func (s *UserService) Delete(ctx context.Context, req *pb.UserDeleteRequest) (*p
 	pbUser := pb.UserResponse_User{
 		Username:           user.GetUsername(),
 		ServerSerialNumber: user.GetServerSerialNumber(),
+		HostID:             user.GetHostID(),
 	}
 	ut = append(ut, &pbUser)
 
@@ -117,6 +121,7 @@ func (s *UserService) Renew(ctx context.Context, req *pb.UserRenewRequest) (*pb.
 	pbUser := pb.UserResponse_User{
 		Username:           user.GetUsername(),
 		ServerSerialNumber: user.GetServerSerialNumber(),
+		HostID:             user.GetHostID(),
 	}
 	ut = append(ut, &pbUser)
 

+ 44 - 2
cmd/ovpm/main.go

@@ -3,6 +3,7 @@ package main
 import (
 	"context"
 	"fmt"
+	"net"
 	"os"
 
 	"github.com/Sirupsen/logrus"
@@ -69,7 +70,11 @@ func main() {
 						table.SetHeader([]string{"#", "username", "ip", "created at", "valid crt", "no gw"})
 						//table.SetBorder(false)
 						for i, user := range resp.Users {
-							data := []string{fmt.Sprintf("%v", i+1), user.Username, user.IPNet, user.CreatedAt, fmt.Sprintf("%t", user.ServerSerialNumber == server.SerialNumber), fmt.Sprintf("%t", user.NoGW)}
+							static := ""
+							if user.HostID != 0 {
+								static = "s"
+							}
+							data := []string{fmt.Sprintf("%v", i+1), user.Username, fmt.Sprintf("%s %s", user.IPNet, static), user.CreatedAt, fmt.Sprintf("%t", user.ServerSerialNumber == server.SerialNumber), fmt.Sprintf("%t", user.NoGW)}
 							table.Append(data)
 						}
 						table.Render()
@@ -93,24 +98,42 @@ func main() {
 							Name:  "no-gw",
 							Usage: "don't push vpn server as default gateway for this user",
 						},
+						cli.StringFlag{
+							Name:  "static",
+							Usage: "ip address for the vpn user",
+						},
 					},
 					Action: func(c *cli.Context) error {
 						action = "user:create"
 						username := c.String("username")
 						password := c.String("password")
 						noGW := c.Bool("no-gw")
+						static := c.String("static")
 
 						if username == "" || password == "" {
 							fmt.Println(cli.ShowSubcommandHelp(c))
 							os.Exit(1)
 						}
 
+						var hostid uint32
+						if static != "" {
+							h := ovpm.IP2HostID(net.ParseIP(static).To4())
+							if h == 0 {
+								fmt.Println("--static flag takes a valid ipv4 address")
+								fmt.Println()
+								fmt.Println(cli.ShowSubcommandHelp(c))
+								os.Exit(1)
+							}
+
+							hostid = h
+						}
+
 						//conn := getConn(c.String("port"))
 						conn := getConn(c.GlobalString("daemon-port"))
 						defer conn.Close()
 						userSvc := pb.NewUserServiceClient(conn)
 
-						response, err := userSvc.Create(context.Background(), &pb.UserCreateRequest{Username: username, Password: password, NoGW: noGW})
+						response, err := userSvc.Create(context.Background(), &pb.UserCreateRequest{Username: username, Password: password, NoGW: noGW, HostID: hostid})
 						if err != nil {
 							logrus.Errorf("user can not be created '%s': %v", username, err)
 							os.Exit(1)
@@ -140,6 +163,10 @@ func main() {
 							Name:  "gw",
 							Usage: "push vpn server as default gateway for this user",
 						},
+						cli.StringFlag{
+							Name:  "static",
+							Usage: "ip address for the vpn user",
+						},
 					},
 					Action: func(c *cli.Context) error {
 						action = "user:update"
@@ -147,6 +174,7 @@ func main() {
 						password := c.String("password")
 						nogw := c.Bool("no-gw")
 						gw := c.Bool("gw")
+						static := c.String("static")
 
 						if username == "" {
 							fmt.Println(cli.ShowSubcommandHelp(c))
@@ -160,6 +188,19 @@ func main() {
 							os.Exit(1)
 						}
 
+						var hostid uint32
+						if static != "" {
+							h := ovpm.IP2HostID(net.ParseIP(static).To4())
+							if h == 0 {
+								fmt.Println("--static flag takes a valid ipv4 address")
+								fmt.Println()
+								fmt.Println(cli.ShowSubcommandHelp(c))
+								os.Exit(1)
+							}
+
+							hostid = h
+						}
+
 						var gwPref pb.UserUpdateRequest_GWPref
 
 						switch {
@@ -187,6 +228,7 @@ func main() {
 							Username: username,
 							Password: password,
 							Gwpref:   gwPref,
+							HostID:   hostid,
 						})
 
 						if err != nil {

+ 15 - 1
net.go

@@ -1,12 +1,14 @@
 package ovpm
 
 import (
+	"encoding/binary"
 	"fmt"
 	"net"
 
+	"time"
+
 	"github.com/Sirupsen/logrus"
 	"github.com/coreos/go-iptables/iptables"
-	"time"
 )
 
 // routedInterface returns a network interface that can route IP
@@ -156,4 +158,16 @@ func enableNat() error {
 	ipt.AppendUnique("filter", "FORWARD", "-i", rif.Name, "-o", vpnIfc.Name, "-m", "state", "--state", "RELATED, ESTABLISHED", "-j", "ACCEPT")
 	ipt.AppendUnique("filter", "FORWARD", "-i", vpnIfc.Name, "-o", rif.Name, "-j", "ACCEPT")
 	return nil
+
+}
+
+func HostID2IP(hostid uint32) net.IP {
+	ip := make([]byte, 4)
+	binary.BigEndian.PutUint32(ip, hostid)
+	return net.IP(ip)
+}
+
+func IP2HostID(ip net.IP) uint32 {
+	hostid := binary.BigEndian.Uint32(ip)
+	return hostid
 }

+ 55 - 30
pb/user.pb.go

@@ -80,6 +80,7 @@ type UserCreateRequest struct {
 	Username string `protobuf:"bytes,1,opt,name=Username" json:"Username,omitempty"`
 	Password string `protobuf:"bytes,2,opt,name=Password" json:"Password,omitempty"`
 	NoGW     bool   `protobuf:"varint,3,opt,name=NoGW" json:"NoGW,omitempty"`
+	HostID   uint32 `protobuf:"varint,4,opt,name=HostID" json:"HostID,omitempty"`
 }
 
 func (m *UserCreateRequest) Reset()                    { *m = UserCreateRequest{} }
@@ -108,10 +109,18 @@ func (m *UserCreateRequest) GetNoGW() bool {
 	return false
 }
 
+func (m *UserCreateRequest) GetHostID() uint32 {
+	if m != nil {
+		return m.HostID
+	}
+	return 0
+}
+
 type UserUpdateRequest struct {
 	Username string                   `protobuf:"bytes,1,opt,name=Username" json:"Username,omitempty"`
 	Password string                   `protobuf:"bytes,2,opt,name=Password" json:"Password,omitempty"`
 	Gwpref   UserUpdateRequest_GWPref `protobuf:"varint,3,opt,name=gwpref,enum=pb.UserUpdateRequest_GWPref" json:"gwpref,omitempty"`
+	HostID   uint32                   `protobuf:"varint,4,opt,name=HostID" json:"HostID,omitempty"`
 }
 
 func (m *UserUpdateRequest) Reset()                    { *m = UserUpdateRequest{} }
@@ -140,6 +149,13 @@ func (m *UserUpdateRequest) GetGwpref() UserUpdateRequest_GWPref {
 	return UserUpdateRequest_NOPREF
 }
 
+func (m *UserUpdateRequest) GetHostID() uint32 {
+	if m != nil {
+		return m.HostID
+	}
+	return 0
+}
+
 type UserDeleteRequest struct {
 	Username string `protobuf:"bytes,1,opt,name=Username" json:"Username,omitempty"`
 }
@@ -211,6 +227,7 @@ type UserResponse_User struct {
 	CreatedAt          string `protobuf:"bytes,4,opt,name=CreatedAt" json:"CreatedAt,omitempty"`
 	IPNet              string `protobuf:"bytes,5,opt,name=IPNet" json:"IPNet,omitempty"`
 	NoGW               bool   `protobuf:"varint,6,opt,name=NoGW" json:"NoGW,omitempty"`
+	HostID             uint32 `protobuf:"varint,7,opt,name=HostID" json:"HostID,omitempty"`
 }
 
 func (m *UserResponse_User) Reset()                    { *m = UserResponse_User{} }
@@ -260,6 +277,13 @@ func (m *UserResponse_User) GetNoGW() bool {
 	return false
 }
 
+func (m *UserResponse_User) GetHostID() uint32 {
+	if m != nil {
+		return m.HostID
+	}
+	return 0
+}
+
 type UserGenConfigResponse struct {
 	ClientConfig string `protobuf:"bytes,1,opt,name=ClientConfig" json:"ClientConfig,omitempty"`
 }
@@ -529,34 +553,35 @@ var _UserService_serviceDesc = grpc.ServiceDesc{
 func init() { proto.RegisterFile("user.proto", fileDescriptor0) }
 
 var fileDescriptor0 = []byte{
-	// 461 bytes of a gzipped FileDescriptorProto
-	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xc1, 0x6e, 0xd3, 0x40,
-	0x10, 0xed, 0xba, 0x8e, 0x95, 0x4c, 0x2b, 0x70, 0x87, 0x54, 0x32, 0x51, 0x0f, 0xd1, 0x1e, 0x50,
-	0x24, 0x24, 0x57, 0xa4, 0xdc, 0x38, 0x41, 0x00, 0x0b, 0x09, 0xb9, 0x91, 0xab, 0x2a, 0x47, 0x94,
-	0x90, 0x49, 0x65, 0x29, 0xb5, 0xcd, 0xee, 0x86, 0x7c, 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0x15,
-	0x74, 0x8c, 0xd7, 0xb0, 0x5f, 0x83, 0xb5, 0xf5, 0x5a, 0x29, 0xef, 0xa0, 0xb7, 0xd3, 0x12, 0x83,
-	0xaa, 0x61, 0xdf, 0x81, 0x83, 0xe7, 0x2d, 0x48, 0x75, 0xc6, 0xc2, 0x33, 0xbf, 0x90, 0xab, 0x3f,
-	0x01, 0x00, 0x00, 0xff, 0xff, 0x9e, 0x2b, 0xc6, 0x91, 0x50, 0x04, 0x00, 0x00,
+	// 480 bytes of a gzipped FileDescriptorProto
+	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xcd, 0x6e, 0xd3, 0x40,
+	0x10, 0xae, 0x5d, 0xc7, 0xc4, 0xd3, 0x02, 0xee, 0x90, 0x22, 0x13, 0xf5, 0x10, 0xf9, 0x80, 0x22,
+	0x21, 0xb9, 0x22, 0xe5, 0xc6, 0x09, 0x52, 0x30, 0x95, 0x90, 0x1b, 0x6d, 0x55, 0xe5, 0x9c, 0x90,
+	0x49, 0x65, 0x29, 0xb1, 0xcd, 0xee, 0x86, 0xbc, 0x00, 0x2f, 0xc6, 0x85, 0x27, 0xe0, 0x81, 0xd0,
+	0x7a, 0xfd, 0x83, 0x83, 0x83, 0x72, 0xe0, 0x36, 0x7f, 0xdf, 0x8e, 0xe7, 0x9b, 0x6f, 0x0c, 0xb0,
+	0x11, 0xc4, 0x83, 0x8c, 0xa7, 0x32, 0x45, 0x33, 0x9b, 0xfb, 0x67, 0xf0, 0xf4, 0x5e, 0x10, 0xff,
+	0x1c, 0x0b, 0xc9, 0xe8, 0xeb, 0x86, 0x84, 0xf4, 0xb7, 0x70, 0xa6, 0x42, 0x63, 0x4e, 0x33, 0x49,
+	0x45, 0x10, 0xfb, 0xd0, 0x55, 0xc1, 0x64, 0xb6, 0x26, 0xcf, 0x18, 0x18, 0x43, 0x87, 0x55, 0xbe,
+	0xca, 0x4d, 0x66, 0x42, 0x6c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 0xcf, 0x89, 0x17, 0x3b, 0x69, 0xc9, 0x28,
+	0x5d, 0x8c, 0x89, 0xcb, 0x7c, 0x37, 0x0e, 0xcb, 0x6d, 0xbc, 0x00, 0x47, 0x8b, 0x6e, 0xf1, 0x4e,
+	0xe6, 0xf4, 0x3b, 0xac, 0x0e, 0x60, 0x0f, 0x3a, 0x37, 0x93, 0x88, 0xa4, 0xd7, 0xc9, 0x33, 0xda,
+	0xa9, 0xf4, 0x65, 0xb7, 0xea, 0xeb, 0x51, 0x63, 0x87, 0x6f, 0xe1, 0x7c, 0x87, 0xba, 0x82, 0x0e,
+	0x1f, 0x4e, 0xc7, 0xab, 0x98, 0x12, 0xa9, 0xe3, 0xc5, 0x70, 0x8d, 0xd8, 0xe8, 0x97, 0x09, 0x27,
+	0x0a, 0xad, 0x66, 0x89, 0xbf, 0x10, 0x5e, 0x82, 0xa5, 0x8e, 0x06, 0x9f, 0x95, 0xdc, 0xfd, 0x71,
+	0x42, 0x7d, 0x77, 0x97, 0x50, 0xff, 0x08, 0xaf, 0xc0, 0xd6, 0xc3, 0x60, 0x45, 0x77, 0xe3, 0xc4,
+	0xf6, 0x81, 0xb4, 0x5c, 0x6b, 0x50, 0x43, 0xbe, 0xfb, 0x40, 0x5a, 0x7f, 0x35, 0xa8, 0xa1, 0xc7,
+	0x56, 0xd0, 0x6b, 0xe8, 0xe4, 0x1a, 0xc4, 0x5e, 0x9d, 0xac, 0x25, 0xd9, 0x0a, 0x79, 0x0f, 0x4e,
+	0xc5, 0x25, 0x7a, 0x65, 0xc1, 0xae, 0x32, 0xfb, 0x2f, 0x5a, 0x32, 0xe5, 0x1b, 0x73, 0x3b, 0xff,
+	0x15, 0x5d, 0xfd, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x90, 0xef, 0x0f, 0xc4, 0x98, 0x04, 0x00, 0x00,
 }

+ 3 - 0
pb/user.proto

@@ -10,6 +10,7 @@ message UserCreateRequest {
   string Username = 1;
   string Password = 2;
   bool NoGW = 3;
+  uint32 HostID = 4;
 }
 
 message UserUpdateRequest {
@@ -21,6 +22,7 @@ message UserUpdateRequest {
     GW = 2;
   }
   GWPref gwpref = 3;
+  uint32 HostID = 4;
 }
 
 
@@ -53,6 +55,7 @@ message UserResponse {
     string CreatedAt = 4;
     string IPNet = 5;
     bool NoGW = 6;
+    uint32 HostID = 7;
   }
 
   repeated User users = 1;

+ 109 - 8
user.go

@@ -20,6 +20,7 @@ type User interface {
 	GetCert() string
 	GetIPNet() string
 	IsNoGW() bool
+	GetHostID() uint32
 }
 
 // DBUser is database model for VPN users.
@@ -34,6 +35,7 @@ type DBUser struct {
 	Hash               string
 	Key                string // not user writable
 	NoGW               bool
+	HostID             uint32 // not user writable
 }
 
 // DBRevoked is a database model for revoked VPN users.
@@ -87,7 +89,7 @@ func GetAllUsers() ([]*DBUser, error) {
 //
 // It also generates the necessary client keys and signs certificates with the current
 // server's CA.
-func CreateNewUser(username, password string, nogw bool) (*DBUser, error) {
+func CreateNewUser(username, password string, nogw bool, hostid uint32) (*DBUser, error) {
 	if !IsInitialized() {
 		return nil, fmt.Errorf("you first need to create server")
 	}
@@ -98,6 +100,7 @@ func CreateNewUser(username, password string, nogw bool) (*DBUser, error) {
 	if !govalidator.IsAlphanumeric(username) {
 		return nil, fmt.Errorf("validation error: `%s` can only contain letters and numbers", username)
 	}
+
 	ca, err := GetSystemCA()
 	if err != nil {
 		return nil, err
@@ -111,12 +114,29 @@ func CreateNewUser(username, password string, nogw bool) (*DBUser, error) {
 	if err != nil {
 		return nil, fmt.Errorf("can not get server: %v", err)
 	}
+
+	if hostid != 0 {
+		ip := HostID2IP(hostid)
+		if ip == nil {
+			return nil, fmt.Errorf("host id doesn't represent an ip %d", hostid)
+		}
+
+		network := net.IPNet{IP: net.ParseIP(server.Net).To4(), Mask: net.IPMask(net.ParseIP(server.Mask).To4())}
+		if !network.Contains(ip) {
+			return nil, fmt.Errorf("ip %s, is out of vpn network %s", ip, network.String())
+		}
+
+		if hostIDsContains(getStaticHostIDs(), hostid) {
+			return nil, fmt.Errorf("ip %s is already allocated", ip)
+		}
+	}
 	user := DBUser{
 		Username:           username,
 		Cert:               clientCert.Cert,
 		Key:                clientCert.Key,
 		ServerSerialNumber: server.SerialNumber,
 		NoGW:               nogw,
+		HostID:             hostid,
 	}
 	user.setPassword(password)
 
@@ -138,7 +158,7 @@ func CreateNewUser(username, password string, nogw bool) (*DBUser, error) {
 // Update updates the user's attributes and writes them to the database.
 //
 // How this method works is similiar to PUT semantics of REST. It sets the user record fields to the provided function arguments.
-func (u *DBUser) Update(password string, nogw bool) error {
+func (u *DBUser) Update(password string, nogw bool, hostid uint32) error {
 	if !IsInitialized() {
 		return fmt.Errorf("you first need to create server")
 	}
@@ -149,8 +169,30 @@ func (u *DBUser) Update(password string, nogw bool) error {
 	}
 
 	u.NoGW = nogw
+	u.HostID = hostid
 	db.Save(u)
 
+	if hostid != 0 {
+		server, err := GetServerInstance()
+		if err != nil {
+			return fmt.Errorf("can not get server: %v", err)
+		}
+
+		ip := HostID2IP(hostid)
+		if ip == nil {
+			return fmt.Errorf("host id doesn't represent an ip %d", hostid)
+		}
+
+		network := net.IPNet{IP: net.ParseIP(server.Net).To4(), Mask: net.IPMask(net.ParseIP(server.Mask).To4())}
+		if !network.Contains(ip) {
+			return fmt.Errorf("ip %s, is out of vpn network %s", ip, network.String())
+		}
+
+		if hostIDsContains(getStaticHostIDs(), hostid) {
+			return fmt.Errorf("ip %s is already allocated", ip)
+		}
+	}
+
 	err := Emit()
 	if err != nil {
 		return err
@@ -257,16 +299,39 @@ func (u *DBUser) GetCreatedAt() string {
 
 // getIP returns user's vpn ip addr.
 func (u *DBUser) getIP() net.IP {
-	clientsNetMask := net.IPMask(net.ParseIP(_DefaultServerNetMask))
-	clientsNetPrefix := net.ParseIP(_DefaultServerNetwork)
-	clientNet := clientsNetPrefix.Mask(clientsNetMask).To4()
-	clientNet[3] = byte(u.ID)
-	return clientNet
+	users := getNonStaticHostUsers()
+	staticHostIDs := getStaticHostIDs()
+	mask := net.IPMask(net.ParseIP(_DefaultServerNetMask).To4())
+	network := net.ParseIP(_DefaultServerNetwork).To4().Mask(mask)
+
+	// Host is static?
+	if u.HostID != 0 {
+		// Host is really static?
+		if hostIDsContains(staticHostIDs, u.HostID) {
+			return HostID2IP(u.HostID)
+		}
+		return nil
+	}
+
+	// Host is dynamic.
+	for i, user := range users {
+		hostID := IP2HostID(network) + uint32(i+2)
+		if hostIDsContains(staticHostIDs, hostID) {
+			for hostIDsContains(staticHostIDs, hostID) {
+				i++
+				hostID = IP2HostID(network) + uint32(i+1)
+			}
+		}
+		if user.ID == u.ID {
+			return HostID2IP(hostID)
+		}
+	}
+	return nil
 }
 
 // GetIPNet returns user's vpn ip network. (e.g. 192.168.0.1/24)
 func (u *DBUser) GetIPNet() string {
-	mask := net.IPMask(net.ParseIP(_DefaultServerNetMask))
+	mask := net.IPMask(net.ParseIP(_DefaultServerNetMask).To4())
 
 	ipn := net.IPNet{
 		IP:   u.getIP(),
@@ -279,3 +344,39 @@ func (u *DBUser) GetIPNet() string {
 func (u *DBUser) IsNoGW() bool {
 	return u.NoGW
 }
+
+// GetHostID returns user's Host ID.
+func (u *DBUser) GetHostID() uint32 {
+	return u.HostID
+}
+
+func getStaticHostUsers() []*DBUser {
+	var users []*DBUser
+	db.Unscoped().Not(DBUser{HostID: 0}).Find(&users)
+	return users
+}
+
+func getNonStaticHostUsers() []*DBUser {
+	var users []*DBUser
+	db.Unscoped().Where(DBUser{HostID: 0}).Find(&users)
+	return users
+}
+
+func getStaticHostIDs() []uint32 {
+	var ids []uint32
+	users := getStaticHostUsers()
+	for _, user := range users {
+		ids = append(ids, user.HostID)
+	}
+
+	return ids
+}
+
+func hostIDsContains(s []uint32, e uint32) bool {
+	for _, a := range s {
+		if a == e {
+			return true
+		}
+	}
+	return false
+}