Exemplo n.º 1
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            if (!data.GlobalSettings.Captchas.BypassBalanceCheck)
            {
                base.Process(data);
            }

            data.Log(new LogEntry("WARNING! This block is obsolete and WILL BE REMOVED IN THE FUTURE! Use the SOLVECAPTCHA block!", Colors.Tomato));
            data.Log(new LogEntry("Solving reCaptcha...", Colors.White));

            string recapResponse = "";

            try
            {
                recapResponse = Captchas.GetService(data.GlobalSettings.Captchas)
                                .SolveRecaptchaV2Async(ReplaceValues(siteKey, data), ReplaceValues(url, data)).Result.Response;
            }
            catch
            {
                data.Log(recapResponse == string.Empty ? new LogEntry("Couldn't get a reCaptcha response from the service", Colors.Tomato) : new LogEntry("Succesfully got the response: " + recapResponse, Colors.GreenYellow));
            }

            if (VariableName != string.Empty)
            {
                data.Log(new LogEntry("Response stored in variable: " + variableName, Colors.White));
                data.Variables.Set(new CVar(variableName, recapResponse));
            }
        }
Exemplo n.º 2
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            if (data.Driver == null)
            {
                data.Log(new LogEntry("Open a browser first!", Colors.White));
                throw new Exception("Browser not open");
            }

            data.Log(new LogEntry("Navigating to " + ReplaceValues(url, data), Colors.White));
            data.Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(timeout);
            try
            {
                data.Driver.Navigate().GoToUrl(ReplaceValues(url, data));
                //data.Driver.Url = ReplaceValues(url, data);
                data.Log(new LogEntry("Navigated!", Colors.White));
            }
            catch (OpenQA.Selenium.WebDriverTimeoutException)
            {
                data.Log(new LogEntry("Timeout on Page Load", Colors.Tomato));
                if (BanOnTimeout)
                {
                    data.Status = BotStatus.BAN;
                }
            }

            data.Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(data.GlobalSettings.Selenium.PageLoadTimeout);
            UpdateSeleniumData(data);
        }
Exemplo n.º 3
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            string errorMessage;
            var    service = Captchas.GetService(data.GlobalSettings.Captchas);

            try
            {
                try
                {
                    var replacedId = ReplaceValues(CaptchaId, data);
                    service.ReportSolution(long.Parse(replacedId), Type).Wait();
                    data.Log(new LogEntry($"Captcha reported successfully!", Colors.GreenYellow));
                    return;
                }
                catch (Exception ex) // This unwraps aggregate exceptions
                {
                    if (ex is AggregateException)
                    {
                        throw ex.InnerException;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            catch (TaskReportException ex) { errorMessage = $"The captcha report was not accepted! {ex.Message}"; }
            catch (NotSupportedException ex) { errorMessage =
                                                   $"The currently selected service ({data.GlobalSettings.Captchas.CurrentService}) does not support reports! {ex.Message}"; }
            catch (Exception ex) { errorMessage = $"An error occurred! {ex.Message}"; }

            data.Log(new LogEntry(errorMessage, Colors.Tomato));
        }
Exemplo n.º 4
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            // If bypass balance check, skip this method.
            if (data.GlobalSettings.Captchas.BypassBalanceCheck)
            {
                return;
            }

            // Get balance. If balance is under a certain threshold, don't ask for captcha solve
            Balance = 0; // Reset it or the block will save it for future calls
            data.Log(new LogEntry("Checking balance...", Colors.White));
            switch (data.GlobalSettings.Captchas.CurrentService)
            {
            case CaptchaService.ImageTypers:
                Balance = new ImageTyperz(data.GlobalSettings.Captchas.ImageTypToken, 0).GetBalance();
                break;

            case CaptchaService.AntiCaptcha:
                Balance = new AntiCaptcha(data.GlobalSettings.Captchas.AntiCapToken, 0).GetBalance();
                break;

            case CaptchaService.DBC:
                Balance = new DeathByCaptcha(data.GlobalSettings.Captchas.DBCUser, data.GlobalSettings.Captchas.DBCPass, 0).GetBalance();
                break;

            case CaptchaService.TwoCaptcha:
                Balance = new TwoCaptcha(data.GlobalSettings.Captchas.TwoCapToken, 0).GetBalance();
                break;

            case CaptchaService.DeCaptcher:
                Balance = new DeCaptcher(data.GlobalSettings.Captchas.DCUser, data.GlobalSettings.Captchas.DCPass, 0).GetBalance();
                break;

            case CaptchaService.AZCaptcha:
                Balance = new AZCaptcha(data.GlobalSettings.Captchas.AZCapToken, 0).GetBalance();
                break;

            case CaptchaService.SolveRecaptcha:
                Balance = new SolveReCaptcha(data.GlobalSettings.Captchas.SRUserId, data.GlobalSettings.Captchas.SRToken, 0).GetBalance();
                break;

            case CaptchaService.CaptchasIO:
                Balance = new CaptchasIO(data.GlobalSettings.Captchas.CIOToken, 0).GetBalance();
                break;

            default:
                Balance = 999;
                break;
            }

            if (Balance <= 0)
            {
                throw new System.Exception($"[{data.GlobalSettings.Captchas.CurrentService}] Bad token/credentials or zero balance!");
            }

            data.Log(new LogEntry($"[{data.GlobalSettings.Captchas.CurrentService}] Current Balance: ${Balance}", Colors.GreenYellow));
            data.Balance = Balance;
        }
Exemplo n.º 5
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            if (data.Driver == null)
            {
                data.Log(new LogEntry("Open a browser first!", Colors.White));
                throw new Exception("Browser not open");
            }

            data.Log(new LogEntry("Executing JS code!", Colors.White));
            var returned = data.Driver.ExecuteScript(ReplaceValues(javascriptCode, data));

            if (returned != null)
            {
                try
                {
                    InsertVariable(data, isCapture, false, new List <string>()
                    {
                        returned.ToString()
                    }, outputVariable, "", "", false, true);
                }
                catch
                {
                    throw new Exception($"Failed to convert the returned value to a string");
                }
            }

            data.Log(new LogEntry("... executed!", Colors.White));

            UpdateSeleniumData(data);
        }
Exemplo n.º 6
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            if (!data.GlobalSettings.Captchas.BypassBalanceCheck)
            {
                base.Process(data);
            }

            data.Log(new LogEntry("Solving reCaptcha...", Colors.White));

            string recapResponse = "";

            CaptchaServices.CaptchaService service = null;

            switch (data.GlobalSettings.Captchas.CurrentService)
            {
            case CaptchaService.ImageTypers:
                service = new ImageTyperz(data.GlobalSettings.Captchas.ImageTypToken, data.GlobalSettings.Captchas.Timeout);
                break;

            case CaptchaService.AntiCaptcha:
                service = new AntiCaptcha(data.GlobalSettings.Captchas.AntiCapToken, data.GlobalSettings.Captchas.Timeout);
                break;

            case CaptchaService.DBC:
                service = new DeathByCaptcha(data.GlobalSettings.Captchas.DBCUser, data.GlobalSettings.Captchas.DBCPass, data.GlobalSettings.Captchas.Timeout);
                break;

            case CaptchaService.TwoCaptcha:
                service = new TwoCaptcha(data.GlobalSettings.Captchas.TwoCapToken, data.GlobalSettings.Captchas.Timeout);
                break;

            case CaptchaService.DeCaptcher:
                service = new DeCaptcher(data.GlobalSettings.Captchas.DCUser, data.GlobalSettings.Captchas.DCPass, data.GlobalSettings.Captchas.Timeout);
                break;

            case CaptchaService.AZCaptcha:
                service = new AZCaptcha(data.GlobalSettings.Captchas.AZCapToken, data.GlobalSettings.Captchas.Timeout);
                break;

            case CaptchaService.SolveRecaptcha:
                service = new SolveReCaptcha(data.GlobalSettings.Captchas.SRUserId, data.GlobalSettings.Captchas.SRToken, data.GlobalSettings.Captchas.Timeout);
                break;

            case CaptchaService.CaptchasIO:
                service = new CaptchasIO(data.GlobalSettings.Captchas.CIOToken, data.GlobalSettings.Captchas.Timeout);
                break;

            default:
                throw new Exception("This service cannot solve reCaptchas!");
            }
            recapResponse = service.SolveRecaptcha(siteKey, ReplaceValues(url, data));

            data.Log(recapResponse == "" ? new LogEntry("Couldn't get a reCaptcha response from the service", Colors.Tomato) : new LogEntry("Succesfully got the response: " + recapResponse, Colors.GreenYellow));
            if (VariableName != "")
            {
                data.Log(new LogEntry("Response stored in variable: " + variableName, Colors.White));
                data.Variables.Set(new CVar(variableName, recapResponse));
            }
        }
