Exemple #1
0
 public MainServer(IApplicationsDatabase database, ICertificateRequest request, ICertificateGroup certificateGroup, bool autoApprove = true)
 {
     _database         = database ?? throw new Exception("Please provide data storage information.");
     _request          = request;
     _certificateGroup = certificateGroup;
     _autoApprove      = autoApprove;
     _requestLock      = new object();
     _contexts         = new Dictionary <uint, ImpersonationContext>();
 }
 public static ICertificateRequest Create(
     IApplicationsDatabase database,
     ICertificateGroup certificateGroup,
     IServicesConfig config,
     IDocumentDBRepository db,
     ILogger logger
     )
 {
     return(new CosmosDBCertificateRequest(database, certificateGroup, config, db, logger));
 }
Exemple #3
0
 /// <summary>
 /// Create the status controller.
 /// </summary>
 public StatusController(
     IApplicationsDatabase applicationDatabase,
     ICertificateGroup certificateGroups,
     ILogger logger
     )
 {
     this._applicationDatabase = applicationDatabase;
     this._certificateGroups   = certificateGroups;
     this._log = logger;
 }
Exemple #4
0
 public GlobalDiscoverySampleServer(
     IApplicationsDatabase database,
     ICertificateRequest request,
     ICertificateGroup certificateGroup
     )
 {
     m_database         = database;
     m_request          = request;
     m_certificateGroup = certificateGroup;
 }
Exemple #5
0
 public GlobalDiscoverySampleServer(
     IApplicationsDatabase database,
     ICertificateRequest request,
     ICertificateGroup certificateGroup,
     bool autoApprove = true
     )
 {
     m_database         = database;
     m_request          = request;
     m_certificateGroup = certificateGroup;
     m_autoApprove      = autoApprove;
 }
 public CertificateRequestTest(CertificateRequestTestFixture fixture, ITestOutputHelper log)
 {
     _fixture = fixture;
     // fixture
     fixture.SkipOnInvalidConfiguration();
     _logger = SerilogTestLogger.Create <CertificateRequestTest>(log);
     _applicationsDatabase = fixture.ApplicationsDatabase;
     _certificateGroup     = fixture.CertificateGroup;
     _certificateRequest   = fixture.CertificateRequest;
     _applicationTestSet   = fixture.ApplicationTestSet;
     _randomSource         = new RandomSource(10815);
 }
 public OpcVaultGlobalDiscoveryServer(
     IApplicationsDatabase database,
     ICertificateRequest request,
     ICertificateGroup certificateGroup,
     bool autoApprove = true
     )
 {
     _database         = database;
     _request          = request;
     _certificateGroup = certificateGroup;
     _autoApprove      = autoApprove;
 }
 public CosmosDBCertificateRequest(
     IApplicationsDatabase database,
     ICertificateGroup certificateGroup,
     IServicesConfig config,
     IDocumentDBRepository db,
     ILogger logger)
 {
     _applicationsDatabase = database;
     _certificateGroup     = certificateGroup;
     _log = logger;
     _certificateRequests = new DocumentDBCollection <CosmosDB.Models.CertificateRequest>(db, config.CosmosDBCollection);
     // set unique key in CosmosDB for Certificate ID ()
     // db.UniqueKeyPolicy.UniqueKeys.Add(new UniqueKey { Paths = new Collection<string> { "/" + nameof(CertificateRequest.ClassType), "/" + nameof(CertificateRequest.ID) } });
     _log.Debug("Created new instance of `CosmosDBApplicationsDatabase` service " + config.CosmosDBCollection);
 }
