THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Browse Source

Implements generator cli for secrets (#3531)

Signed-off-by: Codruț Constantin Gușoi <codrut.gusoi@gmail.com>
tags/v1.5.0-dev
Codruț Constantin Gușoi 1 year ago
parent
commit
96c268c0fc

+ 83
- 0
cmd/generate.go View File

@@ -0,0 +1,83 @@
1
+// Copyright 2016 The Gogs Authors. All rights reserved.
2
+// Copyright 2016 The Gitea Authors. All rights reserved.
3
+// Use of this source code is governed by a MIT-style
4
+// license that can be found in the LICENSE file.
5
+
6
+package cmd
7
+
8
+import (
9
+	"fmt"
10
+
11
+	"code.gitea.io/gitea/modules/generate"
12
+
13
+	"github.com/urfave/cli"
14
+)
15
+
16
+var (
17
+	// CmdGenerate represents the available generate sub-command.
18
+	CmdGenerate = cli.Command{
19
+		Name:  "generate",
20
+		Usage: "Command line interface for running generators",
21
+		Subcommands: []cli.Command{
22
+			subcmdSecret,
23
+		},
24
+	}
25
+
26
+	subcmdSecret = cli.Command{
27
+		Name:  "secret",
28
+		Usage: "Generate a secret token",
29
+		Subcommands: []cli.Command{
30
+			microcmdGenerateInternalToken,
31
+			microcmdGenerateLfsJwtSecret,
32
+			microcmdGenerateSecretKey,
33
+		},
34
+	}
35
+
36
+	microcmdGenerateInternalToken = cli.Command{
37
+		Name:   "INTERNAL_TOKEN",
38
+		Usage:  "Generate a new INTERNAL_TOKEN",
39
+		Action: runGenerateInternalToken,
40
+	}
41
+
42
+	microcmdGenerateLfsJwtSecret = cli.Command{
43
+		Name:   "LFS_JWT_SECRET",
44
+		Usage:  "Generate a new LFS_JWT_SECRET",
45
+		Action: runGenerateLfsJwtSecret,
46
+	}
47
+
48
+	microcmdGenerateSecretKey = cli.Command{
49
+		Name:   "SECRET_KEY",
50
+		Usage:  "Generate a new SECRET_KEY",
51
+		Action: runGenerateSecretKey,
52
+	}
53
+)
54
+
55
+func runGenerateInternalToken(c *cli.Context) error {
56
+	internalToken, err := generate.NewInternalToken()
57
+	if err != nil {
58
+		return err
59
+	}
60
+
61
+	fmt.Printf("%s\n", internalToken)
62
+	return nil
63
+}
64
+
65
+func runGenerateLfsJwtSecret(c *cli.Context) error {
66
+	JWTSecretBase64, err := generate.NewLfsJwtSecret()
67
+	if err != nil {
68
+		return err
69
+	}
70
+
71
+	fmt.Printf("%s\n", JWTSecretBase64)
72
+	return nil
73
+}
74
+
75
+func runGenerateSecretKey(c *cli.Context) error {
76
+	secretKey, err := generate.NewSecretKey()
77
+	if err != nil {
78
+		return err
79
+	}
80
+
81
+	fmt.Printf("%s\n", secretKey)
82
+	return nil
83
+}

+ 1
- 0
main.go View File

@@ -45,6 +45,7 @@ arguments - which can alternatively be run by running the subcommand web.`
45 45
 		cmd.CmdDump,
46 46
 		cmd.CmdCert,
47 47
 		cmd.CmdAdmin,
48
+		cmd.CmdGenerate,
48 49
 	}
49 50
 	app.Flags = append(app.Flags, []cli.Flag{}...)
50 51
 	app.Action = cmd.CmdWeb.Action

+ 3
- 3
models/migrations/migrations.go View File

@@ -20,7 +20,7 @@ import (
20 20
 	gouuid "github.com/satori/go.uuid"
21 21
 	"gopkg.in/ini.v1"
22 22
 
23
-	"code.gitea.io/gitea/modules/base"
23
+	"code.gitea.io/gitea/modules/generate"
24 24
 	"code.gitea.io/gitea/modules/log"
25 25
 	"code.gitea.io/gitea/modules/setting"
26 26
 )
@@ -539,10 +539,10 @@ func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
539 539
 	}
540 540
 
541 541
 	for _, org := range orgs {
542
-		if org.Rands, err = base.GetRandomString(10); err != nil {
542
+		if org.Rands, err = generate.GetRandomString(10); err != nil {
543 543
 			return err
544 544
 		}
545
-		if org.Salt, err = base.GetRandomString(10); err != nil {
545
+		if org.Salt, err = generate.GetRandomString(10); err != nil {
546 546
 			return err
547 547
 		}
548 548
 		if _, err = sess.Id(org.ID).Update(org); err != nil {

+ 2
- 2
models/twofactor.go View File

@@ -16,7 +16,7 @@ import (
16 16
 
17 17
 	"github.com/pquerna/otp/totp"
18 18
 
19
-	"code.gitea.io/gitea/modules/base"
19
+	"code.gitea.io/gitea/modules/generate"
20 20
 	"code.gitea.io/gitea/modules/setting"
21 21
 	"code.gitea.io/gitea/modules/util"
22 22
 )
@@ -33,7 +33,7 @@ type TwoFactor struct {
33 33
 
34 34
 // GenerateScratchToken recreates the scratch token the user is using.
35 35
 func (t *TwoFactor) GenerateScratchToken() error {
36
-	token, err := base.GetRandomString(8)
36
+	token, err := generate.GetRandomString(8)
37 37
 	if err != nil {
38 38
 		return err
39 39
 	}

+ 2
- 1
models/user.go View File

@@ -34,6 +34,7 @@ import (
34 34
 
35 35
 	"code.gitea.io/gitea/modules/avatar"
36 36
 	"code.gitea.io/gitea/modules/base"
37
+	"code.gitea.io/gitea/modules/generate"
37 38
 	"code.gitea.io/gitea/modules/log"
38 39
 	"code.gitea.io/gitea/modules/setting"
39 40
 	"code.gitea.io/gitea/modules/util"
@@ -638,7 +639,7 @@ func IsUserExist(uid int64, name string) (bool, error) {
638 639
 
639 640
 // GetUserSalt returns a random user salt token.
640 641
 func GetUserSalt() (string, error) {
641
-	return base.GetRandomString(10)
642
+	return generate.GetRandomString(10)
642 643
 }
643 644
 
644 645
 // NewGhostUser creates and returns a fake user for someone has deleted his/her account.

+ 0
- 29
modules/base/tool.go View File

@@ -14,7 +14,6 @@ import (
14 14
 	"html/template"
15 15
 	"io"
16 16
 	"math"
17
-	"math/big"
18 17
 	"net/http"
19 18
 	"net/url"
20 19
 	"path"
@@ -88,25 +87,6 @@ func BasicAuthEncode(username, password string) string {
88 87
 	return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
89 88
 }
90 89
 
91
-// GetRandomString generate random string by specify chars.
92
-func GetRandomString(n int) (string, error) {
93
-	const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
94
-
95
-	buffer := make([]byte, n)
96
-	max := big.NewInt(int64(len(alphanum)))
97
-
98
-	for i := 0; i < n; i++ {
99
-		index, err := randomInt(max)
100
-		if err != nil {
101
-			return "", err
102
-		}
103
-
104
-		buffer[i] = alphanum[index]
105
-	}
106
-
107
-	return string(buffer), nil
108
-}
109
-
110 90
 // GetRandomBytesAsBase64 generates a random base64 string from n bytes
111 91
 func GetRandomBytesAsBase64(n int) string {
112 92
 	bytes := make([]byte, 32)
@@ -119,15 +99,6 @@ func GetRandomBytesAsBase64(n int) string {
119 99
 	return base64.RawURLEncoding.EncodeToString(bytes)
120 100
 }
121 101
 
122
-func randomInt(max *big.Int) (int, error) {
123
-	rand, err := rand.Int(rand.Reader, max)
124
-	if err != nil {
125
-		return 0, err
126
-	}
127
-
128
-	return int(rand.Int64()), nil
129
-}
130
-
131 102
 // VerifyTimeLimitCode verify time limit code
132 103
 func VerifyTimeLimitCode(data string, minutes int, code string) bool {
133 104
 	if len(code) <= 18 {

+ 0
- 6
modules/base/tool_test.go View File

@@ -107,12 +107,6 @@ func TestBasicAuthEncode(t *testing.T) {
107 107
 	assert.Equal(t, "Zm9vOmJhcg==", BasicAuthEncode("foo", "bar"))
108 108
 }
109 109
 
110
-func TestGetRandomString(t *testing.T) {
111
-	randomString, err := GetRandomString(4)
112
-	assert.NoError(t, err)
113
-	assert.Len(t, randomString, 4)
114
-}
115
-
116 110
 // TODO: Test PBKDF2()
117 111
 // TODO: Test VerifyTimeLimitCode()
118 112
 // TODO: Test CreateTimeLimitCode()

+ 89
- 0
modules/generate/generate.go View File

@@ -0,0 +1,89 @@
1
+// Copyright 2016 The Gogs Authors. All rights reserved.
2
+// Copyright 2016 The Gitea Authors. All rights reserved.
3
+// Use of this source code is governed by a MIT-style
4
+// license that can be found in the LICENSE file.
5
+
6
+package generate
7
+
8
+import (
9
+	"crypto/rand"
10
+	"encoding/base64"
11
+	"io"
12
+	"math/big"
13
+	"time"
14
+
15
+	"github.com/dgrijalva/jwt-go"
16
+)
17
+
18
+// GetRandomString generate random string by specify chars.
19
+func GetRandomString(n int) (string, error) {
20
+	const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
21
+
22
+	buffer := make([]byte, n)
23
+	max := big.NewInt(int64(len(alphanum)))
24
+
25
+	for i := 0; i < n; i++ {
26
+		index, err := randomInt(max)
27
+		if err != nil {
28
+			return "", err
29
+		}
30
+
31
+		buffer[i] = alphanum[index]
32
+	}
33
+
34
+	return string(buffer), nil
35
+}
36
+
37
+// NewInternalToken generate a new value intended to be used by INTERNAL_TOKEN.
38
+func NewInternalToken() (string, error) {
39
+	secretBytes := make([]byte, 32)
40
+	_, err := io.ReadFull(rand.Reader, secretBytes)
41
+	if err != nil {
42
+		return "", err
43
+	}
44
+
45
+	secretKey := base64.RawURLEncoding.EncodeToString(secretBytes)
46
+
47
+	now := time.Now()
48
+
49
+	var internalToken string
50
+	internalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
51
+		"nbf": now.Unix(),
52
+	}).SignedString([]byte(secretKey))
53
+	if err != nil {
54
+		return "", err
55
+	}
56
+
57
+	return internalToken, nil
58
+}
59
+
60
+// NewLfsJwtSecret generate a new value intended to be used by LFS_JWT_SECRET.
61
+func NewLfsJwtSecret() (string, error) {
62
+	JWTSecretBytes := make([]byte, 32)
63
+	_, err := io.ReadFull(rand.Reader, JWTSecretBytes)
64
+	if err != nil {
65
+		return "", err
66
+	}
67
+
68
+	JWTSecretBase64 := base64.RawURLEncoding.EncodeToString(JWTSecretBytes)
69
+	return JWTSecretBase64, nil
70
+}
71
+
72
+// NewSecretKey generate a new value intended to be used by SECRET_KEY.
73
+func NewSecretKey() (string, error) {
74
+	secretKey, err := GetRandomString(64)
75
+	if err != nil {
76
+		return "", err
77
+	}
78
+
79
+	return secretKey, nil
80
+}
81
+
82
+func randomInt(max *big.Int) (int, error) {
83
+	rand, err := rand.Int(rand.Reader, max)
84
+	if err != nil {
85
+		return 0, err
86
+	}
87
+
88
+	return int(rand.Int64()), nil
89
+}

+ 20
- 0
modules/generate/generate_test.go View File

@@ -0,0 +1,20 @@
1
+package generate
2
+
3
+import (
4
+	"os"
5
+	"testing"
6
+
7
+	"github.com/stretchr/testify/assert"
8
+)
9
+
10
+func TestMain(m *testing.M) {
11
+	retVal := m.Run()
12
+
13
+	os.Exit(retVal)
14
+}
15
+
16
+func TestGetRandomString(t *testing.T) {
17
+	randomString, err := GetRandomString(4)
18
+	assert.NoError(t, err)
19
+	assert.Len(t, randomString, 4)
20
+}

+ 5
- 23
modules/setting/setting.go View File

@@ -6,10 +6,8 @@
6 6
 package setting
7 7
 
8 8
 import (
9
-	"crypto/rand"
10 9
 	"encoding/base64"
11 10
 	"fmt"
12
-	"io"
13 11
 	"net"
14 12
 	"net/mail"
15 13
 	"net/url"
@@ -24,12 +22,12 @@ import (
24 22
 	"time"
25 23
 
26 24
 	"code.gitea.io/git"
25
+	"code.gitea.io/gitea/modules/generate"
27 26
 	"code.gitea.io/gitea/modules/log"
28 27
 	_ "code.gitea.io/gitea/modules/minwinsvc" // import minwinsvc for windows services
29 28
 	"code.gitea.io/gitea/modules/user"
30 29
 
31 30
 	"github.com/Unknwon/com"
32
-	"github.com/dgrijalva/jwt-go"
33 31
 	_ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
34 32
 	_ "github.com/go-macaron/cache/redis"
35 33
 	"github.com/go-macaron/session"
@@ -834,16 +832,12 @@ func NewContext() {
834 832
 		n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
835 833
 
836 834
 		if err != nil || n != 32 {
837
-			//Generate new secret and save to config
838
-
839
-			_, err := io.ReadFull(rand.Reader, LFS.JWTSecretBytes)
840
-
835
+			LFS.JWTSecretBase64, err = generate.NewLfsJwtSecret()
841 836
 			if err != nil {
842
-				log.Fatal(4, "Error reading random bytes: %v", err)
837
+				log.Fatal(4, "Error generating JWT Secret for custom config: %v", err)
838
+				return
843 839
 			}
844 840
 
845
-			LFS.JWTSecretBase64 = base64.RawURLEncoding.EncodeToString(LFS.JWTSecretBytes)
846
-
847 841
 			// Save secret
848 842
 			cfg := ini.Empty()
849 843
 			if com.IsFile(CustomConf) {
@@ -913,19 +907,7 @@ func NewContext() {
913 907
 	DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(false)
914 908
 	InternalToken = sec.Key("INTERNAL_TOKEN").String()
915 909
 	if len(InternalToken) == 0 {
916
-		secretBytes := make([]byte, 32)
917
-		_, err := io.ReadFull(rand.Reader, secretBytes)
918
-		if err != nil {
919
-			log.Fatal(4, "Error reading random bytes: %v", err)
920
-		}
921
-
922
-		secretKey := base64.RawURLEncoding.EncodeToString(secretBytes)
923
-
924
-		now := time.Now()
925
-		InternalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
926
-			"nbf": now.Unix(),
927
-		}).SignedString([]byte(secretKey))
928
-
910
+		InternalToken, err = generate.NewInternalToken()
929 911
 		if err != nil {
930 912
 			log.Fatal(4, "Error generate internal token: %v", err)
931 913
 		}

+ 8
- 2
routers/install.go View File

@@ -20,6 +20,7 @@ import (
20 20
 	"code.gitea.io/gitea/modules/auth"
21 21
 	"code.gitea.io/gitea/modules/base"
22 22
 	"code.gitea.io/gitea/modules/context"
23
+	"code.gitea.io/gitea/modules/generate"
23 24
 	"code.gitea.io/gitea/modules/log"
24 25
 	"code.gitea.io/gitea/modules/setting"
25 26
 	"code.gitea.io/gitea/modules/user"
@@ -275,7 +276,12 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
275 276
 	if form.LFSRootPath != "" {
276 277
 		cfg.Section("server").Key("LFS_START_SERVER").SetValue("true")
277 278
 		cfg.Section("server").Key("LFS_CONTENT_PATH").SetValue(form.LFSRootPath)
278
-		cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(base.GetRandomBytesAsBase64(32))
279
+		var secretKey string
280
+		if secretKey, err = generate.NewLfsJwtSecret(); err != nil {
281
+			ctx.RenderWithErr(ctx.Tr("install.lfs_jwt_secret_failed", err), tplInstall, &form)
282
+			return
283
+		}
284
+		cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(secretKey)
279 285
 	} else {
280 286
 		cfg.Section("server").Key("LFS_START_SERVER").SetValue("false")
281 287
 	}
@@ -315,7 +321,7 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
315 321
 
316 322
 	cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
317 323
 	var secretKey string
318
-	if secretKey, err = base.GetRandomString(10); err != nil {
324
+	if secretKey, err = generate.NewSecretKey(); err != nil {
319 325
 		ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, &form)
320 326
 		return
321 327
 	}

+ 2
- 1
routers/user/auth_openid.go View File

@@ -13,6 +13,7 @@ import (
13 13
 	"code.gitea.io/gitea/modules/auth/openid"
14 14
 	"code.gitea.io/gitea/modules/base"
15 15
 	"code.gitea.io/gitea/modules/context"
16
+	"code.gitea.io/gitea/modules/generate"
16 17
 	"code.gitea.io/gitea/modules/log"
17 18
 	"code.gitea.io/gitea/modules/setting"
18 19
 
@@ -348,7 +349,7 @@ func RegisterOpenIDPost(ctx *context.Context, cpt *captcha.Captcha, form auth.Si
348 349
 	if len < 256 {
349 350
 		len = 256
350 351
 	}
351
-	password, err := base.GetRandomString(len)
352
+	password, err := generate.GetRandomString(len)
352 353
 	if err != nil {
353 354
 		ctx.RenderWithErr(err.Error(), tplSignUpOID, form)
354 355
 		return

Loading…
Cancel
Save