Utils.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #include <stdio.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <stdarg.h>
  22. #include <time.h>
  23. #include <sys/stat.h>
  24. #include "Constants.hpp"
  25. #ifdef __UNIX_LIKE__
  26. #include <unistd.h>
  27. #include <errno.h>
  28. #include <fcntl.h>
  29. #include <sys/types.h>
  30. #include <sys/stat.h>
  31. #include <sys/uio.h>
  32. #include <dirent.h>
  33. #endif
  34. #ifdef __WINDOWS__
  35. #include <wincrypt.h>
  36. #endif
  37. #include "Utils.hpp"
  38. #include "Mutex.hpp"
  39. #include "Salsa20.hpp"
  40. namespace ZeroTier {
  41. const char Utils::HEXCHARS[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
  42. // Crazy hack to force memory to be securely zeroed in spite of the best efforts of optimizing compilers.
  43. static void _Utils_doBurn(volatile uint8_t *ptr,unsigned int len)
  44. {
  45. volatile uint8_t *const end = ptr + len;
  46. while (ptr != end) *(ptr++) = (uint8_t)0;
  47. }
  48. static void (*volatile _Utils_doBurn_ptr)(volatile uint8_t *,unsigned int) = _Utils_doBurn;
  49. void Utils::burn(void *ptr,unsigned int len) { (_Utils_doBurn_ptr)((volatile uint8_t *)ptr,len); }
  50. std::string Utils::hex(const void *data,unsigned int len)
  51. {
  52. std::string r;
  53. r.reserve(len * 2);
  54. for(unsigned int i=0;i<len;++i) {
  55. r.push_back(HEXCHARS[(((const unsigned char *)data)[i] & 0xf0) >> 4]);
  56. r.push_back(HEXCHARS[((const unsigned char *)data)[i] & 0x0f]);
  57. }
  58. return r;
  59. }
  60. std::string Utils::unhex(const char *hex,unsigned int maxlen)
  61. {
  62. int n = 1;
  63. unsigned char c,b = 0;
  64. const char *eof = hex + maxlen;
  65. std::string r;
  66. if (!maxlen)
  67. return r;
  68. while ((c = (unsigned char)*(hex++))) {
  69. if ((c >= 48)&&(c <= 57)) { // 0..9
  70. if ((n ^= 1))
  71. r.push_back((char)(b | (c - 48)));
  72. else b = (c - 48) << 4;
  73. } else if ((c >= 65)&&(c <= 70)) { // A..F
  74. if ((n ^= 1))
  75. r.push_back((char)(b | (c - (65 - 10))));
  76. else b = (c - (65 - 10)) << 4;
  77. } else if ((c >= 97)&&(c <= 102)) { // a..f
  78. if ((n ^= 1))
  79. r.push_back((char)(b | (c - (97 - 10))));
  80. else b = (c - (97 - 10)) << 4;
  81. }
  82. if (hex == eof)
  83. break;
  84. }
  85. return r;
  86. }
  87. unsigned int Utils::unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len)
  88. {
  89. int n = 1;
  90. unsigned char c,b = 0;
  91. unsigned int l = 0;
  92. const char *eof = hex + maxlen;
  93. if (!maxlen)
  94. return 0;
  95. while ((c = (unsigned char)*(hex++))) {
  96. if ((c >= 48)&&(c <= 57)) { // 0..9
  97. if ((n ^= 1)) {
  98. if (l >= len) break;
  99. ((unsigned char *)buf)[l++] = (b | (c - 48));
  100. } else b = (c - 48) << 4;
  101. } else if ((c >= 65)&&(c <= 70)) { // A..F
  102. if ((n ^= 1)) {
  103. if (l >= len) break;
  104. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  105. } else b = (c - (65 - 10)) << 4;
  106. } else if ((c >= 97)&&(c <= 102)) { // a..f
  107. if ((n ^= 1)) {
  108. if (l >= len) break;
  109. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  110. } else b = (c - (97 - 10)) << 4;
  111. }
  112. if (hex == eof)
  113. break;
  114. }
  115. return l;
  116. }
  117. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  118. {
  119. static Mutex globalLock;
  120. static Salsa20 s20;
  121. static bool s20Initialized = false;
  122. static uint8_t randomBuf[65536];
  123. static unsigned int randomPtr = sizeof(randomBuf);
  124. Mutex::Lock _l(globalLock);
  125. /* Just for posterity we Salsa20 encrypt the result of whatever system
  126. * CSPRNG we use. There have been several bugs at the OS or OS distribution
  127. * level in the past that resulted in systematically weak or predictable
  128. * keys due to random seeding problems. This mitigates that by grabbing
  129. * a bit of extra entropy and further randomizing the result, and comes
  130. * at almost no cost and with no real downside if the random source is
  131. * good. */
  132. if (!s20Initialized) {
  133. s20Initialized = true;
  134. uint64_t s20Key[4];
  135. s20Key[0] = (uint64_t)time(0); // system clock
  136. s20Key[1] = (uint64_t)buf; // address of buf
  137. s20Key[2] = (uint64_t)s20Key; // address of s20Key[]
  138. s20Key[3] = (uint64_t)&s20; // address of s20
  139. s20.init(s20Key,256,s20Key);
  140. }
  141. #ifdef __WINDOWS__
  142. static HCRYPTPROV cryptProvider = NULL;
  143. for(unsigned int i=0;i<bytes;++i) {
  144. if (randomPtr >= sizeof(randomBuf)) {
  145. if (cryptProvider == NULL) {
  146. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  147. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  148. exit(1);
  149. }
  150. }
  151. if (!CryptGenRandom(cryptProvider,(DWORD)sizeof(randomBuf),(BYTE *)randomBuf)) {
  152. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  153. exit(1);
  154. }
  155. randomPtr = 0;
  156. s20.crypt12(randomBuf,randomBuf,sizeof(randomBuf));
  157. }
  158. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  159. }
  160. #else // not __WINDOWS__
  161. static int devURandomFd = -1;
  162. if (devURandomFd < 0) {
  163. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  164. if (devURandomFd < 0) {
  165. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  166. exit(1);
  167. return;
  168. }
  169. }
  170. for(unsigned int i=0;i<bytes;++i) {
  171. if (randomPtr >= sizeof(randomBuf)) {
  172. for(;;) {
  173. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  174. ::close(devURandomFd);
  175. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  176. if (devURandomFd < 0) {
  177. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  178. exit(1);
  179. return;
  180. }
  181. } else break;
  182. }
  183. randomPtr = 0;
  184. s20.crypt12(randomBuf,randomBuf,sizeof(randomBuf));
  185. }
  186. ((uint8_t *)buf)[i] = randomBuf[randomPtr++];
  187. }
  188. #endif // __WINDOWS__ or not
  189. }
  190. bool Utils::scopy(char *dest,unsigned int len,const char *src)
  191. {
  192. if (!len)
  193. return false; // sanity check
  194. if (!src) {
  195. *dest = (char)0;
  196. return true;
  197. }
  198. char *end = dest + len;
  199. while ((*dest++ = *src++)) {
  200. if (dest == end) {
  201. *(--dest) = (char)0;
  202. return false;
  203. }
  204. }
  205. return true;
  206. }
  207. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  208. throw(std::length_error)
  209. {
  210. va_list ap;
  211. va_start(ap,fmt);
  212. int n = (int)vsnprintf(buf,len,fmt,ap);
  213. va_end(ap);
  214. if ((n >= (int)len)||(n < 0)) {
  215. if (len)
  216. buf[len - 1] = (char)0;
  217. throw std::length_error("buf[] overflow in Utils::snprintf");
  218. }
  219. return (unsigned int)n;
  220. }
  221. } // namespace ZeroTier