コード例 #1
0
        private void ProcessRewriteAction(InboundRule inboundRule, Uri uri, Match inboundRuleMatch, Match lastConditionMatch, InboundRuleResult ruleResult)
        {
            var redirectAction = inboundRule.Action as Rewrite;

            var rewriteUrl        = redirectAction.RewriteUrl;
            var rewriteItemAnchor = redirectAction.RewriteItemAnchor;

            if (string.IsNullOrEmpty(rewriteUrl))
            {
                ruleResult.RuleMatched = false;
                return;
            }

            // process token replacements
            var replacements = new RewriteHelper.Replacements
            {
                RequestHeaders         = RequestHeaders,
                RequestServerVariables = RequestServerVariables
            };

            rewriteUrl = RewriteHelper.ReplaceTokens(replacements, rewriteUrl);

            if (redirectAction.AppendQueryString)
            {
                rewriteUrl += uri.Query;
            }

            rewriteUrl = RewriteHelper.ReplaceRuleBackReferences(inboundRuleMatch, rewriteUrl);
            rewriteUrl = RewriteHelper.ReplaceConditionBackReferences(lastConditionMatch, rewriteUrl);

            ruleResult.RewrittenUri   = new Uri(rewriteUrl);
            ruleResult.StopProcessing = redirectAction.StopProcessingOfSubsequentRules;
        }
コード例 #2
0
        private InboundRuleResult ProcessInboundRule(Uri originalUri, InboundRule inboundRule)
        {
            Log.Debug(this, "Processing inbound rule - requestUri: {0} inboundRule: {1}", originalUri, inboundRule.Name);

            var ruleResult = new InboundRuleResult
            {
                OriginalUri  = originalUri,
                RewrittenUri = originalUri
            };

            switch (inboundRule.Using)
            {
            case Using.ExactMatch:
            case Using.RegularExpressions:
            case Using.Wildcards:
                ruleResult = ProcessRegularExpressionInboundRule(ruleResult.OriginalUri, inboundRule);

                break;
                //case Using.Wildcards:
                //    //TODO: Implement Wildcards
                //    throw new NotImplementedException("Using Wildcards has not been implemented");
                //    break;
            }

            Log.Debug(this, "Processing inbound rule - requestUri: {0} inboundRule: {1} rewrittenUrl: {2}", ruleResult.OriginalUri, inboundRule.Name, ruleResult.RewrittenUri);

            ruleResult.ItemId = inboundRule.ItemId;

            return(ruleResult);
        }
コード例 #3
0
        private bool TestSiteNameRestriction(InboundRule inboundRule)
        {
            var  currentSiteName    = Sitecore.Context.Site.Name;
            bool isInboundRuleMatch = false;

            if (currentSiteName != null)
            {
                isInboundRuleMatch = currentSiteName.Equals(inboundRule.SiteNameRestriction,
                                                            StringComparison.InvariantCultureIgnoreCase);

                if (!isInboundRuleMatch)
                {
                    Log.Debug(this, "Regex - Rule '{0}' failed.  Site '{1}' does not equal rules site condition '{2}'",
                              inboundRule.Name, currentSiteName, inboundRule.SiteNameRestriction);
                }
                else
                {
                    Log.Debug(this, "Regex - Rule '{0}' matched site name restriction.  Site '{1}' equal rules site condition '{2}'",
                              inboundRule.Name, currentSiteName, inboundRule.SiteNameRestriction);
                }
            }
            else
            {
                Log.Warn(this, "Regex - Rule '{0}' matching based on site name will not occur because site name is null.",
                         inboundRule.Name);
            }

            return(isInboundRuleMatch);
        }
