tcp-proxy.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. #define ZT_NO_METRICS 1
  41. #include "../osdep/Phy.hpp"
  42. #ifndef ZT_NO_METRICS
  43. #include "../node/Metrics.hpp"
  44. #endif
  45. #define ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS 300
  46. #define ZT_TCP_PROXY_TCP_PORT 443
  47. using namespace ZeroTier;
  48. /*
  49. * ZeroTier TCP Proxy Server
  50. *
  51. * This implements a simple packet encapsulation that is designed to look like
  52. * a TLS connection. It's not a TLS connection, but it sends TLS format record
  53. * headers. It could be extended in the future to implement a fake TLS
  54. * handshake.
  55. *
  56. * At the moment, each packet is just made to look like TLS application data:
  57. * <[1] TLS content type> - currently 0x17 for "application data"
  58. * <[1] TLS major version> - currently 0x03 for TLS 1.2
  59. * <[1] TLS minor version> - currently 0x03 for TLS 1.2
  60. * <[2] payload length> - 16-bit length of payload in bytes
  61. * <[...] payload> - Message payload
  62. *
  63. * TCP is inherently inefficient for encapsulating Ethernet, since TCP and TCP
  64. * like protocols over TCP lead to double-ACKs. So this transport is only used
  65. * to enable access when UDP or other datagram protocols are not available.
  66. *
  67. * Clients send a greeting, which is a four-byte message that contains:
  68. * <[1] ZeroTier major version>
  69. * <[1] minor version>
  70. * <[2] revision>
  71. *
  72. * If a client has sent a greeting, it uses the new version of this protocol
  73. * in which every encapsulated ZT packet is prepended by an IP address where
  74. * it should be forwarded (or where it came from for replies). This causes
  75. * this proxy to act as a remote UDP socket similar to a socks proxy, which
  76. * will allow us to move this function off the rootservers and onto dedicated
  77. * proxy nodes.
  78. *
  79. * Older ZT clients that do not send this message get their packets relayed
  80. * to/from 127.0.0.1:9993, which will allow them to talk to and relay via
  81. * the ZT node on the same machine as the proxy. We'll only support this for
  82. * as long as such nodes appear to be in the wild.
  83. */
  84. struct TcpProxyService;
  85. struct TcpProxyService
  86. {
  87. Phy<TcpProxyService *> *phy;
  88. int udpPortCounter;
  89. struct Client
  90. {
  91. char tcpReadBuf[131072];
  92. char tcpWriteBuf[131072];
  93. unsigned long tcpWritePtr;
  94. unsigned long tcpReadPtr;
  95. PhySocket *tcp;
  96. PhySocket *udp;
  97. time_t lastActivity;
  98. bool newVersion;
  99. };
  100. std::map< PhySocket *,Client > clients;
  101. PhySocket *getUnusedUdp(void *uptr)
  102. {
  103. for(int i=0;i<65535;++i) {
  104. ++udpPortCounter;
  105. if (udpPortCounter > 0xfffe)
  106. udpPortCounter = 1024;
  107. struct sockaddr_in laddr;
  108. memset(&laddr,0,sizeof(struct sockaddr_in));
  109. laddr.sin_family = AF_INET;
  110. laddr.sin_port = htons((uint16_t)udpPortCounter);
  111. PhySocket *udp = phy->udpBind(reinterpret_cast<struct sockaddr *>(&laddr),uptr);
  112. if (udp)
  113. return udp;
  114. }
  115. return (PhySocket *)0;
  116. }
  117. void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  118. {
  119. if (!*uptr)
  120. return;
  121. if ((from->sa_family == AF_INET)&&(len >= 16)&&(len < 2048)) {
  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. phy->close(sockN);
  158. clients.erase(sockN);
  159. printf("** TCP rejected, no more UDP ports to assign\n");
  160. return;
  161. }
  162. c.tcpWritePtr = 0;
  163. c.tcpReadPtr = 0;
  164. c.tcp = sockN;
  165. c.udp = udp;
  166. c.lastActivity = time((time_t *)0);
  167. c.newVersion = false;
  168. *uptrN = (void *)&c;
  169. printf("<< TCP from %s -> %.16llx\n",inet_ntoa(reinterpret_cast<const struct sockaddr_in *>(from)->sin_addr),(unsigned long long)&c);
  170. }
  171. void phyOnTcpClose(PhySocket *sock,void **uptr)
  172. {
  173. if (!*uptr)
  174. return;
  175. Client &c = *((Client *)*uptr);
  176. phy->close(c.udp);
  177. clients.erase(sock);
  178. printf("** TCP %.16llx closed\n",(unsigned long long)*uptr);
  179. }
  180. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  181. {
  182. Client &c = *((Client *)*uptr);
  183. c.lastActivity = time((time_t *)0);
  184. for(unsigned long i=0;i<len;++i) {
  185. if (c.tcpReadPtr >= sizeof(c.tcpReadBuf)) {
  186. phy->close(sock);
  187. return;
  188. }
  189. c.tcpReadBuf[c.tcpReadPtr++] = ((const char *)data)[i];
  190. if (c.tcpReadPtr >= 5) {
  191. unsigned long mlen = ( ((((unsigned long)c.tcpReadBuf[3]) & 0xff) << 8) | (((unsigned long)c.tcpReadBuf[4]) & 0xff) );
  192. if (c.tcpReadPtr >= (mlen + 5)) {
  193. if (mlen == 4) {
  194. // Right now just sending this means the client is 'new enough' for the IP header
  195. c.newVersion = true;
  196. printf("<< TCP %.16llx HELLO\n",(unsigned long long)*uptr);
  197. } else if (mlen >= 7) {
  198. char *payload = c.tcpReadBuf + 5;
  199. unsigned long payloadLen = mlen;
  200. struct sockaddr_in dest;
  201. memset(&dest,0,sizeof(dest));
  202. if (c.newVersion) {
  203. if (*payload == (char)4) {
  204. // New clients tell us where their packets go.
  205. ++payload;
  206. dest.sin_family = AF_INET;
  207. dest.sin_addr.s_addr = *((uint32_t *)payload);
  208. payload += 4;
  209. dest.sin_port = *((uint16_t *)payload); // will be in network byte order already
  210. payload += 2;
  211. payloadLen -= 7;
  212. }
  213. } else {
  214. // For old clients we will just proxy everything to a local ZT instance. The
  215. // fact that this will come from 127.0.0.1 will in turn prevent that instance
  216. // from doing unite() with us. It'll just forward. There will not be many of
  217. // these.
  218. dest.sin_family = AF_INET;
  219. dest.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
  220. dest.sin_port = htons(9993);
  221. }
  222. // Note: we do not relay to privileged ports... just an abuse prevention rule.
  223. if ((ntohs(dest.sin_port) > 1024)&&(payloadLen >= 16)) {
  224. phy->udpSend(c.udp,(const struct sockaddr *)&dest,payload,payloadLen);
  225. printf(">> TCP %.16llx to %s:%d\n",(unsigned long long)*uptr,inet_ntoa(dest.sin_addr),(int)ntohs(dest.sin_port));
  226. }
  227. }
  228. memmove(c.tcpReadBuf,c.tcpReadBuf + (mlen + 5),c.tcpReadPtr -= (mlen + 5));
  229. }
  230. }
  231. }
  232. }
  233. void phyOnTcpWritable(PhySocket *sock,void **uptr)
  234. {
  235. Client &c = *((Client *)*uptr);
  236. if (c.tcpWritePtr) {
  237. long n = phy->streamSend(sock,c.tcpWriteBuf,c.tcpWritePtr);
  238. if (n > 0) {
  239. memmove(c.tcpWriteBuf,c.tcpWriteBuf + n,c.tcpWritePtr -= (unsigned long)n);
  240. if (!c.tcpWritePtr)
  241. phy->setNotifyWritable(sock,false);
  242. }
  243. } else phy->setNotifyWritable(sock,false);
  244. }
  245. void doHousekeeping()
  246. {
  247. std::vector<PhySocket *> toClose;
  248. time_t now = time((time_t *)0);
  249. for(std::map< PhySocket *,Client >::iterator c(clients.begin());c!=clients.end();++c) {
  250. if ((now - c->second.lastActivity) >= ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS) {
  251. toClose.push_back(c->first);
  252. toClose.push_back(c->second.udp);
  253. }
  254. }
  255. for(std::vector<PhySocket *>::iterator s(toClose.begin());s!=toClose.end();++s)
  256. phy->close(*s);
  257. }
  258. };
  259. int main(int argc,char **argv)
  260. {
  261. signal(SIGPIPE,SIG_IGN);
  262. signal(SIGHUP,SIG_IGN);
  263. srand(time((time_t *)0));
  264. TcpProxyService svc;
  265. Phy<TcpProxyService *> phy(&svc,false,true);
  266. svc.phy = &phy;
  267. svc.udpPortCounter = 1023;
  268. {
  269. struct sockaddr_in laddr;
  270. memset(&laddr,0,sizeof(laddr));
  271. laddr.sin_family = AF_INET;
  272. laddr.sin_port = htons(ZT_TCP_PROXY_TCP_PORT);
  273. if (!phy.tcpListen((const struct sockaddr *)&laddr)) {
  274. fprintf(stderr,"%s: fatal error: unable to bind TCP port %d\n",argv[0],ZT_TCP_PROXY_TCP_PORT);
  275. return 1;
  276. }
  277. }
  278. time_t lastDidHousekeeping = time((time_t *)0);
  279. for(;;) {
  280. phy.poll(120000);
  281. time_t now = time((time_t *)0);
  282. if ((now - lastDidHousekeeping) > 120) {
  283. lastDidHousekeeping = now;
  284. svc.doHousekeeping();
  285. }
  286. }
  287. return 0;
  288. }