DHCPV4: use c++11 random number generator
This uses c++11 random number generator to replace the old
c-style random number generator.
In addition, this deletes the function DHCPMessage::
GenerateTransactionID(). Both the DHCP transaction id and
IP transaction id will be generated by the random engine in
DHCPV4.
Bug: 25642025
TEST=compile and unittest
Change-Id: Ie23600f08f5dab8b373bf19eac7b25c112e1a1c8
diff --git a/dhcp_message.cc b/dhcp_message.cc
index b1c83e6..7b9a8b2 100644
--- a/dhcp_message.cc
+++ b/dhcp_message.cc
@@ -376,12 +376,6 @@
return ~static_cast<uint16_t>(sum);
}
-uint32_t DHCPMessage::GenerateTransactionID() {
- // TODO(nywang): use arc4 random number for better security.
- srand(time(NULL));
- return rand() % UINT32_MAX;
-}
-
void DHCPMessage::SetClientIdentifier(
const ByteString& client_identifier) {
client_identifier_ = client_identifier;
diff --git a/dhcp_message.h b/dhcp_message.h
index 3b0a852..39b3929 100644
--- a/dhcp_message.h
+++ b/dhcp_message.h
@@ -60,7 +60,6 @@
DHCPMessage* message);
static DHCPMessage InitRequest();
static uint16_t ComputeChecksum(const uint8_t* data, size_t len);
- static uint32_t GenerateTransactionID();
// Initialize part of the data fields for outbound DHCP message.
// Serialize the message to a buffer
bool Serialize(shill::ByteString* data) const;
diff --git a/dhcpv4.cc b/dhcpv4.cc
index 016d75f..3ef58ed 100644
--- a/dhcpv4.cc
+++ b/dhcpv4.cc
@@ -24,6 +24,8 @@
#include <netinet/ip.h>
#include <netinet/udp.h>
+#include <random>
+
#include <base/bind.h>
#include <base/logging.h>
@@ -86,7 +88,8 @@
from_(INADDR_ANY),
to_(INADDR_BROADCAST),
socket_(kInvalidSocketDescriptor),
- sockets_(new shill::Sockets()) {
+ sockets_(new shill::Sockets()),
+ random_engine_(time(nullptr)) {
}
DHCPV4::~DHCPV4() {
@@ -266,8 +269,9 @@
// so fragmentation is not needed.
ip->frag_off = 0;
// Identification.
- // TODO(nywang) Use arc4 random number.
- ip->id = static_cast<uint16_t>(rand());
+ ip->id = static_cast<uint16_t>(
+ std::uniform_int_distribution<unsigned int>()(
+ random_engine_) % UINT16_MAX + 1);
// Time to live.
ip->ttl = IPDEFTTL;
// Total length.
diff --git a/dhcpv4.h b/dhcpv4.h
index c1ea166..ebe2f5a 100644
--- a/dhcpv4.h
+++ b/dhcpv4.h
@@ -17,6 +17,7 @@
#ifndef DHCP_CLIENT_DHCPV4_H_
#define DHCP_CLIENT_DHCPV4_H_
+#include <random>
#include <string>
#include <base/macros.h>
@@ -94,6 +95,8 @@
// Helper class with wrapped socket relavent functions.
std::unique_ptr<shill::Sockets> sockets_;
+ std::default_random_engine random_engine_;
+
DISALLOW_COPY_AND_ASSIGN(DHCPV4);
};