IncomingPacket.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "../include/ZeroTierOne.h"
  14. #include "Constants.hpp"
  15. #include "RuntimeEnvironment.hpp"
  16. #include "IncomingPacket.hpp"
  17. #include "Topology.hpp"
  18. #include "Switch.hpp"
  19. #include "Peer.hpp"
  20. #include "NetworkController.hpp"
  21. #include "SelfAwareness.hpp"
  22. #include "Salsa20.hpp"
  23. #include "Node.hpp"
  24. #include "CertificateOfMembership.hpp"
  25. #include "Capability.hpp"
  26. #include "Tag.hpp"
  27. #include "Revocation.hpp"
  28. #include "Trace.hpp"
  29. #include <cstring>
  30. #include <cstdlib>
  31. #include <list>
  32. namespace ZeroTier {
  33. namespace {
  34. //////////////////////////////////////////////////////////////////////////////
  35. // Implementation of each protocol verb //
  36. //////////////////////////////////////////////////////////////////////////////
  37. void _sendErrorNeedCredentials(IncomingPacket &pkt,const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid,const SharedPtr<Path> &path)
  38. {
  39. Packet outp(pkt.source(),RR->identity.address(),Packet::VERB_ERROR);
  40. outp.append((uint8_t)pkt.verb());
  41. outp.append(pkt.packetId());
  42. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  43. outp.append(nwid);
  44. outp.armor(peer->key(),true);
  45. path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  46. }
  47. ZT_ALWAYS_INLINE bool _doHELLO(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const bool alreadyAuthenticated,const SharedPtr<Path> &path)
  48. {
  49. const int64_t now = RR->node->now();
  50. const uint64_t pid = pkt.packetId();
  51. const Address fromAddress(pkt.source());
  52. const unsigned int protoVersion = pkt[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  53. const unsigned int vMajor = pkt[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  54. const unsigned int vMinor = pkt[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  55. const unsigned int vRevision = pkt.at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  56. const int64_t timestamp = pkt.at<int64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  57. Identity id;
  58. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(pkt,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  59. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  60. RR->t->incomingPacketDroppedHELLO(tPtr,path,pid,fromAddress,"protocol version too old");
  61. return true;
  62. }
  63. if (fromAddress != id.address()) {
  64. RR->t->incomingPacketDroppedHELLO(tPtr,path,pid,fromAddress,"identity/address mismatch");
  65. return true;
  66. }
  67. SharedPtr<Peer> peer(RR->topology->get(id.address()));
  68. if (peer) {
  69. // We already have an identity with this address -- check for collisions
  70. if (!alreadyAuthenticated) {
  71. if (peer->identity() != id) {
  72. // Identity is different from the one we already have -- address collision
  73. // Check rate limits
  74. if (!RR->node->rateGateIdentityVerification(now,path->address()))
  75. return true;
  76. uint8_t key[ZT_PEER_SECRET_KEY_LENGTH];
  77. if (RR->identity.agree(id,key)) {
  78. if (pkt.dearmor(key)) { // ensure packet is authentic, otherwise drop
  79. RR->t->incomingPacketDroppedHELLO(tPtr,path,pid,fromAddress,"address collision");
  80. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  81. outp.append((uint8_t)Packet::VERB_HELLO);
  82. outp.append((uint64_t)pid);
  83. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  84. outp.armor(key,true);
  85. path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  86. } else {
  87. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,path,pid,fromAddress,pkt.hops(),"invalid MAC");
  88. }
  89. } else {
  90. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,path,pid,fromAddress,pkt.hops(),"invalid identity");
  91. }
  92. return true;
  93. } else {
  94. // Identity is the same as the one we already have -- check packet integrity
  95. if (!pkt.dearmor(peer->key())) {
  96. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,path,pid,fromAddress,pkt.hops(),"invalid MAC");
  97. return true;
  98. }
  99. // Continue at // VALID
  100. }
  101. } // else if alreadyAuthenticated then continue at // VALID
  102. } else {
  103. // We don't already have an identity with this address -- validate and learn it
  104. // Sanity check: this basically can't happen
  105. if (alreadyAuthenticated) {
  106. RR->t->incomingPacketDroppedHELLO(tPtr,path,pid,fromAddress,"illegal alreadyAuthenticated state");
  107. return true;
  108. }
  109. // Check rate limits
  110. if (!RR->node->rateGateIdentityVerification(now,path->address())) {
  111. RR->t->incomingPacketDroppedHELLO(tPtr,path,pid,fromAddress,"rate limit exceeded");
  112. return true;
  113. }
  114. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  115. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  116. if (!pkt.dearmor(newPeer->key())) {
  117. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,path,pid,fromAddress,pkt.hops(),"invalid MAC");
  118. return true;
  119. }
  120. // Check that identity's address is valid as per the derivation function
  121. if (!id.locallyValidate()) {
  122. RR->t->incomingPacketDroppedHELLO(tPtr,path,pid,fromAddress,"invalid identity");
  123. return true;
  124. }
  125. peer = RR->topology->add(newPeer);
  126. // Continue at // VALID
  127. }
  128. // VALID -- if we made it here, packet passed identity and authenticity checks!
  129. // Get address to which this packet was sent to learn our external surface address if packet was direct.
  130. if (pkt.hops() == 0) {
  131. InetAddress externalSurfaceAddress;
  132. if (ptr < pkt.size()) {
  133. ptr += externalSurfaceAddress.deserialize(pkt,ptr);
  134. if ((externalSurfaceAddress)&&(pkt.hops() == 0))
  135. RR->sa->iam(tPtr,id.address(),path->localSocket(),path->address(),externalSurfaceAddress,RR->topology->isRoot(id),now);
  136. }
  137. }
  138. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  139. // information about us: version, sent-to address, etc.
  140. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  141. outp.append((unsigned char)Packet::VERB_HELLO);
  142. outp.append((uint64_t)pid);
  143. outp.append((uint64_t)timestamp);
  144. outp.append((unsigned char)ZT_PROTO_VERSION);
  145. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  146. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  147. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  148. path->address().serialize(outp);
  149. outp.armor(peer->key(),true);
  150. path->send(RR,tPtr,outp.data(),outp.size(),now);
  151. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  152. peer->received(tPtr,path,pkt.hops(),pid,pkt.payloadLength(),Packet::VERB_HELLO,0,Packet::VERB_NOP,0);
  153. return true;
  154. }
  155. ZT_ALWAYS_INLINE bool _doERROR(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  156. {
  157. const Packet::Verb inReVerb = (Packet::Verb)pkt[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  158. const uint64_t inRePacketId = pkt.at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  159. const Packet::ErrorCode errorCode = (Packet::ErrorCode)pkt[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  160. uint64_t networkId = 0;
  161. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  162. * avoid having to log every outgoing packet ID. Instead we put the
  163. * logic to determine whether we should consider an ERROR in each
  164. * error handler. In most cases these are only trusted in specific
  165. * circumstances. */
  166. switch(errorCode) {
  167. case Packet::ERROR_OBJ_NOT_FOUND:
  168. // Object not found, currently only meaningful from network controllers.
  169. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  170. networkId = pkt.at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  171. const SharedPtr<Network> network(RR->node->network(networkId));
  172. if ((network)&&(network->controller() == peer->address()))
  173. network->setNotFound();
  174. }
  175. break;
  176. case Packet::ERROR_UNSUPPORTED_OPERATION:
  177. // This can be sent in response to any operation, though right now we only
  178. // consider it meaningful from network controllers. This would indicate
  179. // that the queried node does not support acting as a controller.
  180. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  181. networkId = pkt.at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  182. const SharedPtr<Network> network(RR->node->network(networkId));
  183. if ((network)&&(network->controller() == peer->address()))
  184. network->setNotFound();
  185. }
  186. break;
  187. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  188. // Peers can send this to ask for a cert for a network.
  189. networkId = pkt.at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  190. const SharedPtr<Network> network(RR->node->network(networkId));
  191. const int64_t now = RR->node->now();
  192. if ((network)&&(network->config().com))
  193. network->pushCredentialsNow(tPtr,peer->address(),now);
  194. } break;
  195. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  196. // Network controller: network access denied.
  197. networkId = pkt.at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  198. const SharedPtr<Network> network(RR->node->network(networkId));
  199. if ((network)&&(network->controller() == peer->address()))
  200. network->setAccessDenied();
  201. } break;
  202. default: break;
  203. }
  204. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_ERROR,inRePacketId,inReVerb,networkId);
  205. return true;
  206. }
  207. ZT_ALWAYS_INLINE bool _doOK(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  208. {
  209. const Packet::Verb inReVerb = (Packet::Verb)pkt[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  210. const uint64_t inRePacketId = pkt.at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  211. uint64_t networkId = 0;
  212. if (!RR->node->expectingReplyTo(inRePacketId))
  213. return true;
  214. switch(inReVerb) {
  215. case Packet::VERB_HELLO: {
  216. const uint64_t latency = RR->node->now() - pkt.at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  217. const unsigned int vProto = pkt[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  218. const unsigned int vMajor = pkt[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  219. const unsigned int vMinor = pkt[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  220. const unsigned int vRevision = pkt.at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  221. if (vProto < ZT_PROTO_VERSION_MIN)
  222. return true;
  223. if (pkt.hops() == 0) {
  224. if ((ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2) < pkt.size()) {
  225. InetAddress externalSurfaceAddress;
  226. externalSurfaceAddress.deserialize(pkt,ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2);
  227. if (externalSurfaceAddress)
  228. RR->sa->iam(tPtr,peer->address(),path->localSocket(),path->address(),externalSurfaceAddress,RR->topology->isRoot(peer->identity()),RR->node->now());
  229. }
  230. }
  231. peer->updateLatency((unsigned int)latency);
  232. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  233. } break;
  234. case Packet::VERB_WHOIS:
  235. if (RR->topology->isRoot(peer->identity())) {
  236. unsigned int p = ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY;
  237. while (p < pkt.size()) {
  238. try {
  239. Identity id;
  240. p += id.deserialize(pkt,p);
  241. if (id)
  242. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->add(SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  243. } catch ( ... ) {
  244. break;
  245. }
  246. }
  247. }
  248. break;
  249. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  250. networkId = pkt.at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  251. const SharedPtr<Network> network(RR->node->network(networkId));
  252. if (network)
  253. network->handleConfigChunk(tPtr,pkt.packetId(),pkt.source(),pkt,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  254. } break;
  255. case Packet::VERB_MULTICAST_GATHER: {
  256. } break;
  257. default: break;
  258. }
  259. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_OK,inRePacketId,inReVerb,networkId);
  260. return true;
  261. }
  262. ZT_ALWAYS_INLINE bool _doWHOIS(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  263. {
  264. if (!peer->rateGateInboundWhoisRequest(RR->node->now()))
  265. return true;
  266. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  267. outp.append((unsigned char)Packet::VERB_WHOIS);
  268. outp.append(pkt.packetId());
  269. unsigned int count = 0;
  270. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  271. while ((ptr + ZT_ADDRESS_LENGTH) <= pkt.size()) {
  272. const Address addr(pkt.field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  273. ptr += ZT_ADDRESS_LENGTH;
  274. const Identity id(RR->topology->getIdentity(tPtr,addr));
  275. if (id) {
  276. id.serialize(outp,false);
  277. ++count;
  278. } else {
  279. // Request unknown WHOIS from upstream from us (if we have one)
  280. RR->sw->requestWhois(tPtr,RR->node->now(),addr);
  281. }
  282. }
  283. if (count > 0) {
  284. outp.armor(peer->key(),true);
  285. path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  286. }
  287. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,0);
  288. return true;
  289. }
  290. ZT_ALWAYS_INLINE bool _doRENDEZVOUS(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  291. {
  292. if (RR->topology->isRoot(peer->identity())) {
  293. uint16_t junk = (uint16_t)Utils::random();
  294. const Address with(pkt.field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  295. const SharedPtr<Peer> rendezvousWith(RR->topology->get(with));
  296. if (rendezvousWith) {
  297. const unsigned int port = pkt.at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  298. const unsigned int addrlen = pkt[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  299. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  300. InetAddress atAddr(pkt.field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  301. if (rendezvousWith->shouldTryPath(tPtr,RR->node->now(),peer,atAddr)) {
  302. if (atAddr.isV4())
  303. RR->node->putPacket(tPtr,path->localSocket(),atAddr,&junk,2,2); // IPv4 "firewall opener"
  304. rendezvousWith->sendHELLO(tPtr,path->localSocket(),atAddr,RR->node->now());
  305. }
  306. }
  307. }
  308. }
  309. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,0);
  310. return true;
  311. }
  312. ZT_ALWAYS_INLINE bool _doFRAME(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  313. {
  314. const uint64_t nwid = pkt.at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  315. const SharedPtr<Network> network(RR->node->network(nwid));
  316. if (network) {
  317. if (network->gate(tPtr,peer)) {
  318. if (pkt.size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  319. const unsigned int etherType = pkt.at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  320. const MAC sourceMac(peer->address(),nwid);
  321. const unsigned int frameLen = pkt.size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  322. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(pkt.data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  323. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  324. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  325. }
  326. } else {
  327. _sendErrorNeedCredentials(pkt,RR,tPtr,peer,nwid,path);
  328. return false;
  329. }
  330. }
  331. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_FRAME,0,Packet::VERB_NOP,nwid);
  332. return true;
  333. }
  334. ZT_ALWAYS_INLINE bool _doEXT_FRAME(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  335. {
  336. const uint64_t nwid = pkt.at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  337. const SharedPtr<Network> network(RR->node->network(nwid));
  338. if (network) {
  339. const unsigned int flags = pkt[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  340. unsigned int comLen = 0;
  341. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  342. CertificateOfMembership com;
  343. comLen = com.deserialize(pkt,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  344. if (com)
  345. network->addCredential(tPtr,com);
  346. }
  347. if (!network->gate(tPtr,peer)) {
  348. RR->t->incomingNetworkAccessDenied(tPtr,network,path,pkt.packetId(),pkt.size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  349. _sendErrorNeedCredentials(pkt,RR,tPtr,peer,nwid,path);
  350. return false;
  351. }
  352. if (pkt.size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  353. const unsigned int etherType = pkt.at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  354. const MAC to(pkt.field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_TO,ZT_PROTO_VERB_EXT_FRAME_LEN_TO),ZT_PROTO_VERB_EXT_FRAME_LEN_TO);
  355. const MAC from(pkt.field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_FROM,ZT_PROTO_VERB_EXT_FRAME_LEN_FROM),ZT_PROTO_VERB_EXT_FRAME_LEN_FROM);
  356. const unsigned int frameLen = pkt.size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  357. const uint8_t *const frameData = (const uint8_t *)pkt.field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  358. if ((!from)||(from == network->mac())) {
  359. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  360. return true;
  361. }
  362. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  363. case 1:
  364. if (from != MAC(peer->address(),nwid)) {
  365. if (network->config().permitsBridging(peer->address())) {
  366. network->learnBridgeRoute(from,peer->address());
  367. } else {
  368. RR->t->incomingNetworkFrameDropped(tPtr,network,path,pkt.packetId(),pkt.size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  369. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  370. return true;
  371. }
  372. } else if (to != network->mac()) {
  373. if (to.isMulticast()) {
  374. if (network->config().multicastLimit == 0) {
  375. RR->t->incomingNetworkFrameDropped(tPtr,network,path,pkt.packetId(),pkt.size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  376. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  377. return true;
  378. }
  379. } else if (!network->config().permitsBridging(RR->identity.address())) {
  380. RR->t->incomingNetworkFrameDropped(tPtr,network,path,pkt.packetId(),pkt.size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  381. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  382. return true;
  383. }
  384. }
  385. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  386. case 2:
  387. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  388. break;
  389. }
  390. }
  391. if ((flags & 0x10U) != 0) { // ACK requested
  392. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  393. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  394. outp.append((uint64_t)pkt.packetId());
  395. outp.append((uint64_t)nwid);
  396. outp.armor(peer->key(),true);
  397. path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  398. }
  399. }
  400. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  401. return true;
  402. }
  403. ZT_ALWAYS_INLINE bool _doECHO(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  404. {
  405. if (!peer->rateGateEchoRequest(RR->node->now()))
  406. return true;
  407. const uint64_t pid = pkt.packetId();
  408. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  409. outp.append((unsigned char)Packet::VERB_ECHO);
  410. outp.append((uint64_t)pid);
  411. if (pkt.size() > ZT_PACKET_IDX_PAYLOAD)
  412. outp.append(reinterpret_cast<const unsigned char *>(pkt.data()) + ZT_PACKET_IDX_PAYLOAD,pkt.size() - ZT_PACKET_IDX_PAYLOAD);
  413. outp.armor(peer->key(),true);
  414. path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  415. peer->received(tPtr,path,pkt.hops(),pid,pkt.payloadLength(),Packet::VERB_ECHO,0,Packet::VERB_NOP,0);
  416. return true;
  417. }
  418. ZT_ALWAYS_INLINE bool _doNETWORK_CREDENTIALS(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  419. {
  420. CertificateOfMembership com;
  421. Capability cap;
  422. Tag tag;
  423. Revocation revocation;
  424. CertificateOfOwnership coo;
  425. SharedPtr<Network> network;
  426. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  427. while ((p < pkt.size())&&(pkt[p] != 0)) {
  428. p += com.deserialize(pkt,p);
  429. if (com) {
  430. network = RR->node->network(com.networkId());
  431. if (network) {
  432. if (network->addCredential(tPtr,com) == Membership::ADD_DEFERRED_FOR_WHOIS)
  433. return false;
  434. }
  435. }
  436. }
  437. ++p; // skip trailing 0 after COMs if present
  438. if (p < pkt.size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  439. const unsigned int numCapabilities = pkt.at<uint16_t>(p); p += 2;
  440. for(unsigned int i=0;i<numCapabilities;++i) {
  441. p += cap.deserialize(pkt,p);
  442. if ((!network)||(network->id() != cap.networkId()))
  443. network = RR->node->network(cap.networkId());
  444. if (network) {
  445. if (network->addCredential(tPtr,cap) == Membership::ADD_DEFERRED_FOR_WHOIS)
  446. return false;
  447. }
  448. }
  449. if (p >= pkt.size()) return true;
  450. const unsigned int numTags = pkt.at<uint16_t>(p); p += 2;
  451. for(unsigned int i=0;i<numTags;++i) {
  452. p += tag.deserialize(pkt,p);
  453. if ((!network)||(network->id() != tag.networkId()))
  454. network = RR->node->network(tag.networkId());
  455. if (network) {
  456. if (network->addCredential(tPtr,tag) == Membership::ADD_DEFERRED_FOR_WHOIS)
  457. return false;
  458. }
  459. }
  460. if (p >= pkt.size()) return true;
  461. const unsigned int numRevocations = pkt.at<uint16_t>(p); p += 2;
  462. for(unsigned int i=0;i<numRevocations;++i) {
  463. p += revocation.deserialize(pkt,p);
  464. if ((!network)||(network->id() != revocation.networkId()))
  465. network = RR->node->network(revocation.networkId());
  466. if (network) {
  467. if (network->addCredential(tPtr,peer->address(),revocation) == Membership::ADD_DEFERRED_FOR_WHOIS)
  468. return false;
  469. }
  470. }
  471. if (p >= pkt.size()) return true;
  472. const unsigned int numCoos = pkt.at<uint16_t>(p); p += 2;
  473. for(unsigned int i=0;i<numCoos;++i) {
  474. p += coo.deserialize(pkt,p);
  475. if ((!network)||(network->id() != coo.networkId()))
  476. network = RR->node->network(coo.networkId());
  477. if (network) {
  478. if (network->addCredential(tPtr,coo) == Membership::ADD_DEFERRED_FOR_WHOIS)
  479. return false;
  480. }
  481. }
  482. }
  483. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,(network) ? network->id() : 0);
  484. return true;
  485. }
  486. ZT_ALWAYS_INLINE bool _doNETWORK_CONFIG_REQUEST(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  487. {
  488. const uint64_t nwid = pkt.at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  489. const unsigned int hopCount = pkt.hops();
  490. const uint64_t requestPacketId = pkt.packetId();
  491. if (RR->localNetworkController) {
  492. const unsigned int metaDataLength = (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN <= pkt.size()) ? pkt.at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN) : 0;
  493. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)pkt.field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  494. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  495. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : path->address(),requestPacketId,peer->identity(),metaData);
  496. } else {
  497. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  498. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  499. outp.append(requestPacketId);
  500. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  501. outp.append(nwid);
  502. outp.armor(peer->key(),true);
  503. path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  504. }
  505. peer->received(tPtr,path,hopCount,requestPacketId,pkt.payloadLength(),Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,nwid);
  506. return true;
  507. }
  508. ZT_ALWAYS_INLINE bool _doNETWORK_CONFIG(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  509. {
  510. const SharedPtr<Network> network(RR->node->network(pkt.at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  511. if (network) {
  512. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,pkt.packetId(),pkt.source(),pkt,ZT_PACKET_IDX_PAYLOAD);
  513. if (configUpdateId) {
  514. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  515. outp.append((uint8_t)Packet::VERB_ECHO);
  516. outp.append((uint64_t)pkt.packetId());
  517. outp.append((uint64_t)network->id());
  518. outp.append((uint64_t)configUpdateId);
  519. outp.armor(peer->key(),true);
  520. path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  521. }
  522. }
  523. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,(network) ? network->id() : 0);
  524. return true;
  525. }
  526. ZT_ALWAYS_INLINE bool _doMULTICAST_GATHER(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  527. {
  528. const uint64_t nwid = pkt.at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  529. const unsigned int flags = pkt[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  530. const MulticastGroup mg(MAC(pkt.field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),pkt.at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  531. const unsigned int gatherLimit = pkt.at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  532. const SharedPtr<Network> network(RR->node->network(nwid));
  533. if ((flags & 0x01) != 0) {
  534. try {
  535. CertificateOfMembership com;
  536. com.deserialize(pkt,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  537. if ((com)&&(network))
  538. network->addCredential(tPtr,com);
  539. } catch ( ... ) {} // discard invalid COMs
  540. }
  541. if (network) {
  542. if (!network->gate(tPtr,peer)) {
  543. _sendErrorNeedCredentials(pkt,RR,tPtr,peer,nwid,path);
  544. return false;
  545. }
  546. }
  547. const int64_t now = RR->node->now();
  548. if (gatherLimit) {
  549. // TODO
  550. /*
  551. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  552. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  553. outp.append(packetId());
  554. outp.append(nwid);
  555. mg.mac().appendTo(outp);
  556. outp.append((uint32_t)mg.adi());
  557. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  558. if (gatheredLocally > 0) {
  559. outp.armor(peer->key(),true);
  560. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  561. }
  562. */
  563. }
  564. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,nwid);
  565. return true;
  566. }
  567. ZT_ALWAYS_INLINE bool _doPUSH_DIRECT_PATHS(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  568. {
  569. const int64_t now = RR->node->now();
  570. if (peer->rateGateInboundPushDirectPaths(now)) {
  571. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  572. memset(countPerScope,0,sizeof(countPerScope));
  573. unsigned int count = pkt.at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  574. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  575. uint16_t junk = (uint16_t)Utils::random();
  576. while (count--) {
  577. /* unsigned int flags = (*this)[ptr++]; */ ++ptr;
  578. unsigned int extLen = pkt.at<uint16_t>(ptr); ptr += 2;
  579. ptr += extLen; // unused right now
  580. unsigned int addrType = pkt[ptr++];
  581. unsigned int addrLen = pkt[ptr++];
  582. switch(addrType) {
  583. case 4: {
  584. const InetAddress a(pkt.field(ptr,4),4,pkt.at<uint16_t>(ptr + 4));
  585. if (peer->shouldTryPath(tPtr,now,peer,a)) {
  586. if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  587. RR->node->putPacket(tPtr,path->localSocket(),a,&junk,2,2); // IPv4 "firewall opener"
  588. ++junk;
  589. peer->sendHELLO(tPtr,-1,a,now);
  590. }
  591. }
  592. } break;
  593. case 6: {
  594. const InetAddress a(pkt.field(ptr,16),16,pkt.at<uint16_t>(ptr + 16));
  595. if (peer->shouldTryPath(tPtr,now,peer,a)) {
  596. if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  597. peer->sendHELLO(tPtr,-1,a,now);
  598. }
  599. } break;
  600. }
  601. ptr += addrLen;
  602. }
  603. }
  604. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,0);
  605. return true;
  606. }
  607. ZT_ALWAYS_INLINE bool _doUSER_MESSAGE(IncomingPacket &pkt,const RuntimeEnvironment *const RR,void *const tPtr,const SharedPtr<Peer> &peer,const SharedPtr<Path> &path)
  608. {
  609. if (likely(pkt.size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  610. ZT_UserMessage um;
  611. um.origin = peer->address().toInt();
  612. um.typeId = pkt.at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  613. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(pkt.data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  614. um.length = pkt.size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  615. RR->node->postEvent(tPtr,ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  616. }
  617. peer->received(tPtr,path,pkt.hops(),pkt.packetId(),pkt.payloadLength(),Packet::VERB_USER_MESSAGE,0,Packet::VERB_NOP,0);
  618. return true;
  619. }
  620. //////////////////////////////////////////////////////////////////////////////
  621. } // anonymous namespace
  622. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr)
  623. {
  624. const Address sourceAddress(source());
  625. try {
  626. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  627. const unsigned int c = cipher();
  628. bool trusted = false;
  629. if (c == ZT_PROTO_CIPHER_SUITE__NONE) {
  630. // If this is marked as a packet via a trusted path, check source address and path ID.
  631. // Obviously if no trusted paths are configured this always returns false and such
  632. // packets are dropped on the floor.
  633. const uint64_t tpid = trustedPathId();
  634. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),tpid)) {
  635. trusted = true;
  636. } else {
  637. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"path not trusted");
  638. return true;
  639. }
  640. } else if ((c == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  641. // Only HELLO is allowed in the clear, but will still have a MAC
  642. return _doHELLO(*this,RR,tPtr,false,_path);
  643. }
  644. const SharedPtr<Peer> peer(RR->topology->get(sourceAddress));
  645. if (peer) {
  646. if (!trusted) {
  647. if (!dearmor(peer->key())) {
  648. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"invalid MAC");
  649. return true;
  650. }
  651. }
  652. if (!uncompress()) {
  653. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),Packet::VERB_NOP,"LZ4 decompression failed");
  654. return true;
  655. }
  656. const Packet::Verb v = verb();
  657. bool r = true;
  658. switch(v) {
  659. //case Packet::VERB_NOP:
  660. default: // ignore unknown verbs, but if they pass auth check they are "received"
  661. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),v,0,Packet::VERB_NOP,0);
  662. break;
  663. case Packet::VERB_HELLO: r = _doHELLO(*this,RR,tPtr,true,_path); break;
  664. case Packet::VERB_ERROR: r = _doERROR(*this,RR,tPtr,peer,_path); break;
  665. case Packet::VERB_OK: r = _doOK(*this,RR,tPtr,peer,_path); break;
  666. case Packet::VERB_WHOIS: r = _doWHOIS(*this,RR,tPtr,peer,_path); break;
  667. case Packet::VERB_RENDEZVOUS: r = _doRENDEZVOUS(*this,RR,tPtr,peer,_path); break;
  668. case Packet::VERB_FRAME: r = _doFRAME(*this,RR,tPtr,peer,_path); break;
  669. case Packet::VERB_EXT_FRAME: r = _doEXT_FRAME(*this,RR,tPtr,peer,_path); break;
  670. case Packet::VERB_ECHO: r = _doECHO(*this,RR,tPtr,peer,_path); break;
  671. case Packet::VERB_NETWORK_CREDENTIALS: r = _doNETWORK_CREDENTIALS(*this,RR,tPtr,peer,_path); break;
  672. case Packet::VERB_NETWORK_CONFIG_REQUEST: r = _doNETWORK_CONFIG_REQUEST(*this,RR,tPtr,peer,_path); break;
  673. case Packet::VERB_NETWORK_CONFIG: r = _doNETWORK_CONFIG(*this,RR,tPtr,peer,_path); break;
  674. case Packet::VERB_MULTICAST_GATHER: r = _doMULTICAST_GATHER(*this,RR,tPtr,peer,_path); break;
  675. case Packet::VERB_PUSH_DIRECT_PATHS: r = _doPUSH_DIRECT_PATHS(*this,RR,tPtr,peer,_path); break;
  676. case Packet::VERB_USER_MESSAGE: r = _doUSER_MESSAGE(*this,RR,tPtr,peer,_path); break;
  677. }
  678. return r;
  679. } else {
  680. RR->sw->requestWhois(tPtr,RR->node->now(),sourceAddress);
  681. return false;
  682. }
  683. } catch (int ztExcCode) {
  684. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  685. return true;
  686. } catch ( ... ) {
  687. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  688. return true;
  689. }
  690. }
  691. } // namespace ZeroTier