コード例 #1
0
    public IEnumerable <Server> ParseUri(string text)
    {
        var dict = text.Replace("tg://socks?", "")
                   .Replace("https://t.me/socks?", "")
                   .Split('&')
                   .Select(str => str.Split('='))
                   .ToDictionary(splited => splited[0], splited => splited[1]);

        if (!dict.ContainsKey("server") || !dict.ContainsKey("port"))
        {
            throw new FormatException();
        }

        var data = new Socks5Server
        {
            Hostname = dict["server"],
            Port     = ushort.Parse(dict["port"])
        };

        if (dict.ContainsKey("user") && !string.IsNullOrWhiteSpace(dict["user"]))
        {
            data.Username = dict["user"];
        }

        if (dict.ContainsKey("pass") && !string.IsNullOrWhiteSpace(dict["pass"]))
        {
            data.Password = dict["pass"];
        }

        return(new[] { data });
    }
コード例 #2
0
ファイル: Program.cs プロジェクト: biljettshop/Socks5
        static void Main(string[] args)
        {
            Socks5Server x = new Socks5Server(IPAddress.Any, 1080);

            x.Start();
            //enable plugin.

            /*foreach (object p in PluginLoader.GetPlugins)
             * {
             *  if (p.GetType() == typeof(LoginHandlerExample))
             *  {
             *      //enable it.
             *      PluginLoader.ChangePluginStatus(true, p.GetType());
             *      Console.WriteLine("Enabled {0}.", p.GetType().ToString());
             *  }
             * }*/
            //Start showing network stats.
            while (true)
            {
                Console.Clear();
                Console.Write("Total Clients: \t{0}\nTotal Recvd: \t{1:0.00##}MB\nTotal Sent: \t{2:0.00##}MB\n", x.Stats.TotalClients, ((x.Stats.NetworkReceived / 1024f) / 1024f), ((x.Stats.NetworkSent / 1024f) / 1024f));
                Console.Write("Receiving/sec: \t{0}\nSending/sec: \t{1}", x.Stats.BytesReceivedPerSec, x.Stats.BytesSentPerSec);
                Thread.Sleep(1000);
            }
        }
コード例 #3
0
        static void Main(string[] args)
        {
            Socks5Server x = new Socks5Server(IPAddress.Any, 10084);

            x.Start();
            PluginLoader.ChangePluginStatus(false, typeof(DataHandlerExample));
            //enable plugin.
            foreach (object pl in PluginLoader.GetPlugins)
            {
                //if (pl.GetType() == typeof(LoginHandlerExample))
                //{
                //    //enable it.
                //    PluginLoader.ChangePluginStatus(true, pl.GetType());
                //    Console.WriteLine("Enabled {0}.", pl.GetType().ToString());
                //}
            }
            //Start showing network stats.
            Socks5Client p = new Socks5Client("localhost", 10084, "127.0.0.1", 10084, "yolo", "swag");

            p.OnConnected += p_OnConnected;
            p.ConnectAsync();
            //while (true)
            //{
            // //   Console.Clear();
            //    Console.Write("Total Clients: \t{0}\nTotal Recvd: \t{1:0.00##}MB\nTotal Sent: \t{2:0.00##}MB\n", x.Stats.TotalClients, ((x.Stats.NetworkReceived / 1024f) / 1024f), ((x.Stats.NetworkSent / 1024f) / 1024f));
            //    Console.Write("Receiving/sec: \t{0}\nSending/sec: \t{1}", x.Stats.BytesReceivedPerSec, x.Stats.BytesSentPerSec);
            //    Thread.Sleep(1000);
            //}
        }
コード例 #4
0
 /// <summary>
 /// Creates a new and configured instance of the <see cref="Log4NetUdpReceiver"/> class.
 /// </summary>
 /// <param name="multicastIp">The multicast IP address to listen for.</param>
 /// <param name="listenInterface">The network interface to listen on.</param>
 /// <param name="codePage">The codepage to use for encoding of the data to parse.</param>
 public Socks5Receiver(int port, int codePage, Socks5Server socks5Server) : base(codePage)
 {
     _port                         = port;
     _socks5Server                 = socks5Server;
     _socks5Server.OnDataSent     += _onDataSent;
     _socks5Server.OnDataReceived += _onDataReceived;
 }