Exemplo n.º 7
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            if (!data.GlobalSettings.Captchas.BypassBalanceCheck)
            {
                base.Process(data);
            }

            var localUrl = ReplaceValues(url, data);

            data.Log(new LogEntry("Downloading image...", Colors.White));

            // Download captcha
            var captchaFile = string.Format("Captchas/captcha{0}.jpg", data.BotNumber);

            if (base64)
            {
                var bytes = Convert.FromBase64String(localUrl);
                using (var imageFile = new FileStream(captchaFile, FileMode.Create))
                {
                    imageFile.Write(bytes, 0, bytes.Length);
                    imageFile.Flush();
                }
            }
            else if (sendScreenshot && data.Screenshots.Count > 0)
            {
                Bitmap image = new Bitmap(data.Screenshots.Last());
                image.Save(captchaFile);
            }
            else
            {
                try
                {
                    Download.RemoteFile(captchaFile, localUrl,
                                        data.UseProxies, data.Proxy, data.Cookies, out Dictionary <string, string> newCookies,
                                        data.GlobalSettings.General.RequestTimeout * 1000, ReplaceValues(UserAgent, data));
                    data.Cookies = newCookies;
                }
                catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); throw; }
            }

            string response = "";

            var bitmap = new Bitmap(captchaFile);

            try
            {
                response = Service.Initialize(data.GlobalSettings.Captchas).SolveCaptcha(bitmap);
            }
            catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); throw; }
            finally { bitmap.Dispose(); }

            data.Log(response == "" ? new LogEntry("Couldn't get a response from the service", Colors.Tomato) : new LogEntry("Succesfully got the response: " + response, Colors.GreenYellow));

            if (VariableName != "")
            {
                data.Log(new LogEntry("Response stored in variable: " + variableName, Colors.White));
                data.Variables.Set(new CVar(variableName, response));
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Adds a single or list variable with the given value.
        /// </summary>
        /// <param name="data">The BotData used for variable replacement and insertion</param>
        /// <param name="isCapture">Whether the variable should be marked for Capture</param>
        /// <param name="recursive">Whether the variable to add should be a list or a single value</param>
        /// <param name="values">The list of values. In case recursive is set to false, only the first value of the list will be taken.</param>
        /// <param name="variableName">The name of the variable to create</param>
        /// <param name="prefix">The string to add at the start of the value</param>
        /// <param name="suffix">The string to add at the end of the value</param>
        /// <param name="urlEncode">Whether to URLencode the values before creating the variables</param>
        /// <param name="createEmpty">Whether to create an empty (single) variable if the list of values is empty</param>
        internal static void InsertVariable(BotData data, bool isCapture, bool recursive, IEnumerable <string> values, string variableName,
                                            string prefix = "", string suffix = "", bool urlEncode = false, bool createEmpty = true)
        {
            var list = values.Select(v => ReplaceValues(prefix, data) + v.Trim() + ReplaceValues(suffix, data)).ToList();

            if (urlEncode)
            {
                list = list.Select(v => Uri.EscapeDataString(v)).ToList();
            }

            CVar variable = null;

            if (recursive)
            {
                if (list.Count == 0)
                {
                    if (createEmpty)
                    {
                        variable = new CVar(variableName, list, isCapture);
                    }
                }
                else
                {
                    variable = new CVar(variableName, list, isCapture);
                }
            }
            else
            {
                if (list.Count == 0)
                {
                    if (createEmpty)
                    {
                        variable = new CVar(variableName, "", isCapture);
                    }
                }
                else
                {
                    variable = new CVar(variableName, list.First(), isCapture);
                }
            }

            // If we don't want to save empty captures, and it's a capture, and the list is either an empty string or a list made of an empty string
            if (!data.ConfigSettings.SaveEmptyCaptures && isCapture &&
                (list.Count == 0 || list.Count > 0 && string.IsNullOrWhiteSpace(list.First())))
            {
                variable = null;
            }

            if (variable != null)
            {
                data.Variables.Set(variable);
                data.Log(new LogEntry("Parsed variable" + " | Name: " + variable.Name + " | Value: " + variable.ToString() + Environment.NewLine, isCapture ? Colors.OrangeRed : Colors.Gold));
            }
            else
            {
                data.Log(new LogEntry("Could not parse any data. The variable was not created.", Colors.White));
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Adds a single or list variable with the given value.
        /// </summary>
        /// <param name="data">The BotData used for variable replacement and insertion</param>
        /// <param name="isCapture">Whether the variable should be marked for Capture</param>
        /// <param name="recursive">Whether the variable to add should be a list or a single value</param>
        /// <param name="values">The list of values. In case recursive is set to false, only the first value of the list will be taken.</param>
        /// <param name="variableName">The name of the variable to create</param>
        /// <param name="prefix">The string to add at the start of the value</param>
        /// <param name="suffix">The string to add at the end of the value</param>
        /// <param name="urlEncode">Whether to URLencode the values before creating the variables</param>
        /// <param name="createEmpty">Whether to create an empty (single) variable if the list of values is empty</param>
        public static void InsertVariables(BotData data, bool isCapture, bool recursive, List <string> values, string variableName, string prefix, string suffix, bool urlEncode, bool createEmpty)
        {
            var list = values.Select(v => ReplaceValues(prefix, data) + v.Trim() + ReplaceValues(suffix, data)).ToList();

            if (urlEncode)
            {
                list = list.Select(v => System.Uri.EscapeDataString(v)).ToList();
            }

            CVar variable = null;

            if (recursive)
            {
                if (list.Count == 0)
                {
                    if (createEmpty)
                    {
                        variable = new CVar(variableName, list, isCapture);
                    }
                }
                else
                {
                    variable = new CVar(variableName, list, isCapture);
                }
            }
            else
            {
                if (list.Count == 0)
                {
                    if (createEmpty)
                    {
                        variable = new CVar(variableName, "", isCapture);
                    }
                }
                else
                {
                    variable = new CVar(variableName, list.First(), isCapture);
                }
            }

            if (variable != null)
            {
                data.Variables.Set(variable);
                data.Log(new LogEntry("Parsed variable" + " | Name: " + variable.Name + " | Value: " + variable.ToString() + Environment.NewLine, isCapture ? Colors.OrangeRed : Colors.Gold));
            }
            else
            {
                data.Log(new LogEntry("Could not parse any data. The variable was not created.", Colors.White));
            }
        }
Exemplo n.º 10
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            if (data.Driver == null)
            {
                data.Log(new LogEntry("Open a browser first!", Colors.White));
                throw new Exception("Browser not open");
            }

            data.Log(new LogEntry("Executing JS code!", Colors.White));
            data.Driver.ExecuteScript(ReplaceValues(javascriptCode, data));
            data.Log(new LogEntry("... executed!", Colors.White));

            UpdateSeleniumData(data);
        }
Exemplo n.º 11
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            if (!data.GlobalSettings.Captchas.BypassBalanceCheck)
            {
                base.Process(data);
            }

            data.Log(new LogEntry("Solving reCaptcha...", Colors.White));

            string recapResponse = Service.Initialize(data.GlobalSettings.Captchas).SolveRecaptcha(siteKey, ReplaceValues(url, data));

            data.Log(recapResponse == string.Empty ? new LogEntry("Couldn't get a reCaptcha response from the service", Colors.Tomato) : new LogEntry("Succesfully got the response: " + recapResponse, Colors.GreenYellow));
            if (VariableName != string.Empty)
            {
                data.Log(new LogEntry("Response stored in variable: " + variableName, Colors.White));
                data.Variables.Set(new CVar(variableName, recapResponse));
            }
        }
Exemplo n.º 12
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            // If bypass balance check, skip this method.
            if (data.GlobalSettings.Captchas.BypassBalanceCheck)
            {
                return;
            }

            // Get balance. If balance is under a certain threshold, don't ask for captcha solve
            Balance = 0; // Reset it or the block will save it for future calls
            data.Log(new LogEntry("Checking balance...", Colors.White));

            Balance = Captchas.GetService(data.GlobalSettings.Captchas).GetBalanceAsync().Result;

            if (Balance <= 0)
            {
                throw new System.Exception($"[{data.GlobalSettings.Captchas.CurrentService}] Bad token/credentials or zero balance!");
            }

            data.Log(new LogEntry($"[{data.GlobalSettings.Captchas.CurrentService}] Current Balance: ${Balance}", Colors.GreenYellow));
            data.Balance = Balance;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Adds a single or list variable with the given value.
        /// </summary>
        /// <param name="data">The BotData used for variable replacement and insertion</param>
        /// <param name="isCapture">Whether the variable should be marked for Capture</param>
        /// <param name="recursive">Whether the variable to add should be a list or a single value</param>
        /// <param name="values">The list of values. In case recursive is set to false, only the first value of the list will be taken.</param>
        /// <param name="variableName">The name of the variable to create</param>
        /// <param name="prefix">The string to add at the start of the value</param>
        /// <param name="suffix">The string to add at the end of the value</param>
        public static void InsertVariables(BotData data, bool isCapture, bool recursive, List <string> values, string variableName, string prefix, string suffix)
        {
            var  list = values.Select(v => ReplaceValues(prefix, data) + v.Trim() + ReplaceValues(suffix, data));
            CVar variable;

            if (recursive)
            {
                variable = new CVar(variableName, list.ToList(), isCapture);
            }
            else
            {
                variable = new CVar(variableName, list.First(), isCapture);
            }
            data.Variables.Set(variable);
            data.Log(new LogEntry("Parsed variable" + " | Name: " + variable.Name + " | Value: " + variable.ToString() + Environment.NewLine, isCapture ? Colors.OrangeRed : Colors.Gold));
        }
Exemplo n.º 14
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            try
            {
                var replacedInput = ReplaceValues(inputString, data);
                switch (group)
                {
                case UtilityGroup.List:
                    var  list     = data.Variables.GetList(listName);
                    var  list2    = data.Variables.GetList(secondListName);
                    var  item     = ReplaceValues(listItem, data);
                    var  index    = int.Parse(ReplaceValues(listIndex, data));
                    CVar variable = null;

                    switch (listAction)
                    {
                    case ListAction.Create:
                        data.Variables.Set(new CVar(variableName, new List <string>(), isCapture));
                        break;

                    case ListAction.Length:
                        data.Variables.Set(new CVar(variableName, list.Count().ToString(), isCapture));
                        break;

                    case ListAction.Join:
                        data.Variables.Set(new CVar(variableName, string.Join(separator, list), isCapture));
                        break;

                    case ListAction.Sort:
                        var sorted = list.Select(e => e).ToList();         // Clone the list so we don't edit the original one
                        if (Numeric)
                        {
                            var nums = sorted.Select(e => double.Parse(e, CultureInfo.InvariantCulture)).ToList();
                            nums.Sort();
                            sorted = nums.Select(e => e.ToString()).ToList();
                        }
                        else
                        {
                            sorted.Sort();
                        }
                        if (!Ascending)
                        {
                            sorted.Reverse();
                        }
                        data.Variables.Set(new CVar(variableName, sorted, isCapture));
                        break;

                    case ListAction.Concat:
                        data.Variables.Set(new CVar(variableName, list.Concat(list2).ToList(), isCapture));
                        break;

                    case ListAction.Zip:
                        data.Variables.Set(new CVar(variableName, list.Zip(list2, (a, b) => a + b).ToList(), isCapture));
                        break;

                    case ListAction.Map:
                        data.Variables.Set(new CVar(variableName, list.Zip(list2, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v), isCapture));
                        break;

                    case ListAction.Add:
                        // TODO: Refactor this
                        variable = data.Variables.Get(listName, CVar.VarType.List);
                        if (variable == null)
                        {
                            variable = data.GlobalVariables.Get(listName, CVar.VarType.List);
                        }
                        if (variable == null)
                        {
                            break;
                        }
                        if (variable.Value.Count == 0)
                        {
                            index = 0;
                        }
                        else if (index < 0)
                        {
                            index += variable.Value.Count;
                        }
                        variable.Value.Insert(index, item);
                        break;

                    case ListAction.Remove:
                        // TODO: Refactor this
                        variable = data.Variables.Get(listName, CVar.VarType.List);
                        if (variable == null)
                        {
                            variable = data.GlobalVariables.Get(listName, CVar.VarType.List);
                        }
                        if (variable == null)
                        {
                            break;
                        }
                        if (variable.Value.Count == 0)
                        {
                            index = 0;
                        }
                        else if (index < 0)
                        {
                            index += variable.Value.Count;
                        }
                        variable.Value.RemoveAt(index);
                        break;

                    case ListAction.RemoveValues:
                        data.Variables.Set(new CVar(variableName, list.Where(l => !Condition.Verify(new KeycheckCondition
                        {
                            Left     = ReplaceValues(l, data),
                            Comparer = ListElementComparer,
                            Right    = ListComparisonTerm
                        })).ToList(), isCapture));
                        break;

                    case ListAction.RemoveDuplicates:
                        data.Variables.Set(new CVar(variableName, list.Distinct().ToList(), isCapture));
                        break;

                    case ListAction.Random:
                        data.Variables.Set(new CVar(variableName, list[data.random.Next(list.Count)], isCapture));
                        break;

                    case ListAction.Shuffle:
                        // This makes a copy of the original list
                        var listCopy = list.ToArray().ToList();
                        listCopy.Shuffle(data.random);
                        data.Variables.Set(new CVar(variableName, listCopy, isCapture));
                        break;

                    default:
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {listAction} on file {listName}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Variable:
                    string single;
                    switch (varAction)
                    {
                    case VarAction.Split:
                        single = data.Variables.GetSingle(varName);
                        data.Variables.Set(new CVar(variableName, single.Split(new string[] { ReplaceValues(splitSeparator, data) }, StringSplitOptions.None).ToList(), isCapture));
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {varAction} on variable {varName}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Conversion:
                    byte[] conversionInputBytes = replacedInput.ConvertFrom(conversionFrom);
                    var    conversionResult     = conversionInputBytes.ConvertTo(conversionTo);
                    data.Variables.Set(new CVar(variableName, conversionResult, isCapture));
                    data.Log(new LogEntry($"Executed conversion {conversionFrom} to {conversionTo} on input {replacedInput} with outcome {conversionResult}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.File:
                    var file = ReplaceValues(filePath, data);
                    Files.ThrowIfNotInCWD(file);

                    switch (fileAction)
                    {
                    case FileAction.Exists:
                        data.Variables.Set(new CVar(variableName, File.Exists(file).ToString(), isCapture));
                        break;

                    case FileAction.Read:
                        lock (FileLocker.GetLock(file))
                            data.Variables.Set(new CVar(variableName, File.ReadAllText(file), isCapture));
                        break;

                    case FileAction.ReadLines:
                        lock (FileLocker.GetLock(file))
                            data.Variables.Set(new CVar(variableName, File.ReadAllLines(file).ToList(), isCapture));
                        break;

                    case FileAction.Write:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.WriteAllText(file, replacedInput.Unescape());
                        break;

                    case FileAction.WriteLines:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.WriteAllLines(file, ReplaceValuesRecursive(inputString, data).Select(i => i.Unescape()));
                        break;

                    case FileAction.Append:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.AppendAllText(file, replacedInput.Unescape());
                        break;

                    case FileAction.AppendLines:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.AppendAllLines(file, ReplaceValuesRecursive(inputString, data).Select(i => i.Unescape()));
                        break;

                    case FileAction.Copy:
                        var fileCopyLocation = ReplaceValues(inputString, data);
                        Files.ThrowIfNotInCWD(fileCopyLocation);
                        Files.CreatePath(fileCopyLocation);
                        lock (FileLocker.GetLock(file))
                            lock (FileLocker.GetLock(fileCopyLocation))
                                File.Copy(file, fileCopyLocation);
                        break;

                    case FileAction.Move:
                        var fileMoveLocation = ReplaceValues(inputString, data);
                        Files.ThrowIfNotInCWD(fileMoveLocation);
                        Files.CreatePath(fileMoveLocation);
                        lock (FileLocker.GetLock(file))
                            lock (FileLocker.GetLock(fileMoveLocation))
                                File.Move(file, fileMoveLocation);
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {fileAction} on file {file}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Folder:
                    var folder = ReplaceValues(folderPath, data);
                    Files.ThrowIfNotInCWD(folder);

                    switch (folderAction)
                    {
                    case FolderAction.Exists:
                        data.Variables.Set(new CVar(variableName, Directory.Exists(folder).ToString(), isCapture));
                        break;

                    case FolderAction.Create:
                        data.Variables.Set(new CVar(variableName, Directory.CreateDirectory(folder).ToString(), isCapture));
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {folderAction} on folder {folder}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); }
        }
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            if (!data.GlobalSettings.Captchas.BypassBalanceCheck)
            {
                base.Process(data);
            }

            var localUrl = ReplaceValues(url, data);

            data.Log(new LogEntry("Downloading image...", Colors.White));

            // Download captcha
            var captchaFile = string.Format("Captchas/captcha{0}.jpg", data.BotNumber);

            if (base64)
            {
                var bytes = Convert.FromBase64String(localUrl);
                using (var imageFile = new FileStream(captchaFile, FileMode.Create))
                {
                    imageFile.Write(bytes, 0, bytes.Length);
                    imageFile.Flush();
                }
            }
            else if (sendScreenshot && data.Screenshots.Count > 0)
            {
                Bitmap image = new Bitmap(data.Screenshots.Last());
                image.Save(captchaFile);
            }
            else
            {
                try
                {
                    DownloadRemoteImageFile(captchaFile, data, localUrl);
                }
                catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); throw; }
            }

            string response = "";

            CaptchaServices.CaptchaService service = null;
            var bitmap = new Bitmap(captchaFile);

            try
            {
                switch (data.GlobalSettings.Captchas.CurrentService)
                {
                case CaptchaService.ImageTypers:
                    service = new ImageTyperz(data.GlobalSettings.Captchas.ImageTypToken, data.GlobalSettings.Captchas.Timeout);
                    break;

                case CaptchaService.AntiCaptcha:
                    service = new AntiCaptcha(data.GlobalSettings.Captchas.AntiCapToken, data.GlobalSettings.Captchas.Timeout);
                    break;

                case CaptchaService.DBC:
                    service = new DeathByCaptcha(data.GlobalSettings.Captchas.DBCUser, data.GlobalSettings.Captchas.DBCPass, data.GlobalSettings.Captchas.Timeout);
                    break;

                case CaptchaService.TwoCaptcha:
                    service = new TwoCaptcha(data.GlobalSettings.Captchas.TwoCapToken, data.GlobalSettings.Captchas.Timeout);
                    break;

                case CaptchaService.RuCaptcha:
                    service = new RuCaptcha(data.GlobalSettings.Captchas.RuCapToken, data.GlobalSettings.Captchas.Timeout);
                    break;

                case CaptchaService.DeCaptcher:
                    service = new DeCaptcher(data.GlobalSettings.Captchas.DCUser, data.GlobalSettings.Captchas.DCPass, data.GlobalSettings.Captchas.Timeout);
                    break;

                case CaptchaService.AZCaptcha:
                    service = new AZCaptcha(data.GlobalSettings.Captchas.AZCapToken, data.GlobalSettings.Captchas.Timeout);
                    break;

                case CaptchaService.CaptchasIO:
                    service = new CaptchasIO(data.GlobalSettings.Captchas.CIOToken, data.GlobalSettings.Captchas.Timeout);
                    break;

                default:
                    throw new Exception("This service cannot solve normal captchas!");
                }
                response = service.SolveCaptcha(bitmap);
            }
            catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); throw; }
            finally { bitmap.Dispose(); }

            data.CaptchaService = service;
            data.Log(response == "" ? new LogEntry("Couldn't get a response from the service", Colors.Tomato) : new LogEntry("Succesfully got the response: " + response, Colors.GreenYellow));

            if (VariableName != "")
            {
                data.Log(new LogEntry("Response stored in variable: " + variableName, Colors.White));
                data.Variables.Set(new CVar(variableName, response));
            }
        }
Exemplo n.º 16
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            // If the clearance info is already set and we're not getting it fresh each time, skip
            if (data.UseProxies)
            {
                if (data.Proxy.Clearance != "" && data.Proxy.Cfduid != "" && !data.GlobalSettings.Proxies.AlwaysGetClearance)
                {
                    data.Log(new LogEntry("Skipping CF Bypass because there is already a valid cookie", Colors.White));
                    return;
                }
            }

            var localUrl = ReplaceValues(url, data);
            var uri      = new Uri(localUrl);

            var timeout = data.GlobalSettings.General.RequestTimeout * 1000;

            var request = new HttpRequest();

            request.IgnoreProtocolErrors = true;
            request.ConnectTimeout       = timeout;
            request.ReadWriteTimeout     = timeout;
            request.Cookies = new CookieStorage();
            foreach (var cookie in data.Cookies)
            {
                request.Cookies.Add(new Cookie(cookie.Key, cookie.Value, "/", uri.Host));
            }

            if (data.UseProxies)
            {
                switch (data.Proxy.Type)
                {
                case Extreme.Net.ProxyType.Http:
                    request.Proxy = HttpProxyClient.Parse(data.Proxy.Proxy);
                    break;

                case Extreme.Net.ProxyType.Socks4:
                    request.Proxy = Socks4ProxyClient.Parse(data.Proxy.Proxy);
                    break;

                case Extreme.Net.ProxyType.Socks4a:
                    request.Proxy = Socks4AProxyClient.Parse(data.Proxy.Proxy);
                    break;

                case Extreme.Net.ProxyType.Socks5:
                    request.Proxy = Socks5ProxyClient.Parse(data.Proxy.Proxy);
                    break;

                case Extreme.Net.ProxyType.Chain:
                    throw new Exception("The Chain Proxy Type is not supported in Leaf.xNet (used for CF Bypass).");
                }

                request.Proxy.ReadWriteTimeout = timeout;
                request.Proxy.ConnectTimeout   = timeout;
                request.Proxy.Username         = data.Proxy.Username;
                request.Proxy.Password         = data.Proxy.Password;
            }

            request.UserAgent = ReplaceValues(userAgent, data);

            var twoCapToken = data.GlobalSettings.Captchas.TwoCapToken;

            if (twoCapToken != "")
            {
                request.CaptchaSolver = new TwoCaptchaSolver()
                {
                    ApiKey = data.GlobalSettings.Captchas.TwoCapToken
                }
            }
            ;

            var response       = request.GetThroughCloudflare(new Uri(localUrl));
            var responseString = response.ToString();

            // Save the cookies
            var ck = response.Cookies.GetCookies(localUrl);

            var clearance = "";
            var cfduid    = "";

            try
            {
                clearance = ck["cf_clearance"].Value;
                cfduid    = ck["__cfduid"].Value;
            }
            catch { }

            if (data.UseProxies)
            {
                data.Proxy.Clearance = clearance;
                data.Proxy.Cfduid    = cfduid;
            }

            if (clearance != "")
            {
                data.Log(new LogEntry("Got Cloudflare clearance!", Colors.GreenYellow));
                data.Log(new LogEntry(clearance + Environment.NewLine + cfduid + Environment.NewLine, Colors.White));
            }

            // Get code
            data.ResponseCode = ((int)response.StatusCode).ToString();
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry($"Response code: {data.ResponseCode}", Colors.Cyan));
            }

            // Get headers
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Received headers:", Colors.DeepPink));
            }
            var receivedHeaders = response.EnumerateHeaders();

            data.ResponseHeaders.Clear();
            while (receivedHeaders.MoveNext())
            {
                var header = receivedHeaders.Current;
                data.ResponseHeaders.Add(header.Key, header.Value);
                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"{header.Key}: {header.Value}", Colors.LightPink));
                }
            }
            if (!response.ContainsHeader(HttpHeader.ContentLength))
            {
                if (data.ResponseHeaders.ContainsKey("Content-Encoding") && data.ResponseHeaders["Content-Encoding"].Contains("gzip"))
                {
                    data.ResponseHeaders["Content-Length"] = GZip.Zip(responseString).Length.ToString();
                }
                else
                {
                    data.ResponseHeaders["Content-Length"] = responseString.Length.ToString();
                }

                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"Content-Length: {data.ResponseHeaders["Content-Length"]}", Colors.LightPink));
                }
            }

            // Get cookies
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Received cookies:", Colors.Goldenrod));
            }
            foreach (Cookie cookie in response.Cookies.GetCookies(localUrl))
            {
                if (data.Cookies.ContainsKey(cookie.Name))
                {
                    data.Cookies[cookie.Name] = cookie.Value;
                }
                else
                {
                    data.Cookies.Add(cookie.Name, cookie.Value);
                }
                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"{cookie.Name}: {cookie.Value}", Colors.LightGoldenrodYellow));
                }
            }

            data.ResponseSource = responseString;
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Response Source:", Colors.Green));
                data.Log(new LogEntry(data.ResponseSource, Colors.GreenYellow));
            }
        }
    }
