Utils.cpp 11 KB

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