Skip to content

Commit

Permalink
Use crypto/rand instead of math/rand
Browse files Browse the repository at this point in the history
math/rand isn't suitable for security-sensitive contexts. This PR
replaces it with crypto/rand (which uses the somewhat inconvenient
big.Int type).
  • Loading branch information
Daniel Kessler committed Oct 23, 2023
1 parent f15249d commit ded3a65
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
5 changes: 4 additions & 1 deletion internal/server/turn.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 18 additions & 5 deletions internal/server/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ package server

import (
"crypto/md5" //nolint:gosec,gci
"crypto/rand"
"errors"
"fmt"
"io"
"math/rand"
"math/big"
"net"
"strconv"
"time"
Expand All @@ -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) {
Expand All @@ -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
Expand Down

0 comments on commit ded3a65

Please sign in to comment.