コード例 #5
0
ファイル: Program.cs プロジェクト: cuongnq/Socks5
        static void Main(string[] args)
        {
            Socks5Server x = new Socks5Server(IPAddress.Any, 1080);

            x.Start();
            //PluginLoader.ChangePluginStatus(true, typeof(socks5.ExamplePlugins.DataHandlerExample));
            //enable plugin.

            /*foreach (object p in PluginLoader.GetPlugins)
             * {
             *  if (p.GetType() == typeof(LoginHandlerExample))
             *  {
             *      //enable it.
             *      PluginLoader.ChangePluginStatus(true, p.GetType());
             *      Console.WriteLine("Enabled {0}.", p.GetType().ToString());
             *  }
             * }*/
            //socks5 client.

            /*socks5.Socks5Client.Socks5Client cli = new socks5.Socks5Client.Socks5Client("localhost", 1080, "www.thrdu.de", 80, "thrdev", "testing1234");
             * cli.OnConnected += cli_OnConnected;
             * cli.Connect();*/
            //Start showing network stats.
            while (true)
            {
                Console.Clear();
                Console.Write("Total Clients: \t{0}\nTotal Recvd: \t{1:0.00##}MB\nTotal Sent: \t{2:0.00##}MB\n", x.Stats.TotalClients, ((x.Stats.NetworkReceived / 1024f) / 1024f), ((x.Stats.NetworkSent / 1024f) / 1024f));
                Console.Write("Receiving/sec: \t{0}\nSending/sec: \t{1}", x.Stats.BytesReceivedPerSec, x.Stats.BytesSentPerSec);
                Thread.Sleep(1000);
            }
        }
コード例 #6
0
ファイル: DreamBotApp.cs プロジェクト: PleXone2019/DreamBot
        public DreamBotApp(int port, BotIdentifier id)
        {
            BotId = id;
            Logger.Info(0, "DreamBot [id: {0}] listenning on port {1}", BotId, port);

            _worker = new ClientWorker();
            _worker.QueueForever(AntiDebugging.CheckDebugger, TimeSpan.FromSeconds(1));
            _worker.QueueForever(AntiDebugging.CheckDebugging, TimeSpan.FromSeconds(0.3));

            _peerList = new PeerList(_worker);
            _peerList.DesparadoModeActivated += DesperateModeActivated;

            _listener = new MessageListener(port);
            _listener.UdpPacketReceived += EnqueueMessage;

            _comunicationManager = new ComunicationManager(_listener, _worker);
            _peersManager = new PeerManager(_comunicationManager, _peerList, _worker, BotId);
            _messagesManager = new MessageManager(_peersManager);

            _messagesManager.Register(0x00, MessageType.Request,  typeof(HelloMessage), new HelloMessageHandler(_peerList, _messagesManager), false);
            _messagesManager.Register(0x01, MessageType.Reply, typeof(HelloReplyMessage), new HelloReplyMessageHandler(_peerList, _messagesManager), true);
            _messagesManager.Register(0x02, MessageType.Request, typeof(GetPeerListMessage), new GetPeerListMessageHandler(_peerList, _messagesManager), true);
            _messagesManager.Register(0x03, MessageType.Reply, typeof(GetPeerListReplyMessage), new GetPeerListReplyMessageHandler(_peerList, _messagesManager), true);
            _messagesManager.Register(0xFF, MessageType.Special, typeof(InvalidMessage), new InvalidMessageHandler(_peerList), false);

            _socks5 = new Socks5Server(8009);
            _https = new HttpsProxyServer(8019);
            //_connectivityTester = new ConnectivityTester();
            //_connectivityTester.OnConnectivityStatusChanged += OnConnectivityStatusChanged;
        }
