diff --git a/internal/server/turn.go b/internal/server/turn.go index 69e2285b..554c451b 100644 --- a/internal/server/turn.go +++ b/internal/server/turn.go @@ -106,7 +106,10 @@ func handleAllocateRequest(r Request, m *stun.Message) error { return buildAndSendErr(r.Conn, r.SrcAddr, err, insufficientCapacityMsg...) } requestedPort = randomPort - reservationToken = randSeq(8) + reservationToken, err = randSeq(8) + if err != nil { + return err + } } // 7. At any point, the server MAY choose to reject the request with a diff --git a/internal/server/util.go b/internal/server/util.go index 9df12c22..bdf256de 100644 --- a/internal/server/util.go +++ b/internal/server/util.go @@ -5,10 +5,11 @@ package server import ( "crypto/md5" //nolint:gosec,gci + "crypto/rand" "errors" "fmt" "io" - "math/rand" + "math/big" "net" "strconv" "time" @@ -22,13 +23,17 @@ const ( nonceLifetime = time.Hour // See: https://tools.ietf.org/html/rfc5766#section-4 ) -func randSeq(n int) string { +func randSeq(n int) (string, error) { letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") b := make([]rune, n) for i := range b { - b[i] = letters[rand.Intn(len(letters))] //nolint:gosec + j, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters)))) + if err != nil { + return "", err + } + b[i] = letters[int(j.Int64())] //nolint:gosec } - return string(b) + return string(b), nil } func buildNonce() (string, error) { @@ -37,7 +42,15 @@ func buildNonce() (string, error) { if _, err := io.WriteString(h, strconv.FormatInt(time.Now().Unix(), 10)); err != nil { return "", fmt.Errorf("%w: %v", errFailedToGenerateNonce, err) //nolint:errorlint } - if _, err := io.WriteString(h, strconv.FormatInt(rand.Int63(), 10)); err != nil { //nolint:gosec + + maxInt63 := big.NewInt(1<<63 - 1) + maxInt63.Add(maxInt63, big.NewInt(1)) + randInt63, err := rand.Int(rand.Reader, maxInt63) + if err != nil { + return "", fmt.Errorf("%w: %v", errFailedToGenerateNonce, err) + } + + if _, err := io.WriteString(h, randInt63.String()); err != nil { //nolint:gosec return "", fmt.Errorf("%w: %v", errFailedToGenerateNonce, err) //nolint:errorlint } return fmt.Sprintf("%x", h.Sum(nil)), nil