Example #1
0
        private void _ruleFilter_CheckedChanged(object sender, EventArgs e)
        {
            if (_ruleFilter.Checked)
            {
                using (var dialog = new RuleFilterDialog())
                {
                    dialog.Initialize(_model);
                    dialog.Rule = _filteringRule;

                    if (dialog.ShowDialog(Form.ActiveForm) == DialogResult.OK)
                    {
                        _filteringRule    = dialog.Rule;
                        _ruleFilter.Image = Properties.Resources.checkbox_small;
                    }
                    else
                    {
                        _ruleFilter.Checked = false;
                        _ruleFilter.Image   = null;
                    }
                }
            }
            else
            {
                _ruleFilter.Image = null;
            }
        }
        public bool Execute(IIdentity identity)
        {
            var result = false;

            IEnumerable <IPropertiesContainer> children = null;
            SelectionRule rule = null;

            if (identity is IThreatType threatType)
            {
                children = threatType.Mitigations;
                rule     = threatType.GetRule(threatType.Model);
            }
            else if (identity is IWeakness weakness)
            {
                children = weakness.Mitigations;
                rule     = weakness.GetRule(weakness.Model);
            }

            if (children?.Any() ?? false)
            {
                Ask?.Invoke(this, new Context()
                {
                    Containers = children, Rule = rule
                },
                            "Propagate Auto Gen Rule to children", $"Are you sure you want to replace the existing rule to all Mitigations associated to '{identity.Name}' with the rule assigned to the latter?",
                            true, RequestOptions.YesNo);
                result = true;
            }

            return(result);
        }
Example #3
0
 public ProfileSelectionRuleCreatedNotification(
     Profile profile,
     SelectionRule selectionRule)
 {
     Profile       = profile;
     SelectionRule = selectionRule;
 }
        public SelectionRuleViewModel(IMediator mediator, SelectionRule selectionRule)
        {
            _mediator      = mediator;
            _selectionRule = selectionRule;

            DeleteSelectionRuleCommand = new RelayCommand(async() => await DeleteSelectionRule());
        }
Example #5
0
        /// <summary>
        /// builds the XPT node of this
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public bool BuildXPTNode(SelectionRulezContext ctx)
        {
            // $ctx.XPTreeNode = (eXPressionTree.IeXPressionTree) new SelectionRule($ctx.ruleid().GetText(), engine: this.Engine);
            // get the name
            SelectionRule aRule = new SelectionRule(ctx.ruleid().GetText(), engine: this.Engine);

            ctx.XPTreeNode = aRule;

            // add expression
            if (ctx.selection() != null)
            {
                aRule.Selection = new SelectionStatementBlock(engine: this.Engine);
                aRule.Selection.Add(new @Return((SelectionExpression)ctx.selection().XPTreeNode));
            }
            else if (ctx.selectStatementBlock() != null)
            {
                aRule.Selection = (SelectionStatementBlock)ctx.selectStatementBlock().XPTreeNode;
            }
            // add the parameters
            foreach (ParameterDefinition aParameter in ctx.names.Values)
            {
                ISymbol symbol = aRule.AddNewParameter(aParameter.name, datatype: aParameter.datatype);
                // defaultvalue assignment
                if (aParameter.defaultvalue != null)
                {
                    aRule.Selection.Nodes.Insert(0, new eXPressionTree.IfThenElse(
                                                     eXPressionTree.CompareExpression.EQ(symbol, new Literal(null, otDataType.@Null)),
                                                     new eXPressionTree.Assignment(symbol, (IExpression)aParameter.defaultvalue)));
                }
            }
            return(true);
        }
Example #6
0
        /// <summary>
        /// generate theCode for a rule rule
        /// </summary>
        /// <param name="rule"></param>
        /// <returns></returns>
        public bool Generate(SelectionRule rule, out ICodeBit code)
        {
            try
            {
                bool result = true;
                code = null;

                // check if the object to which data engine
                foreach (iDataObjectEngine aDataEngine in _dataobjectEngines.Reverse <iDataObjectEngine> ())
                {
                    foreach (String aName in rule.ResultingObjectnames())
                    {
                        result &= aDataEngine.Objects.HasObjectDefinition(id: aName);
                    }
                    if (result)
                    {
                        return(aDataEngine.Generate((rule as eXPressionTree.IRule), out code));
                    }
                }

                // failure
                if (!result)
                {
                    String theNames = DataType.ToString(rule.ResultingObjectnames());
                    throw new RulezException(RulezException.Types.NoDataEngineAvailable, arguments: new object[] { theNames });
                }

                return(false);
            }
            catch (Exception ex)
            {
                throw new RulezException(RulezException.Types.GenerateFailed, inner: ex);
            }
        }
