Utils.cpp 11 KB

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