Skip to content

Commit

Permalink
Merge pull request #307 from pixlise/feature/impersonate-user
Browse files Browse the repository at this point in the history
Added safety check for connect tokens in case of injection attack, as…
  • Loading branch information
pnemere authored Sep 16, 2024
2 parents c811836 + e4f6aaa commit bc057db
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
8 changes: 7 additions & 1 deletion api/ws/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,17 @@ func (ws *WSHandler) HandleConnect(s *melody.Session) {
} else {
// Validate the token
if len(token) != 1 {
fmt.Printf("WS connect failed for token: %v\n", token)
fmt.Printf("WS connect failed due to unexpected token count %v\n", len(token))
s.CloseWithMsg([]byte("--Multiple tokens provided"))
return
}

if !wsHelpers.IsValidConnectToken(token[0]) {
fmt.Printf("WS connect received invalid token: %v\n", token[0])
s.CloseWithMsg([]byte("--Invalid token provided"))
return
}

var err error
connectingUser, err = wsHelpers.CheckConnectToken(token[0], ws.svcs)

Expand Down
16 changes: 16 additions & 0 deletions api/ws/wsHelpers/connectTokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package wsHelpers
import (
"context"
"errors"
"strings"

"github.com/pixlise/core/v4/api/dbCollections"
"github.com/pixlise/core/v4/api/services"
Expand Down Expand Up @@ -47,6 +48,21 @@ func CreateConnectToken(svcs *services.APIServices, user jwtparser.JWTUserInfo)
return token.Id
}

func IsValidConnectToken(token string) bool {
if len(token) != 32 {
return false
}

possibleChars := utils.RandomStringChars
for i := range token {
if strings.Index(possibleChars, token[i:i+1]) < 0 {
return false
}
}

return true
}

func CheckConnectToken(token string, svcs *services.APIServices) (jwtparser.JWTUserInfo, error) {
// Check to see if token exists in DB
ctx := context.TODO()
Expand Down
6 changes: 3 additions & 3 deletions core/utils/random-string.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import "math/rand"

// Random string generation
// https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
const letterBytes = "abcdefghijklmnopqrstuvwxyz1234567890"
const RandomStringChars = "abcdefghijklmnopqrstuvwxyz1234567890"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
Expand All @@ -35,8 +35,8 @@ func RandStringBytesMaskImpr(n int) string {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
if idx := int(cache & letterIdxMask); idx < len(RandomStringChars) {
b[i] = RandomStringChars[idx]
i--
}
cache >>= letterIdxBits
Expand Down

0 comments on commit bc057db

Please sign in to comment.