SoftwareUpdater.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 or looks bad, delete.
  242. try {
  243. std::string buf;
  244. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_META_FILENAME).c_str(),buf)) {
  245. nlohmann::json meta = OSUtils::jsonParse(buf);
  246. buf = std::string();
  247. const unsigned int rvMaj = (unsigned int)OSUtils::jsonInt(meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR],0);
  248. const unsigned int rvMin = (unsigned int)OSUtils::jsonInt(meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR],0);
  249. const unsigned int rvRev = (unsigned int)OSUtils::jsonInt(meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION],0);
  250. 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))) {
  251. if ((uint64_t)buf.length() == OSUtils::jsonInt(meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIZE],0)) {
  252. _latestMeta = meta;
  253. _latestValid = true;
  254. printf("CACHED UPDATE IS NEWER AND LOOKS GOOD\n");
  255. }
  256. }
  257. }
  258. } catch ( ... ) {} // exceptions indicate invalid cached update
  259. if (!_latestValid) {
  260. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_META_FILENAME).c_str());
  261. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_BIN_FILENAME).c_str());
  262. }
  263. }
  264. SoftwareUpdater::~SoftwareUpdater()
  265. {
  266. }
  267. void SoftwareUpdater::setUpdateDistribution(bool distribute)
  268. {
  269. _dist.clear();
  270. if (distribute) {
  271. std::string udd(_homePath + ZT_PATH_SEPARATOR_S + "update-dist.d");
  272. std::vector<std::string> ud(OSUtils::listDirectory(udd.c_str()));
  273. for(std::vector<std::string>::iterator u(ud.begin());u!=ud.end();++u) {
  274. // Each update has a companion .json file describing it. Other files are ignored.
  275. if ((u->length() > 5)&&(u->substr(u->length() - 5,5) == ".json")) {
  276. std::string buf;
  277. if (OSUtils::readFile((udd + ZT_PATH_SEPARATOR_S + *u).c_str(),buf)) {
  278. try {
  279. _D d;
  280. d.meta = OSUtils::jsonParse(buf);
  281. std::string metaHash = OSUtils::jsonBinFromHex(d.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH]);
  282. if ((metaHash.length() == ZT_SHA512_DIGEST_LEN)&&(OSUtils::readFile((udd + ZT_PATH_SEPARATOR_S + u->substr(0,u->length() - 5)).c_str(),d.bin))) {
  283. uint8_t sha512[ZT_SHA512_DIGEST_LEN];
  284. SHA512::hash(sha512,d.bin.data(),(unsigned int)d.bin.length());
  285. if (!memcmp(sha512,metaHash.data(),ZT_SHA512_DIGEST_LEN)) { // double check that hash in JSON is correct
  286. d.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIZE] = d.bin.length(); // override with correct value -- setting this in meta json is optional
  287. _dist[Array<uint8_t,16>(sha512)] = d;
  288. printf("update-dist.d: %s\n",u->c_str());
  289. }
  290. }
  291. } catch ( ... ) {} // ignore bad meta JSON, etc.
  292. }
  293. }
  294. }
  295. }
  296. }
  297. void SoftwareUpdater::handleSoftwareUpdateUserMessage(uint64_t origin,const void *data,unsigned int len)
  298. {
  299. if (!len) return;
  300. try {
  301. const MessageVerb v = (MessageVerb)reinterpret_cast<const uint8_t *>(data)[0];
  302. switch(v) {
  303. case VERB_GET_LATEST:
  304. case VERB_LATEST: {
  305. nlohmann::json req = OSUtils::jsonParse(std::string(reinterpret_cast<const char *>(data) + 1,len - 1));
  306. if (req.is_object()) {
  307. const unsigned int rvMaj = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR],0);
  308. const unsigned int rvMin = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR],0);
  309. const unsigned int rvRev = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION],0);
  310. const unsigned int rvPlatform = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_PLATFORM],0);
  311. const unsigned int rvArch = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE],0);
  312. const unsigned int rvVendor = (unsigned int)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_VENDOR],0);
  313. const std::string rvChannel(OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_CHANNEL],""));
  314. if (v == VERB_GET_LATEST) {
  315. if (_dist.size() > 0) {
  316. const nlohmann::json *latest = (const nlohmann::json *)0;
  317. const std::string expectedSigner = OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_EXPECT_SIGNED_BY],"");
  318. for(std::map< Array<uint8_t,16>,_D >::const_iterator d(_dist.begin());d!=_dist.end();++d) {
  319. if ((OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_PLATFORM],0) == rvPlatform)&&
  320. (OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE],0) == rvArch)&&
  321. (OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VENDOR],0) == rvVendor)&&
  322. (OSUtils::jsonString(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_CHANNEL],"") == rvChannel)&&
  323. (OSUtils::jsonString(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNED_BY],"") == expectedSigner)) {
  324. const unsigned int dvMaj = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR],0);
  325. const unsigned int dvMin = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR],0);
  326. const unsigned int dvRev = (unsigned int)OSUtils::jsonInt(d->second.meta[ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION],0);
  327. if (Utils::compareVersion(dvMaj,dvMin,dvRev,rvMaj,rvMin,rvRev) > 0) {
  328. latest = &(d->second.meta);
  329. }
  330. }
  331. }
  332. if (latest) {
  333. std::string lj;
  334. lj.push_back((char)VERB_LATEST);
  335. lj.append(OSUtils::jsonDump(*latest));
  336. _node.sendUserMessage(origin,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,lj.data(),(unsigned int)lj.length());
  337. }
  338. } // else no reply, since we have nothing to distribute
  339. } else { // VERB_LATEST
  340. if ((origin == ZT_SOFTWARE_UPDATE_SERVICE)&&
  341. (Utils::compareVersion(rvMaj,rvMin,rvRev,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION) > 0)&&
  342. (OSUtils::jsonString(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNED_BY],"") == ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY)) {
  343. const unsigned long len = (unsigned long)OSUtils::jsonInt(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIZE],0);
  344. const std::string hash = OSUtils::jsonBinFromHex(req[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH]);
  345. if ((len <= ZT_SOFTWARE_UPDATE_MAX_SIZE)&&(hash.length() >= 16)) {
  346. if (_latestMeta != req) {
  347. _latestMeta = req;
  348. _latestValid = false;
  349. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_META_FILENAME).c_str());
  350. OSUtils::rm((_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_BIN_FILENAME).c_str());
  351. _download = std::string();
  352. memcpy(_downloadHashPrefix.data,hash.data(),16);
  353. _downloadLength = len;
  354. }
  355. if ((_downloadLength > 0)&&(_download.length() < _downloadLength)) {
  356. Buffer<128> gd;
  357. gd.append((uint8_t)VERB_GET_DATA);
  358. gd.append(_downloadHashPrefix.data,16);
  359. gd.append((uint32_t)_download.length());
  360. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  361. printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  362. }
  363. }
  364. }
  365. }
  366. }
  367. } break;
  368. case VERB_GET_DATA:
  369. if ((len >= 21)&&(_dist.size() > 0)) {
  370. unsigned long idx = (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 17) << 24;
  371. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 18) << 16;
  372. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 19) << 8;
  373. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 20);
  374. 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());
  375. std::map< Array<uint8_t,16>,_D >::iterator d(_dist.find(Array<uint8_t,16>(reinterpret_cast<const uint8_t *>(data) + 1)));
  376. if ((d != _dist.end())&&(idx < (unsigned long)d->second.bin.length())) {
  377. Buffer<ZT_SOFTWARE_UPDATE_CHUNK_SIZE + 128> buf;
  378. buf.append((uint8_t)VERB_DATA);
  379. buf.append(reinterpret_cast<const uint8_t *>(data) + 1,16);
  380. buf.append((uint32_t)idx);
  381. buf.append(d->second.bin.data() + idx,std::min((unsigned long)ZT_SOFTWARE_UPDATE_CHUNK_SIZE,(unsigned long)(d->second.bin.length() - idx)));
  382. _node.sendUserMessage(origin,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,buf.data(),buf.size());
  383. printf(">> DATA @%u\n",(unsigned int)idx);
  384. }
  385. }
  386. break;
  387. case VERB_DATA:
  388. if ((len >= 21)&&(_downloadLength > 0)&&(!memcmp(_downloadHashPrefix.data,reinterpret_cast<const uint8_t *>(data) + 1,16))) {
  389. unsigned long idx = (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 17) << 24;
  390. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 18) << 16;
  391. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 19) << 8;
  392. idx |= (unsigned long)*(reinterpret_cast<const uint8_t *>(data) + 20);
  393. printf("<< DATA @%u / %u bytes (we now have %u bytes)\n",(unsigned int)idx,(unsigned int)(len - 21),(unsigned int)_download.length());
  394. if (idx == (unsigned long)_download.length()) {
  395. _download.append(reinterpret_cast<const char *>(data) + 21,len - 21);
  396. if (_download.length() < _downloadLength) {
  397. Buffer<128> gd;
  398. gd.append((uint8_t)VERB_GET_DATA);
  399. gd.append(_downloadHashPrefix.data,16);
  400. gd.append((uint32_t)_download.length());
  401. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  402. printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  403. }
  404. }
  405. }
  406. break;
  407. default:
  408. break;
  409. }
  410. } catch ( ... ) {
  411. // Discard bad messages
  412. }
  413. }
  414. bool SoftwareUpdater::check(const uint64_t now)
  415. {
  416. if ((now - _lastCheckTime) >= ZT_SOFTWARE_UPDATE_CHECK_PERIOD) {
  417. _lastCheckTime = now;
  418. char tmp[512];
  419. const unsigned int len = Utils::snprintf(tmp,sizeof(tmp),
  420. "%c{\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_MAJOR "\":%d,"
  421. "\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_MINOR "\":%d,"
  422. "\"" ZT_SOFTWARE_UPDATE_JSON_VERSION_REVISION "\":%d,"
  423. "\"" ZT_SOFTWARE_UPDATE_JSON_EXPECT_SIGNED_BY "\":\"%s\","
  424. "\"" ZT_SOFTWARE_UPDATE_JSON_PLATFORM "\":%d,"
  425. "\"" ZT_SOFTWARE_UPDATE_JSON_ARCHITECTURE "\":%d,"
  426. "\"" ZT_SOFTWARE_UPDATE_JSON_VENDOR "\":%d,"
  427. "\"" ZT_SOFTWARE_UPDATE_JSON_CHANNEL "\":\"%s\"}",
  428. (char)VERB_GET_LATEST,
  429. ZEROTIER_ONE_VERSION_MAJOR,
  430. ZEROTIER_ONE_VERSION_MINOR,
  431. ZEROTIER_ONE_VERSION_REVISION,
  432. ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY,
  433. ZT_BUILD_PLATFORM,
  434. ZT_BUILD_ARCHITECTURE,
  435. (int)ZT_VENDOR_ZEROTIER,
  436. _channel.c_str());
  437. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,tmp,len);
  438. printf(">> GET_LATEST\n");
  439. }
  440. if (_latestValid)
  441. return true;
  442. if (_downloadLength > 0) {
  443. if (_download.length() >= _downloadLength) {
  444. // This is the very important security validation part that makes sure
  445. // this software update doesn't have cooties.
  446. const std::string metaPath(_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_META_FILENAME);
  447. const std::string binPath(_homePath + ZT_PATH_SEPARATOR_S ZT_SOFTWARE_UPDATE_BIN_FILENAME);
  448. try {
  449. // (1) Check the hash itself to make sure the image is basically okay
  450. uint8_t sha512[ZT_SHA512_DIGEST_LEN];
  451. SHA512::hash(sha512,_download.data(),(unsigned int)_download.length());
  452. if (Utils::hex(sha512,ZT_SHA512_DIGEST_LEN) == OSUtils::jsonString(_latestMeta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_HASH],"~")) {
  453. // (2) Check signature by signing authority
  454. std::string sig(OSUtils::jsonBinFromHex(_latestMeta[ZT_SOFTWARE_UPDATE_JSON_UPDATE_SIGNATURE]));
  455. if (Identity(ZT_SOFTWARE_UPDATE_SIGNING_AUTHORITY).verify(_download.data(),(unsigned int)_download.length(),sig.data(),(unsigned int)sig.length())) {
  456. // (3) Try to save file, and if so we are good.
  457. if (OSUtils::writeFile(metaPath.c_str(),OSUtils::jsonDump(_latestMeta)) && OSUtils::writeFile(binPath.c_str(),_download)) {
  458. OSUtils::lockDownFile(metaPath.c_str(),false);
  459. OSUtils::lockDownFile(binPath.c_str(),false);
  460. _latestValid = true;
  461. printf("VALID UPDATE\n%s\n",OSUtils::jsonDump(_latestMeta).c_str());
  462. _download = std::string();
  463. _downloadLength = 0;
  464. return true;
  465. }
  466. }
  467. }
  468. } catch ( ... ) {} // any exception equals verification failure
  469. // If we get here, checks failed.
  470. printf("INVALID UPDATE (!!!)\n%s\n",OSUtils::jsonDump(_latestMeta).c_str());
  471. OSUtils::rm(metaPath.c_str());
  472. OSUtils::rm(binPath.c_str());
  473. _latestMeta = nlohmann::json();
  474. _latestValid = false;
  475. _download = std::string();
  476. _downloadLength = 0;
  477. } else {
  478. Buffer<128> gd;
  479. gd.append((uint8_t)VERB_GET_DATA);
  480. gd.append(_downloadHashPrefix.data,16);
  481. gd.append((uint32_t)_download.length());
  482. _node.sendUserMessage(ZT_SOFTWARE_UPDATE_SERVICE,ZT_SOFTWARE_UPDATE_USER_MESSAGE_TYPE,gd.data(),gd.size());
  483. printf(">> GET_DATA @%u\n",(unsigned int)_download.length());
  484. }
  485. }
  486. return false;
  487. }
  488. void SoftwareUpdater::apply()
  489. {
  490. }
  491. } // namespace ZeroTier