Utils.cpp 9.3 KB

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