コード例 #7
0
        /// <summary>
        /// Waits for a client connection to be made and subsequently verifies it.
        /// </summary>
        /// <param name="session">The SI session whose data to transfer.</param>
        /// <param name="server">The instance of the SOCKS5 server to accept
        /// client connections on.</param>
        /// <param name="timeout">The number of milliseconds to wait for a client
        /// connection before returning to the caller, or -1 to wait
        /// indefinitely.</param>
        /// <exception cref="SocketException">An error occurred when accessing the
        /// underlying socket of the SOCKS5 server instance.</exception>
        /// <exception cref="Socks5Exception">The SOCKS5 negotiation with the client
        /// failed.</exception>
        /// <exception cref="TimeoutException">A timeout was specified and it
        /// expired.</exception>
        /// <exception cref="IOException">The stream could not be read, or the
        /// operation timed out.</exception>
        void AcceptClientConnection(SISession session, Socks5Server server,
                                    int timeout = -1)
        {
            var request = server.Accept(timeout);

            if (request.Command != SocksCommand.Connect)
            {
                throw new Socks5Exception("Unexpected SOCKS5 command: " +
                                          request.Command);
            }
            if (request.ATyp != ATyp.Domain)
            {
                throw new Socks5Exception("Unexpected ATyp: " + request.ATyp);
            }
            string hash = (string)request.Destination;
            // Calculate the SHA-1 hash and compare it with the one in the request.
            string calculated = Sha1(session.Sid + im.Jid + session.To);

            if (calculated != hash)
            {
                throw new Socks5Exception("Hostname hash mismatch.");
            }
            // We're good to go.
            server.Reply(ReplyStatus.Succeeded, hash, request.Port);
        }
コード例 #8
0
        public static void Main(string[] args)
        {
            //to test this - use something like proxifier or configure firefox for this proxy.
            Socks5Server s = new Socks5Server(IPAddress.Any, 1080);

            s.Start();
        }
コード例 #9
0
    public async Task StartAsync(Socks5Server server, Mode mode)
    {
        if (mode is not ShareMode shareMode)
        {
            throw new InvalidOperationException();
        }

        _server = server;
        _mode   = shareMode;

        var outboundNetworkInterface = NetworkInterfaceUtils.GetBest();

        var arguments = new List <object?>
        {
            "--interface", $@"\Device\NPF_{outboundNetworkInterface.Id}",
            "--destination", $"{await _server.AutoResolveHostnameAsync()}:{_server.Port}",
            _mode.Argument, SpecialArgument.Flag
        };

        if (_server.Auth())
        {
            arguments.AddRange(new[]
            {
                "--username", server.Username,
                "--password", server.Password
            });
        }

        await StartGuardAsync(Arguments.Format(arguments));
    }
