Utils.cpp 11 KB

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