SoftwareUpdater.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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. SoftwareUpdater::SoftwareUpdater(const RuntimeEnvironment *renv) :
  51. _r(renv),
  52. _myVersion(packVersion(ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION)),
  53. _lastUpdateAttempt(0),
  54. _status(UPDATE_STATUS_IDLE),
  55. _die(false),
  56. _lock()
  57. {
  58. }
  59. SoftwareUpdater::~SoftwareUpdater()
  60. {
  61. _die = true;
  62. for(;;) {
  63. _lock.lock();
  64. bool ip = (_status != UPDATE_STATUS_IDLE);
  65. _lock.unlock();
  66. if (ip)
  67. Thread::sleep(500);
  68. else break;
  69. }
  70. }
  71. void SoftwareUpdater::cleanOldUpdates()
  72. {
  73. std::string updatesDir(RR->homePath + ZT_PATH_SEPARATOR_S + "updates.d");
  74. std::map<std::string,bool> dl(Utils::listDirectory(updatesDir.c_str()));
  75. for(std::map<std::string,bool>::iterator i(dl.begin());i!=dl.end();++i) {
  76. if (!i->second)
  77. Utils::rm((updatesDir + ZT_PATH_SEPARATOR_S + i->first).c_str());
  78. }
  79. }
  80. void SoftwareUpdater::sawRemoteVersion(unsigned int vmaj,unsigned int vmin,unsigned int rev)
  81. {
  82. const uint64_t tmp = packVersion(vmaj,vmin,rev);
  83. if (tmp > _myVersion) {
  84. Mutex::Lock _l(_lock);
  85. if ((_status == UPDATE_STATUS_IDLE)&&(!_die)&&(ZT_DEFAULTS.updateLatestNfoURL.length())) {
  86. const uint64_t now = Utils::now();
  87. if ((now - _lastUpdateAttempt) >= ZT_UPDATE_MIN_INTERVAL) {
  88. _lastUpdateAttempt = now;
  89. _status = UPDATE_STATUS_GETTING_NFO;
  90. RR->http->GET(ZT_DEFAULTS.updateLatestNfoURL,HttpClient::NO_HEADERS,ZT_UPDATE_HTTP_TIMEOUT,&_cbHandleGetLatestVersionInfo,this);
  91. }
  92. }
  93. }
  94. }
  95. void SoftwareUpdater::checkNow()
  96. {
  97. Mutex::Lock _l(_lock);
  98. if (_status == UPDATE_STATUS_IDLE) {
  99. _lastUpdateAttempt = Utils::now();
  100. _status = UPDATE_STATUS_GETTING_NFO;
  101. RR->http->GET(ZT_DEFAULTS.updateLatestNfoURL,HttpClient::NO_HEADERS,ZT_UPDATE_HTTP_TIMEOUT,&_cbHandleGetLatestVersionInfo,this);
  102. }
  103. }
  104. const char *SoftwareUpdater::parseNfo(
  105. const char *nfoText,
  106. unsigned int &vMajor,
  107. unsigned int &vMinor,
  108. unsigned int &vRevision,
  109. Address &signedBy,
  110. std::string &signature,
  111. std::string &url)
  112. {
  113. try {
  114. Dictionary nfo(nfoText);
  115. vMajor = Utils::strToUInt(nfo.get("vMajor").c_str());
  116. vMinor = Utils::strToUInt(nfo.get("vMinor").c_str());
  117. vRevision = Utils::strToUInt(nfo.get("vRevision").c_str());
  118. signedBy = nfo.get("signedBy");
  119. signature = Utils::unhex(nfo.get("ed25519"));
  120. url = nfo.get("url");
  121. if (signature.length() != ZT_C25519_SIGNATURE_LEN)
  122. return "bad ed25519 signature, invalid length";
  123. if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
  124. return "invalid URL, must begin with http://";
  125. return (const char *)0;
  126. } catch ( ... ) {
  127. return "invalid NFO file format or one or more required fields missing";
  128. }
  129. }
  130. bool SoftwareUpdater::validateUpdate(
  131. const void *data,
  132. unsigned int len,
  133. const Address &signedBy,
  134. const std::string &signature)
  135. {
  136. std::map< Address,Identity >::const_iterator updateAuthority = ZT_DEFAULTS.updateAuthorities.find(signedBy);
  137. if (updateAuthority == ZT_DEFAULTS.updateAuthorities.end())
  138. return false;
  139. return updateAuthority->second.verify(data,len,signature.data(),(unsigned int)signature.length());
  140. }
  141. void SoftwareUpdater::_cbHandleGetLatestVersionInfo(void *arg,int code,const std::string &url,const std::string &body)
  142. {
  143. SoftwareUpdater *upd = (SoftwareUpdater *)arg;
  144. const RuntimeEnvironment *RR = (const RuntimeEnvironment *)upd->_r;
  145. Mutex::Lock _l(upd->_lock);
  146. if ((upd->_die)||(upd->_status != UPDATE_STATUS_GETTING_NFO)) {
  147. upd->_status = UPDATE_STATUS_IDLE;
  148. return;
  149. }
  150. if (code != 200) {
  151. LOG("software update check failed: server responded with code %d",code);
  152. upd->_status = UPDATE_STATUS_IDLE;
  153. return;
  154. }
  155. try {
  156. unsigned int vMajor = 0,vMinor = 0,vRevision = 0;
  157. Address signedBy;
  158. std::string signature,url;
  159. const char *err = parseNfo(body.c_str(),vMajor,vMinor,vRevision,signedBy,signature,url);
  160. if (err) {
  161. LOG("software update check aborted: .nfo file parse error: %s",err);
  162. upd->_status = UPDATE_STATUS_IDLE;
  163. return;
  164. }
  165. if (!ZT_DEFAULTS.updateAuthorities.count(signedBy)) {
  166. LOG("software update check aborted: .nfo file specifies unknown signing authority");
  167. upd->_status = UPDATE_STATUS_IDLE;
  168. return;
  169. }
  170. #ifndef ZT_ALWAYS_UPDATE /* for testing */
  171. if (packVersion(vMajor,vMinor,vRevision) <= upd->_myVersion) {
  172. TRACE("software update check complete: version on update site is not newer than my version, no update necessary");
  173. upd->_status = UPDATE_STATUS_IDLE;
  174. return;
  175. }
  176. #endif
  177. upd->_status = UPDATE_STATUS_GETTING_FILE;
  178. upd->_signedBy = signedBy;
  179. upd->_signature = signature;
  180. RR->http->GET(url,HttpClient::NO_HEADERS,ZT_UPDATE_HTTP_TIMEOUT,&_cbHandleGetLatestVersionBinary,arg);
  181. } catch ( ... ) {
  182. LOG("software update check failed: .nfo file invalid or missing field(s)");
  183. upd->_status = UPDATE_STATUS_IDLE;
  184. }
  185. }
  186. void SoftwareUpdater::_cbHandleGetLatestVersionBinary(void *arg,int code,const std::string &url,const std::string &body)
  187. {
  188. SoftwareUpdater *upd = (SoftwareUpdater *)arg;
  189. const RuntimeEnvironment *RR = (const RuntimeEnvironment *)upd->_r;
  190. Mutex::Lock _l(upd->_lock);
  191. if (!validateUpdate(body.data(),(unsigned int)body.length(),upd->_signedBy,upd->_signature)) {
  192. LOG("software update failed: update fetched from '%s' failed signature check (image size: %u)",url.c_str(),(unsigned int)body.length());
  193. upd->_status = UPDATE_STATUS_IDLE;
  194. return;
  195. }
  196. size_t lastSlash = url.rfind('/');
  197. if (lastSlash == std::string::npos) { // sanity check, shouldn't happen
  198. LOG("software update failed: invalid URL");
  199. upd->_status = UPDATE_STATUS_IDLE;
  200. return;
  201. }
  202. std::string updatesDir(RR->homePath + ZT_PATH_SEPARATOR_S + "updates.d");
  203. std::string updateFilename(url.substr(lastSlash + 1));
  204. if ((updateFilename.length() < 3)||(updateFilename.find("..") != std::string::npos)) {
  205. LOG("software update failed: invalid URL: filename contains invalid characters");
  206. upd->_status = UPDATE_STATUS_IDLE;
  207. return;
  208. }
  209. for(std::string::iterator c(updateFilename.begin());c!=updateFilename.end();++c) {
  210. // Only allow a list of whitelisted characters to make up the filename to prevent any
  211. // path shenanigans, esp on Windows where / is not the path separator.
  212. if (!strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.0123456789",*c)) {
  213. LOG("software update failed: invalid URL: filename contains invalid characters");
  214. upd->_status = UPDATE_STATUS_IDLE;
  215. return;
  216. }
  217. }
  218. std::string updatePath(updatesDir + ZT_PATH_SEPARATOR_S + updateFilename);
  219. #ifdef __WINDOWS__
  220. CreateDirectoryA(updatesDir.c_str(),NULL);
  221. #else
  222. mkdir(updatesDir.c_str(),0755);
  223. #endif
  224. FILE *upf = fopen(updatePath.c_str(),"wb");
  225. if (!upf) {
  226. LOG("software update failed: unable to open %s for writing",updatePath.c_str());
  227. upd->_status = UPDATE_STATUS_IDLE;
  228. return;
  229. }
  230. if (fwrite(body.data(),body.length(),1,upf) != 1) {
  231. LOG("software update failed: unable to write to %s",updatePath.c_str());
  232. upd->_status = UPDATE_STATUS_IDLE;
  233. fclose(upf);
  234. Utils::rm(updatePath);
  235. return;
  236. }
  237. fclose(upf);
  238. #ifdef __UNIX_LIKE__
  239. ::chmod(updatePath.c_str(),0755);
  240. #endif
  241. // We exit with this reason code and the path as the text. It is the
  242. // caller's responsibility (main.c) to pick this up and do the right
  243. // thing.
  244. upd->_status = UPDATE_STATUS_IDLE;
  245. RR->node->terminate(Node::NODE_RESTART_FOR_UPGRADE,updatePath.c_str());
  246. }
  247. } // namespace ZeroTier