コード例 #10
0
        public Agent(int port, BotIdentifier id)
        {
            BotIdentifier.Id = id;
            Logger.Info("Vinchuca Agent [id: {0}] listenning on port {1}", BotIdentifier.Id, port);

            _worker = ClientWorker.Instance;
            _worker.QueueForever(AntiDebugging.CheckDebugger, TimeSpan.FromSeconds(1));
            _worker.QueueForever(AntiDebugging.CheckDebugging, TimeSpan.FromSeconds(0.3));
            _worker.QueueForever(SandboxDetection.CheckSandboxed, TimeSpan.FromSeconds(1));

            _peerList = new PeerList(_worker);
            _peerList.DesparadoModeActivated += DesperateModeActivated;


            if (IPAddressUtils.BehingNAT(IPAddressUtils.GetLocalIPAddress()))
            {
                var upnpSearcher = new UpnpSearcher();
                upnpSearcher.DeviceFound += (s, e) =>
                {
                    PublicIP = e.Device.GetExternalIP();
                    Logger.Verbose("External IP Address: {0}", PublicIP);
                    try
                    {
                        var externalPort = BotIdentifier.Id.GetPort();
                        BotIdentifier.EndPoint = new IPEndPoint(PublicIP, externalPort);
                        var device = e.Device;
                        device.CreatePortMap(new Mapping(Protocol.Udp, port, externalPort));
                        device.CreatePortMap(new Mapping(Protocol.Tcp, port, externalPort + 1));
                        device.CreatePortMap(new Mapping(Protocol.Tcp, port, externalPort + 2));
                    }
                    catch (MappingException ex)
                    {
                        Logger.Warn("UPnp - port mapping failed: {0} - {1}", ex.ErrorCode, ex.ErrorText);
                    }
                    finally
                    {
                        upnpSearcher.Stop();
                    }
                };
                upnpSearcher.Search();
            }

            _listener = new MessageListener(port);
            _listener.UdpPacketReceived += EnqueueMessage;
            _communicationManager        = new CommunicationManager(_listener, _worker);
            var peersManager = new PeerManager(_communicationManager, _peerList, _worker);

            _messagesManager           = new MessageManager(peersManager);
            peersManager.MessageSender = _messagesManager;

            RegisterMessageHandlers(peersManager);

            var externPort = BotIdentifier.Id.GetPort();

            _socks5             = new Socks5Server(externPort + 1);
            _https              = new HttpsProxyServer(externPort + 2);
            _connectivityTester = new ConnectivityTester();
            _connectivityTester.OnConnectivityStatusChanged += OnConnectivityStatusChanged;
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: cuongnq/Socks5
        static void Main(string[] args)
        {
            Socks5Server f = new Socks5Server(IPAddress.Any, 1080);

            f.Authentication    = true;
            f.OnAuthentication += f_OnAuthentication;
            f.Start();
        }
コード例 #12
0
        static void Main(string[] args)
        {
            Socks5Server x = new Socks5Server(IPAddress.Any, 1080);

            PluginLoader.ChangePluginStatus(false, typeof(Auth));
            x.Start();
            while (true)
            {
                Console.Clear();
                Console.Write("Total Clients: \t{0}\nTotal Recvd: \t{1:0.00##}MB\nTotal Sent: \t{2:0.00##}MB\n", x.Stats.TotalClients, ((x.Stats.NetworkReceived / 1024f) / 1024f), ((x.Stats.NetworkSent / 1024f) / 1024f));
                Console.Write("Receiving/sec: \t{0}\nSending/sec: \t{1}", x.Stats.BytesReceivedPerSec, x.Stats.BytesSentPerSec);
                Thread.Sleep(1000);
            }
        }
コード例 #13
0
    public static async Task <NatTypeTestResult> DiscoveryNatTypeAsync(Socks5Server socks5, CancellationToken ctx = default)
    {
        var stunServer = Global.Settings.STUN_Server;
        var port       = (ushort)Global.Settings.STUN_Server_Port;
        var local      = new IPEndPoint(IPAddress.Any, 0);

        var socks5Option = new Socks5CreateOption
        {
            Address          = await DnsUtils.LookupAsync(socks5.Hostname),
            Port             = socks5.Port,
            UsernamePassword = new UsernamePassword
            {
                UserName = socks5.Username,
                Password = socks5.Password
            }
        };

        var ip = await DnsUtils.LookupAsync(stunServer);

        if (ip == null)
        {
            return(new NatTypeTestResult {
                Result = "Wrong STUN Server!"
            });
        }

        using IUdpProxy proxy = ProxyFactory.CreateProxy(ProxyType.Socks5, new IPEndPoint(IPAddress.Loopback, 0), socks5Option);
        using var client      = new StunClient5389UDP(new IPEndPoint(ip, port), local, proxy);

        await client.ConnectProxyAsync(ctx);

        try
        {
            await client.QueryAsync(ctx);
        }
        finally
        {
            await client.CloseProxyAsync(ctx);
        }

        var res    = client.State;
        var result = GetSimpleResult(res);

        return(new NatTypeTestResult
        {
            Result = result,
            LocalEnd = res.LocalEndPoint?.ToString(),
            PublicEnd = res.PublicEndPoint?.ToString()
        });
    }
コード例 #14
0
        private void btnResetSrv_Click(object sender, RoutedEventArgs e)
        {
            var thread = new Thread(() =>
            {
                if (x != null)
                {
                    DoLog("SERVER STOPPING!");
                    try
                    {
                        x.Stop();
                    }
                    catch (Exception ex)
                    {
                        DoLog(ex.Message);
                    }
                    x = null;

                    DoLog("\tSERVER STOPPED!");
                }
                DoLog("SERVER RESTARTING!");
                x = new Socks5Server(IPAddress.Any, port);
                x.Start();
                PluginLoader.ChangePluginStatus(false, typeof(DataHandlerExample));
                //enable plugin.
                foreach (object pl in PluginLoader.GetPlugins)
                {
                    //if (pl.GetType() == typeof(LoginHandlerExample))
                    //{
                    //    //enable it.
                    //    PluginLoader.ChangePluginStatus(true, pl.GetType());
                    //    Console.WriteLine("Enabled {0}.", pl.GetType().ToString());
                    //}
                }

                //Start showing network stats.
                Socks5Client.Socks5Client p = new Socks5Client.Socks5Client("localhost", 80, "127.0.0.1", 80, "lemur", "bison");
                p.OnConnected += p_OnConnected;
                p.ConnectAsync();
                //while (true)
                //{
                // //   Console.Clear();
                //    Console.Write("Total Clients: \t{0}\nTotal Recvd: \t{1:0.00##}MB\nTotal Sent: \t{2:0.00##}MB\n", x.Stats.TotalClients, ((x.Stats.NetworkReceived / 1024f) / 1024f), ((x.Stats.NetworkSent / 1024f) / 1024f));
                //    Console.Write("Receiving/sec: \t{0}\nSending/sec: \t{1}", x.Stats.BytesReceivedPerSec, x.Stats.BytesSentPerSec);
                //    Thread.Sleep(1000);
                //}
                DoLog("\tSERVER RESTARTED!");
            });

            thread.Start();
        }
コード例 #15
0
 private void btnStopSrv_Click(object sender, RoutedEventArgs e)
 {
     if (x != null)
     {
         var thread = new Thread(() =>
         {
             DoLog("SERVER STOPPING!");
             x.Stop();
             x = null;
             DoLog("\tSERVER STOPPED!");
         });
         thread.Start();
     }
 }
コード例 #16
0
ファイル: Socks5ServerWrapper.cs プロジェクト: 2m0nd/Socks5
        public void Start(int port, string userName, string password)
        {
            x = new Socks5Server(IPAddress.Any, port);
            Auth.Initialize(userName, password);
            PluginLoader.ChangePluginStatus(true, typeof(Auth));
            x.Start();

            while (true)
            {
                //Console.Clear();
                Console.Write("Total Clients: \t{0}\nTotal Recvd: \t{1:0.00##}MB\nTotal Sent: \t{2:0.00##}MB\n", x.Stats.TotalClients, ((x.Stats.NetworkReceived / 1024f) / 1024f), ((x.Stats.NetworkSent / 1024f) / 1024f));
                Console.Write("Receiving/sec: \t{0}\nSending/sec: \t{1}", x.Stats.SBytesReceivedPerSec, x.Stats.SBytesSentPerSec);
                Thread.Sleep(TimeSpan.FromHours(1));
            }
        }
コード例 #17
0
        /// <summary>
        /// Creates and returns a fully configured <see cref="ILogProvider"/> instance.
        /// </summary>
        /// <returns>A fully configured <see cref="ILogProvider"/> instance.</returns>
        public ILogProvider GetConfiguredInstance()
        {
            try
            {
                var port = (int)nudPort.Value;
                var ss   = new Socks5Server(IPAddress.Any, port);
                ss.PacketSize = 65535;

                ss.Start();
                return(new Socks5Receiver(port, Settings.Default.PnlLog4NetUdpSettingsEncoding, ss));
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return(null);
            }
        }
コード例 #18
0
    static void AcceptSocks5(Socks5Server server)
    {
        var request = server.Accept();

        if (request.Destination is string)
        {
            server.Reply(0, (string)request.Destination, request.Port);
        }
        else if (request.Destination is System.Net.IPAddress)
        {
            server.Reply(0, (System.Net.IPAddress)request.Destination, request.Port);
        }
        else
        {
            throw new InvalidOperationException($"Unexpected type: \"{request.Destination.GetType()}\".");
        }
    }
コード例 #19
0
    static void RunSocks5()
    {
        Task.Run(
            () =>
        {
            var server = new Socks5Server(socks5port);

            for (;;)
            {
                AcceptSocks5(server);
                WriteSocks5(server);
            }
        }
            ).ContinueWith(
            task => EndApplication(task.Exception.GetBaseException()),
            TaskContinuationOptions.OnlyOnFaulted
            );
    }
コード例 #20
0
ファイル: Program.cs プロジェクト: zoltanharmath/Socks5
        static void Main(string[] args)
        {
            Socks5Server x = new Socks5Server(IPAddress.Any, 1080);

            PluginLoader.ChangePluginStatus(false, typeof(Auth));
            x.Start();
            Socks5Client m = new Socks5Client("localhost", 1080, "portquiz.net", 65532);

            m.OnConnected    += M_OnConnected;
            m.OnDataReceived += M_OnDataReceived;
            m.ConnectAsync();
            while (true)
            {
                //Console.Clear();
                //Console.Write("Total Clients: \t{0}\nTotal Recvd: \t{1:0.00##}MB\nTotal Sent: \t{2:0.00##}MB\n", x.Stats.TotalClients, ((x.Stats.NetworkReceived / 1024f) / 1024f), ((x.Stats.NetworkSent / 1024f) / 1024f));
                //Console.Write("Receiving/sec: \t{0}\nSending/sec: \t{1}", x.Stats.SBytesReceivedPerSec, x.Stats.SBytesSentPerSec);
                Thread.Sleep(1000);
            }
        }
コード例 #21
0
        private void AcceptClientConnection(SISession session, Socks5Server server, int timeout = -1)
        {
            SocksRequest request = server.Accept(timeout);

            if (request.Command != SocksCommand.Connect)
            {
                throw new Socks5Exception("Unexpected SOCKS5 command: " + request.Command);
            }
            if (request.ATyp != ATyp.Domain)
            {
                throw new Socks5Exception("Unexpected ATyp: " + request.ATyp);
            }
            string destination = (string)request.Destination;

            if (this.Sha1(session.Sid + base.im.Jid + session.To) != destination)
            {
                throw new Socks5Exception("Hostname hash mismatch.");
            }
            server.Reply(ReplyStatus.Succeeded, destination, request.Port);
        }
コード例 #22
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            logStream      = new MemoryStream();
            logWriter      = new StreamWriter(logStream);
            logReader      = new StreamReader(logStream);
            port           = 80;
            txtIpAddr.Text = IPAddress.Any.ToString() + ":" + port.ToString();
            x = new Socks5Server(IPAddress.Any, port);
            x.Start();
            TestServer();

            normalOutput = Console.Out;

            Console.SetOut(logWriter);


            timer          = new Timer(500);
            timer.Elapsed += timer_Elapsed;
            timer.Start();
        }