コード例 #4
0
        public void ProcessRequestUrlWithCustomResponse()
        {
            var rewriter       = new InboundRewriter();
            var newInboundRule = new InboundRule()
            {
                Name    = "Custom Response Rule",
                Pattern = "customresponse",
                Using   = Using.ExactMatch,
                Action  = new CustomResponse()
                {
                    Name             = "Custom Response Action",
                    StatusCode       = 550,
                    SubStatusCode    = 100,
                    ErrorDescription = "Custom Response Because I Said So",
                    Reason           = "Custom Response 550"
                },
                MatchType = MatchType.MatchesThePattern
            };

            InboundRules.Insert(0, newInboundRule);

            var rewriteResult  = rewriter.ProcessRequestUrl(new Uri("http://fictitioussite.com/customresponse"), InboundRules);
            var customResponse = rewriteResult.FinalAction as CustomResponse;

            Assert.IsNotNull(customResponse);
            Assert.AreEqual(customResponse.StatusCode, 550);
            Assert.AreEqual(customResponse.SubStatusCode, 100);
            Assert.IsTrue(rewriteResult.ProcessedResults.Count == 1);
        }
コード例 #5
0
        public void ConditionMatchesAtLeastOne()
        {
            var rule = new InboundRule
            {
                ConditionLogicalGrouping = LogicalGrouping.MatchAny,
                Conditions = new List <Condition>
                {
                    new Condition()
                    {
                        CheckIfInputString = CheckIfInputString.DoesNotMatchThePattern,
                        InputString        = "OFF",
                        Pattern            = "OFF"
                    },
                    new Condition()
                    {
                        CheckIfInputString = CheckIfInputString.MatchesThePattern,
                        InputString        = "OFF",
                        Pattern            = "OFF"
                    },
                }
            };

            Match match = null;
            var   conditionMatchResult = RewriteHelper.TestConditionMatches(rule, null, out match);

            Assert.IsTrue(conditionMatchResult.Matched);
        }
コード例 #6
0
ファイル: InboundRewriter.cs プロジェクト: prem16/UrlRewrite
        private bool TestAllRuleMatches(InboundRule inboundRule, Uri originalUri, out Match inboundRuleMatch)
        {
            var haveMatch = TestRuleMatches(inboundRule, originalUri, out inboundRuleMatch, false);

            //If no match, let's include the host and try again
            if (!haveMatch)
            {
                haveMatch = TestRuleMatches(inboundRule, originalUri, out inboundRuleMatch, true);
            }

            return(haveMatch);
        }
コード例 #7
0
 public InboundRuleListViewItem(InboundRule item, RewritePage page)
     : base(item.Name)
 {
     Item  = item;
     _page = page;
     SubItems.Add(new ListViewSubItem(this, item.Input));
     SubItems.Add(new ListViewSubItem(this, item.Negate ? "Does not matches" : "Matches"));
     SubItems.Add(new ListViewSubItem(this, item.PatternUrl));
     SubItems.Add(new ListViewSubItem(this, ToString(item.Type)));
     SubItems.Add(new ListViewSubItem(this, item.ActionUrl));
     SubItems.Add(new ListViewSubItem(this, item.StopProcessing ? "True" : "False"));
     SubItems.Add(new ListViewSubItem(this, item.Flag));
 }
コード例 #8
0
        private bool TestRuleMatches(InboundRule inboundRule, Uri originalUri, out Match inboundRuleMatch)
        {
            var absolutePath = originalUri.AbsolutePath;
            var uriPath      = absolutePath.Substring(1); // remove starting "/"

            var escapedAbsolutePath = HttpUtility.UrlDecode(absolutePath);
            var escapedUriPath      = (escapedAbsolutePath ?? string.Empty).Substring(1); // remove starting "/"

            // TODO : I have only implemented "MatchesThePattern" - need to implement the other types
            var matchesThePattern = inboundRule.MatchType.HasValue &&
                                    inboundRule.MatchType.Value == MatchType.MatchesThePattern;

            if (!matchesThePattern)
            {
                throw new NotImplementedException(
                          "Have not yet implemented 'Does Not Match the Pattern' because of possible redirect loops");
            }

            var pattern = inboundRule.Pattern;

            if (inboundRule.Using.HasValue && inboundRule.Using.Value == Using.ExactMatch)
            {
                pattern = "^" + pattern + "$";
            }

            inboundRuleMatch = Regex.Match(uriPath, pattern, inboundRule.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None, TimeSpan.FromSeconds(5));

            bool isInboundRuleMatch = matchesThePattern ? inboundRuleMatch.Success : !inboundRuleMatch.Success;

            // Removing logging until a fast way of seeing if it is enabled is implemented
            //Log.Debug(this, "Regex - Pattern: '{0}' Input: '{1}' Success: {2}", pattern, uriPath,
            //        isInboundRuleMatch);

            if (!isInboundRuleMatch && !uriPath.Equals(escapedUriPath, StringComparison.InvariantCultureIgnoreCase))
            {
                inboundRuleMatch = Regex.Match(escapedUriPath, pattern, inboundRule.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None, TimeSpan.FromSeconds(5));

                isInboundRuleMatch = matchesThePattern ? inboundRuleMatch.Success : !inboundRuleMatch.Success;

                // Removing logging until a fast way of seeing if it is enabled is implemented
                //Log.Debug(this, "Regex - Pattern: '{0}' Input: '{1}' Success: {2}", pattern, escapedUriPath,
                //        isInboundRuleMatch);
            }
            return(isInboundRuleMatch);
        }
