1
0

Utils.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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[4];
  127. static uint8_t randomBuf[16384];
  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. randomPtr = 0;
  177. for(unsigned int k=0;k<4;++k) {
  178. if (++randomState[k])
  179. break;
  180. }
  181. uint8_t h[48];
  182. HMACSHA384((const uint8_t *)randomState,randomBuf,sizeof(randomBuf),h);
  183. AES c(h);
  184. c.ctr(h + 32,randomBuf,sizeof(randomBuf),randomBuf);
  185. }
  186. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  187. }
  188. }
  189. int Utils::b32e(const uint8_t *data,int length,char *result,int bufSize)
  190. {
  191. if (length < 0 || length > (1 << 28)) {
  192. result[0] = (char)0;
  193. return -1;
  194. }
  195. int count = 0;
  196. if (length > 0) {
  197. int buffer = data[0];
  198. int next = 1;
  199. int bitsLeft = 8;
  200. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  201. if (bitsLeft < 5) {
  202. if (next < length) {
  203. buffer <<= 8;
  204. buffer |= data[next++] & 0xFF;
  205. bitsLeft += 8;
  206. } else {
  207. int pad = 5 - bitsLeft;
  208. buffer <<= pad;
  209. bitsLeft += pad;
  210. }
  211. }
  212. int index = 0x1F & (buffer >> (bitsLeft - 5));
  213. bitsLeft -= 5;
  214. result[count++] = "abcdefghijklmnopqrstuvwxyZ234567"[index];
  215. }
  216. }
  217. if (count < bufSize) {
  218. result[count] = (char)0;
  219. return count;
  220. }
  221. result[0] = (char)0;
  222. return -1;
  223. }
  224. int Utils::b32d(const char *encoded,uint8_t *result,int bufSize)
  225. {
  226. int buffer = 0;
  227. int bitsLeft = 0;
  228. int count = 0;
  229. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  230. uint8_t ch = *ptr;
  231. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  232. continue;
  233. }
  234. buffer <<= 5;
  235. if (ch == '0') {
  236. ch = 'O';
  237. } else if (ch == '1') {
  238. ch = 'L';
  239. } else if (ch == '8') {
  240. ch = 'B';
  241. }
  242. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  243. ch = (ch & 0x1F) - 1;
  244. } else if (ch >= '2' && ch <= '7') {
  245. ch -= '2' - 26;
  246. } else {
  247. return -1;
  248. }
  249. buffer |= ch;
  250. bitsLeft += 5;
  251. if (bitsLeft >= 8) {
  252. result[count++] = buffer >> (bitsLeft - 8);
  253. bitsLeft -= 8;
  254. }
  255. }
  256. if (count < bufSize)
  257. result[count] = (uint8_t)0;
  258. return count;
  259. }
  260. unsigned int Utils::b64e(const uint8_t *in,unsigned int inlen,char *out,unsigned int outlen)
  261. {
  262. 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','+','/' };
  263. unsigned int i = 0,j = 0;
  264. uint8_t l = 0;
  265. int s = 0;
  266. for (;i<inlen;++i) {
  267. uint8_t c = in[i];
  268. switch (s) {
  269. case 0:
  270. s = 1;
  271. if (j >= outlen) return 0;
  272. out[j++] = base64en[(c >> 2) & 0x3f];
  273. break;
  274. case 1:
  275. s = 2;
  276. if (j >= outlen) return 0;
  277. out[j++] = base64en[((l & 0x3) << 4) | ((c >> 4) & 0xf)];
  278. break;
  279. case 2:
  280. s = 0;
  281. if (j >= outlen) return 0;
  282. out[j++] = base64en[((l & 0xf) << 2) | ((c >> 6) & 0x3)];
  283. if (j >= outlen) return 0;
  284. out[j++] = base64en[c & 0x3f];
  285. break;
  286. }
  287. l = c;
  288. }
  289. switch (s) {
  290. case 1:
  291. if (j >= outlen) return 0;
  292. out[j++] = base64en[(l & 0x3) << 4];
  293. //out[j++] = '=';
  294. //out[j++] = '=';
  295. break;
  296. case 2:
  297. if (j >= outlen) return 0;
  298. out[j++] = base64en[(l & 0xf) << 2];
  299. //out[j++] = '=';
  300. break;
  301. }
  302. if (j >= outlen) return 0;
  303. out[j] = 0;
  304. return j;
  305. }
  306. unsigned int Utils::b64d(const char *in,unsigned char *out,unsigned int outlen)
  307. {
  308. 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 };
  309. unsigned int i = 0;
  310. unsigned int j = 0;
  311. while ((in[i] != '=')&&(in[i] != 0)) {
  312. if (j >= outlen)
  313. break;
  314. uint8_t c = base64de[(unsigned char)in[i]];
  315. if (c != 255) {
  316. switch (i & 0x3) {
  317. case 0:
  318. out[j] = (c << 2) & 0xff;
  319. break;
  320. case 1:
  321. out[j++] |= (c >> 4) & 0x3;
  322. out[j] = (c & 0xf) << 4;
  323. break;
  324. case 2:
  325. out[j++] |= (c >> 2) & 0xf;
  326. out[j] = (c & 0x3) << 6;
  327. break;
  328. case 3:
  329. out[j++] |= c;
  330. break;
  331. }
  332. }
  333. ++i;
  334. }
  335. return j;
  336. }
  337. #define ROL64(x,k) (((x) << (k)) | ((x) >> (64 - (k))))
  338. uint64_t Utils::random()
  339. {
  340. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  341. static Mutex l;
  342. static uint64_t s0 = Utils::getSecureRandom64();
  343. static uint64_t s1 = Utils::getSecureRandom64();
  344. static uint64_t s2 = Utils::getSecureRandom64();
  345. static uint64_t s3 = Utils::getSecureRandom64();
  346. l.lock();
  347. const uint64_t result = ROL64(s1 * 5,7) * 9;
  348. const uint64_t t = s1 << 17;
  349. s2 ^= s0;
  350. s3 ^= s1;
  351. s1 ^= s2;
  352. s0 ^= s3;
  353. s2 ^= t;
  354. s3 = ROL64(s3,45);
  355. l.unlock();
  356. return result;
  357. }
  358. } // namespace ZeroTier