Exemple #9
0
 private async Task RevokeCertificateAsync(byte[] certificate)
 {
     if (certificate != null && certificate.Length > 0)
     {
         ICertificateGroup certificateGroup = GetGroupForCertificate(certificate);
         if (certificateGroup != null)
         {
             try
             {
                 X509Certificate2 x509 = new X509Certificate2(certificate);
                 await certificateGroup.RevokeCertificateAsync(x509);
             }
             catch (Exception e)
             {
                 Utils.Trace(e, $"Unexpected error revoking certificate. {new X509Certificate2(certificate).Subject} for Authority={certificateGroup.Id}");
             }
         }
     }
 }
        public CertificateRequestTestFixture()
        {
            RandomGenerator = new ApplicationTestDataGenerator(_randomStart);
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("testsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile("testsettings.Development.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables();
            IConfigurationRoot configuration = builder.Build();

            configuration.Bind("OpcVault", _serviceConfig);
            configuration.Bind("Auth", _clientConfig);
            _logger = SerilogTestLogger.Create <CertificateRequestTestFixture>();
            if (!InvalidConfiguration())
            {
                _documentDBRepository = new OpcVaultDocumentDbRepository(_serviceConfig);
                ApplicationsDatabase  = CosmosDBApplicationsDatabaseFactory.Create(null, _serviceConfig, _documentDBRepository, _logger);

                var timeid = (DateTime.UtcNow.ToFileTimeUtc() / 1000) % 10000;
                _groupId  = "CertReqIssuerCA" + timeid.ToString();
                _configId = "CertReqConfig" + timeid.ToString();
                var keyVaultServiceClient = KeyVaultServiceClient.Get(_configId, _serviceConfig, _clientConfig, _logger);
                _keyVaultCertificateGroup = new KeyVaultCertificateGroup(keyVaultServiceClient, _serviceConfig, _clientConfig, _logger);
                _keyVaultCertificateGroup.PurgeAsync(_configId, _groupId).Wait();
                CertificateGroup = _keyVaultCertificateGroup;
                CertificateGroup = new KeyVaultCertificateGroup(keyVaultServiceClient, _serviceConfig, _clientConfig, _logger);
                CertificateGroup.CreateCertificateGroupConfiguration(_groupId, "CN=OPC Vault Cert Request Test CA, O=Microsoft, OU=Azure IoT", null).Wait();
                CertificateRequest = CosmosDBCertificateRequestFactory.Create(ApplicationsDatabase, CertificateGroup, _serviceConfig, _documentDBRepository, _logger);

                // create test set
                ApplicationTestSet = new List <ApplicationTestData>();
                for (int i = 0; i < _testSetSize; i++)
                {
                    var randomApp = RandomGenerator.RandomApplicationTestData();
                    ApplicationTestSet.Add(randomApp);
                }
                // try initialize DB
                ApplicationsDatabase.Initialize().Wait();
            }
            RegistrationOk = false;
        }
Exemple #11
0
        private void SetCertificateGroupNodes(ICertificateGroup certificateGroup)
        {
            NodeId certificateType = (typeof(ObjectTypeIds)).GetField(certificateGroup.Configuration.CertificateType).GetValue(null) as NodeId;

            certificateGroup.CertificateType  = certificateType;
            certificateGroup.DefaultTrustList = null;
            if (Utils.Equals(certificateType, ObjectTypeIds.HttpsCertificateType))
            {
                certificateGroup.Id = _defaultHttpsGroupId;
                certificateGroup.DefaultTrustList = (TrustListState)FindPredefinedNode(ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultHttpsGroup_TrustList, Server.NamespaceUris), typeof(TrustListState));
            }
            else if (Utils.Equals(certificateType, ObjectTypeIds.UserCredentialCertificateType))
            {
                certificateGroup.Id = _defaultUserTokenGroupId;
                certificateGroup.DefaultTrustList = (TrustListState)FindPredefinedNode(ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultUserTokenGroup_TrustList, Server.NamespaceUris), typeof(TrustListState));
            }
            else if (Utils.Equals(certificateType, ObjectTypeIds.ApplicationCertificateType) ||
                     Utils.Equals(certificateType, ObjectTypeIds.RsaMinApplicationCertificateType) ||
                     Utils.Equals(certificateType, ObjectTypeIds.RsaSha256ApplicationCertificateType)
                     )
            {
                certificateGroup.Id = _defaultApplicationGroupId;
                certificateGroup.DefaultTrustList = (TrustListState)FindPredefinedNode(ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultApplicationGroup_TrustList, Server.NamespaceUris), typeof(TrustListState));
            }
            else
            {
                throw new NotImplementedException("Unknown certificate type {certificateGroup.Configuration.CertificateType}. Use ApplicationCertificateType, HttpsCertificateType or UserCredentialCertificateType");
            }

            if (certificateGroup.DefaultTrustList != null)
            {
                certificateGroup.DefaultTrustList.Handle = new TrustList(
                    certificateGroup.DefaultTrustList,
                    certificateGroup.Configuration.TrustedListPath,
                    certificateGroup.Configuration.IssuerListPath,
                    HasApplicationUserAccess,
                    HasApplicationAdminAccess);
            }
        }
