feat: 资源密码加密处理&登录密码加密加强等

This commit is contained in:
meilin.huang
2022-08-02 21:44:01 +08:00
parent daa2ef5203
commit 12f8cf0111
33 changed files with 340 additions and 51 deletions

View File

@@ -29,7 +29,9 @@ jwt:
key:
# 过期时间单位分钟
expire-time: 1440
# 资源密码aes加密key
aes:
key: 1111111111111111
mysql:
host: localhost:3306
username: root

View File

@@ -3,10 +3,10 @@ module mayfly-go
go 1.18
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible // jwt
github.com/gin-gonic/gin v1.8.1
github.com/go-redis/redis/v8 v8.11.5
github.com/go-sql-driver/mysql v1.6.0
github.com/golang-jwt/jwt/v4 v4.4.2
github.com/gorilla/websocket v1.5.0
github.com/lib/pq v1.10.6
github.com/mojocn/base64Captcha v1.3.5 //
@@ -15,11 +15,11 @@ require (
github.com/sirupsen/logrus v1.9.0
github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2
go.mongodb.org/mongo-driver v1.9.1 // mongo
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // ssh
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa // ssh
gopkg.in/yaml.v3 v3.0.1
// gorm
gorm.io/driver/mysql v1.3.4
gorm.io/gorm v1.23.5
gorm.io/driver/mysql v1.3.5
gorm.io/gorm v1.23.8
)
require (
@@ -34,7 +34,7 @@ require (
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.4 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/kr/fs v0.1.0 // indirect

View File

@@ -0,0 +1,32 @@
package utils
import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/config"
)
// 使用config.yml的aes.key进行密码加密
func PwdAesEncrypt(password string) string {
if password == "" {
return ""
}
aes := config.Conf.Aes
if aes == nil {
return password
}
encryptPwd, err := aes.EncryptBase64([]byte(password))
biz.ErrIsNilAppendErr(err, "密码加密失败: %s")
return encryptPwd
}
// 使用config.yml的aes.key进行密码解密
func PwdAesDecrypt(encryptPwd string) string {
aes := config.Conf.Aes
if aes == nil {
return encryptPwd
}
decryptPwd, err := aes.DecryptBase64(encryptPwd)
biz.ErrIsNilAppendErr(err, "密码解密失败: %s")
// 解密后的密码
return string(decryptPwd)
}

View File

@@ -61,6 +61,14 @@ func (d *Db) Save(rc *ctx.ReqCtx) {
d.DbApp.Save(db)
}
// 获取数据库实例密码,由于数据库是加密存储,故提供该接口展示原文密码
func (d *Db) GetDbPwd(rc *ctx.ReqCtx) {
dbId := GetDbId(rc.GinCtx)
dbEntity := d.DbApp.GetById(dbId, "Password")
dbEntity.PwdDecrypt()
rc.ResData = dbEntity.Password
}
// 获取数据库实例的所有数据库名
func (d *Db) GetDatabaseNames(rc *ctx.ReqCtx) {
form := &form.DbForm{}

View File

@@ -72,6 +72,14 @@ func (m *Machine) SaveMachine(rc *ctx.ReqCtx) {
m.MachineApp.Save(me)
}
// 获取机器实例密码,由于数据库是加密存储,故提供该接口展示原文密码
func (m *Machine) GetMachinePwd(rc *ctx.ReqCtx) {
mid := GetMachineId(rc.GinCtx)
me := m.MachineApp.GetById(mid, "Password")
me.PwdDecrypt()
rc.ResData = me.Password
}
func (m *Machine) ChangeStatus(rc *ctx.ReqCtx) {
g := rc.GinCtx
id := uint64(ginx.PathParamInt(g, "machineId"))

View File

@@ -52,6 +52,14 @@ func (r *Redis) Save(rc *ctx.ReqCtx) {
r.RedisApp.Save(redis)
}
// 获取redis实例密码由于数据库是加密存储故提供该接口展示原文密码
func (r *Redis) GetRedisPwd(rc *ctx.ReqCtx) {
rid := uint64(ginx.PathParamInt(rc.GinCtx, "id"))
re := r.RedisApp.GetById(rid, "Password")
re.PwdDecrypt()
rc.ResData = re.Password
}
func (r *Redis) DeleteRedis(rc *ctx.ReqCtx) {
r.RedisApp.Delete(uint64(ginx.PathParamInt(rc.GinCtx, "id")))
}

View File

@@ -97,6 +97,7 @@ func (d *dbAppImpl) Save(dbEntity *entity.Db) {
if dbEntity.Id == 0 {
biz.NotEmpty(dbEntity.Password, "密码不能为空")
biz.IsTrue(err != nil, "该数据库实例已存在")
dbEntity.PwdEncrypt()
d.dbRepo.Insert(dbEntity)
return
}
@@ -129,6 +130,7 @@ func (d *dbAppImpl) Save(dbEntity *entity.Db) {
d.dbSqlRepo.DeleteBy(&entity.DbSql{DbId: dbId, Db: v.(string)})
}
dbEntity.PwdEncrypt()
d.dbRepo.Update(dbEntity)
}
@@ -184,6 +186,8 @@ func (da *dbAppImpl) GetDbInstance(id uint64, db string) *DbInstance {
defer mutex.Unlock()
d := da.GetById(id)
// 密码解密
d.PwdDecrypt()
biz.NotNil(d, "数据库信息不存在")
biz.IsTrue(strings.Contains(d.Database, db), "未配置该库的操作权限")

View File

@@ -69,11 +69,13 @@ func (m *machineAppImpl) Save(me *entity.Machine) {
}
// 关闭连接
machine.DeleteCli(me.Id)
me.PwdEncrypt()
m.machineRepo.UpdateById(me)
} else {
biz.IsTrue(err != nil, "该机器信息已存在")
// 新增机器,默认启用状态
me.Status = entity.MachineStatusEnable
me.PwdEncrypt()
m.machineRepo.Create(me)
}
}
@@ -123,6 +125,7 @@ func (m *machineAppImpl) GetById(id uint64, cols ...string) *entity.Machine {
func (m *machineAppImpl) GetCli(id uint64) *machine.Cli {
cli, err := machine.GetCli(id, func(machineId uint64) *entity.Machine {
machine := m.GetById(machineId)
machine.PwdDecrypt()
biz.IsTrue(machine.Status == entity.MachineStatusEnable, "该机器已被停用")
return machine
})
@@ -133,6 +136,7 @@ func (m *machineAppImpl) GetCli(id uint64) *machine.Cli {
func (m *machineAppImpl) GetSshTunnelMachine(id uint64) *machine.SshTunnelMachine {
sshTunnel, err := machine.GetSshTunnelMachine(id, func(machineId uint64) *entity.Machine {
machine := m.GetById(machineId)
machine.PwdDecrypt()
biz.IsTrue(machine.Status == entity.MachineStatusEnable, "该机器已被停用")
return machine
})

View File

@@ -80,6 +80,7 @@ func (r *redisAppImpl) Save(re *entity.Redis) {
if re.Id == 0 {
biz.IsTrue(err != nil, "该库已存在")
re.PwdEncrypt()
r.redisRepo.Insert(re)
} else {
// 如果存在该库,则校验修改的库是否为该库
@@ -88,6 +89,7 @@ func (r *redisAppImpl) Save(re *entity.Redis) {
}
// 先关闭数据库连接
CloseRedis(re.Id)
re.PwdEncrypt()
r.redisRepo.Update(re)
}
}
@@ -110,6 +112,7 @@ func (r *redisAppImpl) GetRedisInstance(id uint64) *RedisInstance {
}
// 缓存不存在则回调获取redis信息
re := r.GetById(id)
re.PwdDecrypt()
biz.NotNil(re, "redis信息不存在")
redisMode := re.Mode

View File

@@ -2,6 +2,7 @@ package entity
import (
"fmt"
"mayfly-go/internal/common/utils"
"mayfly-go/pkg/model"
)
@@ -27,9 +28,9 @@ type Db struct {
}
// 获取数据库连接网络, 若没有使用ssh隧道则直接返回。否则返回拼接的网络需要注册至指定dial
func (d Db) GetNetwork() string {
func (d *Db) GetNetwork() string {
network := d.Network
if d.EnableSshTunnel == -1 {
if d.EnableSshTunnel == 0 || d.EnableSshTunnel == -1 {
if network == "" {
return "tcp"
} else {
@@ -39,6 +40,16 @@ func (d Db) GetNetwork() string {
return fmt.Sprintf("%s+ssh:%d", d.Type, d.SshTunnelMachineId)
}
func (d *Db) PwdEncrypt() {
// 密码替换为加密后的密码
d.Password = utils.PwdAesEncrypt(d.Password)
}
func (d *Db) PwdDecrypt() {
// 密码替换为解密后的密码
d.Password = utils.PwdAesDecrypt(d.Password)
}
const (
DbTypeMysql = "mysql"
DbTypePostgres = "postgres"

View File

@@ -1,6 +1,7 @@
package entity
import (
"mayfly-go/internal/common/utils"
"mayfly-go/pkg/model"
)
@@ -26,3 +27,13 @@ const (
MachineAuthMethodPassword int8 = 1 // 密码登录
MachineAuthMethodPublicKey int8 = 2 // 公钥免密登录
)
func (m *Machine) PwdEncrypt() {
// 密码替换为加密后的密码
m.Password = utils.PwdAesEncrypt(m.Password)
}
func (m *Machine) PwdDecrypt() {
// 密码替换为解密后的密码
m.Password = utils.PwdAesDecrypt(m.Password)
}

View File

@@ -1,6 +1,7 @@
package entity
import (
"mayfly-go/internal/common/utils"
"mayfly-go/pkg/model"
)
@@ -24,3 +25,13 @@ const (
RedisModeStandalone = "standalone"
RedisModeCluster = "cluster"
)
func (r *Redis) PwdEncrypt() {
// 密码替换为加密后的密码
r.Password = utils.PwdAesEncrypt(r.Password)
}
func (r *Redis) PwdDecrypt() {
// 密码替换为解密后的密码
r.Password = utils.PwdAesDecrypt(r.Password)
}

View File

@@ -20,8 +20,7 @@ func InitDbRouter(router *gin.RouterGroup) {
}
// 获取所有数据库列表
db.GET("", func(c *gin.Context) {
rc := ctx.NewReqCtxWithGin(c)
rc.Handle(d.Dbs)
ctx.NewReqCtxWithGin(c).Handle(d.Dbs)
})
saveDb := ctx.NewLogInfo("保存数据库信息").WithSave(true)
@@ -31,11 +30,16 @@ func InitDbRouter(router *gin.RouterGroup) {
Handle(d.Save)
})
// 获取数据库实例的所有数据库名
db.POST("databases", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).
Handle(d.GetDatabaseNames)
})
db.GET(":dbId/pwd", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(d.GetDbPwd)
})
deleteDb := ctx.NewLogInfo("删除数据库信息").WithSave(true)
db.DELETE(":dbId", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).

View File

@@ -20,6 +20,10 @@ func InitMachineRouter(router *gin.RouterGroup) {
ctx.NewReqCtxWithGin(c).Handle(m.Machines)
})
machines.GET(":machineId/pwd", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(m.GetMachinePwd)
})
machines.GET(":machineId/stats", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(m.MachineStats)
})

View File

@@ -26,6 +26,10 @@ func InitRedisRouter(router *gin.RouterGroup) {
ctx.NewReqCtxWithGin(c).WithLog(save).Handle(rs.Save)
})
redis.GET(":id/pwd", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(rs.GetRedisPwd)
})
delRedis := ctx.NewLogInfo("删除redis信息").WithSave(true)
redis.DELETE(":id", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).WithLog(delRedis).Handle(rs.DeleteRedis)

View File

@@ -38,8 +38,10 @@ func (a *Account) Login(rc *ctx.ReqCtx) {
originPwd, err := utils.DefaultRsaDecrypt(loginForm.Password, true)
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
account := &entity.Account{Username: loginForm.Username, Password: utils.Md5(originPwd)}
biz.ErrIsNil(a.AccountApp.GetAccount(account, "Id", "Username", "Status", "LastLoginTime", "LastLoginIp"), "用户名或密码错误")
account := &entity.Account{Username: loginForm.Username}
err = a.AccountApp.GetAccount(account, "Id", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp")
biz.ErrIsNil(err, "用户名或密码错误")
biz.IsTrue(utils.CheckPwdHash(originPwd, account.Password), "用户名或密码错误")
biz.IsTrue(account.IsEnable(), "该账号不可用")
// 校验密码强度是否符合
@@ -86,8 +88,11 @@ func (a *Account) ChangePassword(rc *ctx.ReqCtx) {
originOldPwd, err := utils.DefaultRsaDecrypt(form.OldPassword, true)
biz.ErrIsNilAppendErr(err, "解密旧密码错误: %s")
account := &entity.Account{Username: form.Username, Password: utils.Md5(originOldPwd)}
biz.ErrIsNil(a.AccountApp.GetAccount(account, "Id", "Username", "Status"), "旧密码不正确")
account := &entity.Account{Username: form.Username}
err = a.AccountApp.GetAccount(account, "Id", "Username", "Password", "Status")
biz.ErrIsNil(err, "旧密码错误")
biz.IsTrue(utils.CheckPwdHash(originOldPwd, account.Password), "旧密码错误")
biz.IsTrue(account.IsEnable(), "该账号不可用")
originNewPwd, err := utils.DefaultRsaDecrypt(form.NewPassword, true)
biz.ErrIsNilAppendErr(err, "解密新密码错误: %s")
@@ -95,7 +100,7 @@ func (a *Account) ChangePassword(rc *ctx.ReqCtx) {
updateAccount := new(entity.Account)
updateAccount.Id = account.Id
updateAccount.Password = utils.Md5(originNewPwd)
updateAccount.Password = utils.PwdHash(originNewPwd)
a.AccountApp.Update(updateAccount)
// 赋值loginAccount 主要用于记录操作日志,因为操作日志保存请求上下文没有该信息不保存日志
@@ -176,7 +181,7 @@ func (a *Account) UpdateAccount(rc *ctx.ReqCtx) {
if updateAccount.Password != "" {
biz.IsTrue(CheckPasswordLever(updateAccount.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
updateAccount.Password = utils.Md5(updateAccount.Password)
updateAccount.Password = utils.PwdHash(updateAccount.Password)
}
a.AccountApp.Update(updateAccount)
}

View File

@@ -43,7 +43,7 @@ func (a *accountAppImpl) GetPageList(condition *entity.Account, pageParam *model
func (a *accountAppImpl) Create(account *entity.Account) {
biz.IsTrue(a.GetAccount(&entity.Account{Username: account.Username}) != nil, "该账号用户名已存在")
// 默认密码为账号用户名
account.Password = utils.Md5(account.Username)
account.Password = utils.PwdHash(account.Username)
account.Status = entity.AccountEnableStatus
a.accountRepo.Insert(account)
}

27
server/pkg/config/aes.go Normal file
View File

@@ -0,0 +1,27 @@
package config
import (
"fmt"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/assert"
)
type Aes struct {
Key string `yaml:"key"`
}
// 编码并base64
func (a *Aes) EncryptBase64(data []byte) (string, error) {
return utils.AesEncryptBase64(data, []byte(a.Key))
}
// base64解码后再aes解码
func (a *Aes) DecryptBase64(data string) ([]byte, error) {
return utils.AesDecryptBase64(data, []byte(a.Key))
}
func (j *Aes) Valid() {
aesKeyLen := len(j.Key)
assert.IsTrue(aesKeyLen == 16 || aesKeyLen == 24 || aesKeyLen == 32,
fmt.Sprintf("config.yml之 [aes.key] 长度需为16、24、32位长度, 当前为%d位", aesKeyLen))
}

View File

@@ -40,6 +40,7 @@ type Config struct {
App *App `yaml:"app"`
Server *Server `yaml:"server"`
Jwt *Jwt `yaml:"jwt"`
Aes *Aes `yaml:"aes"`
Redis *Redis `yaml:"redis"`
Mysql *Mysql `yaml:"mysql"`
Log *Log `yaml:"log"`
@@ -49,14 +50,7 @@ type Config struct {
func (c *Config) Valid() {
assert.IsTrue(c.Jwt != nil, "配置文件的[jwt]信息不能为空")
c.Jwt.Valid()
}
// 获取执行可执行文件时,指定的启动参数
func getStartConfig() *CmdConfigParam {
configFilePath := flag.String("e", "./config.yml", "配置文件路径,默认为可执行文件目录")
flag.Parse()
// 获取配置文件绝对路径
path, _ := filepath.Abs(*configFilePath)
sc := &CmdConfigParam{ConfigFilePath: path}
return sc
if c.Aes != nil {
c.Aes.Valid()
}
}

View File

@@ -10,7 +10,7 @@ import (
"mayfly-go/pkg/utils"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/golang-jwt/jwt/v4"
)
var (

View File

@@ -2,6 +2,8 @@ package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
@@ -10,6 +12,8 @@ import (
"encoding/hex"
"encoding/pem"
"errors"
"golang.org/x/crypto/bcrypt"
)
// md5
@@ -19,6 +23,17 @@ func Md5(str string) string {
return hex.EncodeToString(h.Sum(nil))
}
// bcrypt加密密码
func PwdHash(password string) string {
bytes, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes)
}
// 检查密码是否一致
func CheckPwdHash(password, hash string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
// 系统统一RSA秘钥对
var RsaPair []string
@@ -130,3 +145,84 @@ func GetRsaPrivateKey() (string, error) {
RsaPair = append(RsaPair, publicKey)
return privateKey, nil
}
//AesEncrypt 加密
func AesEncrypt(data []byte, key []byte) ([]byte, error) {
//创建加密实例
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//判断加密快的大小
blockSize := block.BlockSize()
//填充
encryptBytes := pkcs7Padding(data, blockSize)
//初始化加密数据接收切片
crypted := make([]byte, len(encryptBytes))
//使用cbc加密模式
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
//执行加密
blockMode.CryptBlocks(crypted, encryptBytes)
return crypted, nil
}
//AesDecrypt 解密
func AesDecrypt(data []byte, key []byte) ([]byte, error) {
//创建实例
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//获取块的大小
blockSize := block.BlockSize()
//使用cbc
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
//初始化解密数据接收切片
crypted := make([]byte, len(data))
//执行解密
blockMode.CryptBlocks(crypted, data)
//去除填充
crypted, err = pkcs7UnPadding(crypted)
if err != nil {
return nil, err
}
return crypted, nil
}
// aes加密 后 再base64
func AesEncryptBase64(data []byte, key []byte) (string, error) {
res, err := AesEncrypt(data, key)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(res), nil
}
// base64解码后再 aes解码
func AesDecryptBase64(data string, key []byte) ([]byte, error) {
dataByte, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return nil, err
}
return AesDecrypt(dataByte, key)
}
//pkcs7Padding 填充
func pkcs7Padding(data []byte, blockSize int) []byte {
//判断缺少几位长度。最少1最多 blockSize
padding := blockSize - len(data)%blockSize
//补足位数。把切片[]byte{byte(padding)}复制padding个
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
//pkcs7UnPadding 填充的反向操作
func pkcs7UnPadding(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, errors.New("加密字符串错误!")
}
//获取填充的个数
unPadding := int(data[length-1])
return data[:(length - unPadding)], nil
}

View File

@@ -1,10 +1,12 @@
相关配置文件:
后端:
config.yml: 服务端口mysql等信息在此配置即可。
config.yml: 服务端口mysqlaeskey(16 24 32位)jwtkey等信息在此配置即可。
建议务必将aes.key(资源密码加密如机器、数据库、redis等密码)与jwt.key(jwt秘钥)两信息使用随机字符串替换。
前端:
static/config.js: 若前后端分开部署则将该文件中的api地址配成后端服务的真实地址即可否则无需修改。
服务启动:./startup.sh
服务启动&重启./startup.sh
服务关闭:./shutdown.sh
直接通过 host:ip即可访问项目

View File

@@ -2,6 +2,12 @@
execfile=./mayfly-go
pid=`ps ax | grep -i 'mayfly-go' | grep -v grep | awk '{print $1}'`
if [ ! -z "${pid}" ] ; then
echo "The mayfly-go already running, shutdown and restart..."
kill ${pid}
fi
if [ ! -x "${execfile}" ]; then
sudo chmod +x "${execfile}"
fi