Exemplo n.º 17
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            // Get easy handles
            var tcp = data.TCPClient;
            var net = data.NETStream;
            var ssl = data.SSLStream;

            byte[] buffer   = new byte[2048];
            int    bytes    = -1;
            string response = "";

            switch (TCPCommand)
            {
            case TCPCommand.Connect:
                // Replace the Host and Port
                var h = ReplaceValues(host, data);
                var p = int.Parse(ReplaceValues(port, data));

                // Initialize the TCP client, connect to the host and get the SSL stream
                tcp = new TcpClient();
                tcp.Connect(h, p);
                if (tcp.Connected)
                {
                    net = tcp.GetStream();
                    if (UseSSL)
                    {
                        ssl = new SslStream(net);
                        ssl.AuthenticateAsClient(h);
                    }

                    //Wait a bit and read the Stream if not Empty
                    System.Threading.Thread.Sleep(200);
                    if (net.DataAvailable)
                    {
                        if (UseSSL)
                        {
                            bytes = ssl.Read(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            bytes = net.Read(buffer, 0, buffer.Length);
                        }

                        // Save the response as ASCII in the SOURCE variable
                        response = Encoding.ASCII.GetString(buffer, 0, bytes);
                    }

                    // Save the TCP client and the streams
                    data.TCPClient = tcp;
                    data.NETStream = net;
                    data.SSLStream = ssl;
                    data.TCPSSL    = UseSSL;

                    data.Log(new LogEntry($"Succesfully connected to host {h} on port {p}. The server says:", Colors.Green));
                    data.Log(new LogEntry(response, Colors.GreenYellow));
                }

                if (VariableName != "")
                {
                    data.Variables.Set(new CVar(VariableName, response, IsCapture));
                    data.Log(new LogEntry($"Saved Response in variable {VariableName}", Colors.White));
                }
                break;

            case TCPCommand.Disconnect:
                if (tcp == null)
                {
                    throw new Exception("Make a connection first!");
                }

                tcp.Close();
                tcp = null;
                if (net != null)
                {
                    net.Close();
                }
                if (ssl != null)
                {
                    ssl.Close();
                }
                data.Log(new LogEntry($"Succesfully closed the stream", Colors.GreenYellow));
                break;

            case TCPCommand.Send:
                if (tcp == null)
                {
                    throw new Exception("Make a connection first!");
                }

                var msg = ReplaceValues(Message, data);
                var b   = Encoding.ASCII.GetBytes(msg.Replace(@"\r\n", "\r\n"));
                data.Log(new LogEntry("> " + msg, Colors.White));

                if (data.TCPSSL)
                {
                    ssl.Write(b);
                    bytes = ssl.Read(buffer, 0, buffer.Length);
                }
                else
                {
                    net.Write(b, 0, b.Length);
                    bytes = net.Read(buffer, 0, buffer.Length);
                }

                // Save the response as ASCII in the SOURCE variable and log it
                response = Encoding.ASCII.GetString(buffer, 0, bytes);
                data.Log(new LogEntry("> " + response, Colors.GreenYellow));

                if (VariableName != "")
                {
                    data.Variables.Set(new CVar(VariableName, response, IsCapture));
                    data.Log(new LogEntry($"Saved Response in variable {VariableName}.", Colors.White));
                }
                break;
            }
        }
Exemplo n.º 18
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            #region Request
            // Set base URL
            var localUrl = ReplaceValues(url, data);
            var cType    = ReplaceValues(contentType, data);
            var oldJar   = data.Cookies;

            // Create request
            HttpRequest request = new HttpRequest();

            // Setup options
            var timeout = data.GlobalSettings.General.RequestTimeout * 1000;
            request.IgnoreProtocolErrors         = true;
            request.AllowAutoRedirect            = autoRedirect;
            request.EnableEncodingContent        = acceptEncoding;
            request.ReadWriteTimeout             = timeout;
            request.ConnectTimeout               = timeout;
            request.KeepAlive                    = true;
            request.MaximumAutomaticRedirections = data.ConfigSettings.MaxRedirects;

            // Check if it has GET parameters
            if (ParseQuery && localUrl.Contains('?') && localUrl.Contains('='))
            {
                // Remove the query from the base URL
                localUrl = ReplaceValues(url.Split('?')[0], data);
                data.Log(new LogEntry($"Calling Base URL: {localUrl}", Colors.MediumTurquoise));

                // Parse the GET parameters
                var getParams = ReplaceValues(url.Split('?')[1], data);
                var paramList = getParams.Split('&');

                // Build the query, first replace variables in them and encode the parameters
                foreach (var par in paramList)
                {
                    var split = par.Split('=');

                    // Encode them if needed
                    if (split[0].Contains('%'))
                    {
                        split[0] = Uri.EscapeDataString(split[0]);
                    }
                    if (split[1].Contains('%'))
                    {
                        split[1] = Uri.EscapeDataString(split[1]);
                    }

                    // Add them to the query
                    request.AddUrlParam(split[0], split[1]);

                    data.Log(new LogEntry($"Added Query Parameter: {split[0]} = {split[1]}", Colors.MediumTurquoise));
                }
            }
            else
            {
                data.Log(new LogEntry($"Calling URL: {localUrl}", Colors.MediumTurquoise));
            }

            // Set up the Content and Content-Type
            HttpContent content = null;
            switch (requestType)
            {
            case RequestType.Standard:
                var pData = ReplaceValues(Regex.Replace(postData, @"(?<!\\)\\n", Environment.NewLine).Replace(@"\\n", @"\n"), data);

                if (CanContainBody(method))
                {
                    if (encodeContent)
                    {
                        // Very dirty but it works
                        var nonce = data.Random.Next(1000000, 9999999);
                        pData = pData.Replace("&", $"{nonce}&{nonce}").Replace("=", $"{nonce}={nonce}");
                        pData = string.Join("", BlockFunction.SplitInChunks(pData, 2080)
                                            .Select(s => Uri.EscapeDataString(s)))
                                .Replace($"{nonce}%26{nonce}", "&").Replace($"{nonce}%3D{nonce}", "=");
                    }

                    content             = new StringContent(pData);
                    content.ContentType = cType;
                    data.Log(new LogEntry($"Post Data: {pData}", Colors.MediumTurquoise));
                }
                break;

            case RequestType.Multipart:
                var bdry = multipartBoundary != "" ? ReplaceValues(multipartBoundary, data) : GenerateMultipartBoundary();
                content = new Extreme.Net.MultipartContent(bdry);
                var mContent = content as Extreme.Net.MultipartContent;
                data.Log(new LogEntry($"Content-Type: multipart/form-data; boundary={bdry}", Colors.MediumTurquoise));
                data.Log(new LogEntry("Multipart Data:", Colors.MediumTurquoise));
                data.Log(new LogEntry(bdry, Colors.MediumTurquoise));
                foreach (var c in MultipartContents)
                {
                    var rValue       = ReplaceValues(c.Value, data);
                    var rName        = ReplaceValues(c.Name, data);
                    var rContentType = ReplaceValues(c.ContentType, data);

                    if (c.Type == MultipartContentType.String)
                    {
                        mContent.Add(new StringContent(rValue), rName);
                        data.Log(new LogEntry($"Content-Disposition: form-data; name=\"{rName}\"{Environment.NewLine}{Environment.NewLine}{rValue}", Colors.MediumTurquoise));
                    }
                    else if (c.Type == MultipartContentType.File)
                    {
                        mContent.Add(new FileContent(rValue), rName, rValue, rContentType);
                        data.Log(new LogEntry($"Content-Disposition: form-data; name=\"{rName}\"; filename=\"{rValue}\"{Environment.NewLine}Content-Type: {rContentType}{Environment.NewLine}{Environment.NewLine}[FILE CONTENT OMITTED]", Colors.MediumTurquoise));
                    }
                    data.Log(new LogEntry(bdry, Colors.MediumTurquoise));
                }
                break;

            default:
                break;
            }

            // Set proxy
            if (data.UseProxies)
            {
                request.Proxy = data.Proxy.GetClient();

                try
                {
                    request.Proxy.ReadWriteTimeout = timeout;
                    request.Proxy.ConnectTimeout   = timeout;
                    request.Proxy.Username         = data.Proxy.Username;
                    request.Proxy.Password         = data.Proxy.Password;
                }
                catch { }
            }

            // Set headers
            data.Log(new LogEntry("Sent Headers:", Colors.DarkTurquoise));
            // var fixedNames = Enum.GetNames(typeof(HttpHeader)).Select(n => n.ToLower());
            foreach (var header in CustomHeaders)
            {
                try
                {
                    var key         = ReplaceValues(header.Key, data);
                    var replacedKey = key.Replace("-", "").ToLower(); // Used to compare with the HttpHeader enum
                    var val         = ReplaceValues(header.Value, data);

                    if (replacedKey == "contenttype" && content != null)
                    {
                        continue;
                    }                                                                  // Disregard additional Content-Type headers
                    if (replacedKey == "acceptencoding" && acceptEncoding)
                    {
                        continue;
                    }                                                                    // Disregard additional Accept-Encoding headers
                    // else if (fixedNames.Contains(replacedKey)) request.AddHeader((HttpHeader)Enum.Parse(typeof(HttpHeader), replacedKey, true), val);
                    else
                    {
                        request.AddHeader(key, val);
                    }

                    data.Log(new LogEntry(key + ": " + val, Colors.MediumTurquoise));
                }
                catch { }
            }

            // Add the authorization header on a Basic Auth request
            if (requestType == RequestType.BasicAuth)
            {
                var usr  = ReplaceValues(authUser, data);
                var pwd  = ReplaceValues(authPass, data);
                var auth = "Basic " + BlockFunction.Base64Encode(usr + ":" + pwd);
                request.AddHeader("Authorization", auth);
                data.Log(new LogEntry($"Authorization: {auth}", Colors.MediumTurquoise));
            }

            // Add the content-type header
            if (CanContainBody(method) && content != null && requestType == RequestType.Standard)
            {
                data.Log(new LogEntry($"Content-Type: {cType}", Colors.MediumTurquoise));
            }

            // Add new user-defined custom cookies to the bot's cookie jar
            request.Cookies = new CookieDictionary();
            foreach (var cookie in CustomCookies)
            {
                data.Cookies[ReplaceValues(cookie.Key, data)] = ReplaceValues(cookie.Value, data);
            }

            // Set cookies from the bot's cookie jar to the request's CookieDictionary
            data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise));
            foreach (var cookie in data.Cookies)
            {
                request.Cookies.Add(cookie.Key, cookie.Value);
                data.Log(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.MediumTurquoise));
            }

            data.LogNewLine();
            #endregion

            #region Response
            // Create the response
            HttpResponse response = null;

            try
            {
                // Get response
                response = request.Raw(method, localUrl, content);
                var responseString = "";

                // Get address
                data.Address = response.Address.ToString();
                data.Log(new LogEntry("Address: " + data.Address, Colors.Cyan));

                // Get code
                data.ResponseCode = ((int)response.StatusCode).ToString();
                data.Log(new LogEntry($"Response code: {data.ResponseCode} ({response.StatusCode})", Colors.Cyan));

                // Get headers
                data.Log(new LogEntry("Received headers:", Colors.DeepPink));
                var headerList      = new List <KeyValuePair <string, string> >();
                var receivedHeaders = response.EnumerateHeaders();
                data.ResponseHeaders.Clear();
                while (receivedHeaders.MoveNext())
                {
                    var header = receivedHeaders.Current;
                    data.ResponseHeaders.Add(header.Key, header.Value);
                    data.Log(new LogEntry($"{header.Key}: {header.Value}", Colors.LightPink));
                }
                if (!response.ContainsHeader(HttpHeader.ContentLength) && ResponseType != ResponseType.File)
                {
                    responseString = response.ToString(); // Read the stream

                    if (data.ResponseHeaders.ContainsKey("Content-Encoding") && data.ResponseHeaders["Content-Encoding"].Contains("gzip"))
                    {
                        data.ResponseHeaders["Content-Length"] = GZip.Zip(responseString).Length.ToString();
                    }
                    else
                    {
                        data.ResponseHeaders["Content-Length"] = responseString.Length.ToString();
                    }

                    data.Log(new LogEntry($"Content-Length: {data.ResponseHeaders["Content-Length"]}", Colors.LightPink));
                }

                // Get cookies
                data.Log(new LogEntry("Received cookies:", Colors.Goldenrod));
                data.Cookies = response.Cookies;
                foreach (var cookie in response.Cookies)
                {
                    // If the cookie was already present before, don't log it
                    if (oldJar.ContainsKey(cookie.Key) && oldJar[cookie.Key] == cookie.Value)
                    {
                        continue;
                    }

                    data.Log(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.LightGoldenrodYellow));
                }

                // Save the response content
                switch (responseType)
                {
                case ResponseType.String:
                    data.Log(new LogEntry("Response Source:", Colors.Green));
                    if (readResponseSource)
                    {
                        if (responseString == "")
                        {
                            responseString = response.ToString();                           // Read the stream if you didn't already read it
                        }
                        data.ResponseSource = responseString;
                        data.Log(new LogEntry(data.ResponseSource, Colors.GreenYellow));
                    }
                    else
                    {
                        data.ResponseSource = "";
                        data.Log(new LogEntry("[SKIPPED]", Colors.GreenYellow));
                    }
                    break;

                case ResponseType.File:
                    if (SaveAsScreenshot)
                    {
                        SaveScreenshot(response.ToMemoryStream(), data);     // Read the stream
                        data.Log(new LogEntry("File saved as screenshot", Colors.Green));
                    }
                    else
                    {
                        var filePath = ReplaceValues(downloadPath, data);
                        var dirName  = Path.GetDirectoryName(filePath);
                        if (dirName != "")
                        {
                            dirName += Path.DirectorySeparatorChar.ToString();
                        }
                        var fileName      = Path.GetFileNameWithoutExtension(filePath);
                        var fileExtension = Path.GetExtension(filePath);
                        var sanitizedPath = $"{dirName}{MakeValidFileName(fileName)}{fileExtension}";
                        using (var stream = File.Create(sanitizedPath)) { response.ToMemoryStream().CopyTo(stream); }     // Read the stream
                        data.Log(new LogEntry("File saved as " + sanitizedPath, Colors.Green));
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                data.Log(new LogEntry(ex.Message, Colors.White));
                if (ex.GetType() == typeof(HttpException))
                {
                    data.ResponseCode = ((HttpException)ex).HttpStatusCode.ToString();
                    data.Log(new LogEntry("Status code: " + data.ResponseCode, Colors.Cyan));
                }

                if (!data.ConfigSettings.IgnoreResponseErrors)
                {
                    throw;
                }
            }
            #endregion
        }
