public async Task SendAsync_Get_Cookies()
        {
            var name  = "name";
            var value = "value";

            var message = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri($"http://httpbin.org/cookies/set?{name}={value}")
            };

            var settings        = new ProxySettings();
            var proxyClient     = new NoProxyClient(settings);
            var cookieContainer = new CookieContainer();

            using var proxyClientHandler = new ProxyClientHandler(proxyClient)
                  {
                      CookieContainer = cookieContainer
                  };

            using var client = new HttpClient(proxyClientHandler);
            var response = await client.SendAsync(message);

            var cookies = cookieContainer.GetCookies(new Uri("http://httpbin.org/"));

            Assert.Single(cookies);
            var cookie = cookies[name];

            Assert.Equal(name, cookie.Name);
            Assert.Equal(value, cookie.Value);

            client.Dispose();
        }
Esempio n. 2
0
        public async Task CheckRelayingToNonExistentHostnameResolveRemotely()
        {
            using (var relay = CreateRelayServer())
            {
                relay.ResolveHostnamesRemotely = true;
                relay.Start();

                var settings = new ProxySettings()
                {
                    Host             = relay.LocalEndPoint.Address.ToString(),
                    Port             = relay.LocalEndPoint.Port,
                    ConnectTimeout   = 15000,
                    ReadWriteTimeOut = 15000
                };

                using (var proxyClientHandler = new ProxyClientHandler <Socks4a>(settings))
                {
                    using (var httpClient = new HttpClient(proxyClientHandler))
                    {
                        try
                        {
                            await httpClient.GetAsync("https://nonexists-subdomain.google.com");

                            Assert.Fail();
                        }
                        catch (ProxyException e)
                        {
                            Assert.AreEqual("Request rejected or failed", e.Message);
                        }
                    }
                }
            }
        }
        public async Task CheckRelayingToNonExistentHostnameUsingCustomResolver()
        {
            using (var relay = CreateRelayServer())
            {
                relay.ResolveHostnamesRemotely = false;
                relay.DnsResolver = new CustomDnsResolver();
                relay.Start();

                var settings = new ProxySettings
                {
                    Host             = relay.LocalEndPoint.Address.ToString(),
                    Port             = relay.LocalEndPoint.Port,
                    ConnectTimeout   = 15000,
                    ReadWriteTimeOut = 15000,
                };

                using (var proxyClientHandler = new ProxyClientHandler <Socks4a>(settings))
                {
                    using (var httpClient = new HttpClient(proxyClientHandler))
                    {
                        try
                        {
                            await httpClient.GetAsync("https://nonexists-subdomain.google.com");

                            Assert.Fail();
                        }
                        catch (ProxyException)
                        {
                            // this is expected
                        }
                    }
                }
            }
        }
        public async Task CheckRelayingToNonExistentIpAddress()
        {
            using (var relay = CreateRelayServer())
            {
                relay.Start();

                var settings = new ProxySettings
                {
                    Host             = relay.LocalEndPoint.Address.ToString(),
                    Port             = relay.LocalEndPoint.Port,
                    ConnectTimeout   = 15000,
                    ReadWriteTimeOut = 15000,
                };

                using (var proxyClientHandler = new ProxyClientHandler <Socks4a>(settings))
                {
                    using (var httpClient = new HttpClient(proxyClientHandler))
                    {
                        try
                        {
                            await httpClient.GetAsync("http://0.1.2.3");

                            Assert.Fail();
                        }
                        catch (ProxyException e)
                        {
                            Assert.AreEqual("Request rejected or failed", e.Message);
                        }
                    }
                }
            }
        }
        private static async Task <HttpResponseMessage> RequestAsync(HttpRequestMessage request)
        {
            var settings    = new ProxySettings();
            var proxyClient = new NoProxyClient(settings);

            using var proxyClientHandler = new ProxyClientHandler(proxyClient)
                  {
                      CookieContainer = new CookieContainer()
                  };

            using var client = new HttpClient(proxyClientHandler);
            return(await client.SendAsync(request));
        }
        /// <summary>
        /// Add's a sock's proxy to the HTTPClient Handler using "SocksSharp" and refreshes the shared HttpClient
        /// </summary>
        /// <param name="proxyUrl"></param>
        /// <param name="proxyPort"></param>
        public static void AddSocksProxy(string proxyUrl, int proxyPort)
        {
            client.CancelPendingRequests();
            client.Dispose();

            var settings = new ProxySettings {
                Host = proxyUrl,
                Port = proxyPort
            };

            var proxyClientHandler = new ProxyClientHandler <Socks5>(settings);

            client = new HttpClient(proxyClientHandler);
        }
        private static async Task <byte[]> DownloadResolverListAsync(ProxySettings proxySettings = null)
        {
            try
            {
                if (proxySettings != null)
                {
                    using (var proxyClientHandler = new ProxyClientHandler <Socks5>(proxySettings))
                    {
                        using (var client = new HttpClient(proxyClientHandler))
                        {
                            var getDataTask  = client.GetByteArrayAsync(Global.ResolverUrl);
                            var resolverList = await getDataTask.ConfigureAwait(false);

                            return(resolverList);
                        }
                    }
                }
                using (var client = new HttpClient())
                {
                    var getDataTask  = client.GetByteArrayAsync(Global.ResolverUrl);
                    var resolverList = await getDataTask.ConfigureAwait(false);

                    return(resolverList);
                }
            }
            catch (HttpRequestException)
            {
                if (proxySettings != null)
                {
                    using (var proxyClientHandler = new ProxyClientHandler <Socks5>(proxySettings))
                    {
                        using (var client = new HttpClient(proxyClientHandler))
                        {
                            var getDataTask  = client.GetByteArrayAsync(Global.ResolverBackupUrl);
                            var resolverList = await getDataTask.ConfigureAwait(false);

                            return(resolverList);
                        }
                    }
                }
                using (var client = new HttpClient())
                {
                    var getDataTask  = client.GetByteArrayAsync(Global.ResolverBackupUrl);
                    var resolverList = await getDataTask.ConfigureAwait(false);

                    return(resolverList);
                }
            }
        }
