Utils.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  79. {
  80. static Mutex globalLock;
  81. static Salsa20 s20;
  82. static bool s20Initialized = false;
  83. static uint8_t randomBuf[65536];
  84. static unsigned int randomPtr = sizeof(randomBuf);
  85. Mutex::Lock _l(globalLock);
  86. /* Just for posterity we Salsa20 encrypt the result of whatever system
  87. * CSPRNG we use. There have been several bugs at the OS or OS distribution
  88. * level in the past that resulted in systematically weak or predictable
  89. * keys due to random seeding problems. This mitigates that by grabbing
  90. * a bit of extra entropy and further randomizing the result, and comes
  91. * at almost no cost and with no real downside if the random source is
  92. * good. */
  93. if (!s20Initialized) {
  94. s20Initialized = true;
  95. uint64_t s20Key[4];
  96. s20Key[0] = (uint64_t)time(0); // system clock
  97. s20Key[1] = (uint64_t)buf; // address of buf
  98. s20Key[2] = (uint64_t)s20Key; // address of s20Key[]
  99. s20Key[3] = (uint64_t)&s20; // address of s20
  100. s20.init(s20Key,s20Key);
  101. }
  102. #ifdef __WINDOWS__
  103. static HCRYPTPROV cryptProvider = NULL;
  104. for(unsigned int i=0;i<bytes;++i) {
  105. if (randomPtr >= sizeof(randomBuf)) {
  106. if (cryptProvider == NULL) {
  107. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  108. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  109. exit(1);
  110. }
  111. }
  112. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  113. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  114. exit(1);
  115. }
  116. randomPtr = 0;
  117. s20.crypt12(randomBuf,randomBuf,sizeof(randomBuf));
  118. s20.init(randomBuf,randomBuf);
  119. }
  120. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  121. }
  122. #else // not __WINDOWS__
  123. static int devURandomFd = -1;
  124. if (devURandomFd < 0) {
  125. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  126. if (devURandomFd < 0) {
  127. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  128. exit(1);
  129. return;
  130. }
  131. }
  132. for(unsigned int i=0;i<bytes;++i) {
  133. if (randomPtr >= sizeof(randomBuf)) {
  134. for(;;) {
  135. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  136. ::close(devURandomFd);
  137. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  138. if (devURandomFd < 0) {
  139. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  140. exit(1);
  141. return;
  142. }
  143. } else break;
  144. }
  145. randomPtr = 0;
  146. s20.crypt12(randomBuf,randomBuf,sizeof(randomBuf));
  147. s20.init(randomBuf,randomBuf);
  148. }
  149. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  150. }
  151. #endif // __WINDOWS__ or not
  152. }
  153. int Utils::b32d(const char *encoded, uint8_t *result, int bufSize)
  154. {
  155. int buffer = 0;
  156. int bitsLeft = 0;
  157. int count = 0;
  158. for (const uint8_t *ptr = (const uint8_t *)encoded;count<bufSize && *ptr; ++ptr) {
  159. uint8_t ch = *ptr;
  160. if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-' || ch == '.') {
  161. continue;
  162. }
  163. buffer <<= 5;
  164. if (ch == '0') {
  165. ch = 'O';
  166. } else if (ch == '1') {
  167. ch = 'L';
  168. } else if (ch == '8') {
  169. ch = 'B';
  170. }
  171. if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  172. ch = (ch & 0x1F) - 1;
  173. } else if (ch >= '2' && ch <= '7') {
  174. ch -= '2' - 26;
  175. } else {
  176. return -1;
  177. }
  178. buffer |= ch;
  179. bitsLeft += 5;
  180. if (bitsLeft >= 8) {
  181. result[count++] = buffer >> (bitsLeft - 8);
  182. bitsLeft -= 8;
  183. }
  184. }
  185. if (count < bufSize)
  186. result[count] = (uint8_t)0;
  187. return count;
  188. }
  189. int Utils::b32e(const uint8_t *data,int length,char *result,int bufSize)
  190. {
  191. if (length < 0 || length > (1 << 28))
  192. return -1;
  193. int count = 0;
  194. if (length > 0) {
  195. int buffer = data[0];
  196. int next = 1;
  197. int bitsLeft = 8;
  198. while (count < bufSize && (bitsLeft > 0 || next < length)) {
  199. if (bitsLeft < 5) {
  200. if (next < length) {
  201. buffer <<= 8;
  202. buffer |= data[next++] & 0xFF;
  203. bitsLeft += 8;
  204. } else {
  205. int pad = 5 - bitsLeft;
  206. buffer <<= pad;
  207. bitsLeft += pad;
  208. }
  209. }
  210. int index = 0x1F & (buffer >> (bitsLeft - 5));
  211. bitsLeft -= 5;
  212. result[count++] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"[index];
  213. }
  214. }
  215. if (count < bufSize)
  216. result[count] = (char)0;
  217. return count;
  218. }
  219. } // namespace ZeroTier