2
0

Utils.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 *hex10(uint64_t i,char s[11])
  89. {
  90. s[0] = HEXCHARS[(i >> 36U) & 0xfU];
  91. s[1] = HEXCHARS[(i >> 32U) & 0xfU];
  92. s[2] = HEXCHARS[(i >> 28U) & 0xfU];
  93. s[3] = HEXCHARS[(i >> 24U) & 0xfU];
  94. s[4] = HEXCHARS[(i >> 20U) & 0xfU];
  95. s[5] = HEXCHARS[(i >> 16U) & 0xfU];
  96. s[6] = HEXCHARS[(i >> 12U) & 0xfU];
  97. s[7] = HEXCHARS[(i >> 8U) & 0xfU];
  98. s[8] = HEXCHARS[(i >> 4U) & 0xfU];
  99. s[9] = HEXCHARS[i & 0xfU];
  100. s[10] = (char)0;
  101. return s;
  102. }
  103. char *hex(const void *d,unsigned int l,char *s)
  104. {
  105. char *const save = s;
  106. for(unsigned int i=0;i<l;++i) {
  107. const unsigned int b = reinterpret_cast<const uint8_t *>(d)[i];
  108. *(s++) = HEXCHARS[b >> 4U];
  109. *(s++) = HEXCHARS[b & 0xfU];
  110. }
  111. *s = (char)0;
  112. return save;
  113. }
  114. unsigned int unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen)
  115. {
  116. unsigned int l = 0;
  117. const char *hend = h + hlen;
  118. while (l < buflen) {
  119. if (h == hend) break;
  120. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  121. if (!hc) break;
  122. uint8_t c = 0;
  123. if ((hc >= 48)&&(hc <= 57))
  124. c = hc - 48;
  125. else if ((hc >= 97)&&(hc <= 102))
  126. c = hc - 87;
  127. else if ((hc >= 65)&&(hc <= 70))
  128. c = hc - 55;
  129. if (h == hend) break;
  130. hc = *(reinterpret_cast<const uint8_t *>(h++));
  131. if (!hc) break;
  132. c <<= 4;
  133. if ((hc >= 48)&&(hc <= 57))
  134. c |= hc - 48;
  135. else if ((hc >= 97)&&(hc <= 102))
  136. c |= hc - 87;
  137. else if ((hc >= 65)&&(hc <= 70))
  138. c |= hc - 55;
  139. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  140. }
  141. return l;
  142. }
  143. void getSecureRandom(void *buf,unsigned int bytes)
  144. {
  145. static Mutex globalLock;
  146. static bool initialized = false;
  147. static uint64_t randomState[8];
  148. static uint64_t randomBuf[8192];
  149. static unsigned int randomPtr = 65536;
  150. Mutex::Lock gl(globalLock);
  151. for(unsigned int i=0;i<bytes;++i) {
  152. if (randomPtr >= 65536) {
  153. randomPtr = 0;
  154. if (!initialized) {
  155. initialized = true;
  156. #ifdef __WINDOWS__
  157. HCRYPTPROV cryptProvider = NULL;
  158. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  159. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  160. exit(1);
  161. }
  162. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomState),(BYTE *)randomState)) {
  163. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  164. exit(1);
  165. }
  166. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  167. fprintf(stderr,"FATAL: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  168. exit(1);
  169. }
  170. CryptReleaseContext(cryptProvider,0);
  171. #else
  172. int devURandomFd = ::open("/dev/urandom",O_RDONLY);
  173. if (devURandomFd < 0) {
  174. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to open /dev/urandom\n");
  175. exit(1);
  176. }
  177. if ((int)::read(devURandomFd,randomState,sizeof(randomState)) != (int)sizeof(randomState)) {
  178. ::close(devURandomFd);
  179. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  180. exit(1);
  181. }
  182. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  183. ::close(devURandomFd);
  184. fprintf(stderr,"FATAL: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  185. exit(1);
  186. }
  187. close(devURandomFd);
  188. #endif
  189. // Mix in additional entropy just in case the standard random source is wonky somehow
  190. randomState[0] ^= (uint64_t)time(nullptr);
  191. randomState[1] ^= (uint64_t)((uintptr_t)buf);
  192. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  193. if (CPUID.rdrand) {
  194. uint64_t tmp = 0;
  195. _rdrand64_step((unsigned long long *)&tmp);
  196. randomState[2] ^= tmp;
  197. _rdrand64_step((unsigned long long *)&tmp);
  198. randomState[3] ^= tmp;
  199. }
  200. #endif
  201. }
  202. ++randomState[0];
  203. SHA512(randomState,randomState,sizeof(randomState));
  204. AES aes(reinterpret_cast<const uint8_t *>(randomState));
  205. uint64_t ctr[2],tmp[2];
  206. ctr[0] = randomState[6];
  207. ctr[1] = randomState[7];
  208. for(int k=0;k<8192;) {
  209. ++ctr[0];
  210. aes.encrypt(reinterpret_cast<const uint8_t *>(ctr),reinterpret_cast<uint8_t *>(tmp));
  211. randomBuf[k] ^= tmp[0];
  212. randomBuf[k+1] ^= tmp[1];
  213. k += 2;
  214. }
  215. }
  216. reinterpret_cast<uint8_t *>(buf)[i] = reinterpret_cast<uint8_t *>(randomBuf)[randomPtr++];
  217. }
  218. }
  219. int b32e(const uint8_t *data,int length,char *result,int bufSize)
  220. {
  221. if (length < 0 || length > (1 << 28)) {
  222. result[0] = (char)0;
  223. return -1;
  224. }
  225. int count = 0;
  226. if (length > 0) {
  227. int buffer = data[0];
  228. int next = 1;
  229. int bitsLeft = 8;
  230. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  231. if (bitsLeft < 5) {
  232. if (next < length) {
  233. buffer <<= 8U;
  234. buffer |= data[next++] & 0xffU;
  235. bitsLeft += 8;
  236. } else {
  237. int pad = 5 - bitsLeft;
  238. buffer <<= pad;
  239. bitsLeft += pad;
  240. }
  241. }
  242. int index = 0x1f & (buffer >> (unsigned int)(bitsLeft - 5));
  243. bitsLeft -= 5;
  244. result[count++] = "abcdefghijklmnopqrstuvwxyz234567"[index];
  245. }
  246. }
  247. if (count < bufSize) {
  248. result[count] = (char)0;
  249. return count;
  250. }
  251. result[0] = (char)0;
  252. return -1;
  253. }
  254. int b32d(const char *encoded,uint8_t *result,int bufSize)
  255. {
  256. int buffer = 0;
  257. int bitsLeft = 0;
  258. int count = 0;
  259. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  260. uint8_t ch = *ptr;
  261. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  262. continue;
  263. }
  264. buffer <<= 5;
  265. if (ch == '0') {
  266. ch = 'O';
  267. } else if (ch == '1') {
  268. ch = 'L';
  269. } else if (ch == '8') {
  270. ch = 'B';
  271. }
  272. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  273. ch = (ch & 0x1f) - 1;
  274. } else if (ch >= '2' && ch <= '7') {
  275. ch -= '2' - 26;
  276. } else {
  277. return -1;
  278. }
  279. buffer |= ch;
  280. bitsLeft += 5;
  281. if (bitsLeft >= 8) {
  282. result[count++] = buffer >> (bitsLeft - 8);
  283. bitsLeft -= 8;
  284. }
  285. }
  286. if (count < bufSize)
  287. result[count] = (uint8_t)0;
  288. return count;
  289. }
  290. static uint64_t _secureRandom64()
  291. {
  292. uint64_t tmp = 0;
  293. getSecureRandom(&tmp,sizeof(tmp));
  294. return tmp;
  295. }
  296. #define ROL64(x,k) (((x) << (k)) | ((x) >> (64 - (k))))
  297. uint64_t random()
  298. {
  299. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  300. static Mutex l;
  301. static uint64_t s0 = _secureRandom64();
  302. static uint64_t s1 = _secureRandom64();
  303. static uint64_t s2 = _secureRandom64();
  304. static uint64_t s3 = _secureRandom64();
  305. l.lock();
  306. const uint64_t result = ROL64(s1 * 5,7) * 9;
  307. const uint64_t t = s1 << 17U;
  308. s2 ^= s0;
  309. s3 ^= s1;
  310. s1 ^= s2;
  311. s0 ^= s3;
  312. s2 ^= t;
  313. s3 = ROL64(s3,45);
  314. l.unlock();
  315. return result;
  316. }
  317. bool scopy(char *dest,unsigned int len,const char *src)
  318. {
  319. if (!len)
  320. return false; // sanity check
  321. if (!src) {
  322. *dest = (char)0;
  323. return true;
  324. }
  325. char *const end = dest + len;
  326. while ((*dest++ = *src++)) {
  327. if (dest == end) {
  328. *(--dest) = (char)0;
  329. return false;
  330. }
  331. }
  332. return true;
  333. }
  334. } // namespace Utils
  335. } // namespace ZeroTier