public void StartProxy(string serverHost, int serverPort, int listeningPort, ProxyType proxyType, int[] filteredPackets)
        {

            Proxy = new ProxyProcessor(serverHost, serverPort, listeningPort, proxyType, filteredPackets);
            SubscribeProxy();
            IsActive = true;
        }
Пример #2
0
        /// <summary>
        /// Создаёт клиент для заданного типа прокси-сервера.
        /// </summary>
        /// <param name="proxyType">Тип прокси-сервера.</param>
        /// <param name="host">Хост прокси-сервера, или значение <see langword="null"/>.</param>
        /// <param name="port">Порт прокси-сервера.</param>
        /// <param name="username">Имя пользователя для авторизации на прокси-сервере, или значение <see langword="null"/>.</param>
        /// <param name="password">Пароль для авторизации на прокси-сервере, или значение <see langword="null"/>.</param>
        /// <returns>Экземпляр класса прокси-клиента, унаследованный от <see cref="xNet.Net.ProxyClient"/>.</returns>
        /// <exception cref="System.InvalidOperationException">Получен неподдерживаемый тип прокси-сервера.</exception>
        public static ProxyClient CreateProxyClient(ProxyType proxyType, string host = null,
            int port = 0, string username = null, string password = null)
        {
            switch (proxyType)
            {
                case ProxyType.Http:
                    return (port == 0) ?
                        new HttpProxyClient(host) : new HttpProxyClient(host, port, username, password);

                case ProxyType.Socks4:
                    return (port == 0) ?
                        new Socks4ProxyClient(host) : new Socks4ProxyClient(host, port, username);

                case ProxyType.Socks4a:
                    return (port == 0) ?
                        new Socks4aProxyClient(host) : new Socks4aProxyClient(host, port, username);

                case ProxyType.Socks5:
                    return (port == 0) ?
                        new Socks5ProxyClient(host) : new Socks5ProxyClient(host, port, username, password);

                default:
                    throw new InvalidOperationException(string.Format(
                        Resources.InvalidOperationException_ProxyHelper_NotSupportedProxyType, proxyType));
            }
        }
Пример #3
0
 public ProxyInfo(ProxyType proxyType, IPEndPoint proxyEndPoint, NetworkCredential proxyCredential)
 {
     fProxyType = proxyType;
     fProxyEndPoint = proxyEndPoint;
     fProxyCredential = proxyCredential;
     fSOCKS5Phase = SOCKS5Phase.spIdle;
 }
Пример #4
0
 public static void SetProxy(ProxyType proxy_type,
                                          string proxy_address,
                                          int proxy_port,
                                          string proxy_user,
                                          string proxy_password)
 {
 }
Пример #5
0
        public Image GetAvatar(string proxy = "", ProxyType proxyType = ProxyType.HTTPS)
        {
            HttpRequest req = new HttpRequest();

            req.AddHeader("Authorization", token);
            ProxyManager.SimpleChange(req, proxy, proxyType);
            return((Bitmap)((new ImageConverter()).ConvertFrom(req.Get(GetAvatarLink(proxy, proxyType)).ToBytes())));
        }
Пример #6
0
        public void AddProxies(string fileName, ProxyType type, List <string> lines)
        {
            List <string> fromFile = new List <string>();
            List <string> fromBox  = new List <string>();

            // Load proxies from file
            if (fileName != "")
            {
                Globals.LogInfo(Components.ProxyManager, $"Trying to load from file {fileName}");

                fromFile.AddRange(File.ReadAllLines(fileName).ToList());
            }
            else
            {
                Globals.LogInfo(Components.ProxyManager, "No file specified, skipping the import from file");
            }

            // Load proxies from textbox lines
            fromBox.AddRange(lines);

            Globals.LogInfo(Components.ProxyManager, $"Adding {fromFile.Count + fromBox.Count} proxies to the database");

            // Check if they're valid
            using (var db = new LiteDatabase(Globals.dataBaseFile))
            {
                foreach (var p in fromFile.Where(p => !string.IsNullOrEmpty(p)).Distinct().ToList())
                {
                    try
                    {
                        CProxy proxy = new CProxy(p, type);
                        if (!proxy.IsNumeric || proxy.IsValidNumeric)
                        {
                            vm.ProxyList.Add(proxy);
                            db.GetCollection <CProxy>("proxies").Insert(proxy);
                        }
                    }
                    catch { }
                }

                foreach (var p in fromBox.Where(p => !string.IsNullOrEmpty(p)).Distinct().ToList())
                {
                    try
                    {
                        CProxy proxy = new CProxy();
                        proxy.Parse(p, type);
                        if (!proxy.IsNumeric || proxy.IsValidNumeric)
                        {
                            vm.ProxyList.Add(proxy);
                            db.GetCollection <CProxy>("proxies").Insert(proxy);
                        }
                    }
                    catch { }
                }
            }

            // Refresh
            vm.UpdateProperties();
        }
Пример #7
0
 /// <summary>
 /// Adds a proxy server for network requests. Can be called before authorization
 /// </summary>
 public static Task <Proxy> AddProxyAsync(
     this Client client, string server = default, int port = default, bool enable = default,
     ProxyType type = default)
 {
     return(client.ExecuteAsync(new AddProxy
     {
         Server = server, Port = port, Enable = enable, Type = type
     }));
 }
Пример #8
0
        public AntiCaptchaProxy(ProxyType type, string address, int port, string login = null, string password = null)
        {
            Type    = type;
            Address = address;
            Port    = port;

            Login    = login;
            Password = password;
        }