コード例 #9
0
ファイル: InboundRewriter.cs プロジェクト: prem16/UrlRewrite
        private bool TestRuleMatches(InboundRule inboundRule, Uri originalUri, out Match inboundRuleMatch, bool includeHost)
        {
            var pathToCheck = includeHost ? originalUri.Host + originalUri.PathAndQuery : originalUri.AbsolutePath.Substring(1);

            var escapedPath = HttpUtility.UrlDecode(pathToCheck);
            //var escapedUriPath = includeHost ? escapedPath : (escapedPath ?? string.Empty).Substring(1); // remove starting "/"

            // TODO : I have only implemented "MatchesThePattern" - need to implement the other types
            var matchesThePattern = inboundRule.MatchType.HasValue &&
                                    inboundRule.MatchType.Value == MatchType.MatchesThePattern;

            if (!matchesThePattern)
            {
                throw new NotImplementedException(
                          "Have not yet implemented 'Does Not Match the Pattern' because of possible redirect loops");
            }

            var pattern = inboundRule.Pattern;

            if (inboundRule.Using.HasValue && inboundRule.Using.Value == Using.ExactMatch)
            {
                pattern = "^" + pattern + "$";
            }

            var inboundRuleRegex = new Regex(pattern, inboundRule.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);

            inboundRuleMatch = inboundRuleRegex.Match(pathToCheck);
            bool isInboundRuleMatch = matchesThePattern ? inboundRuleMatch.Success : !inboundRuleMatch.Success;

            Log.Debug(this, "Regex - Pattern: '{0}' Input: '{1}' Success: {2}", pattern, pathToCheck,
                      isInboundRuleMatch);

            if (!isInboundRuleMatch && !pathToCheck.Equals(escapedPath, StringComparison.InvariantCultureIgnoreCase))
            {
                inboundRuleMatch   = inboundRuleRegex.Match(escapedPath);
                isInboundRuleMatch = matchesThePattern ? inboundRuleMatch.Success : !inboundRuleMatch.Success;

                Log.Debug(this, "Regex - Pattern: '{0}' Input: '{1}' Success: {2}", pattern, escapedPath,
                          isInboundRuleMatch);
            }
            return(isInboundRuleMatch);
        }
