Utils.cpp 10 KB

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