@@ -22,6 +22,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/d4l3k/messagediff"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/syncthing/syncthing/lib/build"
|
||||
"github.com/syncthing/syncthing/lib/events"
|
||||
@@ -773,8 +774,9 @@ func TestGUIConfigURL(t *testing.T) {
|
||||
func TestGUIPasswordHash(t *testing.T) {
|
||||
var c GUIConfiguration
|
||||
|
||||
// Setting a plaintext password should work
|
||||
testPass := "pass"
|
||||
if err := c.HashAndSetPassword(testPass); err != nil {
|
||||
if err := c.SetPassword(testPass); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Password == testPass {
|
||||
@@ -789,6 +791,16 @@ func TestGUIPasswordHash(t *testing.T) {
|
||||
if err := c.CompareHashedPassword(failPass); err == nil {
|
||||
t.Errorf("Match on different password: %v", err)
|
||||
}
|
||||
|
||||
// Setting a bcrypt hash directly should also work
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("test"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.SetPassword(string(hash))
|
||||
if err := c.CompareHashedPassword("test"); err != nil {
|
||||
t.Errorf("No match on hashed password: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateDevices(t *testing.T) {
|
||||
|
||||
@@ -9,6 +9,7 @@ package config
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -115,9 +116,19 @@ func (c GUIConfiguration) URL() string {
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// SetHashedPassword hashes the given plaintext password and stores the new hash.
|
||||
func (c *GUIConfiguration) HashAndSetPassword(password string) error {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), 0)
|
||||
// matches a bcrypt hash and not too much else
|
||||
var bcryptExpr = regexp.MustCompile(`^\$2[aby]\$\d+\$.{50,}`)
|
||||
|
||||
// SetPassword takes a bcrypt hash or a plaintext password and stores it.
|
||||
// Plaintext passwords are hashed. Returns an error if the password is not
|
||||
// valid.
|
||||
func (c *GUIConfiguration) SetPassword(password string) error {
|
||||
if bcryptExpr.MatchString(password) {
|
||||
// Already hashed
|
||||
c.Password = password
|
||||
return nil
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user