コード例 #10
0
        private async Task EnterInboundRule(Message message)
        {
            var firewall     = _storageService.Get <FirewallRequest>(StorageKeys.NewFirewall);
            var inboundRules = new List <InboundRule>();
            var invalidRules = new List <string>();
            var rules        = message.Text.Split(";");
            var regExp       = new Regex(RegExpPatterns.NetworkAddress);

            foreach (var rule in rules)
            {
                var resultMatch = regExp.Match(rule);

                if (resultMatch.Success)
                {
                    var inboundRule = new InboundRule
                    {
                        Protocol = resultMatch.Groups[1].Value,
                        Ports    = resultMatch.Groups[2].Value,
                        Sources  = new SourceLocation
                        {
                            Addresses = new List <string>
                            {
                                $"{resultMatch.Groups[3].Value}/{resultMatch.Groups[4].Value}"
                            }
                        }
                    };

                    inboundRules.Add(inboundRule);
                }
                else
                {
                    invalidRules.Add(rule);
                }
            }

            if (inboundRules.Count > 0 && invalidRules.Count == 0)
            {
                var droplets = await _digitalOceanClient.Droplets.GetAll();

                if (droplets is not null and {
                    Count : > 0
                })
コード例 #11
0
        internal InboundRule CreateInboundRuleFromSimpleRedirectItem(SimpleRedirectItem simpleRedirectItem, RedirectFolderItem redirectFolderItem)
        {
            var inboundRulePattern = string.Format("^{0}/?$", simpleRedirectItem.Path.Value);

            var siteNameRestriction = GetSiteNameRestriction(redirectFolderItem);

            var    redirectTo = simpleRedirectItem.Target;
            string actionRewriteUrl;
            Guid?  redirectItem;
            string redirectItemAnchor;

            GetRedirectUrlOrItemId(redirectTo, out actionRewriteUrl, out redirectItem, out redirectItemAnchor);

            Log.Debug(this, simpleRedirectItem.Database, "Creating Inbound Rule From Simple Redirect Item - {0} - id: {1} actionRewriteUrl: {2} redirectItem: {3}", simpleRedirectItem.Name, simpleRedirectItem.ID.Guid, actionRewriteUrl, redirectItem);

            var inboundRule = new InboundRule
            {
                Action = new Redirect
                {
                    AppendQueryString = true,
                    Name              = "Redirect",
                    StatusCode        = RedirectStatusCode.Permanent,
                    RewriteUrl        = actionRewriteUrl,
                    RewriteItemId     = redirectItem,
                    RewriteItemAnchor = redirectItemAnchor,
                    StopProcessingOfSubsequentRules = false,
                    HttpCacheability = HttpCacheability.NoCache
                },
                SiteNameRestriction = siteNameRestriction,
                Enabled             = simpleRedirectItem.BaseEnabledItem.Enabled.Checked,
                IgnoreCase          = true,
                ItemId = simpleRedirectItem.ID.Guid,
                ConditionLogicalGrouping = LogicalGrouping.MatchAll,
                Name      = simpleRedirectItem.Name,
                Pattern   = inboundRulePattern,
                MatchType = MatchType.MatchesThePattern,
                Using     = Using.RegularExpressions,
                SortOrder = simpleRedirectItem.SortOrder
            };

            return(inboundRule);
        }
コード例 #12
0
        private void ProcessItemQueryRedirectAction(InboundRule inboundRule, Uri uri, Match inboundRuleMatch, Match lastConditionMatch, InboundRuleResult ruleResult)
        {
            var redirectAction = inboundRule.Action as ItemQueryRedirect;

            var itemQuery = redirectAction.ItemQuery;

            if (string.IsNullOrEmpty(itemQuery))
            {
                ruleResult.RuleMatched = false;
                return;
            }

            // process token replacements in the item query
            itemQuery = RewriteHelper.ReplaceRuleBackReferences(inboundRuleMatch, itemQuery);
            itemQuery = RewriteHelper.ReplaceConditionBackReferences(lastConditionMatch, itemQuery);

            var rewriteItemId = ExecuteItemQuery(itemQuery);

            if (!rewriteItemId.HasValue)
            {
                ruleResult.RuleMatched = false;
                return;
            }

            string rewriteUrl = GetRewriteUrlFromItemId(rewriteItemId.Value, null, null);


            // process token replacements
            var replacements = new RewriteHelper.Replacements
            {
                RequestHeaders         = RequestHeaders,
                RequestServerVariables = RequestServerVariables
            };

            rewriteUrl = RewriteHelper.ReplaceTokens(replacements, rewriteUrl);
            rewriteUrl = RewriteHelper.ReplaceRuleBackReferences(inboundRuleMatch, rewriteUrl);
            rewriteUrl = RewriteHelper.ReplaceConditionBackReferences(lastConditionMatch, rewriteUrl);

            ruleResult.RewrittenUri   = new Uri(rewriteUrl);
            ruleResult.StopProcessing = redirectAction.StopProcessingOfSubsequentRules;
        }
コード例 #13
0
        private async Task AddInboundRule(Message message)
        {
            await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "\U0001F4C0 Adding inbound rule...", replyMarkup : Keyboards.GetFirewallMenuKeyboard());

            var session      = _sessionRepo.Get(message.From.Id);
            var inboundRules = new List <InboundRule>();
            var userRules    = message.Text.Split(';');

            foreach (var rule in userRules)
            {
                var ruleData = rule.Split(':');
                if (ruleData.Length == 3)
                {
                    var inboundRule = new InboundRule
                    {
                        Protocol = ruleData[0],
                        Ports    = ruleData[1],
                        Sources  = new SourceLocation
                        {
                            Addresses = ruleData[2].Split(',').ToList()
                        }
                    };

                    inboundRules.Add(inboundRule);
                }
                else
                {
                    await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"Invalid rule: {rule.Replace(".", "\\.")}\nPlease, try again");

                    return;
                }
            }

            var digitalOceanApi = _digitalOceanClientFactory.GetInstance(message.From.Id);
            await digitalOceanApi.Firewalls.AddRules((string)session.Data, new FirewallRules
            {
                InboundRules = inboundRules
            });

            await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"Done \U00002705");
        }