Пример #9
0
 public Proxy(string ipAddress, string port, ProxyType type, Location location, Anonymity anonymity, int speed)
 {
     this.Ip        = ipAddress;
     this.Port      = port;
     this.Type      = type;
     this.Location  = location;
     this.Anonymity = anonymity;
     this.Speed     = speed;
 }
Пример #10
0
        /// <summary>
        ///  Returns the count of accessible com proxies
        /// </summary>
        /// <param name="type">target proxy type</param>
        /// <returns>count of accessible proxies</returns>
        public static int GetAccessibleProxyCount(ProxyType type)
        {
            IEnumerable <AccessibleWindowTarget>      targets = ConvertToTargets(type);
            IDisposableEnumeration <ProxyInformation> result  = GetAccessibleProxiesFromPath(targets);
            int count = result.Count;

            result.Dispose();
            return(count);
        }
Пример #11
0
 /// <summary>
 /// Sends a simple network request to the Telegram servers via proxy; for testing only. Can be called before authorization
 /// </summary>
 public static Task <Ok> TestProxyAsync(
     this Client client, string server = default, int port = default, ProxyType type = default,
     int dcId = default, double?timeout = default)
 {
     return(client.ExecuteAsync(new TestProxy
     {
         Server = server, Port = port, Type = type, DcId = dcId, Timeout = timeout
     }));
 }
Пример #12
0
                private CachedType(Type type)
                {
                    Name      = type.Name;
                    Type      = type;
                    ProxyType = new ProxyType(type);
                    FullName  = type.FullName;

                    _Crawl();
                }
Пример #13
0
        protected override void Finish()
        {
            ProxyType.IsAbstract = false;

            // Ensure constructor is public
            ProxyType.GetConstructors().Single(x => !x.IsStatic).IsPublic = true;

            base.Finish();
        }
Пример #14
0
 public ConnectivitySettings(string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, ProxyType proxyType, WebProxy webProxy)
 {
     fProxyHost     = proxyHost;
     fProxyPort     = proxyPort;
     fProxyUsername = proxyUsername;
     fProxyPassword = proxyPassword;
     fProxyType     = proxyType;
     fWebProxy      = webProxy;
 }
Пример #15
0
 public ConnectivitySettings(ConnectivitySettings x)
 {
     fProxyType     = x.fProxyType;
     fProxyHost     = x.fProxyHost;
     fProxyPort     = x.fProxyPort;
     fProxyUsername = x.fProxyUsername;
     fProxyPassword = x.fProxyPassword;
     fWebProxy      = x.fWebProxy;
 }
Пример #16
0
 public CustomWebClient(Uri uri, string path, Encoding encoding, DateTime localVersion, string ua = null, ProxyType proxyType = ProxyType.NULL)
 {
     this.Uri          = uri;
     this.Path         = path;
     this.LocalVersion = localVersion;
     this.Encoding     = encoding;
     this.UserAgent    = ua;
     this.proxyType    = proxyType;
     this.proxyIndex   = (int)proxyType;
 }
