Utils.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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[16]; // secret state
  237. static uint64_t randomBuf[8192]; // next batch of random bytes
  238. static unsigned long randomPtr = sizeof(randomBuf); // refresh on first iteration
  239. // This secure random function gets entropy from the system random source (e.g. /dev/urandom),
  240. // CPU random instructions if present, and other sources and uses them to initialize a SHA/AES
  241. // based CSPRNG with a large state. System random sources are not used directly to mitigate
  242. // against cases where the system random source is broken in some way, which does happen from
  243. // time to time.
  244. Mutex::Lock gl(globalLock);
  245. for(unsigned int i=0;i<bytes;++i) {
  246. if (randomPtr >= sizeof(randomBuf)) {
  247. randomPtr = 0;
  248. if (!initialized) {
  249. initialized = true;
  250. // Fill both randomState and randomBuf from system random source. Failure here
  251. // is fatal to the running application and indicates a serious system problem.
  252. // This is some of the only OS-specific code in the core.
  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. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  264. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  265. exit(1);
  266. }
  267. CryptReleaseContext(cryptProvider,0);
  268. #else
  269. int devURandomFd = ::open("/dev/urandom",O_RDONLY);
  270. if (devURandomFd < 0) {
  271. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to open /dev/urandom\n");
  272. exit(1);
  273. }
  274. if ((long)::read(devURandomFd,randomState,sizeof(randomState)) != (long)sizeof(randomState)) {
  275. ::close(devURandomFd);
  276. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  277. exit(1);
  278. }
  279. if ((long)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (long)sizeof(randomBuf)) {
  280. ::close(devURandomFd);
  281. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  282. exit(1);
  283. }
  284. close(devURandomFd);
  285. #endif
  286. // Mix in additional entropy from time, the address of 'buf', rdrand if present, etc.
  287. randomState[0] ^= (uint64_t)time(nullptr);
  288. randomState[1] ^= (uint64_t)((uintptr_t)buf);
  289. #ifdef __UNIX_LIKE__
  290. randomState[2] ^= (uint64_t)getpid();
  291. randomState[3] ^= (uint64_t)getppid();
  292. #endif
  293. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  294. if (CPUID.rdrand) {
  295. uint64_t tmp = 0;
  296. for(int i=0;i<16;++i) {
  297. _rdrand64_step((unsigned long long *)&tmp);
  298. randomState[i] ^= tmp;
  299. }
  300. }
  301. #endif
  302. }
  303. // Generate a new randomBuf:
  304. //
  305. // (1) Generate next randomState by perturbing, hashing, and replacing the first 384 bits with the hash.
  306. // (2) Initialize AES using the first 256 bits of the new randomState as its key.
  307. // (3) Initialize a 128-bit counter field using the following 128 bits of randomState.
  308. // (4) Encrypt randomBuf with AES-CTR (machine-endian counter since spec conformance doesn't matter).
  309. ++randomState[15];
  310. SHA384(randomState,randomState,sizeof(randomState));
  311. AES aes(randomState);
  312. uint64_t ctr[2],tmp[2];
  313. ctr[0] = randomState[4];
  314. ctr[1] = randomState[5]; // AES key + CTR/nonce = part replaced each time by SHA384
  315. for(int k=0;k<8192;) {
  316. ++ctr[0];
  317. aes.encrypt(ctr,tmp);
  318. randomBuf[k] ^= tmp[0];
  319. randomBuf[k+1] ^= tmp[1];
  320. k += 2;
  321. }
  322. }
  323. reinterpret_cast<uint8_t *>(buf)[i] = reinterpret_cast<uint8_t *>(randomBuf)[randomPtr++];
  324. }
  325. }
  326. uint64_t getSecureRandomU64() noexcept
  327. {
  328. uint64_t tmp = 0;
  329. getSecureRandom(&tmp,sizeof(tmp));
  330. return tmp;
  331. }
  332. int b32e(const uint8_t *data,int length,char *result,int bufSize) noexcept
  333. {
  334. if (length < 0 || length > (1 << 28)) {
  335. result[0] = (char)0;
  336. return -1;
  337. }
  338. int count = 0;
  339. if (length > 0) {
  340. int buffer = data[0];
  341. int next = 1;
  342. int bitsLeft = 8;
  343. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  344. if (bitsLeft < 5) {
  345. if (next < length) {
  346. buffer <<= 8U;
  347. buffer |= data[next++] & 0xffU;
  348. bitsLeft += 8;
  349. } else {
  350. int pad = 5 - bitsLeft;
  351. buffer <<= pad;
  352. bitsLeft += pad;
  353. }
  354. }
  355. int index = 0x1f & (buffer >> (unsigned int)(bitsLeft - 5));
  356. bitsLeft -= 5;
  357. result[count++] = "abcdefghijklmnopqrstuvwxyz234567"[index];
  358. }
  359. }
  360. if (count < bufSize) {
  361. result[count] = (char)0;
  362. return count;
  363. }
  364. result[0] = (char)0;
  365. return -1;
  366. }
  367. int b32d(const char *encoded,uint8_t *result,int bufSize) noexcept
  368. {
  369. int buffer = 0;
  370. int bitsLeft = 0;
  371. int count = 0;
  372. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  373. uint8_t ch = *ptr;
  374. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  375. continue;
  376. }
  377. buffer <<= 5;
  378. if (ch == '0') {
  379. ch = 'O';
  380. } else if (ch == '1') {
  381. ch = 'L';
  382. } else if (ch == '8') {
  383. ch = 'B';
  384. }
  385. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  386. ch = (ch & 0x1f) - 1;
  387. } else if (ch >= '2' && ch <= '7') {
  388. ch -= '2' - 26;
  389. } else {
  390. return -1;
  391. }
  392. buffer |= ch;
  393. bitsLeft += 5;
  394. if (bitsLeft >= 8) {
  395. result[count++] = buffer >> (bitsLeft - 8);
  396. bitsLeft -= 8;
  397. }
  398. }
  399. if (count < bufSize)
  400. result[count] = (uint8_t)0;
  401. return count;
  402. }
  403. uint64_t random() noexcept
  404. {
  405. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  406. static volatile uint64_t s_s0 = getSecureRandomU64();
  407. static volatile uint64_t s_s1 = getSecureRandomU64();
  408. static volatile uint64_t s_s2 = getSecureRandomU64();
  409. static volatile uint64_t s_s3 = getSecureRandomU64();
  410. uint64_t s0 = s_s0;
  411. uint64_t s1 = s_s1;
  412. uint64_t s2 = s_s2;
  413. uint64_t s3 = s_s3;
  414. const uint64_t s1x5 = s1 * 5;
  415. const uint64_t result = ((s1x5 << 7U)|(s1x5 >> 57U)) * 9;
  416. const uint64_t t = s1 << 17U;
  417. s2 ^= s0;
  418. s3 ^= s1;
  419. s1 ^= s2;
  420. s0 ^= s3;
  421. s2 ^= t;
  422. s3 = ((s3 << 45U)|(s3 >> 19U));
  423. s_s0 = s0;
  424. s_s1 = s1;
  425. s_s2 = s2;
  426. s_s3 = s3;
  427. return result;
  428. }
  429. bool scopy(char *dest,unsigned int len,const char *src) noexcept
  430. {
  431. if (!len)
  432. return false; // sanity check
  433. if (!src) {
  434. *dest = (char)0;
  435. return true;
  436. }
  437. char *const end = dest + len;
  438. while ((*dest++ = *src++)) {
  439. if (dest == end) {
  440. *(--dest) = (char)0;
  441. return false;
  442. }
  443. }
  444. return true;
  445. }
  446. } // namespace Utils
  447. } // namespace ZeroTier