コード例 #14
0
        public static InboundRule ToInboundRule(this SimpleRedirectItem simpleRedirectItem, string siteNameRestriction)
        {
            var escapedPath = Regex.Escape(simpleRedirectItem.Path.Value).Replace("/", @"\/");

            var inboundRulePattern = string.Format("^{0}/?$", escapedPath);

            var redirectAction = new Redirect
            {
                AppendQueryString = true,
                Name       = "Redirect",
                StatusCode = RedirectStatusCode.Permanent,
                StopProcessingOfSubsequentRules = false,
                HttpCacheability = HttpCacheability.NoCache
            };

            GetBaseRewriteUrlItem(simpleRedirectItem.BaseRewriteUrlItem, redirectAction);

            Log.Debug(logObject, simpleRedirectItem.Database, "Creating Inbound Rule From Simple Redirect Item - {0} - id: {1} actionRewriteUrl: {2} redirectItem: {3}", simpleRedirectItem.Name, simpleRedirectItem.ID.Guid, redirectAction.RewriteUrl, redirectAction.RewriteItemId);

            if (simpleRedirectItem.BaseRedirectTypeItem != null)
            {
                GetStatusCode(simpleRedirectItem.BaseRedirectTypeItem, redirectAction);
            }

            var inboundRule = new InboundRule
            {
                Action = redirectAction,
                SiteNameRestriction = siteNameRestriction,
                Enabled             = simpleRedirectItem.BaseEnabledItem.Enabled.Checked,
                IgnoreCase          = true,
                ItemId = simpleRedirectItem.ID.Guid,
                ConditionLogicalGrouping = LogicalGrouping.MatchAll,
                Name      = simpleRedirectItem.Name,
                Pattern   = inboundRulePattern,
                MatchType = MatchType.MatchesThePattern,
                Using     = Using.RegularExpressions,
                SortOrder = simpleRedirectItem.SortOrder
            };

            return(inboundRule);
        }
コード例 #15
0
        public void ProcessRequestUrlWithAbort()
        {
            var rewriter       = new InboundRewriter();
            var newInboundRule = new InboundRule()
            {
                Name    = "Abort Rule",
                Pattern = "^abort$",
                Using   = Using.RegularExpressions,
                Action  = new AbortRequest()
                {
                    Name = "Abort Action"
                },
                MatchType = MatchType.MatchesThePattern
            };

            InboundRules.Insert(1, newInboundRule);

            var rewriteResult = rewriter.ProcessRequestUrl(new Uri("http://fictitioussite.com/abort"), InboundRules);

            Assert.IsInstanceOfType(rewriteResult.FinalAction, typeof(AbortRequest));
            Assert.IsTrue(rewriteResult.ProcessedResults.Count == 2);
        }