Пример #17
0
 /// <summary>
 /// Creates a ValidData object after a valid check.
 /// </summary>
 /// <param name="data">The data line that was used in the check</param>
 /// <param name="proxy">The proxy that was used for the check (empty string if none)</param>
 /// <param name="proxyType">The proxy type</param>
 /// <param name="result">The result of the check</param>
 /// <param name="capturedData">The data captured during the check</param>
 /// <param name="source">The last page source code of the check</param>
 /// <param name="log">The detailed log of the check</param>
 public ValidData(string data, string proxy, ProxyType proxyType, BotStatus result, string capturedData, string source, List <LogEntry> log)
 {
     Data         = data;
     Proxy        = proxy;
     Result       = result;
     CapturedData = capturedData;
     UnixDate     = (int)Math.Round((DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds);
     Source       = source;
     Log          = log;
 }
Пример #18
0
 /// <summary>
 /// Решение капчи Google с прокси
 /// </summary>
 /// <param name="websiteURL">Адрес страницы на которой решается капча</param>
 /// <param name="websiteKey">Ключ-индентификатор рекапчи на целевой странице.</param>
 /// <param name="proxyType">Тип прокси</param>
 /// <param name="proxyAddress">IP адрес прокси ipv4/ipv6. Не допускается:</param>
 /// <param name="proxyPort">Порт прокси</param>
 /// <param name="userAgent">User-Agent браузера, используемый в эмуляции.</param>
 public NoCaptcha(string websiteURL, string websiteKey, ProxyType proxyType, string proxyAddress, int proxyPort, string userAgent)
 {
     this.Type         = Method.NoCaptchaTask;
     this.WebsiteUrl   = websiteURL;
     this.WebsiteKey   = websiteKey;
     this.ProxyAddress = proxyAddress;
     this.ProxyType    = proxyType;
     this.ProxyPort    = proxyPort;
     this.UserAgent    = userAgent;
 }
Пример #19
0
        private ulong GetChannelID(string proxy = "", ProxyType proxyType = ProxyType.HTTPS)
        {
            HttpRequest req = new HttpRequest();

            req.AddHeader("Authorization", token);
            ProxyManager.SimpleChange(req, proxy, proxyType);
            dynamic Resp = JsonConvert.DeserializeObject(req.Post($"https://discordapp.com/api/v6/users/@me/channels", "{" + $"\"recipient_id\": \"{userId}\"" + "}", "application/json").ToString());

            return(Resp.id);
        }
Пример #20
0
        public MultiplayerProxy(IPEndPoint proxyEndPoint, ProxyType proxyType = ProxyType.Socks5, string username = null, string password = null)
        {
            this.Address = proxyEndPoint.Address.ToString();
            this.Port    = proxyEndPoint.Port;

            this.Type = proxyType;

            this.Username = username;
            this.Password = password;
        }
Пример #21
0
        /// <summary>
        /// Указать прокси
        /// </summary>
        /// <param name="proxyType">Тип прокси</param>
        /// <param name="proxyAdress">Прокси адрес, в формате ip:port, ip:port:login:password</param>
        public static void SetProxy(ProxyType proxyType, string proxyAdress)
        {
            if (string.IsNullOrWhiteSpace(proxyAdress))
            {
                throw new System.NullReferenceException("Переменная с прокси null или пустая");
            }

            ProxyAdress   = proxyAdress;
            ProxyTypeLeaf = proxyType;
        }
Пример #22
0
 public HttpProxySettings(ProxyType type, string host, int port, string bypassFilter, bool bypassLocalAddress, string username = null, string password = null)
 {
     Type = type;
     Host = host.IsNullOrWhiteSpace() ? "127.0.0.1" : host;
     Port = port;
     Username = username ?? string.Empty;
     Password = password ?? string.Empty;
     BypassFilter = bypassFilter ?? string.Empty;
     BypassLocalAddress = bypassLocalAddress;
 }
Пример #23
0
 public BaseCrawler(FeedUriTypes uriType, string uri, string localPath, DateTime localVersion, string ua = null, ProxyType proxyType = ProxyType.NULL)
 {
     this.UriType       = uriType;
     this.URI           = uri;
     this.LocalPath     = localPath;
     this.LocalVersion  = localVersion;
     this.RemoteVersion = DateTime.MinValue;
     this.UserAgent     = ua;
     this.proxyType     = proxyType;
 }
Пример #24
0
 public HttpProxySettings(ProxyType type, string host, int port, string bypassFilter, bool bypassLocalAddress, string username = null, string password = null)
 {
     Type               = type;
     Host               = host.IsNullOrWhiteSpace() ? "127.0.0.1" : host;
     Port               = port;
     Username           = username ?? string.Empty;
     Password           = password ?? string.Empty;
     BypassFilter       = bypassFilter ?? string.Empty;
     BypassLocalAddress = bypassLocalAddress;
 }
Пример #25
0
 public void Initialize(ProxyType type, string strDestHost, int nDestPort, string strAuthUser, string strAuthPwd)
 {
     m_lProxyType  = type;
     m_szDestHost  = strDestHost;
     m_nDestPort   = nDestPort;
     m_szAuthUser  = strAuthUser;
     m_szAuthPwd   = strAuthPwd;
     m_lProxyState = 0;
     m_lBuffPos    = 0;
 }
Пример #26
0
        public ProxyClient(string Host, int?Port, string Username, string Password, ProxyType Type)
        {
            if (Type == ProxyType.Http)
            {
                InternalUri = new Uri($"http://{Host}:{Port}");
                return;
            }

            if (string.IsNullOrEmpty(Host))
            {
                throw new ArgumentNullException("Host null or empty");
            }

            if (Port == null && Host.Contains(":"))
            {
                Port = Convert.ToInt32(Host.Split(':')[1].Trim());
                Host = Host.Split(':')[0];

                if (Port < 0 || Port > 65535)
                {
                    throw new ArgumentOutOfRangeException("Port goes beyond");
                }
            }
            else if (Port == null && !Host.Contains(":"))
            {
                throw new ArgumentNullException("Incorrect host");
            }

            if (!string.IsNullOrEmpty(Username))
            {
                if (Username.Length > 255)
                {
                    throw new ArgumentNullException("Username null or long");
                }

                this.Username = Username;
            }

            if (!string.IsNullOrEmpty(Password))
            {
                if (Password.Length > 255)
                {
                    throw new ArgumentNullException("Password null or long");
                }

                this.Password = Password;
            }

            this.Host         = GetHost(Host);
            this.Port         = Port.Value;
            this.Type         = Type;
            this.SocksVersion = (Type == ProxyType.Socks4) ? 4 : 5;

            CreateInternalServer();
        }
Пример #27
0
        public ProxyAttrStruct GetProxy(ProxyType type)
        {
            switch (type)
            {
            case ProxyType.Gang: return(gangProxy);

            case ProxyType.System: return(systemProxy);

            default: return(systemProxy);
            }
        }
        /*
         * Constructs the wrapper for a known MethodBase instance
         */
        public LuaMethodWrapper(ObjectTranslator translator, object target, ProxyType targetType, MethodBase method)
        {
            InvokeFunction = Call;
            _translator    = translator;
            _target        = target;
            _extractTarget = translator.typeChecker.GetExtractor(targetType);

            _method     = method;
            _methodName = method.Name;
            _isStatic   = method.IsStatic;
        }
Пример #29
0
        /// <summary>
        /// Returns an accessible com proxy through the IAccessible interface
        /// </summary>
        /// <param name="type">target proxy type</param>
        /// <param name="throwExceptionIfNothingFound">throw an exception if no proxy found</param>
        /// <returns>com proxy instance or null</returns>
        public static object GetAccessibleProxy(ProxyType type, bool throwExceptionIfNothingFound)
        {
            IEnumerable <AccessibleWindowTarget>      targets = ConvertToTargets(type);
            IDisposableEnumeration <ProxyInformation> result  = GetAccessibleProxiesFromPath(targets, 1);

            if (result.Count == 0 && throwExceptionIfNothingFound)
            {
                throw new ArgumentOutOfRangeException("type", "Unable to find accessible proxy");
            }
            return(result);
        }
Пример #30
0
 public Proxy(ProxyType proxyType, string host, int port, ProxyCredentials proxyCreds)
 {
     ProxyType     = proxyType;
     Host          = host;
     Port          = port;
     ProxyCreds    = proxyCreds;
     ProxyState    = ProxyState.Online;
     NetworkType   = NetworkType.Datacenter;
     AddressFamily = AddressFamily.InterNetwork;
     IsStaticIP    = true;
 }
Пример #31
0
        /// <summary>
        ///     获取请求代理对象
        /// </summary>
        /// <param name="proxyType"></param>
        /// <returns></returns>
        public static ProxyBase GetProxyBaseObject(ProxyType proxyType)
        {
            Type loadType = GetType(proxyType);

            if (loadType == null)
            {
                throw new ProxyServiceException(string.Format("proxyType {0},{1} is not exist", proxyType.FullName,
                                                              proxyType.AssemblyName));
            }
            return(Activator.CreateInstance(loadType) as ProxyBase);
        }
Пример #32
0
 public static void SimpleChange(HttpRequest req, string proxy, ProxyType proxyType)
 {
     if (IsUsingProxy())
     {
         Change(req, proxy);
     }
     else
     {
         Change(req, proxy, proxyType);
     }
 }
Пример #33
0
        private void DisplayClassProperties()
        {
            try
            {
                OMETrace.WriteFunctionStart();

                if (Helper.ClassName != null)
                {
                    if (OMEInteraction.GetCurrentConnParams() != null)
                    {
                        if (OMEInteraction.GetCurrentConnParams() != null)
                        {
                            buttonSaveIndex.Enabled = !OMEInteraction.GetCurrentConnParams().ConnectionReadOnly&&
                                                      !AssemblyInspectorObject.Connection.CheckForClientServer();

                            labelNoOfObjects.Text = "Number of objects : " +
                                                    AssemblyInspectorObject.ClassProperties.GetObjectCountForAClass(Helper.ClassName);
                            dbGridViewProperties.Size = Size;
                            dbGridViewProperties.Rows.Clear();
                            dbGridViewProperties.Columns.Clear();

                            ArrayList fieldPropertiesList = GetFieldsForAllClass();
                            dbGridViewProperties.ReadOnly = false;
                            dbGridViewProperties.PopulateDisplayGrid(Constants.VIEW_CLASSPOPERTY, fieldPropertiesList);

                            //Enable Disable IsIndexed Checkboxes
                            foreach (DataGridViewRow row in dbGridViewProperties.Rows)
                            {
                                ProxyType type = row.Cells["Type"].Value as ProxyType;
                                if (type.IsEditable && (type.IsPrimitive || type.IsNullable))
                                {
                                    row.Cells[2].ReadOnly = false;
                                }
                                else
                                {
                                    row.Cells[2].ReadOnly = true;
                                }
                            }

                            if (!panelForClassPropTable.Controls.Contains(dbGridViewProperties))
                            {
                                panelForClassPropTable.Controls.Add(dbGridViewProperties);
                            }
                            dbGridViewProperties.Dock = DockStyle.Fill;
                        }
                    }
                }
                OMETrace.WriteFunctionEnd();
            }
            catch (Exception oEx)
            {
                LoggingHelper.ShowMessage(oEx);
            }
        }
Пример #34
0
 public GeeTest(string websiteURL, string gt, string challenge, ProxyType proxyType, string proxyAddress, int proxyPort, string userAgent)
 {
     this.Type         = Method.GeeTestTask;
     this.WebsiteUrl   = websiteURL;
     this.Gt           = gt;
     this.Challenge    = challenge;
     this.ProxyType    = proxyType;
     this.ProxyAddress = proxyAddress;
     this.ProxyPort    = proxyPort;
     this.UserAgent    = userAgent;
 }
Пример #35
0
        private static Component GetComponent(GameObject gameObject, ProxyType componentType)
        {
            Component result = AutotestingInternal.unityBinding.ExecuteOnMainThreadAndWaitForCompletion(() => gameObject.GetComponent(componentType.UnderlyingSystemType));

            if (result == null)
            {
                throw new ScriptException("GetComponent", $"Component \"{componentType.UnderlyingSystemType.Name}\" not found on GameObject \"{gameObject.name}\"");
            }

            return(result);
        }
Пример #36
0
   private static void SecurityExample() {
      ProxyType highSecurityObject = new ProxyType();
      highSecurityObject.AttemptAccess("High");   // Works OK

      PermissionSet grantSet = new PermissionSet(PermissionState.None);
      grantSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
      AppDomain lowSecurityAppDomain = AppDomain.CreateDomain("LowSecurity", null, new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }, grantSet, null);
      ProxyType lowSecurityObject = (ProxyType)lowSecurityAppDomain.CreateInstanceAndUnwrap(typeof(ProxyType).Assembly.ToString(), typeof(ProxyType).FullName);
      lowSecurityObject.DoSomething(highSecurityObject);
      Console.ReadLine();
   }