Esempio n. 8
0
 public static async Task <byte[]> DownloadRemoteInstallerAsync(Uri uri, ProxySettings proxySettings = null)
 {
     if (proxySettings != null)
     {
         using (var proxyClientHandler = new ProxyClientHandler <Socks5>(proxySettings))
         {
             using (var client = new HttpClient(proxyClientHandler))
             {
                 var getDataTask = client.GetByteArrayAsync(uri);
                 return(await getDataTask.ConfigureAwait(false));
             }
         }
     }
     using (var client = new HttpClient())
     {
         var getDataTask = client.GetByteArrayAsync(uri);
         return(await getDataTask.ConfigureAwait(false));
     }
 }
Esempio n. 9
0
 private static async Task <byte[]> DownloadRemoteUpdateFileAsync(string remoteUpdateFile, ProxySettings proxySettings = null)
 {
     if (proxySettings != null)
     {
         using (var proxyClientHandler = new ProxyClientHandler <Socks5>(proxySettings))
         {
             using (var client = new HttpClient(proxyClientHandler))
             {
                 var getDataTask = client.GetByteArrayAsync(remoteUpdateFile);
                 return(await getDataTask.ConfigureAwait(false));
             }
         }
     }
     using (var client = new HttpClient())
     {
         var getDataTask = client.GetByteArrayAsync(remoteUpdateFile);
         return(await getDataTask.ConfigureAwait(false));
     }
 }
Esempio n. 10
0
        public override bool Connect()
        {
            var data = (GpsdInfo)GpsInfo;

            IsRunning = true;
            OnGpsStatusChanged(GpsStatus.Connecting);

            try
            {
                _client       = data.IsProxyEnabled ? ProxyClientHandler.GetTcpClient(data) : new TcpClient(data.Address, data.Port);
                _streamReader = new StreamReader(_client.GetStream());
                _streamWriter = new StreamWriter(_client.GetStream());

                _gpsdDataParser = new GpsdDataParser();

                var gpsData = "";
                while (string.IsNullOrEmpty(gpsData))
                {
                    gpsData = _streamReader.ReadLine();
                }

                var message = _gpsdDataParser.GetGpsData(gpsData);
                var version = message as GpsdVersion;
                if (version == null)
                {
                    return(false);
                }
                ExecuteGpsdCommand(data.GpsOptions.GetCommand());
                OnGpsStatusChanged(GpsStatus.Connected);


                StartGpsReading(data);
            }
            catch
            {
                Disconnect();
                throw;
            }
            return(true);
        }
