Subject: [PATCH 1/1] Bug 22919: Force better random numbers for HTML Form Boundary --- dom/html/HTMLFormSubmission.cpp | 37 ++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/dom/html/HTMLFormSubmission.cpp b/dom/html/HTMLFormSubmission.cpp index d6269a7ca..a967947f9 100644 --- a/dom/html/HTMLFormSubmission.cpp +++ b/dom/html/HTMLFormSubmission.cpp @@ -35,6 +35,7 @@ #include "nsCExternalHandlerService.h" #include "nsIFileStreams.h" #include "nsContentUtils.h" +#include "nsIRandomGenerator.h" #include "mozilla/dom/Directory.h" #include "mozilla/dom/EncodingUtils.h" @@ -426,18 +427,48 @@ FSURLEncoded::URLEncode(const nsAString& aStr, nsACString& aEncoded) // -------------------------------------------------------------------------- +static void +GenerateGlobalRandomBytes(unsigned char *buf, int32_t len) +{ + // Attempt to generate bytes from system entropy-based RNG. + nsCOMPtr randomGenerator(do_GetService("@mozilla.org/security/random-generator;1")); + MOZ_ASSERT(randomGenerator, "nsIRandomGenerator service not retrievable"); + uint8_t *tempBuffer; + nsresult rv = randomGenerator->GenerateRandomBytes(len, &tempBuffer); + if (NS_SUCCEEDED(rv)) + { + memcpy(buf, tempBuffer, len); + free(tempBuffer); + return; + } + // nsIRandomGenerator failed -- fall back to low entropy PRNG. + static bool firstTime = true; + if (firstTime) + { + // Seed the random-number generator with current time so that + // the numbers will be different every time we run. + srand( (unsigned)PR_Now() ); + } + + for( int32_t i = 0; i < len; i++ ) { + buf[i] = rand() % 256; + } +} + FSMultipartFormData::FSMultipartFormData(const nsACString& aCharset, nsIContent* aOriginatingElement) : EncodingFormSubmission(aCharset, aOriginatingElement) { + unsigned char rand_buf[4]; + GenerateGlobalRandomBytes(rand_buf, 3); mPostDataStream = do_CreateInstance("@mozilla.org/io/multiplex-input-stream;1"); mTotalLength = 0; mBoundary.AssignLiteral("---------------------------"); - mBoundary.AppendInt(rand()); - mBoundary.AppendInt(rand()); - mBoundary.AppendInt(rand()); + mBoundary.AppendInt(rand_buf[0]); + mBoundary.AppendInt(rand_buf[1]); + mBoundary.AppendInt(rand_buf[2]); } FSMultipartFormData::~FSMultipartFormData() -- 2.23.0