Exemplo n.º 19
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            // Get easy handles
            var tcp = data.TCPClient;
            var net = data.NETStream;
            var ssl = data.SSLStream;

            byte[] buffer   = new byte[2048];
            int    bytes    = -1;
            string response = "";

            switch (TCPCommand)
            {
            case TCPCommand.Connect:
                // Replace the Host and Port
                var h = ReplaceValues(host, data);
                var p = int.Parse(ReplaceValues(port, data));

                // Initialize the TCP client, connect to the host and get the SSL stream
                tcp = new TcpClient();
                tcp.Connect(h, p);

                if (tcp.Connected)
                {
                    net = tcp.GetStream();
                    if (UseSSL)
                    {
                        ssl = new SslStream(net);
                        ssl.AuthenticateAsClient(h);
                    }

                    //Wait a bit and read the Stream if not Empty
                    Thread.Sleep(200);
                    if (net.DataAvailable)
                    {
                        if (UseSSL)
                        {
                            bytes = ssl.Read(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            bytes = net.Read(buffer, 0, buffer.Length);
                        }

                        // Save the response as ASCII in the SOURCE variable
                        response = Encoding.ASCII.GetString(buffer, 0, bytes);
                    }

                    // Save the TCP client and the streams
                    data.TCPClient = tcp;
                    data.NETStream = net;
                    data.SSLStream = ssl;
                    data.TCPSSL    = UseSSL;

                    data.Log(new LogEntry($"Succesfully connected to host {h} on port {p}. The server says:", Colors.Green));
                    data.Log(new LogEntry(response, Colors.GreenYellow));
                }

                if (VariableName != "")
                {
                    data.Variables.Set(new CVar(VariableName, response, IsCapture));
                    data.Log(new LogEntry($"Saved Response in variable {VariableName}", Colors.White));
                }
                break;

            case TCPCommand.Disconnect:
                if (tcp == null)
                {
                    throw new Exception("Make a connection first!");
                }

                tcp.Close();
                tcp = null;
                if (net != null)
                {
                    net.Close();
                }
                if (ssl != null)
                {
                    ssl.Close();
                }
                data.Log(new LogEntry($"Succesfully closed the stream", Colors.GreenYellow));
                break;

            case TCPCommand.Send:
                if (tcp == null)
                {
                    throw new Exception("Make a connection first!");
                }

                var    msg     = ReplaceValues(Message, data);
                byte[] b       = { };
                var    payload = Encoding.ASCII.GetBytes(msg.Replace(@"\r\n", "\r\n"));

                // Manual implementation of the WebSocket frame
                if (WebSocket)
                {
                    List <byte> bl = new List <byte>();

                    // (FIN=1) (RSV1=0) (RSV2=0) (RSV3=0) (OPCODE=0001) = 128 + 1 = 129
                    bl.Add(129);

                    ulong pllen = (ulong)payload.Length;

                    // We add 128 because the mask bit (MSB) is always 1. In this case the payload len is 7 bits long
                    if (pllen <= 125)
                    {
                        bl.Add((byte)(pllen + 128));
                    }

                    // Payload len set to 126 -> Next 2 bytes are payload len
                    else if (pllen <= ushort.MaxValue)
                    {
                        bl.Add(126 + 128);
                        bl.Add((byte)(pllen >> 8));     // Shift by 1 byte
                        bl.Add((byte)(pllen % 255));    // Take LSB
                    }

                    // Payload len set to 127 -> Next 4 bytes are payload len
                    else if (pllen <= ulong.MaxValue)
                    {
                        bl.Add(127 + 128);
                        bl.Add((byte)(pllen >> 24));         // Shift by 3 bytes
                        bl.Add((byte)((pllen >> 16) % 255)); // Shift by 2 bytes and take LSB
                        bl.Add((byte)((pllen >> 8) % 255));  // Shift by 1 byte and take LSB
                        bl.Add((byte)(pllen % 255));         // Take LSB
                    }

                    // Set the mask used for this message
                    byte[] mask = new byte[4] {
                        61, 84, 35, 6
                    };
                    bl.AddRange(mask);

                    // Finally we add the payload XORed with the mask
                    for (int i = 0; i < payload.Length; i++)
                    {
                        bl.Add((byte)(payload[i] ^ mask[i % 4]));
                    }

                    b = bl.ToArray();
                }
                else
                {
                    b = payload;
                }
                data.Log(new LogEntry("> " + msg, Colors.White));

                if (data.TCPSSL)
                {
                    ssl.Write(b);
                    bytes = ssl.Read(buffer, 0, buffer.Length);
                }
                else
                {
                    net.Write(b, 0, b.Length);
                    bytes = net.Read(buffer, 0, buffer.Length);
                }

                // Save the response as ASCII in the SOURCE variable and log it
                response = Encoding.ASCII.GetString(buffer, 0, bytes);
                data.Log(new LogEntry("> " + response, Colors.GreenYellow));

                if (VariableName != "")
                {
                    data.Variables.Set(new CVar(VariableName, response, IsCapture));
                    data.Log(new LogEntry($"Saved Response in variable {VariableName}.", Colors.White));
                }
                break;
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// Executes the actual block logic.
 /// </summary>
 /// <param name="data">The BotData needed for variable replacement</param>
 public virtual void Process(BotData data)
 {
     // Clear log buffer
     data.LogBuffer.Clear();
     data.Log(new LogEntry(string.Format("<--- Executing Block {0} --->", Label), Colors.Orange));
 }
Exemplo n.º 21
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            if (!data.GlobalSettings.Captchas.BypassBalanceCheck)
            {
                base.Process(data);
            }

            var localUrl = ReplaceValues(url, data);

            data.Log(new LogEntry("WARNING! This block is obsolete and WILL BE REMOVED IN THE FUTURE! Use the SOLVECAPTCHA block!", Colors.Tomato));
            data.Log(new LogEntry("Downloading image...", Colors.White));

            // Download captcha
            var captchaFile = string.Format("Captchas/captcha{0}.jpg", data.BotNumber);

            if (base64)
            {
                var bytes = Convert.FromBase64String(localUrl);
                using (var imageFile = new FileStream(captchaFile, FileMode.Create))
                {
                    imageFile.Write(bytes, 0, bytes.Length);
                    imageFile.Flush();
                }
            }
            else if (sendScreenshot && data.Screenshots.Count > 0)
            {
                Bitmap image = new Bitmap(data.Screenshots.Last());
                image.Save(captchaFile);
            }
            else
            {
                try
                {
                    Download.RemoteFile(captchaFile, localUrl,
                                        data.UseProxies, data.Proxy, data.Cookies, out Dictionary <string, string> newCookies,
                                        data.GlobalSettings.General.RequestTimeout * 1000, ReplaceValues(UserAgent, data));
                    data.Cookies = newCookies;
                }
                catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); throw; }
            }

            string response = "";

            var bitmap = new Bitmap(captchaFile);

            try
            {
                var converter = new ImageConverter();
                var bytes     = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));

                response = Captchas.GetService(data.GlobalSettings.Captchas)
                           .SolveImageCaptchaAsync(Convert.ToBase64String(bytes)).Result.Response;
            }
            catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); throw; }
            finally { bitmap.Dispose(); }

            data.Log(response == string.Empty ? new LogEntry("Couldn't get a response from the service", Colors.Tomato) : new LogEntry("Succesfully got the response: " + response, Colors.GreenYellow));

            if (VariableName != string.Empty)
            {
                data.Log(new LogEntry("Response stored in variable: " + variableName, Colors.White));
                data.Variables.Set(new CVar(variableName, response));
            }
        }
Exemplo n.º 22
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            try
            {
                switch (group)
                {
                case UtilityGroup.List:

                    var  list     = data.Variables.GetList(listName);
                    var  list2    = data.Variables.GetList(secondListName);
                    var  item     = ReplaceValues(listItem, data);
                    var  index    = int.Parse(ReplaceValues(listIndex, data));
                    CVar variable = null;

                    switch (listAction)
                    {
                    case ListAction.Create:
                        data.Variables.Set(new CVar(variableName, new List <string>(), isCapture));
                        break;

                    case ListAction.Length:
                        data.Variables.Set(new CVar(variableName, list.Count().ToString(), isCapture));
                        break;

                    case ListAction.Join:
                        data.Variables.Set(new CVar(variableName, string.Join(separator, list), isCapture));
                        break;

                    case ListAction.Concat:
                        data.Variables.Set(new CVar(variableName, list.Concat(list2).ToList(), isCapture));
                        break;

                    case ListAction.Zip:
                        data.Variables.Set(new CVar(variableName, list.Zip(list2, (a, b) => a + b).ToList(), isCapture));
                        break;

                    case ListAction.Map:
                        data.Variables.Set(new CVar(variableName, list.Zip(list2, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v), isCapture));
                        break;

                    case ListAction.Add:
                        variable = data.Variables.Get(listName, CVar.VarType.List);
                        if (variable == null)
                        {
                            variable = data.GlobalVariables.Get(listName, CVar.VarType.List);
                        }
                        if (variable == null)
                        {
                            break;
                        }
                        if (variable.Value.Count == 0)
                        {
                            index = 0;
                        }
                        else if (index < 0)
                        {
                            index += variable.Value.Count;
                        }
                        variable.Value.Insert(index, item);
                        break;

                    case ListAction.Remove:
                        variable = data.Variables.Get(listName, CVar.VarType.List);
                        if (variable == null)
                        {
                            variable = data.GlobalVariables.Get(listName, CVar.VarType.List);
                        }
                        if (variable == null)
                        {
                            break;
                        }
                        if (variable.Value.Count == 0)
                        {
                            index = 0;
                        }
                        else if (index < 0)
                        {
                            index += variable.Value.Count;
                        }
                        variable.Value.RemoveAt(index);
                        break;

                    case ListAction.Random:
                        data.Variables.Set(new CVar(variableName, list[data.rand.Next(list.Count)], isCapture));
                        break;

                    default:
                        break;
                    }

                    data.Log(new LogEntry(string.Format("Executed action {0} on list {1}", listAction, listName), Colors.White));
                    break;

                case UtilityGroup.Variable:
                    string single;
                    switch (varAction)
                    {
                    case VarAction.Split:
                        single = data.Variables.GetSingle(varName);
                        data.Variables.Set(new CVar(variableName, single.Split(new string[] { ReplaceValues(separator, data) }, StringSplitOptions.None).ToList(), isCapture));
                        break;
                    }
                    data.Log(new LogEntry(string.Format("Executed action {0} on variable {1}", varAction, varName), Colors.White));
                    break;

                case UtilityGroup.Conversion:
                    byte[] convertedBytes = ConvertFrom(ReplaceValues(inputString, data), conversionFrom);
                    data.Variables.Set(new CVar(variableName, ConvertTo(convertedBytes, conversionTo), isCapture));
                    data.Log(new LogEntry(string.Format("Converted input from {0} to {1}", conversionFrom, conversionTo), Colors.White));
                    break;

                case UtilityGroup.File:
                    var file   = ReplaceValues(filePath, data);
                    var input  = ReplaceValues(inputString, data).Replace("\\r\\n", "\r\n").Replace("\\n", "\n");
                    var inputs = ReplaceValuesRecursive(inputString, data);
                    switch (fileAction)
                    {
                    case FileAction.Read:
                        data.Variables.Set(new CVar(variableName, File.ReadAllText(file), isCapture));
                        break;

                    case FileAction.ReadLines:
                        data.Variables.Set(new CVar(variableName, File.ReadAllLines(file).ToList(), isCapture));
                        break;

                    case FileAction.Write:
                        File.WriteAllText(file, input);
                        break;

                    case FileAction.WriteLines:
                        File.WriteAllLines(file, inputs);
                        break;

                    case FileAction.Append:
                        File.AppendAllText(file, input);
                        break;

                    case FileAction.AppendLines:
                        File.AppendAllLines(file, inputs);
                        break;
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); }
        }