Пример #37
0
		/*
		 * Constructs the wrapper for a known MethodBase instance
		 */
		public LuaMethodWrapper (ObjectTranslator translator, object target, ProxyType targetType, MethodBase method)
		{
			invokeFunction = new LuaNativeFunction (this.Call);
			_Translator = translator;
			_Target = target;

			if (targetType != null)
				_ExtractTarget = translator.typeChecker.GetExtractor (targetType);

			_Method = method;
			_MethodName = method.Name;
			_IsStatic = method.IsStatic;
		}
Пример #38
0
 public Proxy(ProxyType type, string url)
 {
     switch (type)
     {
         case ProxyType.AjaxWithJson:
             {
                 this.type = "ajax";
                 this.url = url;
                 this.reader = new Reader();
                 this.reader.root = "items";
                 this.reader.type = "json";
             } break;
     }
 }
Пример #39
0
        public static bool ValidateDataType(string classname, ProxyType fieldname, object data)
        {
            if (null == data && "null" == data.ToString())
                return false;

            try
            {
                return AssemblyInspectorObject.DataType.ValidateDataType(classname, fieldname.DisplayName, data);
            }
            catch (Exception oEx)
            {
                LoggingHelper.ShowMessage(oEx);
            }

            return false;
        }
Пример #40
0
        public bool AcceptProxy(ProxyType type, UInt64 targetID)
        {
            if( NeedProxies(type) )
                return true;

            // else go through proxies, determine if targetid is closer than proxies already hosted
            lock(SocketList)
                foreach(TcpConnect connection in SocketList)
                    if(connection.Proxy == type)
                        // if closer than at least 1 contact
                        if ((targetID ^ Network.Local.UserID) < (connection.UserID ^ Network.Local.UserID) || targetID == connection.UserID)
                        {
                            return true;
                        }

            return false;
        }
        /// <summary>
        /// Factory method for creating new proxy client objects.
        /// </summary>
        /// <param name="type">The type of proxy client to create.</param>
        /// <returns>Proxy client object.</returns>
        public IProxyClient CreateProxyClient(ProxyType type)
        {
            if (type == ProxyType.None)
                throw new ArgumentOutOfRangeException("type");

            switch (type)
            {
                case ProxyType.Http:
                    return new HttpProxyClient();
                case ProxyType.Socks4:
                    return new Socks4ProxyClient();
                case ProxyType.Socks4a:
                    return new Socks4aProxyClient();
                case ProxyType.Socks5:
                    return new Socks5ProxyClient();
                default:
                    throw new ProxyException(String.Format("Unknown proxy type {0}.", type.ToString()));
            }
        }        
