Handle creating the default crypto context if it doesn't already exist
[folly.git] / folly / Random.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/Random.h>
18
19 #include <atomic>
20 #include <mutex>
21 #include <random>
22 #include <array>
23
24 #include <glog/logging.h>
25 #include <folly/CallOnce.h>
26 #include <folly/File.h>
27 #include <folly/FileUtil.h>
28 #include <folly/ThreadLocal.h>
29 #include <folly/portability/SysTime.h>
30 #include <folly/portability/Unistd.h>
31
32 #ifdef _MSC_VER
33 # include <wincrypt.h>
34 #endif
35
36 namespace folly {
37
38 namespace {
39
40 void readRandomDevice(void* data, size_t size) {
41 #ifdef _MSC_VER
42   static folly::once_flag flag;
43   static HCRYPTPROV cryptoProv;
44   folly::call_once(flag, [&] {
45     if (!CryptAcquireContext(&cryptoProv, nullptr, nullptr, PROV_RSA_FULL, 0)) {
46       if (GetLastError() == NTE_BAD_KEYSET) {
47         // Mostly likely cause of this is that no key container
48         // exists yet, so try to create one.
49         PCHECK(CryptAcquireContext(
50             &cryptoProv, nullptr, nullptr, PROV_RSA_FULL, CRYPT_NEWKEYSET));
51       } else {
52         LOG(FATAL) << "Failed to acquire the default crypto context.";
53       }
54     }
55   });
56   CHECK(size <= std::numeric_limits<DWORD>::max());
57   PCHECK(CryptGenRandom(cryptoProv, (DWORD)size, (BYTE*)data));
58 #else
59   // Keep the random device open for the duration of the program.
60   static int randomFd = ::open("/dev/urandom", O_RDONLY);
61   PCHECK(randomFd >= 0);
62   auto bytesRead = readFull(randomFd, data, size);
63   PCHECK(bytesRead >= 0 && size_t(bytesRead) == size);
64 #endif
65 }
66
67 class BufferedRandomDevice {
68  public:
69   static constexpr size_t kDefaultBufferSize = 128;
70
71   explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
72
73   void get(void* data, size_t size) {
74     if (LIKELY(size <= remaining())) {
75       memcpy(data, ptr_, size);
76       ptr_ += size;
77     } else {
78       getSlow(static_cast<unsigned char*>(data), size);
79     }
80   }
81
82  private:
83   void getSlow(unsigned char* data, size_t size);
84
85   inline size_t remaining() const {
86     return buffer_.get() + bufferSize_ - ptr_;
87   }
88
89   const size_t bufferSize_;
90   std::unique_ptr<unsigned char[]> buffer_;
91   unsigned char* ptr_;
92 };
93
94 BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
95   : bufferSize_(bufferSize),
96     buffer_(new unsigned char[bufferSize]),
97     ptr_(buffer_.get() + bufferSize) {  // refill on first use
98 }
99
100 void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
101   DCHECK_GT(size, remaining());
102   if (size >= bufferSize_) {
103     // Just read directly.
104     readRandomDevice(data, size);
105     return;
106   }
107
108   size_t copied = remaining();
109   memcpy(data, ptr_, copied);
110   data += copied;
111   size -= copied;
112
113   // refill
114   readRandomDevice(buffer_.get(), bufferSize_);
115   ptr_ = buffer_.get();
116
117   memcpy(data, ptr_, size);
118   ptr_ += size;
119 }
120
121
122 }  // namespace
123
124 void Random::secureRandom(void* data, size_t size) {
125   static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
126   bufferedRandomDevice->get(data, size);
127 }
128
129 class ThreadLocalPRNG::LocalInstancePRNG {
130  public:
131   LocalInstancePRNG() : rng(Random::create()) { }
132
133   Random::DefaultGenerator rng;
134 };
135
136 ThreadLocalPRNG::ThreadLocalPRNG() {
137   static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance;
138   local_ = localInstance.get();
139 }
140
141 uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {
142   return local->rng();
143 }
144
145 }