Utils.cpp 11 KB

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