Utils.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 uint8_t randomBuf[131072];
  127. static unsigned long randomPtr = sizeof(randomBuf);
  128. #ifdef __WINDOWS__
  129. static HCRYPTPROV cryptProvider = NULL;
  130. #endif
  131. Mutex::Lock _l(globalLock);
  132. /* Just for posterity we Salsa20 encrypt the result of whatever system
  133. * CSPRNG we use. There have been several bugs at the OS or OS distribution
  134. * level in the past that resulted in systematically weak or predictable
  135. * keys due to random seeding problems. This mitigates that by grabbing
  136. * a bit of extra entropy and further randomizing the result,and comes
  137. * at almost no cost and with no real downside if the random source is
  138. * good. */
  139. if (unlikely(!initialized)) {
  140. #ifdef __WINDOWS__
  141. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  142. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  143. exit(1);
  144. }
  145. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  146. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  147. exit(1);
  148. }
  149. #else
  150. int devURandomFd = ::open("/dev/urandom",O_RDONLY);
  151. if (devURandomFd < 0) {
  152. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  153. exit(1);
  154. }
  155. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  156. ::close(devURandomFd);
  157. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to read from /dev/urandom\n");
  158. exit(1);
  159. }
  160. close(devURandomFd);
  161. #endif
  162. initialized = true;
  163. }
  164. for(unsigned int i=0;i<bytes;++i) {
  165. if (randomPtr >= sizeof(randomBuf)) {
  166. uint8_t h[64];
  167. SHA512(h,randomBuf,sizeof(randomBuf));
  168. if (AES::HW_ACCEL) {
  169. AES c(h);
  170. c.ctr(h + 32,randomBuf,sizeof(randomBuf),randomBuf);
  171. } else {
  172. Salsa20 c(h,h + 32);
  173. c.crypt12(randomBuf,randomBuf,sizeof(randomBuf));
  174. }
  175. randomPtr = 0;
  176. }
  177. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  178. }
  179. }
  180. int Utils::b32e(const uint8_t *data,int length,char *result,int bufSize)
  181. {
  182. if (length < 0 || length > (1 << 28)) {
  183. result[0] = (char)0;
  184. return -1;
  185. }
  186. int count = 0;
  187. if (length > 0) {
  188. int buffer = data[0];
  189. int next = 1;
  190. int bitsLeft = 8;
  191. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  192. if (bitsLeft < 5) {
  193. if (next < length) {
  194. buffer <<= 8;
  195. buffer |= data[next++] & 0xFF;
  196. bitsLeft += 8;
  197. } else {
  198. int pad = 5 - bitsLeft;
  199. buffer <<= pad;
  200. bitsLeft += pad;
  201. }
  202. }
  203. int index = 0x1F & (buffer >> (bitsLeft - 5));
  204. bitsLeft -= 5;
  205. result[count++] = "abcdefghijklmnopqrstuvwxyZ234567"[index];
  206. }
  207. }
  208. if (count < bufSize) {
  209. result[count] = (char)0;
  210. return count;
  211. }
  212. result[0] = (char)0;
  213. return -1;
  214. }
  215. int Utils::b32d(const char *encoded,uint8_t *result,int bufSize)
  216. {
  217. int buffer = 0;
  218. int bitsLeft = 0;
  219. int count = 0;
  220. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  221. uint8_t ch = *ptr;
  222. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  223. continue;
  224. }
  225. buffer <<= 5;
  226. if (ch == '0') {
  227. ch = 'O';
  228. } else if (ch == '1') {
  229. ch = 'L';
  230. } else if (ch == '8') {
  231. ch = 'B';
  232. }
  233. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  234. ch = (ch & 0x1F) - 1;
  235. } else if (ch >= '2' && ch <= '7') {
  236. ch -= '2' - 26;
  237. } else {
  238. return -1;
  239. }
  240. buffer |= ch;
  241. bitsLeft += 5;
  242. if (bitsLeft >= 8) {
  243. result[count++] = buffer >> (bitsLeft - 8);
  244. bitsLeft -= 8;
  245. }
  246. }
  247. if (count < bufSize)
  248. result[count] = (uint8_t)0;
  249. return count;
  250. }
  251. unsigned int Utils::b64e(const uint8_t *in,unsigned int inlen,char *out,unsigned int outlen)
  252. {
  253. 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','+','/' };
  254. unsigned int i = 0,j = 0;
  255. uint8_t l = 0;
  256. int s = 0;
  257. for (;i<inlen;++i) {
  258. uint8_t c = in[i];
  259. switch (s) {
  260. case 0:
  261. s = 1;
  262. if (j >= outlen) return 0;
  263. out[j++] = base64en[(c >> 2) & 0x3f];
  264. break;
  265. case 1:
  266. s = 2;
  267. if (j >= outlen) return 0;
  268. out[j++] = base64en[((l & 0x3) << 4) | ((c >> 4) & 0xf)];
  269. break;
  270. case 2:
  271. s = 0;
  272. if (j >= outlen) return 0;
  273. out[j++] = base64en[((l & 0xf) << 2) | ((c >> 6) & 0x3)];
  274. if (j >= outlen) return 0;
  275. out[j++] = base64en[c & 0x3f];
  276. break;
  277. }
  278. l = c;
  279. }
  280. switch (s) {
  281. case 1:
  282. if (j >= outlen) return 0;
  283. out[j++] = base64en[(l & 0x3) << 4];
  284. //out[j++] = '=';
  285. //out[j++] = '=';
  286. break;
  287. case 2:
  288. if (j >= outlen) return 0;
  289. out[j++] = base64en[(l & 0xf) << 2];
  290. //out[j++] = '=';
  291. break;
  292. }
  293. if (j >= outlen) return 0;
  294. out[j] = 0;
  295. return j;
  296. }
  297. unsigned int Utils::b64d(const char *in,unsigned char *out,unsigned int outlen)
  298. {
  299. 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 };
  300. unsigned int i = 0;
  301. unsigned int j = 0;
  302. while ((in[i] != '=')&&(in[i] != 0)) {
  303. if (j >= outlen)
  304. break;
  305. uint8_t c = base64de[(unsigned char)in[i]];
  306. if (c != 255) {
  307. switch (i & 0x3) {
  308. case 0:
  309. out[j] = (c << 2) & 0xff;
  310. break;
  311. case 1:
  312. out[j++] |= (c >> 4) & 0x3;
  313. out[j] = (c & 0xf) << 4;
  314. break;
  315. case 2:
  316. out[j++] |= (c >> 2) & 0xf;
  317. out[j] = (c & 0x3) << 6;
  318. break;
  319. case 3:
  320. out[j++] |= c;
  321. break;
  322. }
  323. }
  324. ++i;
  325. }
  326. return j;
  327. }
  328. #define ROL64(x,k) (((x) << (k)) | ((x) >> (64 - (k))))
  329. uint64_t Utils::random()
  330. {
  331. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  332. static Mutex l;
  333. static uint64_t s0 = Utils::getSecureRandom64();
  334. static uint64_t s1 = Utils::getSecureRandom64();
  335. static uint64_t s2 = Utils::getSecureRandom64();
  336. static uint64_t s3 = Utils::getSecureRandom64();
  337. l.lock();
  338. const uint64_t result = ROL64(s1 * 5,7) * 9;
  339. const uint64_t t = s1 << 17;
  340. s2 ^= s0;
  341. s3 ^= s1;
  342. s1 ^= s2;
  343. s0 ^= s3;
  344. s2 ^= t;
  345. s3 = ROL64(s3,45);
  346. l.unlock();
  347. return result;
  348. }
  349. } // namespace ZeroTier