Exemplo n.º 23
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            var localInputStrings = ReplaceValuesRecursive(inputString, data);
            var outputs           = new List <string>();

            for (int i = 0; i < localInputStrings.Count; i++)
            {
                var localInputString = localInputStrings[i];
                var outputString     = "";

                switch (FunctionType)
                {
                case Function.Constant:
                    outputString = localInputString;
                    break;

                case Function.Base64Encode:
                    outputString = localInputString.ToBase64();
                    break;

                case Function.Base64Decode:
                    outputString = localInputString.FromBase64();
                    break;

                case Function.HTMLEntityEncode:
                    outputString = WebUtility.HtmlEncode(localInputString);
                    break;

                case Function.HTMLEntityDecode:
                    outputString = WebUtility.HtmlDecode(localInputString);
                    break;

                case Function.Hash:
                    outputString = GetHash(localInputString, hashType).ToLower();
                    break;

                case Function.HMAC:
                    outputString = Hmac(localInputString, hashType, ReplaceValues(hmacKey, data), hmacBase64, keyBase64);
                    break;

                case Function.Translate:
                    outputString = localInputString;
                    foreach (var entry in TranslationDictionary.OrderBy(e => e.Key.Length).Reverse())
                    {
                        if (outputString.Contains(entry.Key))
                        {
                            outputString = outputString.Replace(entry.Key, entry.Value);
                            if (StopAfterFirstMatch)
                            {
                                break;
                            }
                        }
                    }
                    break;

                case Function.DateToUnixTime:
                    outputString = localInputString.ToDateTime(dateFormat).ToUnixTimeSeconds().ToString();
                    break;

                case Function.Length:
                    outputString = localInputString.Length.ToString();
                    break;

                case Function.ToLowercase:
                    outputString = localInputString.ToLower();
                    break;

                case Function.ToUppercase:
                    outputString = localInputString.ToUpper();
                    break;

                case Function.Replace:
                    if (useRegex)
                    {
                        outputString = Regex.Replace(localInputString, ReplaceValues(replaceWhat, data), ReplaceValues(replaceWith, data));
                    }
                    else
                    {
                        outputString = localInputString.Replace(ReplaceValues(replaceWhat, data), ReplaceValues(replaceWith, data));
                    }
                    break;

                case Function.RegexMatch:
                    outputString = Regex.Match(localInputString, ReplaceValues(regexMatch, data)).Value;
                    break;

                case Function.Unescape:
                    outputString = Regex.Unescape(localInputString);
                    break;

                case Function.URLEncode:
                    // The maximum allowed Uri size is 2083 characters, we use 2080 as a precaution
                    outputString = string.Join("", SplitInChunks(localInputString, 2080).Select(s => Uri.EscapeDataString(s)));
                    break;

                case Function.URLDecode:
                    outputString = Uri.UnescapeDataString(localInputString);
                    break;

                case Function.UnixTimeToDate:
                    outputString = double.Parse(localInputString).ToDateTime().ToString(dateFormat);
                    break;

                case Function.CurrentUnixTime:
                    outputString = DateTime.UtcNow.ToUnixTimeSeconds().ToString();
                    break;

                case Function.UnixTimeToISO8601:
                    outputString = double.Parse(localInputString).ToDateTime().ToISO8601();
                    break;

                case Function.RandomNum:
                    var min             = int.Parse(ReplaceValues(randomMin, data));
                    var max             = int.Parse(ReplaceValues(randomMax, data));
                    var randomNumString = data.random.Next(min, max).ToString();
                    outputString = randomZeroPad ? randomNumString.PadLeft(max.ToString().Length, '0') : randomNumString;
                    break;

                case Function.RandomString:
                    outputString = localInputString;
                    outputString = Regex.Replace(outputString, @"\?l", m => _lowercase[data.random.Next(_lowercase.Length)].ToString());
                    outputString = Regex.Replace(outputString, @"\?u", m => _uppercase[data.random.Next(_uppercase.Length)].ToString());
                    outputString = Regex.Replace(outputString, @"\?d", m => _digits[data.random.Next(_digits.Length)].ToString());
                    outputString = Regex.Replace(outputString, @"\?s", m => _symbols[data.random.Next(_symbols.Length)].ToString());
                    outputString = Regex.Replace(outputString, @"\?h", m => _hex[data.random.Next(_hex.Length)].ToString());
                    outputString = Regex.Replace(outputString, @"\?a", m => _allChars[data.random.Next(_allChars.Length)].ToString());
                    outputString = Regex.Replace(outputString, @"\?m", m => _udChars[data.random.Next(_udChars.Length)].ToString());
                    outputString = Regex.Replace(outputString, @"\?i", m => _ludChars[data.random.Next(_ludChars.Length)].ToString());
                    break;

                case Function.Ceil:
                    outputString = Math.Ceiling(Decimal.Parse(localInputString, _style, _provider)).ToString();
                    break;

                case Function.Floor:
                    outputString = Math.Floor(Decimal.Parse(localInputString, _style, _provider)).ToString();
                    break;

                case Function.Round:
                    outputString = Math.Round(Decimal.Parse(localInputString, _style, _provider), 0, MidpointRounding.AwayFromZero).ToString();
                    break;

                case Function.Compute:
                    outputString = new DataTable().Compute(localInputString.Replace(',', '.'), null).ToString();
                    break;

                case Function.CountOccurrences:
                    outputString = CountStringOccurrences(localInputString, stringToFind).ToString();
                    break;

                case Function.ClearCookies:
                    data.Cookies.Clear();
                    break;

                case Function.RSAEncrypt:
                    outputString = Crypto.RSAEncrypt(
                        localInputString,
                        ReplaceValues(RsaN, data),
                        ReplaceValues(RsaE, data),
                        RsaOAEP
                        );
                    break;

                /*
                 * case Function.RSADecrypt:
                 * outputString = Crypto.RSADecrypt(
                 *  localInputString,
                 *  ReplaceValues(RsaN, data),
                 *  ReplaceValues(RsaD, data),
                 *  RsaOAEP
                 *  );
                 * break;
                 */

                case Function.RSAPKCS1PAD2:
                    outputString = Crypto.RSAPkcs1Pad2(
                        localInputString,
                        ReplaceValues(RsaN, data),
                        ReplaceValues(RsaE, data)
                        );
                    break;

                case Function.Delay:
                    try { Thread.Sleep(int.Parse(localInputString)); } catch { }
                    break;

                case Function.CharAt:
                    outputString = localInputString.ToCharArray()[int.Parse(ReplaceValues(charIndex, data))].ToString();
                    break;

                case Function.Substring:
                    outputString = localInputString.Substring(int.Parse(ReplaceValues(substringIndex, data)), int.Parse(ReplaceValues(substringLength, data)));
                    break;

                case Function.ReverseString:
                    char[] charArray = localInputString.ToCharArray();
                    Array.Reverse(charArray);
                    outputString = new string(charArray);
                    break;

                case Function.Trim:
                    outputString = localInputString.Trim();
                    break;

                case Function.GetRandomUA:
                    if (UserAgentSpecifyBrowser)
                    {
                        outputString = UserAgent.ForBrowser(UserAgentBrowser);
                    }
                    else
                    {
                        outputString = UserAgent.Random(data.random);
                    }
                    break;

                case Function.AESEncrypt:
                    outputString = Crypto.AESEncrypt(localInputString, ReplaceValues(aesKey, data), ReplaceValues(aesIV, data), AesMode, AesPadding);
                    break;

                case Function.AESDecrypt:
                    outputString = Crypto.AESDecrypt(localInputString, ReplaceValues(aesKey, data), ReplaceValues(aesIV, data), AesMode, AesPadding);
                    break;

                case Function.PBKDF2PKCS5:
                    outputString = Crypto.PBKDF2PKCS5(localInputString, ReplaceValues(KdfSalt, data), KdfSaltSize, KdfIterations, KdfKeySize, KdfAlgorithm);
                    break;
                }

                data.Log(new LogEntry(string.Format("Executed function {0} on input {1} with outcome {2}", functionType, localInputString, outputString), Colors.GreenYellow));

                // Add to the outputs
                outputs.Add(outputString);
            }

            var isList = outputs.Count > 1 || InputString.Contains("[*]") || InputString.Contains("(*)") || InputString.Contains("{*}");

            InsertVariable(data, isCapture, isList, outputs, variableName, "", "", false, true);
        }
Exemplo n.º 24
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            // If the clearance info is already set and we're not getting it fresh each time, skip
            if (data.UseProxies)
            {
                if (data.Proxy.Clearance != "" && !data.GlobalSettings.Proxies.AlwaysGetClearance)
                {
                    data.Log(new LogEntry("Skipping CF Bypass because there is already a valid cookie", Colors.White));
                    data.Cookies["cf_clearance"] = data.Proxy.Clearance;
                    data.Cookies["__cfduid"]     = data.Proxy.Cfduid;
                    return;
                }
            }

            var localUrl = ReplaceValues(url, data);
            var uri      = new Uri(localUrl);

            // Initialize the captcha provider
            CaptchaService service = Captchas.GetService(data.GlobalSettings.Captchas);

            // Initialize the Cloudflare Solver
            CloudflareSolver cf = new CloudflareSolver(service, ReplaceValues(UserAgent, data))
            {
                ClearanceDelay  = 3000,
                MaxCaptchaTries = 1,
                MaxTries        = 3
            };

            // Create the cookie container
            CookieContainer cookies = new CookieContainer();

            foreach (var cookie in data.Cookies)
            {
                cookies.Add(new Cookie(cookie.Key, cookie.Value, "/", uri.Host));
            }

            // Initialize the http handler
            HttpClientHandler handler = new HttpClientHandler
            {
                AllowAutoRedirect      = AutoRedirect,
                CookieContainer        = cookies,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                SslProtocols           = SecurityProtocol.ToSslProtocols()
            };

            // Assign the proxy to the inner handler if necessary
            if (data.UseProxies)
            {
                if (data.Proxy.Type != Extreme.Net.ProxyType.Http)
                {
                    throw new Exception($"The proxy type {data.Proxy.Type} is not supported by this block yet");
                }

                handler.Proxy    = new WebProxy(data.Proxy.Proxy, false);
                handler.UseProxy = true;

                if (!string.IsNullOrEmpty(data.Proxy.Username))
                {
                    handler.DefaultProxyCredentials = new NetworkCredential(data.Proxy.Username, data.Proxy.Password);
                }
            }

            // Initialize the http client
            HttpClient http = new HttpClient(handler);

            http.Timeout = TimeSpan.FromSeconds(data.GlobalSettings.General.RequestTimeout);
            http.DefaultRequestHeaders.Add("User-Agent", ReplaceValues(UserAgent, data));

            SolveResult result = new SolveResult();

            try
            {
                result = cf.Solve(http, handler, uri, ReplaceValues(UserAgent, data)).Result;
            }
            catch (AggregateException ex)
            {
                // Join all the aggregate exception inner exception messages
                var message = string.Join(Environment.NewLine, ex.InnerExceptions.Select(e => e.Message));

                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.Log(new LogEntry(message, Colors.Tomato));
                    data.ResponseCode = message;
                    return;
                }
                throw new Exception(message);
            }
            catch (Exception ex)
            {
                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.Log(new LogEntry(ex.Message, Colors.Tomato));
                    data.ResponseSource = ex.Message;
                    return;
                }
                throw;
            }

            if (result.Success)
            {
                data.Log(new LogEntry($"[Success] Protection bypassed: {result.DetectResult.Protection}", Colors.GreenYellow));
            }
            else if (result.DetectResult.Protection == CloudflareProtection.Unknown)
            {
                data.Log(new LogEntry($"Unknown protection, skipping the bypass!", Colors.Tomato));
            }
            else
            {
                var message = $"CF Bypass Failed: {result.FailReason}";

                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.Log(new LogEntry(message, Colors.Tomato));
                    data.ResponseSource = message;
                    return;
                }
                throw new Exception(message);
            }

            // Now that we got the cookies, proceed with the normal request
            HttpResponseMessage response = null;

            try
            {
                response = http.GetAsync(uri).Result;
            }
            catch (Exception ex)
            {
                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.ResponseSource = ex.Message;
                    return;
                }
                throw new Exception(ex.Message);
            }
            finally
            {
                handler.Dispose();
                http.Dispose();
            }

            var responseString = response.Content.ReadAsStringAsync().Result;

            // Save the cloudflare cookies
            var clearance = "";
            var cfduid    = "";

            foreach (Cookie cookie in cookies.GetCookies(uri))
            {
                switch (cookie.Name)
                {
                case "cf_clearance":
                    clearance = cookie.Value;
                    break;

                case "__cfduid":
                    cfduid = cookie.Value;
                    break;
                }
            }

            // Save the cookies in the proxy
            if (data.UseProxies)
            {
                data.Proxy.Clearance = clearance;
                data.Proxy.Cfduid    = cfduid;
            }

            if (clearance != "")
            {
                data.Log(new LogEntry("Got Cloudflare clearance!", Colors.GreenYellow));
                data.Log(new LogEntry(clearance + Environment.NewLine + cfduid + Environment.NewLine, Colors.White));
            }

            // Get address
            data.Address = response.RequestMessage.RequestUri.AbsoluteUri;
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry($"Address: {data.Address}", Colors.Cyan));
            }

            // Get code
            data.ResponseCode = ((int)response.StatusCode).ToString();
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry($"Response code: {data.ResponseCode}", Colors.Cyan));
            }

            // Get headers
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Received headers:", Colors.DeepPink));
            }
            data.ResponseHeaders.Clear();
            foreach (var header in response.Headers)
            {
                var h = new KeyValuePair <string, string>(header.Key, header.Value.First());
                data.ResponseHeaders.Add(h.Key, h.Value);
                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"{h.Key}: {h.Value}", Colors.LightPink));
                }
            }

            // Add the Content-Length header if it was not sent by the server
            if (!data.ResponseHeaders.ContainsKey("Content-Length"))
            {
                if (data.ResponseHeaders.ContainsKey("Content-Encoding") && data.ResponseHeaders["Content-Encoding"].Contains("gzip"))
                {
                    data.ResponseHeaders["Content-Length"] = GZip.Zip(responseString).Length.ToString();
                }
                else
                {
                    data.ResponseHeaders["Content-Length"] = responseString.Length.ToString();
                }

                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"Content-Length: {data.ResponseHeaders["Content-Length"]}", Colors.LightPink));
                }
            }

            // Get cookies
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Received cookies:", Colors.Goldenrod));
            }
            foreach (Cookie cookie in cookies.GetCookies(uri))
            {
                data.Cookies[cookie.Name] = cookie.Value;
                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"{cookie.Name}: {cookie.Value}", Colors.LightGoldenrodYellow));
                }
            }

            // Print source
            data.ResponseSource = responseString;
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Response Source:", Colors.Green));
                data.Log(new LogEntry(data.ResponseSource, Colors.GreenYellow));
            }
        }
