Utils.cpp 11 KB

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