Utils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "Utils.hpp"
  14. #include "Mutex.hpp"
  15. #include "AES.hpp"
  16. #include "SHA512.hpp"
  17. #ifdef __UNIX_LIKE__
  18. #include <unistd.h>
  19. #include <fcntl.h>
  20. #include <sys/uio.h>
  21. #endif
  22. #include <time.h>
  23. #ifdef __WINDOWS__
  24. #include <wincrypt.h>
  25. #endif
  26. namespace ZeroTier {
  27. namespace Utils {
  28. #ifdef ZT_ARCH_X64
  29. CPUIDRegisters::CPUIDRegisters() noexcept
  30. {
  31. uint32_t eax, ebx, ecx, edx;
  32. #ifdef __WINDOWS__
  33. int regs[4];
  34. __cpuid(regs,1);
  35. eax = (uint32_t)regs[0];
  36. ebx = (uint32_t)regs[1];
  37. ecx = (uint32_t)regs[2];
  38. edx = (uint32_t)regs[3];
  39. #else
  40. __asm__ __volatile__ (
  41. "cpuid"
  42. : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
  43. : "a"(1), "c"(0)
  44. );
  45. #endif
  46. rdrand = ((ecx & (1U << 30U)) != 0);
  47. aes = (((ecx & (1U << 25U)) != 0) && ((ecx & (1U << 19U)) != 0) && ((ecx & (1U << 1U)) != 0));
  48. avx = ((ecx & (1U << 25U)) != 0);
  49. #ifdef __WINDOWS__
  50. __cpuid(regs,7);
  51. eax = (uint32_t)regs[0];
  52. ebx = (uint32_t)regs[1];
  53. ecx = (uint32_t)regs[2];
  54. edx = (uint32_t)regs[3];
  55. #else
  56. __asm__ __volatile__ (
  57. "cpuid"
  58. : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
  59. : "a"(7), "c"(0)
  60. );
  61. #endif
  62. vaes = aes && avx && ((ecx & (1U << 9U)) != 0);
  63. vpclmulqdq = aes && avx && ((ecx & (1U << 10U)) != 0);
  64. avx2 = avx && ((ebx & (1U << 5U)) != 0);
  65. avx512f = avx && ((ebx & (1U << 16U)) != 0);
  66. sha = ((ebx & (1U << 29U)) != 0);
  67. fsrm = sha = ((edx & (1U << 4U)) != 0);
  68. }
  69. const CPUIDRegisters CPUID;
  70. #endif
  71. const std::bad_alloc BadAllocException;
  72. const std::out_of_range OutOfRangeException("access out of range");
  73. const uint64_t ZERO256[4] = {0, 0, 0, 0};
  74. const char HEXCHARS[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  75. const uint64_t s_mapNonce = getSecureRandomU64();
  76. bool secureEq(const void *a, const void *b, unsigned int len) noexcept
  77. {
  78. uint8_t diff = 0;
  79. for (unsigned int i = 0; i < len; ++i)
  80. diff |= ((reinterpret_cast<const uint8_t *>(a))[i] ^ (reinterpret_cast<const uint8_t *>(b))[i]);
  81. return (diff == 0);
  82. }
  83. // Crazy hack to force memory to be securely zeroed in spite of the best efforts of optimizing compilers.
  84. static void _Utils_doBurn(volatile uint8_t *ptr, unsigned int len)
  85. {
  86. for (unsigned int i = 0; i < len; ++i)
  87. ptr[i] = 0;
  88. }
  89. static void (*volatile _Utils_doBurn_ptr)(volatile uint8_t *, unsigned int) = _Utils_doBurn;
  90. void burn(void *ptr, unsigned int len)
  91. { (_Utils_doBurn_ptr)((volatile uint8_t *)ptr, len); }
  92. static unsigned long _Utils_itoa(unsigned long n, char *s)
  93. {
  94. if (n == 0)
  95. return 0;
  96. unsigned long pos = _Utils_itoa(n / 10, s);
  97. if (pos >= 22) // sanity check,should be impossible
  98. pos = 22;
  99. s[pos] = (char)('0' + (n % 10));
  100. return pos + 1;
  101. }
  102. char *decimal(unsigned long n, char s[24]) noexcept
  103. {
  104. if (n == 0) {
  105. s[0] = '0';
  106. s[1] = (char)0;
  107. return s;
  108. }
  109. s[_Utils_itoa(n, s)] = (char)0;
  110. return s;
  111. }
  112. char *hex(uint64_t i, char buf[17]) noexcept
  113. {
  114. if (i != 0) {
  115. char *p = nullptr;
  116. for (int b = 60; b >= 0; b -= 4) {
  117. const unsigned int nyb = (unsigned int)(i >> (unsigned int)b) & 0xfU;
  118. if (p) {
  119. *(p++) = HEXCHARS[nyb];
  120. } else if (nyb != 0) {
  121. p = buf;
  122. *(p++) = HEXCHARS[nyb];
  123. }
  124. }
  125. *p = 0;
  126. return buf;
  127. } else {
  128. buf[0] = '0';
  129. buf[1] = 0;
  130. return buf;
  131. }
  132. }
  133. uint64_t unhex(const char *s) noexcept
  134. {
  135. uint64_t n = 0;
  136. if (s) {
  137. int k = 0;
  138. while (k < 16) {
  139. char hc = *(s++);
  140. if (!hc) break;
  141. uint8_t c = 0;
  142. if ((hc >= 48) && (hc <= 57))
  143. c = (uint8_t)hc - 48;
  144. else if ((hc >= 97) && (hc <= 102))
  145. c = (uint8_t)hc - 87;
  146. else if ((hc >= 65) && (hc <= 70))
  147. c = (uint8_t)hc - 55;
  148. n <<= 4U;
  149. n |= (uint64_t)c;
  150. ++k;
  151. }
  152. }
  153. return n;
  154. }
  155. char *hex(const void *d, unsigned int l, char *s) noexcept
  156. {
  157. char *const save = s;
  158. for (unsigned int i = 0; i < l; ++i) {
  159. const unsigned int b = reinterpret_cast<const uint8_t *>(d)[i];
  160. *(s++) = HEXCHARS[b >> 4U];
  161. *(s++) = HEXCHARS[b & 0xfU];
  162. }
  163. *s = (char)0;
  164. return save;
  165. }
  166. unsigned int unhex(const char *h, unsigned int hlen, void *buf, unsigned int buflen) noexcept
  167. {
  168. unsigned int l = 0;
  169. const char *hend = h + hlen;
  170. while (l < buflen) {
  171. if (h == hend) break;
  172. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  173. if (!hc) break;
  174. uint8_t c = 0;
  175. if ((hc >= 48) && (hc <= 57))
  176. c = hc - 48;
  177. else if ((hc >= 97) && (hc <= 102))
  178. c = hc - 87;
  179. else if ((hc >= 65) && (hc <= 70))
  180. c = hc - 55;
  181. if (h == hend) break;
  182. hc = *(reinterpret_cast<const uint8_t *>(h++));
  183. if (!hc) break;
  184. c <<= 4U;
  185. if ((hc >= 48) && (hc <= 57))
  186. c |= hc - 48;
  187. else if ((hc >= 97) && (hc <= 102))
  188. c |= hc - 87;
  189. else if ((hc >= 65) && (hc <= 70))
  190. c |= hc - 55;
  191. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  192. }
  193. return l;
  194. }
  195. #define ZT_GETSECURERANDOM_STATE_SIZE 64
  196. #define ZT_GETSECURERANDOM_ITERATIONS_PER_GENERATOR 1048576
  197. void getSecureRandom(void *const buf, unsigned int bytes) noexcept
  198. {
  199. static Mutex globalLock;
  200. static bool initialized = false;
  201. static uint64_t randomState[ZT_GETSECURERANDOM_STATE_SIZE];
  202. static unsigned int randomByteCounter = ZT_GETSECURERANDOM_ITERATIONS_PER_GENERATOR; // init on first run
  203. static AES randomGen;
  204. Mutex::Lock gl(globalLock);
  205. // Re-initialize the generator every ITERATIONS_PER_GENERATOR bytes.
  206. if (unlikely((randomByteCounter += bytes) >= ZT_GETSECURERANDOM_ITERATIONS_PER_GENERATOR)) {
  207. // On first run fill randomState with random bits from the system.
  208. if (unlikely(!initialized)) {
  209. initialized = true;
  210. // Don't let randomState be swapped to disk (if supported by OS).
  211. Utils::memoryLock(randomState, sizeof(randomState));
  212. // Fill randomState with entropy from the system. Failure equals hard exit.
  213. Utils::zero< sizeof(randomState) >(randomState);
  214. #ifdef __WINDOWS__
  215. HCRYPTPROV cryptProvider = NULL;
  216. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  217. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  218. exit(1);
  219. }
  220. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomState),(BYTE *)randomState)) {
  221. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  222. exit(1);
  223. }
  224. CryptReleaseContext(cryptProvider,0);
  225. #else
  226. int devURandomFd = ::open("/dev/urandom", O_RDONLY);
  227. if (devURandomFd < 0) {
  228. fprintf(stderr, "FATAL: Utils::getSecureRandom() unable to open /dev/urandom\n");
  229. exit(1);
  230. }
  231. if ((long)::read(devURandomFd, randomState, sizeof(randomState)) != (long)sizeof(randomState)) {
  232. ::close(devURandomFd);
  233. fprintf(stderr, "FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  234. exit(1);
  235. }
  236. close(devURandomFd);
  237. #endif
  238. #ifdef __UNIX_LIKE__
  239. randomState[0] += (uint64_t)getpid();
  240. randomState[1] += (uint64_t)getppid();
  241. #endif
  242. #ifdef ZT_ARCH_X64
  243. if (CPUID.rdrand) {
  244. // RDRAND is very slow on some chips, so only sample it a little bit for extra entropy.
  245. uint64_t tmp = 0;
  246. _rdrand64_step((unsigned long long *)&tmp);
  247. randomState[2] ^= tmp;
  248. _rdrand64_step((unsigned long long *)&tmp);
  249. randomState[3] ^= tmp;
  250. }
  251. #endif
  252. }
  253. // Initialize or re-initialize generator by hashing the full state,
  254. // replacing the first 64 bytes with this hash, and then re-initializing
  255. // AES with the first 32 bytes.
  256. randomByteCounter = 0;
  257. randomState[4] += (uint64_t)((uintptr_t)buf);
  258. randomState[5] += (uint64_t)bytes;
  259. randomState[6] += (uint64_t)time(nullptr);
  260. SHA512(randomState, randomState, sizeof(randomState));
  261. randomGen.init(randomState);
  262. }
  263. // Generate random bytes using AES and bytes 32-48 of randomState as an in-place
  264. // AES-CTR counter. Counter can be machine endian; we don't care about portability
  265. // for a random generator.
  266. uint64_t *const ctr = randomState + 4;
  267. uint8_t *out = reinterpret_cast<uint8_t *>(buf);
  268. while (bytes >= 16) {
  269. ++*ctr;
  270. randomGen.encrypt(ctr, out);
  271. out += 16;
  272. bytes -= 16;
  273. }
  274. if (bytes > 0) {
  275. uint8_t tmp[16];
  276. ++*ctr;
  277. randomGen.encrypt(ctr, tmp);
  278. for (unsigned int i = 0; i < bytes; ++i)
  279. out[i] = tmp[i];
  280. Utils::burn(tmp, sizeof(tmp)); // don't leave used cryptographic randomness lying around!
  281. }
  282. }
  283. uint64_t getSecureRandomU64() noexcept
  284. {
  285. uint64_t tmp = 0;
  286. getSecureRandom(&tmp, sizeof(tmp));
  287. return tmp;
  288. }
  289. int b32e(const uint8_t *data, int length, char *result, int bufSize) noexcept
  290. {
  291. if (length < 0 || length > (1 << 28U)) {
  292. result[0] = (char)0;
  293. return -1;
  294. }
  295. int count = 0;
  296. if (length > 0) {
  297. int buffer = data[0];
  298. int next = 1;
  299. int bitsLeft = 8;
  300. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  301. if (bitsLeft < 5) {
  302. if (next < length) {
  303. buffer <<= 8U;
  304. buffer |= data[next++] & 0xffU;
  305. bitsLeft += 8;
  306. } else {
  307. int pad = 5 - bitsLeft;
  308. buffer <<= pad;
  309. bitsLeft += pad;
  310. }
  311. }
  312. int index = 0x1f & (buffer >> (unsigned int)(bitsLeft - 5));
  313. bitsLeft -= 5;
  314. result[count++] = "abcdefghijklmnopqrstuvwxyz234567"[index];
  315. }
  316. }
  317. if (count < bufSize) {
  318. result[count] = (char)0;
  319. return count;
  320. }
  321. result[0] = (char)0;
  322. return -1;
  323. }
  324. int b32d(const char *encoded, uint8_t *result, int bufSize) noexcept
  325. {
  326. int buffer = 0;
  327. int bitsLeft = 0;
  328. int count = 0;
  329. for (const uint8_t *ptr = (const uint8_t *)encoded; count < bufSize && *ptr; ++ptr) {
  330. uint8_t ch = *ptr;
  331. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  332. continue;
  333. }
  334. buffer <<= 5;
  335. if (ch == '0') {
  336. ch = 'O';
  337. } else if (ch == '1') {
  338. ch = 'L';
  339. } else if (ch == '8') {
  340. ch = 'B';
  341. }
  342. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  343. ch = (ch & 0x1f) - 1;
  344. } else if (ch >= '2' && ch <= '7') {
  345. ch -= '2' - 26;
  346. } else {
  347. return -1;
  348. }
  349. buffer |= ch;
  350. bitsLeft += 5;
  351. if (bitsLeft >= 8) {
  352. result[count++] = buffer >> (bitsLeft - 8);
  353. bitsLeft -= 8;
  354. }
  355. }
  356. if (count < bufSize)
  357. result[count] = (uint8_t)0;
  358. return count;
  359. }
  360. uint64_t random() noexcept
  361. {
  362. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  363. static volatile uint64_t s_s0 = getSecureRandomU64();
  364. static volatile uint64_t s_s1 = getSecureRandomU64();
  365. static volatile uint64_t s_s2 = getSecureRandomU64();
  366. static volatile uint64_t s_s3 = getSecureRandomU64();
  367. uint64_t s0 = s_s0;
  368. uint64_t s1 = s_s1;
  369. uint64_t s2 = s_s2;
  370. uint64_t s3 = s_s3;
  371. const uint64_t s1x5 = s1 * 5;
  372. const uint64_t result = ((s1x5 << 7U) | (s1x5 >> 57U)) * 9;
  373. const uint64_t t = s1 << 17U;
  374. s2 ^= s0;
  375. s3 ^= s1;
  376. s1 ^= s2;
  377. s0 ^= s3;
  378. s2 ^= t;
  379. s3 = ((s3 << 45U) | (s3 >> 19U));
  380. s_s0 = s0;
  381. s_s1 = s1;
  382. s_s2 = s2;
  383. s_s3 = s3;
  384. return result;
  385. }
  386. bool scopy(char *const dest, const unsigned int len, const char *const src) noexcept
  387. {
  388. if (!len)
  389. return false; // sanity check
  390. if (!src) {
  391. *dest = (char)0;
  392. return true;
  393. }
  394. unsigned int i = 0;
  395. for (;;) {
  396. if (i >= len) {
  397. dest[len - 1] = 0;
  398. return false;
  399. }
  400. if ((dest[i] = src[i]) == 0)
  401. return true;
  402. ++i;
  403. }
  404. }
  405. } // namespace Utils
  406. } // namespace ZeroTier