SoftwareUpdater.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. #include "SoftwareUpdater.hpp"
  23. #include "../version.h"
  24. #include "../node/Constants.hpp"
  25. #include "../node/Utils.hpp"
  26. #include "../node/SHA512.hpp"
  27. #include "../node/Buffer.hpp"
  28. #include "../node/Node.hpp"
  29. #include "../osdep/OSUtils.hpp"
  30. #ifndef ZT_BUILD_ARCHITECTURE
  31. #define ZT_BUILD_ARCHITECTURE 0
  32. #endif
  33. #ifndef ZT_BUILD_PLATFORM
  34. #define ZT_BUILD_PLATFORM 0
  35. #endif
  36. namespace ZeroTier {
  37. #if 0
  38. #ifdef ZT_AUTO_UPDATE
  39. #define ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE (1024 * 1024 * 64)
  40. #define ZT_AUTO_UPDATE_CHECK_PERIOD 21600000
  41. class BackgroundSoftwareUpdateChecker
  42. {
  43. public:
  44. bool isValidSigningIdentity(const Identity &id)
  45. {
  46. return (
  47. /* 0001 - 0004 : obsolete, used in old versions */
  48. /* 0005 */ (id == Identity("ba57ea350e:0:9d4be6d7f86c5660d5ee1951a3d759aa6e12a84fc0c0b74639500f1dbc1a8c566622e7d1c531967ebceb1e9d1761342f88324a8ba520c93c35f92f35080fa23f"))
  49. /* 0006 */ ||(id == Identity("5067b21b83:0:8af477730f5055c48135b84bed6720a35bca4c0e34be4060a4c636288b1ec22217eb22709d610c66ed464c643130c51411bbb0294eef12fbe8ecc1a1e2c63a7a"))
  50. /* 0007 */ ||(id == Identity("4f5e97a8f1:0:57880d056d7baeb04bbc057d6f16e6cb41388570e87f01492fce882485f65a798648595610a3ad49885604e7fb1db2dd3c2c534b75e42c3c0b110ad07b4bb138"))
  51. /* 0008 */ ||(id == Identity("580bbb8e15:0:ad5ef31155bebc6bc413991992387e083fed26d699997ef76e7c947781edd47d1997161fa56ba337b1a2b44b129fd7c7197ce5185382f06011bc88d1363b4ddd"))
  52. );
  53. }
  54. void doUpdateCheck()
  55. {
  56. std::string url(OneService::autoUpdateUrl());
  57. if ((url.length() <= 7)||(url.substr(0,7) != "http://"))
  58. return;
  59. std::string httpHost;
  60. std::string httpPath;
  61. {
  62. std::size_t slashIdx = url.substr(7).find_first_of('/');
  63. if (slashIdx == std::string::npos) {
  64. httpHost = url.substr(7);
  65. httpPath = "/";
  66. } else {
  67. httpHost = url.substr(7,slashIdx);
  68. httpPath = url.substr(slashIdx + 7);
  69. }
  70. }
  71. if (httpHost.length() == 0)
  72. return;
  73. std::vector<InetAddress> ips(OSUtils::resolve(httpHost.c_str()));
  74. for(std::vector<InetAddress>::iterator ip(ips.begin());ip!=ips.end();++ip) {
  75. if (!ip->port())
  76. ip->setPort(80);
  77. std::string nfoPath = httpPath + "LATEST.nfo";
  78. std::map<std::string,std::string> requestHeaders,responseHeaders;
  79. std::string body;
  80. requestHeaders["Host"] = httpHost;
  81. unsigned int scode = Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),nfoPath.c_str(),requestHeaders,responseHeaders,body);
  82. //fprintf(stderr,"UPDATE %s %s %u %lu\n",ip->toString().c_str(),nfoPath.c_str(),scode,body.length());
  83. if ((scode == 200)&&(body.length() > 0)) {
  84. /* NFO fields:
  85. *
  86. * file=<filename>
  87. * signedBy=<signing identity>
  88. * ed25519=<ed25519 ECC signature of archive in hex>
  89. * vMajor=<major version>
  90. * vMinor=<minor version>
  91. * vRevision=<revision> */
  92. Dictionary<4096> nfo(body.c_str());
  93. char tmp[2048];
  94. if (nfo.get("vMajor",tmp,sizeof(tmp)) <= 0) return;
  95. const unsigned int vMajor = Utils::strToUInt(tmp);
  96. if (nfo.get("vMinor",tmp,sizeof(tmp)) <= 0) return;
  97. const unsigned int vMinor = Utils::strToUInt(tmp);
  98. if (nfo.get("vRevision",tmp,sizeof(tmp)) <= 0) return;
  99. const unsigned int vRevision = Utils::strToUInt(tmp);
  100. if (Utils::compareVersion(vMajor,vMinor,vRevision,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) <= 0) {
  101. //fprintf(stderr,"UPDATE %u.%u.%u is not newer than our version\n",vMajor,vMinor,vRevision);
  102. return;
  103. }
  104. if (nfo.get("signedBy",tmp,sizeof(tmp)) <= 0) return;
  105. Identity signedBy;
  106. if ((!signedBy.fromString(tmp))||(!isValidSigningIdentity(signedBy))) {
  107. //fprintf(stderr,"UPDATE invalid signedBy or not authorized signing identity.\n");
  108. return;
  109. }
  110. if (nfo.get("file",tmp,sizeof(tmp)) <= 0) return;
  111. std::string filePath(tmp);
  112. if ((!filePath.length())||(filePath.find("..") != std::string::npos))
  113. return;
  114. filePath = httpPath + filePath;
  115. std::string fileData;
  116. if (Http::GET(ZT_AUTO_UPDATE_MAX_HTTP_RESPONSE_SIZE,60000,reinterpret_cast<const struct sockaddr *>(&(*ip)),filePath.c_str(),requestHeaders,responseHeaders,fileData) != 200) {
  117. //fprintf(stderr,"UPDATE GET %s failed\n",filePath.c_str());
  118. return;
  119. }
  120. if (nfo.get("ed25519",tmp,sizeof(tmp)) <= 0) return;
  121. std::string ed25519(Utils::unhex(tmp));
  122. if ((ed25519.length() == 0)||(!signedBy.verify(fileData.data(),(unsigned int)fileData.length(),ed25519.data(),(unsigned int)ed25519.length()))) {
  123. //fprintf(stderr,"UPDATE %s failed signature check!\n",filePath.c_str());
  124. return;
  125. }
  126. /* --------------------------------------------------------------- */
  127. /* We made it! Begin OS-specific installation code. */
  128. #ifdef __APPLE__
  129. /* OSX version is in the form of a MacOSX .pkg file, so we will
  130. * launch installer (normally in /usr/sbin) to install it. It will
  131. * then turn around and shut down the service, update files, and
  132. * relaunch. */
  133. {
  134. char bashp[128],pkgp[128];
  135. Utils::snprintf(bashp,sizeof(bashp),"/tmp/ZeroTierOne-update-%u.%u.%u.sh",vMajor,vMinor,vRevision);
  136. Utils::snprintf(pkgp,sizeof(pkgp),"/tmp/ZeroTierOne-update-%u.%u.%u.pkg",vMajor,vMinor,vRevision);
  137. FILE *pkg = fopen(pkgp,"w");
  138. if ((!pkg)||(fwrite(fileData.data(),fileData.length(),1,pkg) != 1)) {
  139. fclose(pkg);
  140. unlink(bashp);
  141. unlink(pkgp);
  142. fprintf(stderr,"UPDATE error writing %s\n",pkgp);
  143. return;
  144. }
  145. fclose(pkg);
  146. FILE *bash = fopen(bashp,"w");
  147. if (!bash) {
  148. fclose(pkg);
  149. unlink(bashp);
  150. unlink(pkgp);
  151. fprintf(stderr,"UPDATE error writing %s\n",bashp);
  152. return;
  153. }
  154. fprintf(bash,
  155. "#!/bin/bash\n"
  156. "export PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin\n"
  157. "sleep 1\n"
  158. "installer -pkg \"%s\" -target /\n"
  159. "sleep 1\n"
  160. "rm -f \"%s\" \"%s\"\n"
  161. "exit 0\n",
  162. pkgp,
  163. pkgp,
  164. bashp);
  165. fclose(bash);
  166. long pid = (long)vfork();
  167. if (pid == 0) {
  168. setsid(); // detach from parent so that shell isn't killed when parent is killed
  169. signal(SIGHUP,SIG_IGN);
  170. signal(SIGTERM,SIG_IGN);
  171. signal(SIGQUIT,SIG_IGN);
  172. execl("/bin/bash","/bin/bash",bashp,(char *)0);
  173. exit(0);
  174. }
  175. }
  176. #endif // __APPLE__
  177. #ifdef __WINDOWS__
  178. /* Windows version comes in the form of .MSI package that
  179. * takes care of everything. */
  180. {
  181. char tempp[512],batp[512],msip[512],cmdline[512];
  182. if (GetTempPathA(sizeof(tempp),tempp) <= 0)
  183. return;
  184. CreateDirectoryA(tempp,(LPSECURITY_ATTRIBUTES)0);
  185. Utils::snprintf(batp,sizeof(batp),"%s\\ZeroTierOne-update-%u.%u.%u.bat",tempp,vMajor,vMinor,vRevision);
  186. Utils::snprintf(msip,sizeof(msip),"%s\\ZeroTierOne-update-%u.%u.%u.msi",tempp,vMajor,vMinor,vRevision);
  187. FILE *msi = fopen(msip,"wb");
  188. if ((!msi)||(fwrite(fileData.data(),(size_t)fileData.length(),1,msi) != 1)) {
  189. fclose(msi);
  190. return;
  191. }
  192. fclose(msi);
  193. FILE *bat = fopen(batp,"wb");
  194. if (!bat)
  195. return;
  196. fprintf(bat,
  197. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  198. "NET.EXE STOP \"ZeroTierOneService\"\r\n"
  199. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  200. "MSIEXEC.EXE /i \"%s\" /qn\r\n"
  201. "TIMEOUT.EXE /T 1 /NOBREAK\r\n"
  202. "NET.EXE START \"ZeroTierOneService\"\r\n"
  203. "DEL \"%s\"\r\n"
  204. "DEL \"%s\"\r\n",
  205. msip,
  206. msip,
  207. batp);
  208. fclose(bat);
  209. STARTUPINFOA si;
  210. PROCESS_INFORMATION pi;
  211. memset(&si,0,sizeof(si));
  212. memset(&pi,0,sizeof(pi));
  213. Utils::snprintf(cmdline,sizeof(cmdline),"CMD.EXE /c \"%s\"",batp);
  214. CreateProcessA(NULL,cmdline,NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi);
  215. }
  216. #endif // __WINDOWS__
  217. /* --------------------------------------------------------------- */
  218. return;
  219. } // else try to fetch from next IP address
  220. }
  221. }
  222. void threadMain()
  223. throw()
  224. {
  225. try {
  226. this->doUpdateCheck();
  227. } catch ( ... ) {}
  228. }
  229. };
  230. static BackgroundSoftwareUpdateChecker backgroundSoftwareUpdateChecker;
  231. #endif // ZT_AUTO_UPDATE
  232. #endif
  233. SoftwareUpdater::SoftwareUpdater(Node &node,const std::string &homePath) :
  234. _node(node),
  235. _lastCheckTime(0),
  236. _homePath(homePath),
  237. _channel(ZT_SOFTWARE_UPDATE_DEFAULT_CHANNEL),
  238. _latestValid(false),
  239. _downloadLength(0)
  240. {
  241. // Check for a cached newer update. If there's a cached update that is not newer, delete.
  242. }
  243. SoftwareUpdater::~SoftwareUpdater()
  244. {
  245. }
  246. void SoftwareUpdater::setUpdateDistribution(bool distribute)
  247. {
  248. _dist.clear();
  249. if (distribute) {
  250. std::string udd(_homePath + ZT_PATH_SEPARATOR_S + "update-dist.d");
  251. std::vector<std::string> ud(OSUtils::listDirectory(udd.c_str()));
  252. for(std::vector<std::string>::iterator u(ud.begin());u!=ud.end();++u) {
  253. // Each update has a companion .json file describing it. Other files are ignored.
  254. if ((u->length() > 5)&&(u->substr(u->length() - 5,5) == ".json")) {
  255. std::string buf;
  256. if (OSUtils::readFile((udd + ZT_PATH_SEPARATOR_S + *u).c_str(),buf)) {
  257. try {
  258. _D d;
  259. d.meta = OSUtils::jsonParse(buf);
  260. std::string metaHash = OSUtils::jsonBinFromHex(d.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH]);
  261. if ((metaHash.length() == ZT_SHA512_DIGEST_LEN)&&(OSUtils::readFile((udd + ZT_PATH_SEPARATOR_S + u->substr(0,u->length() - 5)).c_str(),d.bin))) {
  262. uint8_t sha512[ZT_SHA512_DIGEST_LEN];
  263. SHA512::hash(sha512,d.bin.data(),(unsigned int)d.bin.length());
  264. if (!memcmp(sha512,metaHash.data(),ZT_SHA512_DIGEST_LEN)) { // double check that hash in JSON is correct
  265. d.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIZE] = d.bin.length(); // override with correct value -- setting this in meta json is optional
  266. _dist[Array<uint8_t,16>(sha512)] = d;
  267. printf("update-dist.d: %s\n",u->c_str());
  268. }
  269. }
  270. } catch ( ... ) {} // ignore bad meta JSON, etc.
  271. }
  272. }
  273. }
  274. }
  275. }
  276. void SoftwareUpdater::handleSoftwareUpdateUserMessage(uint64_t origin,const void *data,unsigned int len)
  277. {
  278. if (!len) return;
  279. try {
  280. const MessageVerb v = (MessageVerb)reinterpret_cast<const uint8_t *>(data)[0];
  281. switch(v) {
  282. case VERB_GET_LATEST:
  283. case VERB_LATEST: {
  284. nlohmann::json req = OSUtils::jsonParse(std::string(reinterpret_cast<const char *>(data) + 1,len - 1));
  285. if (req.is_object()) {
  286. const unsigned int rvMaj = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR],0);
  287. const unsigned int rvMin = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR],0);
  288. const unsigned int rvRev = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION],0);
  289. const unsigned int rvPlatform = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_PLATFORM],0);
  290. const unsigned int rvArch = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE],0);
  291. const unsigned int rvVendor = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VENDOR],0);
  292. const std::string rvChannel(OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_CHANNEL],""));
  293. if (v == VERB_GET_LATEST) {
  294. if (_dist.size() > 0) {
  295. const nlohmann::json *latest = (const nlohmann::json *)0;
  296. const std::string expectedSigner = OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_EXPECT_SIGNED_BY],"");
  297. for(std::map< Array<uint8_t,16>,_D >::const_iterator d(_dist.begin());d!=_dist.end();++d) {
  298. if ((OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_PLATFORM],0) == rvPlatform)&&
  299. (OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE],0) == rvArch)&&
  300. (OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VENDOR],0) == rvVendor)&&
  301. (OSUtils::jsonString(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_CHANNEL],"") == rvChannel)&&
  302. (OSUtils::jsonString(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNED_BY],"") == expectedSigner)) {
  303. const unsigned int dvMaj = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR],0);
  304. const unsigned int dvMin = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR],0);
  305. const unsigned int dvRev = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION],0);
  306. if (Utils::compareVersion(dvMaj,dvMin,dvRev,rvMaj,rvMin,rvRev) > 0) {
  307. latest = &(d->second.meta);
  308. }
  309. }
  310. }
  311. if (latest) {
  312. std::string lj;
  313. lj.push_back((char)VERB_LATEST);
  314. lj.append(OSUtils::jsonDump(*latest));
  315. _node.sendUserMessage(origin,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,lj.data(),(unsigned int)lj.length());
  316. }
  317. } // else no reply, since we have nothing to distribute
  318. } else { // VERB_LATEST
  319. if ((origin == ZT_SOFTWARE_UPDATE_SERVICE)&&
  320. (Utils::compareVersion(rvMaj,rvMin,rvRev,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) > 0)&&
  321. (OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNED_BY],"") == ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY)) {
  322. const unsigned long len = (unsigned long)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIZE],0);
  323. const std::string hash = OSUtils::jsonBinFromHex(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH]);
  324. if ((len <= ZT_SOFTWARE_UPDATE_MAX_SIZE)&&(hash.length() >= 16)) {
  325. if (_latestMeta != req) {
  326. _latestMeta = req;
  327. _latestValid = false;
  328. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S + ZT_SOFTWARE_UPDATE_META_FILENAME).c_str());
  329. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S + ZT_SOFTWARE_UPDATE_BIN_FILENAME).c_str());
  330. _download = std::string();
  331. memcpy(_downloadHashPrefix.data,hash.data(),16);
  332. _downloadLength = len;
  333. }
  334. if ((_downloadLength > 0)&&(_download.length() < _downloadLength)) {
  335. Buffer<128> gd;
  336. gd.append((uint8_t)VERB_GET_DATA);
  337. gd.append(_downloadHashPrefix.data,16);
  338. gd.append((uint32_t)_download.length());
  339. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  340. printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  341. }
  342. }
  343. }
  344. }
  345. }
  346. } break;
  347. case VERB_GET_DATA:
  348. if ((len >= 21)&&(_dist.size() > 0)) {
  349. unsigned long idx = (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 17) << 24;
  350. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 18) << 16;
  351. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 19) << 8;
  352. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 20);
  353. 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());
  354. std::map< Array<uint8_t,16>,_D >::iterator d(_dist.find(Array<uint8_t,16>(reinterpret_cast<const uint8_t *>(data) + 1)));
  355. if ((d != _dist.end())&&(idx < (unsigned long)d->second.bin.length())) {
  356. Buffer<ZT_SOFTWARE_UPDATE_CHUNK_SIZE + 128> buf;
  357. buf.append((uint8_t)VERB_DATA);
  358. buf.append(reinterpret_cast<const uint8_t *>(data) + 1,16);
  359. buf.append((uint32_t)idx);
  360. buf.append(d->second.bin.data() + idx,std::min((unsigned long)ZT_SOFTWARE_UPDATE_CHUNK_SIZE,(unsigned long)(d->second.bin.length() - idx)));
  361. _node.sendUserMessage(origin,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,buf.data(),buf.size());
  362. printf(">> DATA @%u\n",(unsigned int)idx);
  363. }
  364. }
  365. break;
  366. case VERB_DATA:
  367. if ((len >= 21)&&(_downloadLength > 0)&&(!memcmp(_downloadHashPrefix.data,reinterpret_cast<const uint8_t *>(data) + 1,16))) {
  368. unsigned long idx = (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 17) << 24;
  369. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 18) << 16;
  370. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 19) << 8;
  371. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 20);
  372. printf("<< DATA @%u / %u bytes (we now have %u bytes)\n",(unsigned int)idx,(unsigned int)(len - 21),(unsigned int)_download.length());
  373. if (idx == (unsigned long)_download.length()) {
  374. _download.append(reinterpret_cast<const char *>(data) + 21,len - 21);
  375. if (_download.length() < _downloadLength) {
  376. Buffer<128> gd;
  377. gd.append((uint8_t)VERB_GET_DATA);
  378. gd.append(_downloadHashPrefix.data,16);
  379. gd.append((uint32_t)_download.length());
  380. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  381. printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  382. }
  383. }
  384. }
  385. break;
  386. default:
  387. break;
  388. }
  389. } catch ( ... ) {
  390. // Discard bad messages
  391. }
  392. }
  393. bool SoftwareUpdater::check(const uint64_t now)
  394. {
  395. if ((now - _lastCheckTime) >= ZT_SOFTWARE_UPDATE_CHECK_PERIOD) {
  396. _lastCheckTime = now;
  397. char tmp[512];
  398. const unsigned int len = Utils::snprintf(tmp,sizeof(tmp),
  399. "%c{\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR "\":%d,"
  400. "\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR "\":%d,"
  401. "\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION "\":%d,"
  402. "\"" ZT_SOFTWARE_UPDATE_JSON_EXPECT_SIGNED_BY "\":\"%s\","
  403. "\"" ZT_SOFTWARE_UPDATE_JSON_PLATFORM "\":%d,"
  404. "\"" ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE "\":%d,"
  405. "\"" ZT_SOFTWARE_UPDATE_JSON_VENDOR "\":%d,"
  406. "\"" ZT_SOFTWARE_UPDATE_JSON_CHANNEL "\":\"%s\"}",
  407. (char)VERB_GET_LATEST,
  408. ZEROTIER_ONE_VERSION_MAJOR,
  409. ZEROTIER_ONE_VERSION_MINOR,
  410. ZEROTIER_ONE_VERSION_REVISION,
  411. ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY,
  412. ZT_BUILD_PLATFORM,
  413. ZT_BUILD_ARCHITECTURE,
  414. (int)ZT_VENDOR_ZEROTIER,
  415. _channel.c_str());
  416. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,tmp,len);
  417. printf(">> GET_LATEST\n");
  418. }
  419. if (_latestValid)
  420. return true;
  421. if (_downloadLength > 0) {
  422. if (_download.length() >= _downloadLength) {
  423. // This is the very important security validation part that makes sure
  424. // this software update doesn't have cooties.
  425. try {
  426. // (1) Check the hash itself to make sure the image is basically okay
  427. uint8_t sha512[ZT_SHA512_DIGEST_LEN];
  428. SHA512::hash(sha512,_download.data(),(unsigned int)_download.length());
  429. if (Utils::hex(sha512,ZT_SHA512_DIGEST_LEN) == OSUtils::jsonString(_latestMeta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH],"~")) {
  430. // (2) Check signature by signing authority
  431. std::string sig(OSUtils::jsonBinFromHex(_latestMeta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNATURE]));
  432. if (Identity(ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY).verify(_download.data(),(unsigned int)_download.length(),sig.data(),(unsigned int)sig.length())) {
  433. // If we passed both of these, the update is good!
  434. if (OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + ZT_SOFTWARE_UPDATE_META_FILENAME).c_str(),OSUtils::jsonDump(_latestMeta)) && OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + ZT_SOFTWARE_UPDATE_BIN_FILENAME).c_str(),_download)) {
  435. _latestValid = true;
  436. printf("VALID UPDATE\n%s\n",OSUtils::jsonDump(_latestMeta).c_str());
  437. } else {
  438. _latestMeta = nlohmann::json();
  439. _latestValid = false;
  440. }
  441. _download = std::string();
  442. _downloadLength = 0;
  443. return _latestValid;
  444. }
  445. }
  446. } catch ( ... ) {} // any exception equals verification failure
  447. // If we get here, checks failed.
  448. printf("INVALID UPDATE (!!!)\n%s\n",OSUtils::jsonDump(_latestMeta).c_str());
  449. _latestMeta = nlohmann::json();
  450. _latestValid = false;
  451. _download = std::string();
  452. _downloadLength = 0;
  453. } else {
  454. Buffer<128> gd;
  455. gd.append((uint8_t)VERB_GET_DATA);
  456. gd.append(_downloadHashPrefix.data,16);
  457. gd.append((uint32_t)_download.length());
  458. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  459. printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  460. }
  461. }
  462. return false;
  463. }
  464. void SoftwareUpdater::apply()
  465. {
  466. }
  467. } // namespace ZeroTier