Exemple #12
0
 /// <summary>
 /// Create the controller.
 /// </summary>
 /// <param name="certificateGroups"></param>
 public CertificateGroupController(
     ICertificateGroup certificateGroups)
 {
     _certificateGroups = certificateGroups;
 }
Exemple #13
0
        /// <summary>
        /// Initializes the node manager.
        /// </summary>
        public GlobalDiscoveryServiceNodeManager(IServerInternal server, ApplicationConfiguration applicationConfiguration,
                                                 IApplicationsDatabase database, ICertificateRequest request, ICertificateGroup certificateGroup, bool autoApprove = false)
            : base(server, applicationConfiguration)
        {
            NamespaceUris = new List <string> {
                $"http://{Dns.GetHostName()}/GDS/Default", Namespaces.OpcUaGds
            };
            _nextNodeId = 0;
            SystemContext.NodeIdFactory = this;
            _defaultSubjectNameContext  = "CN=" + applicationConfiguration.ApplicationName + ", DC=" + Dns.GetHostName();
            _certificateGroupConfigurationCollection = new CertificateGroupConfigurationCollection();

            //Authorities Certificates Store Path
            string directoryName = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);

            if (string.IsNullOrEmpty(directoryName))
            {
                return;
            }
            string authoritiesStorePathDirectory = Path.Combine(directoryName, "pki\\authoritie");

            if (!Directory.Exists(authoritiesStorePathDirectory))
            {
                Directory.CreateDirectory(authoritiesStorePathDirectory);
            }
            _authoritiesStorePath = authoritiesStorePathDirectory;
            //Application Certificates Store Path
            string applicationCertificatesStorePathDirectory = Path.Combine(directoryName, "pki\\applications");

            if (!Directory.Exists(applicationCertificatesStorePathDirectory))
            {
                Directory.CreateDirectory(applicationCertificatesStorePathDirectory);
            }
            _applicationCertificatesStorePath = applicationCertificatesStorePathDirectory;
            //Base Certificates Store Path
            string baseCertificateGroupStorePathDirectory = Path.Combine(directoryName, "pki\\CA\\default");

            if (!Directory.Exists(baseCertificateGroupStorePathDirectory))
            {
                Directory.CreateDirectory(baseCertificateGroupStorePathDirectory);
            }
            _certificateGroupConfigurationCollection.Add(new CertificateGroupConfiguration {
                Id = "Default",
                CertificateType            = "RsaSha256ApplicationCertificateType",
                SubjectName                = _defaultSubjectNameContext,
                BaseStorePath              = baseCertificateGroupStorePathDirectory,
                DefaultCertificateLifetime = 12,
                DefaultCertificateKeySize  = 2048,
                DefaultCertificateHashSize = 256,
                CACertificateLifetime      = 60,
                CACertificateKeySize       = 2048,
                CACertificateHashSize      = 256
            });
            _knownHostNames = new StringCollection();

            _defaultApplicationGroupId = ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultApplicationGroup, Server.NamespaceUris);
            _defaultHttpsGroupId       = ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultHttpsGroup, Server.NamespaceUris);
            _defaultUserTokenGroupId   = ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultUserTokenGroup, Server.NamespaceUris);

            _autoApprove             = autoApprove;
            _database                = database;
            _request                 = request;
            _certificateGroupFactory = certificateGroup;
            _certificateGroups       = new Dictionary <NodeId, CertificateGroup>();

            try
            {
                ServerOnNetwork[] results = _database.QueryServers(0, 5, null, null, null, null, out DateTime _);
                Utils.Trace($"QueryServers Returned: {results.Length} records");
                foreach (ServerOnNetwork result in results)
                {
                    Utils.Trace($"Server Found at {result.DiscoveryUrl}");
                }
            }
            catch (Exception e)
            {
                Utils.Trace($"Could not connect to the Database! Exception:\r\n{e.InnerException}");
                Utils.Trace("Initialize Database tables!");
                _database.Initialize();
                Utils.Trace("Database Initialized!");
            }
            Server.MessageContext.Factory.AddEncodeableTypes(typeof(ObjectIds).GetTypeInfo().Assembly);
        }