Example #7
0
        //---------------------------------------------

        #region Private Methods
        private double calculateBinWidth(Array data, SelectionRule rule)
        {
            //TODO: use a more object oriented approach other than enumerating rules

            double width = 1.0;


            switch (rule)
            {
            case SelectionRule.Scotts:
                if (data is int[])
                {
                    width = (3.5 * Statistics.Tools.StandardDeviation((int[])data)) / Math.Pow(data.Length, 1.0 / 3.0);
                }
                else if (data is double[])
                {
                    width = (3.5 * Statistics.Tools.StandardDeviation((double[])data)) / Math.Pow(data.Length, 1.0 / 3.0);
                }
                break;

            case SelectionRule.FreedmanDiaconis:
                throw new NotImplementedException();
                //double width = 2.0 * Quartile.Range / Math.Pow(data.Length, 1.0 / 3.0);
                break;

            case SelectionRule.Wand:
                throw new NotImplementedException();
                break;

            default:
                goto case SelectionRule.Scotts;
            }

            return(width);
        }
Example #8
0
        private static bool ApplyThreatType([NotNull] IIdentity identity,
                                            [NotNull] IThreatType threatType, [NotNull] SelectionRule rule)
        {
            bool result = false;

            if (rule.Evaluate(identity) && identity is IThreatEventsContainer container)
            {
                var threatEvent = container.AddThreatEvent(threatType);
                if (threatEvent == null)
                {
                    threatEvent = container.ThreatEvents.FirstOrDefault(x => x.ThreatTypeId == threatType.Id);
                }
                else
                {
                    result = true;
                }

                if (threatEvent != null)
                {
                    result |= threatEvent.ApplyMitigations();
                }
            }

            return(result);
        }
        public bool Initialize([NotNull] IThreatTypeMitigation threatTypeMitigation)
        {
            bool result = false;

            _model = threatTypeMitigation.Model;
            _threatType.Text = threatTypeMitigation.ThreatType.Name;
            _mitigation.Text = threatTypeMitigation.Mitigation.Name;

            _strengthOverride.SelectedIndex = 0;
            var strengths = _model.Strengths?.ToArray();
            if (strengths?.Any() ?? false)
                _strengthOverride.Items.AddRange(strengths);

            _statusOverride.SelectedIndex = 0;
            _statusOverride.Items.AddRange(EnumExtensions.GetEnumLabels<MitigationStatus>().ToArray());

            _severityOverride.SelectedIndex = 0;
            var severities = _model.Severities?.Where(x => x.Visible).ToArray();
            if (severities?.Any() ?? false)
                _severityOverride.Items.AddRange(severities);

            _threatTypeRule = threatTypeMitigation.ThreatType.GetRule();
            if (_threatTypeRule != null)
            {
                result = true;
                _ruleEditor.Initialize(_model);
            }

            return result;
        }
Example #10
0
        public override string ToString()
        {
            string selectionRule = $"Формула для определения норм отбора: {SelectionRule.ToString()}";
            string settingCL     = SettingCL.ToString();

            string result = $"{selectionRule}\n{settingCL}";

            return(result);
        }
Example #11
0
 /// <summary>
 /// adds a rule rule to the repository by handle
 /// </summary>
 /// <param name="handle"></param>
 /// <param name="rule"></param>
 /// <returns></returns>
 public bool AddSelectionRule(string id, SelectionRule rule)
 {
     Initialize();
     if (this.HasSelectionRule(id))
     {
         _selectionrules.Remove(id);
     }
     _selectionrules.Add(id, rule);
     return(true);
 }
Example #12
0
        /// <summary>
        /// returns a rule rule from the repository or creates a new one and returns this
        /// </summary>
        /// <param name="handle"></param>
        /// <returns></returns>
        public SelectionRule GetSelectionRule(string id = null)
        {
            if (_repository.HasSelectionRule(id))
            {
                return(_repository.GetSelectionRule(id));
            }
            SelectionRule aRule = new SelectionRule(id);

            _repository.AddSelectionRule(aRule.ID, aRule);
            return(aRule);
        }
Example #13
0
        /// <summary>
        /// visit LogicalExpression
        /// </summary>
        /// <param name="expression"></param>
        public void Visit(SelectionRule rule)
        {
            VisitorEventArgs <T> args = new VisitorEventArgs <T>(currentNode: rule, stack: _stack);

            // call the event
            VisitingSelectionRule(this, args);

            // visit subnodes from left to right
            Visit(rule.Result);
            Visit(rule.Selection);

            // call the event
            VisitedSelectionRule(this, args);
        }
