diff --git a/attic/http-tunnel-proxy.js b/attic/http-tunnel-proxy.js new file mode 100755 index 000000000..5a47a7d37 --- /dev/null +++ b/attic/http-tunnel-proxy.js @@ -0,0 +1,136 @@ +#!/usr/bin/env node + +// Note: this is unfinished and not currently used. Stashed in case we resurrect this idea. + +var UDP_PORT_START = 9994; +var UDP_PORT_COUNT = 16384; +var HTTP_PORT = 8080; +var LONG_POLLING_TIMEOUT = 25000; + +var http = require('http'); +var dgram = require('dgram'); + +// clients[token] = [ most recent HTTP activity, assigned UDP socket ] +var clients = {}; + +// GETs[token] = [ [ request, timestamp ], ... ] +var GETs = {}; + +// mappings[localPort+'/'+remoteIp+'/'+remotePort] = { ZT source: [ token ] } +var mappings = {}; + +// Array of available UDP sockets to assign randomly to clients +var udpSocketPool = []; + +function onIncomingUdp(socket,message,remoteIp,remotePort) +{ + if (message.length > 16) { + var mappingKey = socket.localPort + '/' + remoteIp + '/' + remotePort; + var mapping = mappings[mappingKey]; + if (mapping) { + var ztDestination = message.readUIntBE(8,5); + if (ztDestination in mapping) { + } + } + } +} + +function onOutgoingUdp(token,socket,message,remoteIp,remotePort) +{ + if (message.length > 16) { + var ztDestination = message.readUIntBE(8,5); + var ztSource = (message.length >= 28) ? message.readUIntBE(13,5) ? 0; + if ((ztSource & 0xff00000000) == 0xff00000000) // fragment + ztSource = 0; + + if ((ztDestination !== 0)&&((ztDestination & 0xff00000000) !== 0xff00000000)) { + socket.send(message,0,message.length,remotePort,remoteIp); + } + } +} + +function doHousekeeping() +{ +} + +for(var udpPort=UDP_PORT_START;udpPort<(UDP_PORT_START+UDP_PORT_COUNT)++udpPort) { + var socket = dgram.createSocket('udp4',function(message,rinfo) { onIncomingUdp(socket,message,rinfo.address,rinfo.port); }); + socket.on('listening',function() { + console.log('Listening on '+socket.localPort); + udpSocketPool.push(socket); + } + socket.on('error',function() { + console.log('Error listening on '+socket.localPort); + socket.close(); + }) + socket.bind(udpPort); +} + +server = http.createServer(function(request,response) { + console.log(request.socket.remoteAddress+" "+request.method+" "+request.url); + + try { + // ///... + var urlSp = request.url.split('/'); + if ((urlSp.length >= 3)&&(udpSocketPool.length > 0)) { + var token = urlSp[1]; // urlSp[0] == '' since URLs start with / + + if (token.length >= 8) { + var client = clients[token]; + if (!Array.isArray(client)) { + client = [ Date.now(),udpSocketPool[Math.floor(Math.random() * udpSocketPool.length)] ]; + clients[token] = client; + } else client[0] = Date.now(); + + if (request.method === "GET") { + + // // ... waits via old skool long polling + + } else if (request.method === "POST") { + + // //// + if (urlSp.length === 5) { + var ipSp = urlSp[3].split('.'); + var port = parseInt(urlSp[4],10); + // Note: do not allow the use of this proxy to talk to privileged ports + if ((ipSp.length === 4)&&(port >= 1024)&&(port <= 0xffff)) { + var ip = [ parseInt(ipSp[0]),parseInt(ipSp[1]),parseInt(ipSp[2]),parseInt(ipSp[3]) ]; + if ( (ip[0] > 0) + &&(ip[0] < 240) + &&(ip[0] !== 127) + &&(ip[1] >= 0) + &&(ip[1] <= 255) + &&(ip[2] >= 0) + &&(ip[2] <= 255) + &&(ip[3] > 0) + &&(ip[3] < 255) ) { + var postData = null; + request.on('data',function(chunk) { + postData = ((postData === null) ? chunk : Buffer.concat([ postData,chunk ])); + }); + request.on('end',function() { + if (postData !== null) + onOutgoingUdp(token,client[1],postData,urlSp[3],port); + response.writeHead(200,{'Content-Length':0,'Pragma':'no-cache','Cache-Control':'no-cache'}); + response.end(); + }); + return; // no 400 -- read from stream + } // else 400 + } // else 400 + } // else 400 + + } // else 400 + + } // else 400 + } // else 400 + } catch (e) {} // 400 + + response.writeHead(400,{'Content-Length':0,'Pragma':'no-cache','Cache-Control':'no-cache'}); + response.end(); + return; +}); + +setInterval(doHousekeeping,5000); + +server.setTimeout(120000); +server.listen(HTTP_PORT); diff --git a/node/Switch.cpp b/node/Switch.cpp index 8c27fdfac..e2bc74c5f 100644 --- a/node/Switch.cpp +++ b/node/Switch.cpp @@ -296,6 +296,9 @@ bool Switch::unite(const Address &p1,const Address &p2,bool force) if (!(cg.first)) return false; + if (cg.first.ipScope() != cg.second.ipScope()) + return false; + // Addresses are sorted in key for last unite attempt map for order // invariant lookup: (p1,p2) == (p2,p1) Array uniteKey; diff --git a/service/OneService.cpp b/service/OneService.cpp index bff705007..a04d46dff 100644 --- a/service/OneService.cpp +++ b/service/OneService.cpp @@ -158,6 +158,7 @@ public: _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&in4,this,131072); if (!_v4UdpSocket) throw std::runtime_error("cannot bind to port (UDP/IPv4)"); + in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this); if (!_v4TcpListenSocket) { _phy.close(_v4UdpSocket); @@ -168,6 +169,7 @@ public: in6.sin6_family = AF_INET6; in6.sin6_port = in4.sin_port; _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&in6,this,131072); + in6.sin6_addr.s6_addr[15] = 1; // listen for TCP only at localhost _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this); char portstr[64]; diff --git a/tcp-proxy/README.md b/tcp-proxy/README.md new file mode 100644 index 000000000..6f347d640 --- /dev/null +++ b/tcp-proxy/README.md @@ -0,0 +1,4 @@ +TCP Proxy Server +====== + +This is the TCP proxy server we run for TCP tunneling from peers behind fascist NATs. Regular users won't have much use for this. diff --git a/tcp-proxy/tcp-proxy.cpp b/tcp-proxy/tcp-proxy.cpp new file mode 100644 index 000000000..6837803f2 --- /dev/null +++ b/tcp-proxy/tcp-proxy.cpp @@ -0,0 +1,322 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015 ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "../osdep/Phy.hpp" + +#define ZT_TCP_PROXY_UDP_POOL_SIZE 1024 +#define ZT_TCP_PROXY_UDP_POOL_START_PORT 10000 +#define ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS 300 + +using namespace ZeroTier; + +/* + * This implements a simple packet encapsulation that is designed to look like + * a TLS connection. It's not a TLS connection, but it sends TLS format record + * headers. It could be extended in the future to implement a fake TLS + * handshake. + * + * At the moment, each packet is just made to look like TLS application data: + * <[1] TLS content type> - currently 0x17 for "application data" + * <[1] TLS major version> - currently 0x03 for TLS 1.2 + * <[1] TLS minor version> - currently 0x03 for TLS 1.2 + * <[2] payload length> - 16-bit length of payload in bytes + * <[...] payload> - Message payload + * + * The primary purpose of TCP sockets is to work over ports like HTTPS(443), + * allowing users behind particularly fascist firewalls to at least reach + * ZeroTier's supernodes. UDP is the preferred method of communication as + * encapsulating L2 and L3 protocols over TCP is inherently inefficient + * due to double-ACKs. So TCP is only used as a fallback. + * + * New clients send a HELLO message consisting of a 4-byte message (too small + * for a ZT packet) containing: + * <[1] ZeroTier major version> + * <[1] minor version> + * <[2] revision> + * + * Clients that have send a HELLO and that have a new enough version prepend + * each payload with the remote IP the message is destined for. This is in + * the same format as the IP portion of ZeroTier HELLO packets. + */ + +struct TcpProxyService; +struct TcpProxyService +{ + Phy *phy; + PhySocket *udpPool[ZT_TCP_PROXY_UDP_POOL_SIZE]; + + struct Client + { + char tcpReadBuf[131072]; + char tcpWriteBuf[131072]; + unsigned long tcpWritePtr; + unsigned long tcpReadPtr; + PhySocket *tcp; + PhySocket *assignedUdp; + time_t lastActivity; + bool newVersion; + }; + + std::map< PhySocket *,Client > clients; + + struct ReverseMappingKey + { + uint64_t sourceZTAddress; + PhySocket *sendingUdpSocket; + uint32_t destIp; + unsigned int destPort; + + ReverseMappingKey() {} + ReverseMappingKey(uint64_t zt,PhySocket *s,uint32_t ip,unsigned int port) : sourceZTAddress(zt),sendingUdpSocket(s),destIp(ip),destPort(port) {} + inline bool operator<(const ReverseMappingKey &k) const throw() { return (memcmp((const void *)this,(const void *)&k,sizeof(ReverseMappingKey)) < 0); } + inline bool operator==(const ReverseMappingKey &k) const throw() { return (memcmp((const void *)this,(const void *)&k,sizeof(ReverseMappingKey)) == 0); } + }; + + std::map< ReverseMappingKey,Client * > reverseMappings; + + void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) + { + if ((from->sa_family == AF_INET)&&(len > 16)&&(len < 2048)) { + const uint64_t destZt = ( + (((uint64_t)(((const unsigned char *)data)[8])) << 32) | + (((uint64_t)(((const unsigned char *)data)[9])) << 24) | + (((uint64_t)(((const unsigned char *)data)[10])) << 16) | + (((uint64_t)(((const unsigned char *)data)[11])) << 8) | + ((uint64_t)(((const unsigned char *)data)[12])) ); + const uint32_t fromIp = ((const struct sockaddr_in *)from)->sin_addr.s_addr; + const unsigned int fromPort = ntohs(((const struct sockaddr_in *)from)->sin_port); + + std::map< ReverseMappingKey,Client * >::iterator rm(reverseMappings.find(ReverseMappingKey(destZt,sock,fromIp,fromPort))); + if (rm != reverseMappings.end()) { + Client &c = *(rm->second); + + unsigned long mlen = len; + if (c.newVersion) + mlen += 7; // new clients get IP info + + if ((c.tcpWritePtr + 5 + mlen) <= sizeof(c.tcpWriteBuf)) { + if (!c.tcpWritePtr) + phy->tcpSetNotifyWritable(c.tcp,true); + + c.tcpWriteBuf[c.tcpWritePtr++] = 0x17; // look like TLS data + c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2 + c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2 + + c.tcpWriteBuf[c.tcpWritePtr++] = (char)((mlen >> 8) & 0xff); + c.tcpWriteBuf[c.tcpWritePtr++] = (char)(mlen & 0xff); + + if (c.newVersion) { + c.tcpWriteBuf[c.tcpWritePtr++] = (char)4; // IPv4 + *((uint32_t *)(c.tcpWriteBuf + c.tcpWritePtr)) = fromIp; + c.tcpWritePtr += 4; + c.tcpWriteBuf[c.tcpWritePtr++] = (char)((fromPort >> 8) & 0xff); + c.tcpWriteBuf[c.tcpWritePtr++] = (char)(fromPort & 0xff); + } + + for(unsigned long i=0;i::iterator rm(reverseMappings.begin());rm!=reverseMappings.end();) { + if (rm->second == (Client *)*uptr) + reverseMappings.erase(rm++); + else ++rm; + } + clients.erase(sock); + } + + void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) + { + Client &c = *((Client *)*uptr); + c.lastActivity = time((time_t *)0); + + for(unsigned long i=0;i= sizeof(c.tcpReadBuf)) { + phy->close(sock); + return; + } + c.tcpReadBuf[c.tcpReadPtr++] = ((const char *)data)[i]; + + if (c.tcpReadPtr >= 5) { + unsigned long mlen = ( ((((unsigned long)c.tcpReadBuf[3]) & 0xff) << 8) | (((unsigned long)c.tcpReadBuf[4]) & 0xff) ); + if (c.tcpReadPtr >= (mlen + 5)) { + if (mlen == 4) { + // Right now just sending this means the client is 'new enough' for the IP header + c.newVersion = true; + } else if (mlen >= 7) { + char *payload = c.tcpReadBuf + 5; + unsigned long payloadLen = mlen; + + struct sockaddr_in dest; + memset(&dest,0,sizeof(dest)); + if (c.newVersion) { + if (*payload == (char)4) { + // New clients tell us where their packets go. + ++payload; + dest.sin_family = AF_INET; + dest.sin_addr.s_addr = *((uint32_t *)payload); + payload += 4; + dest.sin_port = *((uint16_t *)payload); // will be in network byte order already + payload += 2; + payloadLen -= 7; + } + } else { + // For old clients we will just proxy everything to a local ZT instance. The + // fact that this will come from 127.0.0.1 will in turn prevent that instance + // from doing unite() with us. It'll just forward. There will not be many of + // these. + dest.sin_family = AF_INET; + dest.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1 + dest.sin_port = htons(9993); + } + + // Note: we do not relay to privileged ports... just an abuse prevention rule. + if ((ntohs(dest.sin_port) > 1024)&&(payloadLen >= 16)) { + if ((payloadLen >= 28)&&(payload[13] != (char)0xff)) { + // Learn reverse mappings -- we will route replies to these packets + // back to their sending TCP socket. They're on a first come first + // served basis. + const uint64_t sourceZt = ( + (((uint64_t)(((const unsigned char *)payload)[13])) << 32) | + (((uint64_t)(((const unsigned char *)payload)[14])) << 24) | + (((uint64_t)(((const unsigned char *)payload)[15])) << 16) | + (((uint64_t)(((const unsigned char *)payload)[16])) << 8) | + ((uint64_t)(((const unsigned char *)payload)[17])) ); + ReverseMappingKey k(sourceZt,c.assignedUdp,dest.sin_addr.s_addr,ntohl(dest.sin_port)); + if (reverseMappings.count(k) == 0) + reverseMappings[k] = &c; + } + + phy->udpSend(c.assignedUdp,(const struct sockaddr *)&dest,payload,payloadLen); + } + } + + memmove(c.tcpReadBuf,c.tcpReadBuf + (mlen + 5),c.tcpReadPtr -= (mlen + 5)); + } + } + } + } + + void phyOnTcpWritable(PhySocket *sock,void **uptr) + { + Client &c = *((Client *)*uptr); + if (c.tcpWritePtr) { + long n = phy->tcpSend(sock,c.tcpWriteBuf,c.tcpWritePtr); + if (n > 0) { + memmove(c.tcpWriteBuf,c.tcpWriteBuf + n,c.tcpWritePtr -= (unsigned long)n); + if (!c.tcpWritePtr) + phy->tcpSetNotifyWritable(sock,false); + } + } else phy->tcpSetNotifyWritable(sock,false); + } + + void doHousekeeping() + { + std::vector toClose; + time_t now = time((time_t *)0); + for(std::map< PhySocket *,Client >::iterator c(clients.begin());c!=clients.end();++c) { + if ((now - c->second.lastActivity) >= ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS) + toClose.push_back(c->first); + } + for(std::vector::iterator s(toClose.begin());s!=toClose.end();++s) + phy->close(*s); // will call phyOnTcpClose() which does cleanup + } +}; + +int main(int argc,char **argv) +{ + signal(SIGPIPE,SIG_IGN); + signal(SIGHUP,SIG_IGN); + srand(time((time_t *)0)); + + TcpProxyService svc; + Phy phy(&svc,true); + svc.phy = &phy; + + { + int poolSize = 0; + for(unsigned int p=ZT_TCP_PROXY_UDP_POOL_START_PORT;((poolSize 120) { + lastDidHousekeeping = now; + svc.doHousekeeping(); + } + } +} diff --git a/updater.cpp b/updater.cpp new file mode 100644 index 000000000..bc36394ba --- /dev/null +++ b/updater.cpp @@ -0,0 +1,177 @@ +/* + * ZeroTier One - Network Virtualization Everywhere + * Copyright (C) 2011-2015 ZeroTier, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * -- + * + * ZeroTier may be used and distributed under the terms of the GPLv3, which + * are available at: http://www.gnu.org/licenses/gpl-3.0.html + * + * If you would like to embed ZeroTier into a commercial application or + * redistribute it in a modified binary form, please contact ZeroTier Networks + * LLC. Start here: http://www.zerotier.com/ + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "version.h" +#include "include/ZeroTierOne.h" +#include "node/Constants.hpp" + +#ifdef __WINDOWS__ +#include +#include +#include +#include +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +#include "node/Utils.hpp" +#include "node/Address.hpp" +#include "node/Dictionary.hpp" +#include "node/Identity.hpp" +#include "osdep/OSUtils.hpp" +#include "osdep/Http.hpp" + +using namespace ZeroTier; + +namespace { + +static std::map< Address,Identity > updateAuthorities() +{ + std::map< Address,Identity > ua; + { // 0001 + Identity id("e9bc3707b5:0:c4cef17bde99eadf9748c4fd11b9b06dc5cd8eb429227811d2c336e6b96a8d329e8abd0a4f45e47fe1bcebf878c004c822d952ff77fc2833af4c74e65985c435"); + ua[id.address()] = id; + } + { // 0002 + Identity id("56520eaf93:0:7d858b47988b34399a9a31136de07b46104d7edb4a98fa1d6da3e583d3a33e48be531532b886f0b12cd16794a66ab9220749ec5112cbe96296b18fe0cc79ca05"); + ua[id.address()] = id; + } + { // 0003 + Identity id("7c195de2e0:0:9f659071c960f9b0f0b96f9f9ecdaa27c7295feed9c79b7db6eedcc11feb705e6dd85c70fa21655204d24c897865b99eb946b753a2bbcf2be5f5e006ae618c54"); + ua[id.address()] = id; + } + { // 0004 + Identity id("415f4cfde7:0:54118e87777b0ea5d922c10b337c4f4bd1db7141845bd54004b3255551a6e356ba6b9e1e85357dbfafc45630b8faa2ebf992f31479e9005f0472685f2d8cbd6e"); + ua[id.address()] = id; + } + return ua; +} + +static bool validateUpdate( + const void *data, + unsigned int len, + const Address &signedBy, + const std::string &signature) +{ + std::map< Address,Identity > ua(updateAuthorities()); + std::map< Address,Identity >::const_iterator updateAuthority = ua.find(signedBy); + if (updateAuthority == ua.end()) + return false; + return updateAuthority->second.verify(data,len,signature.data(),(unsigned int)signature.length()); +} + +/* +static inline const char *updateUrl() +{ +#if defined(__LINUX__) && ( defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__i386) ) + if (sizeof(void *) == 8) + return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x64-LATEST.nfo"; + else return "http://download.zerotier.com/ZeroTierOneInstaller-linux-x86-LATEST.nfo"; +#define GOT_UPDATE_URL +#endif + +#ifdef __APPLE__ + return "http://download.zerotier.com/ZeroTierOneInstaller-mac-combined-LATEST.nfo"; +#define GOT_UPDATE_URL +#endif + +#ifdef __WINDOWS__ + return "http://download.zerotier.com/ZeroTierOneInstaller-windows-intel-LATEST.nfo"; +#define GOT_UPDATE_URL +#endif + +#ifndef GOT_UPDATE_URL + return ""; +#endif +} +*/ + +static const char *parseUpdateNfo( + const char *nfoText, + unsigned int &vMajor, + unsigned int &vMinor, + unsigned int &vRevision, + Address &signedBy, + std::string &signature, + std::string &url) +{ + try { + Dictionary nfo(nfoText); + + vMajor = Utils::strToUInt(nfo.get("vMajor").c_str()); + vMinor = Utils::strToUInt(nfo.get("vMinor").c_str()); + vRevision = Utils::strToUInt(nfo.get("vRevision").c_str()); + signedBy = nfo.get("signedBy"); + signature = Utils::unhex(nfo.get("ed25519")); + url = nfo.get("url"); + + if (signature.length() != ZT_C25519_SIGNATURE_LEN) + return "bad ed25519 signature, invalid length"; + if ((url.length() <= 7)||(url.substr(0,7) != "http://")) + return "invalid URL, must begin with http://"; + + return (const char *)0; + } catch ( ... ) { + return "invalid NFO file format or one or more required fields missing"; + } +} + +} // anonymous namespace + +#ifdef __WINDOWS__ +int _tmain(int argc, _TCHAR* argv[]) +#else +int main(int argc,char **argv) +#endif +{ +#ifdef __WINDOWS__ + WSADATA wsaData; + WSAStartup(MAKEWORD(2,2),&wsaData); +#endif + + return 0; +}