Utils.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. static void _Utils_doBurn(char *ptr,unsigned int len)
  43. {
  44. for(unsigned int i=0;i<len;++i)
  45. ptr[i] = (char)0;
  46. }
  47. void (*volatile _Utils_doBurn_ptr)(char *,unsigned int) = _Utils_doBurn;
  48. void Utils::burn(void *ptr,unsigned int len)
  49. throw()
  50. {
  51. // Ridiculous hack: call _doBurn() via a volatile function pointer to
  52. // hold down compiler optimizers and beat them mercilessly until they
  53. // cry and mumble something about never eliding secure memory zeroing
  54. // again.
  55. (_Utils_doBurn_ptr)((char *)ptr,len);
  56. }
  57. std::string Utils::hex(const void *data,unsigned int len)
  58. {
  59. std::string r;
  60. r.reserve(len * 2);
  61. for(unsigned int i=0;i<len;++i) {
  62. r.push_back(HEXCHARS[(((const unsigned char *)data)[i] & 0xf0) >> 4]);
  63. r.push_back(HEXCHARS[((const unsigned char *)data)[i] & 0x0f]);
  64. }
  65. return r;
  66. }
  67. std::string Utils::unhex(const char *hex,unsigned int maxlen)
  68. {
  69. int n = 1;
  70. unsigned char c,b = 0;
  71. const char *eof = hex + maxlen;
  72. std::string r;
  73. if (!maxlen)
  74. return r;
  75. while ((c = (unsigned char)*(hex++))) {
  76. if ((c >= 48)&&(c <= 57)) { // 0..9
  77. if ((n ^= 1))
  78. r.push_back((char)(b | (c - 48)));
  79. else b = (c - 48) << 4;
  80. } else if ((c >= 65)&&(c <= 70)) { // A..F
  81. if ((n ^= 1))
  82. r.push_back((char)(b | (c - (65 - 10))));
  83. else b = (c - (65 - 10)) << 4;
  84. } else if ((c >= 97)&&(c <= 102)) { // a..f
  85. if ((n ^= 1))
  86. r.push_back((char)(b | (c - (97 - 10))));
  87. else b = (c - (97 - 10)) << 4;
  88. }
  89. if (hex == eof)
  90. break;
  91. }
  92. return r;
  93. }
  94. unsigned int Utils::unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len)
  95. {
  96. int n = 1;
  97. unsigned char c,b = 0;
  98. unsigned int l = 0;
  99. const char *eof = hex + maxlen;
  100. if (!maxlen)
  101. return 0;
  102. while ((c = (unsigned char)*(hex++))) {
  103. if ((c >= 48)&&(c <= 57)) { // 0..9
  104. if ((n ^= 1)) {
  105. if (l >= len) break;
  106. ((unsigned char *)buf)[l++] = (b | (c - 48));
  107. } else b = (c - 48) << 4;
  108. } else if ((c >= 65)&&(c <= 70)) { // A..F
  109. if ((n ^= 1)) {
  110. if (l >= len) break;
  111. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  112. } else b = (c - (65 - 10)) << 4;
  113. } else if ((c >= 97)&&(c <= 102)) { // a..f
  114. if ((n ^= 1)) {
  115. if (l >= len) break;
  116. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  117. } else b = (c - (97 - 10)) << 4;
  118. }
  119. if (hex == eof)
  120. break;
  121. }
  122. return l;
  123. }
  124. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  125. {
  126. static Mutex globalLock;
  127. static Salsa20 s20;
  128. static bool s20Initialized = false;
  129. Mutex::Lock _l(globalLock);
  130. /* Just for posterity we Salsa20 encrypt the result of whatever system
  131. * CSPRNG we use. There have been several bugs at the OS or OS distribution
  132. * level in the past that resulted in systematically weak or predictable
  133. * keys due to random seeding problems. This mitigates that by grabbing
  134. * a bit of extra entropy and further randomizing the result, and comes
  135. * at almost no cost and with no real downside if the random source is
  136. * good. */
  137. if (!s20Initialized) {
  138. s20Initialized = true;
  139. uint64_t s20Key[4];
  140. s20Key[0] = (uint64_t)time(0); // system clock
  141. s20Key[1] = (uint64_t)buf; // address of buf
  142. s20Key[2] = (uint64_t)s20Key; // address of s20Key[]
  143. s20Key[3] = (uint64_t)&s20; // address of s20
  144. s20.init(s20Key,256,s20Key);
  145. }
  146. #ifdef __WINDOWS__
  147. static HCRYPTPROV cryptProvider = NULL;
  148. if (cryptProvider == NULL) {
  149. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  150. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  151. exit(1);
  152. return;
  153. }
  154. }
  155. if (!CryptGenRandom(cryptProvider,(DWORD)bytes,(BYTE *)buf)) {
  156. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  157. exit(1);
  158. }
  159. #else // not __WINDOWS__
  160. static char randomBuf[131072];
  161. static unsigned int randomPtr = sizeof(randomBuf);
  162. static int devURandomFd = -1;
  163. if (devURandomFd <= 0) {
  164. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  165. if (devURandomFd <= 0) {
  166. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  167. exit(1);
  168. return;
  169. }
  170. }
  171. for(unsigned int i=0;i<bytes;++i) {
  172. if (randomPtr >= sizeof(randomBuf)) {
  173. for(;;) {
  174. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  175. ::close(devURandomFd);
  176. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  177. if (devURandomFd <= 0) {
  178. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\n");
  179. exit(1);
  180. return;
  181. }
  182. } else break;
  183. }
  184. randomPtr = 0;
  185. }
  186. ((char *)buf)[i] = randomBuf[randomPtr++];
  187. }
  188. #endif // __WINDOWS__ or not
  189. s20.encrypt12(buf,buf,bytes);
  190. }
  191. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  192. {
  193. std::vector<std::string> fields;
  194. std::string buf;
  195. if (!esc)
  196. esc = "";
  197. if (!quot)
  198. quot = "";
  199. bool escapeState = false;
  200. char quoteState = 0;
  201. while (*s) {
  202. if (escapeState) {
  203. escapeState = false;
  204. buf.push_back(*s);
  205. } else if (quoteState) {
  206. if (*s == quoteState) {
  207. quoteState = 0;
  208. fields.push_back(buf);
  209. buf.clear();
  210. } else buf.push_back(*s);
  211. } else {
  212. const char *quotTmp;
  213. if (strchr(esc,*s))
  214. escapeState = true;
  215. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  216. quoteState = *quotTmp;
  217. else if (strchr(sep,*s)) {
  218. if (buf.size() > 0) {
  219. fields.push_back(buf);
  220. buf.clear();
  221. } // else skip runs of seperators
  222. } else buf.push_back(*s);
  223. }
  224. ++s;
  225. }
  226. if (buf.size())
  227. fields.push_back(buf);
  228. return fields;
  229. }
  230. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  231. throw(std::length_error)
  232. {
  233. va_list ap;
  234. va_start(ap,fmt);
  235. int n = (int)vsnprintf(buf,len,fmt,ap);
  236. va_end(ap);
  237. if ((n >= (int)len)||(n < 0)) {
  238. if (len)
  239. buf[len - 1] = (char)0;
  240. throw std::length_error("buf[] overflow in Utils::snprintf");
  241. }
  242. return (unsigned int)n;
  243. }
  244. } // namespace ZeroTier