🔒️ more secure token generation
This commit is contained in:
parent
c027ae1396
commit
8ae885874b
2
.github/workflows/test.yml
vendored
2
.github/workflows/test.yml
vendored
@ -31,4 +31,4 @@ jobs:
|
|||||||
- name: Run Gosec Security Scanner
|
- name: Run Gosec Security Scanner
|
||||||
run: |
|
run: |
|
||||||
go install github.com/securego/gosec/v2/cmd/gosec@latest
|
go install github.com/securego/gosec/v2/cmd/gosec@latest
|
||||||
gosec -exclude=G104,G404 ./...
|
gosec -exclude=G104 ./...
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
<br>
|
<br>
|
||||||
<small><i>LOGO designed by <a href="https://xio.ng" target="_blank">熊大</a> .</i></small>
|
<small><i>LOGO designed by <a href="https://xio.ng" target="_blank">熊大</a> .</i></small>
|
||||||
<br><br>
|
<br><br>
|
||||||
<img src="https://img.shields.io/github/workflow/status/naiba/nezha/Dashboard%20image?label=Dash%20v0.14.7&logo=github&style=for-the-badge"> <img src="https://img.shields.io/github/v/release/naiba/nezha?color=brightgreen&label=Agent&style=for-the-badge&logo=github"> <img src="https://img.shields.io/github/workflow/status/naiba/nezha/Agent%20release?label=Agent%20CI&logo=github&style=for-the-badge"> <img src="https://img.shields.io/badge/Installer-v0.11.0-brightgreen?style=for-the-badge&logo=linux">
|
<img src="https://img.shields.io/github/workflow/status/naiba/nezha/Dashboard%20image?label=Dash%20v0.14.8&logo=github&style=for-the-badge"> <img src="https://img.shields.io/github/v/release/naiba/nezha?color=brightgreen&label=Agent&style=for-the-badge&logo=github"> <img src="https://img.shields.io/github/workflow/status/naiba/nezha/Agent%20release?label=Agent%20CI&logo=github&style=for-the-badge"> <img src="https://img.shields.io/badge/Installer-v0.11.1-brightgreen?style=for-the-badge&logo=linux">
|
||||||
<br>
|
<br>
|
||||||
<br>
|
<br>
|
||||||
<p>:trollface: <b>Nezha Monitoring: Self-hosted, lightweight server and website monitoring and O&M tool.</b></p>
|
<p>:trollface: <b>Nezha Monitoring: Self-hosted, lightweight server and website monitoring and O&M tool.</b></p>
|
||||||
|
@ -100,9 +100,17 @@ func (ma *memberAPI) issueNewToken(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
secureToken, err := utils.GenerateRandomString(32)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, model.Response{
|
||||||
|
Code: http.StatusBadRequest,
|
||||||
|
Message: fmt.Sprintf("请求错误:%s", err),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
token := &model.ApiToken{
|
token := &model.ApiToken{
|
||||||
UserID: u.ID,
|
UserID: u.ID,
|
||||||
Token: utils.MD5(fmt.Sprintf("%d%d%s", time.Now().UnixNano(), u.ID, u.Login)),
|
Token: secureToken,
|
||||||
Note: tf.Note,
|
Note: tf.Note,
|
||||||
}
|
}
|
||||||
singleton.DB.Create(token)
|
singleton.DB.Create(token)
|
||||||
@ -310,7 +318,6 @@ type serverForm struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ma *memberAPI) addOrEditServer(c *gin.Context) {
|
func (ma *memberAPI) addOrEditServer(c *gin.Context) {
|
||||||
admin := c.MustGet(model.CtxKeyAuthorizedUser).(*model.User)
|
|
||||||
var sf serverForm
|
var sf serverForm
|
||||||
var s model.Server
|
var s model.Server
|
||||||
var isEdit bool
|
var isEdit bool
|
||||||
@ -324,9 +331,10 @@ func (ma *memberAPI) addOrEditServer(c *gin.Context) {
|
|||||||
s.Note = sf.Note
|
s.Note = sf.Note
|
||||||
s.HideForGuest = sf.HideForGuest == "on"
|
s.HideForGuest = sf.HideForGuest == "on"
|
||||||
if s.ID == 0 {
|
if s.ID == 0 {
|
||||||
s.Secret = utils.MD5(fmt.Sprintf("%s%s%d", time.Now(), sf.Name, admin.ID))
|
s.Secret, err = utils.GenerateRandomString(18)
|
||||||
s.Secret = s.Secret[:18]
|
if err == nil {
|
||||||
err = singleton.DB.Create(&s).Error
|
err = singleton.DB.Create(&s).Error
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
isEdit = true
|
isEdit = true
|
||||||
err = singleton.DB.Save(&s).Error
|
err = singleton.DB.Save(&s).Error
|
||||||
|
@ -7,6 +7,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"code.gitea.io/sdk/gitea"
|
"code.gitea.io/sdk/gitea"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@ -92,7 +93,15 @@ func (oa *oauth2controller) getRedirectURL(c *gin.Context) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (oa *oauth2controller) login(c *gin.Context) {
|
func (oa *oauth2controller) login(c *gin.Context) {
|
||||||
randomString := utils.RandStringBytesMaskImprSrcUnsafe(32)
|
randomString, err := utils.GenerateRandomString(32)
|
||||||
|
if err != nil {
|
||||||
|
mygin.ShowErrorPage(c, mygin.ErrInfo{
|
||||||
|
Code: http.StatusBadRequest,
|
||||||
|
Title: "Something Wrong",
|
||||||
|
Msg: err.Error(),
|
||||||
|
}, true)
|
||||||
|
return
|
||||||
|
}
|
||||||
state, stateKey := randomString[:16], randomString[16:]
|
state, stateKey := randomString[:16], randomString[16:]
|
||||||
singleton.Cache.Set(fmt.Sprintf("%s%s", model.CacheKeyOauth2State, stateKey), state, cache.DefaultExpiration)
|
singleton.Cache.Set(fmt.Sprintf("%s%s", model.CacheKeyOauth2State, stateKey), state, cache.DefaultExpiration)
|
||||||
url := oa.getCommonOauth2Config(c).AuthCodeURL(state, oauth2.AccessTypeOnline)
|
url := oa.getCommonOauth2Config(c).AuthCodeURL(state, oauth2.AccessTypeOnline)
|
||||||
@ -195,7 +204,16 @@ func (oa *oauth2controller) callback(c *gin.Context) {
|
|||||||
}, true)
|
}, true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
user.IssueNewToken()
|
user.Token, err = utils.GenerateRandomString(32)
|
||||||
|
if err != nil {
|
||||||
|
mygin.ShowErrorPage(c, mygin.ErrInfo{
|
||||||
|
Code: http.StatusBadRequest,
|
||||||
|
Title: "Something wrong",
|
||||||
|
Msg: err.Error(),
|
||||||
|
}, true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user.TokenExpired = time.Now().AddDate(0, 2, 0)
|
||||||
singleton.DB.Save(&user)
|
singleton.DB.Save(&user)
|
||||||
c.SetCookie(singleton.Conf.Site.CookieName, user.Token, 60*60*24, "", "", false, false)
|
c.SetCookie(singleton.Conf.Site.CookieName, user.Token, 60*60*24, "", "", false, false)
|
||||||
c.HTML(http.StatusOK, "dashboard-"+singleton.Conf.Site.DashboardTheme+"/redirect", mygin.CommonEnvironment(c, gin.H{
|
c.HTML(http.StatusOK, "dashboard-"+singleton.Conf.Site.DashboardTheme+"/redirect", mygin.CommonEnvironment(c, gin.H{
|
||||||
|
@ -1,14 +1,11 @@
|
|||||||
package model
|
package model
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"code.gitea.io/sdk/gitea"
|
"code.gitea.io/sdk/gitea"
|
||||||
"github.com/google/go-github/v47/github"
|
"github.com/google/go-github/v47/github"
|
||||||
"github.com/xanzy/go-gitlab"
|
"github.com/xanzy/go-gitlab"
|
||||||
|
|
||||||
"github.com/naiba/nezha/pkg/utils"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
@ -72,8 +69,3 @@ func NewUserFromGitHub(gu *github.User) User {
|
|||||||
u.Bio = gu.GetBio()
|
u.Bio = gu.GetBio()
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *User) IssueNewToken() {
|
|
||||||
u.Token = utils.MD5(fmt.Sprintf("%d%d%s", time.Now().UnixNano(), u.ID, u.Login))
|
|
||||||
u.TokenExpired = time.Now().AddDate(0, 2, 0)
|
|
||||||
}
|
|
||||||
|
@ -1,53 +1,17 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/md5" // #nosec
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"math/big"
|
||||||
"math/rand"
|
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
jsoniter "github.com/json-iterator/go"
|
jsoniter "github.com/json-iterator/go"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Json = jsoniter.ConfigCompatibleWithStandardLibrary
|
var Json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||||
|
|
||||||
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
||||||
const (
|
|
||||||
letterIdxBits = 6 // 6 bits to represent a letter index
|
|
||||||
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
|
|
||||||
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
|
|
||||||
)
|
|
||||||
|
|
||||||
func RandStringBytesMaskImprSrcUnsafe(n int) string {
|
|
||||||
var src = rand.NewSource(time.Now().UnixNano())
|
|
||||||
b := make([]byte, n)
|
|
||||||
|
|
||||||
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
|
|
||||||
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
|
|
||||||
if remain == 0 {
|
|
||||||
cache, remain = src.Int63(), letterIdxMax
|
|
||||||
}
|
|
||||||
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
|
|
||||||
b[i] = letterBytes[idx]
|
|
||||||
i--
|
|
||||||
}
|
|
||||||
cache >>= letterIdxBits
|
|
||||||
remain--
|
|
||||||
}
|
|
||||||
|
|
||||||
return *(*string)(unsafe.Pointer(&b)) //#nosec
|
|
||||||
}
|
|
||||||
|
|
||||||
func MD5(plantext string) string {
|
|
||||||
hash := md5.New() // #nosec
|
|
||||||
hash.Write([]byte(plantext))
|
|
||||||
return hex.EncodeToString(hash.Sum(nil))
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsWindows() bool {
|
func IsWindows() bool {
|
||||||
return os.PathSeparator == '\\' && os.PathListSeparator == ';'
|
return os.PathSeparator == '\\' && os.PathListSeparator == ';'
|
||||||
}
|
}
|
||||||
@ -98,3 +62,17 @@ func IsFileExists(path string) bool {
|
|||||||
_, err := os.Stat(path)
|
_, err := os.Stat(path)
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GenerateRandomString(n int) (string, error) {
|
||||||
|
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||||
|
lettersLength := big.NewInt(int64(len(letters)))
|
||||||
|
ret := make([]byte, n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
num, err := rand.Int(rand.Reader, lettersLength)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
ret[i] = letters[num.Int64()]
|
||||||
|
}
|
||||||
|
return string(ret), nil
|
||||||
|
}
|
||||||
|
@ -39,3 +39,14 @@ func TestNotification(t *testing.T) {
|
|||||||
assert.Equal(t, IPDesensitize(c.input), c.output)
|
assert.Equal(t, IPDesensitize(c.input), c.output)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGenerGenerateRandomString(t *testing.T) {
|
||||||
|
generatedString := make(map[string]bool)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
str, err := GenerateRandomString(32)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, len(str), 32)
|
||||||
|
assert.False(t, generatedString[str])
|
||||||
|
generatedString[str] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -11,7 +11,7 @@ NZ_BASE_PATH="/opt/nezha"
|
|||||||
NZ_DASHBOARD_PATH="${NZ_BASE_PATH}/dashboard"
|
NZ_DASHBOARD_PATH="${NZ_BASE_PATH}/dashboard"
|
||||||
NZ_AGENT_PATH="${NZ_BASE_PATH}/agent"
|
NZ_AGENT_PATH="${NZ_BASE_PATH}/agent"
|
||||||
NZ_AGENT_SERVICE="/etc/systemd/system/nezha-agent.service"
|
NZ_AGENT_SERVICE="/etc/systemd/system/nezha-agent.service"
|
||||||
NZ_VERSION="v0.11.0"
|
NZ_VERSION="v0.11.1"
|
||||||
|
|
||||||
red='\033[0;31m'
|
red='\033[0;31m'
|
||||||
green='\033[0;32m'
|
green='\033[0;32m'
|
||||||
|
@ -11,7 +11,7 @@ NZ_BASE_PATH="/opt/nezha"
|
|||||||
NZ_DASHBOARD_PATH="${NZ_BASE_PATH}/dashboard"
|
NZ_DASHBOARD_PATH="${NZ_BASE_PATH}/dashboard"
|
||||||
NZ_AGENT_PATH="${NZ_BASE_PATH}/agent"
|
NZ_AGENT_PATH="${NZ_BASE_PATH}/agent"
|
||||||
NZ_AGENT_SERVICE="/etc/systemd/system/nezha-agent.service"
|
NZ_AGENT_SERVICE="/etc/systemd/system/nezha-agent.service"
|
||||||
NZ_VERSION="v0.11.0"
|
NZ_VERSION="v0.11.1"
|
||||||
|
|
||||||
red='\033[0;31m'
|
red='\033[0;31m'
|
||||||
green='\033[0;32m'
|
green='\033[0;32m'
|
||||||
|
@ -12,7 +12,7 @@ import (
|
|||||||
"github.com/naiba/nezha/pkg/utils"
|
"github.com/naiba/nezha/pkg/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Version = "v0.14.7" // !!记得修改 README 中的 badge 版本!!
|
var Version = "v0.14.8" // !!记得修改 README 中的 badge 版本!!
|
||||||
|
|
||||||
var (
|
var (
|
||||||
Conf *model.Config
|
Conf *model.Config
|
||||||
|
Loading…
Reference in New Issue
Block a user