コード例 #16
0
        public NewRuleBlockingDialog(IServiceProvider serviceProvider, InboundFeature rewriteFeature)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbMode.SelectedIndex     = 1;
            cbInput.SelectedIndex    = 0;
            cbMatch.SelectedIndex    = 0;
            cbResponse.SelectedIndex = 1;

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbInput, "SelectedIndexChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(cbMode, "SelectedIndexChanged"))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                switch (cbInput.SelectedIndex)
                {
                case 0:
                    lblPattern.Text = "Pattern (URL Path):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: IMG*.jpg" : "Example: ^IMG.*\\.jpg$";
                    break;

                case 1:
                    lblPattern.Text = "Pattern (User-agent Header):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: Mozilla/4*" : "Example: ^Mozilla/[1234].*";
                    break;

                case 2:
                    lblPattern.Text = "Pattern (IP Address):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Exmaple: 192.168.1.*" : "Example: 192\\.168\\.1\\.[1-9]";
                    break;

                case 3:
                    lblPattern.Text = "Pattern (Query String):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: *id=*&p=*" : "Example: id=[0-9]+&p=[a-z]+";
                    break;

                case 4:
                    lblPattern.Text = "Pattern (Referer):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: http://*.consoto.com" : "Example: http://(?:www\\.)?contoso\\.com$";
                    break;

                case 5:
                    lblPattern.Text = "Pattern (Host Header):";
                    lblExample.Text = cbMode.SelectedIndex == 1 ? "Example: *.consoto.com" : "Example: (?:www\\.)?contoso\\.com$";
                    break;
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtPattern, "TextChanged")
                .Sample(TimeSpan.FromSeconds(0.5))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtPattern.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var inputType = cbInput.SelectedIndex;
                var pattern   = txtPattern.Text;
                var match     = cbMatch.SelectedIndex;
                var response  = cbResponse.SelectedIndex;
                var mode      = cbMode.SelectedIndex;

                int index = 0;
                string name;
                do
                {
                    index++;
                    name = string.Format("RequestBlockingRule{0}", index);
                }while (rewriteFeature.Items.All(item => item.Name != name));
                var newRule               = new InboundRule(null);
                newRule.Name              = name;
                newRule.Input             = "URL Path";
                newRule.Enabled           = true;
                newRule.PatternSyntax     = mode == 0 ? 0L : 1L;
                newRule.PatternUrl        = mode == 0 ? ".*" : "*";
                newRule.Type              = response == 3 ? 4L : 3L;
                newRule.ActionUrl         = "{C:1}";
                newRule.RedirectType      = 301;
                newRule.StatusCode        = GetStatusCode(response);
                newRule.SubStatusCode     = 0;
                newRule.StatusReason      = GetReason(response);
                newRule.StatusDescription = GetMessage(response);
                newRule.Conditions.Add(
                    new ConditionItem(null)
                {
                    Input      = GetInput(inputType),
                    MatchType  = match == 0 ? 4 : 5,
                    Pattern    = pattern,
                    IgnoreCase = true
                });
                rewriteFeature.AddItem(newRule);
                DialogResult = DialogResult.OK;
            }));
        }
コード例 #17
0
        private InboundRuleResult ProcessRegularExpressionInboundRule(Uri originalUri, InboundRule inboundRule)
        {
            var ruleResult = new InboundRuleResult
            {
                OriginalUri  = originalUri,
                RewrittenUri = originalUri
            };

            Match inboundRuleMatch,
                  lastConditionMatch = null;

            // test rule match
            var isInboundRuleMatch = TestRuleMatches(inboundRule, originalUri, out inboundRuleMatch);
            ConditionMatchResult conditionMatchResult = null;

            // test conditions matches
            if (isInboundRuleMatch && inboundRule.Conditions != null && inboundRule.Conditions.Any())
            {
                var replacements = new RewriteHelper.Replacements
                {
                    RequestHeaders         = RequestHeaders,
                    RequestServerVariables = RequestServerVariables
                };

                conditionMatchResult = RewriteHelper.TestConditionMatches(inboundRule, replacements, out lastConditionMatch);
                isInboundRuleMatch   = conditionMatchResult.Matched;
            }

            // test site name restrictions
            if (isInboundRuleMatch && !string.IsNullOrEmpty(inboundRule.SiteNameRestriction))
            {
                isInboundRuleMatch = TestSiteNameRestriction(inboundRule);
            }

            if (isInboundRuleMatch && inboundRule.Action != null)
            {
                ruleResult.RuleMatched = true;

                if (inboundRule.ResponseHeaders.Any())
                {
                    ruleResult.ResponseHeaders = inboundRule.ResponseHeaders;
                }

                Log.Debug(this, "INBOUND RULE MATCH - requestUri: {0} inboundRule: {1}", originalUri, inboundRule.Name);

                // TODO: Need to implement Rewrite, None

                if (inboundRule.Action is Redirect)
                {
                    ProcessRedirectAction(inboundRule, originalUri, inboundRuleMatch, lastConditionMatch, ruleResult);
                }
                else if (inboundRule.Action is Rewrite)
                {
                    ProcessRewriteAction(inboundRule, originalUri, inboundRuleMatch, lastConditionMatch, ruleResult);
                }
                else if (inboundRule.Action is ItemQueryRedirect)
                {
                    ProcessItemQueryRedirectAction(inboundRule, originalUri, inboundRuleMatch, lastConditionMatch, ruleResult);
                }
                else if (inboundRule.Action is AbortRequest || inboundRule.Action is CustomResponse)
                {
                    ProcessActionProcessing(ruleResult);
                }
                else
                {
                    throw new NotImplementedException("Redirect Action, Custome Response and Abort Reqeust Action are the only supported type of redirects");
                }

                ruleResult.ResultAction         = inboundRule.Action;
                ruleResult.ConditionMatchResult = conditionMatchResult;
            }
            else if (inboundRule.Action == null)
            {
                Log.Warn(this, "Inbound Rule has no Action set - inboundRule: {0} inboundRule ItemId: {1}", inboundRule.Name, inboundRule.ItemId);

                // we are going to skip this because we don't know what to do with it during processing
                ruleResult.RuleMatched = false;
            }

            return(ruleResult);
        }
