Utils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. #ifdef ZT_ARCH_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. for(unsigned int i=0;i<len;++i)
  65. ptr[i] = 0;
  66. }
  67. static void (*volatile _Utils_doBurn_ptr)(volatile uint8_t *,unsigned int) = _Utils_doBurn;
  68. void burn(void *ptr,unsigned int len) { (_Utils_doBurn_ptr)((volatile uint8_t *)ptr,len); }
  69. static unsigned long _Utils_itoa(unsigned long n,char *s)
  70. {
  71. if (n == 0)
  72. return 0;
  73. unsigned long pos = _Utils_itoa(n / 10,s);
  74. if (pos >= 22) // sanity check,should be impossible
  75. pos = 22;
  76. s[pos] = (char)('0' + (n % 10));
  77. return pos + 1;
  78. }
  79. char *decimal(unsigned long n,char s[24]) noexcept
  80. {
  81. if (n == 0) {
  82. s[0] = '0';
  83. s[1] = (char)0;
  84. return s;
  85. }
  86. s[_Utils_itoa(n,s)] = (char)0;
  87. return s;
  88. }
  89. char *hex(uint8_t i,char s[3]) noexcept
  90. {
  91. s[0] = HEXCHARS[(i >> 4U) & 0xfU];
  92. s[1] = HEXCHARS[i & 0xfU];
  93. s[2] = 0;
  94. return s;
  95. }
  96. char *hex(uint16_t i,char s[5]) noexcept
  97. {
  98. s[0] = HEXCHARS[(i >> 12U) & 0xfU];
  99. s[1] = HEXCHARS[(i >> 8U) & 0xfU];
  100. s[2] = HEXCHARS[(i >> 4U) & 0xfU];
  101. s[3] = HEXCHARS[i & 0xfU];
  102. s[4] = 0;
  103. return s;
  104. }
  105. char *hex(uint32_t i,char s[9]) noexcept
  106. {
  107. s[0] = HEXCHARS[(i >> 28U) & 0xfU];
  108. s[1] = HEXCHARS[(i >> 24U) & 0xfU];
  109. s[2] = HEXCHARS[(i >> 20U) & 0xfU];
  110. s[3] = HEXCHARS[(i >> 16U) & 0xfU];
  111. s[4] = HEXCHARS[(i >> 12U) & 0xfU];
  112. s[5] = HEXCHARS[(i >> 8U) & 0xfU];
  113. s[6] = HEXCHARS[(i >> 4U) & 0xfU];
  114. s[7] = HEXCHARS[i & 0xfU];
  115. s[8] = 0;
  116. return s;
  117. }
  118. char *hex(uint64_t i,char s[17]) noexcept
  119. {
  120. s[0] = HEXCHARS[(i >> 60U) & 0xfU];
  121. s[1] = HEXCHARS[(i >> 56U) & 0xfU];
  122. s[2] = HEXCHARS[(i >> 52U) & 0xfU];
  123. s[3] = HEXCHARS[(i >> 48U) & 0xfU];
  124. s[4] = HEXCHARS[(i >> 44U) & 0xfU];
  125. s[5] = HEXCHARS[(i >> 40U) & 0xfU];
  126. s[6] = HEXCHARS[(i >> 36U) & 0xfU];
  127. s[7] = HEXCHARS[(i >> 32U) & 0xfU];
  128. s[8] = HEXCHARS[(i >> 28U) & 0xfU];
  129. s[9] = HEXCHARS[(i >> 24U) & 0xfU];
  130. s[10] = HEXCHARS[(i >> 20U) & 0xfU];
  131. s[11] = HEXCHARS[(i >> 16U) & 0xfU];
  132. s[12] = HEXCHARS[(i >> 12U) & 0xfU];
  133. s[13] = HEXCHARS[(i >> 8U) & 0xfU];
  134. s[14] = HEXCHARS[(i >> 4U) & 0xfU];
  135. s[15] = HEXCHARS[i & 0xfU];
  136. s[16] = 0;
  137. return s;
  138. }
  139. uint64_t unhex(const char *s) noexcept
  140. {
  141. uint64_t n = 0;
  142. if (s) {
  143. int k = 0;
  144. while (k < 16) {
  145. char hc = *(s++);
  146. if (!hc) break;
  147. uint8_t c = 0;
  148. if ((hc >= 48)&&(hc <= 57))
  149. c = hc - 48;
  150. else if ((hc >= 97)&&(hc <= 102))
  151. c = hc - 87;
  152. else if ((hc >= 65)&&(hc <= 70))
  153. c = hc - 55;
  154. n <<= 4U;
  155. n |= (uint64_t)c;
  156. ++k;
  157. }
  158. }
  159. return n;
  160. }
  161. char *hex(const void *d,unsigned int l,char *s) noexcept
  162. {
  163. char *const save = s;
  164. for(unsigned int i=0;i<l;++i) {
  165. const unsigned int b = reinterpret_cast<const uint8_t *>(d)[i];
  166. *(s++) = HEXCHARS[b >> 4U];
  167. *(s++) = HEXCHARS[b & 0xfU];
  168. }
  169. *s = (char)0;
  170. return save;
  171. }
  172. unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen) noexcept
  173. {
  174. unsigned int l = 0;
  175. const char *hend = h + hlen;
  176. while (l < buflen) {
  177. if (h == hend) break;
  178. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  179. if (!hc) break;
  180. uint8_t c = 0;
  181. if ((hc >= 48)&&(hc <= 57))
  182. c = hc - 48;
  183. else if ((hc >= 97)&&(hc <= 102))
  184. c = hc - 87;
  185. else if ((hc >= 65)&&(hc <= 70))
  186. c = hc - 55;
  187. if (h == hend) break;
  188. hc = *(reinterpret_cast<const uint8_t *>(h++));
  189. if (!hc) break;
  190. c <<= 4;
  191. if ((hc >= 48)&&(hc <= 57))
  192. c |= hc - 48;
  193. else if ((hc >= 97)&&(hc <= 102))
  194. c |= hc - 87;
  195. else if ((hc >= 65)&&(hc <= 70))
  196. c |= hc - 55;
  197. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  198. }
  199. return l;
  200. }
  201. void getSecureRandom(void *buf,unsigned int bytes) noexcept
  202. {
  203. static Mutex globalLock;
  204. static bool initialized = false;
  205. static uint64_t randomState[16]; // secret state
  206. static uint64_t randomBuf[8192]; // next batch of random bytes
  207. static unsigned long randomPtr = sizeof(randomBuf); // refresh on first iteration
  208. // This secure random function gets entropy from the system random source (e.g. /dev/urandom),
  209. // CPU random instructions if present, and other sources and uses them to initialize a SHA/AES
  210. // based CSPRNG with a large state. System random sources are not used directly to mitigate
  211. // against cases where the system random source is broken in some way, which does happen from
  212. // time to time.
  213. Mutex::Lock gl(globalLock);
  214. for(unsigned int i=0;i<bytes;++i) {
  215. if (randomPtr >= sizeof(randomBuf)) {
  216. randomPtr = 0;
  217. if (!initialized) {
  218. initialized = true;
  219. // Fill both randomState and randomBuf from system random source. Failure here
  220. // is fatal to the running application and indicates a serious system problem.
  221. // This is some of the only OS-specific code in the core.
  222. #ifdef __WINDOWS__
  223. HCRYPTPROV cryptProvider = NULL;
  224. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  225. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  226. exit(1);
  227. }
  228. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomState),(BYTE *)randomState)) {
  229. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  230. exit(1);
  231. }
  232. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  233. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  234. exit(1);
  235. }
  236. CryptReleaseContext(cryptProvider,0);
  237. #else
  238. int devURandomFd = ::open("/dev/urandom",O_RDONLY);
  239. if (devURandomFd < 0) {
  240. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to open /dev/urandom\n");
  241. exit(1);
  242. }
  243. if ((long)::read(devURandomFd,randomState,sizeof(randomState)) != (long)sizeof(randomState)) {
  244. ::close(devURandomFd);
  245. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  246. exit(1);
  247. }
  248. if ((long)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (long)sizeof(randomBuf)) {
  249. ::close(devURandomFd);
  250. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  251. exit(1);
  252. }
  253. close(devURandomFd);
  254. #endif
  255. // Mix in additional entropy from time, the address of 'buf', rdrand if present, etc.
  256. randomState[0] ^= (uint64_t)time(nullptr);
  257. randomState[1] ^= (uint64_t)((uintptr_t)buf);
  258. #ifdef __UNIX_LIKE__
  259. randomState[2] ^= (uint64_t)getpid();
  260. randomState[3] ^= (uint64_t)getppid();
  261. #endif
  262. #ifdef ZT_ARCH_X64
  263. if (CPUID.rdrand) {
  264. uint64_t tmp = 0;
  265. for(int k=0;k<16;++k) {
  266. _rdrand64_step((unsigned long long *)&tmp);
  267. randomState[k] ^= tmp;
  268. }
  269. }
  270. #endif
  271. }
  272. // Generate a new randomBuf:
  273. //
  274. // (1) Generate next randomState by perturbing, hashing, and replacing the first 384 bits with the hash.
  275. // (2) Initialize AES using the first 256 bits of the new randomState as its key.
  276. // (3) Initialize a 128-bit counter field using the following 128 bits of randomState.
  277. // (4) Encrypt randomBuf with AES-CTR (machine-endian counter since spec conformance doesn't matter).
  278. ++randomState[15];
  279. SHA384(randomState,randomState,sizeof(randomState));
  280. AES aes(randomState);
  281. uint64_t ctr[2],tmp[2];
  282. ctr[0] = randomState[4];
  283. ctr[1] = randomState[5]; // AES key + CTR/nonce = part replaced each time by SHA384
  284. for(int k=0;k<8192;k+=2) {
  285. ++ctr[0];
  286. aes.encrypt(ctr,tmp);
  287. randomBuf[k] ^= tmp[0];
  288. randomBuf[k+1] ^= tmp[1];
  289. }
  290. }
  291. reinterpret_cast<uint8_t *>(buf)[i] = reinterpret_cast<uint8_t *>(randomBuf)[randomPtr++];
  292. }
  293. }
  294. uint64_t getSecureRandomU64() noexcept
  295. {
  296. uint64_t tmp = 0;
  297. getSecureRandom(&tmp,sizeof(tmp));
  298. return tmp;
  299. }
  300. int b32e(const uint8_t *data,int length,char *result,int bufSize) noexcept
  301. {
  302. if (length < 0 || length > (1 << 28)) {
  303. result[0] = (char)0;
  304. return -1;
  305. }
  306. int count = 0;
  307. if (length > 0) {
  308. int buffer = data[0];
  309. int next = 1;
  310. int bitsLeft = 8;
  311. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  312. if (bitsLeft < 5) {
  313. if (next < length) {
  314. buffer <<= 8U;
  315. buffer |= data[next++] & 0xffU;
  316. bitsLeft += 8;
  317. } else {
  318. int pad = 5 - bitsLeft;
  319. buffer <<= pad;
  320. bitsLeft += pad;
  321. }
  322. }
  323. int index = 0x1f & (buffer >> (unsigned int)(bitsLeft - 5));
  324. bitsLeft -= 5;
  325. result[count++] = "abcdefghijklmnopqrstuvwxyz234567"[index];
  326. }
  327. }
  328. if (count < bufSize) {
  329. result[count] = (char)0;
  330. return count;
  331. }
  332. result[0] = (char)0;
  333. return -1;
  334. }
  335. int b32d(const char *encoded,uint8_t *result,int bufSize) noexcept
  336. {
  337. int buffer = 0;
  338. int bitsLeft = 0;
  339. int count = 0;
  340. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  341. uint8_t ch = *ptr;
  342. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  343. continue;
  344. }
  345. buffer <<= 5;
  346. if (ch == '0') {
  347. ch = 'O';
  348. } else if (ch == '1') {
  349. ch = 'L';
  350. } else if (ch == '8') {
  351. ch = 'B';
  352. }
  353. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  354. ch = (ch & 0x1f) - 1;
  355. } else if (ch >= '2' && ch <= '7') {
  356. ch -= '2' - 26;
  357. } else {
  358. return -1;
  359. }
  360. buffer |= ch;
  361. bitsLeft += 5;
  362. if (bitsLeft >= 8) {
  363. result[count++] = buffer >> (bitsLeft - 8);
  364. bitsLeft -= 8;
  365. }
  366. }
  367. if (count < bufSize)
  368. result[count] = (uint8_t)0;
  369. return count;
  370. }
  371. uint64_t random() noexcept
  372. {
  373. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  374. static volatile uint64_t s_s0 = getSecureRandomU64();
  375. static volatile uint64_t s_s1 = getSecureRandomU64();
  376. static volatile uint64_t s_s2 = getSecureRandomU64();
  377. static volatile uint64_t s_s3 = getSecureRandomU64();
  378. uint64_t s0 = s_s0;
  379. uint64_t s1 = s_s1;
  380. uint64_t s2 = s_s2;
  381. uint64_t s3 = s_s3;
  382. const uint64_t s1x5 = s1 * 5;
  383. const uint64_t result = ((s1x5 << 7U)|(s1x5 >> 57U)) * 9;
  384. const uint64_t t = s1 << 17U;
  385. s2 ^= s0;
  386. s3 ^= s1;
  387. s1 ^= s2;
  388. s0 ^= s3;
  389. s2 ^= t;
  390. s3 = ((s3 << 45U)|(s3 >> 19U));
  391. s_s0 = s0;
  392. s_s1 = s1;
  393. s_s2 = s2;
  394. s_s3 = s3;
  395. return result;
  396. }
  397. bool scopy(char *const dest,const unsigned int len,const char *const src) noexcept
  398. {
  399. if (!len)
  400. return false; // sanity check
  401. if (!src) {
  402. *dest = (char)0;
  403. return true;
  404. }
  405. unsigned int i = 0;
  406. for(;;) {
  407. if (i >= len) {
  408. dest[len - 1] = 0;
  409. return false;
  410. }
  411. if ((dest[i] = src[i]) == 0)
  412. return true;
  413. ++i;
  414. }
  415. }
  416. } // namespace Utils
  417. } // namespace ZeroTier