Skip to content

Commit

Permalink
began windows userspace implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
0xdcarns committed Sep 10, 2021
1 parent 90390db commit 3471741
Show file tree
Hide file tree
Showing 32 changed files with 1,089 additions and 507 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ netclient/netclient-arm
netclient/netclient-arm64
netclient/netclient-32
config/dnsconfig/
winsw.exe
data/
10 changes: 8 additions & 2 deletions controllers/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,14 @@ func TestGetPeerList(t *testing.T) {
CreateNode(createnode, "skynet")
peers, err := GetPeersList("skynet")
assert.Nil(t, err)
assert.Equal(t, node.Endpoint, peers[0].Endpoint)
assert.Equal(t, createnode.Endpoint, peers[1].Endpoint)
assert.Equal(t, len(peers), 2)
foundNodeEndpoint := false
for _, peer := range peers {
if foundNodeEndpoint = peer.Endpoint == createnode.Endpoint; foundNodeEndpoint {
break
}
}
assert.True(t, foundNodeEndpoint)
})
}

Expand Down
8 changes: 0 additions & 8 deletions controllers/networkHttpController_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,6 @@ func TestCreateKey(t *testing.T) {
var accesskey models.AccessKey
var network models.Network
network.NetID = "skynet"
t.Run("InvalidName", func(t *testing.T) {
network, err := GetNetwork("skynet")
assert.Nil(t, err)
accesskey.Name = "bad-name"
_, err = CreateAccessKey(accesskey, network)
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "Field validation for 'Name' failed on the 'alphanum' tag")
})
t.Run("NameTooLong", func(t *testing.T) {
network, err := GetNetwork("skynet")
assert.Nil(t, err)
Expand Down
7 changes: 7 additions & 0 deletions controllers/nodeHttpController.go
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,9 @@ func createEgressGateway(w http.ResponseWriter, r *http.Request) {

func CreateEgressGateway(gateway models.EgressGatewayRequest) (models.Node, error) {
node, err := functions.GetNodeByMacAddress(gateway.NetID, gateway.NodeID)
if node.OS == "windows" { // add in darwin later
return models.Node{}, errors.New(node.OS + " is unsupported for egress gateways")
}
if err != nil {
return models.Node{}, err
}
Expand Down Expand Up @@ -630,6 +633,10 @@ func createIngressGateway(w http.ResponseWriter, r *http.Request) {
func CreateIngressGateway(netid string, macaddress string) (models.Node, error) {

node, err := functions.GetNodeByMacAddress(netid, macaddress)
if node.OS == "windows" { // add in darwin later
return models.Node{}, errors.New(node.OS + " is unsupported for ingress gateways")
}

if err != nil {
return models.Node{}, err
}
Expand Down
15 changes: 10 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,28 @@ require (
github.com/gorilla/handlers v1.5.1
github.com/gorilla/mux v1.8.0
github.com/jinzhu/copier v0.3.2 // indirect
github.com/josephspurrier/goversioninfo v1.3.0 // indirect
github.com/kardianos/service v1.2.0 // indirect
github.com/mattn/go-sqlite3 v1.14.8
github.com/mdlayher/genetlink v1.0.0 // indirect
github.com/mikioh/ipaddr v0.0.0-20190404000644-d465c8ab6721 // indirect
github.com/rqlite/gorqlite v0.0.0-20210514125552-08ff1e76b22f
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/stretchr/testify v1.6.1
github.com/txn2/txeh v1.3.0
github.com/urfave/cli v1.22.5 // indirect
github.com/urfave/cli/v2 v2.3.0
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
golang.org/x/net v0.0.0-20210119194325-5f4716e94777 // indirect
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 // indirect
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c // indirect
golang.org/x/text v0.3.5 // indirect
golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20200609130330-bd2cb7843e1b
golang.zx2c4.com/wireguard v0.0.0-20210805125648-3957e9b9dd19 // indirect
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20210803171230-4253848d036c
golang.zx2c4.com/wireguard/windows v0.4.5 // indirect
google.golang.org/genproto v0.0.0-20210201151548-94839c025ad4 // indirect
google.golang.org/grpc v1.35.0
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0 // indirect
google.golang.org/protobuf v1.26.0
gopkg.in/Knetic/govaluate.v3 v3.0.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c
)
74 changes: 74 additions & 0 deletions go.sum

Large diffs are not rendered by default.

29 changes: 15 additions & 14 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
"google.golang.org/grpc"
)

//Start MongoDB Connection and start API Request Handler
// Start DB Connection and start API Request Handler
func main() {
fmt.Println(models.RetrieveLogo()) // print the logo
initialize() // initial db and grpc server
Expand All @@ -37,19 +37,20 @@ func initialize() { // Client Mode Prereq Check
log.Fatal(err)
}
log.Println("database successfully connected.")
output, err := local.RunCmd("id -u")

if err != nil {
log.Println("Error running 'id -u' for prereq check. Please investigate or disable client mode.")
log.Fatal(output, err)
}
uid, err := strconv.Atoi(string(output[:len(output)-1]))
if err != nil {
log.Println("Error retrieving uid from 'id -u' for prereq check. Please investigate or disable client mode.")
log.Fatal(err)
}
if uid != 0 {
log.Fatal("To run in client mode requires root privileges. Either disable client mode or run with sudo.")
if servercfg.IsClientMode() {
output, err := local.RunCmd("id -u")
if err != nil {
log.Println("Error running 'id -u' for prereq check. Please investigate or disable client mode.")
log.Fatal(output, err)
}
uid, err := strconv.Atoi(string(output[:len(output)-1]))
if err != nil {
log.Println("Error retrieving uid from 'id -u' for prereq check. Please investigate or disable client mode.")
log.Fatal(err)
}
if uid != 0 {
log.Fatal("To run in client mode requires root privileges. Either disable client mode or run with sudo.")
}
}

if servercfg.IsDNSMode() {
Expand Down
55 changes: 3 additions & 52 deletions models/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"time"

Expand Down Expand Up @@ -41,51 +40,13 @@ type Network struct {
DefaultCheckInInterval int32 `json:"checkininterval,omitempty" bson:"checkininterval,omitempty" validate:"omitempty,numeric,min=2,max=100000"`
DefaultUDPHolePunch string `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"`
DefaultExtClientDNS string `json:"defaultextclientdns" bson:"defaultextclientdns"`
DefaultMTU int32 `json:"defaultmtu" bson:"defaultmtu"`
}

type SaveData struct { // put sensitive fields here
NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=12,netid_valid"`
}

const STRING_FIELD_TYPE = "string"
const INT64_FIELD_TYPE = "int64"
const INT32_FIELD_TYPE = "int32"
const ACCESS_KEY_TYPE = "[]AccessKey"

var FIELD_TYPES = []string{STRING_FIELD_TYPE, INT64_FIELD_TYPE, INT32_FIELD_TYPE, ACCESS_KEY_TYPE}

var FIELDS = map[string][]string{
// "id": {"ID", "string"},
"addressrange": {"AddressRange", STRING_FIELD_TYPE},
"addressrange6": {"AddressRange6", STRING_FIELD_TYPE},
"displayname": {"DisplayName", STRING_FIELD_TYPE},
"netid": {"NetID", STRING_FIELD_TYPE},
"nodeslastmodified": {"NodesLastModified", INT64_FIELD_TYPE},
"networklastmodified": {"NetworkLastModified", INT64_FIELD_TYPE},
"defaultinterface": {"DefaultInterface", STRING_FIELD_TYPE},
"defaultlistenport": {"DefaultListenPort", INT32_FIELD_TYPE},
"nodelimit": {"NodeLimit", INT32_FIELD_TYPE},
"defaultpostup": {"DefaultPostUp", STRING_FIELD_TYPE},
"defaultpostdown": {"DefaultPostDown", STRING_FIELD_TYPE},
"keyupdatetimestamp": {"KeyUpdateTimeStamp", INT64_FIELD_TYPE},
"defaultkeepalive": {"DefaultKeepalive", INT32_FIELD_TYPE},
"defaultsaveconfig": {"DefaultSaveConfig", STRING_FIELD_TYPE},
"accesskeys": {"AccessKeys", ACCESS_KEY_TYPE},
"allowmanualsignup": {"AllowManualSignUp", STRING_FIELD_TYPE},
"islocal": {"IsLocal", STRING_FIELD_TYPE},
"isdualstack": {"IsDualStack", STRING_FIELD_TYPE},
"isipv4": {"IsIPv4", STRING_FIELD_TYPE},
"isipv6": {"IsIPv6", STRING_FIELD_TYPE},
"isgrpchub": {"IsGRPCHub", STRING_FIELD_TYPE},
"localrange": {"LocalRange", STRING_FIELD_TYPE},
"checkininterval": {"DefaultCheckInInterval", INT32_FIELD_TYPE},
"defaultudpholepunch": {"DefaultUDPHolePunch", STRING_FIELD_TYPE},
}

func (network *Network) FieldExists(field string) bool {
return len(FIELDS[field]) > 0
}

func (network *Network) NetIDInNetworkCharSet() bool {

charset := "abcdefghijklmnopqrstuvwxyz1234567890-_."
Expand Down Expand Up @@ -268,19 +229,9 @@ func (network *Network) SetDefaults() {
network.IsIPv6 = "no"
network.IsIPv4 = "yes"
}
}

func (network *Network) CopyValues(newNetwork *Network, fieldName string) {
reflection := reflect.ValueOf(newNetwork)
value := reflect.Indirect(reflection).FieldByName(FIELDS[fieldName][0])
if value.IsValid() && len(FIELDS[fieldName]) == 2 {
fieldData := FIELDS[fieldName]
for _, indexVal := range FIELD_TYPES {
if indexVal == fieldData[1] {
currentReflection := reflect.ValueOf(network)
reflect.Indirect(currentReflection).FieldByName(FIELDS[fieldName][0]).Set(value)
}
}
if network.DefaultMTU == 0 {
network.DefaultMTU = 1280
}
}

Expand Down
13 changes: 13 additions & 0 deletions models/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ type Node struct {
LocalRange string `json:"localrange" bson:"localrange" yaml:"localrange"`
Roaming string `json:"roaming" bson:"roaming" yaml:"roaming" validate:"checkyesorno"`
IPForwarding string `json:"ipforwarding" bson:"ipforwarding" yaml:"ipforwarding" validate:"checkyesorno"`
OS string `json:"os" bson:"os" yaml:"os"`
MTU int32 `json:"mtu" bson:"mtu" yaml:"mtu"`
}

func (node *Node) SetDefaultMTU() {
if node.MTU == 0 {
node.MTU = 1280
}
}

func (node *Node) SetDefaulIsPending() {
Expand Down Expand Up @@ -241,6 +249,7 @@ func (node *Node) SetDefaults() {
// == Parent Network settings ==
node.CheckInInterval = parentNetwork.DefaultCheckInInterval
node.IsDualStack = parentNetwork.IsDualStack
node.MTU = parentNetwork.DefaultMTU
// == node defaults if not set by parent ==
node.SetIPForwardingDefault()
node.SetDNSOnDefault()
Expand All @@ -259,6 +268,7 @@ func (node *Node) SetDefaults() {
node.SetDefaultEgressGateway()
node.SetDefaultIngressGateway()
node.SetDefaulIsPending()
node.SetDefaultMTU()
node.KeyUpdateTimeStamp = time.Now().Unix()
}

Expand Down Expand Up @@ -391,6 +401,9 @@ func (newNode *Node) Fill(currentNode *Node) {
if newNode.IsServer == "yes" {
newNode.IsStatic = "yes"
}
if newNode.MTU == 0 {
newNode.MTU = currentNode.MTU
}
}

func (currentNode *Node) Update(newNode *Node) error {
Expand Down
18 changes: 9 additions & 9 deletions models/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ type SuccessResponse struct {
}

type AccessKey struct {
Name string `json:"name" bson:"name" validate:"omitempty,alphanum,max=20"`
Name string `json:"name" bson:"name" validate:"omitempty,max=20"`
Value string `json:"value" bson:"value" validate:"omitempty,alphanum,max=16"`
AccessString string `json:"accessstring" bson:"accessstring"`
Uses int `json:"uses" bson:"uses"`
Expand Down Expand Up @@ -98,15 +98,15 @@ type CheckInResponse struct {
}

type PeersResponse struct {
PublicKey string `json:"publickey" bson:"publickey"`
Endpoint string `json:"endpoint" bson:"endpoint"`
Address string `json:"address" bson:"address"`
Address6 string `json:"address6" bson:"address6"`
LocalAddress string `json:"localaddress" bson:"localaddress"`
IsEgressGateway string `json:"isegressgateway" bson:"isegressgateway"`
PublicKey string `json:"publickey" bson:"publickey"`
Endpoint string `json:"endpoint" bson:"endpoint"`
Address string `json:"address" bson:"address"`
Address6 string `json:"address6" bson:"address6"`
LocalAddress string `json:"localaddress" bson:"localaddress"`
IsEgressGateway string `json:"isegressgateway" bson:"isegressgateway"`
EgressGatewayRanges string `json:"egressgatewayrange" bson:"egressgatewayrange"`
ListenPort int32 `json:"listenport" bson:"listenport"`
KeepAlive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
ListenPort int32 `json:"listenport" bson:"listenport"`
KeepAlive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
}

type ExtPeersResponse struct {
Expand Down
18 changes: 8 additions & 10 deletions netclient/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/config"
"github.com/gravitl/netmaker/netclient/netclientutils"

// "os"
"context"
Expand All @@ -19,15 +20,14 @@ import (

// CreateJWT func will used to create the JWT while signing in and signing out
func SetJWT(client nodepb.NodeServiceClient, network string) (context.Context, error) {
//home, err := os.UserHomeDir()
home := "/etc/netclient"
tokentext, err := ioutil.ReadFile(home + "/nettoken-" + network)
home := netclientutils.GetNetclientPathSpecific()
tokentext, err := ioutil.ReadFile(home + "nettoken-" + network)
if err != nil {
err = AutoLogin(client, network)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong with Auto Login: %v", err))
}
tokentext, err = ioutil.ReadFile(home + "/nettoken-" + network)
tokentext, err = ioutil.ReadFile(home + "nettoken-" + network)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong: %v", err))
}
Expand All @@ -42,9 +42,7 @@ func SetJWT(client nodepb.NodeServiceClient, network string) (context.Context, e
}

func AutoLogin(client nodepb.NodeServiceClient, network string) error {
//home, err := os.UserHomeDir()
home := "/etc/netclient"
//nodecfg := config.Config.Node
home := netclientutils.GetNetclientPathSpecific()
cfg, err := config.ReadConfig(network)
if err != nil {
return err
Expand Down Expand Up @@ -72,7 +70,7 @@ func AutoLogin(client nodepb.NodeServiceClient, network string) error {
return err
}
tokenstring := []byte(res.Data)
err = ioutil.WriteFile(home+"/nettoken-"+network, tokenstring, 0644)
err = ioutil.WriteFile(home+"nettoken-"+network, tokenstring, 0644)
if err != nil {
return err
}
Expand All @@ -81,12 +79,12 @@ func AutoLogin(client nodepb.NodeServiceClient, network string) error {

func StoreSecret(key string, network string) error {
d1 := []byte(key)
err := ioutil.WriteFile("/etc/netclient/secret-"+network, d1, 0644)
err := ioutil.WriteFile(netclientutils.GetNetclientPathSpecific()+"secret-"+network, d1, 0644)
return err
}

func RetrieveSecret(network string) (string, error) {
dat, err := ioutil.ReadFile("/etc/netclient/secret-" + network)
dat, err := ioutil.ReadFile(netclientutils.GetNetclientPathSpecific() + "secret-" + network)
return string(dat), err
}

Expand Down
Loading

0 comments on commit 3471741

Please sign in to comment.