tcp-proxy.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <time.h>
  31. #include <stdint.h>
  32. #include <unistd.h>
  33. #include <signal.h>
  34. #include <map>
  35. #include <set>
  36. #include <string>
  37. #include <algorithm>
  38. #include <vector>
  39. #include "../osdep/Phy.hpp"
  40. #define ZT_TCP_PROXY_UDP_POOL_SIZE 1024
  41. #define ZT_TCP_PROXY_UDP_POOL_START_PORT 10000
  42. #define ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS 300
  43. // Uncomment to print tracing output to stdout
  44. #define ZT_TCP_PROXY_TRACE
  45. using namespace ZeroTier;
  46. /*
  47. * ZeroTier TCP Proxy Server
  48. *
  49. * This implements a simple packet encapsulation that is designed to look like
  50. * a TLS connection. It's not a TLS connection, but it sends TLS format record
  51. * headers. It could be extended in the future to implement a fake TLS
  52. * handshake.
  53. *
  54. * At the moment, each packet is just made to look like TLS application data:
  55. * <[1] TLS content type> - currently 0x17 for "application data"
  56. * <[1] TLS major version> - currently 0x03 for TLS 1.2
  57. * <[1] TLS minor version> - currently 0x03 for TLS 1.2
  58. * <[2] payload length> - 16-bit length of payload in bytes
  59. * <[...] payload> - Message payload
  60. *
  61. * TCP is inherently inefficient for encapsulating Ethernet, since TCP and TCP
  62. * like protocols over TCP lead to double-ACKs. So this transport is only used
  63. * to enable access when UDP or other datagram protocols are not available.
  64. *
  65. * Clients send a greeting, which is a four-byte message that contains:
  66. * <[1] ZeroTier major version>
  67. * <[1] minor version>
  68. * <[2] revision>
  69. *
  70. * If a client has sent a greeting, it uses the new version of this protocol
  71. * in which every encapsulated ZT packet is prepended by an IP address where
  72. * it should be forwarded (or where it came from for replies). This causes
  73. * this proxy to act as a remote UDP socket similar to a socks proxy, which
  74. * will allow us to move this function off the supernodes and onto dedicated
  75. * proxy nodes.
  76. *
  77. * Older ZT clients that do not send this message get their packets relayed
  78. * to/from 127.0.0.1:9993, which will allow them to talk to and relay via
  79. * the ZT node on the same machine as the proxy. We'll only support this for
  80. * as long as such nodes appear to be in the wild.
  81. */
  82. struct TcpProxyService;
  83. struct TcpProxyService
  84. {
  85. Phy<TcpProxyService *> *phy;
  86. PhySocket *udpPool[ZT_TCP_PROXY_UDP_POOL_SIZE];
  87. struct Client
  88. {
  89. char tcpReadBuf[131072];
  90. char tcpWriteBuf[131072];
  91. unsigned long tcpWritePtr;
  92. unsigned long tcpReadPtr;
  93. PhySocket *tcp;
  94. PhySocket *assignedUdp;
  95. time_t lastActivity;
  96. bool newVersion;
  97. };
  98. std::map< PhySocket *,Client > clients;
  99. struct ReverseMappingKey
  100. {
  101. uint64_t sourceZTAddress;
  102. PhySocket *sendingUdpSocket;
  103. uint32_t destIp;
  104. unsigned int destPort;
  105. ReverseMappingKey() {}
  106. ReverseMappingKey(uint64_t zt,PhySocket *s,uint32_t ip,unsigned int port) : sourceZTAddress(zt),sendingUdpSocket(s),destIp(ip),destPort(port) {}
  107. inline bool operator<(const ReverseMappingKey &k) const throw() { return (memcmp((const void *)this,(const void *)&k,sizeof(ReverseMappingKey)) < 0); }
  108. inline bool operator==(const ReverseMappingKey &k) const throw() { return (memcmp((const void *)this,(const void *)&k,sizeof(ReverseMappingKey)) == 0); }
  109. };
  110. std::map< ReverseMappingKey,Client * > reverseMappings;
  111. void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  112. {
  113. if ((from->sa_family == AF_INET)&&(len > 16)&&(len < 2048)) {
  114. const uint64_t destZt = (
  115. (((uint64_t)(((const unsigned char *)data)[8])) << 32) |
  116. (((uint64_t)(((const unsigned char *)data)[9])) << 24) |
  117. (((uint64_t)(((const unsigned char *)data)[10])) << 16) |
  118. (((uint64_t)(((const unsigned char *)data)[11])) << 8) |
  119. ((uint64_t)(((const unsigned char *)data)[12])) );
  120. const uint32_t fromIp = ((const struct sockaddr_in *)from)->sin_addr.s_addr;
  121. const unsigned int fromPort = ntohs(((const struct sockaddr_in *)from)->sin_port);
  122. std::map< ReverseMappingKey,Client * >::iterator rm(reverseMappings.find(ReverseMappingKey(destZt,sock,fromIp,fromPort)));
  123. if (rm != reverseMappings.end()) {
  124. Client &c = *(rm->second);
  125. #ifdef ZT_TCP_PROXY_TRACE
  126. printf("UDP [%u] %s >> %.16llx\n",len,reinterpret_cast<const InetAddress *>(from)->toString().c_str(),(unsigned long long)&c);
  127. #endif
  128. unsigned long mlen = len;
  129. if (c.newVersion)
  130. mlen += 7; // new clients get IP info
  131. if ((c.tcpWritePtr + 5 + mlen) <= sizeof(c.tcpWriteBuf)) {
  132. if (!c.tcpWritePtr)
  133. phy->tcpSetNotifyWritable(c.tcp,true);
  134. c.tcpWriteBuf[c.tcpWritePtr++] = 0x17; // look like TLS data
  135. c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
  136. c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
  137. c.tcpWriteBuf[c.tcpWritePtr++] = (char)((mlen >> 8) & 0xff);
  138. c.tcpWriteBuf[c.tcpWritePtr++] = (char)(mlen & 0xff);
  139. if (c.newVersion) {
  140. c.tcpWriteBuf[c.tcpWritePtr++] = (char)4; // IPv4
  141. *((uint32_t *)(c.tcpWriteBuf + c.tcpWritePtr)) = fromIp;
  142. c.tcpWritePtr += 4;
  143. c.tcpWriteBuf[c.tcpWritePtr++] = (char)((fromPort >> 8) & 0xff);
  144. c.tcpWriteBuf[c.tcpWritePtr++] = (char)(fromPort & 0xff);
  145. }
  146. for(unsigned long i=0;i<len;++i)
  147. c.tcpWriteBuf[c.tcpWritePtr++] = ((const char *)data)[i];
  148. }
  149. } else {
  150. #ifdef ZT_TCP_PROXY_TRACE
  151. printf("UDP [%u] %s >> (unknown, discarded)\n",len,reinterpret_cast<const InetAddress *>(from)->toString().c_str());
  152. #endif
  153. }
  154. }
  155. }
  156. void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  157. {
  158. // unused, we don't initiate
  159. }
  160. void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  161. {
  162. Client &c = clients[sockN];
  163. c.tcpWritePtr = 0;
  164. c.tcpReadPtr = 0;
  165. c.tcp = sockN;
  166. c.assignedUdp = udpPool[rand() % ZT_TCP_PROXY_UDP_POOL_SIZE];
  167. c.lastActivity = time((time_t *)0);
  168. c.newVersion = false;
  169. *uptrN = (void *)&c;
  170. #ifdef ZT_TCP_PROXY_TRACE
  171. printf("TCP connect from %s -> %.16llx\n",reinterpret_cast<const InetAddress *>(from)->toString().c_str(),(unsigned long long)&c);
  172. #endif
  173. }
  174. void phyOnTcpClose(PhySocket *sock,void **uptr)
  175. {
  176. for(std::map< ReverseMappingKey,Client * >::iterator rm(reverseMappings.begin());rm!=reverseMappings.end();) {
  177. if (rm->second == (Client *)*uptr)
  178. reverseMappings.erase(rm++);
  179. else ++rm;
  180. }
  181. clients.erase(sock);
  182. }
  183. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  184. {
  185. Client &c = *((Client *)*uptr);
  186. c.lastActivity = time((time_t *)0);
  187. for(unsigned long i=0;i<len;++i) {
  188. if (c.tcpReadPtr >= sizeof(c.tcpReadBuf)) {
  189. phy->close(sock);
  190. return;
  191. }
  192. c.tcpReadBuf[c.tcpReadPtr++] = ((const char *)data)[i];
  193. if (c.tcpReadPtr >= 5) {
  194. unsigned long mlen = ( ((((unsigned long)c.tcpReadBuf[3]) & 0xff) << 8) | (((unsigned long)c.tcpReadBuf[4]) & 0xff) );
  195. if (c.tcpReadPtr >= (mlen + 5)) {
  196. if (mlen == 4) {
  197. // Right now just sending this means the client is 'new enough' for the IP header
  198. c.newVersion = true;
  199. } else if (mlen >= 7) {
  200. char *payload = c.tcpReadBuf + 5;
  201. unsigned long payloadLen = mlen;
  202. struct sockaddr_in dest;
  203. memset(&dest,0,sizeof(dest));
  204. if (c.newVersion) {
  205. if (*payload == (char)4) {
  206. // New clients tell us where their packets go.
  207. ++payload;
  208. dest.sin_family = AF_INET;
  209. dest.sin_addr.s_addr = *((uint32_t *)payload);
  210. payload += 4;
  211. dest.sin_port = *((uint16_t *)payload); // will be in network byte order already
  212. payload += 2;
  213. payloadLen -= 7;
  214. }
  215. } else {
  216. // For old clients we will just proxy everything to a local ZT instance. The
  217. // fact that this will come from 127.0.0.1 will in turn prevent that instance
  218. // from doing unite() with us. It'll just forward. There will not be many of
  219. // these.
  220. dest.sin_family = AF_INET;
  221. dest.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
  222. dest.sin_port = htons(9993);
  223. }
  224. // Note: we do not relay to privileged ports... just an abuse prevention rule.
  225. if ((ntohs(dest.sin_port) > 1024)&&(payloadLen >= 16)) {
  226. if ((payloadLen >= 28)&&(payload[13] != (char)0xff)) {
  227. // Learn reverse mappings -- we will route replies to these packets
  228. // back to their sending TCP socket. They're on a first come first
  229. // served basis.
  230. const uint64_t sourceZt = (
  231. (((uint64_t)(((const unsigned char *)payload)[13])) << 32) |
  232. (((uint64_t)(((const unsigned char *)payload)[14])) << 24) |
  233. (((uint64_t)(((const unsigned char *)payload)[15])) << 16) |
  234. (((uint64_t)(((const unsigned char *)payload)[16])) << 8) |
  235. ((uint64_t)(((const unsigned char *)payload)[17])) );
  236. ReverseMappingKey k(sourceZt,c.assignedUdp,dest.sin_addr.s_addr,ntohl(dest.sin_port));
  237. if (reverseMappings.count(k) == 0)
  238. reverseMappings[k] = &c;
  239. }
  240. phy->udpSend(c.assignedUdp,(const struct sockaddr *)&dest,payload,payloadLen);
  241. }
  242. }
  243. memmove(c.tcpReadBuf,c.tcpReadBuf + (mlen + 5),c.tcpReadPtr -= (mlen + 5));
  244. }
  245. }
  246. }
  247. }
  248. void phyOnTcpWritable(PhySocket *sock,void **uptr)
  249. {
  250. Client &c = *((Client *)*uptr);
  251. if (c.tcpWritePtr) {
  252. long n = phy->tcpSend(sock,c.tcpWriteBuf,c.tcpWritePtr);
  253. if (n > 0) {
  254. memmove(c.tcpWriteBuf,c.tcpWriteBuf + n,c.tcpWritePtr -= (unsigned long)n);
  255. if (!c.tcpWritePtr)
  256. phy->tcpSetNotifyWritable(sock,false);
  257. }
  258. } else phy->tcpSetNotifyWritable(sock,false);
  259. }
  260. void doHousekeeping()
  261. {
  262. std::vector<PhySocket *> toClose;
  263. time_t now = time((time_t *)0);
  264. for(std::map< PhySocket *,Client >::iterator c(clients.begin());c!=clients.end();++c) {
  265. if ((now - c->second.lastActivity) >= ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS)
  266. toClose.push_back(c->first);
  267. }
  268. for(std::vector<PhySocket *>::iterator s(toClose.begin());s!=toClose.end();++s)
  269. phy->close(*s); // will call phyOnTcpClose() which does cleanup
  270. }
  271. };
  272. int main(int argc,char **argv)
  273. {
  274. signal(SIGPIPE,SIG_IGN);
  275. signal(SIGHUP,SIG_IGN);
  276. srand(time((time_t *)0));
  277. TcpProxyService svc;
  278. Phy<TcpProxyService *> phy(&svc,true);
  279. svc.phy = &phy;
  280. {
  281. int poolSize = 0;
  282. for(unsigned int p=ZT_TCP_PROXY_UDP_POOL_START_PORT;((poolSize<ZT_TCP_PROXY_UDP_POOL_SIZE)&&(p<=65535));++p) {
  283. struct sockaddr_in laddr;
  284. memset(&laddr,0,sizeof(laddr));
  285. laddr.sin_family = AF_INET;
  286. laddr.sin_port = htons((uint16_t)p);
  287. PhySocket *s = phy.udpBind((const struct sockaddr *)&laddr);
  288. if (s)
  289. svc.udpPool[poolSize++] = s;
  290. }
  291. if (poolSize < ZT_TCP_PROXY_UDP_POOL_SIZE) {
  292. fprintf(stderr,"%s: fatal error: cannot bind %d UDP ports\n",argv[0],ZT_TCP_PROXY_UDP_POOL_SIZE);
  293. return 1;
  294. }
  295. }
  296. time_t lastDidHousekeeping = time((time_t *)0);
  297. for(;;) {
  298. phy.poll(120000);
  299. time_t now = time((time_t *)0);
  300. if ((now - lastDidHousekeeping) > 120) {
  301. lastDidHousekeeping = now;
  302. svc.doHousekeeping();
  303. }
  304. }
  305. }