From 6ec00a80fdfbecf5a8f49066d0ba1afc8db26d09 Mon Sep 17 00:00:00 2001 From: xtaci Date: Fri, 19 Aug 2016 10:08:55 +0800 Subject: [PATCH] enhance convid security and fix a race of random number generator --- sess.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/sess.go b/sess.go index ba0c50b..acf4711 100644 --- a/sess.go +++ b/sess.go @@ -20,7 +20,6 @@ import ( var ( errTimeout = errors.New("i/o timeout") errBrokenPipe = errors.New("broken pipe") - rng = rand.New(rand.NewSource(time.Now().UnixNano())) ) const ( @@ -58,6 +57,7 @@ type ( ackNoDelay bool keepAliveInterval time.Duration xmitBuf sync.Pool + rng *rand.Rand } ) @@ -76,6 +76,7 @@ func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn sess.l = l sess.block = block sess.fec = newFEC(rxFecLimit, dataShards, parityShards) + sess.rng = rand.New(rand.NewSource(time.Now().UnixNano())) sess.xmitBuf.New = func() interface{} { return make([]byte, mtuLimit) } @@ -452,7 +453,7 @@ func (s *UDPSession) outputTask() { interval := s.keepAliveInterval s.mu.Unlock() if interval > 0 && time.Now().After(lastPing.Add(interval)) { - sz := rng.Intn(IKCP_MTU_DEF - s.headerSize - IKCP_OVERHEAD) + sz := s.rng.Intn(IKCP_MTU_DEF - s.headerSize - IKCP_OVERHEAD) sz += s.headerSize + IKCP_OVERHEAD ping := make([]byte, sz) io.ReadFull(crand.Reader, ping) @@ -824,7 +825,10 @@ func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards in if err != nil { return nil, err } - return newUDPSession(rng.Uint32(), dataShards, parityShards, nil, udpconn, udpaddr, block), nil + + convid := make([]byte, 4) + io.ReadFull(crand.Reader, convid) + return newUDPSession(binary.LittleEndian.Uint32(convid), dataShards, parityShards, nil, udpconn, udpaddr, block), nil } func currentMs() uint32 {