Esempio n. 11
0
        public static async Task DoTestRequest <T>(IPEndPoint relayEndPoint, string url)
            where T : IProxy
        {
            var settings = new ProxySettings
            {
                Host             = relayEndPoint.Address.ToString(),
                Port             = relayEndPoint.Port,
                ConnectTimeout   = 15000,
                ReadWriteTimeOut = 15000,
            };

            string responseContentWithProxy;

            using (var proxyClientHandler = new ProxyClientHandler <T>(settings))
            {
                using (var httpClient = new HttpClient(proxyClientHandler))
                {
                    var response = await httpClient.SendAsync(GenerateRequestMessageForTestRequest(url));

                    responseContentWithProxy = await response.Content.ReadAsStringAsync();
                }
            }

            string responseContentWithoutProxy;

            using (var handler = new HttpClientHandler())
            {
                handler.AllowAutoRedirect = false;

                using (var httpClient = new HttpClient(handler))
                {
                    var response = await httpClient.SendAsync(GenerateRequestMessageForTestRequest(url));

                    responseContentWithoutProxy = await response.Content.ReadAsStringAsync();
                }
            }

            Assert.AreEqual(responseContentWithoutProxy, responseContentWithProxy);
        }
Esempio n. 12
0
 private static void Init()
 {
     if (AppConfiguration.UseProxy)
     {
         const string strSocks5 = "socks5";
         const string strHttp   = "http";
         if (AppConfiguration.Proxy.Type == strSocks5)
         {
             var proxyClientHandler = new ProxyClientHandler <Socks5>(new ProxySettings()
             {
                 Host        = AppConfiguration.Proxy.Host,
                 Port        = AppConfiguration.Proxy.Port,
                 Credentials = AppConfiguration.Proxy.Auth
                     ? new NetworkCredential(AppConfiguration.Proxy.Username, AppConfiguration.Proxy.Password)
                     : null
             });
             var httpClient = new HttpClient(proxyClientHandler);
             _bot = new TelegramBotClient(AppConfiguration.Bot.Token, httpClient);
         }
         else if (AppConfiguration.Proxy.Type == strHttp)
         {
             var proxy = new WebProxy(AppConfiguration.Proxy.Host, AppConfiguration.Proxy.Port)
             {
                 UseDefaultCredentials = true
             };
             _bot = new TelegramBotClient(AppConfiguration.Bot.Token, proxy);
         }
         else
         {
             Console.WriteLine("no suitable proxy setting found,use os default setting.");
             _bot = new TelegramBotClient(AppConfiguration.Bot.Token);
         }
     }
     else
     {
         _bot = new TelegramBotClient(AppConfiguration.Bot.Token);
     }
 }
        public async Task CheckIfLargeFilesAreDownloaded()
        {
            using (var relay = CreateRelayServer())
            {
                relay.ResolveHostnamesRemotely = false;
                relay.Start();

                var settings = new ProxySettings
                {
                    Host             = relay.LocalEndPoint.Address.ToString(),
                    Port             = relay.LocalEndPoint.Port,
                    ConnectTimeout   = 15000,
                    ReadWriteTimeOut = 15000,
                };

                using (var proxyClientHandler = new ProxyClientHandler <Socks4a>(settings))
                {
                    using (var httpClient = new HttpClient(proxyClientHandler))
                    {
                        var request = new HttpRequestMessage
                        {
                            Version    = HttpVersion.Version11,
                            Method     = HttpMethod.Get,
                            RequestUri = new Uri("https://updates.tdesktop.com/tsetup/tportable.1.8.15.zip"),
                        };

                        var response = await httpClient.SendAsync(request);

                        var content = await response.Content.ReadAsByteArrayAsync();

                        var contentLengthHeader = long.Parse(response.Content.Headers.First(h => h.Key.Equals("Content-Length")).Value.First());
                        Assert.IsTrue(contentLengthHeader > 5 * 1024 * 1024); // at least 5 MB

                        Assert.AreEqual(contentLengthHeader, content.Length);
                    }
                }
            }
        }
