]> git.ipfire.org Git - thirdparty/wireguard-go.git/commitdiff
device: timers: use pre-seeded per-thread unlocked fastrandn for jitter
authorJason A. Donenfeld <Jason@zx2c4.com>
Thu, 28 Oct 2021 11:47:50 +0000 (13:47 +0200)
committerJason A. Donenfeld <Jason@zx2c4.com>
Thu, 28 Oct 2021 11:47:50 +0000 (13:47 +0200)
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
device/timers.go

index aa6f28abdd6f177b460ebaf4331374224ea2fdc6..176976d595241c5aca24a16d0010e51d8fc94d0c 100644 (file)
@@ -8,19 +8,14 @@
 package device
 
 import (
-       "crypto/rand"
-       unsafeRand "math/rand"
        "sync"
        "sync/atomic"
        "time"
-       "unsafe"
+       "unsafe"
 )
 
-func init() {
-       var seed int64
-       rand.Read(unsafe.Slice((*byte)(unsafe.Pointer(&seed)), unsafe.Sizeof(seed)))
-       unsafeRand.Seed(seed)
-}
+//go:linkname fastrandn runtime.fastrandn
+func fastrandn(n uint32) uint32
 
 // A Timer manages time-based aspects of the WireGuard protocol.
 // Timer roughly copies the interface of the Linux kernel's struct timer_list.
@@ -152,7 +147,7 @@ func expiredPersistentKeepalive(peer *Peer) {
 /* Should be called after an authenticated data packet is sent. */
 func (peer *Peer) timersDataSent() {
        if peer.timersActive() && !peer.timers.newHandshake.IsPending() {
-               peer.timers.newHandshake.Mod(KeepaliveTimeout + RekeyTimeout + time.Millisecond*time.Duration(unsafeRand.Int63n(RekeyTimeoutJitterMaxMs)))
+               peer.timers.newHandshake.Mod(KeepaliveTimeout + RekeyTimeout + time.Millisecond*time.Duration(fastrandn(RekeyTimeoutJitterMaxMs)))
        }
 }
 
@@ -184,7 +179,7 @@ func (peer *Peer) timersAnyAuthenticatedPacketReceived() {
 /* Should be called after a handshake initiation message is sent. */
 func (peer *Peer) timersHandshakeInitiated() {
        if peer.timersActive() {
-               peer.timers.retransmitHandshake.Mod(RekeyTimeout + time.Millisecond*time.Duration(unsafeRand.Int63n(RekeyTimeoutJitterMaxMs)))
+               peer.timers.retransmitHandshake.Mod(RekeyTimeout + time.Millisecond*time.Duration(fastrandn(RekeyTimeoutJitterMaxMs)))
        }
 }