Utils.cpp 13 KB

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