Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: change rand lib(math/rand => crypto/rand) #465

Merged
merged 1 commit into from
May 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions pkg/bastion/dbinit.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package bastion // import "moul.io/sshportal/pkg/bastion"

import (
"crypto/rand"
"fmt"
"io/ioutil"
"log"
"math/rand"
"math/big"
"os"
"os/user"
"strings"
Expand Down Expand Up @@ -617,7 +618,10 @@ func DBInit(db *gorm.DB) error {
}
if count == 0 {
// if no admin, create an account for the first connection
inviteToken := randStringBytes(16)
inviteToken, err := randStringBytes(16)
if err != nil {
return err
}
if os.Getenv("SSHPORTAL_DEFAULT_ADMIN_INVITE_TOKEN") != "" {
inviteToken = os.Getenv("SSHPORTAL_DEFAULT_ADMIN_INVITE_TOKEN")
}
Expand Down Expand Up @@ -673,12 +677,16 @@ func DBInit(db *gorm.DB) error {
}).Error
}

func randStringBytes(n int) string {
func randStringBytes(n int) (string, error) {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
r, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes))))
if err != nil {
return "", fmt.Errorf("failed to generate random string: %s", err)
}
b[i] = letterBytes[r.Int64()]
}
return string(b)
return string(b), nil
}
6 changes: 5 additions & 1 deletion pkg/bastion/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -1640,11 +1640,15 @@ GLOBAL OPTIONS:
name = c.String("name")
}

r, err := randStringBytes(16)
if err != nil {
return err
}
user := dbmodels.User{
Name: name,
Email: email,
Comment: c.String("comment"),
InviteToken: randStringBytes(16),
InviteToken: r,
}

if _, err := govalidator.ValidateStruct(user); err != nil {
Expand Down