Пример #42
0
        public ProxyServer(int port, ProxyType proxyType)
        {
            this.proxyType = proxyType;

            tcpListener = new TcpListener(IPAddress.Loopback, port);
            tcpListener.Server.DontFragment = true;
            tcpListener.Server.NoDelay = true;
            tcpListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

            try
            {
                tcpListener.Start();
                tcpListener.BeginAcceptTcpClient(new AsyncCallback(OnAcceptTcpClient), null);
            }
            catch (Exception)
            {
                tcpListener = null;
                throw;
            }
        }
        public ProxyProcessor(string serverHost, int serverPort, int listeningPort, ProxyType pType, int[] packetFilter)
        {
            PacketProcessing.CrashOnException = false;
            ServerHost = serverHost;
            ServerPort = serverPort;
            if (packetFilter != null)
            {
                filteredPackets = new List<int>(packetFilter);
            }
            else
            {
                filteredPackets = new List<int>();
            }
            proxyType = pType;
            clientProcessor = new PacketProcessing();
            clientProcessor.SetPort(listeningPort);

            Subscribe(clientProcessor);
            
            clientProcessor.StartClientListener();
        }
Пример #44
0
 private ProxyConfiguration(ProxyAttribute attribute)
 {
     if (attribute == null)
     {
         this.DisableAutoProxy = Convert.ToBoolean(ConfigurationManager.AppSettings["Clover.Proxy.DisableAutoProxy"]);
         this.EnableDebug = Convert.ToBoolean(ConfigurationManager.AppSettings["Clover.Proxy.EnableDebug"]);
         this.DllCachedPath = Convert.ToString(ConfigurationManager.AppSettings["Clover.Proxy.DllCachedPath"]);
         this.ProxyType = (ProxyType)Enum.Parse(typeof(ProxyType), Convert.ToString(ConfigurationManager.AppSettings["Clover.Proxy.ProxyType"]));
     }
     else
     {
         this.DisableAutoProxy = attribute.DisableAutoProxy;
         this.EnableDebug = attribute.EnableDebug;
         this.DllCachedPath = attribute.DllCachedPath;
         this.BeforeCall = attribute.BeforeCall;
         this.AfterCall = attribute.AfterCall;
         this.ProxyType = attribute.ProxyType;
     }
     if (string.IsNullOrWhiteSpace((this.DllCachedPath)))
     {
         this.DllCachedPath = AppDomain.CurrentDomain.BaseDirectory;
     }
 }
Пример #45
0
 public Proxy(ProxyType type, string proxyHost, int proxyPort)
 {
     this.ProxyType = type;
     this.ProxyHost = proxyHost;
     this.ProxyPort = proxyPort;
 }