Example #14
0
        private bool FilterRule(SelectionRule rule, [Required] string filterRule)
        {
            var result = false;

            if (rule != null)
            {
                var ruleText = rule.ToString();
                if (ruleText.ToLower().Contains(filterRule.ToLower()))
                {
                    result = true;
                }
            }

            return(result);
        }
Example #15
0
        private void CreateGenerationRule([NotNull] ThreatModel model,
                                          [NotNull] ThreatType source, [NotNull] IThreatType target)
        {
            SelectionRuleNode include = AnalyzeGenerationRule(model, target.Model, source.IncludeFilter);
            SelectionRuleNode exclude = AnalyzeGenerationRule(model, target.Model, source.ExcludeFilter);
            SelectionRule     rule    = null;

            var andNode = new AndRuleNode()
            {
                Name = "AND"
            };

            if (include != null)
            {
                andNode.Children.Add(include);
            }

            if (exclude != null)
            {
                andNode.Children.Add(new NotRuleNode()
                {
                    Name  = "NOT",
                    Child = exclude
                });
            }

            if (andNode.Children.Any())
            {
                andNode.Children.Add(new BooleanRuleNode("Out of Scope", Resources.DefaultNamespace, Resources.TmtFlowPropertySchema, false)
                {
                    Scope = AutoThreatGeneration.Engine.Scope.Object
                });

                rule = new SelectionRule()
                {
                    Root = andNode
                };

                var schemaManager = new AutoThreatGenPropertySchemaManager(target.Model);
                var propertyType  = schemaManager.GetPropertyType();
                var property      = target.GetProperty(propertyType) ?? target.AddProperty(propertyType, null);
                if (property is IPropertyJsonSerializableObject jsonSerializableObject)
                {
                    jsonSerializableObject.Value = rule;
                }
            }
        }
Example #16
0
        /// <summary>
        /// run a rule rule and return an ienumerable of IDataObjects
        /// </summary>
        /// <param name="ruleid"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public IEnumerable <iDataObject> RunSelectionRule(string ruleid, params object[] parameters)
        {
            SelectionRule aRule = this.GetSelectionRule(id: ruleid);

            // search the rule
            if (aRule == null)
            {
                throw new RulezException(RulezException.Types.IdNotFound, arguments: new object[] { ruleid, "SelectionRule" });
            }
            // not the required number of arguments
            if (parameters.Length != aRule.Parameters.Count())
            {
                throw new RulezException(RulezException.Types.InvalidNumberOfArguments, arguments: new object[] { "SelectionRule", ruleid, aRule.Parameters.Count(), parameters.Length });
            }
            // get the Codebit
            ICodeBit theCode = this.GetCode(aRule.Handle);

            if (theCode == null)
            {
                throw new RulezException(RulezException.Types.HandleNotDefined, arguments: new object[] { aRule.ID });
            }
            if (theCode.Code == null)
            {
                throw new RulezException(RulezException.Types.InvalidCode, arguments: new object[] { aRule.ID, aRule.Handle });
            }
            // push the arguments
            _context.PushParameters(parameters);
            try
            {
                // run the theCode
                if (theCode.Code(_context) == false)
                {
                    return(null);
                }
                // pop result
                IEnumerable <iDataObject> result = (_context.Pop() as IEnumerable <iDataObject>);
                return(result);
            }
            catch (RulezException ex)
            {
                throw new RulezException(RulezException.Types.RunFailed, inner: ex, message: ex.Message);
            }
            catch (Exception ex)
            {
                throw new RulezException(RulezException.Types.RunFailed, inner: ex);
            }
        }
Example #17
0
        public async Task <CreateProfileSelectionRuleResponse> Handle(CreateProfileSelectionRuleCommand request, CancellationToken cancellationToken)
        {
            var selectionRule = new SelectionRule(request.ProfileId, request.SelectionRulePart, request.SelectionRuleCompareType, request.Value);

            // Persist changes
            var profile = await _unitOfWork.ProfileRepository.GetAsync(request.ProfileId);

            profile.SelectionRules.Add(selectionRule);

            // Notify that everything is complete
            await _mediator.Publish(new ProfileSelectionRuleCreatedNotification(profile, selectionRule), cancellationToken);

            return(new CreateProfileSelectionRuleResponse()
            {
                SelectionRule = selectionRule
            });
        }
