Utils.cpp 12 KB

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