Пример #46
0
		private static int SetImageIndex(ProxyType   type)
		{
			int imageIndex = 0;

			try
			{
                if (type.IsEditable &&(type.IsPrimitive || type.IsNullable))	

				{
					imageIndex = 2;
				}
                else if (type.IsArray || type.IsCollection || (type.IsEditable && !type.IsPrimitive))
				{
					imageIndex = 3;
				}
			}
			catch (Exception oEx)
			{
				LoggingHelper.ShowMessage(oEx);
			}

			return imageIndex;
		}
		/*
		 * Constructs the wrapper for a known method name
		 */
		public LuaMethodWrapper (ObjectTranslator translator, ProxyType targetType, string methodName, BindingFlags bindingType)
		{
			invokeFunction = new LuaNativeFunction (this.Call);

			_Translator = translator;
			_MethodName = methodName;

			if (targetType != null)
				_ExtractTarget = translator.typeChecker.GetExtractor (targetType);

			_BindingType = bindingType;
			_Members = targetType.UnderlyingSystemType.GetMember (methodName, MemberTypes.Method, bindingType | BindingFlags.Public);
		}
Пример #48
0
        /**
         * 通信クラスの初期化処理です。タイムアウト値とプロキシを設定します。
         */
        public static void InitializeConnection(int timeout, ProxyType proxy_type, string proxy_address, int proxy_port, string proxy_user, string proxy_password)
        {
            __is_initialized = true;
            ServicePointManager.Expect100Continue = false;
            DefaultTimeout = timeout * 1000;
            // 秒を㍉秒に変換しておきます。
            switch ( proxy_type ) {
            case ProxyType.None:
                __web_proxy = null;
                break;

            case ProxyType.Specified:
                __web_proxy = new WebProxy( string.Format( "http://{0}:{1}", proxy_address, proxy_port ) );
                if ( string.IsNullOrEmpty( proxy_user ) || !string.IsNullOrEmpty( proxy_password ) )
                    __web_proxy.Credentials = new NetworkCredential( proxy_user, proxy_password );
                break;

            case ProxyType.IE:
                // IE(システム設定)はデフォルト値なので、処理しません。
                break;
            }
            __proxy_kind = proxy_type;
            WIN32API.SetProxy( proxy_type, proxy_address, proxy_port, proxy_user, proxy_password );
        }
Пример #49
0
 public ProxyAttribute()
 {
     this.EnableDebug = true;
     this.DllCachedPath = null;
     this.BeforeCall = null;
     this.AfterCall = null;
     this.DisableAutoProxy = false;
     this.ProxyType = Proxy.ProxyType.Default;
 }
Пример #50
0
        private static int GetTokenForMethodDecode(ProxyType PT, int iIndex, AntiProxyParams Params, out FunctionCallType CT)
        {
            FieldInfo fieldFromHandle = PT.arFieldReflection[iIndex];
            Assembly executingAssembly = Params.asmReflection;

            char[] array = new char[fieldFromHandle.Name.Length];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = (char)((int)((byte)fieldFromHandle.Name[i]) ^ i);
            }
            byte[] array2 = Convert.FromBase64String(new string(array));
            CT = (array2[0] == 13) ? FunctionCallType.Callvirt : FunctionCallType.Call;

            return BitConverter.ToInt32(array2, 1) ^ Params.XORTokenMethod;
        }
Пример #51
0
      // This method executes in the low-security AppDomain
      public void DoSomething(ProxyType highSecurityObject) {
         AttemptAccess("High->Low"); // Throws

         // Attempt access from the high-security AppDomain via the low-security AppDomain: Throws
         highSecurityObject.AttemptAccess("High->Low->High");

         // Have the high-security AppDomain via the low-security AppDomain queue a work item to 
         // the thread pool normally (without suppressing the execution context): Throws
         highSecurityObject.AttemptAccessViaThreadPool(false, "TP (with EC)->High");

         // Wait a bit for the work item to complete writing to the console before starting the next work item
         Thread.Sleep(1000);

         // Have the high-security AppDomain via the low-security AppDomain queue a work item to 
         // the thread pool suppressing the execution context: Works OK
         highSecurityObject.AttemptAccessViaThreadPool(true, "TP (no EC)->High");
      }
Пример #52
0
        ///<summary>
        ///通信クラスの初期化処理。タイムアウト値とプロキシを設定する
        ///</summary>
        ///<remarks>
        ///通信開始前に最低一度呼び出すこと
        ///</remarks>
        ///<param name="timeout">タイムアウト値(秒)</param>
        ///<param name="proxyType">なし・指定・IEデフォルト</param>
        ///<param name="proxyAddress">プロキシのホスト名orIPアドレス</param>
        ///<param name="proxyPort">プロキシのポート番号</param>
        ///<param name="proxyUser">プロキシ認証が必要な場合のユーザ名。不要なら空文字</param>
        ///<param name="proxyPassword">プロキシ認証が必要な場合のパスワード。不要なら空文字</param>
        public static void InitializeConnection(
                int timeout,
                ProxyType proxyType,
                string proxyAddress,
                int proxyPort,
                string proxyUser,
                string proxyPassword)
        {
            isInitialize = true;
            ServicePointManager.Expect100Continue = false;
            DefaultTimeout = timeout * 1000;     //s -> ms
            switch (proxyType)
            {
                case ProxyType.None:
                    proxy = null;
                    break;
                case ProxyType.Specified:
                    proxy = new WebProxy("http://" + proxyAddress + ":" + proxyPort);
                    if (!String.IsNullOrEmpty(proxyUser) || !String.IsNullOrEmpty(proxyPassword))
                        proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword);
                    break;
                case ProxyType.IE:
                    //IE設定(システム設定)はデフォルト値なので処理しない
                    break;
            }
            proxyKind = proxyType;

            // Windows 8.1 Previewの場合SecurityProtocolを明確に指定する必要がある  
            // Preview 版使用期限の 2014 年 1 月を過ぎたら消すよ
            var osVersion = Environment.OSVersion.Version;  
            if (osVersion.Major == 6 && osVersion.Minor == 3)  
            {  
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3;  
            }  

            Win32Api.SetProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
        }
