IncomingPacket.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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 <string.h>
  20. #include <stdlib.h>
  21. #include "../version.h"
  22. #include "../include/ZeroTierOne.h"
  23. #include "Constants.hpp"
  24. #include "RuntimeEnvironment.hpp"
  25. #include "IncomingPacket.hpp"
  26. #include "Topology.hpp"
  27. #include "Switch.hpp"
  28. #include "Peer.hpp"
  29. #include "NetworkController.hpp"
  30. #include "SelfAwareness.hpp"
  31. #include "Salsa20.hpp"
  32. #include "SHA512.hpp"
  33. #include "World.hpp"
  34. #include "Cluster.hpp"
  35. #include "Node.hpp"
  36. #include "DeferredPackets.hpp"
  37. namespace ZeroTier {
  38. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,bool deferred)
  39. {
  40. const Address sourceAddress(source());
  41. try {
  42. if ((cipher() == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  43. // Unencrypted HELLOs require some potentially expensive verification, so
  44. // do this in the background if background processing is enabled.
  45. if ((RR->dpEnabled > 0)&&(!deferred)) {
  46. RR->dp->enqueue(this);
  47. return true; // 'handled' via deferring to background thread(s)
  48. } else {
  49. // A null pointer for peer to _doHELLO() tells it to run its own
  50. // special internal authentication logic. This is done for unencrypted
  51. // HELLOs to learn new identities, etc.
  52. SharedPtr<Peer> tmp;
  53. return _doHELLO(RR,tmp);
  54. }
  55. }
  56. SharedPtr<Peer> peer(RR->topology->getPeer(sourceAddress));
  57. if (peer) {
  58. if (!dearmor(peer->key())) {
  59. TRACE("dropped packet from %s(%s), MAC authentication failed (size: %u)",peer->address().toString().c_str(),_remoteAddress.toString().c_str(),size());
  60. return true;
  61. }
  62. if (!uncompress()) {
  63. TRACE("dropped packet from %s(%s), compressed data invalid",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  64. return true;
  65. }
  66. //TRACE("<< %s from %s(%s)",Packet::verbString(v),sourceAddress.toString().c_str(),_remoteAddress.toString().c_str());
  67. const Packet::Verb v = verb();
  68. switch(v) {
  69. //case Packet::VERB_NOP:
  70. default: // ignore unknown verbs, but if they pass auth check they are "received"
  71. peer->received(_localAddress,_remoteAddress,hops(),packetId(),v,0,Packet::VERB_NOP);
  72. return true;
  73. case Packet::VERB_HELLO: return _doHELLO(RR,peer);
  74. case Packet::VERB_ERROR: return _doERROR(RR,peer);
  75. case Packet::VERB_OK: return _doOK(RR,peer);
  76. case Packet::VERB_WHOIS: return _doWHOIS(RR,peer);
  77. case Packet::VERB_RENDEZVOUS: return _doRENDEZVOUS(RR,peer);
  78. case Packet::VERB_FRAME: return _doFRAME(RR,peer);
  79. case Packet::VERB_EXT_FRAME: return _doEXT_FRAME(RR,peer);
  80. case Packet::VERB_ECHO: return _doECHO(RR,peer);
  81. case Packet::VERB_MULTICAST_LIKE: return _doMULTICAST_LIKE(RR,peer);
  82. case Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE: return _doNETWORK_MEMBERSHIP_CERTIFICATE(RR,peer);
  83. case Packet::VERB_NETWORK_CONFIG_REQUEST: return _doNETWORK_CONFIG_REQUEST(RR,peer);
  84. case Packet::VERB_NETWORK_CONFIG_REFRESH: return _doNETWORK_CONFIG_REFRESH(RR,peer);
  85. case Packet::VERB_MULTICAST_GATHER: return _doMULTICAST_GATHER(RR,peer);
  86. case Packet::VERB_MULTICAST_FRAME: return _doMULTICAST_FRAME(RR,peer);
  87. case Packet::VERB_PUSH_DIRECT_PATHS: return _doPUSH_DIRECT_PATHS(RR,peer);
  88. case Packet::VERB_CIRCUIT_TEST: return _doCIRCUIT_TEST(RR,peer);
  89. case Packet::VERB_CIRCUIT_TEST_REPORT: return _doCIRCUIT_TEST_REPORT(RR,peer);
  90. case Packet::VERB_REQUEST_PROOF_OF_WORK: return _doREQUEST_PROOF_OF_WORK(RR,peer);
  91. }
  92. } else {
  93. RR->sw->requestWhois(sourceAddress);
  94. return false;
  95. }
  96. } catch ( ... ) {
  97. // Exceptions are more informatively caught in _do...() handlers but
  98. // this outer try/catch will catch anything else odd.
  99. TRACE("dropped ??? from %s(%s): unexpected exception in tryDecode()",sourceAddress.toString().c_str(),_remoteAddress.toString().c_str());
  100. return true;
  101. }
  102. }
  103. bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  104. {
  105. try {
  106. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  107. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  108. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  109. //TRACE("ERROR %s from %s(%s) in-re %s",Packet::errorString(errorCode),peer->address().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  110. switch(errorCode) {
  111. case Packet::ERROR_OBJ_NOT_FOUND:
  112. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  113. SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  114. if ((network)&&(network->controller() == peer->address()))
  115. network->setNotFound();
  116. }
  117. break;
  118. case Packet::ERROR_UNSUPPORTED_OPERATION:
  119. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  120. SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  121. if ((network)&&(network->controller() == peer->address()))
  122. network->setNotFound();
  123. }
  124. break;
  125. case Packet::ERROR_IDENTITY_COLLISION:
  126. if (RR->topology->isRoot(peer->identity()))
  127. RR->node->postEvent(ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION);
  128. break;
  129. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  130. /* Note: certificates are public so it's safe to push them to anyone
  131. * who asks. We won't communicate unless we also get a certificate
  132. * from the remote that agrees. */
  133. SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  134. if (network) {
  135. SharedPtr<NetworkConfig> nconf(network->config2());
  136. if (nconf) {
  137. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  138. nconf->com().serialize(outp);
  139. outp.armor(peer->key(),true);
  140. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  141. }
  142. }
  143. } break;
  144. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  145. SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  146. if ((network)&&(network->controller() == peer->address()))
  147. network->setAccessDenied();
  148. } break;
  149. case Packet::ERROR_UNWANTED_MULTICAST: {
  150. uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  151. MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8,6),6),at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  152. TRACE("%.16llx: peer %s unsubscrubed from multicast group %s",nwid,peer->address().toString().c_str(),mg.toString().c_str());
  153. RR->mc->remove(nwid,mg,peer->address());
  154. } break;
  155. default: break;
  156. }
  157. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_ERROR,inRePacketId,inReVerb);
  158. } catch ( ... ) {
  159. TRACE("dropped ERROR from %s(%s): unexpected exception",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  160. }
  161. return true;
  162. }
  163. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,SharedPtr<Peer> &peer)
  164. {
  165. /* Note: this is the only packet ever sent in the clear, and it's also
  166. * the only packet that we authenticate via a different path. Authentication
  167. * occurs here and is based on the validity of the identity and the
  168. * integrity of the packet's MAC, but it must be done after we check
  169. * the identity since HELLO is a mechanism for learning new identities
  170. * in the first place. */
  171. try {
  172. const uint64_t pid = packetId();
  173. const Address fromAddress(source());
  174. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  175. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  176. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  177. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  178. const uint64_t timestamp = at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  179. Identity id;
  180. InetAddress externalSurfaceAddress;
  181. uint64_t worldId = ZT_WORLD_ID_NULL;
  182. uint64_t worldTimestamp = 0;
  183. {
  184. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  185. if (ptr < size()) // ZeroTier One < 1.0.3 did not include physical destination address info
  186. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  187. if ((ptr + 16) <= size()) { // older versions also did not include World IDs or timestamps
  188. worldId = at<uint64_t>(ptr); ptr += 8;
  189. worldTimestamp = at<uint64_t>(ptr);
  190. }
  191. }
  192. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  193. TRACE("dropped HELLO from %s(%s): protocol version too old",id.address().toString().c_str(),_remoteAddress.toString().c_str());
  194. return true;
  195. }
  196. if (fromAddress != id.address()) {
  197. TRACE("dropped HELLO from %s(%s): identity not for sending address",fromAddress.toString().c_str(),_remoteAddress.toString().c_str());
  198. return true;
  199. }
  200. if (!peer) { // peer == NULL is the normal case here
  201. peer = RR->topology->getPeer(id.address());
  202. if (peer) {
  203. // We already have an identity with this address -- check for collisions
  204. if (peer->identity() != id) {
  205. // Identity is different from the one we already have -- address collision
  206. unsigned char key[ZT_PEER_SECRET_KEY_LENGTH];
  207. if (RR->identity.agree(id,key,ZT_PEER_SECRET_KEY_LENGTH)) {
  208. if (dearmor(key)) { // ensure packet is authentic, otherwise drop
  209. TRACE("rejected HELLO from %s(%s): address already claimed",id.address().toString().c_str(),_remoteAddress.toString().c_str());
  210. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  211. outp.append((unsigned char)Packet::VERB_HELLO);
  212. outp.append((uint64_t)pid);
  213. outp.append((unsigned char)Packet::ERROR_IDENTITY_COLLISION);
  214. outp.armor(key,true);
  215. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  216. } else {
  217. TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str());
  218. }
  219. } else {
  220. TRACE("rejected HELLO from %s(%s): key agreement failed",id.address().toString().c_str(),_remoteAddress.toString().c_str());
  221. }
  222. return true;
  223. } else {
  224. // Identity is the same as the one we already have -- check packet integrity
  225. if (!dearmor(peer->key())) {
  226. TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str());
  227. return true;
  228. }
  229. // Continue at // VALID
  230. }
  231. } else {
  232. // We don't already have an identity with this address -- validate and learn it
  233. // Check identity proof of work
  234. if (!id.locallyValidate()) {
  235. TRACE("dropped HELLO from %s(%s): identity invalid",id.address().toString().c_str(),_remoteAddress.toString().c_str());
  236. return true;
  237. }
  238. // Check packet integrity and authentication
  239. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  240. if (!dearmor(newPeer->key())) {
  241. TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_remoteAddress.toString().c_str());
  242. return true;
  243. }
  244. peer = RR->topology->addPeer(newPeer);
  245. // Continue at // VALID
  246. }
  247. // VALID -- if we made it here, packet passed identity and authenticity checks!
  248. }
  249. if (externalSurfaceAddress)
  250. RR->sa->iam(id.address(),_localAddress,_remoteAddress,externalSurfaceAddress,RR->topology->isRoot(id),RR->node->now());
  251. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  252. outp.append((unsigned char)Packet::VERB_HELLO);
  253. outp.append((uint64_t)pid);
  254. outp.append((uint64_t)timestamp);
  255. outp.append((unsigned char)ZT_PROTO_VERSION);
  256. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  257. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  258. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  259. if (protoVersion >= 5) {
  260. _remoteAddress.serialize(outp);
  261. } else {
  262. /* LEGACY COMPATIBILITY HACK:
  263. *
  264. * For a while now (since 1.0.3), ZeroTier has recognized changes in
  265. * its network environment empirically by examining its external network
  266. * address as reported by trusted peers. In versions prior to 1.1.0
  267. * (protocol version < 5), they did this by saving a snapshot of this
  268. * information (in SelfAwareness.hpp) keyed by reporting device ID and
  269. * address type.
  270. *
  271. * This causes problems when clustering is combined with symmetric NAT.
  272. * Symmetric NAT remaps ports, so different endpoints in a cluster will
  273. * report back different exterior addresses. Since the old code keys
  274. * this by device ID and not sending physical address and compares the
  275. * entire address including port, it constantly thinks its external
  276. * surface is changing and resets connections when talking to a cluster.
  277. *
  278. * In new code we key by sending physical address and device and we also
  279. * take the more conservative position of only interpreting changes in
  280. * IP address (neglecting port) as a change in network topology that
  281. * necessitates a reset. But we can make older clients work here by
  282. * nulling out the port field. Since this info is only used for empirical
  283. * detection of link changes, it doesn't break anything else.
  284. */
  285. InetAddress tmpa(_remoteAddress);
  286. tmpa.setPort(0);
  287. tmpa.serialize(outp);
  288. }
  289. if ((worldId != ZT_WORLD_ID_NULL)&&(RR->topology->worldTimestamp() > worldTimestamp)&&(worldId == RR->topology->worldId())) {
  290. World w(RR->topology->world());
  291. const unsigned int sizeAt = outp.size();
  292. outp.addSize(2); // make room for 16-bit size field
  293. w.serialize(outp,false);
  294. outp.setAt<uint16_t>(sizeAt,(uint16_t)(outp.size() - (sizeAt + 2)));
  295. } else {
  296. outp.append((uint16_t)0); // no world update needed
  297. }
  298. outp.armor(peer->key(),true);
  299. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  300. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  301. peer->received(_localAddress,_remoteAddress,hops(),pid,Packet::VERB_HELLO,0,Packet::VERB_NOP);
  302. } catch ( ... ) {
  303. TRACE("dropped HELLO from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  304. }
  305. return true;
  306. }
  307. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  308. {
  309. try {
  310. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  311. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  312. //TRACE("%s(%s): OK(%s)",source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  313. switch(inReVerb) {
  314. case Packet::VERB_HELLO: {
  315. const unsigned int latency = std::min((unsigned int)(RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP)),(unsigned int)0xffff);
  316. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  317. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  318. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  319. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  320. if (vProto < ZT_PROTO_VERSION_MIN) {
  321. TRACE("%s(%s): OK(HELLO) dropped, protocol version too old",source().toString().c_str(),_remoteAddress.toString().c_str());
  322. return true;
  323. }
  324. const bool trusted = RR->topology->isRoot(peer->identity());
  325. InetAddress externalSurfaceAddress;
  326. unsigned int ptr = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
  327. if (ptr < size()) // ZeroTier One < 1.0.3 did not include this field
  328. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  329. if ((trusted)&&((ptr + 2) <= size())) { // older versions also did not include this field, and right now we only use if from a root
  330. World worldUpdate;
  331. const unsigned int worldLen = at<uint16_t>(ptr); ptr += 2;
  332. if (worldLen > 0) {
  333. World w;
  334. w.deserialize(*this,ptr);
  335. RR->topology->worldUpdateIfValid(w);
  336. }
  337. }
  338. TRACE("%s(%s): OK(HELLO), version %u.%u.%u, latency %u, reported external address %s",source().toString().c_str(),_remoteAddress.toString().c_str(),vMajor,vMinor,vRevision,latency,((externalSurfaceAddress) ? externalSurfaceAddress.toString().c_str() : "(none)"));
  339. peer->addDirectLatencyMeasurment(latency);
  340. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  341. if (externalSurfaceAddress)
  342. RR->sa->iam(peer->address(),_localAddress,_remoteAddress,externalSurfaceAddress,trusted,RR->node->now());
  343. } break;
  344. case Packet::VERB_WHOIS: {
  345. if (RR->topology->isRoot(peer->identity())) {
  346. const Identity id(*this,ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY);
  347. // Right now we can skip this since OK(WHOIS) is only accepted from
  348. // roots. In the future it should be done if we query less trusted
  349. // sources.
  350. //if (id.locallyValidate())
  351. RR->sw->doAnythingWaitingForPeer(RR->topology->addPeer(SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  352. }
  353. } break;
  354. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  355. const SharedPtr<Network> nw(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID)));
  356. if ((nw)&&(nw->controller() == peer->address())) {
  357. const unsigned int dictlen = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN);
  358. const std::string dict((const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT,dictlen),dictlen);
  359. if (dict.length()) {
  360. nw->setConfiguration(Dictionary(dict));
  361. TRACE("got network configuration for network %.16llx from %s",(unsigned long long)nw->id(),source().toString().c_str());
  362. }
  363. }
  364. } break;
  365. //case Packet::VERB_ECHO: {
  366. //} break;
  367. case Packet::VERB_MULTICAST_GATHER: {
  368. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  369. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI));
  370. TRACE("%s(%s): OK(MULTICAST_GATHER) %.16llx/%s length %u",source().toString().c_str(),_remoteAddress.toString().c_str(),nwid,mg.toString().c_str(),size());
  371. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  372. RR->mc->addMultiple(RR->node->now(),nwid,mg,field(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 6,count * 5),count,at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS));
  373. } break;
  374. case Packet::VERB_MULTICAST_FRAME: {
  375. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  376. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  377. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI));
  378. //TRACE("%s(%s): OK(MULTICAST_FRAME) %.16llx/%s flags %.2x",peer->address().toString().c_str(),_remoteAddress.toString().c_str(),nwid,mg.toString().c_str(),flags);
  379. unsigned int offset = 0;
  380. if ((flags & 0x01) != 0) {
  381. // OK(MULTICAST_FRAME) includes certificate of membership update
  382. CertificateOfMembership com;
  383. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  384. peer->validateAndSetNetworkMembershipCertificate(nwid,com);
  385. }
  386. if ((flags & 0x02) != 0) {
  387. // OK(MULTICAST_FRAME) includes implicit gather results
  388. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  389. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  390. unsigned int count = at<uint16_t>(offset); offset += 2;
  391. RR->mc->addMultiple(RR->node->now(),nwid,mg,field(offset,count * 5),count,totalKnown);
  392. }
  393. } break;
  394. default: break;
  395. }
  396. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_OK,inRePacketId,inReVerb);
  397. } catch ( ... ) {
  398. TRACE("dropped OK from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  399. }
  400. return true;
  401. }
  402. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  403. {
  404. try {
  405. if (payloadLength() == ZT_ADDRESS_LENGTH) {
  406. Identity queried(RR->topology->getIdentity(Address(payload(),ZT_ADDRESS_LENGTH)));
  407. if (queried) {
  408. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  409. outp.append((unsigned char)Packet::VERB_WHOIS);
  410. outp.append(packetId());
  411. queried.serialize(outp,false);
  412. outp.armor(peer->key(),true);
  413. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  414. } else {
  415. #ifdef ZT_ENABLE_CLUSTER
  416. if (RR->cluster)
  417. RR->cluster->sendDistributedQuery(*this);
  418. #endif
  419. }
  420. } else {
  421. TRACE("dropped WHOIS from %s(%s): missing or invalid address",source().toString().c_str(),_remoteAddress.toString().c_str());
  422. }
  423. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_WHOIS,0,Packet::VERB_NOP);
  424. } catch ( ... ) {
  425. TRACE("dropped WHOIS from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  426. }
  427. return true;
  428. }
  429. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  430. {
  431. try {
  432. if (RR->topology->isUpstream(peer->identity())) {
  433. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  434. const SharedPtr<Peer> withPeer(RR->topology->getPeer(with));
  435. if (withPeer) {
  436. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  437. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  438. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  439. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP);
  440. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  441. TRACE("RENDEZVOUS from %s says %s might be at %s, starting NAT-t",peer->address().toString().c_str(),with.toString().c_str(),atAddr.toString().c_str());
  442. if (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,atAddr))
  443. RR->sw->rendezvous(withPeer,_localAddress,atAddr);
  444. } else {
  445. TRACE("dropped corrupt RENDEZVOUS from %s(%s) (bad address or port)",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  446. }
  447. } else {
  448. RR->sw->requestWhois(with);
  449. TRACE("ignored RENDEZVOUS from %s(%s) to meet unknown peer %s",peer->address().toString().c_str(),_remoteAddress.toString().c_str(),with.toString().c_str());
  450. }
  451. } else {
  452. TRACE("ignored RENDEZVOUS from %s(%s): not a root server or a network relay",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  453. }
  454. } catch ( ... ) {
  455. TRACE("dropped RENDEZVOUS from %s(%s): unexpected exception",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  456. }
  457. return true;
  458. }
  459. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  460. {
  461. try {
  462. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID)));
  463. if (network) {
  464. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  465. if (!network->isAllowed(peer)) {
  466. TRACE("dropped FRAME from %s(%s): not a member of private network %.16llx",peer->address().toString().c_str(),_remoteAddress.toString().c_str(),(unsigned long long)network->id());
  467. _sendErrorNeedCertificate(RR,peer,network->id());
  468. return true;
  469. }
  470. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  471. if (!network->config()->permitsEtherType(etherType)) {
  472. TRACE("dropped FRAME from %s(%s): ethertype %.4x not allowed on %.16llx",peer->address().toString().c_str(),_remoteAddress.toString().c_str(),(unsigned int)etherType,(unsigned long long)network->id());
  473. return true;
  474. }
  475. const unsigned int payloadLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  476. RR->node->putFrame(network->id(),network->userPtr(),MAC(peer->address(),network->id()),network->mac(),etherType,0,field(ZT_PROTO_VERB_FRAME_IDX_PAYLOAD,payloadLen),payloadLen);
  477. }
  478. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_FRAME,0,Packet::VERB_NOP);
  479. } else {
  480. TRACE("dropped FRAME from %s(%s): we are not connected to network %.16llx",source().toString().c_str(),_remoteAddress.toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID));
  481. }
  482. } catch ( ... ) {
  483. TRACE("dropped FRAME from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  484. }
  485. return true;
  486. }
  487. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  488. {
  489. try {
  490. SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID)));
  491. if (network) {
  492. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  493. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  494. unsigned int comLen = 0;
  495. if ((flags & 0x01) != 0) {
  496. CertificateOfMembership com;
  497. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  498. peer->validateAndSetNetworkMembershipCertificate(network->id(),com);
  499. }
  500. if (!network->isAllowed(peer)) {
  501. TRACE("dropped EXT_FRAME from %s(%s): not a member of private network %.16llx",peer->address().toString().c_str(),_remoteAddress.toString().c_str(),network->id());
  502. _sendErrorNeedCertificate(RR,peer,network->id());
  503. return true;
  504. }
  505. // Everything after flags must be adjusted based on the length
  506. // of the certificate, if there was one...
  507. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  508. if (!network->config()->permitsEtherType(etherType)) {
  509. TRACE("dropped EXT_FRAME from %s(%s): ethertype %.4x not allowed on network %.16llx",peer->address().toString().c_str(),_remoteAddress.toString().c_str(),(unsigned int)etherType,(unsigned long long)network->id());
  510. return true;
  511. }
  512. const MAC to(field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_TO,ZT_PROTO_VERB_EXT_FRAME_LEN_TO),ZT_PROTO_VERB_EXT_FRAME_LEN_TO);
  513. const MAC from(field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_FROM,ZT_PROTO_VERB_EXT_FRAME_LEN_FROM),ZT_PROTO_VERB_EXT_FRAME_LEN_FROM);
  514. if (to.isMulticast()) {
  515. TRACE("dropped EXT_FRAME from %s@%s(%s) to %s: destination is multicast, must use MULTICAST_FRAME",from.toString().c_str(),peer->address().toString().c_str(),_remoteAddress.toString().c_str(),to.toString().c_str());
  516. return true;
  517. }
  518. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  519. TRACE("dropped EXT_FRAME from %s@%s(%s) to %s: invalid source MAC",from.toString().c_str(),peer->address().toString().c_str(),_remoteAddress.toString().c_str(),to.toString().c_str());
  520. return true;
  521. }
  522. if (from != MAC(peer->address(),network->id())) {
  523. if (network->permitsBridging(peer->address())) {
  524. network->learnBridgeRoute(from,peer->address());
  525. } else {
  526. TRACE("dropped EXT_FRAME from %s@%s(%s) to %s: sender not allowed to bridge into %.16llx",from.toString().c_str(),peer->address().toString().c_str(),_remoteAddress.toString().c_str(),to.toString().c_str(),network->id());
  527. return true;
  528. }
  529. } else if (to != network->mac()) {
  530. if (!network->permitsBridging(RR->identity.address())) {
  531. TRACE("dropped EXT_FRAME from %s@%s(%s) to %s: I cannot bridge to %.16llx or bridging disabled on network",from.toString().c_str(),peer->address().toString().c_str(),_remoteAddress.toString().c_str(),to.toString().c_str(),network->id());
  532. return true;
  533. }
  534. }
  535. const unsigned int payloadLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  536. RR->node->putFrame(network->id(),network->userPtr(),from,to,etherType,0,field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,payloadLen),payloadLen);
  537. }
  538. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP);
  539. } else {
  540. TRACE("dropped EXT_FRAME from %s(%s): we are not connected to network %.16llx",source().toString().c_str(),_remoteAddress.toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID));
  541. }
  542. } catch ( ... ) {
  543. TRACE("dropped EXT_FRAME from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  544. }
  545. return true;
  546. }
  547. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  548. {
  549. try {
  550. const uint64_t pid = packetId();
  551. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  552. outp.append((unsigned char)Packet::VERB_ECHO);
  553. outp.append((uint64_t)pid);
  554. if (size() > ZT_PACKET_IDX_PAYLOAD)
  555. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  556. outp.armor(peer->key(),true);
  557. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  558. peer->received(_localAddress,_remoteAddress,hops(),pid,Packet::VERB_ECHO,0,Packet::VERB_NOP);
  559. } catch ( ... ) {
  560. TRACE("dropped ECHO from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  561. }
  562. return true;
  563. }
  564. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  565. {
  566. try {
  567. const uint64_t now = RR->node->now();
  568. // Iterate through 18-byte network,MAC,ADI tuples
  569. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) {
  570. const uint64_t nwid = at<uint64_t>(ptr);
  571. const MulticastGroup group(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14));
  572. RR->mc->add(now,nwid,group,peer->address());
  573. }
  574. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP);
  575. } catch ( ... ) {
  576. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  577. }
  578. return true;
  579. }
  580. bool IncomingPacket::_doNETWORK_MEMBERSHIP_CERTIFICATE(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  581. {
  582. try {
  583. CertificateOfMembership com;
  584. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  585. while (ptr < size()) {
  586. ptr += com.deserialize(*this,ptr);
  587. peer->validateAndSetNetworkMembershipCertificate(com.networkId(),com);
  588. }
  589. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE,0,Packet::VERB_NOP);
  590. } catch ( ... ) {
  591. TRACE("dropped NETWORK_MEMBERSHIP_CERTIFICATE from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  592. }
  593. return true;
  594. }
  595. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  596. {
  597. try {
  598. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  599. const unsigned int metaDataLength = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN);
  600. const Dictionary metaData((const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength),metaDataLength);
  601. //const uint64_t haveRevision = ((ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT + metaDataLength + 8) <= size()) ? at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT + metaDataLength) : 0ULL;
  602. const unsigned int h = hops();
  603. const uint64_t pid = packetId();
  604. peer->received(_localAddress,_remoteAddress,h,pid,Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP);
  605. if (RR->localNetworkController) {
  606. Dictionary netconf;
  607. switch(RR->localNetworkController->doNetworkConfigRequest((h > 0) ? InetAddress() : _remoteAddress,RR->identity,peer->identity(),nwid,metaData,netconf)) {
  608. case NetworkController::NETCONF_QUERY_OK: {
  609. const std::string netconfStr(netconf.toString());
  610. if (netconfStr.length() > 0xffff) { // sanity check since field ix 16-bit
  611. TRACE("NETWORK_CONFIG_REQUEST failed: internal error: netconf size %u is too large",(unsigned int)netconfStr.length());
  612. } else {
  613. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  614. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  615. outp.append(pid);
  616. outp.append(nwid);
  617. outp.append((uint16_t)netconfStr.length());
  618. outp.append(netconfStr.data(),(unsigned int)netconfStr.length());
  619. outp.compress();
  620. outp.armor(peer->key(),true);
  621. if (outp.size() > ZT_PROTO_MAX_PACKET_LENGTH) { // sanity check
  622. TRACE("NETWORK_CONFIG_REQUEST failed: internal error: netconf size %u is too large",(unsigned int)netconfStr.length());
  623. } else {
  624. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  625. }
  626. }
  627. } break;
  628. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND: {
  629. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  630. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  631. outp.append(pid);
  632. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  633. outp.append(nwid);
  634. outp.armor(peer->key(),true);
  635. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  636. } break;
  637. case NetworkController::NETCONF_QUERY_ACCESS_DENIED: {
  638. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  639. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  640. outp.append(pid);
  641. outp.append((unsigned char)Packet::ERROR_NETWORK_ACCESS_DENIED_);
  642. outp.append(nwid);
  643. outp.armor(peer->key(),true);
  644. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  645. } break;
  646. case NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR:
  647. TRACE("NETWORK_CONFIG_REQUEST failed: internal error: %s",netconf.get("error","(unknown)").c_str());
  648. break;
  649. case NetworkController::NETCONF_QUERY_IGNORE:
  650. break;
  651. default:
  652. TRACE("NETWORK_CONFIG_REQUEST failed: invalid return value from NetworkController::doNetworkConfigRequest()");
  653. break;
  654. }
  655. } else {
  656. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  657. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  658. outp.append(pid);
  659. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  660. outp.append(nwid);
  661. outp.armor(peer->key(),true);
  662. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  663. }
  664. } catch ( ... ) {
  665. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  666. }
  667. return true;
  668. }
  669. bool IncomingPacket::_doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  670. {
  671. try {
  672. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  673. while ((ptr + 8) <= size()) {
  674. uint64_t nwid = at<uint64_t>(ptr);
  675. SharedPtr<Network> nw(RR->node->network(nwid));
  676. if ((nw)&&(peer->address() == nw->controller()))
  677. nw->requestConfiguration();
  678. ptr += 8;
  679. }
  680. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_NETWORK_CONFIG_REFRESH,0,Packet::VERB_NOP);
  681. } catch ( ... ) {
  682. TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  683. }
  684. return true;
  685. }
  686. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  687. {
  688. try {
  689. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  690. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  691. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  692. //TRACE("<<MC %s(%s) GATHER up to %u in %.16llx/%s",source().toString().c_str(),_remoteAddress.toString().c_str(),gatherLimit,nwid,mg.toString().c_str());
  693. if (gatherLimit) {
  694. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  695. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  696. outp.append(packetId());
  697. outp.append(nwid);
  698. mg.mac().appendTo(outp);
  699. outp.append((uint32_t)mg.adi());
  700. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  701. if (gatheredLocally) {
  702. outp.armor(peer->key(),true);
  703. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  704. }
  705. #ifdef ZT_ENABLE_CLUSTER
  706. if ((RR->cluster)&&(gatheredLocally < gatherLimit))
  707. RR->cluster->sendDistributedQuery(*this);
  708. #endif
  709. }
  710. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP);
  711. } catch ( ... ) {
  712. TRACE("dropped MULTICAST_GATHER from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  713. }
  714. return true;
  715. }
  716. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  717. {
  718. try {
  719. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID);
  720. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS];
  721. const SharedPtr<Network> network(RR->node->network(nwid));
  722. if (network) {
  723. // Offset -- size of optional fields added to position of later fields
  724. unsigned int offset = 0;
  725. if ((flags & 0x01) != 0) {
  726. CertificateOfMembership com;
  727. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM);
  728. peer->validateAndSetNetworkMembershipCertificate(nwid,com);
  729. }
  730. // Check membership after we've read any included COM, since
  731. // that cert might be what we needed.
  732. if (!network->isAllowed(peer)) {
  733. TRACE("dropped MULTICAST_FRAME from %s(%s): not a member of private network %.16llx",peer->address().toString().c_str(),_remoteAddress.toString().c_str(),(unsigned long long)network->id());
  734. _sendErrorNeedCertificate(RR,peer,network->id());
  735. return true;
  736. }
  737. unsigned int gatherLimit = 0;
  738. if ((flags & 0x02) != 0) {
  739. gatherLimit = at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT);
  740. offset += 4;
  741. }
  742. MAC from;
  743. if ((flags & 0x04) != 0) {
  744. from.setTo(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6),6);
  745. offset += 6;
  746. } else {
  747. from.fromAddress(peer->address(),nwid);
  748. }
  749. const MulticastGroup to(MAC(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC,6),6),at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI));
  750. const unsigned int etherType = at<uint16_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  751. const unsigned int payloadLen = size() - (offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME);
  752. //TRACE("<<MC FRAME %.16llx/%s from %s@%s flags %.2x length %u",nwid,to.toString().c_str(),from.toString().c_str(),peer->address().toString().c_str(),flags,payloadLen);
  753. if ((payloadLen > 0)&&(payloadLen <= ZT_IF_MTU)) {
  754. if (!to.mac().isMulticast()) {
  755. TRACE("dropped MULTICAST_FRAME from %s@%s(%s) to %s: destination is unicast, must use FRAME or EXT_FRAME",from.toString().c_str(),peer->address().toString().c_str(),_remoteAddress.toString().c_str(),to.toString().c_str());
  756. return true;
  757. }
  758. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  759. TRACE("dropped MULTICAST_FRAME from %s@%s(%s) to %s: invalid source MAC",from.toString().c_str(),peer->address().toString().c_str(),_remoteAddress.toString().c_str(),to.toString().c_str());
  760. return true;
  761. }
  762. if (from != MAC(peer->address(),network->id())) {
  763. if (network->permitsBridging(peer->address())) {
  764. network->learnBridgeRoute(from,peer->address());
  765. } else {
  766. TRACE("dropped MULTICAST_FRAME from %s@%s(%s) to %s: sender not allowed to bridge into %.16llx",from.toString().c_str(),peer->address().toString().c_str(),_remoteAddress.toString().c_str(),to.toString().c_str(),network->id());
  767. return true;
  768. }
  769. }
  770. RR->node->putFrame(network->id(),network->userPtr(),from,to.mac(),etherType,0,field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME,payloadLen),payloadLen);
  771. }
  772. if (gatherLimit) {
  773. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  774. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  775. outp.append(packetId());
  776. outp.append(nwid);
  777. to.mac().appendTo(outp);
  778. outp.append((uint32_t)to.adi());
  779. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  780. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  781. outp.armor(peer->key(),true);
  782. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  783. }
  784. }
  785. } // else ignore -- not a member of this network
  786. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP);
  787. } catch ( ... ) {
  788. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  789. }
  790. return true;
  791. }
  792. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  793. {
  794. try {
  795. const uint64_t now = RR->node->now();
  796. // First, subject this to a rate limit
  797. if (!peer->shouldRespondToDirectPathPush(now)) {
  798. TRACE("dropped PUSH_DIRECT_PATHS from %s(%s): circuit breaker tripped",source().toString().c_str(),_remoteAddress.toString().c_str());
  799. return true;
  800. }
  801. // Second, limit addresses by scope and type
  802. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  803. memset(countPerScope,0,sizeof(countPerScope));
  804. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  805. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  806. while (count--) { // if ptr overflows Buffer will throw
  807. // TODO: some flags are not yet implemented
  808. unsigned int flags = (*this)[ptr++];
  809. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  810. ptr += extLen; // unused right now
  811. unsigned int addrType = (*this)[ptr++];
  812. unsigned int addrLen = (*this)[ptr++];
  813. switch(addrType) {
  814. case 4: {
  815. InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  816. if ( ((flags & 0x01) == 0) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
  817. if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  818. TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
  819. peer->sendHELLO(InetAddress(),a,now);
  820. } else {
  821. TRACE("ignoring contact for %s at %s -- too many per scope",peer->address().toString().c_str(),a.toString().c_str());
  822. }
  823. }
  824. } break;
  825. case 6: {
  826. InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  827. if ( ((flags & 0x01) == 0) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
  828. if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  829. TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
  830. peer->sendHELLO(InetAddress(),a,now);
  831. } else {
  832. TRACE("ignoring contact for %s at %s -- too many per scope",peer->address().toString().c_str(),a.toString().c_str());
  833. }
  834. }
  835. } break;
  836. }
  837. ptr += addrLen;
  838. }
  839. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP);
  840. } catch ( ... ) {
  841. TRACE("dropped PUSH_DIRECT_PATHS from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  842. }
  843. return true;
  844. }
  845. bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  846. {
  847. try {
  848. const Address originatorAddress(field(ZT_PACKET_IDX_PAYLOAD,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  849. SharedPtr<Peer> originator(RR->topology->getPeer(originatorAddress));
  850. if (!originator) {
  851. RR->sw->requestWhois(originatorAddress);
  852. return false;
  853. }
  854. const unsigned int flags = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 5);
  855. const uint64_t timestamp = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 7);
  856. const uint64_t testId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 15);
  857. // Tracks total length of variable length fields, initialized to originator credential length below
  858. unsigned int vlf;
  859. // Originator credentials
  860. const unsigned int originatorCredentialLength = vlf = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23);
  861. uint64_t originatorCredentialNetworkId = 0;
  862. if (originatorCredentialLength >= 1) {
  863. switch((*this)[ZT_PACKET_IDX_PAYLOAD + 25]) {
  864. case 0x01: { // 64-bit network ID, originator must be controller
  865. if (originatorCredentialLength >= 9)
  866. originatorCredentialNetworkId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 26);
  867. } break;
  868. default: break;
  869. }
  870. }
  871. // Add length of "additional fields," which are currently unused
  872. vlf += at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 25 + vlf);
  873. // Verify signature -- only tests signed by their originators are allowed
  874. const unsigned int signatureLength = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 27 + vlf);
  875. if (!originator->identity().verify(field(ZT_PACKET_IDX_PAYLOAD,27 + vlf),27 + vlf,field(ZT_PACKET_IDX_PAYLOAD + 29 + vlf,signatureLength),signatureLength)) {
  876. TRACE("dropped CIRCUIT_TEST from %s(%s): signature by originator %s invalid",source().toString().c_str(),_remoteAddress.toString().c_str(),originatorAddress.toString().c_str());
  877. return true;
  878. }
  879. vlf += signatureLength;
  880. // Save this length so we can copy the immutable parts of this test
  881. // into the one we send along to next hops.
  882. const unsigned int lengthOfSignedPortionAndSignature = 29 + vlf;
  883. // Get previous hop's credential, if any
  884. const unsigned int previousHopCredentialLength = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 29 + vlf);
  885. CertificateOfMembership previousHopCom;
  886. if (previousHopCredentialLength >= 1) {
  887. switch((*this)[ZT_PACKET_IDX_PAYLOAD + 31 + vlf]) {
  888. case 0x01: { // network certificate of membership for previous hop
  889. const unsigned int phcl = previousHopCom.deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 32 + vlf);
  890. if (phcl != (previousHopCredentialLength - 1)) {
  891. TRACE("dropped CIRCUIT_TEST from %s(%s): previous hop COM invalid (%u != %u)",source().toString().c_str(),_remoteAddress.toString().c_str(),phcl,(previousHopCredentialLength - 1));
  892. return true;
  893. }
  894. } break;
  895. default: break;
  896. }
  897. }
  898. vlf += previousHopCredentialLength;
  899. // Check credentials (signature already verified)
  900. SharedPtr<NetworkConfig> originatorCredentialNetworkConfig;
  901. if (originatorCredentialNetworkId) {
  902. if (Network::controllerFor(originatorCredentialNetworkId) == originatorAddress) {
  903. SharedPtr<Network> nw(RR->node->network(originatorCredentialNetworkId));
  904. if (nw) {
  905. originatorCredentialNetworkConfig = nw->config2();
  906. if ( (originatorCredentialNetworkConfig) && ( (originatorCredentialNetworkConfig->isPublic()) || (peer->address() == originatorAddress) || ((originatorCredentialNetworkConfig->com())&&(previousHopCom)&&(originatorCredentialNetworkConfig->com().agreesWith(previousHopCom))) ) ) {
  907. TRACE("CIRCUIT_TEST %.16llx received from hop %s(%s) and originator %s with valid network ID credential %.16llx (verified from originator and next hop)",testId,source().toString().c_str(),_remoteAddress.toString().c_str(),originatorAddress.toString().c_str(),originatorCredentialNetworkId);
  908. } else {
  909. TRACE("dropped CIRCUIT_TEST from %s(%s): originator %s specified network ID %.16llx as credential, and previous hop %s did not supply a valid COM",source().toString().c_str(),_remoteAddress.toString().c_str(),originatorAddress.toString().c_str(),originatorCredentialNetworkId,peer->address().toString().c_str());
  910. return true;
  911. }
  912. } else {
  913. TRACE("dropped CIRCUIT_TEST from %s(%s): originator %s specified network ID %.16llx as credential, and we are not a member",source().toString().c_str(),_remoteAddress.toString().c_str(),originatorAddress.toString().c_str(),originatorCredentialNetworkId);
  914. return true;
  915. }
  916. } else {
  917. TRACE("dropped CIRCUIT_TEST from %s(%s): originator %s specified network ID as credential, is not controller for %.16llx",source().toString().c_str(),_remoteAddress.toString().c_str(),originatorAddress.toString().c_str(),originatorCredentialNetworkId);
  918. return true;
  919. }
  920. } else {
  921. TRACE("dropped CIRCUIT_TEST from %s(%s): originator %s did not specify a credential or credential type",source().toString().c_str(),_remoteAddress.toString().c_str(),originatorAddress.toString().c_str());
  922. return true;
  923. }
  924. const uint64_t now = RR->node->now();
  925. unsigned int breadth = 0;
  926. Address nextHop[256]; // breadth is a uin8_t, so this is the max
  927. InetAddress nextHopBestPathAddress[256];
  928. unsigned int remainingHopsPtr = ZT_PACKET_IDX_PAYLOAD + 33 + vlf;
  929. if ((ZT_PACKET_IDX_PAYLOAD + 31 + vlf) < size()) {
  930. // unsigned int nextHopFlags = (*this)[ZT_PACKET_IDX_PAYLOAD + 31 + vlf]
  931. breadth = (*this)[ZT_PACKET_IDX_PAYLOAD + 32 + vlf];
  932. for(unsigned int h=0;h<breadth;++h) {
  933. nextHop[h].setTo(field(remainingHopsPtr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  934. remainingHopsPtr += ZT_ADDRESS_LENGTH;
  935. SharedPtr<Peer> nhp(RR->topology->getPeer(nextHop[h]));
  936. if (nhp) {
  937. Path *const rp = nhp->getBestPath(now);
  938. if (rp)
  939. nextHopBestPathAddress[h] = rp->address();
  940. }
  941. }
  942. }
  943. // Report back to originator, depending on flags and whether we are last hop
  944. if ( ((flags & 0x01) != 0) || ((breadth == 0)&&((flags & 0x02) != 0)) ) {
  945. Packet outp(originatorAddress,RR->identity.address(),Packet::VERB_CIRCUIT_TEST_REPORT);
  946. outp.append((uint64_t)timestamp);
  947. outp.append((uint64_t)testId);
  948. outp.append((uint64_t)0); // field reserved for future use
  949. outp.append((uint8_t)ZT_VENDOR_ZEROTIER);
  950. outp.append((uint8_t)ZT_PROTO_VERSION);
  951. outp.append((uint8_t)ZEROTIER_ONE_VERSION_MAJOR);
  952. outp.append((uint8_t)ZEROTIER_ONE_VERSION_MINOR);
  953. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  954. outp.append((uint16_t)ZT_PLATFORM_UNSPECIFIED);
  955. outp.append((uint16_t)ZT_ARCHITECTURE_UNSPECIFIED);
  956. outp.append((uint16_t)0); // error code, currently unused
  957. outp.append((uint64_t)0); // flags, currently unused
  958. outp.append((uint64_t)packetId());
  959. peer->address().appendTo(outp);
  960. outp.append((uint8_t)hops());
  961. _localAddress.serialize(outp);
  962. _remoteAddress.serialize(outp);
  963. outp.append((uint16_t)0); // no additional fields
  964. outp.append((uint8_t)breadth);
  965. for(unsigned int h=0;h<breadth;++h) {
  966. nextHop[h].appendTo(outp);
  967. nextHopBestPathAddress[h].serialize(outp); // appends 0 if null InetAddress
  968. }
  969. RR->sw->send(outp,true,0);
  970. }
  971. // If there are next hops, forward the test along through the graph
  972. if (breadth > 0) {
  973. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  974. outp.append(field(ZT_PACKET_IDX_PAYLOAD,lengthOfSignedPortionAndSignature),lengthOfSignedPortionAndSignature);
  975. const unsigned int previousHopCredentialPos = outp.size();
  976. outp.append((uint16_t)0); // no previous hop credentials: default
  977. if ((originatorCredentialNetworkConfig)&&(!originatorCredentialNetworkConfig->isPublic())&&(originatorCredentialNetworkConfig->com())) {
  978. outp.append((uint8_t)0x01); // COM
  979. originatorCredentialNetworkConfig->com().serialize(outp);
  980. outp.setAt<uint16_t>(previousHopCredentialPos,(uint16_t)(outp.size() - (previousHopCredentialPos + 2)));
  981. }
  982. if (remainingHopsPtr < size())
  983. outp.append(field(remainingHopsPtr,size() - remainingHopsPtr),size() - remainingHopsPtr);
  984. for(unsigned int h=0;h<breadth;++h) {
  985. if (RR->identity.address() != nextHop[h]) { // next hops that loop back to the current hop are not valid
  986. outp.newInitializationVector();
  987. outp.setDestination(nextHop[h]);
  988. RR->sw->send(outp,true,originatorCredentialNetworkId);
  989. }
  990. }
  991. }
  992. peer->received(_localAddress,_remoteAddress,hops(),packetId(),Packet::VERB_CIRCUIT_TEST,0,Packet::VERB_NOP);
  993. } catch ( ... ) {
  994. TRACE("dropped CIRCUIT_TEST from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  995. }
  996. return true;
  997. }
  998. bool IncomingPacket::_doCIRCUIT_TEST_REPORT(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  999. {
  1000. try {
  1001. ZT_CircuitTestReport report;
  1002. memset(&report,0,sizeof(report));
  1003. report.current = peer->address().toInt();
  1004. report.upstream = Address(field(ZT_PACKET_IDX_PAYLOAD + 52,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH).toInt();
  1005. report.testId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 8);
  1006. report.timestamp = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  1007. report.remoteTimestamp = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 16);
  1008. report.sourcePacketId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 44);
  1009. report.flags = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 36);
  1010. report.sourcePacketHopCount = (*this)[ZT_PACKET_IDX_PAYLOAD + 57]; // end of fixed length headers: 58
  1011. report.errorCode = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 34);
  1012. report.vendor = (enum ZT_Vendor)((*this)[ZT_PACKET_IDX_PAYLOAD + 24]);
  1013. report.protocolVersion = (*this)[ZT_PACKET_IDX_PAYLOAD + 25];
  1014. report.majorVersion = (*this)[ZT_PACKET_IDX_PAYLOAD + 26];
  1015. report.minorVersion = (*this)[ZT_PACKET_IDX_PAYLOAD + 27];
  1016. report.revision = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 28);
  1017. report.platform = (enum ZT_Platform)at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 30);
  1018. report.architecture = (enum ZT_Architecture)at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 32);
  1019. const unsigned int receivedOnLocalAddressLen = reinterpret_cast<InetAddress *>(&(report.receivedOnLocalAddress))->deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 58);
  1020. const unsigned int receivedFromRemoteAddressLen = reinterpret_cast<InetAddress *>(&(report.receivedFromRemoteAddress))->deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 58 + receivedOnLocalAddressLen);
  1021. unsigned int nhptr = ZT_PACKET_IDX_PAYLOAD + 58 + receivedOnLocalAddressLen + receivedFromRemoteAddressLen;
  1022. nhptr += at<uint16_t>(nhptr) + 2; // add "additional field" length, which right now will be zero
  1023. report.nextHopCount = (*this)[nhptr++];
  1024. if (report.nextHopCount > ZT_CIRCUIT_TEST_MAX_HOP_BREADTH) // sanity check, shouldn't be possible
  1025. report.nextHopCount = ZT_CIRCUIT_TEST_MAX_HOP_BREADTH;
  1026. for(unsigned int h=0;h<report.nextHopCount;++h) {
  1027. report.nextHops[h].address = Address(field(nhptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH).toInt(); nhptr += ZT_ADDRESS_LENGTH;
  1028. nhptr += reinterpret_cast<InetAddress *>(&(report.nextHops[h].physicalAddress))->deserialize(*this,nhptr);
  1029. }
  1030. RR->node->postCircuitTestReport(&report);
  1031. } catch ( ... ) {
  1032. TRACE("dropped CIRCUIT_TEST_REPORT from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  1033. }
  1034. return true;
  1035. }
  1036. bool IncomingPacket::_doREQUEST_PROOF_OF_WORK(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  1037. {
  1038. try {
  1039. // Right now this is only allowed from root servers -- may be allowed from controllers and relays later.
  1040. if (RR->topology->isRoot(peer->identity())) {
  1041. const uint64_t pid = packetId();
  1042. const unsigned int difficulty = (*this)[ZT_PACKET_IDX_PAYLOAD + 1];
  1043. const unsigned int challengeLength = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 2);
  1044. if (challengeLength > ZT_PROTO_MAX_PACKET_LENGTH)
  1045. return true; // sanity check, drop invalid size
  1046. const unsigned char *challenge = field(ZT_PACKET_IDX_PAYLOAD + 4,challengeLength);
  1047. switch((*this)[ZT_PACKET_IDX_PAYLOAD]) {
  1048. // Salsa20/12+SHA512 hashcash
  1049. case 0x01: {
  1050. if (difficulty <= 14) {
  1051. unsigned char result[16];
  1052. computeSalsa2012Sha512ProofOfWork(difficulty,challenge,challengeLength,result);
  1053. TRACE("PROOF_OF_WORK computed for %s: difficulty==%u, challengeLength==%u, result: %.16llx%.16llx",peer->address().toString().c_str(),difficulty,challengeLength,Utils::ntoh(*(reinterpret_cast<const uint64_t *>(result))),Utils::ntoh(*(reinterpret_cast<const uint64_t *>(result + 8))));
  1054. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  1055. outp.append((unsigned char)Packet::VERB_REQUEST_PROOF_OF_WORK);
  1056. outp.append(pid);
  1057. outp.append((uint16_t)sizeof(result));
  1058. outp.append(result,sizeof(result));
  1059. outp.armor(peer->key(),true);
  1060. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  1061. } else {
  1062. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  1063. outp.append((unsigned char)Packet::VERB_REQUEST_PROOF_OF_WORK);
  1064. outp.append(pid);
  1065. outp.append((unsigned char)Packet::ERROR_INVALID_REQUEST);
  1066. outp.armor(peer->key(),true);
  1067. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  1068. }
  1069. } break;
  1070. default:
  1071. TRACE("dropped REQUEST_PROOF_OF_WORK from %s(%s): unrecognized proof of work type",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  1072. break;
  1073. }
  1074. peer->received(_localAddress,_remoteAddress,hops(),pid,Packet::VERB_REQUEST_PROOF_OF_WORK,0,Packet::VERB_NOP);
  1075. } else {
  1076. TRACE("dropped REQUEST_PROOF_OF_WORK from %s(%s): not trusted enough",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  1077. }
  1078. } catch ( ... ) {
  1079. TRACE("dropped REQUEST_PROOF_OF_WORK from %s(%s): unexpected exception",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  1080. }
  1081. return true;
  1082. }
  1083. void IncomingPacket::computeSalsa2012Sha512ProofOfWork(unsigned int difficulty,const void *challenge,unsigned int challengeLength,unsigned char result[16])
  1084. {
  1085. unsigned char salsabuf[131072]; // 131072 == protocol constant, size of memory buffer for this proof of work function
  1086. char candidatebuf[ZT_PROTO_MAX_PACKET_LENGTH + 256];
  1087. unsigned char shabuf[ZT_SHA512_DIGEST_LEN];
  1088. const uint64_t s20iv = 0; // zero IV for Salsa20
  1089. char *const candidate = (char *)(( ((uintptr_t)&(candidatebuf[0])) | 0xf ) + 1); // align to 16-byte boundary to ensure that uint64_t type punning of initial nonce is okay
  1090. Salsa20 s20;
  1091. unsigned int d;
  1092. unsigned char *p;
  1093. Utils::getSecureRandom(candidate,16);
  1094. memcpy(candidate + 16,challenge,challengeLength);
  1095. if (difficulty > 512)
  1096. difficulty = 512; // sanity check
  1097. try_salsa2012sha512_again:
  1098. ++*(reinterpret_cast<volatile uint64_t *>(candidate));
  1099. SHA512::hash(shabuf,candidate,16 + challengeLength);
  1100. s20.init(shabuf,256,&s20iv);
  1101. memset(salsabuf,0,sizeof(salsabuf));
  1102. s20.encrypt12(salsabuf,salsabuf,sizeof(salsabuf));
  1103. SHA512::hash(shabuf,salsabuf,sizeof(salsabuf));
  1104. d = difficulty;
  1105. p = shabuf;
  1106. while (d >= 8) {
  1107. if (*(p++))
  1108. goto try_salsa2012sha512_again;
  1109. d -= 8;
  1110. }
  1111. if (d > 0) {
  1112. if ( ((((unsigned int)*p) << d) & 0xff00) != 0 )
  1113. goto try_salsa2012sha512_again;
  1114. }
  1115. memcpy(result,candidate,16);
  1116. }
  1117. bool IncomingPacket::testSalsa2012Sha512ProofOfWorkResult(unsigned int difficulty,const void *challenge,unsigned int challengeLength,const unsigned char proposedResult[16])
  1118. {
  1119. unsigned char salsabuf[131072]; // 131072 == protocol constant, size of memory buffer for this proof of work function
  1120. char candidate[ZT_PROTO_MAX_PACKET_LENGTH + 256];
  1121. unsigned char shabuf[ZT_SHA512_DIGEST_LEN];
  1122. const uint64_t s20iv = 0; // zero IV for Salsa20
  1123. Salsa20 s20;
  1124. unsigned int d;
  1125. unsigned char *p;
  1126. if (difficulty > 512)
  1127. difficulty = 512; // sanity check
  1128. memcpy(candidate,proposedResult,16);
  1129. memcpy(candidate + 16,challenge,challengeLength);
  1130. SHA512::hash(shabuf,candidate,16 + challengeLength);
  1131. s20.init(shabuf,256,&s20iv);
  1132. memset(salsabuf,0,sizeof(salsabuf));
  1133. s20.encrypt12(salsabuf,salsabuf,sizeof(salsabuf));
  1134. SHA512::hash(shabuf,salsabuf,sizeof(salsabuf));
  1135. d = difficulty;
  1136. p = shabuf;
  1137. while (d >= 8) {
  1138. if (*(p++))
  1139. return false;
  1140. d -= 8;
  1141. }
  1142. if (d > 0) {
  1143. if ( ((((unsigned int)*p) << d) & 0xff00) != 0 )
  1144. return false;
  1145. }
  1146. return true;
  1147. }
  1148. void IncomingPacket::_sendErrorNeedCertificate(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer,uint64_t nwid)
  1149. {
  1150. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  1151. outp.append((unsigned char)verb());
  1152. outp.append(packetId());
  1153. outp.append((unsigned char)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  1154. outp.append(nwid);
  1155. outp.armor(peer->key(),true);
  1156. RR->node->putPacket(_localAddress,_remoteAddress,outp.data(),outp.size());
  1157. }
  1158. } // namespace ZeroTier