コード例 #18
0
        public NewRuleWithRewriteMapsDialog(IServiceProvider serviceProvider, InboundFeature feature)
            : base(serviceProvider)
        {
            InitializeComponent();
            var service      = (IConfigurationService)GetService(typeof(IConfigurationService));
            var rulesSection = service.GetSection("system.webServer/rewrite/rewriteMaps");
            ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();

            foreach (ConfigurationElement ruleElement in rulesCollection)
            {
                cbMap.Items.Add(ruleElement["name"]);
            }

            cbAction.SelectedIndex = 0;

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbMap, "SelectedIndexChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = cbMap.SelectedIndex > -1;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var action = cbAction.Text;
                var map    = cbMap.Text;

                int index = 0;
                string name;
                do
                {
                    index++;
                    name = string.Format("{0} rule{1} for {2}", action, index, map);
                }while (feature.Items.All(item => item.Name != name));
                var rule           = new InboundRule(null);
                rule.Name          = name;
                rule.Input         = "URL Path";
                rule.PatternSyntax = 0L;
                rule.PatternUrl    = ".*";
                rule.Type          = action == "Rewrite" ? 1L : 2L;
                rule.ActionUrl     = "{C:1}";
                rule.RedirectType  = 301;
                rule.Conditions.Add(
                    new ConditionItem(null)
                {
                    Input      = string.Format("{{{0}:{{REQUEST_URI}}}}", map),
                    MatchType  = 4,
                    Pattern    = "(.+)",
                    IgnoreCase = true
                });

                feature.AddItem(rule);
                DialogResult = DialogResult.OK;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbAction, "SelectedIndexChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                lblDescription.Text = cbAction.SelectedIndex == 0 ? s_rewriteText : s_redirectText;
            }));
        }
コード例 #19
0
        public async Task ExecuteHandlerAsync(Message message)
        {
            var firewallId = _storageService.Get <string>(StorageKeys.FirewallId);

            if (string.IsNullOrEmpty(firewallId))
            {
                return;
            }

            var inboundRules = new List <InboundRule>();
            var invalidRules = new List <string>();
            var rules        = message.Text.Split(";");
            var regExp       = new Regex(RegExpPatterns.NetworkAddress);

            foreach (var rule in rules)
            {
                var resultMatch = regExp.Match(rule);

                if (resultMatch.Success)
                {
                    var inboundRule = new InboundRule
                    {
                        Protocol = resultMatch.Groups[1].Value,
                        Ports    = resultMatch.Groups[2].Value,
                        Sources  = new SourceLocation
                        {
                            Addresses = new List <string>
                            {
                                $"{resultMatch.Groups[3].Value}/{resultMatch.Groups[4].Value}"
                            }
                        }
                    };

                    inboundRules.Add(inboundRule);
                }
                else
                {
                    invalidRules.Add(rule);
                }
            }

            if (inboundRules.Count > 0)
            {
                await _digitalOceanClient.Firewalls.AddRules(firewallId, new FirewallRules
                {
                    InboundRules = inboundRules
                });

                await _telegramBotClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : FirewallMessage.GetCreatedBoundRulesMessage(inboundRules.Count),
                    parseMode : ParseMode.Markdown);
            }

            if (invalidRules.Count > 0)
            {
                await _telegramBotClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : FirewallMessage.GetInvalidBoundRulesMessage(invalidRules),
                    parseMode : ParseMode.Html);
            }

            _storageService.AddOrUpdate(StorageKeys.BotCurrentState, BotStateType.None);
        }
