SoftwareUpdater.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 <stdlib.h>
  20. #include <string.h>
  21. #include <stdint.h>
  22. #ifdef __WINDOWS__
  23. #include <WinSock2.h>
  24. #include <Windows.h>
  25. #include <ShlObj.h>
  26. #include <netioapi.h>
  27. #include <iphlpapi.h>
  28. #else
  29. #include <sys/types.h>
  30. #include <sys/socket.h>
  31. #include <sys/wait.h>
  32. #include <unistd.h>
  33. #include <ifaddrs.h>
  34. #endif
  35. #include "SoftwareUpdater.hpp"
  36. #include "../version.h"
  37. #include "../node/Constants.hpp"
  38. #include "../node/Utils.hpp"
  39. #include "../node/SHA512.hpp"
  40. #include "../node/Buffer.hpp"
  41. #include "../node/Node.hpp"
  42. #include "../osdep/OSUtils.hpp"
  43. #ifndef ZT_BUILD_ARCHITECTURE
  44. #define ZT_BUILD_ARCHITECTURE 0
  45. #endif
  46. #ifndef ZT_BUILD_PLATFORM
  47. #define ZT_BUILD_PLATFORM 0
  48. #endif
  49. namespace ZeroTier {
  50. SoftwareUpdater::SoftwareUpdater(Node &node,const std::string &homePath) :
  51. _node(node),
  52. _lastCheckTime(0),
  53. _homePath(homePath),
  54. _channel(ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL),
  55. _latestValid(false),
  56. _downloadLength(0)
  57. {
  58. // Check for a cached newer update. If there's a cached update that is not newer or looks bad, delete.
  59. try {
  60. std::string buf;
  61. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_META_FILENAME).c_str(),buf)) {
  62. nlohmann::json meta = OSUtils::jsonParse(buf);
  63. buf = std::string();
  64. const unsigned int rvMaj = (unsigned int)OSUtils::jsonInt(meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR],0);
  65. const unsigned int rvMin = (unsigned int)OSUtils::jsonInt(meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR],0);
  66. const unsigned int rvRev = (unsigned int)OSUtils::jsonInt(meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION],0);
  67. if ((Utils::compareVersion(rvMaj,rvMin,rvRev,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) > 0)&&(OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_BIN_FILENAME).c_str(),buf))) {
  68. if ((uint64_t)buf.length() == OSUtils::jsonInt(meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIZE],0)) {
  69. _latestMeta = meta;
  70. _latestValid = true;
  71. //printf("CACHED UPDATE IS NEWER AND LOOKS GOOD\n");
  72. }
  73. }
  74. }
  75. } catch ( ... ) {} // exceptions indicate invalid cached update
  76. if (!_latestValid) {
  77. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_META_FILENAME).c_str());
  78. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_BIN_FILENAME).c_str());
  79. }
  80. }
  81. SoftwareUpdater::~SoftwareUpdater()
  82. {
  83. }
  84. void SoftwareUpdater::setUpdateDistribution(bool distribute)
  85. {
  86. _dist.clear();
  87. if (distribute) {
  88. std::string udd(_homePath + ZT_PATH_SEPARATOR_S + "update-dist.d");
  89. std::vector<std::string> ud(OSUtils::listDirectory(udd.c_str()));
  90. for(std::vector<std::string>::iterator u(ud.begin());u!=ud.end();++u) {
  91. // Each update has a companion .json file describing it. Other files are ignored.
  92. if ((u->length() > 5)&&(u->substr(u->length() - 5,5) == ".json")) {
  93. std::string buf;
  94. if (OSUtils::readFile((udd + ZT_PATH_SEPARATOR_S + *u).c_str(),buf)) {
  95. try {
  96. _D d;
  97. d.meta = OSUtils::jsonParse(buf);
  98. std::string metaHash = OSUtils::jsonBinFromHex(d.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH]);
  99. if ((metaHash.length() == ZT_SHA512_DIGEST_LEN)&&(OSUtils::readFile((udd + ZT_PATH_SEPARATOR_S + u->substr(0,u->length() - 5)).c_str(),d.bin))) {
  100. uint8_t sha512[ZT_SHA512_DIGEST_LEN];
  101. SHA512::hash(sha512,d.bin.data(),(unsigned int)d.bin.length());
  102. if (!memcmp(sha512,metaHash.data(),ZT_SHA512_DIGEST_LEN)) { // double check that hash in JSON is correct
  103. d.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIZE] = d.bin.length(); // override with correct value -- setting this in meta json is optional
  104. _dist[Array<uint8_t,16>(sha512)] = d;
  105. //printf("update-dist.d: %s\n",u->c_str());
  106. }
  107. }
  108. } catch ( ... ) {} // ignore bad meta JSON, etc.
  109. }
  110. }
  111. }
  112. }
  113. }
  114. void SoftwareUpdater::handleSoftwareUpdateUserMessage(uint64_t origin,const void *data,unsigned int len)
  115. {
  116. if (!len) return;
  117. try {
  118. const MessageVerb v = (MessageVerb)reinterpret_cast<const uint8_t *>(data)[0];
  119. switch(v) {
  120. case VERB_GET_LATEST:
  121. case VERB_LATEST: {
  122. nlohmann::json req = OSUtils::jsonParse(std::string(reinterpret_cast<const char *>(data) + 1,len - 1));
  123. if (req.is_object()) {
  124. const unsigned int rvMaj = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR],0);
  125. const unsigned int rvMin = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR],0);
  126. const unsigned int rvRev = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION],0);
  127. const unsigned int rvPlatform = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_PLATFORM],0);
  128. const unsigned int rvArch = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE],0);
  129. const unsigned int rvVendor = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VENDOR],0);
  130. const std::string rvChannel(OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_CHANNEL],""));
  131. if (v == VERB_GET_LATEST) {
  132. if (_dist.size() > 0) {
  133. const nlohmann::json *latest = (const nlohmann::json *)0;
  134. const std::string expectedSigner = OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_EXPECT_SIGNED_BY],"");
  135. unsigned int bestVMaj = rvMaj;
  136. unsigned int bestVMin = rvMin;
  137. unsigned int bestVRev = rvRev;
  138. for(std::map< Array<uint8_t,16>,_D >::const_iterator d(_dist.begin());d!=_dist.end();++d) {
  139. if ((OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_PLATFORM],0) == rvPlatform)&&
  140. (OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE],0) == rvArch)&&
  141. (OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VENDOR],0) == rvVendor)&&
  142. (OSUtils::jsonString(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_CHANNEL],"") == rvChannel)&&
  143. (OSUtils::jsonString(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNED_BY],"") == expectedSigner)) {
  144. const unsigned int dvMaj = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR],0);
  145. const unsigned int dvMin = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR],0);
  146. const unsigned int dvRev = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION],0);
  147. if (Utils::compareVersion(dvMaj,dvMin,dvRev,bestVMaj,bestVMin,bestVRev) > 0) {
  148. latest = &(d->second.meta);
  149. bestVMaj = dvMaj;
  150. bestVMin = dvMin;
  151. bestVRev = dvRev;
  152. }
  153. }
  154. }
  155. if (latest) {
  156. std::string lj;
  157. lj.push_back((char)VERB_LATEST);
  158. lj.append(OSUtils::jsonDump(*latest));
  159. _node.sendUserMessage(origin,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,lj.data(),(unsigned int)lj.length());
  160. }
  161. } // else no reply, since we have nothing to distribute
  162. } else { // VERB_LATEST
  163. if ((origin == ZT_SOFTWARE_UPDATE_SERVICE)&&
  164. (Utils::compareVersion(rvMaj,rvMin,rvRev,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) > 0)&&
  165. (OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNED_BY],"") == ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY)) {
  166. const unsigned long len = (unsigned long)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIZE],0);
  167. const std::string hash = OSUtils::jsonBinFromHex(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH]);
  168. if ((len <= ZT_SOFTWARE_UPDATE_MAX_SIZE)&&(hash.length() >= 16)) {
  169. if (_latestMeta != req) {
  170. _latestMeta = req;
  171. _latestValid = false;
  172. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_META_FILENAME).c_str());
  173. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_BIN_FILENAME).c_str());
  174. _download = std::string();
  175. memcpy(_downloadHashPrefix.data,hash.data(),16);
  176. _downloadLength = len;
  177. }
  178. if ((_downloadLength > 0)&&(_download.length() < _downloadLength)) {
  179. Buffer<128> gd;
  180. gd.append((uint8_t)VERB_GET_DATA);
  181. gd.append(_downloadHashPrefix.data,16);
  182. gd.append((uint32_t)_download.length());
  183. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  184. //printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  185. }
  186. }
  187. }
  188. }
  189. }
  190. } break;
  191. case VERB_GET_DATA:
  192. if ((len >= 21)&&(_dist.size() > 0)) {
  193. unsigned long idx = (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 17) << 24;
  194. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 18) << 16;
  195. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 19) << 8;
  196. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 20);
  197. //printf("<< GET_DATA @%u from %.10llx for %s\n",(unsigned int)idx,origin,Utils::hex(reinterpret_cast<const uint8_t *>(data) + 1,16).c_str());
  198. std::map< Array<uint8_t,16>,_D >::iterator d(_dist.find(Array<uint8_t,16>(reinterpret_cast<const uint8_t *>(data) + 1)));
  199. if ((d != _dist.end())&&(idx < (unsigned long)d->second.bin.length())) {
  200. Buffer<ZT_SOFTWARE_UPDATE_CHUNK_SIZE + 128> buf;
  201. buf.append((uint8_t)VERB_DATA);
  202. buf.append(reinterpret_cast<const uint8_t *>(data) + 1,16);
  203. buf.append((uint32_t)idx);
  204. buf.append(d->second.bin.data() + idx,std::min((unsigned long)ZT_SOFTWARE_UPDATE_CHUNK_SIZE,(unsigned long)(d->second.bin.length() - idx)));
  205. _node.sendUserMessage(origin,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,buf.data(),buf.size());
  206. //printf(">> DATA @%u\n",(unsigned int)idx);
  207. }
  208. }
  209. break;
  210. case VERB_DATA:
  211. if ((len >= 21)&&(_downloadLength > 0)&&(!memcmp(_downloadHashPrefix.data,reinterpret_cast<const uint8_t *>(data) + 1,16))) {
  212. unsigned long idx = (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 17) << 24;
  213. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 18) << 16;
  214. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 19) << 8;
  215. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 20);
  216. //printf("<< DATA @%u / %u bytes (we now have %u bytes)\n",(unsigned int)idx,(unsigned int)(len - 21),(unsigned int)_download.length());
  217. if (idx == (unsigned long)_download.length()) {
  218. _download.append(reinterpret_cast<const char *>(data) + 21,len - 21);
  219. if (_download.length() < _downloadLength) {
  220. Buffer<128> gd;
  221. gd.append((uint8_t)VERB_GET_DATA);
  222. gd.append(_downloadHashPrefix.data,16);
  223. gd.append((uint32_t)_download.length());
  224. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  225. //printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  226. }
  227. }
  228. }
  229. break;
  230. default:
  231. break;
  232. }
  233. } catch ( ... ) {
  234. // Discard bad messages
  235. }
  236. }
  237. bool SoftwareUpdater::check(const uint64_t now)
  238. {
  239. if ((now - _lastCheckTime) >= ZT_SOFTWARE_UPDATE_CHECK_PERIOD) {
  240. _lastCheckTime = now;
  241. char tmp[512];
  242. const unsigned int len = Utils::snprintf(tmp,sizeof(tmp),
  243. "%c{\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR "\":%d,"
  244. "\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR "\":%d,"
  245. "\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION "\":%d,"
  246. "\"" ZT_SOFTWARE_UPDATE_JSON_EXPECT_SIGNED_BY "\":\"%s\","
  247. "\"" ZT_SOFTWARE_UPDATE_JSON_PLATFORM "\":%d,"
  248. "\"" ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE "\":%d,"
  249. "\"" ZT_SOFTWARE_UPDATE_JSON_VENDOR "\":%d,"
  250. "\"" ZT_SOFTWARE_UPDATE_JSON_CHANNEL "\":\"%s\"}",
  251. (char)VERB_GET_LATEST,
  252. ZEROTIER_ONE_VERSION_MAJOR,
  253. ZEROTIER_ONE_VERSION_MINOR,
  254. ZEROTIER_ONE_VERSION_REVISION,
  255. ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY,
  256. ZT_BUILD_PLATFORM,
  257. ZT_BUILD_ARCHITECTURE,
  258. (int)ZT_VENDOR_ZEROTIER,
  259. _channel.c_str());
  260. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,tmp,len);
  261. //printf(">> GET_LATEST\n");
  262. }
  263. if (_latestValid)
  264. return true;
  265. if (_downloadLength > 0) {
  266. if (_download.length() >= _downloadLength) {
  267. // This is the very important security validation part that makes sure
  268. // this software update doesn't have cooties.
  269. const std::string metaPath(_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_META_FILENAME);
  270. const std::string binPath(_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_BIN_FILENAME);
  271. try {
  272. // (1) Check the hash itself to make sure the image is basically okay
  273. uint8_t sha512[ZT_SHA512_DIGEST_LEN];
  274. SHA512::hash(sha512,_download.data(),(unsigned int)_download.length());
  275. if (Utils::hex(sha512,ZT_SHA512_DIGEST_LEN) == OSUtils::jsonString(_latestMeta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH],"~")) {
  276. // (2) Check signature by signing authority
  277. std::string sig(OSUtils::jsonBinFromHex(_latestMeta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNATURE]));
  278. if (Identity(ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY).verify(_download.data(),(unsigned int)_download.length(),sig.data(),(unsigned int)sig.length())) {
  279. // (3) Try to save file, and if so we are good.
  280. if (OSUtils::writeFile(metaPath.c_str(),OSUtils::jsonDump(_latestMeta)) && OSUtils::writeFile(binPath.c_str(),_download)) {
  281. OSUtils::lockDownFile(metaPath.c_str(),false);
  282. OSUtils::lockDownFile(binPath.c_str(),false);
  283. _latestValid = true;
  284. //printf("VALID UPDATE\n%s\n",OSUtils::jsonDump(_latestMeta).c_str());
  285. _download = std::string();
  286. _downloadLength = 0;
  287. return true;
  288. }
  289. }
  290. }
  291. } catch ( ... ) {} // any exception equals verification failure
  292. // If we get here, checks failed.
  293. //printf("INVALID UPDATE (!!!)\n%s\n",OSUtils::jsonDump(_latestMeta).c_str());
  294. OSUtils::rm(metaPath.c_str());
  295. OSUtils::rm(binPath.c_str());
  296. _latestMeta = nlohmann::json();
  297. _latestValid = false;
  298. _download = std::string();
  299. _downloadLength = 0;
  300. } else {
  301. Buffer<128> gd;
  302. gd.append((uint8_t)VERB_GET_DATA);
  303. gd.append(_downloadHashPrefix.data,16);
  304. gd.append((uint32_t)_download.length());
  305. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  306. //printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  307. }
  308. }
  309. return false;
  310. }
  311. void SoftwareUpdater::apply()
  312. {
  313. std::string updatePath(_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_BIN_FILENAME);
  314. if ((_latestMeta.is_object())&&(_latestValid)&&(OSUtils::fileExists(updatePath.c_str(),false))) {
  315. #ifdef __WINDOWS__
  316. std::string cmdArgs(OSUtils::jsonString(_latestMeta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_EXEC_ARGS],""));
  317. if (cmdArgs.length() > 0) {
  318. updatePath.push_back(' ');
  319. updatePath.append(cmdArgs);
  320. }
  321. STARTUPINFOA si;
  322. PROCESS_INFORMATION pi;
  323. memset(&si,0,sizeof(si));
  324. memset(&pi,0,sizeof(pi));
  325. CreateProcessA(NULL,updatePath.c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi);
  326. #else
  327. char *argv[256];
  328. unsigned long ac = 0;
  329. argv[ac++] = const_cast<char *>(updatePath.c_str());
  330. std::vector<std::string> argsSplit(OSUtils::split(OSUtils::jsonString(_latestMeta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_EXEC_ARGS],"").c_str()," ","\\","\""));
  331. for(std::vector<std::string>::iterator a(argsSplit.begin());a!=argsSplit.end();++a) {
  332. argv[ac] = const_cast<char *>(a->c_str());
  333. if (++ac == 255) break;
  334. }
  335. argv[ac] = (char *)0;
  336. chmod(updatePath.c_str(),0700);
  337. execv(updatePath.c_str(),argv);
  338. #endif
  339. }
  340. }
  341. } // namespace ZeroTier