Пример #53
0
		private static bool IsSetToNullOperationValidFor(ProxyType  targetFieldType, object containingObject)
		{
		    return targetFieldType != null &&
		           ((targetFieldType.HasIdentity || targetFieldType.IsNullable) && (containingObject != null));
		}
Пример #54
0
 public Proxy(ProxyType type, string proxyServer, int proxyPort, string userName, string password)
     : this(type, proxyServer, proxyPort)
 {
     this.UserName = userName;
     this.Password = password;
 }
Пример #55
0
		/*
		 * Constructs the wrapper for a known method name
		 */
		public LuaMethodWrapper (ObjectTranslator translator, ProxyType targetType, string methodName, BindingFlags bindingType)
		{
			invokeFunction = new LuaNativeFunction (this.Call);

			_Translator = translator;
			_MethodName = methodName;

			if (targetType != null)
				_ExtractTarget = translator.typeChecker.GetExtractor (targetType);

			_IsStatic = (bindingType & BindingFlags.Static) == BindingFlags.Static;
			_Members  = GetMethodsRecursively (targetType.UnderlyingSystemType, methodName, bindingType | BindingFlags.Public);
		}
Пример #56
0
 private Starksoft.Net.Proxy.ProxyType convertType(ProxyType type)
 {
     return (Starksoft.Net.Proxy.ProxyType)Enum.Parse(typeof(Starksoft.Net.Proxy.ProxyType), Enum.GetName(typeof(ProxyType), type));
 }
Пример #57
0
 /// <summary>
 /// Starts a new Proxy server by reading the data from the configuration file and start listening on the specified ports.
 /// </summary>
 public void Start(string ip, int port, ProxyType type)
 {
     // Initialize some objects
     StartTime = DateTime.Now;
     // Start the proxy
     Listener listener = null;
     switch (type)
     {
         case ProxyType.Http:
             listener = CreateListener("Org.Mentalis.Proxy.Http.HttpListener", string.Format("host:{0};int:{1}", ip, port));
             break;
         case ProxyType.Socks:
             listener = CreateListener("Org.Mentalis.Proxy.Socks.SocksListener", string.Format("host:{0};int:{1};authlist", ip, port));
             break;
     }
     if (listener != null)
     {
         listener.Start();
         AddListener(listener);
     }
     else
     {
         throw new Exception("无法在指定端口监听!");
     }
 }
Пример #58
0
        private void socket_Receive(IAsyncResult ar)
        {
            try
            {
                int received = Handle.EndReceive(ar);

                if (received <= 0)
                {
                    Disconnect();
                    return;
                }
                if (received > 5000 || _handshakeStream.Length + received > 5000)
                {
                    //attack prevention of overflowing the HandshakeStream
                    //It's really impossible for Socks or HTTPS proxies to use even 5000 for Initial Packets
                    Disconnect();
                    return;
                }

                LengthReceived += received;
                _handshakeStream.Write(_buffer, 0, received);
            }
            catch
            {
                Disconnect();
                return;
            }

            byte[] payload = _handshakeStream.ToArray();

            switch (PacketsReceived)
            {
                case 0:
                {
                    //initial Socks packet
                    if (payload.Length >= 3)
                    {
                        string headerStr = Encoding.ASCII.GetString(payload);

                        //check the proxy client
                        if (payload[0] == SOCKS5_VERSION_NUMBER)
                        {
                            Type = ProxyType.Socks5;
                        }
                        else if (headerStr.StartsWith("CONNECT") && headerStr.Contains(":"))
                        {
                            Type = ProxyType.HTTPS;

                            //Grab here the IP / PORT
                            using (StreamReader sr = new StreamReader(new MemoryStream(payload)))
                            {
                                string line = sr.ReadLine();
                                if (line == null)
                                    break;

                                //could have done it better with RegEx... oh well
                                string[] split = line.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries);
                                if (split.Length > 0)
                                {
                                    try
                                    {
                                        string ipPort = split[1];
                                        this.TargetServer = ipPort.Split(':')[0];
                                        this.TargetPort = ushort.Parse(ipPort.Split(':')[1]);

                                        this._isConnectCommand = true;
                                        this._isDomainNameType = true;

                                        //Send Command to client and wait for response from CommandHandler
                                        new ReverseProxyConnect(ConnectionId, this.TargetServer, this.TargetPort).Execute(Client);
                                        Server.CallonConnectionEstablished(this);

                                        return; //Quit receiving and wait for client's response
                                    }
                                    catch
                                    {
                                        Disconnect();
                                    }
                                }
                            }
                        }
                        else
                        {
                            break;
                        }

                        if (CheckProxyVersion(payload))
                        {
                            SendSuccessToClient();
                            PacketsReceived++;
                            _handshakeStream.SetLength(0);
                            Server.CallonConnectionEstablished(this);
                        }
                    }
                    break;
                }
                case 1:
                {
                    //Socks command
                    int MinPacketLen = 6;
                    if (payload.Length >= MinPacketLen)
                    {
                        if (!CheckProxyVersion(payload))
                            return;

                        this._isConnectCommand = payload[1] == 1;
                        this._isBindCommand = payload[1] == 2;
                        this._isUdpCommand = payload[1] == 3;

                        this._isIpType = payload[3] == 1;
                        this._isDomainNameType = payload[3] == 3;
                        this._isIPv6NameType = payload[3] == 4;

                        Array.Reverse(payload, payload.Length - 2, 2);
                        this.TargetPort = BitConverter.ToUInt16(payload, payload.Length - 2);

                        if (_isConnectCommand)
                        {
                            if (_isIpType)
                            {
                                this.TargetServer = payload[4] + "." + payload[5] + "." + payload[6] + "." + payload[7];
                            }
                            else if (_isDomainNameType)
                            {
                                int domainLen = payload[4];
                                if (MinPacketLen + domainLen < payload.Length)
                                {
                                    this.TargetServer = Encoding.ASCII.GetString(payload, 5, domainLen);
                                }
                            }

                            if (this.TargetServer.Length > 0)
                            {
                                //Send Command to client and wait for response from CommandHandler
                                new ReverseProxyConnect(ConnectionId, this.TargetServer, this.TargetPort).Execute(Client);
                            }
                        }
                        else
                        {
                            SendFailToClient();
                            return;
                        }

                        Server.CallonUpdateConnection(this);

                        //Quit receiving data and wait for Client's response
                        return;
                    }
                    break;
                }
            }

            try
            {
                Handle.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, socket_Receive, null);
            }
            catch
            {
                Disconnect();
            }
        }
