"Fossies" - the Fresh Open Source Software Archive

Member "src/Core/RandomNumberGenerator.cpp" (10 Oct 2018, 5419 Bytes) of package /windows/misc/VeraCrypt_1.23-Hotfix-2_Source.zip:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "RandomNumberGenerator.cpp" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 1.18_Source_vs_1.19_Source.

    1 /*
    2  Derived from source code of TrueCrypt 7.1a, which is
    3  Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
    4  by the TrueCrypt License 3.0.
    5 
    6  Modifications and additions to the original source code (contained in this file)
    7  and all other portions of this file are Copyright (c) 2013-2017 IDRIX
    8  and are governed by the Apache License 2.0 the full text of which is
    9  contained in the file License.txt included in VeraCrypt binary and source
   10  code distribution packages.
   11 */
   12 
   13 #ifndef TC_WINDOWS
   14 #include <sys/types.h>
   15 #include <errno.h>
   16 #include <fcntl.h>
   17 #endif
   18 
   19 #include "RandomNumberGenerator.h"
   20 #include "Volume/Crc32.h"
   21 
   22 namespace VeraCrypt
   23 {
   24     void RandomNumberGenerator::AddSystemDataToPool (bool fast)
   25     {
   26         SecureBuffer buffer (PoolSize);
   27 
   28 #ifdef TC_WINDOWS
   29 #ifndef DEBUG
   30         throw NotImplemented (SRC_POS);
   31 #endif
   32 #else
   33         int urandom = open ("/dev/urandom", O_RDONLY);
   34         throw_sys_sub_if (urandom == -1, L"/dev/urandom");
   35         finally_do_arg (int, urandom, { close (finally_arg); });
   36 
   37         throw_sys_sub_if (read (urandom, buffer, buffer.Size()) == -1, L"/dev/urandom");
   38         AddToPool (buffer);
   39 
   40         if (!fast)
   41         {
   42             // Read all bytes available in /dev/random up to buffer size
   43             int random = open ("/dev/random", O_RDONLY | O_NONBLOCK);
   44             throw_sys_sub_if (random == -1, L"/dev/random");
   45             finally_do_arg (int, random, { close (finally_arg); });
   46 
   47             throw_sys_sub_if (read (random, buffer, buffer.Size()) == -1 && errno != EAGAIN, L"/dev/random");
   48             AddToPool (buffer);
   49         }
   50 #endif
   51     }
   52 
   53     void RandomNumberGenerator::AddToPool (const ConstBufferPtr &data)
   54     {
   55         if (!Running)
   56             throw NotInitialized (SRC_POS);
   57 
   58         ScopeLock lock (AccessMutex);
   59 
   60         for (size_t i = 0; i < data.Size(); ++i)
   61         {
   62             Pool[WriteOffset++] += data[i];
   63 
   64             if (WriteOffset >= PoolSize)
   65                 WriteOffset = 0;
   66 
   67             if (++BytesAddedSincePoolHashMix >= MaxBytesAddedBeforePoolHashMix)
   68                 HashMixPool();
   69         }
   70     }
   71 
   72     void RandomNumberGenerator::GetData (const BufferPtr &buffer, bool fast, bool allowAnyLength)
   73     {
   74         if (!Running)
   75             throw NotInitialized (SRC_POS);
   76 
   77         if (!allowAnyLength && (buffer.Size() > PoolSize))
   78             throw ParameterIncorrect (SRC_POS);
   79 
   80         ScopeLock lock (AccessMutex);
   81         size_t bufferLen = buffer.Size(), loopLen;
   82         byte* pbBuffer = buffer.Get();
   83 
   84         // Poll system for data
   85         AddSystemDataToPool (fast);
   86         HashMixPool();
   87 
   88         while (bufferLen > 0)
   89         {
   90             if (bufferLen > PoolSize)
   91             {
   92                 loopLen = PoolSize;
   93                 bufferLen -= PoolSize;
   94             }
   95             else
   96             {
   97                 loopLen = bufferLen;
   98                 bufferLen = 0;
   99             }
  100 
  101             // Transfer bytes from pool to output buffer
  102             for (size_t i = 0; i < loopLen; ++i)
  103             {
  104                 pbBuffer[i] += Pool[ReadOffset++];
  105 
  106                 if (ReadOffset >= PoolSize)
  107                     ReadOffset = 0;
  108             }
  109 
  110             // Invert and mix the pool
  111             for (size_t i = 0; i < Pool.Size(); ++i)
  112             {
  113                 Pool[i] = ~Pool[i];
  114             }
  115 
  116             AddSystemDataToPool (true);
  117             HashMixPool();
  118 
  119             // XOR the current pool content into the output buffer to prevent pool state leaks
  120             for (size_t i = 0; i < loopLen; ++i)
  121             {
  122                 pbBuffer[i] ^= Pool[ReadOffset++];
  123 
  124                 if (ReadOffset >= PoolSize)
  125                     ReadOffset = 0;
  126             }
  127 
  128             pbBuffer += loopLen;
  129         }
  130     }
  131 
  132     shared_ptr <Hash> RandomNumberGenerator::GetHash ()
  133     {
  134         ScopeLock lock (AccessMutex);
  135         return PoolHash;
  136     }
  137 
  138     void RandomNumberGenerator::HashMixPool ()
  139     {
  140         BytesAddedSincePoolHashMix = 0;
  141 
  142         for (size_t poolPos = 0; poolPos < Pool.Size(); )
  143         {
  144             // Compute the message digest of the entire pool using the selected hash function
  145             SecureBuffer digest (PoolHash->GetDigestSize());
  146             PoolHash->ProcessData (Pool);
  147             PoolHash->GetDigest (digest);
  148 
  149             // Add the message digest to the pool
  150             for (size_t digestPos = 0; digestPos < digest.Size() && poolPos < Pool.Size(); ++digestPos)
  151             {
  152                 Pool[poolPos++] += digest[digestPos];
  153             }
  154         }
  155     }
  156 
  157     void RandomNumberGenerator::SetHash (shared_ptr <Hash> hash)
  158     {
  159         ScopeLock lock (AccessMutex);
  160         PoolHash = hash;
  161     }
  162 
  163     void RandomNumberGenerator::Start ()
  164     {
  165         ScopeLock lock (AccessMutex);
  166 
  167         if (IsRunning())
  168             return;
  169 
  170         BytesAddedSincePoolHashMix = 0;
  171         ReadOffset = 0;
  172         WriteOffset = 0;
  173         Running = true;
  174         EnrichedByUser = false;
  175 
  176         Pool.Allocate (PoolSize, 16);
  177         Test();
  178 
  179         if (!PoolHash)
  180         {
  181             // First hash algorithm is the default one
  182             PoolHash = Hash::GetAvailableAlgorithms().front();
  183         }
  184 
  185         AddSystemDataToPool (true);
  186     }
  187 
  188     void RandomNumberGenerator::Stop ()
  189     {
  190         ScopeLock lock (AccessMutex);
  191 
  192         if (Pool.IsAllocated())
  193             Pool.Free ();
  194 
  195         PoolHash.reset();
  196 
  197         EnrichedByUser = false;
  198         Running = false;
  199     }
  200 
  201     void RandomNumberGenerator::Test ()
  202     {
  203         shared_ptr <Hash> origPoolHash = PoolHash;
  204         PoolHash.reset (new Ripemd160());
  205 
  206         Pool.Zero();
  207         Buffer buffer (1);
  208         for (size_t i = 0; i < PoolSize * 10; ++i)
  209         {
  210             buffer[0] = (byte) i;
  211             AddToPool (buffer);
  212         }
  213 
  214         if (Crc32::ProcessBuffer (Pool) != 0x2de46d17)
  215             throw TestFailed (SRC_POS);
  216 
  217         buffer.Allocate (PoolSize);
  218         buffer.CopyFrom (PeekPool());
  219         AddToPool (buffer);
  220 
  221         if (Crc32::ProcessBuffer (Pool) != 0xcb88e019)
  222             throw TestFailed (SRC_POS);
  223 
  224         PoolHash = origPoolHash;
  225     }
  226 
  227     Mutex RandomNumberGenerator::AccessMutex;
  228     size_t RandomNumberGenerator::BytesAddedSincePoolHashMix;
  229     bool RandomNumberGenerator::EnrichedByUser;
  230     SecureBuffer RandomNumberGenerator::Pool;
  231     shared_ptr <Hash> RandomNumberGenerator::PoolHash;
  232     size_t RandomNumberGenerator::ReadOffset;
  233     bool RandomNumberGenerator::Running = false;
  234     size_t RandomNumberGenerator::WriteOffset;
  235 }