2
0

tcp-proxy.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. using namespace ZeroTier;
  44. /*
  45. * This implements a simple packet encapsulation that is designed to look like
  46. * a TLS connection. It's not a TLS connection, but it sends TLS format record
  47. * headers. It could be extended in the future to implement a fake TLS
  48. * handshake.
  49. *
  50. * At the moment, each packet is just made to look like TLS application data:
  51. * <[1] TLS content type> - currently 0x17 for "application data"
  52. * <[1] TLS major version> - currently 0x03 for TLS 1.2
  53. * <[1] TLS minor version> - currently 0x03 for TLS 1.2
  54. * <[2] payload length> - 16-bit length of payload in bytes
  55. * <[...] payload> - Message payload
  56. *
  57. * The primary purpose of TCP sockets is to work over ports like HTTPS(443),
  58. * allowing users behind particularly fascist firewalls to at least reach
  59. * ZeroTier's supernodes. UDP is the preferred method of communication as
  60. * encapsulating L2 and L3 protocols over TCP is inherently inefficient
  61. * due to double-ACKs. So TCP is only used as a fallback.
  62. *
  63. * New clients send a HELLO message consisting of a 4-byte message (too small
  64. * for a ZT packet) containing:
  65. * <[1] ZeroTier major version>
  66. * <[1] minor version>
  67. * <[2] revision>
  68. *
  69. * Clients that have send a HELLO and that have a new enough version prepend
  70. * each payload with the remote IP the message is destined for. This is in
  71. * the same format as the IP portion of ZeroTier HELLO packets.
  72. */
  73. struct TcpProxyService;
  74. struct TcpProxyService
  75. {
  76. Phy<TcpProxyService *> *phy;
  77. PhySocket *udpPool[ZT_TCP_PROXY_UDP_POOL_SIZE];
  78. struct Client
  79. {
  80. char tcpReadBuf[131072];
  81. char tcpWriteBuf[131072];
  82. unsigned long tcpWritePtr;
  83. unsigned long tcpReadPtr;
  84. PhySocket *tcp;
  85. PhySocket *assignedUdp;
  86. time_t lastActivity;
  87. bool newVersion;
  88. };
  89. std::map< PhySocket *,Client > clients;
  90. struct ReverseMappingKey
  91. {
  92. uint64_t sourceZTAddress;
  93. PhySocket *sendingUdpSocket;
  94. uint32_t destIp;
  95. unsigned int destPort;
  96. ReverseMappingKey() {}
  97. ReverseMappingKey(uint64_t zt,PhySocket *s,uint32_t ip,unsigned int port) : sourceZTAddress(zt),sendingUdpSocket(s),destIp(ip),destPort(port) {}
  98. inline bool operator<(const ReverseMappingKey &k) const throw() { return (memcmp((const void *)this,(const void *)&k,sizeof(ReverseMappingKey)) < 0); }
  99. inline bool operator==(const ReverseMappingKey &k) const throw() { return (memcmp((const void *)this,(const void *)&k,sizeof(ReverseMappingKey)) == 0); }
  100. };
  101. std::map< ReverseMappingKey,Client * > reverseMappings;
  102. void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  103. {
  104. if ((from->sa_family == AF_INET)&&(len > 16)&&(len < 2048)) {
  105. const uint64_t destZt = (
  106. (((uint64_t)(((const unsigned char *)data)[8])) << 32) |
  107. (((uint64_t)(((const unsigned char *)data)[9])) << 24) |
  108. (((uint64_t)(((const unsigned char *)data)[10])) << 16) |
  109. (((uint64_t)(((const unsigned char *)data)[11])) << 8) |
  110. ((uint64_t)(((const unsigned char *)data)[12])) );
  111. const uint32_t fromIp = ((const struct sockaddr_in *)from)->sin_addr.s_addr;
  112. const unsigned int fromPort = ntohs(((const struct sockaddr_in *)from)->sin_port);
  113. std::map< ReverseMappingKey,Client * >::iterator rm(reverseMappings.find(ReverseMappingKey(destZt,sock,fromIp,fromPort)));
  114. if (rm != reverseMappings.end()) {
  115. Client &c = *(rm->second);
  116. unsigned long mlen = len;
  117. if (c.newVersion)
  118. mlen += 7; // new clients get IP info
  119. if ((c.tcpWritePtr + 5 + mlen) <= sizeof(c.tcpWriteBuf)) {
  120. if (!c.tcpWritePtr)
  121. phy->tcpSetNotifyWritable(c.tcp,true);
  122. c.tcpWriteBuf[c.tcpWritePtr++] = 0x17; // look like TLS data
  123. c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
  124. c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
  125. c.tcpWriteBuf[c.tcpWritePtr++] = (char)((mlen >> 8) & 0xff);
  126. c.tcpWriteBuf[c.tcpWritePtr++] = (char)(mlen & 0xff);
  127. if (c.newVersion) {
  128. c.tcpWriteBuf[c.tcpWritePtr++] = (char)4; // IPv4
  129. *((uint32_t *)(c.tcpWriteBuf + c.tcpWritePtr)) = fromIp;
  130. c.tcpWritePtr += 4;
  131. c.tcpWriteBuf[c.tcpWritePtr++] = (char)((fromPort >> 8) & 0xff);
  132. c.tcpWriteBuf[c.tcpWritePtr++] = (char)(fromPort & 0xff);
  133. }
  134. for(unsigned long i=0;i<len;++i)
  135. c.tcpWriteBuf[c.tcpWritePtr++] = ((const char *)data)[i];
  136. }
  137. }
  138. }
  139. }
  140. void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  141. {
  142. // unused, we don't initiate
  143. }
  144. void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  145. {
  146. Client &c = clients[sockN];
  147. c.tcpWritePtr = 0;
  148. c.tcpReadPtr = 0;
  149. c.tcp = sockN;
  150. c.assignedUdp = udpPool[rand() % ZT_TCP_PROXY_UDP_POOL_SIZE];
  151. c.lastActivity = time((time_t *)0);
  152. c.newVersion = false;
  153. *uptrN = (void *)&c;
  154. }
  155. void phyOnTcpClose(PhySocket *sock,void **uptr)
  156. {
  157. for(std::map< ReverseMappingKey,Client * >::iterator rm(reverseMappings.begin());rm!=reverseMappings.end();) {
  158. if (rm->second == (Client *)*uptr)
  159. reverseMappings.erase(rm++);
  160. else ++rm;
  161. }
  162. clients.erase(sock);
  163. }
  164. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  165. {
  166. Client &c = *((Client *)*uptr);
  167. c.lastActivity = time((time_t *)0);
  168. for(unsigned long i=0;i<len;++i) {
  169. if (c.tcpReadPtr >= sizeof(c.tcpReadBuf)) {
  170. phy->close(sock);
  171. return;
  172. }
  173. c.tcpReadBuf[c.tcpReadPtr++] = ((const char *)data)[i];
  174. if (c.tcpReadPtr >= 5) {
  175. unsigned long mlen = ( ((((unsigned long)c.tcpReadBuf[3]) & 0xff) << 8) | (((unsigned long)c.tcpReadBuf[4]) & 0xff) );
  176. if (c.tcpReadPtr >= (mlen + 5)) {
  177. if (mlen == 4) {
  178. // Right now just sending this means the client is 'new enough' for the IP header
  179. c.newVersion = true;
  180. } else if (mlen >= 7) {
  181. char *payload = c.tcpReadBuf + 5;
  182. unsigned long payloadLen = mlen;
  183. struct sockaddr_in dest;
  184. memset(&dest,0,sizeof(dest));
  185. if (c.newVersion) {
  186. if (*payload == (char)4) {
  187. // New clients tell us where their packets go.
  188. ++payload;
  189. dest.sin_family = AF_INET;
  190. dest.sin_addr.s_addr = *((uint32_t *)payload);
  191. payload += 4;
  192. dest.sin_port = *((uint16_t *)payload); // will be in network byte order already
  193. payload += 2;
  194. payloadLen -= 7;
  195. }
  196. } else {
  197. // For old clients we will just proxy everything to a local ZT instance. The
  198. // fact that this will come from 127.0.0.1 will in turn prevent that instance
  199. // from doing unite() with us. It'll just forward. There will not be many of
  200. // these.
  201. dest.sin_family = AF_INET;
  202. dest.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
  203. dest.sin_port = htons(9993);
  204. }
  205. // Note: we do not relay to privileged ports... just an abuse prevention rule.
  206. if ((ntohs(dest.sin_port) > 1024)&&(payloadLen >= 16)) {
  207. if ((payloadLen >= 28)&&(payload[13] != (char)0xff)) {
  208. // Learn reverse mappings -- we will route replies to these packets
  209. // back to their sending TCP socket. They're on a first come first
  210. // served basis.
  211. const uint64_t sourceZt = (
  212. (((uint64_t)(((const unsigned char *)payload)[13])) << 32) |
  213. (((uint64_t)(((const unsigned char *)payload)[14])) << 24) |
  214. (((uint64_t)(((const unsigned char *)payload)[15])) << 16) |
  215. (((uint64_t)(((const unsigned char *)payload)[16])) << 8) |
  216. ((uint64_t)(((const unsigned char *)payload)[17])) );
  217. ReverseMappingKey k(sourceZt,c.assignedUdp,dest.sin_addr.s_addr,ntohl(dest.sin_port));
  218. if (reverseMappings.count(k) == 0)
  219. reverseMappings[k] = &c;
  220. }
  221. phy->udpSend(c.assignedUdp,(const struct sockaddr *)&dest,payload,payloadLen);
  222. }
  223. }
  224. memmove(c.tcpReadBuf,c.tcpReadBuf + (mlen + 5),c.tcpReadPtr -= (mlen + 5));
  225. }
  226. }
  227. }
  228. }
  229. void phyOnTcpWritable(PhySocket *sock,void **uptr)
  230. {
  231. Client &c = *((Client *)*uptr);
  232. if (c.tcpWritePtr) {
  233. long n = phy->tcpSend(sock,c.tcpWriteBuf,c.tcpWritePtr);
  234. if (n > 0) {
  235. memmove(c.tcpWriteBuf,c.tcpWriteBuf + n,c.tcpWritePtr -= (unsigned long)n);
  236. if (!c.tcpWritePtr)
  237. phy->tcpSetNotifyWritable(sock,false);
  238. }
  239. } else phy->tcpSetNotifyWritable(sock,false);
  240. }
  241. void doHousekeeping()
  242. {
  243. std::vector<PhySocket *> toClose;
  244. time_t now = time((time_t *)0);
  245. for(std::map< PhySocket *,Client >::iterator c(clients.begin());c!=clients.end();++c) {
  246. if ((now - c->second.lastActivity) >= ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS)
  247. toClose.push_back(c->first);
  248. }
  249. for(std::vector<PhySocket *>::iterator s(toClose.begin());s!=toClose.end();++s)
  250. phy->close(*s); // will call phyOnTcpClose() which does cleanup
  251. }
  252. };
  253. int main(int argc,char **argv)
  254. {
  255. signal(SIGPIPE,SIG_IGN);
  256. signal(SIGHUP,SIG_IGN);
  257. srand(time((time_t *)0));
  258. TcpProxyService svc;
  259. Phy<TcpProxyService *> phy(&svc,true);
  260. svc.phy = &phy;
  261. {
  262. int poolSize = 0;
  263. for(unsigned int p=ZT_TCP_PROXY_UDP_POOL_START_PORT;((poolSize<ZT_TCP_PROXY_UDP_POOL_SIZE)&&(p<=65535));++p) {
  264. struct sockaddr_in laddr;
  265. memset(&laddr,0,sizeof(laddr));
  266. laddr.sin_family = AF_INET;
  267. laddr.sin_port = htons((uint16_t)p);
  268. PhySocket *s = phy.udpBind((const struct sockaddr *)&laddr);
  269. if (s)
  270. svc.udpPool[poolSize++] = s;
  271. }
  272. if (poolSize < ZT_TCP_PROXY_UDP_POOL_SIZE) {
  273. fprintf(stderr,"%s: fatal error: cannot bind %d UDP ports\n",argv[0],ZT_TCP_PROXY_UDP_POOL_SIZE);
  274. return 1;
  275. }
  276. }
  277. time_t lastDidHousekeeping = time((time_t *)0);
  278. for(;;) {
  279. phy.poll(120000);
  280. time_t now = time((time_t *)0);
  281. if ((now - lastDidHousekeeping) > 120) {
  282. lastDidHousekeeping = now;
  283. svc.doHousekeeping();
  284. }
  285. }
  286. }