root.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include "../node/Constants.hpp"
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <unistd.h>
  30. #include <string.h>
  31. #include <fcntl.h>
  32. #include <signal.h>
  33. #include <sys/stat.h>
  34. #include <sys/types.h>
  35. #include <sys/socket.h>
  36. #include <sys/select.h>
  37. #include <sys/time.h>
  38. #include <sys/un.h>
  39. #include <sys/ioctl.h>
  40. #include <arpa/inet.h>
  41. #include <netinet/in.h>
  42. #include <netinet/ip.h>
  43. #include <netinet/ip6.h>
  44. #include <netinet/tcp.h>
  45. #include "../node/Packet.hpp"
  46. #include "../node/Utils.hpp"
  47. #include "../node/Address.hpp"
  48. #include "../node/Identity.hpp"
  49. #include "../node/InetAddress.hpp"
  50. #include "../node/Mutex.hpp"
  51. #include "../node/SharedPtr.hpp"
  52. #include "../node/MulticastGroup.hpp"
  53. #include "../osdep/OSUtils.hpp"
  54. #include <string>
  55. #include <thread>
  56. #include <map>
  57. #include <set>
  58. #include <vector>
  59. #include <iostream>
  60. #include <unordered_map>
  61. #include <vector>
  62. #include <atomic>
  63. #include <mutex>
  64. using namespace ZeroTier;
  65. struct IdentityHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Identity &id) const { return (std::size_t)id.hashCode(); } };
  66. struct AddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const Address &a) const { return (std::size_t)a.toInt(); } };
  67. struct InetAddressHasher { ZT_ALWAYS_INLINE std::size_t operator()(const InetAddress &ip) const { return (std::size_t)ip.hashCode(); } };
  68. struct MulticastGroupHasher { ZT_ALWAYS_INLINE std::size_t operator()(const MulticastGroup &mg) const { return (std::size_t)mg.hashCode(); } };
  69. struct PeerInfo
  70. {
  71. Identity id;
  72. uint8_t key[32];
  73. InetAddress ip4,ip6;
  74. int64_t lastReceive;
  75. std::unordered_map< uint64_t,std::unordered_map< MulticastGroup,int64_t,MulticastGroupHasher > > multicastGroups;
  76. Mutex multicastGroups_l;
  77. AtomicCounter __refCount;
  78. ZT_ALWAYS_INLINE ~PeerInfo() { Utils::burn(key,sizeof(key)); }
  79. };
  80. static Identity self;
  81. static std::atomic_bool run;
  82. static std::vector< SharedPtr<PeerInfo> > newPeers;
  83. static std::unordered_map< Identity,SharedPtr<PeerInfo>,IdentityHasher > peersByIdentity;
  84. static std::unordered_map< Address,std::set< SharedPtr<PeerInfo> >,AddressHasher > peersByVirtAddr;
  85. static std::unordered_map< InetAddress,std::set< SharedPtr<PeerInfo> >,InetAddressHasher > peersByPhysAddr;
  86. static std::mutex newPeers_l;
  87. static std::mutex peersByIdentity_l;
  88. static std::mutex peersByVirtAddr_l;
  89. static std::mutex peersByPhysAddr_l;
  90. static void handlePacket(const int sock,const InetAddress *const ip,Packet &pkt)
  91. {
  92. char ipstr[128],ipstr2[128],astr[32],tmpstr[256];
  93. const bool fragment = pkt[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR;
  94. // See if this is destined for us and isn't a fragment / fragmented. (No packets
  95. // understood by the root are fragments/fragmented.)
  96. if ((!fragment)&&(!pkt.fragmented())&&(pkt.destination() == self.address())) {
  97. SharedPtr<PeerInfo> peer;
  98. // If this is an un-encrypted HELLO, either learn a new peer or verify
  99. // that this is a peer we already know.
  100. if ((pkt.cipher() == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(pkt.verb() == Packet::VERB_HELLO)) {
  101. Identity id;
  102. if (id.deserialize(pkt,ZT_PROTO_VERB_HELLO_IDX_IDENTITY)) {
  103. {
  104. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  105. auto pById = peersByIdentity.find(id);
  106. if (pById != peersByIdentity.end()) {
  107. peer = pById->second;
  108. //printf("%s has %s (known (1))" ZT_EOL_S,ip->toString(ipstr),pkt.source().toString(astr));
  109. }
  110. }
  111. if (peer) {
  112. if (!pkt.dearmor(peer->key)) {
  113. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  114. return;
  115. }
  116. } else {
  117. peer.set(new PeerInfo);
  118. if (self.agree(id,peer->key)) {
  119. if (pkt.dearmor(peer->key)) {
  120. peer->id = id;
  121. {
  122. std::lock_guard<std::mutex> np_l(newPeers_l);
  123. newPeers.push_back(peer);
  124. }
  125. {
  126. std::lock_guard<std::mutex> pbi_l(peersByIdentity_l);
  127. peersByIdentity.emplace(id,peer);
  128. }
  129. {
  130. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  131. peersByVirtAddr[id.address()].emplace(peer);
  132. }
  133. } else {
  134. printf("%s HELLO rejected: packet authentication failed" ZT_EOL_S,ip->toString(ipstr));
  135. return;
  136. }
  137. } else {
  138. printf("%s HELLO rejected: key agreement failed" ZT_EOL_S,ip->toString(ipstr));
  139. return;
  140. }
  141. }
  142. }
  143. }
  144. // If it wasn't a HELLO, check to see if any known identities for the sender's
  145. // short ZT address successfully decrypt the packet.
  146. if (!peer) {
  147. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  148. auto peers = peersByVirtAddr.find(pkt.source());
  149. if (peers != peersByVirtAddr.end()) {
  150. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  151. if (pkt.dearmor((*p)->key)) {
  152. peer = (*p);
  153. //printf("%s has %s (known (2))" ZT_EOL_S,ip->toString(ipstr),pkt.source().toString(astr));
  154. break;
  155. }
  156. }
  157. }
  158. }
  159. // If we found the peer, update IP and/or time.
  160. if (peer) {
  161. InetAddress *const peerIp = (ip->ss_family == AF_INET) ? &(peer->ip4) : &(peer->ip6);
  162. if (*peerIp != ip) {
  163. std::lock_guard<std::mutex> pbp_l(peersByPhysAddr_l);
  164. if (*peerIp) {
  165. auto prev = peersByPhysAddr.find(*peerIp);
  166. if (prev != peersByPhysAddr.end()) {
  167. prev->second.erase(peer);
  168. if (prev->second.empty())
  169. peersByPhysAddr.erase(prev);
  170. }
  171. }
  172. *peerIp = ip;
  173. peersByPhysAddr[ip].emplace(peer);
  174. }
  175. const int64_t now = OSUtils::now();
  176. peer->lastReceive = now;
  177. switch(pkt.verb()) {
  178. case Packet::VERB_HELLO: {
  179. const uint64_t origId = pkt.packetId();
  180. const uint64_t ts = pkt.template at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  181. pkt.reset(pkt.source(),self.address(),Packet::VERB_OK);
  182. pkt.append((uint8_t)Packet::VERB_HELLO);
  183. pkt.append(origId);
  184. pkt.append(ts);
  185. pkt.append((uint8_t)ZT_PROTO_VERSION);
  186. pkt.append((uint16_t)1);
  187. pkt.append((uint16_t)9);
  188. pkt.append((uint16_t)0);
  189. ip->serialize(pkt);
  190. pkt.armor(peer->key,true);
  191. //sendto(sock,pkt.data(),pkt.size(),0,(const struct sockaddr *)ip,(socklen_t)((ip->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  192. } break;
  193. case Packet::VERB_MULTICAST_LIKE: {
  194. printf("LIKE\n");
  195. Mutex::Lock l(peer->multicastGroups_l);
  196. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<pkt.size();ptr+=18) {
  197. const uint64_t nwid = pkt.template at<uint64_t>(ptr);
  198. const MulticastGroup mg(MAC(pkt.field(ptr + 8,6),6),pkt.template at<uint32_t>(ptr + 14));
  199. peer->multicastGroups[nwid][mg] = now;
  200. printf("%s subscribes to %s/%.8lx on network %.16llx",ip->toString(ipstr),mg.mac().toString(tmpstr),(unsigned long)mg.adi(),(unsigned long long)nwid);
  201. }
  202. } break;
  203. case Packet::VERB_MULTICAST_GATHER: {
  204. } break;
  205. default:
  206. break;
  207. }
  208. return;
  209. }
  210. }
  211. std::vector<InetAddress> toAddrs;
  212. {
  213. std::lock_guard<std::mutex> pbv_l(peersByVirtAddr_l);
  214. auto peers = peersByVirtAddr.find(pkt.destination());
  215. if (peers != peersByVirtAddr.end()) {
  216. for(auto p=peers->second.begin();p!=peers->second.end();++p) {
  217. if ((*p)->ip6)
  218. toAddrs.push_back((*p)->ip6);
  219. else if ((*p)->ip4)
  220. toAddrs.push_back((*p)->ip4);
  221. }
  222. }
  223. }
  224. if (toAddrs.empty()) {
  225. printf("%s not forwarding to %s: no destinations found" ZT_EOL_S,ip->toString(ipstr),pkt.destination().toString(astr));
  226. return;
  227. }
  228. if (fragment) {
  229. if (reinterpret_cast<Packet::Fragment *>(&pkt)->incrementHops() >= ZT_PROTO_MAX_HOPS) {
  230. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),pkt.destination().toString(astr));
  231. return;
  232. }
  233. } else {
  234. if (pkt.incrementHops() >= ZT_PROTO_MAX_HOPS) {
  235. printf("%s refused to forward to %s: max hop count exceeded" ZT_EOL_S,ip->toString(ipstr),pkt.destination().toString(astr));
  236. return;
  237. }
  238. }
  239. for(auto i=toAddrs.begin();i!=toAddrs.end();++i) {
  240. printf("%s -> %s for %s" ZT_EOL_S,ip->toString(ipstr),i->toString(ipstr2),pkt.destination().toString(astr));
  241. //sendto(sock,pkt.data(),pkt.size(),0,(const struct sockaddr *)&(*i),(socklen_t)((i->ss_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)));
  242. }
  243. }
  244. static int bindSocket(struct sockaddr *bindAddr)
  245. {
  246. int s = socket(bindAddr->sa_family,SOCK_DGRAM,0);
  247. if (s < 0) {
  248. close(s);
  249. return -1;
  250. }
  251. int f = 131072;
  252. setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&f,sizeof(f));
  253. f = 131072;
  254. setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&f,sizeof(f));
  255. if (bindAddr->sa_family == AF_INET6) {
  256. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  257. #ifdef IPV6_MTU_DISCOVER
  258. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  259. #endif
  260. #ifdef IPV6_DONTFRAG
  261. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  262. #endif
  263. }
  264. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  265. f = 1; setsockopt(s,SOL_SOCKET,SO_REUSEPORT,(void *)&f,sizeof(f));
  266. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  267. #ifdef IP_DONTFRAG
  268. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  269. #endif
  270. #ifdef IP_MTU_DISCOVER
  271. f = IP_PMTUDISC_DONT; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  272. #endif
  273. #ifdef SO_NO_CHECK
  274. if (bindAddr->sa_family == AF_INET) {
  275. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  276. }
  277. #endif
  278. if (bind(s,bindAddr,(bindAddr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
  279. close(s);
  280. return -1;
  281. }
  282. return s;
  283. }
  284. void shutdownSigHandler(int sig)
  285. {
  286. run = false;
  287. }
  288. int main(int argc,char **argv)
  289. {
  290. signal(SIGTERM,shutdownSigHandler);
  291. signal(SIGINT,shutdownSigHandler);
  292. signal(SIGQUIT,shutdownSigHandler);
  293. signal(SIGPIPE,SIG_IGN);
  294. signal(SIGUSR1,SIG_IGN);
  295. signal(SIGUSR2,SIG_IGN);
  296. if (argc < 2) {
  297. printf("Usage: zerotier-root <identity.secret> [<port>]" ZT_EOL_S);
  298. return 1;
  299. }
  300. std::string myIdStr;
  301. if (!OSUtils::readFile(argv[1],myIdStr)) {
  302. printf("FATAL: cannot read identity.secret at %s" ZT_EOL_S,argv[1]);
  303. return 1;
  304. }
  305. if (!self.fromString(myIdStr.c_str())) {
  306. printf("FATAL: cannot read identity.secret at %s (invalid identity)" ZT_EOL_S,argv[1]);
  307. return 1;
  308. }
  309. if (!self.hasPrivate()) {
  310. printf("FATAL: cannot read identity.secret at %s (missing secret key)" ZT_EOL_S,argv[1]);
  311. return 1;
  312. }
  313. unsigned int ncores = std::thread::hardware_concurrency();
  314. if (ncores == 0) ncores = 1;
  315. run = true;
  316. std::vector<int> sockets;
  317. std::vector<std::thread> threads;
  318. for(unsigned int tn=0;tn<ncores;++tn) {
  319. struct sockaddr_in6 in6;
  320. memset(&in6,0,sizeof(in6));
  321. in6.sin6_family = AF_INET6;
  322. in6.sin6_port = htons(ZT_DEFAULT_PORT);
  323. const int s6 = bindSocket((struct sockaddr *)&in6);
  324. if (s6 < 0) {
  325. std::cout << "ERROR: unable to bind to port " << ZT_DEFAULT_PORT << ZT_EOL_S;
  326. exit(1);
  327. }
  328. struct sockaddr_in in4;
  329. memset(&in4,0,sizeof(in4));
  330. in4.sin_family = AF_INET;
  331. in4.sin_port = htons(ZT_DEFAULT_PORT);
  332. const int s4 = bindSocket((struct sockaddr *)&in4);
  333. if (s4 < 0) {
  334. std::cout << "ERROR: unable to bind to port " << ZT_DEFAULT_PORT << ZT_EOL_S;
  335. exit(1);
  336. }
  337. sockets.push_back(s6);
  338. sockets.push_back(s4);
  339. threads.push_back(std::thread([s6]() {
  340. struct sockaddr_in6 in6;
  341. Packet pkt;
  342. memset(&in6,0,sizeof(in6));
  343. for(;;) {
  344. socklen_t sl = sizeof(in6);
  345. const int pl = (int)recvfrom(s6,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in6,&sl);
  346. if (pl > 0) {
  347. try {
  348. pkt.setSize((unsigned int)pl);
  349. handlePacket(s6,reinterpret_cast<const InetAddress *>(&in6),pkt);
  350. } catch ( ... ) {
  351. printf("* unexpected exception" ZT_EOL_S);
  352. }
  353. } else {
  354. break;
  355. }
  356. }
  357. }));
  358. threads.push_back(std::thread([s4]() {
  359. struct sockaddr_in in4;
  360. Packet pkt;
  361. memset(&in4,0,sizeof(in4));
  362. for(;;) {
  363. socklen_t sl = sizeof(in4);
  364. const int pl = (int)recvfrom(s4,pkt.unsafeData(),pkt.capacity(),0,(struct sockaddr *)&in4,&sl);
  365. if (pl > 0) {
  366. try {
  367. pkt.setSize((unsigned int)pl);
  368. handlePacket(s4,reinterpret_cast<const InetAddress *>(&in4),pkt);
  369. } catch ( ... ) {
  370. printf("* unexpected exception" ZT_EOL_S);
  371. }
  372. } else {
  373. break;
  374. }
  375. }
  376. }));
  377. }
  378. while (run) {
  379. peersByIdentity_l.lock();
  380. printf("* have %lu peers" ZT_EOL_S,(unsigned long)peersByIdentity.size());
  381. peersByIdentity_l.unlock();
  382. sleep(1);
  383. }
  384. for(auto s=sockets.begin();s!=sockets.end();++s) {
  385. shutdown(*s,SHUT_RDWR);
  386. close(*s);
  387. }
  388. for(auto t=threads.begin();t!=threads.end();++t)
  389. t->join();
  390. return 0;
  391. }