Skip to content

Commit

Permalink
dhcp4client: default to math.Rand over crypto.Rand
Browse files Browse the repository at this point in the history
This prevents blocking until the CRNG is initialized with Linux ≥ 4.16:
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=43838a23a05fbd13e47d750d3dfd77001536dd33

As per https://tools.ietf.org/html/rfc2131#section-4.1, the xid field should be
chosen such a way as to minimize the chance of using an xid identical to one
used by another client.

This only requires a seeded random number generator, not a cryptographically
secure random number generator.
  • Loading branch information
stapelberg committed Jun 8, 2018
1 parent 58c4d7a commit ac8e065
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package dhcp4client

import (
"bytes"
"hash/fnv"
"math/rand"
"net"
"sync"
"time"

"github.com/d2g/dhcp4"
Expand Down Expand Up @@ -31,16 +34,35 @@ type ConnectionInt interface {

func New(options ...func(*Client) error) (*Client, error) {
c := Client{
timeout: time.Second * 10,
broadcast: true,
generateXID: CryptoGenerateXID,
timeout: time.Second * 10,
broadcast: true,
}

err := c.SetOption(options...)
if err != nil {
return nil, err
}

if c.generateXID == nil {
// https://tools.ietf.org/html/rfc2131#section-4.1 explains:
//
// A DHCP client MUST choose 'xid's in such a way as to minimize the chance
// of using an 'xid' identical to one used by another client.
//
// Hence, seed a random number generator with the current time and hardware
// address.
h := fnv.New64()
h.Sum(c.hardwareAddr)
seed := int64(h.Sum64()) + time.Now().Unix()
rnd := rand.New(rand.NewSource(seed))
var rndMu sync.Mutex
c.generateXID = func(b []byte) {
rndMu.Lock()
defer rndMu.Unlock()
rnd.Read(b)
}
}

//if connection hasn't been set as an option create the default.
if c.connection == nil {
conn, err := NewInetSock()
Expand Down Expand Up @@ -299,7 +321,6 @@ func (c *Client) DeclinePacket(acknowledgement *dhcp4.Packet) dhcp4.Packet {
return packet
}


//Lets do a Full DHCP Request.
func (c *Client) Request() (bool, dhcp4.Packet, error) {
discoveryPacket, err := c.SendDiscoverPacket()
Expand Down

0 comments on commit ac8e065

Please sign in to comment.