Utils.cpp 11 KB

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