Exemplo n.º 25
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            if (data.Driver == null && action != BrowserAction.Open)
            {
                data.Log(new LogEntry("Open a browser first!", Colors.White));
                throw new Exception("Browser not open");
            }

            var replacedInput = ReplaceValues(input, data);

            switch (action)
            {
            case BrowserAction.Open:
                OpenBrowser(data);
                try { UpdateSeleniumData(data); } catch { }
                break;

            case BrowserAction.Close:
                data.Driver.Close();
                data.BrowserOpen = false;
                break;

            case BrowserAction.Quit:
                data.Driver.Quit();
                data.BrowserOpen = false;
                break;

            case BrowserAction.ClearCookies:
                data.Driver.Manage().Cookies.DeleteAllCookies();
                break;

            case BrowserAction.SendKeys:
                var action = new Actions(data.Driver);
                foreach (var s in replacedInput.Split(new string[] { "||" }, StringSplitOptions.None))
                {
                    switch (s)
                    {
                    case "<TAB>":
                        action.SendKeys(OpenQA.Selenium.Keys.Tab);
                        break;

                    case "<ENTER>":
                        action.SendKeys(OpenQA.Selenium.Keys.Enter);
                        break;

                    case "<BACKSPACE>":
                        action.SendKeys(OpenQA.Selenium.Keys.Backspace);
                        break;

                    case "<ESC>":
                        action.SendKeys(OpenQA.Selenium.Keys.Escape);
                        break;

                    default:
                        action.SendKeys(s);
                        break;
                    }
                }
                action.Perform();
                Thread.Sleep(1000);
                if (replacedInput.Contains("<ENTER>") || replacedInput.Contains("<BACKSPACE>"))    // These might lead to a page change
                {
                    UpdateSeleniumData(data);
                }
                break;

            case BrowserAction.Screenshot:
                var image = data.Driver.GetScreenshot();
                SaveScreenshot(image, data);
                break;

            case BrowserAction.SwitchToTab:
                data.Driver.SwitchTo().Window(data.Driver.WindowHandles[int.Parse(replacedInput)]);
                UpdateSeleniumData(data);
                break;

            case BrowserAction.Refresh:
                data.Driver.Navigate().Refresh();
                break;

            case BrowserAction.Back:
                data.Driver.Navigate().Back();
                break;

            case BrowserAction.Forward:
                data.Driver.Navigate().Forward();
                break;

            case BrowserAction.Maximize:
                data.Driver.Manage().Window.Maximize();
                break;

            case BrowserAction.Minimize:
                data.Driver.Manage().Window.Minimize();
                break;

            case BrowserAction.FullScreen:
                data.Driver.Manage().Window.FullScreen();
                break;

            case BrowserAction.SetWidth:
                data.Driver.Manage().Window.Size = new Size(int.Parse(replacedInput), data.Driver.Manage().Window.Size.Height);
                break;

            case BrowserAction.SetHeight:
                data.Driver.Manage().Window.Size = new Size(data.Driver.Manage().Window.Size.Width, int.Parse(replacedInput));
                break;

            case BrowserAction.DOMtoSOURCE:
                data.ResponseSource = data.Driver.FindElement(By.TagName("body")).GetAttribute("innerHTML");
                break;

            case BrowserAction.GetCookies:
                foreach (var cookie in data.Driver.Manage().Cookies.AllCookies)
                {
                    try { data.Cookies.Add(cookie.Name, cookie.Value); } catch { }
                }
                break;

            case BrowserAction.SetCookies:
                var baseURL = Regex.Match(ReplaceValues(input, data), "^(?:https?:\\/\\/)?(?:[^@\\/\n]+@)?(?:www\\.)?([^:\\/?\n]+)").Groups[1].Value;
                foreach (var cookie in data.Cookies)
                {
                    try { data.Driver.Manage().Cookies.AddCookie(new Cookie(cookie.Key, cookie.Value, baseURL, "/", DateTime.MaxValue)); } catch { }
                }
                break;

            case BrowserAction.SwitchToDefault:
                data.Driver.SwitchTo().DefaultContent();
                break;

            case BrowserAction.SwitchToAlert:
                data.Driver.SwitchTo().Alert();
                break;

            case BrowserAction.SwitchToParentFrame:
                data.Driver.SwitchTo().ParentFrame();
                break;
            }

            data.Log(new LogEntry(string.Format("Executed browser action {0} on input {1}", action, ReplaceValues(input, data)), Colors.White));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Opens a browser of the given type (if not already open) and with the given settings.
        /// </summary>
        /// <param name="data">The BotData where the settings are stored.</param>
        public static void OpenBrowser(BotData data)
        {
            if (!data.BrowserOpen)
            {
                data.Log(new LogEntry("Opening browser...", Colors.White));

                switch (data.GlobalSettings.Selenium.Browser)
                {
                case BrowserType.Chrome:
                    try
                    {
                        ChromeOptions       chromeop      = new ChromeOptions();
                        ChromeDriverService chromeservice = ChromeDriverService.CreateDefaultService();
                        chromeservice.SuppressInitialDiagnosticInformation = true;
                        chromeservice.HideCommandPromptWindow = true;
                        chromeservice.EnableVerboseLogging    = false;
                        chromeop.AddArgument("--log-level=3");
                        chromeop.BinaryLocation = data.GlobalSettings.Selenium.ChromeBinaryLocation;
                        if (data.GlobalSettings.Selenium.Headless || data.ConfigSettings.ForceHeadless)
                        {
                            chromeop.AddArgument("--headless");
                        }
                        else if (data.GlobalSettings.Selenium.ChromeExtensions.Count > 0)     // This should only be done when not headless
                        {
                            chromeop.AddExtensions(data.GlobalSettings.Selenium.ChromeExtensions
                                                   .Where(ext => ext.EndsWith(".crx"))
                                                   .Select(ext => Directory.GetCurrentDirectory() + "\\ChromeExtensions\\" + ext));
                        }
                        if (data.ConfigSettings.DisableNotifications)
                        {
                            chromeop.AddArgument("--disable-notifications");
                        }
                        if (data.ConfigSettings.CustomCMDArgs != "")
                        {
                            chromeop.AddArgument(data.ConfigSettings.CustomCMDArgs);
                        }
                        if (data.ConfigSettings.RandomUA)
                        {
                            chromeop.AddArgument("--user-agent=" + BlockFunction.RandomUserAgent(data.rand));
                        }
                        else if (data.ConfigSettings.CustomUserAgent != "")
                        {
                            chromeop.AddArgument("--user-agent=" + data.ConfigSettings.CustomUserAgent);
                        }

                        if (data.UseProxies)
                        {
                            chromeop.AddArgument("--proxy-server=" + data.Proxy.Type.ToString().ToLower() + "://" + data.Proxy.Proxy);
                        }

                        data.Driver = new ChromeDriver(chromeservice, chromeop);
                    }
                    catch (Exception ex) { data.Log(new LogEntry(ex.ToString(), Colors.White)); return; }

                    break;

                case BrowserType.Firefox:
                    try
                    {
                        FirefoxOptions       fireop      = new FirefoxOptions();
                        FirefoxDriverService fireservice = FirefoxDriverService.CreateDefaultService();
                        FirefoxProfile       fireprofile = new FirefoxProfile();

                        fireservice.SuppressInitialDiagnosticInformation = true;
                        fireservice.HideCommandPromptWindow = true;
                        fireop.AddArgument("--log-level=3");
                        fireop.BrowserExecutableLocation = data.GlobalSettings.Selenium.FirefoxBinaryLocation;
                        if (data.GlobalSettings.Selenium.Headless || data.ConfigSettings.ForceHeadless)
                        {
                            fireop.AddArgument("--headless");
                        }
                        if (data.ConfigSettings.DisableNotifications)
                        {
                            fireprofile.SetPreference("dom.webnotifications.enabled", false);
                        }
                        if (data.ConfigSettings.CustomCMDArgs != "")
                        {
                            fireop.AddArgument(data.ConfigSettings.CustomCMDArgs);
                        }
                        if (data.ConfigSettings.RandomUA)
                        {
                            fireprofile.SetPreference("general.useragent.override", BlockFunction.RandomUserAgent(data.rand));
                        }
                        else if (data.ConfigSettings.CustomUserAgent != "")
                        {
                            fireprofile.SetPreference("general.useragent.override", data.ConfigSettings.CustomUserAgent);
                        }

                        if (data.UseProxies)
                        {
                            fireprofile.SetPreference("network.proxy.type", 1);
                            if (data.Proxy.Type == Extreme.Net.ProxyType.Http)
                            {
                                fireprofile.SetPreference("network.proxy.http", data.Proxy.Host);
                                fireprofile.SetPreference("network.proxy.http_port", int.Parse(data.Proxy.Port));
                                fireprofile.SetPreference("network.proxy.ssl", data.Proxy.Host);
                                fireprofile.SetPreference("network.proxy.ssl_port", int.Parse(data.Proxy.Port));
                            }
                            else
                            {
                                fireprofile.SetPreference("network.proxy.socks", data.Proxy.Host);
                                fireprofile.SetPreference("network.proxy.socks_port", int.Parse(data.Proxy.Port));
                                if (data.Proxy.Type == Extreme.Net.ProxyType.Socks4)
                                {
                                    fireprofile.SetPreference("network.proxy.socks_version", 4);
                                }
                                else if (data.Proxy.Type == Extreme.Net.ProxyType.Socks5)
                                {
                                    fireprofile.SetPreference("network.proxy.socks_version", 5);
                                }
                            }
                        }

                        fireop.Profile = fireprofile;
                        data.Driver    = new FirefoxDriver(fireservice, fireop, new TimeSpan(0, 1, 0));
                    }
                    catch (Exception ex) { data.Log(new LogEntry(ex.ToString(), Colors.White)); return; }

                    break;
                }

                data.Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(data.GlobalSettings.Selenium.PageLoadTimeout);
                data.Log(new LogEntry("Opened!", Colors.White));
                data.BrowserOpen = true;
            }
            else
            {
                try
                {
                    UpdateSeleniumData(data);
                }
                catch { }
            }
        }