Пример #59
0
        private static bool DoAntiProxy(ProxyType PT, AntiProxyParams Params)
        {
            FunctionCallType CT = FunctionCallType.Call;

            for (int iIndex = 0; iIndex < PT.arMethods.Length; iIndex++)
            {
                if (PT.arProxyTypeDelegate[iIndex] == ProxyTypeDelegate.NewObjectCall)
                {
                    Int32 TokenOfOriginalCall = GetTokenForFieldDecode(PT, iIndex, Params);

                    MethodReference MR = AsmDef.MainModule.Import(Params.asmReflection.GetModules()[0].ResolveMethod(TokenOfOriginalCall));
                    Instruction[] arIns = GetInstructionsWithMethodCall(PT.arMethods[iIndex]).ToArray();

                    for (int i = 0; i < arIns.Length; i++)
                    {
                        arIns[i].OpCode = OpCodes.Newobj;
                        arIns[i].Operand = MR;
                    }
                }

                if (PT.arProxyTypeDelegate[iIndex] == ProxyTypeDelegate.DirectMethodCall)
                {
                    Int32 TokenOfOriginalCall = GetTokenForMethodDecode(PT, iIndex, Params, out CT);

                    ProxyType PT2 = null;
                    MethodReference MR = AsmDef.MainModule.Import(Params.asmReflection.GetModules()[0].ResolveMethod(TokenOfOriginalCall));

                    ProxyType[] NestedPT = Params.lstProxyTypes.Where(m => m.Type.Name == MR.DeclaringType.Name).ToArray();

                    if (NestedPT.Length != 0)
                        PT2 = NestedPT[0];

                    /*foreach (var PTNew in AP17.lstProxyTypes)
                    {
                        if (MR.DeclaringType.Name == PTNew.Type.Name)
                        {
                            PT2 = new ProxyType(PTNew.Type, AP17);
                        }
                    }*/

                    // PT2 = Second stage proxy -> proxy followed by a proxy by a method/newobj
                    if (PT2 != null)
                    {
                        Instruction[] arIns = GetInstructionsWithMethodCall(PT.arMethods[iIndex]);

                        if (PT2.arProxyTypeDelegate[0] == ProxyTypeDelegate.NewObjectCall)
                        {
                            Int32 TokenOfOriginalCall2 = GetTokenForFieldDecode(PT2, 0, Params);

                            MethodReference MR2 = AsmDef.MainModule.Import(Params.asmReflection.GetModules()[0].ResolveMethod(TokenOfOriginalCall2));

                            for (int i = 0; i < arIns.Length; i++)
                            {
                                arIns[i].OpCode = OpCodes.Newobj;
                                arIns[i].Operand = MR2;
                            }
                        }
                    }
                    else
                    {
                        Instruction[] arIns = GetInstructionsWithMethodCall(PT.arMethods[iIndex]);
                        for (int i = 0; i < arIns.Length; i++)
                        {
                            if (CT == FunctionCallType.Call)
                            {
                                arIns[i].OpCode = OpCodes.Call;
                                arIns[i].Operand = MR;
                            }
                            if (CT == FunctionCallType.Callvirt)
                            {
                                arIns[i].OpCode = OpCodes.Callvirt;
                                arIns[i].Operand = MR;
                            }
                        }
                    }
                }
            }
            return true;
        }
Пример #60
0
        private static int GetTokenForFieldDecode(ProxyType PT, int iIndex, AntiProxyParams Params)
        {
            FieldInfo fieldFromHandle = PT.arFieldReflection[iIndex];

            Assembly executingAssembly = Params.asmReflection;

            char[] array = new char[fieldFromHandle.Name.Length];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = (char)((int)((byte)fieldFromHandle.Name[i]) ^ i);
            }
            return BitConverter.ToInt32(Convert.FromBase64String(new string(array)), 0) ^ Params.XORTokenField;
        }