use cryptographic random to generate new connection IDs

fixes #348
This commit is contained in:
Marten Seemann
2017-01-18 14:19:53 +07:00
parent d5ec70fc7d
commit 86e02c4d2c
3 changed files with 39 additions and 4 deletions

View File

@@ -3,7 +3,6 @@ package quic
import (
"bytes"
"errors"
"math/rand"
"net"
"strings"
"sync/atomic"
@@ -52,9 +51,10 @@ func NewClient(host string, cryptoChangeCallback CryptoChangeCallback, versionNe
return nil, err
}
// TODO: generate cryptographically secure random ConnectionID
rand.Seed(time.Now().UTC().UnixNano())
connectionID := protocol.ConnectionID(rand.Int63())
connectionID, err := utils.GenerateConnectionID()
if err != nil {
return nil, err
}
hostname, _, err := net.SplitHostPort(host)
if err != nil {

18
utils/connection_id.go Normal file
View File

@@ -0,0 +1,18 @@
package utils
import (
"crypto/rand"
"encoding/binary"
"github.com/lucas-clemente/quic-go/protocol"
)
// GenerateConnectionID generates a connection ID using cryptographic random
func GenerateConnectionID() (protocol.ConnectionID, error) {
b := make([]byte, 8, 8)
_, err := rand.Read(b)
if err != nil {
return 0, err
}
return protocol.ConnectionID(binary.LittleEndian.Uint64(b)), nil
}

View File

@@ -0,0 +1,17 @@
package utils
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Connection ID generation", func() {
It("generates random connection IDs", func() {
c1, err := GenerateConnectionID()
Expect(err).ToNot(HaveOccurred())
Expect(c1).ToNot(BeZero())
c2, err := GenerateConnectionID()
Expect(err).ToNot(HaveOccurred())
Expect(c1).ToNot(Equal(c2))
})
})