Exemplo n.º 27
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            #region Request
            // Set base URL
            var localUrl = ReplaceValues(url, data);
            var cType    = ReplaceValues(contentType, data);

            // Create request
            HttpRequest request = new HttpRequest();

            // Setup options
            var timeout = data.GlobalSettings.General.RequestTimeout * 1000;
            request.IgnoreProtocolErrors         = true;
            request.AllowAutoRedirect            = autoRedirect;
            request.EnableEncodingContent        = true;
            request.ReadWriteTimeout             = timeout;
            request.ConnectTimeout               = timeout;
            request.KeepAlive                    = true;
            request.MaximumAutomaticRedirections = data.ConfigSettings.MaxRedirects;

            // Check if it has GET parameters
            if (ParseQuery && localUrl.Contains('?') && localUrl.Contains('='))
            {
                // Remove the query from the base URL
                localUrl = ReplaceValues(url.Split('?')[0], data);
                data.Log(new LogEntry($"Calling Base URL: {localUrl}", Colors.MediumTurquoise));

                // Parse the GET parameters
                var getParams = ReplaceValues(url.Split('?')[1], data);
                var paramList = getParams.Split('&');

                // Build the query, first replace variables in them and encode the parameters
                foreach (var par in paramList)
                {
                    var split = par.Split('=');

                    // Encode them if needed
                    if (split[0].Contains('%'))
                    {
                        split[0] = Uri.EscapeDataString(split[0]);
                    }
                    if (split[1].Contains('%'))
                    {
                        split[1] = Uri.EscapeDataString(split[1]);
                    }

                    // Add them to the query
                    request.AddUrlParam(split[0], split[1]);

                    data.Log(new LogEntry($"Added Query Parameter: {split[0]} = {split[1]}", Colors.MediumTurquoise));
                }
            }
            else
            {
                data.Log(new LogEntry($"Calling URL: {localUrl}", Colors.MediumTurquoise));
            }

            // Set up the Content and Content-Type
            HttpContent content = null;
            switch (requestType)
            {
            case RequestType.Standard:
                var pData = string.Join(Environment.NewLine, postData
                                        .Split(new string[] { "\\n" }, StringSplitOptions.None)
                                        .Select(p => ReplaceValues(p, data)));
                if (pData != "")
                {
                    if (encodeContent)
                    {
                        // Very dirty but it works
                        var nonce = data.rand.Next(1000000, 9999999);
                        pData = pData.Replace("&", $"{nonce}&{nonce}").Replace("=", $"{nonce}={nonce}");
                        pData = System.Uri.EscapeDataString(pData).Replace($"{nonce}%26{nonce}", "&").Replace($"{nonce}%3D{nonce}", "=");
                    }

                    content             = new StringContent(pData);
                    content.ContentType = cType;
                    data.Log(new LogEntry(string.Format("Post Data: {0}", pData), Colors.MediumTurquoise));
                }
                break;

            case RequestType.Multipart:
                if (multipartBoundary != "")
                {
                    content = new Extreme.Net.MultipartContent(multipartBoundary);
                }
                else
                {
                    content = new Extreme.Net.MultipartContent(GenerateMultipartBoundary());
                }
                var mContent = content as Extreme.Net.MultipartContent;
                foreach (var c in MultipartContents)
                {
                    if (c.Type == MultipartContentType.String)
                    {
                        mContent.Add(new StringContent(ReplaceValues(c.Value, data)), ReplaceValues(c.Name, data));
                    }
                    else if (c.Type == MultipartContentType.File)
                    {
                        mContent.Add(new FileContent(ReplaceValues(c.Value, data)), ReplaceValues(c.Name, data));
                    }
                }
                break;

            default:
                break;
            }

            // Set proxy
            if (data.UseProxies)
            {
                request.Proxy = data.Proxy.GetClient();

                try
                {
                    request.Proxy.ReadWriteTimeout = timeout;
                    request.Proxy.ConnectTimeout   = timeout;
                    request.Proxy.Username         = data.Proxy.Username;
                    request.Proxy.Password         = data.Proxy.Password;
                }
                catch { }
            }

            // Set headers
            data.Log(new LogEntry("Sent Headers:", Colors.DarkTurquoise));
            var fixedNames = Enum.GetNames(typeof(HttpHeader)).Select(n => n.ToLower());
            foreach (var header in CustomHeaders)
            {
                try
                {
                    var key         = ReplaceValues(header.Key, data);
                    var replacedKey = key.Replace("-", "").ToLower(); // Used to compare with the HttpHeader enum
                    var val         = ReplaceValues(header.Value, data);

                    if (replacedKey == "contenttype") // If it's somewhat needed to define Content-Type in e.g. a GET request
                    {
                        content             = new StringContent("");
                        content.ContentType = val;
                    }
                    else if (fixedNames.Contains(replacedKey))
                    {
                        request.AddHeader((HttpHeader)Enum.Parse(typeof(HttpHeader), replacedKey, true), val);
                    }
                    else
                    {
                        request.AddHeader(key, val);
                    }

                    data.Log(new LogEntry(key + ": " + val, Colors.MediumTurquoise));
                }
                catch { }
            }

            // Add the authorization header on a Basic Auth request
            if (requestType == RequestType.BasicAuth)
            {
                var usr  = ReplaceValues(authUser, data);
                var pwd  = ReplaceValues(authPass, data);
                var auth = "Basic " + BlockFunction.Base64Encode(usr + ":" + pwd);
                request.AddHeader("Authorization", auth);
                data.Log(new LogEntry("Authorization: " + auth, Colors.MediumTurquoise));
            }

            // Add the content-type header
            if ((method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.DELETE) && cType != "")
            {
                data.Log(new LogEntry("Content-Type: " + cType, Colors.MediumTurquoise));
            }

            // Add new user-defined custom cookies to the bot's cookie jar
            request.Cookies = new CookieDictionary();
            foreach (var cookie in CustomCookies)
            {
                data.Cookies[ReplaceValues(cookie.Key, data)] = ReplaceValues(cookie.Value, data);
            }

            // Set cookies from the bot's cookie jar to the request's CookieDictionary
            data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise));
            foreach (var cookie in data.Cookies)
            {
                request.Cookies.Add(cookie.Key, cookie.Value);
                data.Log(new LogEntry(cookie.Key + " : " + cookie.Value, Colors.MediumTurquoise));
            }

            data.LogNewLine();
            #endregion

            #region Response
            // Create the response
            HttpResponse response = null;

            try
            {
                // Get response
                response = request.Raw(method, localUrl, content);

                // Get address
                data.Address = response.Address.ToString();
                data.Log(new LogEntry("Address: " + data.Address, Colors.Cyan));

                // Get code
                data.ResponseCode = ((int)response.StatusCode).ToString();
                data.Log(new LogEntry("Response code: " + data.ResponseCode, Colors.Cyan));

                // Get headers
                data.Log(new LogEntry("Received headers:", Colors.DeepPink));
                var headerList      = new List <KeyValuePair <string, string> >();
                var receivedHeaders = response.EnumerateHeaders();
                data.ResponseHeaders.Clear();
                while (receivedHeaders.MoveNext())
                {
                    var header = receivedHeaders.Current;
                    data.ResponseHeaders.Add(header.Key, header.Value);
                    data.Log(new LogEntry(header.Key + ": " + header.Value, Colors.LightPink));
                }

                // Get cookies
                data.Log(new LogEntry("Received cookies:", Colors.Goldenrod));
                data.Cookies = response.Cookies;
                foreach (var cookie in response.Cookies)
                {
                    data.Log(new LogEntry(cookie.Key + ": " + cookie.Value, Colors.LightGoldenrodYellow));
                }

                // Save the response content
                switch (responseType)
                {
                case ResponseType.String:
                    data.Log(new LogEntry("Response Source:", Colors.Green));
                    if (readResponseSource)
                    {
                        data.ResponseSource = response.ToString();
                        data.Log(new LogEntry(data.ResponseSource, Colors.GreenYellow));
                    }
                    else
                    {
                        data.ResponseSource = "";
                        data.Log(new LogEntry("[SKIPPED]", Colors.GreenYellow));
                    }
                    break;

                case ResponseType.File:
                    var file = ReplaceValues(downloadPath, data);
                    using (var stream = File.Create(file)) { response.ToMemoryStream().CopyTo(stream); }
                    data.Log(new LogEntry("File saved as " + file, Colors.Green));
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                data.Log(new LogEntry(ex.Message, Colors.White));
                if (ex.GetType() == typeof(HttpException))
                {
                    data.ResponseCode = ((HttpException)ex).HttpStatusCode.ToString();
                    data.Log(new LogEntry("Status code: " + data.ResponseCode, Colors.Cyan));
                }

                if (!data.ConfigSettings.IgnoreResponseErrors)
                {
                    throw;
                }
            }
            #endregion
        }