コード例 #23
0
ファイル: Multiplexor.cs プロジェクト: Trogl/WSSockTunnel
        public static async Task Start()
        {
            try
            {
                log.LogInformation("Инициализация");
                wsTunnelConfig = ConfigWatcher.GetSection("wstunnel").ConvertValue <WSTunnelConfig>();


                client = new WsClient();
                await client.OpenManagerTunnel(wsTunnelConfig, DisconnectTunnel, DisconnectSocket);

                await client.Auth();

                var tunnelGuid = await client.OpenDataTunnel(DataReceiver, DisconnecDataTunnel);

                dataConnections.TryAdd(tunnelGuid, new WSDataConnectionInfo
                {
                    TunnelId = tunnelGuid
                });
                var testObj = new EchoReq {
                    ReqId = Guid.NewGuid(), Timestamp = DateTime.UtcNow
                };
                var buffer = Encoding.UTF8.GetBytes(testObj.ToJson());
                await client.SendData(tunnelGuid, Guid.Empty, buffer, buffer.Length);

                log.LogInformation($"Послали echo - {testObj.ReqId}");

                server = new Socks5Server();
                server.Start(wsTunnelConfig.Port, RequireNewConnection, TransferData, CloseSocket);
            }
            catch (Exception e)
            {
                log.LogError($"Ошибка инициализации: {e.Message}");
                server?.Dispose();
                client?.Dispose();
            }
        }
