tcp-proxy.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. // HACK! Will eventually use epoll() or something in Phy<> instead of select().
  19. // Also be sure to change ulimit -n and fs.file-max in /etc/sysctl.conf on relays.
  20. #if defined(__linux__) || defined(__LINUX__) || defined(__LINUX) || defined(LINUX)
  21. #include <linux/posix_types.h>
  22. #include <bits/types.h>
  23. #undef __FD_SETSIZE
  24. #define __FD_SETSIZE 1048576
  25. #undef FD_SETSIZE
  26. #define FD_SETSIZE 1048576
  27. #endif
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <time.h>
  32. #include <stdint.h>
  33. #include <unistd.h>
  34. #include <signal.h>
  35. #include <map>
  36. #include <set>
  37. #include <string>
  38. #include <algorithm>
  39. #include <vector>
  40. #include "../osdep/Phy.hpp"
  41. #include "../osdep/OSUtils.hpp"
  42. #include "Metrics.hpp"
  43. #define ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS 300
  44. #define ZT_TCP_PROXY_TCP_PORT 443
  45. #define HOMEDIR "/var/lib/zt-tcp-proxy"
  46. using namespace ZeroTier;
  47. /*
  48. * ZeroTier TCP Proxy Server
  49. *
  50. * This implements a simple packet encapsulation that is designed to look like
  51. * a TLS connection. It's not a TLS connection, but it sends TLS format record
  52. * headers. It could be extended in the future to implement a fake TLS
  53. * handshake.
  54. *
  55. * At the moment, each packet is just made to look like TLS application data:
  56. * <[1] TLS content type> - currently 0x17 for "application data"
  57. * <[1] TLS major version> - currently 0x03 for TLS 1.2
  58. * <[1] TLS minor version> - currently 0x03 for TLS 1.2
  59. * <[2] payload length> - 16-bit length of payload in bytes
  60. * <[...] payload> - Message payload
  61. *
  62. * TCP is inherently inefficient for encapsulating Ethernet, since TCP and TCP
  63. * like protocols over TCP lead to double-ACKs. So this transport is only used
  64. * to enable access when UDP or other datagram protocols are not available.
  65. *
  66. * Clients send a greeting, which is a four-byte message that contains:
  67. * <[1] ZeroTier major version>
  68. * <[1] minor version>
  69. * <[2] revision>
  70. *
  71. * If a client has sent a greeting, it uses the new version of this protocol
  72. * in which every encapsulated ZT packet is prepended by an IP address where
  73. * it should be forwarded (or where it came from for replies). This causes
  74. * this proxy to act as a remote UDP socket similar to a socks proxy, which
  75. * will allow us to move this function off the rootservers and onto dedicated
  76. * proxy nodes.
  77. *
  78. * Older ZT clients that do not send this message get their packets relayed
  79. * to/from 127.0.0.1:9993, which will allow them to talk to and relay via
  80. * the ZT node on the same machine as the proxy. We'll only support this for
  81. * as long as such nodes appear to be in the wild.
  82. */
  83. struct TcpProxyService;
  84. struct TcpProxyService
  85. {
  86. Phy<TcpProxyService *> *phy;
  87. int udpPortCounter;
  88. struct Client
  89. {
  90. char tcpReadBuf[131072];
  91. char tcpWriteBuf[131072];
  92. unsigned long tcpWritePtr;
  93. unsigned long tcpReadPtr;
  94. PhySocket *tcp;
  95. PhySocket *udp;
  96. time_t lastActivity;
  97. bool newVersion;
  98. };
  99. std::map< PhySocket *,Client > clients;
  100. PhySocket *getUnusedUdp(void *uptr)
  101. {
  102. for(int i=0;i<65535;++i) {
  103. ++udpPortCounter;
  104. if (udpPortCounter > 0xfffe)
  105. udpPortCounter = 1024;
  106. struct sockaddr_in laddr;
  107. memset(&laddr,0,sizeof(struct sockaddr_in));
  108. laddr.sin_family = AF_INET;
  109. laddr.sin_port = htons((uint16_t)udpPortCounter);
  110. PhySocket *udp = phy->udpBind(reinterpret_cast<struct sockaddr *>(&laddr),uptr);
  111. if (udp)
  112. return udp;
  113. }
  114. return (PhySocket *)0;
  115. }
  116. void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  117. {
  118. if (!*uptr)
  119. return;
  120. if ((from->sa_family == AF_INET)&&(len >= 16)&&(len < 2048)) {
  121. // Metrics::udp_bytes_in += len;
  122. Client &c = *((Client *)*uptr);
  123. c.lastActivity = time((time_t *)0);
  124. unsigned long mlen = len;
  125. if (c.newVersion)
  126. mlen += 7; // new clients get IP info
  127. if ((c.tcpWritePtr + 5 + mlen) <= sizeof(c.tcpWriteBuf)) {
  128. if (!c.tcpWritePtr)
  129. phy->setNotifyWritable(c.tcp,true);
  130. c.tcpWriteBuf[c.tcpWritePtr++] = 0x17; // look like TLS data
  131. c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
  132. c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
  133. c.tcpWriteBuf[c.tcpWritePtr++] = (char)((mlen >> 8) & 0xff);
  134. c.tcpWriteBuf[c.tcpWritePtr++] = (char)(mlen & 0xff);
  135. if (c.newVersion) {
  136. c.tcpWriteBuf[c.tcpWritePtr++] = (char)4; // IPv4
  137. *((uint32_t *)(c.tcpWriteBuf + c.tcpWritePtr)) = ((const struct sockaddr_in *)from)->sin_addr.s_addr;
  138. c.tcpWritePtr += 4;
  139. *((uint16_t *)(c.tcpWriteBuf + c.tcpWritePtr)) = ((const struct sockaddr_in *)from)->sin_port;
  140. c.tcpWritePtr += 2;
  141. }
  142. for(unsigned long i=0;i<len;++i)
  143. c.tcpWriteBuf[c.tcpWritePtr++] = ((const char *)data)[i];
  144. }
  145. printf("<< UDP %s:%d -> %.16llx\n",inet_ntoa(reinterpret_cast<const struct sockaddr_in *>(from)->sin_addr),(int)ntohs(reinterpret_cast<const struct sockaddr_in *>(from)->sin_port),(unsigned long long)&c);
  146. }
  147. }
  148. void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  149. {
  150. // unused, we don't initiate outbound connections
  151. }
  152. void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  153. {
  154. Client &c = clients[sockN];
  155. PhySocket *udp = getUnusedUdp((void *)&c);
  156. if (!udp) {
  157. // Metrics::udp_open_failed++;
  158. phy->close(sockN);
  159. clients.erase(sockN);
  160. printf("** TCP rejected, no more UDP ports to assign\n");
  161. return;
  162. }
  163. c.tcpWritePtr = 0;
  164. c.tcpReadPtr = 0;
  165. c.tcp = sockN;
  166. c.udp = udp;
  167. c.lastActivity = time((time_t *)0);
  168. c.newVersion = false;
  169. *uptrN = (void *)&c;
  170. printf("<< TCP from %s -> %.16llx\n",inet_ntoa(reinterpret_cast<const struct sockaddr_in *>(from)->sin_addr),(unsigned long long)&c);
  171. // Metrics::tcp_opened++;
  172. // Metrics::tcp_connections++;
  173. }
  174. void phyOnTcpClose(PhySocket *sock,void **uptr)
  175. {
  176. if (!*uptr)
  177. return;
  178. Client &c = *((Client *)*uptr);
  179. phy->close(c.udp);
  180. clients.erase(sock);
  181. printf("** TCP %.16llx closed\n",(unsigned long long)*uptr);
  182. // Metrics::tcp_closed++;
  183. }
  184. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  185. {
  186. Client &c = *((Client *)*uptr);
  187. c.lastActivity = time((time_t *)0);
  188. // Metrics::tcp_bytes_in += len;
  189. for(unsigned long i=0;i<len;++i) {
  190. if (c.tcpReadPtr >= sizeof(c.tcpReadBuf)) {
  191. phy->close(sock);
  192. return;
  193. }
  194. c.tcpReadBuf[c.tcpReadPtr++] = ((const char *)data)[i];
  195. if (c.tcpReadPtr >= 5) {
  196. unsigned long mlen = ( ((((unsigned long)c.tcpReadBuf[3]) & 0xff) << 8) | (((unsigned long)c.tcpReadBuf[4]) & 0xff) );
  197. if (c.tcpReadPtr >= (mlen + 5)) {
  198. if (mlen == 4) {
  199. // Right now just sending this means the client is 'new enough' for the IP header
  200. c.newVersion = true;
  201. printf("<< TCP %.16llx HELLO\n",(unsigned long long)*uptr);
  202. } else if (mlen >= 7) {
  203. char *payload = c.tcpReadBuf + 5;
  204. unsigned long payloadLen = mlen;
  205. struct sockaddr_in dest;
  206. memset(&dest,0,sizeof(dest));
  207. if (c.newVersion) {
  208. if (*payload == (char)4) {
  209. // New clients tell us where their packets go.
  210. ++payload;
  211. dest.sin_family = AF_INET;
  212. dest.sin_addr.s_addr = *((uint32_t *)payload);
  213. payload += 4;
  214. dest.sin_port = *((uint16_t *)payload); // will be in network byte order already
  215. payload += 2;
  216. payloadLen -= 7;
  217. }
  218. } else {
  219. // For old clients we will just proxy everything to a local ZT instance. The
  220. // fact that this will come from 127.0.0.1 will in turn prevent that instance
  221. // from doing unite() with us. It'll just forward. There will not be many of
  222. // these.
  223. dest.sin_family = AF_INET;
  224. dest.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
  225. dest.sin_port = htons(9993);
  226. }
  227. // Note: we do not relay to privileged ports... just an abuse prevention rule.
  228. if ((ntohs(dest.sin_port) > 1024)&&(payloadLen >= 16)) {
  229. phy->udpSend(c.udp,(const struct sockaddr *)&dest,payload,payloadLen);
  230. printf(">> TCP %.16llx to %s:%d\n",(unsigned long long)*uptr,inet_ntoa(dest.sin_addr),(int)ntohs(dest.sin_port));
  231. // Metrics::udp_bytes_out += payloadLen;
  232. }
  233. }
  234. memmove(c.tcpReadBuf,c.tcpReadBuf + (mlen + 5),c.tcpReadPtr -= (mlen + 5));
  235. }
  236. }
  237. }
  238. }
  239. void phyOnTcpWritable(PhySocket *sock,void **uptr)
  240. {
  241. Client &c = *((Client *)*uptr);
  242. if (c.tcpWritePtr) {
  243. long n = phy->streamSend(sock,c.tcpWriteBuf,c.tcpWritePtr);
  244. if (n > 0) {
  245. // Metrics::tcp_bytes_out += n;
  246. memmove(c.tcpWriteBuf,c.tcpWriteBuf + n,c.tcpWritePtr -= (unsigned long)n);
  247. if (!c.tcpWritePtr)
  248. phy->setNotifyWritable(sock,false);
  249. }
  250. } else phy->setNotifyWritable(sock,false);
  251. }
  252. void doHousekeeping()
  253. {
  254. std::vector<PhySocket *> toClose;
  255. time_t now = time((time_t *)0);
  256. for(std::map< PhySocket *,Client >::iterator c(clients.begin());c!=clients.end();++c) {
  257. if ((now - c->second.lastActivity) >= ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS) {
  258. toClose.push_back(c->first);
  259. toClose.push_back(c->second.udp);
  260. }
  261. }
  262. for(std::vector<PhySocket *>::iterator s(toClose.begin());s!=toClose.end();++s) {
  263. phy->close(*s);
  264. // Metrics::tcp_closed++;
  265. // Metrics::tcp_connections--;
  266. }
  267. }
  268. };
  269. int main(int argc,char **argv)
  270. {
  271. signal(SIGPIPE,SIG_IGN);
  272. signal(SIGHUP,SIG_IGN);
  273. srand(time((time_t *)0));
  274. // if (!OSUtils::fileExists(HOMEDIR)) {
  275. // if (!OSUtils::mkdir(HOMEDIR)) {
  276. // fprintf(stderr,"%s: fatal error: unable to create %s\n",argv[0],HOMEDIR);
  277. // return 1;
  278. // }
  279. // }
  280. // prometheus::simpleapi::saver.set_registry(prometheus::simpleapi::registry_ptr);
  281. // prometheus::simpleapi::saver.set_delay(std::chrono::seconds(5));
  282. // prometheus::simpleapi::saver.set_out_file(HOMEDIR "/metrics.json");
  283. TcpProxyService svc;
  284. Phy<TcpProxyService *> phy(&svc,false,true);
  285. svc.phy = &phy;
  286. svc.udpPortCounter = 1023;
  287. uint16_t listenPort = ZT_TCP_PROXY_TCP_PORT;
  288. if (argc > 1) {
  289. listenPort = (uint16_t)atoi(argv[1]);
  290. }
  291. if (listenPort == 0) {
  292. fprintf(stderr,"%s: fatal error: invalid port number\n",argv[0]);
  293. return 1;
  294. }
  295. {
  296. struct sockaddr_in laddr;
  297. memset(&laddr,0,sizeof(laddr));
  298. laddr.sin_family = AF_INET;
  299. laddr.sin_port = htons(listenPort);
  300. if (!phy.tcpListen((const struct sockaddr *)&laddr)) {
  301. fprintf(stderr,"%s: fatal error: unable to bind TCP port %d\n",argv[0],ZT_TCP_PROXY_TCP_PORT);
  302. return 1;
  303. }
  304. }
  305. time_t lastDidHousekeeping = time((time_t *)0);
  306. for(;;) {
  307. phy.poll(120000);
  308. time_t now = time((time_t *)0);
  309. if ((now - lastDidHousekeeping) > 120) {
  310. lastDidHousekeeping = now;
  311. svc.doHousekeeping();
  312. }
  313. }
  314. return 0;
  315. }