Skip to content

Commit

Permalink
Use crypto/rand for mask key
Browse files Browse the repository at this point in the history
  • Loading branch information
Halo Arrow committed Aug 26, 2023
1 parent 8039329 commit f9cf504
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
13 changes: 10 additions & 3 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ package websocket

import (
"bufio"
"crypto/rand"
"encoding/binary"
"errors"
"io"
"io/ioutil"
"math/rand"
"net"
"strconv"
"strings"
Expand Down Expand Up @@ -181,9 +181,16 @@ var (
errInvalidControlFrame = errors.New("websocket: invalid control frame")
)

// maskRand is an io.Reader for generating mask bytes. The reader is initialized
// to crypto/rand Reader. Tests swap the reader to a math/rand reader for
// reproducible results.
var maskRand = rand.Reader

// newMaskKey returns a new 32 bit value for masking client frames.
func newMaskKey() [4]byte {
n := rand.Uint32()
return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)}
var k [4]byte
_, _ = io.ReadFull(maskRand, k[:])
return k
}

func hideTempErr(err error) error {
Expand Down
9 changes: 7 additions & 2 deletions prepared_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ var preparedMessageTests = []struct {
}

func TestPreparedMessage(t *testing.T) {
testRand := rand.New(rand.NewSource(99))
prevMaskRand := maskRand
maskRand = testRand
defer func() { maskRand = prevMaskRand }()

for _, tt := range preparedMessageTests {
var data = []byte("this is a test")
var buf bytes.Buffer
Expand All @@ -43,7 +48,7 @@ func TestPreparedMessage(t *testing.T) {
c.SetCompressionLevel(tt.compressionLevel)

// Seed random number generator for consistent frame mask.
rand.Seed(1234)
testRand.Seed(1234)

if err := c.WriteMessage(tt.messageType, data); err != nil {
t.Fatal(err)
Expand All @@ -59,7 +64,7 @@ func TestPreparedMessage(t *testing.T) {
copy(data, "hello world")

// Seed random number generator for consistent frame mask.
rand.Seed(1234)
testRand.Seed(1234)

buf.Reset()
if err := c.WritePreparedMessage(pm); err != nil {
Expand Down

0 comments on commit f9cf504

Please sign in to comment.