Utils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 int Utils::unhex(const char *h,void *buf,unsigned int buflen)
  88. {
  89. unsigned int l = 0;
  90. while (l < buflen) {
  91. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  92. if (!hc) break;
  93. uint8_t c = 0;
  94. if ((hc >= 48)&&(hc <= 57)) // 0..9
  95. c = hc - 48;
  96. else if ((hc >= 97)&&(hc <= 102)) // a..f
  97. c = hc - 87;
  98. else if ((hc >= 65)&&(hc <= 70)) // A..F
  99. c = hc - 55;
  100. hc = *(reinterpret_cast<const uint8_t *>(h++));
  101. if (!hc) break;
  102. c <<= 4;
  103. if ((hc >= 48)&&(hc <= 57))
  104. c |= hc - 48;
  105. else if ((hc >= 97)&&(hc <= 102))
  106. c |= hc - 87;
  107. else if ((hc >= 65)&&(hc <= 70))
  108. c |= hc - 55;
  109. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  110. }
  111. return l;
  112. }
  113. unsigned int Utils::unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen)
  114. {
  115. unsigned int l = 0;
  116. const char *hend = h + hlen;
  117. while (l < buflen) {
  118. if (h == hend) break;
  119. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  120. if (!hc) break;
  121. uint8_t c = 0;
  122. if ((hc >= 48)&&(hc <= 57))
  123. c = hc - 48;
  124. else if ((hc >= 97)&&(hc <= 102))
  125. c = hc - 87;
  126. else if ((hc >= 65)&&(hc <= 70))
  127. c = hc - 55;
  128. if (h == hend) break;
  129. hc = *(reinterpret_cast<const uint8_t *>(h++));
  130. if (!hc) break;
  131. c <<= 4;
  132. if ((hc >= 48)&&(hc <= 57))
  133. c |= hc - 48;
  134. else if ((hc >= 97)&&(hc <= 102))
  135. c |= hc - 87;
  136. else if ((hc >= 65)&&(hc <= 70))
  137. c |= hc - 55;
  138. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  139. }
  140. return l;
  141. }
  142. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  143. {
  144. static Mutex globalLock;
  145. static bool initialized = false;
  146. static uint64_t randomState[4];
  147. static uint8_t randomBuf[16384];
  148. static unsigned long randomPtr = sizeof(randomBuf);
  149. Mutex::Lock gl(globalLock);
  150. for(unsigned int i=0;i<bytes;++i) {
  151. if (randomPtr >= sizeof(randomBuf)) {
  152. randomPtr = 0;
  153. if (unlikely(!initialized)) {
  154. initialized = true;
  155. #ifdef __WINDOWS__
  156. HCRYPTPROV cryptProvider = NULL;
  157. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  158. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  159. exit(1);
  160. }
  161. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomState),(BYTE *)randomState)) {
  162. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  163. exit(1);
  164. }
  165. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  166. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  167. exit(1);
  168. }
  169. CryptReleaseContext(cryptProvider,0);
  170. #else
  171. int devURandomFd = ::open("/dev/urandom",O_RDONLY);
  172. if (devURandomFd < 0) {
  173. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to open /dev/urandom\n");
  174. exit(1);
  175. }
  176. if ((int)::read(devURandomFd,randomState,sizeof(randomState)) != (int)sizeof(randomState)) {
  177. ::close(devURandomFd);
  178. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  179. exit(1);
  180. }
  181. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  182. ::close(devURandomFd);
  183. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  184. exit(1);
  185. }
  186. close(devURandomFd);
  187. #endif
  188. // Mix in additional entropy just in case the standard random source is wonky somehow
  189. randomState[0] ^= (uint64_t)time(nullptr);
  190. randomState[1] ^= (uint64_t)((uintptr_t)buf);
  191. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  192. if (_rdrandSupported) {
  193. uint64_t tmp = 0;
  194. _rdrand64_step((unsigned long long *)&tmp);
  195. randomState[2] ^= tmp;
  196. _rdrand64_step((unsigned long long *)&tmp);
  197. randomState[3] ^= tmp;
  198. }
  199. #endif
  200. }
  201. 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
  202. if (++randomState[k] != 0)
  203. break;
  204. }
  205. uint8_t h[48];
  206. HMACSHA384((const uint8_t *)randomState,randomBuf,sizeof(randomBuf),h); // compute HMAC on random buffer using state as secret key
  207. AES c(h);
  208. c.ctr(h + 32,randomBuf,sizeof(randomBuf),randomBuf); // encrypt random buffer with AES-CTR using HMAC result as key
  209. }
  210. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  211. }
  212. }
  213. int Utils::b32e(const uint8_t *data,int length,char *result,int bufSize)
  214. {
  215. if (length < 0 || length > (1 << 28)) {
  216. result[0] = (char)0;
  217. return -1;
  218. }
  219. int count = 0;
  220. if (length > 0) {
  221. int buffer = data[0];
  222. int next = 1;
  223. int bitsLeft = 8;
  224. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  225. if (bitsLeft < 5) {
  226. if (next < length) {
  227. buffer <<= 8;
  228. buffer |= data[next++] & 0xFF;
  229. bitsLeft += 8;
  230. } else {
  231. int pad = 5 - bitsLeft;
  232. buffer <<= pad;
  233. bitsLeft += pad;
  234. }
  235. }
  236. int index = 0x1F & (buffer >> (bitsLeft - 5));
  237. bitsLeft -= 5;
  238. result[count++] = "abcdefghijklmnopqrstuvwxyZ234567"[index];
  239. }
  240. }
  241. if (count < bufSize) {
  242. result[count] = (char)0;
  243. return count;
  244. }
  245. result[0] = (char)0;
  246. return -1;
  247. }
  248. int Utils::b32d(const char *encoded,uint8_t *result,int bufSize)
  249. {
  250. int buffer = 0;
  251. int bitsLeft = 0;
  252. int count = 0;
  253. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  254. uint8_t ch = *ptr;
  255. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  256. continue;
  257. }
  258. buffer <<= 5;
  259. if (ch == '0') {
  260. ch = 'O';
  261. } else if (ch == '1') {
  262. ch = 'L';
  263. } else if (ch == '8') {
  264. ch = 'B';
  265. }
  266. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  267. ch = (ch & 0x1F) - 1;
  268. } else if (ch >= '2' && ch <= '7') {
  269. ch -= '2' - 26;
  270. } else {
  271. return -1;
  272. }
  273. buffer |= ch;
  274. bitsLeft += 5;
  275. if (bitsLeft >= 8) {
  276. result[count++] = buffer >> (bitsLeft - 8);
  277. bitsLeft -= 8;
  278. }
  279. }
  280. if (count < bufSize)
  281. result[count] = (uint8_t)0;
  282. return count;
  283. }
  284. unsigned int Utils::b64e(const uint8_t *in,unsigned int inlen,char *out,unsigned int outlen)
  285. {
  286. 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','+','/' };
  287. unsigned int i = 0,j = 0;
  288. uint8_t l = 0;
  289. int s = 0;
  290. for (;i<inlen;++i) {
  291. uint8_t c = in[i];
  292. switch (s) {
  293. case 0:
  294. s = 1;
  295. if (j >= outlen) return 0;
  296. out[j++] = base64en[(c >> 2) & 0x3f];
  297. break;
  298. case 1:
  299. s = 2;
  300. if (j >= outlen) return 0;
  301. out[j++] = base64en[((l & 0x3) << 4) | ((c >> 4) & 0xf)];
  302. break;
  303. case 2:
  304. s = 0;
  305. if (j >= outlen) return 0;
  306. out[j++] = base64en[((l & 0xf) << 2) | ((c >> 6) & 0x3)];
  307. if (j >= outlen) return 0;
  308. out[j++] = base64en[c & 0x3f];
  309. break;
  310. }
  311. l = c;
  312. }
  313. switch (s) {
  314. case 1:
  315. if (j >= outlen) return 0;
  316. out[j++] = base64en[(l & 0x3) << 4];
  317. //out[j++] = '=';
  318. //out[j++] = '=';
  319. break;
  320. case 2:
  321. if (j >= outlen) return 0;
  322. out[j++] = base64en[(l & 0xf) << 2];
  323. //out[j++] = '=';
  324. break;
  325. }
  326. if (j >= outlen) return 0;
  327. out[j] = 0;
  328. return j;
  329. }
  330. unsigned int Utils::b64d(const char *in,unsigned char *out,unsigned int outlen)
  331. {
  332. 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 };
  333. unsigned int i = 0;
  334. unsigned int j = 0;
  335. while ((in[i] != '=')&&(in[i] != 0)) {
  336. if (j >= outlen)
  337. break;
  338. uint8_t c = base64de[(unsigned char)in[i]];
  339. if (c != 255) {
  340. switch (i & 0x3) {
  341. case 0:
  342. out[j] = (c << 2) & 0xff;
  343. break;
  344. case 1:
  345. out[j++] |= (c >> 4) & 0x3;
  346. out[j] = (c & 0xf) << 4;
  347. break;
  348. case 2:
  349. out[j++] |= (c >> 2) & 0xf;
  350. out[j] = (c & 0x3) << 6;
  351. break;
  352. case 3:
  353. out[j++] |= c;
  354. break;
  355. }
  356. }
  357. ++i;
  358. }
  359. return j;
  360. }
  361. #define ROL64(x,k) (((x) << (k)) | ((x) >> (64 - (k))))
  362. uint64_t Utils::random()
  363. {
  364. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  365. static Mutex l;
  366. static uint64_t s0 = Utils::getSecureRandom64();
  367. static uint64_t s1 = Utils::getSecureRandom64();
  368. static uint64_t s2 = Utils::getSecureRandom64();
  369. static uint64_t s3 = Utils::getSecureRandom64();
  370. l.lock();
  371. const uint64_t result = ROL64(s1 * 5,7) * 9;
  372. const uint64_t t = s1 << 17;
  373. s2 ^= s0;
  374. s3 ^= s1;
  375. s1 ^= s2;
  376. s0 ^= s3;
  377. s2 ^= t;
  378. s3 = ROL64(s3,45);
  379. l.unlock();
  380. return result;
  381. }
  382. } // namespace ZeroTier