SoftwareUpdater.cpp 20 KB

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