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

Use crypto/rand for mask key #846

Closed
wants to merge 1 commit into from
Closed
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
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