Utils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 <cstdio>
  14. #include <cstdlib>
  15. #include <ctime>
  16. #include "Utils.hpp"
  17. #include "Mutex.hpp"
  18. #include "AES.hpp"
  19. #include "SHA512.hpp"
  20. #ifdef __UNIX_LIKE__
  21. #include <unistd.h>
  22. #include <fcntl.h>
  23. #include <sys/uio.h>
  24. #endif
  25. #ifdef __WINDOWS__
  26. #include <wincrypt.h>
  27. #endif
  28. namespace ZeroTier {
  29. namespace Utils {
  30. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  31. CPUIDRegisters::CPUIDRegisters()
  32. {
  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) ); // AES, PCLMUL, SSE4.1
  49. }
  50. const CPUIDRegisters CPUID;
  51. #endif
  52. const uint64_t ZERO256[4] = { 0,0,0,0 };
  53. const char HEXCHARS[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
  54. bool secureEq(const void *a,const void *b,unsigned int len) noexcept
  55. {
  56. uint8_t diff = 0;
  57. for(unsigned int i=0;i<len;++i)
  58. diff |= ( (reinterpret_cast<const uint8_t *>(a))[i] ^ (reinterpret_cast<const uint8_t *>(b))[i] );
  59. return (diff == 0);
  60. }
  61. // Crazy hack to force memory to be securely zeroed in spite of the best efforts of optimizing compilers.
  62. static void _Utils_doBurn(volatile uint8_t *ptr,unsigned int len)
  63. {
  64. #ifndef ZT_NO_UNALIGNED_ACCESS
  65. const uint64_t z = 0;
  66. while (len >= 32) {
  67. *reinterpret_cast<volatile uint64_t *>(ptr) = z;
  68. *reinterpret_cast<volatile uint64_t *>(ptr + 8) = z;
  69. *reinterpret_cast<volatile uint64_t *>(ptr + 16) = z;
  70. *reinterpret_cast<volatile uint64_t *>(ptr + 24) = z;
  71. ptr += 32;
  72. len -= 32;
  73. }
  74. while (len >= 8) {
  75. *reinterpret_cast<volatile uint64_t *>(ptr) = z;
  76. ptr += 8;
  77. len -= 8;
  78. }
  79. #endif
  80. for(unsigned int i=0;i<len;++i)
  81. ptr[i] = 0;
  82. }
  83. static void (*volatile _Utils_doBurn_ptr)(volatile uint8_t *,unsigned int) = _Utils_doBurn;
  84. void burn(void *ptr,unsigned int len) { (_Utils_doBurn_ptr)((volatile uint8_t *)ptr,len); }
  85. static unsigned long _Utils_itoa(unsigned long n,char *s)
  86. {
  87. if (n == 0)
  88. return 0;
  89. unsigned long pos = _Utils_itoa(n / 10,s);
  90. if (pos >= 22) // sanity check,should be impossible
  91. pos = 22;
  92. s[pos] = (char)('0' + (n % 10));
  93. return pos + 1;
  94. }
  95. char *decimal(unsigned long n,char s[24]) noexcept
  96. {
  97. if (n == 0) {
  98. s[0] = '0';
  99. s[1] = (char)0;
  100. return s;
  101. }
  102. s[_Utils_itoa(n,s)] = (char)0;
  103. return s;
  104. }
  105. char *hex(uint8_t i,char s[3]) noexcept
  106. {
  107. s[0] = HEXCHARS[(i >> 4U) & 0xfU];
  108. s[1] = HEXCHARS[i & 0xfU];
  109. s[2] = 0;
  110. return s;
  111. }
  112. char *hex(uint16_t i,char s[5]) noexcept
  113. {
  114. s[0] = HEXCHARS[(i >> 12U) & 0xfU];
  115. s[1] = HEXCHARS[(i >> 8U) & 0xfU];
  116. s[2] = HEXCHARS[(i >> 4U) & 0xfU];
  117. s[3] = HEXCHARS[i & 0xfU];
  118. s[4] = 0;
  119. return s;
  120. }
  121. char *hex(uint32_t i,char s[9]) noexcept
  122. {
  123. s[0] = HEXCHARS[(i >> 28U) & 0xfU];
  124. s[1] = HEXCHARS[(i >> 24U) & 0xfU];
  125. s[2] = HEXCHARS[(i >> 20U) & 0xfU];
  126. s[3] = HEXCHARS[(i >> 16U) & 0xfU];
  127. s[4] = HEXCHARS[(i >> 12U) & 0xfU];
  128. s[5] = HEXCHARS[(i >> 8U) & 0xfU];
  129. s[6] = HEXCHARS[(i >> 4U) & 0xfU];
  130. s[7] = HEXCHARS[i & 0xfU];
  131. s[8] = 0;
  132. return s;
  133. }
  134. char *hex(uint64_t i,char s[17]) noexcept
  135. {
  136. s[0] = HEXCHARS[(i >> 60U) & 0xfU];
  137. s[1] = HEXCHARS[(i >> 56U) & 0xfU];
  138. s[2] = HEXCHARS[(i >> 52U) & 0xfU];
  139. s[3] = HEXCHARS[(i >> 48U) & 0xfU];
  140. s[4] = HEXCHARS[(i >> 44U) & 0xfU];
  141. s[5] = HEXCHARS[(i >> 40U) & 0xfU];
  142. s[6] = HEXCHARS[(i >> 36U) & 0xfU];
  143. s[7] = HEXCHARS[(i >> 32U) & 0xfU];
  144. s[8] = HEXCHARS[(i >> 28U) & 0xfU];
  145. s[9] = HEXCHARS[(i >> 24U) & 0xfU];
  146. s[10] = HEXCHARS[(i >> 20U) & 0xfU];
  147. s[11] = HEXCHARS[(i >> 16U) & 0xfU];
  148. s[12] = HEXCHARS[(i >> 12U) & 0xfU];
  149. s[13] = HEXCHARS[(i >> 8U) & 0xfU];
  150. s[14] = HEXCHARS[(i >> 4U) & 0xfU];
  151. s[15] = HEXCHARS[i & 0xfU];
  152. s[16] = 0;
  153. return s;
  154. }
  155. uint64_t unhex(const char *s) noexcept
  156. {
  157. uint64_t n = 0;
  158. if (s) {
  159. int k = 0;
  160. while (k < 16) {
  161. char hc = *(s++);
  162. if (!hc) break;
  163. uint8_t c = 0;
  164. if ((hc >= 48)&&(hc <= 57))
  165. c = hc - 48;
  166. else if ((hc >= 97)&&(hc <= 102))
  167. c = hc - 87;
  168. else if ((hc >= 65)&&(hc <= 70))
  169. c = hc - 55;
  170. n <<= 4U;
  171. n |= (uint64_t)c;
  172. ++k;
  173. }
  174. }
  175. return n;
  176. }
  177. char *hex10(uint64_t i,char s[11]) noexcept
  178. {
  179. s[0] = HEXCHARS[(i >> 36U) & 0xfU];
  180. s[1] = HEXCHARS[(i >> 32U) & 0xfU];
  181. s[2] = HEXCHARS[(i >> 28U) & 0xfU];
  182. s[3] = HEXCHARS[(i >> 24U) & 0xfU];
  183. s[4] = HEXCHARS[(i >> 20U) & 0xfU];
  184. s[5] = HEXCHARS[(i >> 16U) & 0xfU];
  185. s[6] = HEXCHARS[(i >> 12U) & 0xfU];
  186. s[7] = HEXCHARS[(i >> 8U) & 0xfU];
  187. s[8] = HEXCHARS[(i >> 4U) & 0xfU];
  188. s[9] = HEXCHARS[i & 0xfU];
  189. s[10] = (char)0;
  190. return s;
  191. }
  192. char *hex(const void *d,unsigned int l,char *s) noexcept
  193. {
  194. char *const save = s;
  195. for(unsigned int i=0;i<l;++i) {
  196. const unsigned int b = reinterpret_cast<const uint8_t *>(d)[i];
  197. *(s++) = HEXCHARS[b >> 4U];
  198. *(s++) = HEXCHARS[b & 0xfU];
  199. }
  200. *s = (char)0;
  201. return save;
  202. }
  203. unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen) noexcept
  204. {
  205. unsigned int l = 0;
  206. const char *hend = h + hlen;
  207. while (l < buflen) {
  208. if (h == hend) break;
  209. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  210. if (!hc) break;
  211. uint8_t c = 0;
  212. if ((hc >= 48)&&(hc <= 57))
  213. c = hc - 48;
  214. else if ((hc >= 97)&&(hc <= 102))
  215. c = hc - 87;
  216. else if ((hc >= 65)&&(hc <= 70))
  217. c = hc - 55;
  218. if (h == hend) break;
  219. hc = *(reinterpret_cast<const uint8_t *>(h++));
  220. if (!hc) break;
  221. c <<= 4;
  222. if ((hc >= 48)&&(hc <= 57))
  223. c |= hc - 48;
  224. else if ((hc >= 97)&&(hc <= 102))
  225. c |= hc - 87;
  226. else if ((hc >= 65)&&(hc <= 70))
  227. c |= hc - 55;
  228. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  229. }
  230. return l;
  231. }
  232. void getSecureRandom(void *buf,unsigned int bytes) noexcept
  233. {
  234. static Mutex globalLock;
  235. static bool initialized = false;
  236. static uint64_t randomState[8];
  237. static uint64_t randomBuf[8192];
  238. static unsigned int randomPtr = 65536;
  239. Mutex::Lock gl(globalLock);
  240. for(unsigned int i=0;i<bytes;++i) {
  241. if (randomPtr >= 65536) {
  242. randomPtr = 0;
  243. if (!initialized) {
  244. initialized = true;
  245. #ifdef __WINDOWS__
  246. HCRYPTPROV cryptProvider = NULL;
  247. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  248. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  249. exit(1);
  250. }
  251. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomState),(BYTE *)randomState)) {
  252. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  253. exit(1);
  254. }
  255. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  256. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  257. exit(1);
  258. }
  259. CryptReleaseContext(cryptProvider,0);
  260. #else
  261. int devURandomFd = ::open("/dev/urandom",O_RDONLY);
  262. if (devURandomFd < 0) {
  263. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to open /dev/urandom\n");
  264. exit(1);
  265. }
  266. if ((int)::read(devURandomFd,randomState,sizeof(randomState)) != (int)sizeof(randomState)) {
  267. ::close(devURandomFd);
  268. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  269. exit(1);
  270. }
  271. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  272. ::close(devURandomFd);
  273. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  274. exit(1);
  275. }
  276. close(devURandomFd);
  277. #endif
  278. // Mix in additional entropy just in case the standard random source is wonky somehow
  279. randomState[0] ^= (uint64_t)time(nullptr);
  280. randomState[1] ^= (uint64_t)((uintptr_t)buf);
  281. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  282. if (CPUID.rdrand) {
  283. uint64_t tmp = 0;
  284. _rdrand64_step((unsigned long long *)&tmp);
  285. randomState[2] ^= tmp;
  286. _rdrand64_step((unsigned long long *)&tmp);
  287. randomState[3] ^= tmp;
  288. }
  289. #endif
  290. }
  291. ++randomState[0];
  292. SHA512(randomState,randomState,sizeof(randomState));
  293. AES aes(reinterpret_cast<const uint8_t *>(randomState));
  294. uint64_t ctr[2],tmp[2];
  295. ctr[0] = randomState[6];
  296. ctr[1] = randomState[7];
  297. for(int k=0;k<8192;) {
  298. ++ctr[0];
  299. aes.encrypt(reinterpret_cast<const uint8_t *>(ctr),reinterpret_cast<uint8_t *>(tmp));
  300. randomBuf[k] ^= tmp[0];
  301. randomBuf[k+1] ^= tmp[1];
  302. k += 2;
  303. }
  304. }
  305. reinterpret_cast<uint8_t *>(buf)[i] = reinterpret_cast<uint8_t *>(randomBuf)[randomPtr++];
  306. }
  307. }
  308. uint64_t getSecureRandomU64() noexcept
  309. {
  310. uint64_t tmp = 0;
  311. getSecureRandom(&tmp,sizeof(tmp));
  312. return tmp;
  313. }
  314. int b32e(const uint8_t *data,int length,char *result,int bufSize) noexcept
  315. {
  316. if (length < 0 || length > (1 << 28)) {
  317. result[0] = (char)0;
  318. return -1;
  319. }
  320. int count = 0;
  321. if (length > 0) {
  322. int buffer = data[0];
  323. int next = 1;
  324. int bitsLeft = 8;
  325. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  326. if (bitsLeft < 5) {
  327. if (next < length) {
  328. buffer <<= 8U;
  329. buffer |= data[next++] & 0xffU;
  330. bitsLeft += 8;
  331. } else {
  332. int pad = 5 - bitsLeft;
  333. buffer <<= pad;
  334. bitsLeft += pad;
  335. }
  336. }
  337. int index = 0x1f & (buffer >> (unsigned int)(bitsLeft - 5));
  338. bitsLeft -= 5;
  339. result[count++] = "abcdefghijklmnopqrstuvwxyz234567"[index];
  340. }
  341. }
  342. if (count < bufSize) {
  343. result[count] = (char)0;
  344. return count;
  345. }
  346. result[0] = (char)0;
  347. return -1;
  348. }
  349. int b32d(const char *encoded,uint8_t *result,int bufSize) noexcept
  350. {
  351. int buffer = 0;
  352. int bitsLeft = 0;
  353. int count = 0;
  354. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  355. uint8_t ch = *ptr;
  356. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  357. continue;
  358. }
  359. buffer <<= 5;
  360. if (ch == '0') {
  361. ch = 'O';
  362. } else if (ch == '1') {
  363. ch = 'L';
  364. } else if (ch == '8') {
  365. ch = 'B';
  366. }
  367. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  368. ch = (ch & 0x1f) - 1;
  369. } else if (ch >= '2' && ch <= '7') {
  370. ch -= '2' - 26;
  371. } else {
  372. return -1;
  373. }
  374. buffer |= ch;
  375. bitsLeft += 5;
  376. if (bitsLeft >= 8) {
  377. result[count++] = buffer >> (bitsLeft - 8);
  378. bitsLeft -= 8;
  379. }
  380. }
  381. if (count < bufSize)
  382. result[count] = (uint8_t)0;
  383. return count;
  384. }
  385. #define ROL64(x,k) (((x) << (k)) | ((x) >> (64 - (k))))
  386. uint64_t random() noexcept
  387. {
  388. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  389. static volatile uint64_t s_s0 = getSecureRandomU64();
  390. static volatile uint64_t s_s1 = getSecureRandomU64();
  391. static volatile uint64_t s_s2 = getSecureRandomU64();
  392. static volatile uint64_t s_s3 = getSecureRandomU64();
  393. uint64_t s0 = s_s0;
  394. uint64_t s1 = s_s1;
  395. uint64_t s2 = s_s2;
  396. uint64_t s3 = s_s3;
  397. const uint64_t result = ROL64(s1 * 5,7U) * 9;
  398. const uint64_t t = s1 << 17U;
  399. s2 ^= s0;
  400. s3 ^= s1;
  401. s1 ^= s2;
  402. s0 ^= s3;
  403. s2 ^= t;
  404. s3 = ROL64(s3,45U);
  405. s_s0 = s0;
  406. s_s1 = s1;
  407. s_s2 = s2;
  408. s_s3 = s3;
  409. return result;
  410. }
  411. bool scopy(char *dest,unsigned int len,const char *src) noexcept
  412. {
  413. if (!len)
  414. return false; // sanity check
  415. if (!src) {
  416. *dest = (char)0;
  417. return true;
  418. }
  419. char *const end = dest + len;
  420. while ((*dest++ = *src++)) {
  421. if (dest == end) {
  422. *(--dest) = (char)0;
  423. return false;
  424. }
  425. }
  426. return true;
  427. }
  428. } // namespace Utils
  429. } // namespace ZeroTier