Skip to content

Commit cd4d50b

Browse files
Gustedlafrikszeripath
authored and
Stelios Malathouras
committed
Increase Salt randomness (go-gitea#18179)
- The current implementation of `RandomString` doesn't give you a most-possible unique randomness. It gives you 6*`length` instead of the possible 8*`length` bits(or as `length`x bytes) randomness. This is because `RandomString` is being limited to a max value of 63, this in order to represent the random byte as a letter/digit. - The recommendation of pbkdf2 is to use 64+ bit salt, which the `RandomString` doesn't give with a length of 10, instead of increasing 10 to a higher number, this patch adds a new function called `RandomBytes` which does give you the guarentee of 8*`length` randomness and thus corresponding of `length`x bytes randomness. - Use hexadecimal to store the bytes value in the database, as mentioned, it doesn't play nice in order to convert it to a string. This will always be a length of 32(with `length` being 16). - When we detect on `Authenticate`(source: db) that a user has the old format of salt, re-hash the password such that the user will have it's password hashed with increased salt. Thanks to @zeripath for working out the rouge edges from my first commit 😄. Co-authored-by: lafriks <[email protected]> Co-authored-by: zeripath <[email protected]>
1 parent 17fe876 commit cd4d50b

File tree

6 files changed

+115
-14
lines changed

6 files changed

+115
-14
lines changed

models/migrations/migrations.go

+2
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,8 @@ var migrations = []Migration{
363363
NewMigration("Add Sorting to ProjectIssue table", addProjectIssueSorting),
364364
// v204 -> v205
365365
NewMigration("Add key is verified to ssh key", addSSHKeyIsVerified),
366+
// v205 -> v206
367+
NewMigration("Migrate to higher varchar on user struct", migrateUserPasswordSalt),
366368
}
367369

368370
// GetCurrentDBVersion returns the current db version

models/migrations/v205.go

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Copyright 2022 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package migrations
6+
7+
import (
8+
"xorm.io/xorm"
9+
"xorm.io/xorm/schemas"
10+
)
11+
12+
func migrateUserPasswordSalt(x *xorm.Engine) error {
13+
dbType := x.Dialect().URI().DBType
14+
// For SQLITE, the max length doesn't matter.
15+
if dbType == schemas.SQLITE {
16+
return nil
17+
}
18+
19+
if err := modifyColumn(x, "user", &schemas.Column{
20+
Name: "rands",
21+
SQLType: schemas.SQLType{
22+
Name: "VARCHAR",
23+
},
24+
Length: 32,
25+
// MySQL will like us again.
26+
Nullable: true,
27+
}); err != nil {
28+
return err
29+
}
30+
31+
return modifyColumn(x, "user", &schemas.Column{
32+
Name: "salt",
33+
SQLType: schemas.SQLType{
34+
Name: "VARCHAR",
35+
},
36+
Length: 32,
37+
Nullable: true,
38+
})
39+
}

models/user/user.go

+42-11
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ type User struct {
9595
Type UserType
9696
Location string
9797
Website string
98-
Rands string `xorm:"VARCHAR(10)"`
99-
Salt string `xorm:"VARCHAR(10)"`
98+
Rands string `xorm:"VARCHAR(32)"`
99+
Salt string `xorm:"VARCHAR(32)"`
100100
Language string `xorm:"VARCHAR(5)"`
101101
Description string
102102

@@ -358,24 +358,40 @@ func (u *User) NewGitSig() *git.Signature {
358358
}
359359
}
360360

361-
func hashPassword(passwd, salt, algo string) string {
361+
func hashPassword(passwd, salt, algo string) (string, error) {
362362
var tempPasswd []byte
363+
var saltBytes []byte
364+
365+
// There are two formats for the Salt value:
366+
// * The new format is a (32+)-byte hex-encoded string
367+
// * The old format was a 10-byte binary format
368+
// We have to tolerate both here but Authenticate should
369+
// regenerate the Salt following a successful validation.
370+
if len(salt) == 10 {
371+
saltBytes = []byte(salt)
372+
} else {
373+
var err error
374+
saltBytes, err = hex.DecodeString(salt)
375+
if err != nil {
376+
return "", err
377+
}
378+
}
363379

364380
switch algo {
365381
case algoBcrypt:
366382
tempPasswd, _ = bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
367-
return string(tempPasswd)
383+
return string(tempPasswd), nil
368384
case algoScrypt:
369-
tempPasswd, _ = scrypt.Key([]byte(passwd), []byte(salt), 65536, 16, 2, 50)
385+
tempPasswd, _ = scrypt.Key([]byte(passwd), saltBytes, 65536, 16, 2, 50)
370386
case algoArgon2:
371-
tempPasswd = argon2.IDKey([]byte(passwd), []byte(salt), 2, 65536, 8, 50)
387+
tempPasswd = argon2.IDKey([]byte(passwd), saltBytes, 2, 65536, 8, 50)
372388
case algoPbkdf2:
373389
fallthrough
374390
default:
375-
tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
391+
tempPasswd = pbkdf2.Key([]byte(passwd), saltBytes, 10000, 50, sha256.New)
376392
}
377393

378-
return fmt.Sprintf("%x", tempPasswd)
394+
return fmt.Sprintf("%x", tempPasswd), nil
379395
}
380396

381397
// SetPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO
@@ -391,15 +407,20 @@ func (u *User) SetPassword(passwd string) (err error) {
391407
if u.Salt, err = GetUserSalt(); err != nil {
392408
return err
393409
}
410+
if u.Passwd, err = hashPassword(passwd, u.Salt, setting.PasswordHashAlgo); err != nil {
411+
return err
412+
}
394413
u.PasswdHashAlgo = setting.PasswordHashAlgo
395-
u.Passwd = hashPassword(passwd, u.Salt, setting.PasswordHashAlgo)
396414

397415
return nil
398416
}
399417

400418
// ValidatePassword checks if given password matches the one belongs to the user.
401419
func (u *User) ValidatePassword(passwd string) bool {
402-
tempHash := hashPassword(passwd, u.Salt, u.PasswdHashAlgo)
420+
tempHash, err := hashPassword(passwd, u.Salt, u.PasswdHashAlgo)
421+
if err != nil {
422+
return false
423+
}
403424

404425
if u.PasswdHashAlgo != algoBcrypt && subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1 {
405426
return true
@@ -505,9 +526,19 @@ func IsUserExist(uid int64, name string) (bool, error) {
505526
return isUserExist(db.GetEngine(db.DefaultContext), uid, name)
506527
}
507528

529+
// Note: As of the beginning of 2022, it is recommended to use at least
530+
// 64 bits of salt, but NIST is already recommending to use to 128 bits.
531+
// (16 bytes = 16 * 8 = 128 bits)
532+
const SaltByteLength = 16
533+
508534
// GetUserSalt returns a random user salt token.
509535
func GetUserSalt() (string, error) {
510-
return util.RandomString(10)
536+
rBytes, err := util.RandomBytes(SaltByteLength)
537+
if err != nil {
538+
return "", err
539+
}
540+
// Returns a 32 bytes long string.
541+
return hex.EncodeToString(rBytes), nil
511542
}
512543

513544
// NewGhostUser creates and returns a fake user for someone has deleted his/her account.

modules/util/util.go

+11-2
Original file line numberDiff line numberDiff line change
@@ -139,11 +139,11 @@ func MergeInto(dict map[string]interface{}, values ...interface{}) (map[string]i
139139

140140
// RandomInt returns a random integer between 0 and limit, inclusive
141141
func RandomInt(limit int64) (int64, error) {
142-
int, err := rand.Int(rand.Reader, big.NewInt(limit))
142+
rInt, err := rand.Int(rand.Reader, big.NewInt(limit))
143143
if err != nil {
144144
return 0, err
145145
}
146-
return int.Int64(), nil
146+
return rInt.Int64(), nil
147147
}
148148

149149
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
@@ -161,3 +161,12 @@ func RandomString(length int64) (string, error) {
161161
}
162162
return string(bytes), nil
163163
}
164+
165+
// RandomBytes generates `length` bytes
166+
// This differs from RandomString, as RandomString is limits each byte to have
167+
// a maximum value of 63 instead of 255(max byte size)
168+
func RandomBytes(length int64) ([]byte, error) {
169+
bytes := make([]byte, length)
170+
_, err := rand.Read(bytes)
171+
return bytes, err
172+
}

modules/util/util_test.go

+18
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,24 @@ func Test_RandomString(t *testing.T) {
157157
assert.NotEqual(t, str3, str4)
158158
}
159159

160+
func Test_RandomBytes(t *testing.T) {
161+
bytes1, err := RandomBytes(32)
162+
assert.NoError(t, err)
163+
164+
bytes2, err := RandomBytes(32)
165+
assert.NoError(t, err)
166+
167+
assert.NotEqual(t, bytes1, bytes2)
168+
169+
bytes3, err := RandomBytes(256)
170+
assert.NoError(t, err)
171+
172+
bytes4, err := RandomBytes(256)
173+
assert.NoError(t, err)
174+
175+
assert.NotEqual(t, bytes3, bytes4)
176+
}
177+
160178
func Test_OptionalBool(t *testing.T) {
161179
assert.Equal(t, OptionalBoolNone, OptionalBoolParse(""))
162180
assert.Equal(t, OptionalBoolNone, OptionalBoolParse("x"))

services/auth/source/db/authenticate.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ func Authenticate(user *user_model.User, login, password string) (*user_model.Us
2121
}
2222

2323
// Update password hash if server password hash algorithm have changed
24-
if user.PasswdHashAlgo != setting.PasswordHashAlgo {
24+
// Or update the password when the salt length doesn't match the current
25+
// recommended salt length, this in order to migrate user's salts to a more secure salt.
26+
if user.PasswdHashAlgo != setting.PasswordHashAlgo || len(user.Salt) != user_model.SaltByteLength*2 {
2527
if err := user.SetPassword(password); err != nil {
2628
return nil, err
2729
}

0 commit comments

Comments
 (0)