diff options
Diffstat (limited to 'models')
-rw-r--r-- | models/error.go | 4 | ||||
-rw-r--r-- | models/fixtures/access_token.yml | 16 | ||||
-rw-r--r-- | models/migrations/migrations.go | 2 | ||||
-rw-r--r-- | models/migrations/v85.go | 135 | ||||
-rw-r--r-- | models/token.go | 51 | ||||
-rw-r--r-- | models/token_test.go | 9 |
6 files changed, 194 insertions, 23 deletions
diff --git a/models/error.go b/models/error.go index c3495b28d7..fe0f05d36b 100644 --- a/models/error.go +++ b/models/error.go @@ -507,7 +507,7 @@ func (err ErrDeployKeyNameAlreadyUsed) Error() string { // ErrAccessTokenNotExist represents a "AccessTokenNotExist" kind of error. type ErrAccessTokenNotExist struct { - SHA string + Token string } // IsErrAccessTokenNotExist checks if an error is a ErrAccessTokenNotExist. @@ -517,7 +517,7 @@ func IsErrAccessTokenNotExist(err error) bool { } func (err ErrAccessTokenNotExist) Error() string { - return fmt.Sprintf("access token does not exist [sha: %s]", err.SHA) + return fmt.Sprintf("access token does not exist [sha: %s]", err.Token) } // ErrAccessTokenEmpty represents a "AccessTokenEmpty" kind of error. diff --git a/models/fixtures/access_token.yml b/models/fixtures/access_token.yml index 9572709dd9..5ff5d66f66 100644 --- a/models/fixtures/access_token.yml +++ b/models/fixtures/access_token.yml @@ -2,7 +2,10 @@ id: 1 uid: 1 name: Token A - sha1: hash1 + #token: d2c6c1ba3890b309189a8e618c72a162e4efbf36 + token_hash: 2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f + token_salt: QuSiZr1byZ + token_last_eight: e4efbf36 created_unix: 946687980 updated_unix: 946687980 @@ -10,7 +13,10 @@ id: 2 uid: 1 name: Token B - sha1: hash2 + #token: 4c6f36e6cf498e2a448662f915d932c09c5a146c + token_hash: 1a0e32a231ebbd582dc626c1543a42d3c63d4fa76c07c72862721467c55e8f81c923d60700f0528b5f5f443f055559d3a279 + token_salt: Lfwopukrq5 + token_last_eight: 9c5a146c created_unix: 946687980 updated_unix: 946687980 @@ -18,6 +24,10 @@ id: 3 uid: 2 name: Token A - sha1: hash3 + #token: 90a18faa671dc43924b795806ffe4fd169d28c91 + token_hash: d6d404048048812d9e911d93aefbe94fc768d4876fdf75e3bef0bdc67828e0af422846d3056f2f25ec35c51dc92075685ec5 + token_salt: 99ArgXKlQQ + token_last_eight: 69d28c91 created_unix: 946687980 updated_unix: 946687980 +#commented out tokens so you can see what they are in plaintext
\ No newline at end of file diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 62c41fb906..1d8cf65785 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -223,6 +223,8 @@ var migrations = []Migration{ NewMigration("add uploader id for table attachment", addUploaderIDForAttachment), // v84 -> v85 NewMigration("add table to store original imported gpg keys", addGPGKeyImport), + // v85 -> v86 + NewMigration("hash application token", hashAppToken), } // Migrate database to current version diff --git a/models/migrations/v85.go b/models/migrations/v85.go new file mode 100644 index 0000000000..28f6ac146d --- /dev/null +++ b/models/migrations/v85.go @@ -0,0 +1,135 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package migrations + +import ( + "fmt" + + "github.com/go-xorm/core" + "github.com/go-xorm/xorm" + + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/generate" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/util" +) + +func hashAppToken(x *xorm.Engine) error { + // AccessToken see models/token.go + type AccessToken struct { + ID int64 `xorm:"pk autoincr"` + UID int64 `xorm:"INDEX"` + Name string + Sha1 string + Token string `xorm:"-"` + TokenHash string `xorm:"UNIQUE"` // sha256 of token + TokenSalt string + TokenLastEight string `xorm:"token_last_eight"` + + CreatedUnix util.TimeStamp `xorm:"INDEX created"` + UpdatedUnix util.TimeStamp `xorm:"INDEX updated"` + HasRecentActivity bool `xorm:"-"` + HasUsed bool `xorm:"-"` + } + + // First remove the index + sess := x.NewSession() + defer sess.Close() + if err := sess.Begin(); err != nil { + return err + } + + var err error + if models.DbCfg.Type == core.POSTGRES || models.DbCfg.Type == core.SQLITE { + _, err = sess.Exec("DROP INDEX IF EXISTS UQE_access_token_sha1") + } else if models.DbCfg.Type == core.MSSQL { + _, err = sess.Exec(`DECLARE @ConstraintName VARCHAR(256) + DECLARE @SQL NVARCHAR(256) + SELECT @ConstraintName = obj.name FROM sys.columns col LEFT OUTER JOIN sys.objects obj ON obj.object_id = col.default_object_id AND obj.type = 'D' WHERE col.object_id = OBJECT_ID('access_token') AND obj.name IS NOT NULL AND col.name = 'sha1' + SET @SQL = N'ALTER TABLE [access_token] DROP CONSTRAINT [' + @ConstraintName + N']' + EXEC sp_executesql @SQL`) + } else if models.DbCfg.Type == core.MYSQL { + indexes, err := sess.QueryString(`SHOW INDEX FROM access_token WHERE KEY_NAME = 'UQE_access_token_sha1'`) + if err != nil { + return err + } + + if len(indexes) >= 1 { + _, err = sess.Exec("DROP INDEX UQE_access_token_sha1 ON access_token") + } + } else { + _, err = sess.Exec("DROP INDEX UQE_access_token_sha1 ON access_token") + } + if err != nil { + return fmt.Errorf("Drop index failed: %v", err) + } + + if err = sess.Commit(); err != nil { + return err + } + + if err := sess.Begin(); err != nil { + return err + } + + if err := x.Sync2(new(AccessToken)); err != nil { + return fmt.Errorf("Sync2: %v", err) + } + + if err = sess.Commit(); err != nil { + return err + } + + if err := sess.Begin(); err != nil { + return err + } + + // transform all tokens to hashes + const batchSize = 100 + for start := 0; ; start += batchSize { + tokens := make([]*AccessToken, 0, batchSize) + if err := sess.Limit(batchSize, start).Find(&tokens); err != nil { + return err + } + if len(tokens) == 0 { + break + } + + for _, token := range tokens { + // generate salt + salt, err := generate.GetRandomString(10) + if err != nil { + return err + } + token.TokenSalt = salt + token.TokenHash = hashToken(token.Sha1, salt) + if len(token.Sha1) < 8 { + log.Warn("Unable to transform token %s with name %s belonging to user ID %d, skipping transformation", token.Sha1, token.Name, token.UID) + continue + } + token.TokenLastEight = token.Sha1[len(token.Sha1)-8:] + token.Sha1 = "" // ensure to blank out column in case drop column doesn't work + + if _, err := sess.ID(token.ID).Cols("token_hash, token_salt, token_last_eight, sha1").Update(token); err != nil { + return fmt.Errorf("couldn't add in sha1, token_hash, token_salt and token_last_eight: %v", err) + } + + } + } + + // Commit and begin new transaction for dropping columns + if err := sess.Commit(); err != nil { + return err + } + if err := sess.Begin(); err != nil { + return err + } + + if err := dropTableColumns(sess, "access_token", "sha1"); err != nil { + return err + } + return sess.Commit() + +} diff --git a/models/token.go b/models/token.go index 8393a7cf11..030bff8e1b 100644 --- a/models/token.go +++ b/models/token.go @@ -1,24 +1,30 @@ // Copyright 2014 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package models import ( + "crypto/subtle" "time" gouuid "github.com/satori/go.uuid" "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/generate" "code.gitea.io/gitea/modules/util" ) // AccessToken represents a personal access token. type AccessToken struct { - ID int64 `xorm:"pk autoincr"` - UID int64 `xorm:"INDEX"` - Name string - Sha1 string `xorm:"UNIQUE VARCHAR(40)"` + ID int64 `xorm:"pk autoincr"` + UID int64 `xorm:"INDEX"` + Name string + Token string `xorm:"-"` + TokenHash string `xorm:"UNIQUE"` // sha256 of token + TokenSalt string + TokenLastEight string `xorm:"token_last_eight"` CreatedUnix util.TimeStamp `xorm:"INDEX created"` UpdatedUnix util.TimeStamp `xorm:"INDEX updated"` @@ -34,24 +40,41 @@ func (t *AccessToken) AfterLoad() { // NewAccessToken creates new access token. func NewAccessToken(t *AccessToken) error { - t.Sha1 = base.EncodeSha1(gouuid.NewV4().String()) - _, err := x.Insert(t) + salt, err := generate.GetRandomString(10) + if err != nil { + return err + } + t.TokenSalt = salt + t.Token = base.EncodeSha1(gouuid.NewV4().String()) + t.TokenHash = hashToken(t.Token, t.TokenSalt) + t.TokenLastEight = t.Token[len(t.Token)-8:] + _, err = x.Insert(t) return err } -// GetAccessTokenBySHA returns access token by given sha1. -func GetAccessTokenBySHA(sha string) (*AccessToken, error) { - if sha == "" { +// GetAccessTokenBySHA returns access token by given token value +func GetAccessTokenBySHA(token string) (*AccessToken, error) { + if token == "" { return nil, ErrAccessTokenEmpty{} } - t := &AccessToken{Sha1: sha} - has, err := x.Get(t) + if len(token) < 8 { + return nil, ErrAccessTokenNotExist{token} + } + var tokens []AccessToken + lastEight := token[len(token)-8:] + err := x.Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens) if err != nil { return nil, err - } else if !has { - return nil, ErrAccessTokenNotExist{sha} + } else if len(tokens) == 0 { + return nil, ErrAccessTokenNotExist{token} + } + for _, t := range tokens { + tempHash := hashToken(token, t.TokenSalt) + if subtle.ConstantTimeCompare([]byte(t.TokenHash), []byte(tempHash)) == 1 { + return &t, nil + } } - return t, nil + return nil, ErrAccessTokenNotExist{token} } // ListAccessTokens returns a list of access tokens belongs to given user. diff --git a/models/token_test.go b/models/token_test.go index 540bd40deb..9f2699a168 100644 --- a/models/token_test.go +++ b/models/token_test.go @@ -29,11 +29,12 @@ func TestNewAccessToken(t *testing.T) { func TestGetAccessTokenBySHA(t *testing.T) { assert.NoError(t, PrepareTestDatabase()) - token, err := GetAccessTokenBySHA("hash1") + token, err := GetAccessTokenBySHA("d2c6c1ba3890b309189a8e618c72a162e4efbf36") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) assert.Equal(t, "Token A", token.Name) - assert.Equal(t, "hash1", token.Sha1) + assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash) + assert.Equal(t, "e4efbf36", token.TokenLastEight) token, err = GetAccessTokenBySHA("notahash") assert.Error(t, err) @@ -69,7 +70,7 @@ func TestListAccessTokens(t *testing.T) { func TestUpdateAccessToken(t *testing.T) { assert.NoError(t, PrepareTestDatabase()) - token, err := GetAccessTokenBySHA("hash2") + token, err := GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) token.Name = "Token Z" @@ -80,7 +81,7 @@ func TestUpdateAccessToken(t *testing.T) { func TestDeleteAccessTokenByID(t *testing.T) { assert.NoError(t, PrepareTestDatabase()) - token, err := GetAccessTokenBySHA("hash2") + token, err := GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) |