コード例 #20
0
        public static InboundRule ToInboundRule(this InboundRuleItem inboundRuleItem, string siteNameRestriction)
        {
            if (inboundRuleItem == null)
            {
                return(null);
            }

            var conditionItems = GetBaseConditionItems(inboundRuleItem);
            //var serverVariableItems = GetServerVariableItems(inboundRuleItem);
            //var requestHeaderItems = GetRequestHeaderItems(inboundRuleItem);
            var responseHeaderItems = GetResponseHeaderItems(inboundRuleItem);

            var inboundRule = new InboundRule
            {
                ItemId = inboundRuleItem.ID.Guid,
                Name   = inboundRuleItem.Name
            };

            SetBaseRule(inboundRuleItem.BaseRuleItem, inboundRule);

            if (string.IsNullOrEmpty(inboundRuleItem.BaseRuleItem.BaseMatchItem.MatchPatternItem.Pattern.Value))
            {
                Log.Warn(logObject, inboundRuleItem.Database, "No pattern set on rule with ItemID: {0}", inboundRuleItem.ID);

                return(null);
            }

            if (inboundRuleItem.Action == null)
            {
                Log.Warn(logObject, inboundRuleItem.Database, "No action set on rule with ItemID: {0}", inboundRuleItem.ID);

                return(null);
            }

            var         baseActionItem = inboundRuleItem.Action.TargetItem;
            IBaseAction baseAction     = null;

            if (baseActionItem != null)
            {
                var baseActionItemTemplateId = baseActionItem.TemplateID.ToString();

                if (baseActionItemTemplateId.Equals(RedirectItem.TemplateId, StringComparison.InvariantCultureIgnoreCase))
                {
                    baseAction = new RedirectItem(baseActionItem).ToRedirectAction();
                }
                else if (baseActionItemTemplateId.Equals(RewriteItem.TemplateId,
                                                         StringComparison.InvariantCultureIgnoreCase))
                {
                    baseAction = new RewriteItem(baseActionItem).ToRewriteAction();
                }
                else if (baseActionItemTemplateId.Equals(AbortRequestItem.TemplateId,
                                                         StringComparison.InvariantCultureIgnoreCase))
                {
                    baseAction = new AbortRequestItem(baseActionItem).ToAbortRequestAction();
                }
                else if (baseActionItemTemplateId.Equals(CustomResponseItem.TemplateId,
                                                         StringComparison.InvariantCultureIgnoreCase))
                {
                    baseAction = new CustomResponseItem(baseActionItem).ToCustomResponseAction();
                }
                else if (baseActionItemTemplateId.Equals(ItemQueryRedirectItem.TemplateId))
                {
                    baseAction = new ItemQueryRedirectItem(baseActionItem).ToItemQueryRedirectAction();
                }
            }
            inboundRule.Action = baseAction;

            if (conditionItems != null)
            {
                SetConditions(conditionItems, inboundRule);
            }

            //if (serverVariableItems != null)
            //{
            //    SetServerVariables(serverVariableItems, inboundRule);
            //}

            //if (requestHeaderItems != null)
            //{
            //    SetRequestHeaders(requestHeaderItems, inboundRule);
            //}

            if (responseHeaderItems != null)
            {
                SetResponseHeaders(responseHeaderItems, inboundRule);
            }

            inboundRule.SiteNameRestriction = siteNameRestriction;

            return(inboundRule);
        }