From 97bdd0d7b8411135c67d78441e73b8e2d6aff170 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Sat, 23 Sep 2023 13:52:58 +0700 Subject: cmd/resolver: replace "math/rand" with "crypto/rand" The random number from "math/rand" is predictable if the seed is known. Even though the random number here is only for generating unique request ID, we still need to prevent this by using more secure random number. --- cmd/resolver/resolver.go | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/cmd/resolver/resolver.go b/cmd/resolver/resolver.go index 72204e4..9561089 100644 --- a/cmd/resolver/resolver.go +++ b/cmd/resolver/resolver.go @@ -4,11 +4,13 @@ package main import ( + "crypto/rand" "encoding/json" "fmt" "io" "log" - "math/rand" + "math" + "math/big" "os" "strconv" "strings" @@ -773,15 +775,21 @@ func (rsol *resolver) newRescachedClient() (resc *rescached.Client) { func (rsol *resolver) query(timeout time.Duration, qname string) (res *dns.Message, err error) { var ( - logp = "query" - req = dns.NewMessage() - ) + logp = "query" + req = dns.NewMessage() + randMax = big.NewInt(math.MaxUint16) - rand.Seed(time.Now().Unix()) + randv *big.Int + ) rsol.dnsc.SetTimeout(timeout) - req.Header.ID = uint16(rand.Intn(65535)) + randv, err = rand.Int(rand.Reader, randMax) + if err != nil { + log.Panicf(`%s: %s`, logp, err) + } + + req.Header.ID = uint16(randv.Int64()) req.Question.Name = qname req.Question.Type = rsol.qtype req.Question.Class = rsol.qclass -- cgit v1.3