Esempio n. 14
0
        public static async Task <string> DownloadRemoteSignatureAsync(Uri uri, ProxySettings proxySettings = null)
        {
            if (proxySettings != null)
            {
                using (var proxyClientHandler = new ProxyClientHandler <Socks5>(proxySettings))
                {
                    using (var client = new HttpClient(proxyClientHandler))
                    {
                        var getDataTask  = client.GetStringAsync(uri);
                        var resolverList = await getDataTask.ConfigureAwait(false);

                        return(resolverList);
                    }
                }
            }
            using (var client = new HttpClient())
            {
                var getDataTask  = client.GetStringAsync(uri);
                var resolverList = await getDataTask.ConfigureAwait(false);

                return(resolverList);
            }
        }
Esempio n. 15
0
        public async Task HttpClient_SendAsync_SetCipherSuites_SendsCorrectly()
        {
            // Custom cipher suites are not currently supported on Windows as it uses
            // SecureChannel for the TLS handshake, and ciphers are set by the windows policies.
            // The only known workaround is implementing an OpenSSL / BouncyCastle solution or just using WSL or a linux VM.
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return;
            }

            var message = new HttpRequestMessage(HttpMethod.Get, "https://www.howsmyssl.com/");

            message.Headers.Host = "howsmyssl.com";

            using var handler             = new ProxyClientHandler <NoProxy>(new ProxySettings());
            handler.UseCustomCipherSuites = true;
            handler.AllowedCipherSuites   = new TlsCipherSuite[]
            {
                TlsCipherSuite.TLS_AES_256_GCM_SHA384,
                TlsCipherSuite.TLS_CHACHA20_POLY1305_SHA256,
                TlsCipherSuite.TLS_AES_128_GCM_SHA256,
                TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
            };

            using var client = new HttpClient(handler);
            var response = await client.SendAsync(message);

            var page = await response.Content.ReadAsStringAsync();

            Assert.Contains("TLS_AES_256_GCM_SHA384", page);
            Assert.Contains("TLS_CHACHA20_POLY1305_SHA256", page);
            Assert.Contains("TLS_AES_128_GCM_SHA256", page);
            Assert.Contains("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", page);

            // Make sure it does not contain a cipher suite that we didn't send but that is usually sent by System.Net
            Assert.DoesNotContain("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", page);
        }
Esempio n. 16
0
        private static HttpMessageHandler CreateClientHandler(string url, Dictionary <string, string> header,
                                                              bool autoredirect, bool useProxy = false)
        {
            ParseCookiesInHeader(url, header);
            HttpMessageHandler result = null;

            if (ProgramSettings.Settings.UseProxy && ProxySettings != null)
            {
                switch (ProgramSettings.Settings.ProxyType)
                {
                case ProxyType.SOCKS4: {
                    var handler = new ProxyClientHandler <Socks4>(ProxySettings)
                    {
                        CookieContainer = CookieContainer,
                    };
                    handler.ServerCertificateCustomValidationCallback +=
                        (sender, cert, chain, sslPolicyErrors) => true;
                    result = handler;
                }
                break;

                case ProxyType.SOCKS4A: {
                    var handler = new ProxyClientHandler <Socks4a>(ProxySettings)
                    {
                        CookieContainer = CookieContainer,
                    };
                    handler.ServerCertificateCustomValidationCallback +=
                        (sender, cert, chain, sslPolicyErrors) => true;
                    result = handler;
                }
                break;

                case ProxyType.SOCKS5: {
                    var handler = new ProxyClientHandler <Socks5>(ProxySettings)
                    {
                        CookieContainer = CookieContainer,
                    };
                    handler.ServerCertificateCustomValidationCallback +=
                        (sender, cert, chain, sslPolicyErrors) => true;
                    result = handler;
                }
                break;
                }
            }

            if (result == null)
            {
                var handler = new HttpClientHandler()
                {
                    AllowAutoRedirect = autoredirect,
                    Proxy             = ProgramSettings.Settings.UseProxy &&
                                        (useProxy || !ProgramSettings.Settings.ProxyNotDefaultEnable) &&
                                        Proxy != null
                        ? Proxy
                        : WebRequest.DefaultWebProxy,
                    CookieContainer        = CookieContainer,
                    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
                };
                handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
                result = handler;
            }

            return(result);
        }
