IncomingPacket.cpp 62 KB

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