Saturday, July 23, 2005 12:37 PM
rsamona
Spot the Bug - July 23, 2005
The first bug was just a warm-up and people were asking for a more difficult bug. What's wrong with this chunk of code, and better yet, how do you fix it?
Courtesy of Shanit Gupta, Consultant, Foundstone
private HttpCookie SessionIdentifier ()
{
HttpCookie myCookie = new HttpCookie("SessionId");
Random objRand = new Random (DateTime.Now.Millisecond);
myCookie.Value(“SessionId”) = random(objRand.Next()) ;
return myCookie;
}
Solution:
There was a good chat around this one. Here's one good way to implement it:
byte[] randomCharacters = new Byte[64];
//RNGCryptoServiceProvider is an implementation of a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
private HttpCookie SessionIdentifier (RNGCryptoServiceProvider cryptoRNG)
{
HttpCookie myCookie = new HttpCookie("SessionId")
crptoRNG.GetBytes(randomCharacters); // The array is now filled with cryptographically strong random bytes.
myCookie.Value(“SessionId”) = randomCharacters.toString(); return myCookie;
}
Description: Many developers think that a function/class such as “random” or likes is capable of generating random numbers that are not predictable. Some of them go on to believe that that time in seconds or even milliseconds can server as a good random number or at least a good seed for the random number. Further the deterministic nature of computers makes it extremely simple to calculate the seed of PRNG and the following pseudo random numbers provided a good sample of inputs are available. We recommend the use of cryptographically secure PRNGs which do not generate the same set of random numbers even when seeded with the same string. More information can be found here.