You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

289 lines
7.8 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/base/helpers.h"
  28. #include <limits>
  29. #include "talk/base/sslconfig.h"
  30. #if defined(SSL_USE_OPENSSL)
  31. #include <openssl/rand.h>
  32. #elif defined(SSL_USE_NSS_RNG)
  33. #include "pk11func.h"
  34. #else
  35. #ifdef WIN32
  36. #define WIN32_LEAN_AND_MEAN
  37. #include <windows.h>
  38. #include <ntsecapi.h>
  39. #endif // WIN32
  40. #endif
  41. #include "talk/base/base64.h"
  42. #include "talk/base/basictypes.h"
  43. #include "talk/base/logging.h"
  44. #include "talk/base/scoped_ptr.h"
  45. #include "talk/base/timeutils.h"
  46. // Protect against max macro inclusion.
  47. #undef max
  48. namespace talk_base {
  49. // Base class for RNG implementations.
  50. class RandomGenerator {
  51. public:
  52. virtual ~RandomGenerator() {}
  53. virtual bool Init(const void* seed, size_t len) = 0;
  54. virtual bool Generate(void* buf, size_t len) = 0;
  55. };
  56. #if defined(SSL_USE_OPENSSL)
  57. // The OpenSSL RNG. Need to make sure it doesn't run out of entropy.
  58. class SecureRandomGenerator : public RandomGenerator {
  59. public:
  60. SecureRandomGenerator() : inited_(false) {
  61. }
  62. ~SecureRandomGenerator() {
  63. }
  64. virtual bool Init(const void* seed, size_t len) {
  65. // By default, seed from the system state.
  66. if (!inited_) {
  67. if (RAND_poll() <= 0) {
  68. return false;
  69. }
  70. inited_ = true;
  71. }
  72. // Allow app data to be mixed in, if provided.
  73. if (seed) {
  74. RAND_seed(seed, len);
  75. }
  76. return true;
  77. }
  78. virtual bool Generate(void* buf, size_t len) {
  79. if (!inited_ && !Init(NULL, 0)) {
  80. return false;
  81. }
  82. return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
  83. }
  84. private:
  85. bool inited_;
  86. };
  87. #elif defined(SSL_USE_NSS_RNG)
  88. // The NSS RNG.
  89. class SecureRandomGenerator : public RandomGenerator {
  90. public:
  91. SecureRandomGenerator() {}
  92. ~SecureRandomGenerator() {}
  93. virtual bool Init(const void* seed, size_t len) {
  94. return true;
  95. }
  96. virtual bool Generate(void* buf, size_t len) {
  97. return (PK11_GenerateRandom(reinterpret_cast<unsigned char*>(buf),
  98. static_cast<int>(len)) == SECSuccess);
  99. }
  100. };
  101. #else
  102. #ifdef WIN32
  103. class SecureRandomGenerator : public RandomGenerator {
  104. public:
  105. SecureRandomGenerator() : advapi32_(NULL), rtl_gen_random_(NULL) {}
  106. ~SecureRandomGenerator() {
  107. FreeLibrary(advapi32_);
  108. }
  109. virtual bool Init(const void* seed, size_t seed_len) {
  110. // We don't do any additional seeding on Win32, we just use the CryptoAPI
  111. // RNG (which is exposed as a hidden function off of ADVAPI32 so that we
  112. // don't need to drag in all of CryptoAPI)
  113. if (rtl_gen_random_) {
  114. return true;
  115. }
  116. advapi32_ = LoadLibrary(L"advapi32.dll");
  117. if (!advapi32_) {
  118. return false;
  119. }
  120. rtl_gen_random_ = reinterpret_cast<RtlGenRandomProc>(
  121. GetProcAddress(advapi32_, "SystemFunction036"));
  122. if (!rtl_gen_random_) {
  123. FreeLibrary(advapi32_);
  124. return false;
  125. }
  126. return true;
  127. }
  128. virtual bool Generate(void* buf, size_t len) {
  129. if (!rtl_gen_random_ && !Init(NULL, 0)) {
  130. return false;
  131. }
  132. return (rtl_gen_random_(buf, static_cast<int>(len)) != FALSE);
  133. }
  134. private:
  135. typedef BOOL (WINAPI *RtlGenRandomProc)(PVOID, ULONG);
  136. HINSTANCE advapi32_;
  137. RtlGenRandomProc rtl_gen_random_;
  138. };
  139. #else
  140. #error No SSL implementation has been selected!
  141. #endif // WIN32
  142. #endif
  143. // A test random generator, for predictable output.
  144. class TestRandomGenerator : public RandomGenerator {
  145. public:
  146. TestRandomGenerator() : seed_(7) {
  147. }
  148. ~TestRandomGenerator() {
  149. }
  150. virtual bool Init(const void* seed, size_t len) {
  151. return true;
  152. }
  153. virtual bool Generate(void* buf, size_t len) {
  154. for (size_t i = 0; i < len; ++i) {
  155. static_cast<uint8*>(buf)[i] = static_cast<uint8>(GetRandom());
  156. }
  157. return true;
  158. }
  159. private:
  160. int GetRandom() {
  161. return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
  162. }
  163. int seed_;
  164. };
  165. // TODO: Use Base64::Base64Table instead.
  166. static const char BASE64[64] = {
  167. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  168. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  169. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  170. 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  171. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
  172. };
  173. namespace {
  174. // This round about way of creating a global RNG is to safe-guard against
  175. // indeterminant static initialization order.
  176. scoped_ptr<RandomGenerator>& GetGlobalRng() {
  177. LIBJINGLE_DEFINE_STATIC_LOCAL(scoped_ptr<RandomGenerator>, global_rng,
  178. (new SecureRandomGenerator()));
  179. return global_rng;
  180. }
  181. RandomGenerator& Rng() {
  182. return *GetGlobalRng();
  183. }
  184. } // namespace
  185. void SetRandomTestMode(bool test) {
  186. if (!test) {
  187. GetGlobalRng().reset(new SecureRandomGenerator());
  188. } else {
  189. GetGlobalRng().reset(new TestRandomGenerator());
  190. }
  191. }
  192. bool InitRandom(int seed) {
  193. return InitRandom(reinterpret_cast<const char*>(&seed), sizeof(seed));
  194. }
  195. bool InitRandom(const char* seed, size_t len) {
  196. if (!Rng().Init(seed, len)) {
  197. LOG(LS_ERROR) << "Failed to init random generator!";
  198. return false;
  199. }
  200. return true;
  201. }
  202. std::string CreateRandomString(size_t len) {
  203. std::string str;
  204. CreateRandomString(len, &str);
  205. return str;
  206. }
  207. bool CreateRandomString(size_t len,
  208. const char* table, int table_size,
  209. std::string* str) {
  210. str->clear();
  211. scoped_array<uint8> bytes(new uint8[len]);
  212. if (!Rng().Generate(bytes.get(), len)) {
  213. LOG(LS_ERROR) << "Failed to generate random string!";
  214. return false;
  215. }
  216. str->reserve(len);
  217. for (size_t i = 0; i < len; ++i) {
  218. str->push_back(table[bytes[i] % table_size]);
  219. }
  220. return true;
  221. }
  222. bool CreateRandomString(size_t len, std::string* str) {
  223. return CreateRandomString(len, BASE64, 64, str);
  224. }
  225. bool CreateRandomString(size_t len, const std::string& table,
  226. std::string* str) {
  227. return CreateRandomString(len, table.c_str(),
  228. static_cast<int>(table.size()), str);
  229. }
  230. uint32 CreateRandomId() {
  231. uint32 id;
  232. if (!Rng().Generate(&id, sizeof(id))) {
  233. LOG(LS_ERROR) << "Failed to generate random id!";
  234. }
  235. return id;
  236. }
  237. uint64 CreateRandomId64() {
  238. return static_cast<uint64> (CreateRandomId()) << 32 | CreateRandomId();
  239. }
  240. uint32 CreateRandomNonZeroId() {
  241. uint32 id;
  242. do {
  243. id = CreateRandomId();
  244. } while (id == 0);
  245. return id;
  246. }
  247. double CreateRandomDouble() {
  248. return CreateRandomId() / (std::numeric_limits<uint32>::max() +
  249. std::numeric_limits<double>::epsilon());
  250. }
  251. } // namespace talk_base