SoftwareUpdater.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdexcept>
  31. #include "../version.h"
  32. #include "Constants.hpp"
  33. #include "SoftwareUpdater.hpp"
  34. #include "Dictionary.hpp"
  35. #include "C25519.hpp"
  36. #include "Identity.hpp"
  37. #include "Logger.hpp"
  38. #include "RuntimeEnvironment.hpp"
  39. #include "Thread.hpp"
  40. #include "Node.hpp"
  41. #include "Utils.hpp"
  42. #include "HttpClient.hpp"
  43. #ifdef __UNIX_LIKE__
  44. #include <unistd.h>
  45. #include <fcntl.h>
  46. #include <sys/types.h>
  47. #include <sys/stat.h>
  48. #endif
  49. namespace ZeroTier {
  50. static inline std::map< Address,Identity > _mkUpdateAuth()
  51. {
  52. std::map< Address,Identity > ua;
  53. { // 0001
  54. Identity id("e9bc3707b5:0:c4cef17bde99eadf9748c4fd11b9b06dc5cd8eb429227811d2c336e6b96a8d329e8abd0a4f45e47fe1bcebf878c004c822d952ff77fc2833af4c74e65985c435");
  55. ua[id.address()] = id;
  56. }
  57. { // 0002
  58. Identity id("56520eaf93:0:7d858b47988b34399a9a31136de07b46104d7edb4a98fa1d6da3e583d3a33e48be531532b886f0b12cd16794a66ab9220749ec5112cbe96296b18fe0cc79ca05");
  59. ua[id.address()] = id;
  60. }
  61. { // 0003
  62. Identity id("7c195de2e0:0:9f659071c960f9b0f0b96f9f9ecdaa27c7295feed9c79b7db6eedcc11feb705e6dd85c70fa21655204d24c897865b99eb946b753a2bbcf2be5f5e006ae618c54");
  63. ua[id.address()] = id;
  64. }
  65. { // 0004
  66. Identity id("415f4cfde7:0:54118e87777b0ea5d922c10b337c4f4bd1db7141845bd54004b3255551a6e356ba6b9e1e85357dbfafc45630b8faa2ebf992f31479e9005f0472685f2d8cbd6e");
  67. ua[id.address()] = id;
  68. }
  69. return ua;
  70. }
  71. static inline const char *_mkUpdateUrl()
  72. {
  73. #if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) )
  74. if (sizeof(void *) == 8)
  75. return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo";
  76. else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo";
  77. #define GOT_UPDATE_URL
  78. #endif
  79. #ifdef __APPLE__
  80. return "http://download.zerotier.com/ZeroTierOneInstaller-mac-combined-LATEST.nfo";
  81. #define GOT_UPDATE_URL
  82. #endif
  83. #ifdef __WINDOWS__
  84. return "http://download.zerotier.com/ZeroTierOneInstaller-windows-intel-LATEST.nfo";
  85. #define GOT_UPDATE_URL
  86. #endif
  87. #ifndef GOT_UPDATE_URL
  88. return "";
  89. #endif
  90. }
  91. SoftwareUpdater::SoftwareUpdater(const RuntimeEnvironment *renv) :
  92. RR(renv),
  93. _myVersion(packVersion(ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION)),
  94. _lastUpdateAttempt(0),
  95. _status(UPDATE_STATUS_IDLE),
  96. _die(false),
  97. _lock()
  98. {
  99. }
  100. SoftwareUpdater::~SoftwareUpdater()
  101. {
  102. _die = true;
  103. for(;;) {
  104. _lock.lock();
  105. bool ip = (_status != UPDATE_STATUS_IDLE);
  106. _lock.unlock();
  107. if (ip)
  108. Thread::sleep(500);
  109. else break;
  110. }
  111. }
  112. void SoftwareUpdater::cleanOldUpdates()
  113. {
  114. std::string updatesDir(RR->homePath + ZT_PATH_SEPARATOR_S + "updates.d");
  115. std::map<std::string,bool> dl(Utils::listDirectory(updatesDir.c_str()));
  116. for(std::map<std::string,bool>::iterator i(dl.begin());i!=dl.end();++i) {
  117. if (!i->second)
  118. Utils::rm((updatesDir + ZT_PATH_SEPARATOR_S + i->first).c_str());
  119. }
  120. }
  121. void SoftwareUpdater::sawRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int rev)
  122. {
  123. const uint64_t tmp = packVersion(vmaj,vmin,rev);
  124. if (tmp > _myVersion) {
  125. Mutex::Lock _l(_lock);
  126. if ((_status == UPDATE_STATUS_IDLE)&&(!_die)&&(ZT_DEFAULTS.updateLatestNfoURL.length())) {
  127. const uint64_t now = Utils::now();
  128. if ((now - _lastUpdateAttempt) >= ZT_UPDATE_MIN_INTERVAL) {
  129. _lastUpdateAttempt = now;
  130. _status = UPDATE_STATUS_GETTING_NFO;
  131. RR->http->GET(ZT_DEFAULTS.updateLatestNfoURL,HttpClient::NO_HEADERS,ZT_UPDATE_HTTP_TIMEOUT,&_cbHandleGetLatestVersionInfo,this);
  132. }
  133. }
  134. }
  135. }
  136. void SoftwareUpdater::checkNow()
  137. {
  138. Mutex::Lock _l(_lock);
  139. if (_status == UPDATE_STATUS_IDLE) {
  140. _lastUpdateAttempt = Utils::now();
  141. _status = UPDATE_STATUS_GETTING_NFO;
  142. RR->http->GET(ZT_DEFAULTS.updateLatestNfoURL,HttpClient::NO_HEADERS,ZT_UPDATE_HTTP_TIMEOUT,&_cbHandleGetLatestVersionInfo,this);
  143. }
  144. }
  145. const char *SoftwareUpdater::parseNfo(
  146. const char *nfoText,
  147. unsigned int &vMajor,
  148. unsigned int &vMinor,
  149. unsigned int &vRevision,
  150. Address &signedBy,
  151. std::string &signature,
  152. std::string &url)
  153. {
  154. try {
  155. Dictionary nfo(nfoText);
  156. vMajor = Utils::strToUInt(nfo.get("vMajor").c_str());
  157. vMinor = Utils::strToUInt(nfo.get("vMinor").c_str());
  158. vRevision = Utils::strToUInt(nfo.get("vRevision").c_str());
  159. signedBy = nfo.get("signedBy");
  160. signature = Utils::unhex(nfo.get("ed25519"));
  161. url = nfo.get("url");
  162. if (signature.length() != ZT_C25519_SIGNATURE_LEN)
  163. return "bad ed25519 signature, invalid length";
  164. if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
  165. return "invalid URL, must begin with http://";
  166. return (const char *)0;
  167. } catch ( ... ) {
  168. return "invalid NFO file format or one or more required fields missing";
  169. }
  170. }
  171. bool SoftwareUpdater::validateUpdate(
  172. const void *data,
  173. unsigned int len,
  174. const Address &signedBy,
  175. const std::string &signature)
  176. {
  177. std::map< Address,Identity >::const_iterator updateAuthority = ZT_DEFAULTS.updateAuthorities.find(signedBy);
  178. if (updateAuthority == ZT_DEFAULTS.updateAuthorities.end())
  179. return false;
  180. return updateAuthority->second.verify(data,len,signature.data(),(unsigned int)signature.length());
  181. }
  182. void SoftwareUpdater::_cbHandleGetLatestVersionInfo(void *arg,int code,const std::string &url,const std::string &body)
  183. {
  184. SoftwareUpdater *upd = (SoftwareUpdater *)arg;
  185. const RuntimeEnvironment *RR = (const RuntimeEnvironment *)upd->RR;
  186. Mutex::Lock _l(upd->_lock);
  187. if ((upd->_die)||(upd->_status != UPDATE_STATUS_GETTING_NFO)) {
  188. upd->_status = UPDATE_STATUS_IDLE;
  189. return;
  190. }
  191. if (code != 200) {
  192. LOG("software update check failed: server responded with code %d",code);
  193. upd->_status = UPDATE_STATUS_IDLE;
  194. return;
  195. }
  196. try {
  197. unsigned int vMajor = 0,vMinor = 0,vRevision = 0;
  198. Address signedBy;
  199. std::string signature,url;
  200. const char *err = parseNfo(body.c_str(),vMajor,vMinor,vRevision,signedBy,signature,url);
  201. if (err) {
  202. LOG("software update check aborted: .nfo file parse error: %s",err);
  203. upd->_status = UPDATE_STATUS_IDLE;
  204. return;
  205. }
  206. if (!ZT_DEFAULTS.updateAuthorities.count(signedBy)) {
  207. LOG("software update check aborted: .nfo file specifies unknown signing authority");
  208. upd->_status = UPDATE_STATUS_IDLE;
  209. return;
  210. }
  211. #ifndef ZT_ALWAYS_UPDATE /* for testing */
  212. if (packVersion(vMajor,vMinor,vRevision) <= upd->_myVersion) {
  213. TRACE("software update check complete: version on update site is not newer than my version, no update necessary");
  214. upd->_status = UPDATE_STATUS_IDLE;
  215. return;
  216. }
  217. #endif
  218. upd->_status = UPDATE_STATUS_GETTING_FILE;
  219. upd->_signedBy = signedBy;
  220. upd->_signature = signature;
  221. RR->http->GET(url,HttpClient::NO_HEADERS,ZT_UPDATE_HTTP_TIMEOUT,&_cbHandleGetLatestVersionBinary,arg);
  222. } catch ( ... ) {
  223. LOG("software update check failed: .nfo file invalid or missing field(s)");
  224. upd->_status = UPDATE_STATUS_IDLE;
  225. }
  226. }
  227. void SoftwareUpdater::_cbHandleGetLatestVersionBinary(void *arg,int code,const std::string &url,const std::string &body)
  228. {
  229. SoftwareUpdater *upd = (SoftwareUpdater *)arg;
  230. const RuntimeEnvironment *RR = (const RuntimeEnvironment *)upd->RR;
  231. Mutex::Lock _l(upd->_lock);
  232. if (!validateUpdate(body.data(),(unsigned int)body.length(),upd->_signedBy,upd->_signature)) {
  233. LOG("software update failed: update fetched from '%s' failed signature check (image size: %u)",url.c_str(),(unsigned int)body.length());
  234. upd->_status = UPDATE_STATUS_IDLE;
  235. return;
  236. }
  237. size_t lastSlash = url.rfind('/');
  238. if (lastSlash == std::string::npos) { // sanity check, shouldn't happen
  239. LOG("software update failed: invalid URL");
  240. upd->_status = UPDATE_STATUS_IDLE;
  241. return;
  242. }
  243. std::string updatesDir(RR->homePath + ZT_PATH_SEPARATOR_S + "updates.d");
  244. std::string updateFilename(url.substr(lastSlash + 1));
  245. if ((updateFilename.length() < 3)||(updateFilename.find("..") != std::string::npos)) {
  246. LOG("software update failed: invalid URL: filename contains invalid characters");
  247. upd->_status = UPDATE_STATUS_IDLE;
  248. return;
  249. }
  250. for(std::string::iterator c(updateFilename.begin());c!=updateFilename.end();++c) {
  251. // Only allow a list of whitelisted characters to make up the filename to prevent any
  252. // path shenanigans, esp on Windows where / is not the path separator.
  253. if (!strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.0123456789",*c)) {
  254. LOG("software update failed: invalid URL: filename contains invalid characters");
  255. upd->_status = UPDATE_STATUS_IDLE;
  256. return;
  257. }
  258. }
  259. std::string updatePath(updatesDir + ZT_PATH_SEPARATOR_S + updateFilename);
  260. #ifdef __WINDOWS__
  261. CreateDirectoryA(updatesDir.c_str(),NULL);
  262. #else
  263. mkdir(updatesDir.c_str(),0755);
  264. #endif
  265. FILE *upf = fopen(updatePath.c_str(),"wb");
  266. if (!upf) {
  267. LOG("software update failed: unable to open %s for writing",updatePath.c_str());
  268. upd->_status = UPDATE_STATUS_IDLE;
  269. return;
  270. }
  271. if (fwrite(body.data(),body.length(),1,upf) != 1) {
  272. LOG("software update failed: unable to write to %s",updatePath.c_str());
  273. upd->_status = UPDATE_STATUS_IDLE;
  274. fclose(upf);
  275. Utils::rm(updatePath);
  276. return;
  277. }
  278. fclose(upf);
  279. #ifdef __UNIX_LIKE__
  280. ::chmod(updatePath.c_str(),0755);
  281. #endif
  282. // We exit with this reason code and the path as the text. It is the
  283. // caller's responsibility (main.c) to pick this up and do the right
  284. // thing.
  285. upd->_status = UPDATE_STATUS_IDLE;
  286. RR->node->terminate(Node::NODE_RESTART_FOR_UPGRADE,updatePath.c_str());
  287. }
  288. } // namespace ZeroTier