Utils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 *hex(const void *d,unsigned int l,char *s) noexcept
  178. {
  179. char *const save = s;
  180. for(unsigned int i=0;i<l;++i) {
  181. const unsigned int b = reinterpret_cast<const uint8_t *>(d)[i];
  182. *(s++) = HEXCHARS[b >> 4U];
  183. *(s++) = HEXCHARS[b & 0xfU];
  184. }
  185. *s = (char)0;
  186. return save;
  187. }
  188. unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen) noexcept
  189. {
  190. unsigned int l = 0;
  191. const char *hend = h + hlen;
  192. while (l < buflen) {
  193. if (h == hend) break;
  194. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  195. if (!hc) break;
  196. uint8_t c = 0;
  197. if ((hc >= 48)&&(hc <= 57))
  198. c = hc - 48;
  199. else if ((hc >= 97)&&(hc <= 102))
  200. c = hc - 87;
  201. else if ((hc >= 65)&&(hc <= 70))
  202. c = hc - 55;
  203. if (h == hend) break;
  204. hc = *(reinterpret_cast<const uint8_t *>(h++));
  205. if (!hc) break;
  206. c <<= 4;
  207. if ((hc >= 48)&&(hc <= 57))
  208. c |= hc - 48;
  209. else if ((hc >= 97)&&(hc <= 102))
  210. c |= hc - 87;
  211. else if ((hc >= 65)&&(hc <= 70))
  212. c |= hc - 55;
  213. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  214. }
  215. return l;
  216. }
  217. void getSecureRandom(void *buf,unsigned int bytes) noexcept
  218. {
  219. static Mutex globalLock;
  220. static bool initialized = false;
  221. static uint64_t randomState[16]; // secret state
  222. static uint64_t randomBuf[8192]; // next batch of random bytes
  223. static unsigned long randomPtr = sizeof(randomBuf); // refresh on first iteration
  224. // This secure random function gets entropy from the system random source (e.g. /dev/urandom),
  225. // CPU random instructions if present, and other sources and uses them to initialize a SHA/AES
  226. // based CSPRNG with a large state. System random sources are not used directly to mitigate
  227. // against cases where the system random source is broken in some way, which does happen from
  228. // time to time.
  229. Mutex::Lock gl(globalLock);
  230. for(unsigned int i=0;i<bytes;++i) {
  231. if (randomPtr >= sizeof(randomBuf)) {
  232. randomPtr = 0;
  233. if (!initialized) {
  234. initialized = true;
  235. // Fill both randomState and randomBuf from system random source. Failure here
  236. // is fatal to the running application and indicates a serious system problem.
  237. // This is some of the only OS-specific code in the core.
  238. #ifdef __WINDOWS__
  239. HCRYPTPROV cryptProvider = NULL;
  240. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  241. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  242. exit(1);
  243. }
  244. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomState),(BYTE *)randomState)) {
  245. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  246. exit(1);
  247. }
  248. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  249. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  250. exit(1);
  251. }
  252. CryptReleaseContext(cryptProvider,0);
  253. #else
  254. int devURandomFd = ::open("/dev/urandom",O_RDONLY);
  255. if (devURandomFd < 0) {
  256. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to open /dev/urandom\n");
  257. exit(1);
  258. }
  259. if ((long)::read(devURandomFd,randomState,sizeof(randomState)) != (long)sizeof(randomState)) {
  260. ::close(devURandomFd);
  261. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  262. exit(1);
  263. }
  264. if ((long)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (long)sizeof(randomBuf)) {
  265. ::close(devURandomFd);
  266. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  267. exit(1);
  268. }
  269. close(devURandomFd);
  270. #endif
  271. // Mix in additional entropy from time, the address of 'buf', rdrand if present, etc.
  272. randomState[0] ^= (uint64_t)time(nullptr);
  273. randomState[1] ^= (uint64_t)((uintptr_t)buf);
  274. #ifdef __UNIX_LIKE__
  275. randomState[2] ^= (uint64_t)getpid();
  276. randomState[3] ^= (uint64_t)getppid();
  277. #endif
  278. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  279. if (CPUID.rdrand) {
  280. uint64_t tmp = 0;
  281. for(int k=0;k<16;++k) {
  282. _rdrand64_step((unsigned long long *)&tmp);
  283. randomState[k] ^= tmp;
  284. }
  285. }
  286. #endif
  287. }
  288. // Generate a new randomBuf:
  289. //
  290. // (1) Generate next randomState by perturbing, hashing, and replacing the first 384 bits with the hash.
  291. // (2) Initialize AES using the first 256 bits of the new randomState as its key.
  292. // (3) Initialize a 128-bit counter field using the following 128 bits of randomState.
  293. // (4) Encrypt randomBuf with AES-CTR (machine-endian counter since spec conformance doesn't matter).
  294. ++randomState[15];
  295. SHA384(randomState,randomState,sizeof(randomState));
  296. AES aes(randomState);
  297. uint64_t ctr[2],tmp[2];
  298. ctr[0] = randomState[4];
  299. ctr[1] = randomState[5]; // AES key + CTR/nonce = part replaced each time by SHA384
  300. for(int k=0;k<8192;k+=2) {
  301. ++ctr[0];
  302. aes.encrypt(ctr,tmp);
  303. randomBuf[k] ^= tmp[0];
  304. randomBuf[k+1] ^= tmp[1];
  305. }
  306. }
  307. reinterpret_cast<uint8_t *>(buf)[i] = reinterpret_cast<uint8_t *>(randomBuf)[randomPtr++];
  308. }
  309. }
  310. uint64_t getSecureRandomU64() noexcept
  311. {
  312. uint64_t tmp = 0;
  313. getSecureRandom(&tmp,sizeof(tmp));
  314. return tmp;
  315. }
  316. int b32e(const uint8_t *data,int length,char *result,int bufSize) noexcept
  317. {
  318. if (length < 0 || length > (1 << 28)) {
  319. result[0] = (char)0;
  320. return -1;
  321. }
  322. int count = 0;
  323. if (length > 0) {
  324. int buffer = data[0];
  325. int next = 1;
  326. int bitsLeft = 8;
  327. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  328. if (bitsLeft < 5) {
  329. if (next < length) {
  330. buffer <<= 8U;
  331. buffer |= data[next++] & 0xffU;
  332. bitsLeft += 8;
  333. } else {
  334. int pad = 5 - bitsLeft;
  335. buffer <<= pad;
  336. bitsLeft += pad;
  337. }
  338. }
  339. int index = 0x1f & (buffer >> (unsigned int)(bitsLeft - 5));
  340. bitsLeft -= 5;
  341. result[count++] = "abcdefghijklmnopqrstuvwxyz234567"[index];
  342. }
  343. }
  344. if (count < bufSize) {
  345. result[count] = (char)0;
  346. return count;
  347. }
  348. result[0] = (char)0;
  349. return -1;
  350. }
  351. int b32d(const char *encoded,uint8_t *result,int bufSize) noexcept
  352. {
  353. int buffer = 0;
  354. int bitsLeft = 0;
  355. int count = 0;
  356. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  357. uint8_t ch = *ptr;
  358. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  359. continue;
  360. }
  361. buffer <<= 5;
  362. if (ch == '0') {
  363. ch = 'O';
  364. } else if (ch == '1') {
  365. ch = 'L';
  366. } else if (ch == '8') {
  367. ch = 'B';
  368. }
  369. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  370. ch = (ch & 0x1f) - 1;
  371. } else if (ch >= '2' && ch <= '7') {
  372. ch -= '2' - 26;
  373. } else {
  374. return -1;
  375. }
  376. buffer |= ch;
  377. bitsLeft += 5;
  378. if (bitsLeft >= 8) {
  379. result[count++] = buffer >> (bitsLeft - 8);
  380. bitsLeft -= 8;
  381. }
  382. }
  383. if (count < bufSize)
  384. result[count] = (uint8_t)0;
  385. return count;
  386. }
  387. uint64_t random() noexcept
  388. {
  389. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  390. static volatile uint64_t s_s0 = getSecureRandomU64();
  391. static volatile uint64_t s_s1 = getSecureRandomU64();
  392. static volatile uint64_t s_s2 = getSecureRandomU64();
  393. static volatile uint64_t s_s3 = getSecureRandomU64();
  394. uint64_t s0 = s_s0;
  395. uint64_t s1 = s_s1;
  396. uint64_t s2 = s_s2;
  397. uint64_t s3 = s_s3;
  398. const uint64_t s1x5 = s1 * 5;
  399. const uint64_t result = ((s1x5 << 7U)|(s1x5 >> 57U)) * 9;
  400. const uint64_t t = s1 << 17U;
  401. s2 ^= s0;
  402. s3 ^= s1;
  403. s1 ^= s2;
  404. s0 ^= s3;
  405. s2 ^= t;
  406. s3 = ((s3 << 45U)|(s3 >> 19U));
  407. s_s0 = s0;
  408. s_s1 = s1;
  409. s_s2 = s2;
  410. s_s3 = s3;
  411. return result;
  412. }
  413. bool scopy(char *dest,unsigned int len,const char *src) noexcept
  414. {
  415. if (!len)
  416. return false; // sanity check
  417. if (!src) {
  418. *dest = (char)0;
  419. return true;
  420. }
  421. char *const end = dest + len;
  422. while ((*dest++ = *src++)) {
  423. if (dest == end) {
  424. *(--dest) = (char)0;
  425. return false;
  426. }
  427. }
  428. return true;
  429. }
  430. } // namespace Utils
  431. } // namespace ZeroTier