Utils.cpp 10 KB

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