Пример #1
0
        private int ImportFlowTemplates([NotNull] ThreatModel source, [NotNull] IThreatModel target)
        {
            int result     = 0;
            var connectors = source.FlowTypes?
                             .Where(x => !x.IsGeneric)
                             .ToArray();

            if (connectors?.Any() ?? false)
            {
                var schemaManager = new ObjectPropertySchemaManager(target);
                var baseSchema    = new BaseFlowPropertySchemaManager(target).GetSchema();

                foreach (var connector in connectors)
                {
                    var template = target.AddFlowTemplate(connector.Name, connector.Description);
                    if (template != null)
                    {
                        result++;

                        InitializeBaseSchema(template, baseSchema);
                        schemaManager.SetObjectId(template, connector.TypeId);
                        var properties = connector.Properties?.ToArray();

                        AddProperties(target, connector.Name, Scope.DataFlow, baseSchema, template, properties);
                    }
                }
            }

            return(result);
        }
Пример #2
0
        public IThreatModel CreateNewThreatModel([Required] string name)
        {
            _model = new ThreatModel(name);

            ApplyInitializers();

            return(_model);
        }
Пример #3
0
        private void ImportElements([NotNull] ThreatModel source, [NotNull] IThreatModel target,
                                    out int externalInteractors, out int process, out int dataStore)
        {
            externalInteractors = 0;
            process             = 0;
            dataStore           = 0;

            var elements = source.Elements?.ToArray();

            if (elements?.Any() ?? false)
            {
                var schemaManager = new EntitiesPropertySchemaManager(target);
                var schema        = schemaManager.GetSchema();

                foreach (var element in elements)
                {
                    IEntity entity;

                    switch (element.Value.ElementType)
                    {
                    case ElementType.StencilRectangle:
                        entity = target.AddEntity <IExternalInteractor>(element.Value.Name);
                        externalInteractors++;
                        break;

                    case ElementType.StencilEllipse:
                        entity = target.AddEntity <IProcess>(element.Value.Name);
                        process++;
                        break;

                    case ElementType.StencilParallelLines:
                        entity = target.AddEntity <IDataStore>(element.Value.Name);
                        dataStore++;
                        break;

                    default:
                        entity = null;
                        break;
                    }

                    if (entity != null)
                    {
                        schemaManager.SetMsTmtEntityId(entity, element.Key.ToString());
                        var properties = element.Value.Properties?.ToArray();
                        AddProperties(schema, entity, properties);

                        IDiagram diagram = target.Diagrams?.FirstOrDefault(x =>
                                                                           string.CompareOrdinal(x.Name, element.Value.Page) == 0);
                        if (diagram == null)
                        {
                            diagram = target.AddDiagram(element.Value.Page);
                        }
                        diagram.AddEntityShape(entity.Id, new PointF(element.Value.Position.X * 2f, element.Value.Position.Y * 2f));
                    }
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Import a TMT file inside a Threat Model.
        /// </summary>
        /// <param name="threatModel">Destination Threat Model.</param>
        /// <param name="fileName">Name of the TMT file to be imported.</param>
        /// <param name="unassignedThreatHandler">Function to be manage custom Threats, that have not been assigned to any flow.</param>
        /// <param name="externalInteractors">[out] Counter of the External Interactors.</param>
        /// <param name="process">[out] Counter of the Processes.</param>
        /// <param name="dataStore">[out] Counter of the Data Stores.</param>
        /// <param name="flows">[out] Counter of the Flows.</param>
        /// <param name="threatTypes">[out] Counter of the Threat Types.</param>
        /// <param name="customThreatTypes">[out] Counter of the custom Threat Types, managed through the Unassigned Threat Handler.</param>
        /// <param name="threats">[out] Counter of the generated Threat Events.</param>
        /// <param name="missingThreats">[out] Counter of the Threat Events that has not been possible to generate.</param>
        public void Import([NotNull] IThreatModel threatModel, [Required] string fileName,
                           Func <IThreatModel, Threat, IThreatType, IPropertySchema, bool> unassignedThreatHandler,
                           out int externalInteractors, out int process, out int dataStore, out int flows,
                           out int threatTypes, out int customThreatTypes, out int threats, out int missingThreats)
        {
            var model = new ThreatModel(fileName);

            ImportModelInfo(model, threatModel);
            ImportElements(model, threatModel, out externalInteractors, out process, out dataStore);
            flows = ImportDataFlows(model, threatModel);
            ImportThreats(model, threatModel, unassignedThreatHandler, out threatTypes, out customThreatTypes, out threats, out missingThreats);
        }
Пример #5
0
        public PagingCollectionView LoadData()
        {
            PagingCollectionView cview;
            List <ThreatModel>   modelList = new List <ThreatModel>();

            if (File.Exists(PATH))
            {
                using (var workbook = new XLWorkbook(PATH))
                {
                    try
                    {
                        // Берем в ней первый лист
                        for (int i = 1; i <= workbook.Worksheets.Count; i++)
                        {
                            var worksheet  = workbook.Worksheets.Worksheet(i);
                            int sheetCount = worksheet.RowsUsed().Count();
                            // Перебираем диапазон нужных строк
                            for (int row = 3; row <= sheetCount; ++row)
                            {
                                DateTimeFormatInfo ruDt = new CultureInfo("ru-RU", false).DateTimeFormat;
                                // По каждой строке формируем объект
                                ThreatModel threat = new ThreatModel
                                {
                                    Id          = worksheet.Cell(row, 1).GetValue <int>(),
                                    Name        = worksheet.Cell(row, 2).GetValue <string>(),
                                    Description = worksheet.Cell(row, 3).GetValue <string>(),
                                    Source      = worksheet.Cell(row, 4).GetValue <string>(),
                                    Object      = worksheet.Cell(row, 5).GetValue <string>(),

                                    Conf   = (worksheet.Cell(row, 6).GetValue <int>()).ToString(),
                                    Sust   = (worksheet.Cell(row, 7).GetValue <int>()).ToString(),
                                    Access = (worksheet.Cell(row, 8).GetValue <int>()).ToString(),

                                    InDate   = Convert.ToDateTime(worksheet.Cell(row, 9).GetValue <string>(), ruDt),
                                    EditDate = Convert.ToDateTime(worksheet.Cell(row, 9).GetValue <string>(), ruDt),
                                };
                                modelList.Add(threat);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }
            else
            {
                return(null);
            }
            cview = new PagingCollectionView(modelList, 15);
            return(cview);
        }
Пример #6
0
        private void ImportBaseElementTemplates([NotNull] ThreatModel source, [NotNull] IThreatModel target)
        {
            var elements = source.ElementTypes?
                           .Where(x => x.IsGeneric)
                           .ToArray();

            if (elements?.Any() ?? false)
            {
                IPropertySchema schema       = null;
                var             baseEISchema = new BaseExternalInteractorPropertySchemaManager(target).GetSchema();
                var             basePSchema  = new BaseProcessPropertySchemaManager(target).GetSchema();
                var             baseDSSchema = new BaseDataStorePropertySchemaManager(target).GetSchema();
                var             baseTBSchema = new BaseTrustBoundaryPropertySchemaManager(target).GetSchema();

                foreach (var element in elements)
                {
                    switch (element.ElementType)
                    {
                    case ElementType.StencilRectangle:
                        schema = baseEISchema;
                        break;

                    case ElementType.StencilEllipse:
                        schema = basePSchema;
                        break;

                    case ElementType.StencilParallelLines:
                        schema = baseDSSchema;
                        break;

                    case ElementType.BorderBoundary:
                    case ElementType.LineBoundary:
                        schema = baseTBSchema;
                        break;
                    }

                    if (schema != null)
                    {
                        var properties = element.Properties?.ToArray();

                        var outOfScope = schema.GetPropertyType("Out of Scope") ??
                                         schema.AddPropertyType("Out of Scope", PropertyValueType.Boolean);
                        var reason = schema.GetPropertyType("Reason For Out Of Scope") ??
                                     schema.AddPropertyType("Reason For Out Of Scope", PropertyValueType.String);

                        AddProperties(schema, null, properties);
                    }
                }
            }
        }
Пример #7
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;
                }
            }
        }
        public IThreatModel CreateNewThreatModel([Required] string name)
        {
            _model = new ThreatModel(name);

            try
            {
                _model.SuspendDirty();
                ApplyInitializers();
                _model.RegisterEvents();
            }
            finally
            {
                _model.ResumeDirty();
            }

            return(_model);
        }
Пример #9
0
        /// <summary>
        /// Import a TMT file inside a Threat Model.
        /// </summary>
        /// <param name="threatModel">Destination Threat Model.</param>
        /// <param name="fileName">Name of the TMT file to be imported.</param>
        /// <param name="dpiFactor">Factor for the Dpi representation. 1 represents the standard 96 dpi, 2 doubles it.</param>
        /// <param name="unassignedThreatHandler">Function to be manage custom Threats, that have not been assigned to any flow.
        /// <para>If null, the custom Threats will be associated to the Threat Model itself.</para></param>
        /// <param name="diagrams">[out] Counter of the Diagrams.</param>
        /// <param name="externalInteractors">[out] Counter of the External Interactors.</param>
        /// <param name="processes">[out] Counter of the Processes.</param>
        /// <param name="dataStores">[out] Counter of the Data Stores.</param>
        /// <param name="flows">[out] Counter of the Flows.</param>
        /// <param name="trustBoundaries">[out] Counter of the Trust Boundaries.</param>
        /// <param name="itemTypes">[out] Counter of the Item Types.</param>
        /// <param name="threatTypes">[out] Counter of the Threat Types.</param>
        /// <param name="customThreatTypes">[out] Counter of the custom Threat Types, managed through the Unassigned Threat Handler.</param>
        /// <param name="threats">[out] Counter of the generated Threat Events.</param>
        /// <param name="missingThreats">[out] Counter of the Threat Events that has not been possible to generate.</param>
        public void Import([NotNull] IThreatModel threatModel, [Required] string fileName, float dpiFactor,
                           Func <IThreatModel, Threat, IThreatType, IPropertySchema, bool> unassignedThreatHandler,
                           out int diagrams, out int externalInteractors, out int processes, out int dataStores, out int flows,
                           out int trustBoundaries, out int itemTypes, out int threatTypes, out int customThreatTypes, out int threats,
                           out int missingThreats)
        {
            var model = new ThreatModel(fileName);

            ImportModelInfo(model, threatModel);
            ImportBaseElementTemplates(model, threatModel);
            ImportBaseFlowTemplates(model, threatModel);
            itemTypes  = ImportEntityTemplates(model, threatModel);
            itemTypes += ImportFlowTemplates(model, threatModel);
            ImportElements(model, threatModel, dpiFactor, out diagrams,
                           out externalInteractors, out processes, out dataStores, out trustBoundaries);
            flows = ImportDataFlows(model, threatModel);
            ImportThreats(model, threatModel, unassignedThreatHandler, out threatTypes, out customThreatTypes, out threats, out missingThreats);
        }
Пример #10
0
        private int ImportDataFlows([NotNull] ThreatModel source, [NotNull] IThreatModel target)
        {
            int result = 0;

            var flows = source.Flows?.ToArray();

            if (flows?.Any() ?? false)
            {
                var schemaManager = new ObjectPropertySchemaManager(target);
                var baseSchema    = new BaseFlowPropertySchemaManager(target).GetSchema();

                foreach (var flow in flows)
                {
                    var sourceEntity = GetEntity(flow.SourceGuid.ToString(), target, schemaManager);
                    var targetEntity = GetEntity(flow.TargetGuid.ToString(), target, schemaManager);
                    if (sourceEntity != null && targetEntity != null)
                    {
                        var flowTemplate = target.FlowTemplates?.FirstOrDefault(x =>
                                                                                string.CompareOrdinal(schemaManager.GetObjectId(x), flow.TypeId) == 0);
                        var secondarySchema = flowTemplate != null?
                                              target.GetSchema(flowTemplate.Name, Resources.DefaultNamespace) : null;

                        var dataFlow = flowTemplate != null?flowTemplate.CreateFlow(flow.Name, sourceEntity.Id, targetEntity.Id) :
                                           target.AddDataFlow(flow.Name, sourceEntity.Id, targetEntity.Id);

                        if (dataFlow != null)
                        {
                            schemaManager.SetObjectId(dataFlow, flow.TypeId);
                            schemaManager.SetInstanceId(dataFlow, flow.FlowId.ToString());

                            var properties = flow.Properties?.ToArray();
                            AddProperties(target, baseSchema, secondarySchema, dataFlow, properties);
                        }

                        IDiagram diagram = target.Diagrams?.FirstOrDefault(x =>
                                                                           string.CompareOrdinal(x.Name, flow.PageName) == 0);
                        diagram?.AddLink(dataFlow);
                        result++;
                    }
                }
            }

            return(result);
        }
Пример #11
0
        private void ImportModelInfo([NotNull] ThreatModel source, [NotNull] IThreatModel target)
        {
            target.Owner       = source.Owner;
            target.Name        = source.ThreatModelName;
            target.Description = source.HighLevelSystemDescription;
            var assumptions = source.Assumptions?.Trim(' ', '\r', '\n').Split('\n');

            if (assumptions?.Any() ?? false)
            {
                foreach (var assumption in assumptions)
                {
                    if (!string.IsNullOrWhiteSpace(assumption.Trim('\r')))
                    {
                        target.AddAssumption(assumption.Trim(' ', '\r'));
                    }
                }
            }
            var dependencies = source.ExternalDependencies?.Trim(' ', '\r', '\n').Split('\n');

            if (dependencies?.Any() ?? false)
            {
                foreach (var dependency in dependencies)
                {
                    if (!string.IsNullOrWhiteSpace(dependency.Trim('\r')))
                    {
                        target.AddDependency(dependency.Trim(' ', '\r'));
                    }
                }
            }
            var contributors = source.Contributors?.Trim(' ', '\r', '\n').Split(',', ';');

            if (contributors?.Any() ?? false)
            {
                foreach (var contributor in contributors)
                {
                    if (!string.IsNullOrWhiteSpace(contributor.Trim('\r')))
                    {
                        target.AddContributor(contributor.Trim(' ', '\r'));
                    }
                }
            }
        }
Пример #12
0
        private SelectionRuleNode AnalyzeGenerationRule(ThreatModel source, IThreatModel target, string ruleText)
        {
            SelectionRuleNode result = null;

            if (!string.IsNullOrWhiteSpace(ruleText))
            {
                ICharStream  stream = CharStreams.fromstring(ruleText);
                ITokenSource lexer  = new TmtLexer(stream, TextWriter.Null, TextWriter.Null);
                ITokenStream tokens = new CommonTokenStream(lexer);
                TmtParser    parser = new TmtParser(tokens)
                {
                    BuildParseTree = true
                };
                IParseTree  tree    = parser.parse();
                RuleVisitor visitor = new RuleVisitor(source, target);
                visitor.Visit(tree);
                result = visitor.Rule;
            }

            return(result);
        }
Пример #13
0
        private void ImportBaseFlowTemplates([NotNull] ThreatModel source, [NotNull] IThreatModel target)
        {
            var connectors = source.FlowTypes?
                             .Where(x => x.IsGeneric)
                             .ToArray();

            if (connectors?.Any() ?? false)
            {
                var schema = new BaseFlowPropertySchemaManager(target).GetSchema();

                if (!(schema.PropertyTypes?.Any(x =>
                                                string.CompareOrdinal("Out of Scope", x.Name) == 0) ?? false))
                {
                    var outOfScope = schema.AddPropertyType("Out of Scope",
                                                            PropertyValueType.Boolean);
                    if (outOfScope != null)
                    {
                        outOfScope.Priority = -2;
                    }
                }

                if (!(schema.PropertyTypes?.Any(x =>
                                                string.CompareOrdinal("Reason For Out Of Scope", x.Name) == 0) ?? false))
                {
                    var reasonOutOfScope =
                        schema.AddPropertyType("Reason For Out Of Scope",
                                               PropertyValueType.String);
                    if (reasonOutOfScope != null)
                    {
                        reasonOutOfScope.Priority = -1;
                    }
                }

                foreach (var connector in connectors)
                {
                    AddProperties(schema, null, connector.Properties?.ToArray());
                }
            }
        }
Пример #14
0
        private int ImportDataFlows([NotNull] ThreatModel source, [NotNull] IThreatModel target)
        {
            int result = 0;

            var flows = source.Flows;

            if (flows?.Any() ?? false)
            {
                var entitiesSchemaManager  = new EntitiesPropertySchemaManager(target);
                var dataFlowsSchemaManager = new DataFlowsPropertySchemaManager(target);
                var schema = dataFlowsSchemaManager.GetSchema();

                foreach (var flow in flows)
                {
                    var sourceEntity = GetEntity(flow.SourceGuid.ToString(), target, entitiesSchemaManager);
                    var targetEntity = GetEntity(flow.TargetGuid.ToString(), target, entitiesSchemaManager);
                    if (sourceEntity != null && targetEntity != null)
                    {
                        var dataFlow = target.AddDataFlow(flow.Name, sourceEntity.Id, targetEntity.Id);
                        if (dataFlow != null)
                        {
                            dataFlowsSchemaManager.SetMsTmtDataFlowId(dataFlow, flow.FlowId.ToString());

                            var properties = flow.Properties?.ToArray();
                            AddProperties(schema, dataFlow, properties);
                        }

                        IDiagram diagram = target.Diagrams?.FirstOrDefault(x =>
                                                                           string.CompareOrdinal(x.Name, flow.PageName) == 0);
                        diagram?.AddLink(dataFlow);
                        result++;
                    }
                }
            }

            return(result);
        }
Пример #15
0
 public RuleVisitor([NotNull] ThreatModel source, [NotNull] IThreatModel target)
 {
     _source = source;
     _target = target;
 }
Пример #16
0
        private void ImportThreats([NotNull] ThreatModel source, [NotNull] IThreatModel target,
                                   Func <IThreatModel, Threat, IThreatType, IPropertySchema, bool> unassignedThreatHandler,
                                   out int threatTypes, out int customThreatTypes, out int threats, out int missingThreats)
        {
            threatTypes       = 0;
            customThreatTypes = 0;
            threats           = 0;
            missingThreats    = 0;

            var threatsPerType = source.ThreatsPerType;

            if (threatsPerType?.Any() ?? false)
            {
                var schema = new ThreatsPropertySchemaManager(target).GetSchema();
                InitializeThreatsPropertySchema(schema, source.Properties);
                var schemaManager = new ObjectPropertySchemaManager(target);

                var defaultSeverity = target.GetMappedSeverity(0);

                foreach (var threatPerType in threatsPerType)
                {
                    var         tt         = source.GetThreatType(threatPerType.Key);
                    IThreatType threatType = null;
                    if (!string.IsNullOrWhiteSpace(tt.Name))
                    {
                        ISeverity severity;
                        if (Enum.TryParse <DefaultSeverity>(tt.Priority, out var severityId))
                        {
                            severity = target.GetMappedSeverity((int)severityId);
                        }
                        else
                        {
                            severity = target.GetMappedSeverity((int)DefaultSeverity.High);
                        }

                        threatType = target.AddThreatType(tt.Name, severity);
                        if (threatType != null)
                        {
                            threatType.Description = tt.Description;
                            var threatTypeProperties = tt.Properties?.ToArray();
                            if (threatTypeProperties?.Any() ?? false)
                            {
                                foreach (var property in threatTypeProperties)
                                {
                                    switch (property.Name)
                                    {
                                    case "Title":
                                        break;

                                    case "UserThreatDescription":
                                        break;

                                    case "Priority":
                                        break;

                                    default:
                                        var propertyType = schema.GetPropertyType(property.Label);
                                        if (propertyType != null)
                                        {
                                            threatType.AddProperty(propertyType, property.Values.FirstOrDefault());
                                        }

                                        break;
                                    }
                                }
                            }

                            threatTypes++;
                        }
                        else
                        {
                            threatType = target.ThreatTypes?
                                         .FirstOrDefault(x => string.CompareOrdinal(x.Name, tt.Name) == 0);
                        }
                    }
                    else
                    {
                        var internalThreats = threatPerType.Value;
                        if (internalThreats.Any())
                        {
                            foreach (var internalThreat in internalThreats)
                            {
                                threatType = target.AddThreatType(internalThreat.ToString(), defaultSeverity);
                                if (threatType != null)
                                {
                                    threatType.Description = internalThreat.GetValueFromLabel("Description");
                                    customThreatTypes++;
                                }
                                else
                                {
                                    threatType = target.ThreatTypes?.FirstOrDefault(x =>
                                                                                    string.CompareOrdinal(x.Name, internalThreat.ToString()) == 0);
                                }

                                break;
                            }
                        }
                    }

                    if (threatType != null)
                    {
                        CreateGenerationRule(source, tt, threatType);

                        foreach (var threat in threatPerType.Value)
                        {
                            var flow = GetDataFlow(threat.FlowGuid.ToString(), target, schemaManager);
                            if (flow != null)
                            {
                                var threatEvent = flow.AddThreatEvent(threatType);

                                if (threatEvent != null)
                                {
                                    AddProperties(threatEvent, threat, schema);
                                    threats++;
                                }
                                else
                                {
                                    missingThreats++;
                                }
                            }
                            else
                            {
                                if (unassignedThreatHandler != null)
                                {
                                    if (unassignedThreatHandler(target, threat, threatType, schema))
                                    {
                                        threats++;
                                    }
                                    else
                                    {
                                        missingThreats++;
                                    }
                                }
                                else
                                {
                                    var threatEvent = target.AddThreatEvent(threatType);

                                    if (threatEvent != null)
                                    {
                                        AddProperties(threatEvent, threat, schema);
                                        threats++;
                                    }
                                    else
                                    {
                                        missingThreats++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #17
0
        private int ImportEntityTemplates([NotNull] ThreatModel source, [NotNull] IThreatModel target)
        {
            int result   = 0;
            var elements = source.ElementTypes?
                           .Where(x => !x.IsGeneric)
                           .ToArray();

            if (elements?.Any() ?? false)
            {
                var schemaManager = new ObjectPropertySchemaManager(target);

                IEntityTemplate        entityTemplate;
                ITrustBoundaryTemplate trustBoundaryTemplate;
                Interfaces.Scope       scope;
                IPropertySchema        baseSchema;
                var baseEISchema = new BaseExternalInteractorPropertySchemaManager(target).GetSchema();
                var basePSchema  = new BaseProcessPropertySchemaManager(target).GetSchema();
                var baseDSSchema = new BaseDataStorePropertySchemaManager(target).GetSchema();
                var baseTBSchema = new BaseTrustBoundaryPropertySchemaManager(target).GetSchema();

                foreach (var element in elements)
                {
                    switch (element.ElementType)
                    {
                    case ElementType.StencilRectangle:
                        entityTemplate = target.AddEntityTemplate(element.Name, element.Description,
                                                                  element.Image, element.Image, element.Image,
                                                                  EntityType.ExternalInteractor);
                        trustBoundaryTemplate = null;
                        scope      = Scope.ExternalInteractor;
                        baseSchema = baseEISchema;
                        result++;
                        break;

                    case ElementType.StencilEllipse:
                        entityTemplate = target.AddEntityTemplate(element.Name, element.Description,
                                                                  element.Image, element.Image, element.Image,
                                                                  EntityType.Process);
                        trustBoundaryTemplate = null;
                        scope      = Scope.Process;
                        baseSchema = basePSchema;
                        result++;
                        break;

                    case ElementType.StencilParallelLines:
                        entityTemplate = target.AddEntityTemplate(element.Name, element.Description,
                                                                  element.Image, element.Image, element.Image,
                                                                  EntityType.DataStore);
                        trustBoundaryTemplate = null;
                        scope      = Scope.DataStore;
                        baseSchema = baseDSSchema;
                        result++;
                        break;

                    case ElementType.LineBoundary:
                    case ElementType.BorderBoundary:
                        entityTemplate        = null;
                        trustBoundaryTemplate = target.AddTrustBoundaryTemplate(element.Name, element.Description);
                        scope      = Scope.TrustBoundary;
                        baseSchema = baseTBSchema;
                        result++;
                        break;

                    default:
                        entityTemplate        = null;
                        trustBoundaryTemplate = null;
                        scope      = Scope.Undefined;
                        baseSchema = null;
                        break;
                    }

                    if (entityTemplate != null)
                    {
                        InitializeBaseSchema(entityTemplate, baseSchema);
                        schemaManager.SetObjectId(entityTemplate, element.TypeId);
                        var properties = element.Properties?.ToArray();

                        AddProperties(target, element.Name, scope, baseSchema, entityTemplate, properties);
                    }
                    else if (trustBoundaryTemplate != null)
                    {
                        InitializeBaseSchema(trustBoundaryTemplate, baseSchema);
                        schemaManager.SetObjectId(trustBoundaryTemplate, element.TypeId);
                        var properties = element.Properties?.ToArray();

                        AddProperties(target, element.Name, scope, baseSchema, trustBoundaryTemplate, properties);
                    }
                }
            }

            return(result);
        }
Пример #18
0
        private void ImportElements([NotNull] ThreatModel source, [NotNull] IThreatModel target, float dpiFactor,
                                    out int diagrams, out int externalInteractors, out int processes, out int dataStores, out int trustBoundaries)
        {
            diagrams            = 0;
            externalInteractors = 0;
            processes           = 0;
            dataStores          = 0;
            trustBoundaries     = 0;

            var elements = source.Elements?
                           .OrderBy(x => (int)x.Value.ElementType)
                           .ToArray();

            if (elements?.Any() ?? false)
            {
                var schemaManager = new ObjectPropertySchemaManager(target);

                IEntity                entity;
                ITrustBoundary         boundary;
                IEntityTemplate        entityTemplate;
                ITrustBoundaryTemplate trustBoundaryTemplate;
                IPropertySchema        schema;
                IPropertySchema        secondarySchema;
                var baseEISchema = new BaseExternalInteractorPropertySchemaManager(target).GetSchema();
                var basePSchema  = new BaseProcessPropertySchemaManager(target).GetSchema();
                var baseDSSchema = new BaseDataStorePropertySchemaManager(target).GetSchema();
                var baseTBSchema = new BaseTrustBoundaryPropertySchemaManager(target).GetSchema();

                foreach (var element in elements)
                {
                    switch (element.Value.ElementType)
                    {
                    case ElementType.StencilRectangle:
                        entityTemplate = target.EntityTemplates?.FirstOrDefault(x =>
                                                                                string.CompareOrdinal(schemaManager.GetObjectId(x), element.Value.TypeId) == 0);
                        entity = entityTemplate != null?entityTemplate.CreateEntity(element.Value.Name) :
                                     target.AddEntity <IExternalInteractor>(element.Value.Name);

                        boundary        = null;
                        schema          = baseEISchema;
                        secondarySchema = entityTemplate != null?
                                          target.GetSchema(entityTemplate.Name, Resources.DefaultNamespace) : null;

                        externalInteractors++;
                        break;

                    case ElementType.StencilEllipse:
                        entityTemplate = target.EntityTemplates?.FirstOrDefault(x =>
                                                                                string.CompareOrdinal(schemaManager.GetObjectId(x), element.Value.TypeId) == 0);
                        entity = entityTemplate != null?entityTemplate.CreateEntity(element.Value.Name) :
                                     target.AddEntity <IProcess>(element.Value.Name);

                        boundary        = null;
                        schema          = basePSchema;
                        secondarySchema = entityTemplate != null?
                                          target.GetSchema(entityTemplate.Name, Resources.DefaultNamespace) : null;

                        processes++;
                        break;

                    case ElementType.StencilParallelLines:
                        entityTemplate = target.EntityTemplates?.FirstOrDefault(x =>
                                                                                string.CompareOrdinal(schemaManager.GetObjectId(x), element.Value.TypeId) == 0);
                        entity = entityTemplate != null?entityTemplate.CreateEntity(element.Value.Name) :
                                     target.AddEntity <IDataStore>(element.Value.Name);

                        boundary        = null;
                        schema          = baseDSSchema;
                        secondarySchema = entityTemplate != null?
                                          target.GetSchema(entityTemplate.Name, Resources.DefaultNamespace) : null;

                        dataStores++;
                        break;

                    case ElementType.BorderBoundary:
                    case ElementType.LineBoundary:
                        trustBoundaryTemplate = target.TrustBoundaryTemplates?.FirstOrDefault(x =>
                                                                                              string.CompareOrdinal(schemaManager.GetObjectId(x), element.Value.TypeId) == 0);
                        entity   = null;
                        boundary = trustBoundaryTemplate != null?trustBoundaryTemplate.CreateTrustBoundary(element.Value.Name) :
                                       target.AddGroup <ITrustBoundary>(element.Value.Name);

                        schema          = baseTBSchema;
                        secondarySchema = trustBoundaryTemplate != null?
                                          target.GetSchema(trustBoundaryTemplate.Name, Resources.DefaultNamespace) : null;

                        trustBoundaries++;
                        break;

                    default:
                        entity          = null;
                        boundary        = null;
                        schema          = null;
                        secondarySchema = null;
                        break;
                    }

                    if (entity != null)
                    {
                        schemaManager.SetObjectId(entity, element.Value.TypeId);
                        schemaManager.SetInstanceId(entity, element.Key.ToString());
                        var properties = element.Value.Properties?.ToArray();
                        AddProperties(target, schema, secondarySchema, entity, properties);

                        var diagram = target.Diagrams?.FirstOrDefault(x =>
                                                                      string.CompareOrdinal(x.Name, element.Value.Page) == 0);
                        if (diagram == null)
                        {
                            diagram = target.AddDiagram(element.Value.Page);
                            diagrams++;
                        }

                        diagram.AddEntityShape(entity.Id,
                                               new PointF((element.Value.Position.X + element.Value.Size.Width / 2f) * dpiFactor, (element.Value.Position.Y + element.Value.Size.Height / 2f) * dpiFactor));
                    }
                    else if (boundary != null)
                    {
                        schemaManager.SetObjectId(boundary, element.Value.TypeId);
                        schemaManager.SetInstanceId(boundary, element.Key.ToString());
                        var properties = element.Value.Properties?.ToArray();
                        AddProperties(target, schema, secondarySchema, entity, properties);

                        if (element.Value.ElementType == ElementType.BorderBoundary)
                        {
                            var diagram = target.Diagrams?.FirstOrDefault(x =>
                                                                          string.CompareOrdinal(x.Name, element.Value.Page) == 0);
                            if (diagram == null)
                            {
                                diagram = target.AddDiagram(element.Value.Page);
                                diagrams++;
                            }

                            diagram.AddGroupShape(boundary.Id,
                                                  new PointF((element.Value.Position.X + element.Value.Size.Width / 2f) * dpiFactor, (element.Value.Position.Y + element.Value.Size.Height / 2f) * dpiFactor),
                                                  new SizeF(element.Value.Size.Width * dpiFactor, element.Value.Size.Height * dpiFactor));
                        }
                    }
                }
            }
        }