Utils.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /*
  2. * Copyright (c)2019 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: 2023-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 <stdio.h>
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include <stdarg.h>
  17. #include <time.h>
  18. #include <sys/stat.h>
  19. #include "Constants.hpp"
  20. #ifdef __UNIX_LIKE__
  21. #include <unistd.h>
  22. #include <errno.h>
  23. #include <fcntl.h>
  24. #include <sys/types.h>
  25. #include <sys/stat.h>
  26. #include <sys/uio.h>
  27. #include <dirent.h>
  28. #endif
  29. #ifdef __WINDOWS__
  30. #include <wincrypt.h>
  31. #endif
  32. #include "Utils.hpp"
  33. #include "Mutex.hpp"
  34. #include "Salsa20.hpp"
  35. #include "AES.hpp"
  36. #include "SHA512.hpp"
  37. namespace ZeroTier {
  38. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  39. #include <immintrin.h>
  40. static bool _zt_rdrand_supported()
  41. {
  42. #ifdef __WINDOWS__
  43. int regs[4];
  44. __cpuid(regs,1);
  45. return (((regs[2] >> 30) & 1) != 0);
  46. #else
  47. uint32_t eax,ebx,ecx,edx;
  48. __asm__ __volatile__ (
  49. "cpuid"
  50. : "=a"(eax),"=b"(ebx),"=c"(ecx),"=d"(edx)
  51. : "a"(1),"c"(0)
  52. );
  53. return ((ecx & (1 << 30)) != 0);
  54. #endif
  55. }
  56. static const bool _rdrandSupported = _zt_rdrand_supported();
  57. #endif
  58. const char Utils::HEXCHARS[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
  59. // Crazy hack to force memory to be securely zeroed in spite of the best efforts of optimizing compilers.
  60. static void _Utils_doBurn(volatile uint8_t *ptr,unsigned int len)
  61. {
  62. volatile uint8_t *const end = ptr + len;
  63. while (ptr != end) *(ptr++) = (uint8_t)0;
  64. }
  65. static void (*volatile _Utils_doBurn_ptr)(volatile uint8_t *,unsigned int) = _Utils_doBurn;
  66. void Utils::burn(void *ptr,unsigned int len) { (_Utils_doBurn_ptr)((volatile uint8_t *)ptr,len); }
  67. static unsigned long _Utils_itoa(unsigned long n,char *s)
  68. {
  69. if (n == 0)
  70. return 0;
  71. unsigned long pos = _Utils_itoa(n / 10,s);
  72. if (pos >= 22) // sanity check,should be impossible
  73. pos = 22;
  74. s[pos] = '0' + (char)(n % 10);
  75. return pos + 1;
  76. }
  77. char *Utils::decimal(unsigned long n,char s[24])
  78. {
  79. if (n == 0) {
  80. s[0] = '0';
  81. s[1] = (char)0;
  82. return s;
  83. }
  84. s[_Utils_itoa(n,s)] = (char)0;
  85. return s;
  86. }
  87. unsigned short Utils::crc16(const void *buf,unsigned int len)
  88. {
  89. static const uint16_t crc16tab[256]= {
  90. 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
  91. 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
  92. 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
  93. 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
  94. 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
  95. 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
  96. 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
  97. 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
  98. 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
  99. 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
  100. 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
  101. 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
  102. 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
  103. 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
  104. 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
  105. 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
  106. 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
  107. 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
  108. 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
  109. 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
  110. 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
  111. 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
  112. 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
  113. 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
  114. 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
  115. 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
  116. 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
  117. 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
  118. 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
  119. 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
  120. 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
  121. 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
  122. };
  123. uint16_t crc = 0;
  124. const uint8_t *p = (const uint8_t *)buf;
  125. for(unsigned int i=0;i<len;++i)
  126. crc = (crc << 8) ^ crc16tab[((crc >> 8) ^ *(p++)) & 0x00ff];
  127. return crc;
  128. }
  129. unsigned int Utils::unhex(const char *h,void *buf,unsigned int buflen)
  130. {
  131. unsigned int l = 0;
  132. while (l < buflen) {
  133. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  134. if (!hc) break;
  135. uint8_t c = 0;
  136. if ((hc >= 48)&&(hc <= 57)) // 0..9
  137. c = hc - 48;
  138. else if ((hc >= 97)&&(hc <= 102)) // a..f
  139. c = hc - 87;
  140. else if ((hc >= 65)&&(hc <= 70)) // A..F
  141. c = hc - 55;
  142. hc = *(reinterpret_cast<const uint8_t *>(h++));
  143. if (!hc) break;
  144. c <<= 4;
  145. if ((hc >= 48)&&(hc <= 57))
  146. c |= hc - 48;
  147. else if ((hc >= 97)&&(hc <= 102))
  148. c |= hc - 87;
  149. else if ((hc >= 65)&&(hc <= 70))
  150. c |= hc - 55;
  151. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  152. }
  153. return l;
  154. }
  155. unsigned int Utils::unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen)
  156. {
  157. unsigned int l = 0;
  158. const char *hend = h + hlen;
  159. while (l < buflen) {
  160. if (h == hend) break;
  161. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  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. if (h == hend) break;
  171. hc = *(reinterpret_cast<const uint8_t *>(h++));
  172. if (!hc) break;
  173. c <<= 4;
  174. if ((hc >= 48)&&(hc <= 57))
  175. c |= hc - 48;
  176. else if ((hc >= 97)&&(hc <= 102))
  177. c |= hc - 87;
  178. else if ((hc >= 65)&&(hc <= 70))
  179. c |= hc - 55;
  180. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  181. }
  182. return l;
  183. }
  184. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  185. {
  186. static Mutex globalLock;
  187. static bool initialized = false;
  188. static uint64_t randomState[4];
  189. static uint8_t randomBuf[16384];
  190. static unsigned long randomPtr = sizeof(randomBuf);
  191. Mutex::Lock gl(globalLock);
  192. for(unsigned int i=0;i<bytes;++i) {
  193. if (randomPtr >= sizeof(randomBuf)) {
  194. randomPtr = 0;
  195. if (unlikely(!initialized)) {
  196. initialized = true;
  197. #ifdef __WINDOWS__
  198. HCRYPTPROV cryptProvider = NULL;
  199. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  200. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  201. exit(1);
  202. }
  203. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomState),(BYTE *)randomState)) {
  204. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  205. exit(1);
  206. }
  207. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  208. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  209. exit(1);
  210. }
  211. CryptReleaseContext(cryptProvider,0);
  212. #else
  213. int devURandomFd = ::open("/dev/urandom",O_RDONLY);
  214. if (devURandomFd < 0) {
  215. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to open /dev/urandom\n");
  216. exit(1);
  217. }
  218. if ((int)::read(devURandomFd,randomState,sizeof(randomState)) != (int)sizeof(randomState)) {
  219. ::close(devURandomFd);
  220. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  221. exit(1);
  222. }
  223. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  224. ::close(devURandomFd);
  225. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  226. exit(1);
  227. }
  228. close(devURandomFd);
  229. #endif
  230. // Mix in additional entropy just in case the standard random source is wonky somehow
  231. randomState[0] ^= (uint64_t)time(nullptr);
  232. randomState[1] ^= (uint64_t)((uintptr_t)buf);
  233. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  234. if (_rdrandSupported) {
  235. uint64_t tmp = 0;
  236. _rdrand64_step((unsigned long long *)&tmp);
  237. randomState[2] ^= tmp;
  238. _rdrand64_step((unsigned long long *)&tmp);
  239. randomState[3] ^= tmp;
  240. }
  241. #endif
  242. }
  243. for(unsigned int k=0;k<4;++k) { // treat random state like a 256-bit counter; endian-ness is irrelevant since we just want random
  244. if (++randomState[k] != 0)
  245. break;
  246. }
  247. uint8_t h[48];
  248. HMACSHA384((const uint8_t *)randomState,randomBuf,sizeof(randomBuf),h); // compute HMAC on random buffer using state as secret key
  249. AES c(h);
  250. c.ctr(h + 32,randomBuf,sizeof(randomBuf),randomBuf); // encrypt random buffer with AES-CTR using HMAC result as key
  251. }
  252. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  253. }
  254. }
  255. int Utils::b32e(const uint8_t *data,int length,char *result,int bufSize)
  256. {
  257. if (length < 0 || length > (1 << 28)) {
  258. result[0] = (char)0;
  259. return -1;
  260. }
  261. int count = 0;
  262. if (length > 0) {
  263. int buffer = data[0];
  264. int next = 1;
  265. int bitsLeft = 8;
  266. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  267. if (bitsLeft < 5) {
  268. if (next < length) {
  269. buffer <<= 8;
  270. buffer |= data[next++] & 0xFF;
  271. bitsLeft += 8;
  272. } else {
  273. int pad = 5 - bitsLeft;
  274. buffer <<= pad;
  275. bitsLeft += pad;
  276. }
  277. }
  278. int index = 0x1F & (buffer >> (bitsLeft - 5));
  279. bitsLeft -= 5;
  280. result[count++] = "abcdefghijklmnopqrstuvwxyZ234567"[index];
  281. }
  282. }
  283. if (count < bufSize) {
  284. result[count] = (char)0;
  285. return count;
  286. }
  287. result[0] = (char)0;
  288. return -1;
  289. }
  290. int Utils::b32d(const char *encoded,uint8_t *result,int bufSize)
  291. {
  292. int buffer = 0;
  293. int bitsLeft = 0;
  294. int count = 0;
  295. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  296. uint8_t ch = *ptr;
  297. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  298. continue;
  299. }
  300. buffer <<= 5;
  301. if (ch == '0') {
  302. ch = 'O';
  303. } else if (ch == '1') {
  304. ch = 'L';
  305. } else if (ch == '8') {
  306. ch = 'B';
  307. }
  308. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  309. ch = (ch & 0x1F) - 1;
  310. } else if (ch >= '2' && ch <= '7') {
  311. ch -= '2' - 26;
  312. } else {
  313. return -1;
  314. }
  315. buffer |= ch;
  316. bitsLeft += 5;
  317. if (bitsLeft >= 8) {
  318. result[count++] = buffer >> (bitsLeft - 8);
  319. bitsLeft -= 8;
  320. }
  321. }
  322. if (count < bufSize)
  323. result[count] = (uint8_t)0;
  324. return count;
  325. }
  326. unsigned int Utils::b64e(const uint8_t *in,unsigned int inlen,char *out,unsigned int outlen)
  327. {
  328. static const char base64en[64] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' };
  329. unsigned int i = 0,j = 0;
  330. uint8_t l = 0;
  331. int s = 0;
  332. for (;i<inlen;++i) {
  333. uint8_t c = in[i];
  334. switch (s) {
  335. case 0:
  336. s = 1;
  337. if (j >= outlen) return 0;
  338. out[j++] = base64en[(c >> 2) & 0x3f];
  339. break;
  340. case 1:
  341. s = 2;
  342. if (j >= outlen) return 0;
  343. out[j++] = base64en[((l & 0x3) << 4) | ((c >> 4) & 0xf)];
  344. break;
  345. case 2:
  346. s = 0;
  347. if (j >= outlen) return 0;
  348. out[j++] = base64en[((l & 0xf) << 2) | ((c >> 6) & 0x3)];
  349. if (j >= outlen) return 0;
  350. out[j++] = base64en[c & 0x3f];
  351. break;
  352. }
  353. l = c;
  354. }
  355. switch (s) {
  356. case 1:
  357. if (j >= outlen) return 0;
  358. out[j++] = base64en[(l & 0x3) << 4];
  359. //out[j++] = '=';
  360. //out[j++] = '=';
  361. break;
  362. case 2:
  363. if (j >= outlen) return 0;
  364. out[j++] = base64en[(l & 0xf) << 2];
  365. //out[j++] = '=';
  366. break;
  367. }
  368. if (j >= outlen) return 0;
  369. out[j] = 0;
  370. return j;
  371. }
  372. unsigned int Utils::b64d(const char *in,unsigned char *out,unsigned int outlen)
  373. {
  374. static const uint8_t base64de[256] = { 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,255,255,255,255,255 };
  375. unsigned int i = 0;
  376. unsigned int j = 0;
  377. while ((in[i] != '=')&&(in[i] != 0)) {
  378. if (j >= outlen)
  379. break;
  380. uint8_t c = base64de[(unsigned char)in[i]];
  381. if (c != 255) {
  382. switch (i & 0x3) {
  383. case 0:
  384. out[j] = (c << 2) & 0xff;
  385. break;
  386. case 1:
  387. out[j++] |= (c >> 4) & 0x3;
  388. out[j] = (c & 0xf) << 4;
  389. break;
  390. case 2:
  391. out[j++] |= (c >> 2) & 0xf;
  392. out[j] = (c & 0x3) << 6;
  393. break;
  394. case 3:
  395. out[j++] |= c;
  396. break;
  397. }
  398. }
  399. ++i;
  400. }
  401. return j;
  402. }
  403. #define ROL64(x,k) (((x) << (k)) | ((x) >> (64 - (k))))
  404. uint64_t Utils::random()
  405. {
  406. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  407. static Mutex l;
  408. static uint64_t s0 = Utils::getSecureRandom64();
  409. static uint64_t s1 = Utils::getSecureRandom64();
  410. static uint64_t s2 = Utils::getSecureRandom64();
  411. static uint64_t s3 = Utils::getSecureRandom64();
  412. l.lock();
  413. const uint64_t result = ROL64(s1 * 5,7) * 9;
  414. const uint64_t t = s1 << 17;
  415. s2 ^= s0;
  416. s3 ^= s1;
  417. s1 ^= s2;
  418. s0 ^= s3;
  419. s2 ^= t;
  420. s3 = ROL64(s3,45);
  421. l.unlock();
  422. return result;
  423. }
  424. } // namespace ZeroTier