Beispiel #1
0
        private void cbDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            // create user interface of selected device
            CnlPrototypes = null;

            if (cbDevice.SelectedItem is Device device)
            {
                if (deviceItems.TryGetValue(device.DeviceNum, out DeviceItem deviceItem) &&
                    deviceItem.Instance != null)
                {
                    try
                    {
                        if (deviceItem.DeviceView == null)
                        {
                            if (ExtensionUtils.GetDeviceView(adminContext, deviceItem.Instance.CommApp,
                                                             deviceItem.DeviceConfig, out DeviceView deviceView, out string errMsg))
                            {
                                deviceItem.DeviceView = deviceView;
                            }
                            else
                            {
                                throw new ScadaException(errMsg);
                            }
                        }

                        deviceItem.CnlPrototypes = deviceItem.DeviceView.GetCnlPrototypes();
                        int cnlCnt = deviceItem.CnlPrototypes?.Count ?? 0;

                        txtInfo.Text = string.Format(ExtensionPhrases.DeviceInfo,
                                                     deviceItem.DeviceConfig.Driver, deviceItem.Instance.Name, cnlCnt);
                        pbStatus.Image = cnlCnt > 0 ? Properties.Resources.success : Properties.Resources.warning;
                    }
Beispiel #2
0
        /// <summary>
        /// Creates a placeholder from a specified full qualifier.
        /// </summary>
        /// <param name="fullQualifier">Full qualifier.
        /// <para>It is in the format of [ThreatsManagerPlatform:ModelTest:parameter1#parameter2], where
        /// <list type="bullet">
        /// <item><description>ThreatsManagerPlatform is fixed.</description></item>
        /// <item><description>ModelTest represents the Qualifier which identifies the specific Placeholder.</description></item>
        /// <item><description>parameter1#parameter2 represent the parameters for the Placeholder, separated by #.</description></item>
        /// </list>
        /// </para></param>
        /// <param name="priority">[out] Integer representing the priority of the placeholder.</param>
        /// <returns>Generated Placeholder. It may be null, if no suitable placeholder has been found.</returns>
        public static IPlaceholder Create([Required] string fullQualifier, out int priority)
        {
            IPlaceholder result = null;

            priority = 100;

            var factories = ExtensionUtils.GetExtensions <IPlaceholderFactory>()?.ToArray();

            if (factories?.Any() ?? false)
            {
                var regex = new Regex(
                    @"\[ThreatsManagerPlatform:(?<qualifier>[\w]+):?(?<params>[\S ]*)?\]");
                var match = regex.Match(fullQualifier);
                if (match.Success)
                {
                    var factory = factories.FirstOrDefault(x =>
                                                           string.CompareOrdinal(x.Qualifier, match.Groups["qualifier"]?.Value) == 0);

                    if (factory != null)
                    {
                        priority = factory.GetExtensionPriority();
                        result   = factory.Create(match.Groups["params"]?.Value);
                    }
                }
            }

            return(result);
        }
Beispiel #3
0
        public bool Execute(IIdentity identity)
        {
            bool result = false;

            if (identity is IEntity entity && entity.Model is IThreatModel model)
            {
                var schemaManager = new AssociatedDiagramPropertySchemaManager(model);
                var propertyType  = schemaManager.GetAssociatedDiagramIdPropertyType();
                if (propertyType != null)
                {
                    var property = entity.GetProperty(propertyType);
                    if (property is IPropertyIdentityReference identityReference &&
                        identityReference.Value is IDiagram diagram)
                    {
                        result = true;
                        var factory = ExtensionUtils.GetExtensionByLabel <IPanelFactory>("Diagram");
                        if (factory != null)
                        {
                            OpenPanel?.Invoke(factory, diagram);
                        }
                    }
                }
            }

            if (!result)
            {
                ShowWarning?.Invoke("The Entity is not associated to any Diagram.");
            }

            return(result);
        }
Beispiel #4
0
 private void FrmTableExport_Load(object sender, EventArgs e)
 {
     FormTranslator.Translate(this, GetType().FullName);
     saveFileDialog.SetFilter(ExtensionPhrases.ExportTableFilter);
     ExtensionUtils.FillTableList(cbTable, configDatabase, SelectedItemType);
     cbFormat.SelectedIndex = 0;
 }
        public void GetShouldReturnDefaultAzureServiceGivenDefaultCatalog()
        {
            // given
            ExtensionServiceProvider provider = ExtensionServiceProvider.Create(new Assembly[]
            {
                typeof(IAccountManager).Assembly,
                typeof(IAzureResourceManager).Assembly
            });
            var serverDefinition = new ServerDefinition("sqlserver", "azure");

            // when I query each provider
            IServerDiscoveryProvider serverDiscoveryProvider = ExtensionUtils.GetService <IServerDiscoveryProvider>(provider, serverDefinition);

            // Then I get a valid provider back
            Assert.NotNull(serverDiscoveryProvider);
            Assert.True(serverDiscoveryProvider is AzureSqlServerDiscoveryProvider);

            IDatabaseDiscoveryProvider databaseDiscoveryProvider =
                ExtensionUtils.GetService <IDatabaseDiscoveryProvider>(provider, serverDefinition);

            // TODO Verify account manager is detected as soon as the account manager has a real implementation
            //IAccountManager accountManager = ((AzureSqlServerDiscoveryProvider)serverDiscoveryProvider).AccountManager;
            //Assert.NotNull(accountManager);
            //Assert.True(accountManager is IAzureAuthenticationManager);

            Assert.NotNull(databaseDiscoveryProvider);
            Assert.True(databaseDiscoveryProvider is AzureDatabaseDiscoveryProvider);
        }
Beispiel #6
0
        private void OnOpenDiagram(IDiagram diagram)
        {
            var factory = ExtensionUtils.GetExtensionByLabel <IPanelFactory>("Diagram");

            if (factory != null && diagram != null)
            {
                OpenPanel?.Invoke(factory, diagram);
            }
        }
Beispiel #7
0
        private void OpenDiagram(Guid diagramId)
        {
            var diagram = _model.GetDiagram(diagramId);
            var factory = ExtensionUtils.GetExtensionByLabel <IPanelFactory>("Diagram");

            if (factory != null && diagram != null)
            {
                OpenPanel?.Invoke(factory, diagram);
            }
        }
Beispiel #8
0
        public ResidualRiskEstimatorConfigurationDialog()
        {
            InitializeComponent();

            var estimators = ExtensionUtils.GetExtensions <IResidualRiskEstimator>()?.ToArray();

            if (estimators?.Any() ?? false)
            {
                _estimators.Items.AddRange(estimators);
            }
        }
Beispiel #9
0
        public DevOpsConnectionDialog()
        {
            InitializeComponent();

            var factories = ExtensionUtils.GetExtensions <IDevOpsConnectorFactory>()?.ToArray();

            if (factories?.Any() ?? false)
            {
                _factories.Items.AddRange(factories);
            }
        }
        public void GetShouldReturnImplementedAzureServiceIfFoundInCatalog()
        {
            //given
            ExtensionServiceProvider provider = ExtensionServiceProvider.Create(typeof(FakeAzureServerDiscoveryProvider).SingleItemAsEnumerable());

            //when
            IServerDiscoveryProvider serverDiscoveryProvider = ExtensionUtils.GetService <IServerDiscoveryProvider>(provider, new ServerDefinition("sqlserver", "azure"));

            Assert.NotNull(serverDiscoveryProvider);
            Assert.True(serverDiscoveryProvider is FakeAzureServerDiscoveryProvider);
        }
 private void _superTooltip_MarkupLinkClick(object sender, MarkupLinkClickEventArgs e)
 {
     if (Guid.TryParse(e.HRef, out var id))
     {
         var diagram = _model.GetDiagram(id);
         var factory = ExtensionUtils.GetExtensionByLabel <IPanelFactory>("Diagram");
         if (factory != null && diagram != null)
         {
             OpenPanel?.Invoke(factory, diagram);
         }
     }
 }
        public void GetServiceShouldReturnNullGivenInvalidMetadata()
        {
            //given
            var serverDefinition           = new ServerDefinition(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
            IMultiServiceProvider provider = CreateServiceProvider();

            //when
            IServerDiscoveryProvider service = ExtensionUtils.GetService <IServerDiscoveryProvider>(provider, serverDefinition);

            //then
            Assert.Null(service);
        }
        public void GetServiceShouldReturnNullGivenUnSupportedMetadata()
        {
            //given
            var serverDefinition           = new ServerDefinition("SqlServer", "Local");
            IMultiServiceProvider provider = CreateServiceProvider();

            //when
            IAccountManager service = ExtensionUtils.GetService <IAccountManager>(provider, serverDefinition);

            //then
            Assert.Null(service);
        }
        public void RequiresUserAccountShouldReturnFalseGivenNotSecuredService()
        {
            //given
            var serverDefinition           = new ServerDefinition("SqlServer", "Local");
            IMultiServiceProvider provider = CreateServiceProvider();

            //when
            IServerDiscoveryProvider service = ExtensionUtils.GetService <IServerDiscoveryProvider>(provider, serverDefinition);

            //then
            Assert.NotNull(service);
        }
Beispiel #15
0
        public void ExecuteRibbonAction(IThreatModel threatModel, IActionDefinition action)
        {
            try
            {
                switch (action.Name)
                {
                case "Merge":
                    var dialog = new OpenFileDialog()
                    {
                        AddExtension       = true,
                        AutoUpgradeEnabled = true,
                        CheckFileExists    = true,
                        CheckPathExists    = true,
                        DefaultExt         = "tm",
                        DereferenceLinks   = true,
                        Filter             = "Threat Model (*.tm)|*.tm|Threat Model Template (*.tmt)|*.tmt|Threat Model Json Template (*.tmk)|*.tmk",
                        FilterIndex        = 0,
                        Title            = "Select file to be merged",
                        RestoreDirectory = true
                    };
                    if (dialog.ShowDialog(Form.ActiveForm) == DialogResult.OK)
                    {
                        using (var merge = new MergeDialog())
                        {
                            merge.SetExecutionMode(_executionMode);
                            if (merge.Initialize(threatModel, dialog.FileName))
                            {
                                if (merge.ShowDialog(Form.ActiveForm) == DialogResult.OK)
                                {
                                    RefreshPanels?.Invoke(this);
                                    var factory = ExtensionUtils.GetExtensionByLabel <IPanelFactory>("Diagram");
                                    if (factory != null)
                                    {
                                        ClosePanels?.Invoke(factory);
                                        UpdateStatusInfoProviders?.Invoke();
                                    }

                                    ShowMessage?.Invoke("Merge succeeded.");
                                }
                            }
                        }
                    }

                    break;
                }
            }
            catch
            {
                ShowWarning?.Invoke("Merge failed.\nPlease close the document without saving it.");
                throw;
            }
        }
        public void GetServiceShouldReturnTheServiceThatHasGivenMetadataCorrectly()
        {
            //given
            var serverDefinition           = new ServerDefinition("SqlServer", "Azure");
            IMultiServiceProvider provider = CreateServiceProvider();

            //when
            IServerDiscoveryProvider service = ExtensionUtils.GetService <IServerDiscoveryProvider>(provider, serverDefinition);

            //then
            Assert.NotNull(service);
            Assert.True(service.GetType() == typeof(FakeSecureServerDiscoveryProvider));
        }
Beispiel #17
0
 private void btnProperties_Click(object sender, EventArgs e)
 {
     // show data source properties
     if (GetSelectedItem(out _, out DataSourceConfig dataSourceConfig))
     {
         if (string.IsNullOrEmpty(dataSourceConfig.Driver))
         {
             ScadaUiUtils.ShowError(ExtensionPhrases.DriverNotSpecified);
         }
         else if (!ExtensionUtils.GetDriverView(adminContext, commApp, dataSourceConfig.Driver,
                                                out DriverView driverView, out string message))
         {
             ScadaUiUtils.ShowError(message);
         }
        public void GetGetServiceOfExportableShouldReturnNullGivenSameTypeAsExportable()
        {
            //given
            ExtensionServiceProvider provider = ExtensionServiceProvider.Create(typeof(FakeAzureServerDiscoveryProvider).SingleItemAsEnumerable());

            //when
            IServerDiscoveryProvider serverDiscoveryProvider = ExtensionUtils.GetService <IServerDiscoveryProvider>(provider, new ServerDefinition("sqlserver", "azure"));

            Assert.NotNull(serverDiscoveryProvider);
            FakeAzureServerDiscoveryProvider fakeAzureServerDiscovery = serverDiscoveryProvider as FakeAzureServerDiscoveryProvider;

            Assert.NotNull(fakeAzureServerDiscovery);
            Assert.Null(fakeAzureServerDiscovery.ServerDiscoveryProvider);
        }
        public bool Execute(IIdentity identity)
        {
            bool result = false;

            if (identity is IEntity entity && entity.Model is IThreatModel model)
            {
                using (var dialog = new DiagramSelectionDialog(entity))
                {
                    if (dialog.ShowDialog(Form.ActiveForm) == DialogResult.OK)
                    {
                        var diagram = dialog.Diagram;
                        if (diagram == null)
                        {
                            diagram = model.AddDiagram(dialog.DiagramName);
                        }

                        if (diagram != null)
                        {
                            var schemaManager = new AssociatedDiagramPropertySchemaManager(model);
                            var propertyType  = schemaManager.GetAssociatedDiagramIdPropertyType();
                            if (propertyType != null)
                            {
                                var property = entity.GetProperty(propertyType);
                                if (property == null)
                                {
                                    property = entity.AddProperty(propertyType, diagram.Id.ToString("N"));
                                }
                                else
                                {
                                    property.StringValue = diagram.Id.ToString("N");
                                }

                                result = true;
                                DiagramAssociationHelper.NotifyDiagramAssociation(entity, diagram);
                                var factory = ExtensionUtils.GetExtensionByLabel <IPanelFactory>("Diagram");
                                if (factory != null)
                                {
                                    OpenPanel?.Invoke(factory, diagram);
                                    ShowMessage?.Invoke("Diagram has been associated successfully.");
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
        public IDevOpsConnector GetDevOpsConnector(out string url, out string project)
        {
            IDevOpsConnector result = null;

            url     = null;
            project = null;

            var propertyType = GetPropertyTypeDevOpsConnector();

            if (propertyType != null)
            {
                var property = _model.GetProperty(propertyType);
                if (property is IPropertyJsonSerializableObject jsonSerializableObject &&
                    jsonSerializableObject.Value is DevOpsConnection connection)
                {
                    result = ExtensionUtils.GetExtension <IDevOpsConnectorFactory>(connection.ExtensionId)?.Create();
                    if (result != null)
                    {
                        url     = connection.Url;
                        project = connection.Project;

                        result.MasterParent = connection.MasterParent;
                        result.Tag          = connection.Tag;
                        result.WorkItemType = connection.WorkItemType;

                        var workItemStateMappings = connection.WorkItemStateMappings;
                        if (workItemStateMappings?.Any() ?? false)
                        {
                            foreach (var mapping in workItemStateMappings)
                            {
                                result.SetWorkItemStateMapping(mapping.Field, mapping.Status);
                            }
                        }

                        var workItemFieldMappings = connection.WorkItemFieldMappings;
                        if (workItemFieldMappings?.Any() ?? false)
                        {
                            foreach (var mapping in workItemFieldMappings)
                            {
                                result.SetWorkItemFieldMapping(mapping.Field, mapping.GetMappedField(_model));
                            }
                        }
                    }
                }
            }

            return(result);
        }
Beispiel #21
0
        public RoadmapFilter([NotNull] IThreatModel model)
        {
            var providers = ExtensionUtils.GetExtensions <IRoadmapFilterProvider>()?.ToArray();

            if (providers?.Any() ?? false)
            {
                foreach (var provider in providers)
                {
                    var filters = provider.GetFilters(model)?.ToArray();
                    if (filters?.Any() ?? false)
                    {
                        _filters.AddRange(filters);
                    }
                }
            }
        }
Beispiel #22
0
        private void RegisterPostLoadProcessorsEventHandlers()
        {
            var processors = ExtensionUtils.GetExtensions <IPostLoadProcessor>()?.ToArray();

            if (processors?.Any() ?? false)
            {
                foreach (var processor in processors)
                {
                    if (processor is IDesktopAlertAwareExtension desktopAlertAware)
                    {
                        desktopAlertAware.ShowMessage += s => _showMessage?.Invoke(s);
                        desktopAlertAware.ShowWarning += s => _showWarning?.Invoke(s);
                    }
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Fills the list of the channel types.
        /// </summary>
        private void FillChannelTypeList()
        {
            // fill shared list
            if (sharedChannelTypes == null)
            {
                ValidateInit();
                sharedChannelTypes = new List <ChannelTypeItem>();
                DirectoryInfo dirInfo = new(adminContext.AppDirs.LibDir);

                sharedChannelTypes.Add(new ChannelTypeItem
                {
                    TypeCode = "",
                    TypeName = ExtensionPhrases.UndefinedChannelType,
                    Driver   = ""
                });

                if (dirInfo.Exists)
                {
                    foreach (FileInfo fileInfo in
                             dirInfo.EnumerateFiles("DrvCnl*.View.dll", SearchOption.TopDirectoryOnly))
                    {
                        string driverCode = ScadaUtils.RemoveFileNameSuffixes(fileInfo.Name);

                        if (ExtensionUtils.GetDriverView(adminContext, commApp, driverCode,
                                                         out DriverView driverView, out string message))
                        {
                            if (driverView.CanCreateChannel &&
                                driverView.ChannelTypes is ICollection <ChannelTypeName> channelTypeNames)
                            {
                                foreach (ChannelTypeName channelTypeName in channelTypeNames)
                                {
                                    sharedChannelTypes.Add(new ChannelTypeItem
                                    {
                                        TypeCode = channelTypeName.Code,
                                        TypeName = channelTypeName.Name,
                                        Driver   = driverCode
                                    });
                                }
                            }
                        }
                        else
                        {
                            adminContext.ErrLog.WriteError(message);
                        }
                    }
                }
Beispiel #24
0
        /// <summary>
        /// Initializes the module item if needed.
        /// </summary>
        private void InitModuleItem(ModuleItem moduleItem)
        {
            if (!moduleItem.IsInitialized)
            {
                moduleItem.IsInitialized = true;

                if (ExtensionUtils.GetModuleView(adminContext, serverApp, moduleItem.ModuleCode,
                                                 out ModuleView moduleView, out string message))
                {
                    moduleItem.Descr      = BuildModuleDescr(moduleView);
                    moduleItem.ModuleView = moduleView;
                }
                else
                {
                    moduleItem.Descr      = message;
                    moduleItem.ModuleView = null;
                }
            }
Beispiel #25
0
        /// <summary>
        /// Initializes the driver item if needed.
        /// </summary>
        private void InitDriverItem(DriverItem driverItem)
        {
            if (!driverItem.IsInitialized)
            {
                driverItem.IsInitialized = true;

                if (ExtensionUtils.GetDriverView(adminContext, commApp, driverItem.DriverCode,
                                                 out DriverView driverView, out string message))
                {
                    driverItem.Descr      = BuildDriverDescr(driverView);
                    driverItem.DriverView = driverView;
                }
                else
                {
                    driverItem.Descr      = message;
                    driverItem.DriverView = null;
                }
            }
Beispiel #26
0
        private void HandleExtensionInitializers()
        {
            var initializers = ExtensionUtils.GetExtensions <IExtensionInitializer>()?.ToArray();

            if (initializers?.Any() ?? false)
            {
                foreach (var initializer in initializers)
                {
                    initializer.Initialize();

                    if (initializer is IDesktopAlertAwareExtension alertAwareExtension)
                    {
                        alertAwareExtension.ShowMessage += DesktopAlertAwareExtensionOnShowMessage;
                        alertAwareExtension.ShowWarning += DesktopAlertAwareExtensionOnShowWarning;
                    }
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Creates a new ItemRow for a given Property.
        /// </summary>
        /// <param name="container">Container of the Property.</param>
        /// <param name="property">Property to be analyzed.</param>
        /// <returns>The created ItemRow.</returns>
        public static Cell Create([NotNull] IPropertiesContainer container, [NotNull] IProperty property)
        {
            Cell result = null;

            var propertyType = property.PropertyType;

            if (property is IPropertyIdentityReference propertyIdentityReference)
            {
                if (propertyIdentityReference.Value is IIdentity identity && identity is IThreatModelChild child)
                {
                    result = new Cell($"{identity.Name}",
                                      $"[{child.Model.GetIdentityTypeInitial(identity)}] ", null,
                                      new[] { identity.Id });
                }
            }
            else if (property is IPropertyJsonSerializableObject propertyJsonSerializableObject)
            {
                var propertyViewerId = propertyJsonSerializableObject.PropertyType.CustomPropertyViewer;
                if (!string.IsNullOrWhiteSpace(propertyViewerId))
                {
                    var factory = ExtensionUtils.GetExtensionByLabel <IPropertyViewerFactory>(propertyViewerId);
                    if (factory != null)
                    {
                        var propertyViewer = factory.CreatePropertyViewer(container, property);
                        if (propertyViewer != null)
                        {
                            var blocks = propertyViewer.Blocks?.Where(x => x.Printable).ToArray();
                            if (blocks?.Any() ?? false)
                            {
                                result = new Cell(blocks.First().Text);
                            }
                        }
                    }
                }
            }
            else if (property is IPropertyList propertyList)
            {
                result = new Cell(propertyList.Value?.ToString()?.TrimEnd(' ', '\r', '\n'));
            }

            return(result);
        }
Beispiel #28
0
        /// <summary>
        /// Sets the default polling options of the added device.
        /// </summary>
        private void SetPollingOptions()
        {
            if (!string.IsNullOrEmpty(DeviceConfig.Driver))
            {
                if (ExtensionUtils.GetDriverView(adminContext, Instance.CommApp, DeviceConfig.Driver,
                                                 out DriverView driverView, out string message))
                {
                    if (driverView.CanCreateDevice)
                    {
                        DeviceView     deviceView     = driverView.CreateDeviceView(LineConfig, DeviceConfig);
                        PollingOptions pollingOptions = deviceView?.GetPollingOptions();

                        if (pollingOptions != null)
                        {
                            pollingOptions.CopyTo(DeviceConfig.PollingOptions);
                        }
                    }
                }
                else
                {
                    ScadaUiUtils.ShowError(message);
                }
            }
Beispiel #29
0
        /// <summary>
        /// Sets the default polling options for the specified device.
        /// </summary>
        private void SetPollingOptions(DeviceConfig deviceConfig)
        {
            if (!string.IsNullOrEmpty(deviceConfig.Driver))
            {
                if (ExtensionUtils.GetDriverView(adminContext, commApp, deviceConfig.Driver,
                                                 out DriverView driverView, out string message))
                {
                    if (driverView.CanCreateDevice)
                    {
                        DeviceView     deviceView     = driverView.CreateDeviceView(deviceConfig.ParentLine, deviceConfig);
                        PollingOptions pollingOptions = deviceView?.GetPollingOptions();

                        if (pollingOptions != null)
                        {
                            pollingOptions.CopyTo(deviceConfig.PollingOptions);
                        }
                    }
                }
                else
                {
                    lastErrorMessage = message;
                }
            }
        public void Execute([NotNull] IThreatModel model)
        {
            var schemaManager = new DevOpsConfigPropertySchemaManager(model);
            var iteration     = schemaManager.CurrentIteration ?? schemaManager.PreviousIteration;

            if (iteration != null)
            {
                var extensionId = ExtensionUtils.GetExtensionByLabel <IConfigurationPanelFactory <Form> >(
                    "Extensions Configuration Panel")?.GetExtensionId();

                if (extensionId != null)
                {
                    var normalizationReference = model.GetExtensionConfiguration(extensionId)?
                                                 .GlobalGet <int>("normalization") ?? 0;

                    var risk = model.EvaluateRisk(normalizationReference);
                    if (risk > 0f)
                    {
                        schemaManager.SetIterationRisk(iteration, risk);
                    }
                }
            }
        }