Exemplo n.º 28
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            try
            {
                var replacedInput = ReplaceValues(inputString, data);
                switch (group)
                {
                case UtilityGroup.List:
                    var  list     = data.Variables.GetList(listName);
                    var  list2    = data.Variables.GetList(secondListName);
                    var  item     = ReplaceValues(listItem, data);
                    var  index    = int.Parse(ReplaceValues(listIndex, data));
                    CVar variable = null;

                    switch (listAction)
                    {
                    case ListAction.Create:
                        data.Variables.Set(new CVar(variableName, new List <string>(), isCapture));
                        break;

                    case ListAction.Length:
                        data.Variables.Set(new CVar(variableName, list.Count().ToString(), isCapture));
                        break;

                    case ListAction.Join:
                        data.Variables.Set(new CVar(variableName, string.Join(separator, list), isCapture));
                        break;

                    case ListAction.Sort:
                        var sorted = list.Select(e => e).ToList();         // Clone the list so we don't edit the original one
                        if (Numeric)
                        {
                            var nums = sorted.Select(e => double.Parse(e, CultureInfo.InvariantCulture)).ToList();
                            nums.Sort();
                            sorted = nums.Select(e => e.ToString()).ToList();
                        }
                        else
                        {
                            sorted.Sort();
                        }
                        if (!Ascending)
                        {
                            sorted.Reverse();
                        }
                        data.Variables.Set(new CVar(variableName, sorted, isCapture));
                        break;

                    case ListAction.Concat:
                        data.Variables.Set(new CVar(variableName, list.Concat(list2).ToList(), isCapture));
                        break;

                    case ListAction.Intersection:
                        data.Variables.Set(new CVar(variableName, list.Intersect(list2).ToList(), isCapture));
                        break;

                    case ListAction.Difference:
                        data.Variables.Set(new CVar(variableName, list.Except(list2).ToList(), isCapture));
                        break;

                    case ListAction.Zip:
                        data.Variables.Set(new CVar(variableName, list.Zip(list2, (a, b) => a + b).ToList(), isCapture));
                        break;

                    case ListAction.Map:
                        data.Variables.Set(new CVar(variableName, list.Zip(list2, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v), isCapture));
                        break;

                    case ListAction.Add:
                        // TODO: Refactor this
                        variable = data.Variables.Get(listName, CVar.VarType.List);
                        if (variable == null)
                        {
                            variable = data.GlobalVariables.Get(listName, CVar.VarType.List);
                        }
                        if (variable == null)
                        {
                            break;
                        }
                        if (variable.Value.Count == 0)
                        {
                            index = 0;
                        }
                        else if (index < 0)
                        {
                            index += variable.Value.Count;
                        }
                        variable.Value.Insert(index, item);
                        break;

                    case ListAction.Remove:
                        // TODO: Refactor this
                        variable = data.Variables.Get(listName, CVar.VarType.List);
                        if (variable == null)
                        {
                            variable = data.GlobalVariables.Get(listName, CVar.VarType.List);
                        }
                        if (variable == null)
                        {
                            break;
                        }
                        if (variable.Value.Count == 0)
                        {
                            index = 0;
                        }
                        else if (index < 0)
                        {
                            index += variable.Value.Count;
                        }
                        variable.Value.RemoveAt(index);
                        break;

                    case ListAction.RemoveValues:
                        data.Variables.Set(new CVar(variableName, list.Where(l => !Condition.Verify(new KeycheckCondition
                        {
                            Left     = ReplaceValues(l, data),
                            Comparer = ListElementComparer,
                            Right    = ListComparisonTerm
                        })).ToList(), isCapture));
                        break;

                    case ListAction.RemoveDuplicates:
                        data.Variables.Set(new CVar(variableName, list.Distinct().ToList(), isCapture));
                        break;

                    case ListAction.Random:
                        data.Variables.Set(new CVar(variableName, list[data.random.Next(list.Count)], isCapture));
                        break;

                    case ListAction.Shuffle:
                        // This makes a copy of the original list
                        var listCopy = list.ToArray().ToList();
                        listCopy.Shuffle(data.random);
                        data.Variables.Set(new CVar(variableName, listCopy, isCapture));
                        break;

                    default:
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {listAction} on file {listName}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Variable:
                    string single;
                    switch (varAction)
                    {
                    case VarAction.Split:
                        single = data.Variables.GetSingle(varName);
                        data.Variables.Set(new CVar(variableName, single.Split(new string[] { ReplaceValues(splitSeparator, data) }, StringSplitOptions.None).ToList(), isCapture));
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {varAction} on variable {varName}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Conversion:
                    byte[] conversionInputBytes = replacedInput.ConvertFrom(conversionFrom);
                    var    conversionResult     = conversionInputBytes.ConvertTo(conversionTo);
                    data.Variables.Set(new CVar(variableName, conversionResult, isCapture));
                    data.Log(new LogEntry($"Executed conversion {conversionFrom} to {conversionTo} on input {replacedInput} with outcome {conversionResult}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.File:
                    var file = ReplaceValues(filePath, data);
                    Files.ThrowIfNotInCWD(file);

                    switch (fileAction)
                    {
                    case FileAction.Exists:
                        data.Variables.Set(new CVar(variableName, File.Exists(file).ToString(), isCapture));
                        break;

                    case FileAction.Read:
                        lock (FileLocker.GetLock(file))
                            data.Variables.Set(new CVar(variableName, File.ReadAllText(file), isCapture));
                        break;

                    case FileAction.ReadLines:
                        lock (FileLocker.GetLock(file))
                            data.Variables.Set(new CVar(variableName, File.ReadAllLines(file).ToList(), isCapture));
                        break;

                    case FileAction.Write:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.WriteAllText(file, replacedInput.Unescape());
                        break;

                    case FileAction.WriteLines:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.WriteAllLines(file, ReplaceValuesRecursive(inputString, data).Select(i => i.Unescape()));
                        break;

                    case FileAction.Append:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.AppendAllText(file, replacedInput.Unescape());
                        break;

                    case FileAction.AppendLines:
                        Files.CreatePath(file);
                        lock (FileLocker.GetLock(file))
                            File.AppendAllLines(file, ReplaceValuesRecursive(inputString, data).Select(i => i.Unescape()));
                        break;

                    case FileAction.Copy:
                        var fileCopyLocation = ReplaceValues(inputString, data);
                        Files.ThrowIfNotInCWD(fileCopyLocation);
                        Files.CreatePath(fileCopyLocation);
                        lock (FileLocker.GetLock(file))
                            lock (FileLocker.GetLock(fileCopyLocation))
                                File.Copy(file, fileCopyLocation);
                        break;

                    case FileAction.Move:
                        var fileMoveLocation = ReplaceValues(inputString, data);
                        Files.ThrowIfNotInCWD(fileMoveLocation);
                        Files.CreatePath(fileMoveLocation);
                        lock (FileLocker.GetLock(file))
                            lock (FileLocker.GetLock(fileMoveLocation))
                                File.Move(file, fileMoveLocation);
                        break;

                    case FileAction.Delete:
                        // No deletion if the file is in use (DB/OpenBullet.db cannot be deleted but instead DB/OpenBullet-BackupCopy.db)
                        // If another process is just reading the file it will be deleted
                        lock (FileLocker.GetLock(file))
                            File.Delete(file);
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {fileAction} on file {file}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Folder:
                    var folder = ReplaceValues(folderPath, data);
                    Files.ThrowIfNotInCWD(folder);

                    switch (folderAction)
                    {
                    case FolderAction.Exists:
                        data.Variables.Set(new CVar(variableName, Directory.Exists(folder).ToString(), isCapture));
                        break;

                    case FolderAction.Create:
                        data.Variables.Set(new CVar(variableName, Directory.CreateDirectory(folder).ToString(), isCapture));
                        break;

                    case FolderAction.Delete:
                        // All files in the folder will be deleted expect the ones that are in use
                        // DB/OpenBullet.db cannot be deleted but instead DB/OpenBullet-BackupCopy.db
                        // If another process is just reading a file in the folder it will be deleted
                        Directory.Delete(folder, true);
                        break;
                    }
                    data.Log(new LogEntry($"Executed action {folderAction} on folder {folder}", isCapture ? Colors.Tomato : Colors.Yellow));
                    break;

                case UtilityGroup.Telegram:
                    lock (tlgLocker)
                    {
                        var bot = new TelegramBotClient(BotToken);
                        Telegram.Bot.Types.ChatId chatId = null;
                        try
                        {
                            if (ChatId.StartsWith("@"))
                            {
                                chatId = new Telegram.Bot.Types.ChatId(ChatId);
                            }
                            else
                            {
                                chatId = new Telegram.Bot.Types.ChatId(int.Parse(ChatId));
                            }
                        }
                        catch { data.Log(new LogEntry("Chat Id is invalid", Colors.Red)); }
                        var s = 0;
                        while (s < 20)
                        {
                            var result = bot.SendTextMessageAsync(chatId, ReplaceValues(string.Join("\n", Messages), data), ParseMode).Result;
                            if (result == null)
                            {
                                data.Log(new LogEntry("Message sent not successfully!!", Colors.Red));
                                data.Log(new LogEntry("Sleep 100ms", Colors.Yellow));
                                Thread.Sleep(100);
                                s++;
                                continue;
                            }
                            data.Log(new LogEntry("Message sent successfully!", Colors.LimeGreen));
                            break;
                        }
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.Tomato)); if (ex.InnerException != null)
                                   {
                                       data.Log(new LogEntry(ex.InnerException.Message, Colors.Tomato));
                                   }
            }
        }
Exemplo n.º 29
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            if (data.Driver == null)
            {
                data.Log(new LogEntry("Open a browser first!", Colors.White));
                throw new Exception("Browser not open");
            }

            // Find the element
            IWebElement element = null;
            ReadOnlyCollection <IWebElement> elements = null;

            try
            {
                if (action != ElementAction.WaitForElement)
                {
                    elements = FindElements(data);
                    element  = elements[elementIndex];
                }
            }
            catch { data.Log(new LogEntry("Cannot find element on the page", Colors.White)); }

            List <string> outputs = new List <string>();

            try
            {
                switch (action)
                {
                case ElementAction.Clear:
                    element.Clear();
                    break;

                case ElementAction.SendKeys:
                    element.SendKeys(ReplaceValues(input, data));
                    break;

                case ElementAction.Click:
                    element.Click();
                    UpdateSeleniumData(data);
                    break;

                case ElementAction.Submit:
                    element.Submit();
                    UpdateSeleniumData(data);
                    break;

                case ElementAction.SelectOptionByText:
                    new SelectElement(element).SelectByText(ReplaceValues(input, data));
                    break;

                case ElementAction.SelectOptionByIndex:
                    new SelectElement(element).SelectByIndex(int.Parse(ReplaceValues(input, data)));
                    break;

                case ElementAction.SelectOptionByValue:
                    new SelectElement(element).SelectByValue(ReplaceValues(input, data));
                    break;

                case ElementAction.GetText:
                    if (recursive)
                    {
                        foreach (var elem in elements)
                        {
                            outputs.Add(elem.Text);
                        }
                    }
                    else
                    {
                        outputs.Add(element.Text);
                    }
                    break;

                case ElementAction.GetAttribute:
                    if (recursive)
                    {
                        foreach (var elem in elements)
                        {
                            outputs.Add(elem.GetAttribute(ReplaceValues(input, data)));
                        }
                    }
                    else
                    {
                        outputs.Add(element.GetAttribute(ReplaceValues(input, data)));
                    }
                    break;

                case ElementAction.IsDisplayed:
                    outputs.Add(element.Displayed.ToString());
                    break;

                case ElementAction.IsEnabled:
                    outputs.Add(element.Enabled.ToString());
                    break;

                case ElementAction.IsSelected:
                    outputs.Add(element.Selected.ToString());
                    break;

                case ElementAction.LocationX:
                    outputs.Add(element.Location.X.ToString());
                    break;

                case ElementAction.LocationY:
                    outputs.Add(element.Location.Y.ToString());
                    break;

                case ElementAction.SizeX:
                    outputs.Add(element.Size.Width.ToString());
                    break;

                case ElementAction.SizeY:
                    outputs.Add(element.Size.Height.ToString());
                    break;

                case ElementAction.Screenshot:
                    var image = GetElementScreenShot(data.Driver, element);
                    Files.SaveScreenshot(image, data);
                    break;

                case ElementAction.ScreenshotBase64:
                    var image2    = GetElementScreenShot(data.Driver, element);
                    var memStream = new MemoryStream();
                    image2.Save(memStream, ImageFormat.Jpeg);
                    outputs.Add(Convert.ToBase64String(memStream.ToArray()));
                    break;

                case ElementAction.SwitchToFrame:
                    data.Driver.SwitchTo().Frame(element);
                    break;

                case ElementAction.WaitForElement:
                {
                    var ms  = 0;                                     // Currently waited milliseconds
                    var max = 10000;
                    try { max = int.Parse(input) * 1000; } catch { } // Max ms to wait
                    var found = false;
                    while (ms < max)
                    {
                        try
                        {
                            elements = FindElements(data);
                            element  = elements[0];
                            found    = true;
                            break;
                        }
                        catch { ms += 200; Thread.Sleep(200); }
                    }
                    if (!found)
                    {
                        data.Log(new LogEntry("Timeout while waiting for element", Colors.White));
                    }
                }
                break;

                case ElementAction.WaitForElementNotExists:
                {
                    var ms  = 0;                                     // Currently waited milliseconds
                    var max = 10000;
                    try { max = int.Parse(input) * 1000; } catch { } // Max ms to wait
                    var found = true;
                    while (ms < max)
                    {
                        try
                        {
                            elements = FindElements(data);
                            element  = elements[0];
                            found    = false;
                            ms      += 200; Thread.Sleep(200);
                        }
                        catch { found = false; break; }
                    }
                    if (found)
                    {
                        data.Log(new LogEntry("Timeout while waiting for element not exists", Colors.White));
                    }
                    break;
                }

                case ElementAction.SendKeysHuman:
                    var toSend = ReplaceValues(input, data);
                    var rand   = new Random();
                    foreach (char c in toSend)
                    {
                        element.SendKeys(c.ToString());
                        Thread.Sleep(rand.Next(100, 300));
                    }
                    break;
                }
            }
            catch { data.Log(new LogEntry("Cannot execute action on the element", Colors.White)); }

            data.Log(new LogEntry(string.Format("Executed action {0} on the element with input {1}", action, ReplaceValues(input, data)), Colors.White));

            if (outputs.Count != 0)
            {
                InsertVariable(data, isCapture, recursive, outputs, outputVariable, "", "", false, true);
            }
        }
Exemplo n.º 30
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            var style    = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
            var provider = new CultureInfo("en-US");

            var localInputStrings = ReplaceValuesRecursive(inputString, data);
            var outputs           = new List <string>();

            for (int i = 0; i < localInputStrings.Count; i++)
            {
                var localInputString = localInputStrings[i];
                var outputString     = "";

                switch (FunctionType)
                {
                case Function.Constant:
                    outputString = localInputString;
                    break;

                case Function.Base64Encode:
                    outputString = Base64Encode(localInputString);
                    break;

                case Function.Base64Decode:
                    outputString = Base64Decode(localInputString);
                    break;

                case Function.Hash:
                    outputString = GetHash(localInputString, hashType).ToLower();
                    break;

                case Function.HMAC:
                    outputString = Hmac(localInputString, hashType, ReplaceValues(hmacKey, data), hmacBase64);
                    break;

                case Function.Translate:
                    outputString = localInputString;
                    foreach (var entry in TranslationDictionary.OrderBy(e => e.Key.Length).Reverse())
                    {
                        if (outputString.Contains(entry.Key))
                        {
                            outputString = outputString.Replace(entry.Key, entry.Value);
                            if (StopAfterFirstMatch)
                            {
                                break;
                            }
                        }
                    }
                    break;

                case Function.DateToUnixTime:
                    outputString = (DateTime.ParseExact(localInputString, dateFormat, new CultureInfo("en-US"), DateTimeStyles.AllowWhiteSpaces)
                                    .Subtract(new DateTime(1970, 1, 1)))
                                   .TotalSeconds
                                   .ToString();
                    break;

                case Function.Length:
                    outputString = localInputString.Length.ToString();
                    break;

                case Function.ToLowercase:
                    outputString = localInputString.ToLower();
                    break;

                case Function.ToUppercase:
                    outputString = localInputString.ToUpper();
                    break;

                case Function.Replace:
                    if (useRegex)
                    {
                        outputString = Regex.Replace(localInputString, ReplaceValues(replaceWhat, data), ReplaceValues(replaceWith, data));
                    }
                    else
                    {
                        outputString = localInputString.Replace(ReplaceValues(replaceWhat, data), ReplaceValues(replaceWith, data));
                    }
                    break;

                case Function.RegexMatch:
                    outputString = Regex.Match(localInputString, ReplaceValues(regexMatch, data)).Value;
                    break;

                case Function.URLEncode:
                    outputString = System.Uri.EscapeDataString(localInputString);
                    break;

                case Function.URLDecode:
                    outputString = System.Uri.UnescapeDataString(localInputString);
                    break;

                case Function.UnixTimeToDate:
                    try
                    {
                        var loc = localInputString;
                        if (localInputString.Length > 10)
                        {
                            loc = localInputString.Substring(0, 10);
                        }
                        DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                        dtDateTime   = dtDateTime.AddSeconds(int.Parse(loc)).ToLocalTime();
                        outputString = dtDateTime.ToShortDateString();
                    }
                    catch { }

                    break;

                case Function.CurrentUnixTime:
                    outputString = Math.Round((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString();
                    break;

                case Function.UnixTimeToISO8601:
                    var loc2 = localInputString;
                    if (localInputString.Length > 10)
                    {
                        loc2 = localInputString.Substring(0, 10);
                    }
                    DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                    dateTime     = dateTime.AddSeconds(int.Parse(loc2)).ToLocalTime();
                    outputString = dateTime.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffZ");
                    break;

                case Function.RandomNum:
                    outputString = (data.rand.Next(randomMin, randomMax)).ToString();
                    break;

                case Function.RandomString:
                    var reserved  = new string[] { "?l", "?u", "?d", "?s", "?h", "?a" };
                    var lowercase = "abcdefghijklmnopqrstuvwxyz";
                    var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    var digits    = "0123456789";
                    var symbols   = "\\!\"£$%&/()=?^'{}[]@#,;.:-_*+";
                    var hex       = digits + "abcdef";
                    var allchars  = lowercase + uppercase + digits + symbols;

                    outputString = localInputString;
                    while (reserved.Any(r => outputString.Contains(r)))
                    {
                        if (outputString.Contains("?l"))
                        {
                            outputString = ReplaceFirst(outputString, "?l", lowercase[data.rand.Next(0, lowercase.Length)].ToString());
                        }
                        else if (outputString.Contains("?u"))
                        {
                            outputString = ReplaceFirst(outputString, "?u", uppercase[data.rand.Next(0, uppercase.Length)].ToString());
                        }
                        else if (outputString.Contains("?d"))
                        {
                            outputString = ReplaceFirst(outputString, "?d", digits[data.rand.Next(0, digits.Length)].ToString());
                        }
                        else if (outputString.Contains("?s"))
                        {
                            outputString = ReplaceFirst(outputString, "?s", symbols[data.rand.Next(0, symbols.Length)].ToString());
                        }
                        else if (outputString.Contains("?h"))
                        {
                            outputString = ReplaceFirst(outputString, "?h", hex[data.rand.Next(0, hex.Length)].ToString());
                        }
                        else if (outputString.Contains("?a"))
                        {
                            outputString = ReplaceFirst(outputString, "?a", allchars[data.rand.Next(0, allchars.Length)].ToString());
                        }
                    }
                    break;

                case Function.Ceil:
                    outputString = Math.Ceiling(Decimal.Parse(localInputString, style, provider)).ToString();
                    break;

                case Function.Floor:
                    outputString = Math.Floor(Decimal.Parse(localInputString, style, provider)).ToString();
                    break;

                case Function.Round:
                    outputString = Math.Round(Decimal.Parse(localInputString, style, provider), 0, MidpointRounding.AwayFromZero).ToString();
                    break;

                case Function.Compute:
                    outputString = new DataTable().Compute(localInputString.Replace(',', '.'), null).ToString();
                    break;

                case Function.CountOccurrences:
                    outputString = CountStringOccurrences(localInputString, stringToFind).ToString();
                    break;

                case Function.ClearCookies:
                    data.Cookies.Clear();
                    break;

                case Function.RSA:
                    try
                    {
                        while (outputString.Length < 2 || outputString.Substring(outputString.Length - 2) != "==")
                        {
                            outputString = SteamRSAEncrypt(new RsaParameters {
                                Exponent = ReplaceValues(RSAExp, data), Modulus = ReplaceValues(RSAMod, data), Password = localInputString
                            });
                        }
                    }
                    catch (Exception ex) { outputString = ex.ToString(); }
                    break;

                case Function.Delay:
                    try { Thread.Sleep(int.Parse(localInputString)); } catch { }
                    break;

                case Function.CharAt:
                    outputString = localInputString.ToCharArray()[int.Parse(ReplaceValues(charIndex, data))].ToString();
                    break;

                case Function.Substring:
                    outputString = localInputString.Substring(int.Parse(ReplaceValues(substringIndex, data)), int.Parse(ReplaceValues(substringLength, data)));
                    break;

                case Function.ReverseString:
                    char[] charArray = localInputString.ToCharArray();
                    Array.Reverse(charArray);
                    outputString = new string(charArray);
                    break;

                case Function.Trim:
                    outputString = localInputString.Trim();
                    break;

                case Function.GetRandomUA:
                    outputString = RandomUserAgent(data.rand);
                    break;

                case Function.AESEncrypt:
                    outputString = AESEncrypt(ReplaceValues(aesKey, data), localInputString);
                    break;

                case Function.AESDecrypt:
                    outputString = AESDecrypt(ReplaceValues(aesKey, data), localInputString);
                    break;
                }

                data.Log(new LogEntry(string.Format("Executed function {0} on input {1} with outcome {2}", functionType, localInputString, outputString), Colors.GreenYellow));

                // Add to the outputs
                outputs.Add(outputString);
            }

            var isList = outputs.Count > 1 || InputString.Contains("[*]") || InputString.Contains("(*)") || InputString.Contains("{*}");

            InsertVariables(data, isCapture, isList, outputs, variableName, "", "");
        }