コード例 #24
0
        private void DirectTransfer(SISession session)
        {
            Func <IPAddress, bool> predicate    = null;
            Socks5Server           socks5Server = null;

            try
            {
                socks5Server = this.CreateSocks5Server(this.serverPortFrom, this.serverPortTo);
            }
            catch (Exception exception)
            {
                throw new Socks5Exception("The SOCKS5 server could not be created.", exception);
            }
            IEnumerable <IPAddress> source = null;

            try
            {
                source = this.GetExternalAddresses();
                if (predicate == null)
                {
                    predicate = addr => this.BehindNAT(addr);
                }
                if (source.Any <IPAddress>(predicate) && this.UseUPnP)
                {
                    try
                    {
                        UPnP.ForwardPort(socks5Server.Port, ProtocolType.Tcp, "XMPP SOCKS5 File-transfer");
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            }
            catch (NotSupportedException)
            {
            }
            Task.Factory.StartNew(delegate {
                try
                {
                    this.AcceptClientConnection(session, socks5Server, 0x2bf20);
                    this.SendData(session, socks5Server.GetStream());
                }
                finally
                {
                    socks5Server.Close();
                }
            });
            XmlElement       e   = Xml.Element("query", "http://jabber.org/protocol/bytestreams").Attr("sid", session.Sid);
            ISet <IPAddress> set = new HashSet <IPAddress>();

            if (source != null)
            {
                set.UnionWith(source);
            }
            set.UnionWith(GetIpAddresses(null));
            foreach (IPAddress address in set)
            {
                e.Child(Xml.Element("streamhost", null).Attr("jid", base.im.Jid.ToString()).Attr("host", address.ToString()).Attr("port", socks5Server.Port.ToString()));
            }
            Iq errorIq = base.im.IqRequest(IqType.Set, session.To, base.im.Jid, e, null, -1, "");

            if (errorIq.Type == IqType.Error)
            {
                throw Util.ExceptionFromError(errorIq, "The SOCKS5 connection could not be established.");
            }
        }
コード例 #25
0
        /// <summary>
        /// Performs a direct transfer, meaning we act as a SOCKS5 server.
        /// </summary>
        /// <param name="session">The SI session whose data to transfer.</param>
        /// <exception cref="Socks5Exception">The SOCKS5 server could not be
        /// instantiated.</exception>
        /// <exception cref="XmppErrorException">The server returned an XMPP error code.
        /// Use the Error property of the XmppErrorException to obtain the specific
        /// error condition.</exception>
        /// <exception cref="XmppException">The server returned invalid data or another
        /// unspecified XMPP error occurred.</exception>
        void DirectTransfer(SISession session)
        {
            // Create the listening SOCKS5 server.
            Socks5Server socks5Server = null;

            try {
                socks5Server = CreateSocks5Server(serverPortFrom, serverPortTo);
            } catch (Exception e) {
                throw new Socks5Exception("The SOCKS5 server could not be created.", e);
            }
            IEnumerable <IPAddress> externalAddresses = null;

            try {
                externalAddresses = GetExternalAddresses();
                // Check if we might need to forward the server port.
                if (externalAddresses.Any(addr => BehindNAT(addr)) && UseUPnP)
                {
                    try {
                        UPnP.ForwardPort(socks5Server.Port, ProtocolType.Tcp,
                                         "XMPP SOCKS5 File-transfer");
                    } catch (InvalidOperationException) {
                        // If automatic port forwarding failed for whatever reason, just
                        // go on normally. The user can still configure forwarding manually.
                    }
                }
            } catch (NotSupportedException) {
                // Not much we can do.
            }
            // Waiting for a client connection is a blocking call and we need to
            // negotiate the SOCKS5 connection after we send the IQ request but
            // _before_ we wait for the IQ response.
            Task.Factory.StartNew(() => {
                try {
                    AcceptClientConnection(session, socks5Server, acceptTimeout);
                    SendData(session, socks5Server.GetStream());
                } finally {
                    socks5Server.Close();
                }
            });

            // Send target a list of streamhosts, one for each active network interface.
            var xml = Xml.Element("query", "http://jabber.org/protocol/bytestreams")
                      .Attr("sid", session.Sid);
            // Compile a set of all our IP addresses that we can advertise.
            ISet <IPAddress> ips = new HashSet <IPAddress>();

            if (externalAddresses != null)
            {
                ips.UnionWith(externalAddresses);
            }
            ips.UnionWith(GetIpAddresses());
            foreach (var ip in ips)
            {
                xml.Child(Xml.Element("streamhost")
                          .Attr("jid", im.Jid.ToString())
                          .Attr("host", ip.ToString())
                          .Attr("port", socks5Server.Port.ToString()));
            }
            // Send IQ with streamhosts to the target.
            var iq = im.IqRequest(IqType.Set, session.To, im.Jid, xml);

            if (iq.Type == IqType.Error)
            {
                throw Util.ExceptionFromError(iq, "The SOCKS5 connection could not " +
                                              "be established.");
            }
        }
コード例 #26
0
 public SocksClient(Client cli, Socks5Server server)
 {
     Client = cli;
     Server = server;
 }
コード例 #27
0
        /// <summary>
        /// Performs a direct transfer, meaning we act as a SOCKS5 server.
        /// </summary>
        /// <param name="session">The SI session whose data to transfer.</param>
        /// <exception cref="Socks5Exception">The SOCKS5 server could not be
        /// instantiated.</exception>
        /// <exception cref="XmppErrorException">The server returned an XMPP error code.
        /// Use the Error property of the XmppErrorException to obtain the specific
        /// error condition.</exception>
        /// <exception cref="XmppException">The server returned invalid data or another
        /// unspecified XMPP error occurred.</exception>
        private async Task DirectTransfer(SISession session)
        {
            // Create the listening SOCKS5 server.
            Socks5Server socks5Server = null;

            try
            {
                socks5Server = CreateSocks5Server(serverPortFrom, serverPortTo);
            }
            catch (Exception e)
            {
                throw new Socks5Exception("The SOCKS5 server could not be created.", e);
            }
            IEnumerable <IPAddress> externalAddresses = null;

            try
            {
                externalAddresses = await GetExternalAddresses();

                // Check if we might need to forward the server port.
            }
            catch (NotSupportedException)
            {
                // Not much we can do.
            }
            // Waiting for a client connection is a blocking call and we need to
            // negotiate the SOCKS5 connection after we send the IQ request but
            // _before_ we wait for the IQ response.
            Task.Run(async() =>
            {
                try
                {
                    await AcceptClientConnection(session, socks5Server, acceptTimeout);
                    await SendData(session, socks5Server.GetStream());
                }
                finally
                {
                    socks5Server.Close();
                }
            });

            // Send target a list of streamhosts, one for each active network interface.
            var xml = Xml.Element("query", "http://jabber.org/protocol/bytestreams")
                      .Attr("sid", session.Sid);
            // Compile a set of all our IP addresses that we can advertise.
            ISet <IPAddress> ips = new HashSet <IPAddress>();

            if (externalAddresses != null)
            {
                ips.UnionWith(externalAddresses);
            }
            ips.UnionWith(GetIpAddresses());
            foreach (var ip in ips)
            {
                xml.Child(Xml.Element("streamhost")
                          .Attr("jid", im.Jid.ToString())
                          .Attr("host", ip.ToString())
                          .Attr("port", socks5Server.Port.ToString()));
            }
            // Send IQ with streamhosts to the target.
            var iq = await im.IqRequest(IqType.Set, session.To, im.Jid, xml);

            if (iq.Type == IqType.Error)
            {
                throw Util.ExceptionFromError(iq, "The SOCKS5 connection could not " +
                                              "be established.");
            }
        }
コード例 #28
0
 static void WriteSocks5(Socks5Server server) => File.OpenRead(socks5filepath).CopyTo(server.GetStream());
コード例 #29
0
        static void Main(string[] args)
        {
            Socks5Server f = new Socks5Server(IPAddress.Any, 1080);

            f.Start();
        }