Esempio n. 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <AppDbContext>(options =>
                                                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <User, IdentityRole>(options =>
            {
                //options.Cookies.ApplicationCookie.AutomaticChallenge = true;
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredLength         = 6;
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication().AddFacebook(options =>
            {
                options.AppId     = Configuration["Authentication:Facebook:AppId"];
                options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            });

            services.AddPager();

            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddMvc(options =>
            {
                options.Filters.Add <ExceptionFilter>();
                options.ModelBinderProviders.Insert(0, new DateModelBinderProvider());
            })
            .AddDataAnnotationsLocalization(
                options => options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource)));

            services.AddSingleton <IConfiguration>(Configuration);

            // Add application services.
            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddSingleton(new CardDocxGenerator(
                                      Path.Combine(Environment.ContentRootPath, Configuration["CardTemplatePath"]),
                                      Path.Combine(Environment.ContentRootPath, Configuration["CardTemplateWithoutStampPath"])));
            services.AddSingleton(new Settings(Path.Combine(Environment.ContentRootPath, "daylimit.txt")));

            // Configuring session
            // Adds a default in-memory implementation of IDistributedCache.
            //services.AddDistributedMemoryCache();
            //services.AddSession(options =>
            //{
            //    // Set a short timeout for easy testing.
            //    options.IdleTimeout = TimeSpan.FromMinutes(1);
            //    options.Cookie.HttpOnly = true;
            //});


            // Add Eaisto api
            //services.AddScoped<IUserStorage>(provider =>
            //    new SessionStorage(provider.GetRequiredService<IHttpContextAccessor>()
            //        .HttpContext.Session));
            services.AddScoped <EaistoSessionManager>();
            services.AddScoped <IUserStorage, DbStorage>();

            // Proxy
            var useProxy = Configuration["useproxy"] == "true";

            if (useProxy)
            {
                var settings = new ProxySettings()
                {
                    Host             = Configuration["proxy:host"],
                    Port             = int.Parse(Configuration["proxy:port"]),
                    Credentials      = new NetworkCredential(Configuration["proxy:login"], Configuration["proxy:password"]),
                    ConnectTimeout   = 180000,
                    ReadWriteTimeOut = 180000
                };
                var proxyClientHandler = new ProxyClientHandler <Socks5>(settings)
                {
                    UseCookies = false,
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); },
                };
                var client = new HttpClient(proxyClientHandler);
                EaistoApi.SetHttpClient(client);
            }
            else
            {
                var handler = new HttpClientHandler
                {
                    AllowAutoRedirect = false,
                    UseCookies        = false,
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); },
                    //SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls,
                    //CheckCertificateRevocationList = false
                    //CookieContainer = cookies
                };

                var client = new HttpClient(handler);
                EaistoApi.SetHttpClient(client);
            }

            //var proxy = new WebProxy(Configuration["proxy:address"])
            //{
            //    //Credentials = new NetworkCredential(Configuration["proxy:login"], Configuration["proxy:password"]),
            //    //BypassProxyOnLocal = true
            //};
            //var httpClientHandler = new HttpClientHandler()
            //{
            //    Proxy = proxy,
            //    AllowAutoRedirect = false,
            //    UseCookies = false,
            //    UseProxy = true,

            //};
            //var client = new HttpClient(httpClientHandler);
            //EaistoApi.SetHttpClient(client);

            services.AddScoped <EaistoApi>();
        }