Example #18
0
        public async Task UseBrowserProfileAsync(BrowserProfile browserProfile, string requestUrl, bool saveRequestUrl)
        {
            if (saveRequestUrl)
            {
                var requestDomain = SelectionRule.GetPartFromUrl(SelectionRule.SelectionRuleParts.Domain, requestUrl);
                var command       = new CreateProfileSelectionRuleCommand(
                    browserProfile.Profile.Id,
                    SelectionRule.SelectionRuleParts.Domain,
                    SelectionRule.SelectionRuleCompareTypes.Equals,
                    requestDomain);

                await _mediator.Send(command);
            }

            browserProfile.NavigateToUrl(requestUrl);

            await _mediator.Send(new ApplicationShutdownCommand());
        }
Example #19
0
        public static void SetRule(this IPropertiesContainer container, SelectionRule rule, IThreatModel model = null)
        {
            if (model == null && container is IThreatModelChild child)
            {
                model = child.Model;
            }

            if (model != null)
            {
                var schemaManager = new AutoGenRulesPropertySchemaManager(model);
                var propertyType  = schemaManager.GetPropertyType();
                var property      = container.GetProperty(propertyType) ?? container.AddProperty(propertyType, null);
                if (property is IPropertyJsonSerializableObject jsonSerializableObject)
                {
                    jsonSerializableObject.Value = rule;
                }
            }
        }
Example #20
0
        public static void TraverseTree(Node currentNode,
                                        [NotNull] SelectionRule rule, SelectionRuleNode parentRuleNode)
        {
            SelectionRuleNode ruleNode = null;

            if (currentNode != null)
            {
                ruleNode = CreateRuleNode(currentNode);
            }

            if (parentRuleNode == null)
            {
                rule.Root = ruleNode;
            }
            else
            {
                if (parentRuleNode is NaryRuleNode nary)
                {
                    if (ruleNode != null)
                    {
                        nary.Children.Add(ruleNode);
                    }
                }
                else
                {
                    if (parentRuleNode is UnaryRuleNode unary)
                    {
                        unary.Child = ruleNode;
                    }
                }
            }

            if (currentNode?.HasChildNodes ?? false)
            {
                foreach (Node child in currentNode.Nodes)
                {
                    TraverseTree(child, rule, ruleNode);
                }
            }
        }
Example #21
0
        public static SelectionRule GetRule(this IPropertiesContainer container, IThreatModel model = null)
        {
            SelectionRule result = null;

            if (model == null && container is IThreatModelChild child)
            {
                model = child.Model;
            }

            if (model != null)
            {
                var schemaManager = new AutoGenRulesPropertySchemaManager(model);
                var propertyType  = schemaManager.GetPropertyType();
                if (container.HasProperty(propertyType))
                {
                    if (container.GetProperty(propertyType) is IPropertyJsonSerializableObject jsonSerializableObject)
                    {
                        result = jsonSerializableObject.Value as SelectionRule;
                    }
                }
                else
                {
                    var oldSchema       = model.GetSchema(OldSchemaName, Properties.Resources.DefaultNamespace);
                    var oldPropertyType = oldSchema?.GetPropertyType(OldPropertyName);
                    if (oldPropertyType != null)
                    {
                        if (container.GetProperty(oldPropertyType) is IPropertyJsonSerializableObject
                            jsonSerializableObject)
                        {
                            result = jsonSerializableObject.Value as SelectionRule;
                            container.AddProperty(propertyType, jsonSerializableObject.StringValue);
                            container.RemoveProperty(oldPropertyType);
                        }
                    }
                }
            }

            return(result);
        }
Example #22
0
 public ThreatTypeInfo([NotNull] IThreatType threatType, [NotNull] SelectionRule rule, bool topOnly)
 {
     ThreatType = threatType;
     Rule       = rule;
     TopOnly    = topOnly;
 }
Example #23
0
 /// <summary>
 ///   Computes (populates) an Histogram mapping with values from a sample. A selection rule
 ///   can be (optionally) chosen to better organize the histogram.
 /// </summary>
 /// <param name="data">A range of discrete values.</param>
 /// <param name="rule">The selection rule to be used.</param>
 public void Compute(int[] data, SelectionRule rule)
 {
     this.Compute(data, calculateBinWidth(data, rule));
 }
 public SelectionRuleUpdatedEventArgs(SelectionRule selectionRule)
 {
     SelectionRule = selectionRule;
 }
 public SelectionRuleDeletedEventArgs(SelectionRule selectionRule)
 {
     SelectionRule = selectionRule;
 }
 public void RaiseSelectionRuleDeleted(SelectionRule selectionRule)
 {
     SelectionRuleDeleted?.Invoke(this, new SelectionRuleDeletedEventArgs(selectionRule));
 }
Example #27
0
 /// <summary>
 ///   Constructs an histogram computing the given data in double[] form using the selected selection rule.
 /// </summary>
 /// <param name="data"></param>
 public Histogram(double[] data, SelectionRule rule)
 {
     this.Compute(data, rule);
 }