From 8284ef63a517690a893ffda1083fb966a76b6fbc Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Mon, 23 Jun 2014 19:15:40 -0400 Subject: std: make sure HashMap from_iter uses random initialization by default It turns out that HashMap's from_iter implementation was being initialized without the sip keys being randomized. This adds a custom default hasher that should avoid this potential vulnerability. --- src/libstd/collections/hashmap.rs | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) (limited to 'src/libstd/collections') diff --git a/src/libstd/collections/hashmap.rs b/src/libstd/collections/hashmap.rs index b94141748d5..be5c2e25141 100644 --- a/src/libstd/collections/hashmap.rs +++ b/src/libstd/collections/hashmap.rs @@ -16,15 +16,13 @@ use collections::{Collection, Mutable, Set, MutableSet, Map, MutableMap}; use default::Default; use fmt::Show; use fmt; -use hash::{Hash, Hasher, sip}; +use hash::{Hash, Hasher, RandomSipHasher}; use iter::{Iterator, FilterMap, Chain, Repeat, Zip, Extendable}; use iter::{range, range_inclusive, FromIterator}; use iter; use mem::replace; use num; use option::{Some, None, Option}; -use rand::Rng; -use rand; use result::{Ok, Err}; mod table { @@ -733,7 +731,7 @@ impl DefaultResizePolicy { /// } /// ``` #[deriving(Clone)] -pub struct HashMap { +pub struct HashMap { // All hashes are keyed on these values, to prevent hash collision attacks. hasher: H, @@ -1033,18 +1031,15 @@ impl, V, S, H: Hasher> MutableMap for HashMap } -impl HashMap { +impl HashMap { /// Create an empty HashMap. - pub fn new() -> HashMap { + pub fn new() -> HashMap { HashMap::with_capacity(INITIAL_CAPACITY) } /// Creates an empty hash map with the given initial capacity. - pub fn with_capacity(capacity: uint) -> HashMap { - let mut r = rand::task_rng(); - let r0 = r.gen(); - let r1 = r.gen(); - let hasher = sip::SipHasher::new_with_keys(r0, r1); + pub fn with_capacity(capacity: uint) -> HashMap { + let hasher = RandomSipHasher::new(); HashMap::with_capacity_and_hasher(capacity, hasher) } } @@ -1489,7 +1484,7 @@ pub type SetMoveItems = /// HashMap where the value is (). As with the `HashMap` type, a `HashSet` /// requires that the elements implement the `Eq` and `Hash` traits. #[deriving(Clone)] -pub struct HashSet { +pub struct HashSet { map: HashMap } @@ -1529,15 +1524,15 @@ impl, S, H: Hasher> MutableSet for HashSet { fn remove(&mut self, value: &T) -> bool { self.map.remove(value) } } -impl HashSet { +impl HashSet { /// Create an empty HashSet - pub fn new() -> HashSet { + pub fn new() -> HashSet { HashSet::with_capacity(INITIAL_CAPACITY) } /// Create an empty HashSet with space for at least `n` elements in /// the hash table. - pub fn with_capacity(capacity: uint) -> HashSet { + pub fn with_capacity(capacity: uint) -> HashSet { HashSet { map: HashMap::with_capacity(capacity) } } } -- cgit 1.4.1-3-g733a5