Utils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier,Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation,either version 3 of the License,or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not,see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <stdlib.h>
  29. #include <stdarg.h>
  30. #include <time.h>
  31. #include <sys/stat.h>
  32. #include "Constants.hpp"
  33. #ifdef __UNIX_LIKE__
  34. #include <unistd.h>
  35. #include <errno.h>
  36. #include <fcntl.h>
  37. #include <sys/types.h>
  38. #include <sys/stat.h>
  39. #include <sys/uio.h>
  40. #include <dirent.h>
  41. #endif
  42. #ifdef __WINDOWS__
  43. #include <wincrypt.h>
  44. #endif
  45. #include "Utils.hpp"
  46. #include "Mutex.hpp"
  47. #include "Salsa20.hpp"
  48. namespace ZeroTier {
  49. const char Utils::HEXCHARS[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
  50. // Crazy hack to force memory to be securely zeroed in spite of the best efforts of optimizing compilers.
  51. static void _Utils_doBurn(volatile uint8_t *ptr,unsigned int len)
  52. {
  53. volatile uint8_t *const end = ptr + len;
  54. while (ptr != end) *(ptr++) = (uint8_t)0;
  55. }
  56. static void (*volatile _Utils_doBurn_ptr)(volatile uint8_t *,unsigned int) = _Utils_doBurn;
  57. void Utils::burn(void *ptr,unsigned int len) { (_Utils_doBurn_ptr)((volatile uint8_t *)ptr,len); }
  58. static unsigned long _Utils_itoa(unsigned long n,char *s)
  59. {
  60. if (n == 0)
  61. return 0;
  62. unsigned long pos = _Utils_itoa(n / 10,s);
  63. if (pos >= 22) // sanity check,should be impossible
  64. pos = 22;
  65. s[pos] = '0' + (char)(n % 10);
  66. return pos + 1;
  67. }
  68. char *Utils::decimal(unsigned long n,char s[24])
  69. {
  70. if (n == 0) {
  71. s[0] = '0';
  72. s[1] = (char)0;
  73. return s;
  74. }
  75. s[_Utils_itoa(n,s)] = (char)0;
  76. return s;
  77. }
  78. unsigned int Utils::unhex(const char *h,void *buf,unsigned int buflen)
  79. {
  80. unsigned int l = 0;
  81. while (l < buflen) {
  82. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  83. if (!hc) break;
  84. uint8_t c = 0;
  85. if ((hc >= 48)&&(hc <= 57)) // 0..9
  86. c = hc - 48;
  87. else if ((hc >= 97)&&(hc <= 102)) // a..f
  88. c = hc - 87;
  89. else if ((hc >= 65)&&(hc <= 70)) // A..F
  90. c = hc - 55;
  91. hc = *(reinterpret_cast<const uint8_t *>(h++));
  92. if (!hc) break;
  93. c <<= 4;
  94. if ((hc >= 48)&&(hc <= 57))
  95. c |= hc - 48;
  96. else if ((hc >= 97)&&(hc <= 102))
  97. c |= hc - 87;
  98. else if ((hc >= 65)&&(hc <= 70))
  99. c |= hc - 55;
  100. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  101. }
  102. return l;
  103. }
  104. unsigned int Utils::unhex(const char *h,unsigned int hlen,void *buf,unsigned int buflen)
  105. {
  106. unsigned int l = 0;
  107. const char *hend = h + hlen;
  108. while (l < buflen) {
  109. if (h == hend) break;
  110. uint8_t hc = *(reinterpret_cast<const uint8_t *>(h++));
  111. if (!hc) break;
  112. uint8_t c = 0;
  113. if ((hc >= 48)&&(hc <= 57))
  114. c = hc - 48;
  115. else if ((hc >= 97)&&(hc <= 102))
  116. c = hc - 87;
  117. else if ((hc >= 65)&&(hc <= 70))
  118. c = hc - 55;
  119. if (h == hend) break;
  120. hc = *(reinterpret_cast<const uint8_t *>(h++));
  121. if (!hc) break;
  122. c <<= 4;
  123. if ((hc >= 48)&&(hc <= 57))
  124. c |= hc - 48;
  125. else if ((hc >= 97)&&(hc <= 102))
  126. c |= hc - 87;
  127. else if ((hc >= 65)&&(hc <= 70))
  128. c |= hc - 55;
  129. reinterpret_cast<uint8_t *>(buf)[l++] = c;
  130. }
  131. return l;
  132. }
  133. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  134. {
  135. static Mutex globalLock;
  136. static Salsa20 s20;
  137. static bool s20Initialized = false;
  138. static uint8_t randomBuf[65536];
  139. static unsigned int randomPtr = sizeof(randomBuf);
  140. Mutex::Lock _l(globalLock);
  141. /* Just for posterity we Salsa20 encrypt the result of whatever system
  142. * CSPRNG we use. There have been several bugs at the OS or OS distribution
  143. * level in the past that resulted in systematically weak or predictable
  144. * keys due to random seeding problems. This mitigates that by grabbing
  145. * a bit of extra entropy and further randomizing the result,and comes
  146. * at almost no cost and with no real downside if the random source is
  147. * good. */
  148. if (!s20Initialized) {
  149. s20Initialized = true;
  150. uint64_t s20Key[4];
  151. s20Key[0] = (uint64_t)time(nullptr);
  152. #ifdef __WINDOWS__
  153. s20Key[1] = (uint64_t)buf; // address of buf
  154. #else
  155. s20Key[1] = (uint64_t)getpid();
  156. #endif
  157. s20Key[2] = (uint64_t)s20Key; // address of s20Key[]
  158. s20Key[3] = (uint64_t)&s20; // address of s20
  159. s20.init(s20Key,s20Key);
  160. }
  161. #ifdef __WINDOWS__
  162. static HCRYPTPROV cryptProvider = NULL;
  163. for(unsigned int i=0;i<bytes;++i) {
  164. if (randomPtr >= sizeof(randomBuf)) {
  165. if (cryptProvider == NULL) {
  166. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  167. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  168. exit(1);
  169. }
  170. }
  171. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  172. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  173. exit(1);
  174. }
  175. randomPtr = 0;
  176. s20.crypt12(randomBuf,randomBuf,sizeof(randomBuf));
  177. s20.init(randomBuf,randomBuf);
  178. }
  179. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  180. }
  181. #else // not __WINDOWS__
  182. static int devURandomFd = -1;
  183. if (devURandomFd < 0) {
  184. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  185. if (devURandomFd < 0) {
  186. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  187. exit(1);
  188. return;
  189. }
  190. }
  191. for(unsigned int i=0;i<bytes;++i) {
  192. if (randomPtr >= sizeof(randomBuf)) {
  193. for(;;) {
  194. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  195. ::close(devURandomFd);
  196. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  197. if (devURandomFd < 0) {
  198. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  199. exit(1);
  200. return;
  201. }
  202. } else break;
  203. }
  204. randomPtr = 0;
  205. s20.crypt12(randomBuf,randomBuf,sizeof(randomBuf));
  206. s20.init(randomBuf,randomBuf);
  207. }
  208. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  209. }
  210. #endif // __WINDOWS__ or not
  211. }
  212. int Utils::b32e(const uint8_t *data,int length,char *result,int bufSize)
  213. {
  214. if (length < 0 || length > (1 << 28)) {
  215. result[0] = (char)0;
  216. return -1;
  217. }
  218. int count = 0;
  219. if (length > 0) {
  220. int buffer = data[0];
  221. int next = 1;
  222. int bitsLeft = 8;
  223. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  224. if (bitsLeft < 5) {
  225. if (next < length) {
  226. buffer <<= 8;
  227. buffer |= data[next++] & 0xFF;
  228. bitsLeft += 8;
  229. } else {
  230. int pad = 5 - bitsLeft;
  231. buffer <<= pad;
  232. bitsLeft += pad;
  233. }
  234. }
  235. int index = 0x1F & (buffer >> (bitsLeft - 5));
  236. bitsLeft -= 5;
  237. result[count++] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"[index];
  238. }
  239. }
  240. if (count < bufSize) {
  241. result[count] = (char)0;
  242. return count;
  243. }
  244. result[0] = (char)0;
  245. return -1;
  246. }
  247. int Utils::b32d(const char *encoded,uint8_t *result,int bufSize)
  248. {
  249. int buffer = 0;
  250. int bitsLeft = 0;
  251. int count = 0;
  252. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  253. uint8_t ch = *ptr;
  254. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  255. continue;
  256. }
  257. buffer <<= 5;
  258. if (ch == '0') {
  259. ch = 'O';
  260. } else if (ch == '1') {
  261. ch = 'L';
  262. } else if (ch == '8') {
  263. ch = 'B';
  264. }
  265. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  266. ch = (ch & 0x1F) - 1;
  267. } else if (ch >= '2' && ch <= '7') {
  268. ch -= '2' - 26;
  269. } else {
  270. return -1;
  271. }
  272. buffer |= ch;
  273. bitsLeft += 5;
  274. if (bitsLeft >= 8) {
  275. result[count++] = buffer >> (bitsLeft - 8);
  276. bitsLeft -= 8;
  277. }
  278. }
  279. if (count < bufSize)
  280. result[count] = (uint8_t)0;
  281. return count;
  282. }
  283. unsigned int Utils::b64e(const uint8_t *in,unsigned int inlen,char *out,unsigned int outlen)
  284. {
  285. 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','+','/' };
  286. unsigned int i = 0,j = 0;
  287. uint8_t l = 0;
  288. int s = 0;
  289. for (;i<inlen;++i) {
  290. uint8_t c = in[i];
  291. switch (s) {
  292. case 0:
  293. s = 1;
  294. if (j >= outlen) return 0;
  295. out[j++] = base64en[(c >> 2) & 0x3f];
  296. break;
  297. case 1:
  298. s = 2;
  299. if (j >= outlen) return 0;
  300. out[j++] = base64en[((l & 0x3) << 4) | ((c >> 4) & 0xf)];
  301. break;
  302. case 2:
  303. s = 0;
  304. if (j >= outlen) return 0;
  305. out[j++] = base64en[((l & 0xf) << 2) | ((c >> 6) & 0x3)];
  306. if (j >= outlen) return 0;
  307. out[j++] = base64en[c & 0x3f];
  308. break;
  309. }
  310. l = c;
  311. }
  312. switch (s) {
  313. case 1:
  314. if (j >= outlen) return 0;
  315. out[j++] = base64en[(l & 0x3) << 4];
  316. //out[j++] = '=';
  317. //out[j++] = '=';
  318. break;
  319. case 2:
  320. if (j >= outlen) return 0;
  321. out[j++] = base64en[(l & 0xf) << 2];
  322. //out[j++] = '=';
  323. break;
  324. }
  325. if (j >= outlen) return 0;
  326. out[j] = 0;
  327. return j;
  328. }
  329. unsigned int Utils::b64d(const char *in,unsigned char *out,unsigned int outlen)
  330. {
  331. 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 };
  332. unsigned int i = 0;
  333. unsigned int j = 0;
  334. while ((in[i] != '=')&&(in[i] != 0)) {
  335. if (j >= outlen)
  336. break;
  337. uint8_t c = base64de[(unsigned char)in[i]];
  338. if (c != 255) {
  339. switch (i & 0x3) {
  340. case 0:
  341. out[j] = (c << 2) & 0xff;
  342. break;
  343. case 1:
  344. out[j++] |= (c >> 4) & 0x3;
  345. out[j] = (c & 0xf) << 4;
  346. break;
  347. case 2:
  348. out[j++] |= (c >> 2) & 0xf;
  349. out[j] = (c & 0x3) << 6;
  350. break;
  351. case 3:
  352. out[j++] |= c;
  353. break;
  354. }
  355. }
  356. ++i;
  357. }
  358. return j;
  359. }
  360. #define ROL64(x,k) (((x) << (k)) | ((x) >> (64 - (k))))
  361. uint64_t Utils::random()
  362. {
  363. // https://en.wikipedia.org/wiki/Xorshift#xoshiro256**
  364. static Mutex l;
  365. static uint64_t s0 = Utils::getSecureRandom64();
  366. static uint64_t s1 = Utils::getSecureRandom64();
  367. static uint64_t s2 = Utils::getSecureRandom64();
  368. static uint64_t s3 = Utils::getSecureRandom64();
  369. l.lock();
  370. const uint64_t result = ROL64(s1 * 5,7) * 9;
  371. const uint64_t t = s1 << 17;
  372. s2 ^= s0;
  373. s3 ^= s1;
  374. s1 ^= s2;
  375. s0 ^= s3;
  376. s2 ^= t;
  377. s3 = ROL64(s3,45);
  378. l.unlock();
  379. return result;
  380. }
  381. } // namespace ZeroTier