encrypt and save hostpass on HostCreate

This commit is contained in:
Matthew R. Kasun 2022-12-21 14:43:46 -05:00
parent b07504c286
commit bc47ef4868
3 changed files with 22 additions and 13 deletions

View file

@ -607,8 +607,10 @@ func createNode(w http.ResponseWriter, r *http.Request) {
// consume password before hashing for mq client creation
nodePassword := data.Host.HostPass
data.Node.Server = servercfg.GetServer()
if _, err := logic.GetHost(data.Node.HostID.String()); err != nil {
if err := logic.CreateHost(&data.Host); err != nil {
if err := logic.CreateHost(&data.Host); err != nil {
if errors.Is(err, logic.ErrHostExists) {
logger.Log(3, "host exists .. no need to create")
} else {
logger.Log(0, "error creating host", err.Error())
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
return

View file

@ -2,12 +2,15 @@ package logic
import (
"encoding/json"
"fmt"
"errors"
"github.com/gravitl/netmaker/database"
"github.com/gravitl/netmaker/models"
"golang.org/x/crypto/bcrypt"
)
var ErrHostExists error = errors.New("host already exists")
// GetAllHosts - returns all hosts in flat list or error
func GetAllHosts() ([]models.Host, error) {
currHostMap, err := GetHostsMap()
@ -61,9 +64,14 @@ func GetHost(hostid string) (*models.Host, error) {
func CreateHost(h *models.Host) error {
_, err := GetHost(h.ID.String())
if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) {
return fmt.Errorf("host already exists")
return ErrHostExists
}
//encrypt that password so we never see it
hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5)
if err != nil {
return err
}
h.HostPass = string(hash)
return UpsertHost(h)
}
@ -136,3 +144,10 @@ func RemoveHost(h *models.Host) error {
}
return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String())
}
// host.UpdatePass updates and saves host.HostPass
// Password saved on server needs to be the hashedPassword, whereas the raw password belongs to client
func UpdatePass(h *models.Host, pass string) error {
h.HostPass = pass
return UpsertHost(h)
}

View file

@ -20,7 +20,6 @@ import (
"github.com/gravitl/netmaker/netclient/ncutils"
"github.com/gravitl/netmaker/servercfg"
"github.com/gravitl/netmaker/validation"
"golang.org/x/crypto/bcrypt"
)
const (
@ -191,13 +190,6 @@ func CreateNode(node *models.Node) error {
return err
}
//encrypt that password so we never see it
hash, err := bcrypt.GenerateFromPassword([]byte(host.HostPass), 5)
if err != nil {
return err
}
//set password to encrypted password
host.HostPass = string(hash)
if !node.DNSOn {
if servercfg.IsDNSMode() {
node.DNSOn = true