Esempio n. 1
0
        public static async Task ProvisioningServiceClient_GroupEnrollments_Create_Ok(string proxyServerAddress, AttestationType attestationType, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection <string> iothubs)
        {
            string groupId = "some-valid-group-id-" + attestationTypeToString(attestationType) + "-" + Guid.NewGuid();

            using (ProvisioningServiceClient provisioningServiceClient = CreateProvisioningService(proxyServerAddress))
            {
                EnrollmentGroup enrollmentGroup = await CreateEnrollmentGroup(provisioningServiceClient, attestationType, groupId, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iothubs).ConfigureAwait(false);

                EnrollmentGroup enrollmentGroupResult = await provisioningServiceClient.GetEnrollmentGroupAsync(enrollmentGroup.EnrollmentGroupId).ConfigureAwait(false);

                Assert.AreEqual(enrollmentGroupResult.ProvisioningStatus, ProvisioningStatus.Enabled);

                if (reprovisionPolicy != null)
                {
                    Assert.AreEqual(reprovisionPolicy.MigrateDeviceData, enrollmentGroupResult.ReprovisionPolicy.MigrateDeviceData);
                    Assert.AreEqual(reprovisionPolicy.UpdateHubAssignment, enrollmentGroupResult.ReprovisionPolicy.UpdateHubAssignment);
                }

                if (customAllocationDefinition != null)
                {
                    Assert.AreEqual(customAllocationDefinition.WebhookUrl, enrollmentGroupResult.CustomAllocationDefinition.WebhookUrl);
                    Assert.AreEqual(customAllocationDefinition.ApiVersion, enrollmentGroupResult.CustomAllocationDefinition.ApiVersion);
                }

                Assert.AreEqual(allocationPolicy, enrollmentGroup.AllocationPolicy);

                await provisioningServiceClient.DeleteEnrollmentGroupAsync(enrollmentGroup.EnrollmentGroupId).ConfigureAwait(false);
            }
        }
        public static async Task<EnrollmentGroup> CreateEnrollmentGroup(ProvisioningServiceClient provisioningServiceClient, AttestationMechanismType attestationType, string groupId, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection<string> iothubs, DeviceCapabilities capabilities)
        {
            Attestation attestation;
            switch (attestationType)
            {
                case AttestationMechanismType.Tpm:
                    throw new NotSupportedException("Group enrollments do not support tpm attestation");
                case AttestationMechanismType.SymmetricKey:
                    string primaryKey = CryptoKeyGenerator.GenerateKey(32);
                    string secondaryKey = CryptoKeyGenerator.GenerateKey(32);
                    attestation = new SymmetricKeyAttestation(primaryKey, secondaryKey);
                    break;

                case AttestationMechanismType.X509:
                default:
                    throw new NotSupportedException("Test code has not been written for testing this attestation type yet");
            }

            var enrollmentGroup = new EnrollmentGroup(groupId, attestation)
            {
                Capabilities = capabilities,
                ReprovisionPolicy = reprovisionPolicy,
                AllocationPolicy = allocationPolicy,
                CustomAllocationDefinition = customAllocationDefinition,
                IotHubs = iothubs,
            };

            return await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);
        }
        public static async Task ProvisioningServiceClient_GroupEnrollments_Create_Ok(string proxyServerAddress, AttestationMechanismType attestationType, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection<string> iothubs)
        {
            string groupId = s_devicePrefix + AttestationTypeToString(attestationType) + "-" + Guid.NewGuid();
            using (ProvisioningServiceClient provisioningServiceClient = CreateProvisioningService(proxyServerAddress))
            {
                EnrollmentGroup enrollmentGroup = await CreateEnrollmentGroup(provisioningServiceClient, attestationType, groupId, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iothubs, null).ConfigureAwait(false);
                EnrollmentGroup enrollmentGroupResult = await provisioningServiceClient.GetEnrollmentGroupAsync(enrollmentGroup.EnrollmentGroupId).ConfigureAwait(false);
                Assert.AreEqual(enrollmentGroupResult.ProvisioningStatus, ProvisioningStatus.Enabled);

                if (reprovisionPolicy != null)
                {
                    Assert.AreEqual(reprovisionPolicy.MigrateDeviceData, enrollmentGroupResult.ReprovisionPolicy.MigrateDeviceData);
                    Assert.AreEqual(reprovisionPolicy.UpdateHubAssignment, enrollmentGroupResult.ReprovisionPolicy.UpdateHubAssignment);
                }

                if (customAllocationDefinition != null)
                {
                    Assert.AreEqual(customAllocationDefinition.WebhookUrl, enrollmentGroupResult.CustomAllocationDefinition.WebhookUrl);
                    Assert.AreEqual(customAllocationDefinition.ApiVersion, enrollmentGroupResult.CustomAllocationDefinition.ApiVersion);
                }

                Assert.AreEqual(allocationPolicy, enrollmentGroup.AllocationPolicy);

                try
                {
                    await provisioningServiceClient.DeleteEnrollmentGroupAsync(enrollmentGroup.EnrollmentGroupId).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Cleanup of enrollment group failed due to {ex}");
                }
            }
        }
        public void EnrollmentGroupConstructorJSONSucceedOnMinimumJSON()
        {
            // arrange
            string minJson =
                "{\n" +
                "   \"enrollmentGroupId\":\"" + SampleEnrollmentGroupId + "\",\n" +
                "   \"attestation\":{\n" +
                "       \"type\":\"x509\",\n" +
                "       \"x509\":{\n" +
                "           \"signingCertificates\":{\n" +
                "               \"primary\":{\n" +
                "                   \"info\": {\n" +
                "                       \"subjectName\": \"CN=ROOT_00000000-0000-0000-0000-000000000000, OU=Azure IoT, O=MSFT, C=US\",\n" +
                "                       \"sha1Thumbprint\": \"0000000000000000000000000000000000\",\n" +
                "                       \"sha256Thumbprint\": \"" + SampleEnrollmentGroupId + "\",\n" +
                "                       \"issuerName\": \"CN=ROOT_00000000-0000-0000-0000-000000000000, OU=Azure IoT, O=MSFT, C=US\",\n" +
                "                       \"notBeforeUtc\": \"2017-11-14T12:34:18Z\",\n" +
                "                       \"notAfterUtc\": \"2017-11-20T12:34:18Z\",\n" +
                "                       \"serialNumber\": \"000000000000000000\",\n" +
                "                       \"version\": 3\n" +
                "                   }\n" +
                "               }\n" +
                "           }\n" +
                "       }\n" +
                "   },\n" +
                "   \"etag\": \"" + SampleEtag + "\"\n" +
                "}";
            EnrollmentGroup enrollmentGroup = Newtonsoft.Json.JsonConvert.DeserializeObject <EnrollmentGroup>(minJson);

            // act - assert
            Assert.IsNotNull(enrollmentGroup);
            Assert.AreEqual(SampleEnrollmentGroupId, enrollmentGroup.EnrollmentGroupId);
            Assert.IsTrue(enrollmentGroup.Attestation is X509Attestation);
            Assert.AreEqual(SampleEtag, enrollmentGroup.ETag);
        }
Esempio n. 5
0
        public async Task <(string primaryKey, string secondaryKey)> CreateEnrollementGroup(string enrollName)
        {
            var primaryKey   = Base64Encode(RandomString(50));
            var secondaryKey = Base64Encode(RandomString(50));

            var attestation      = new SymmetricKeyAttestation(primaryKey, secondaryKey);
            var enrollementGroup = new EnrollmentGroup(enrollName, attestation);

            var tags = new TwinCollection();

            tags["group-Enrollment"] = enrollName;

            var properties = new TwinCollection()
            {
            };

            enrollementGroup.InitialTwinState = new TwinState(tags, properties);
            enrollementGroup.IotHubs          = new List <string>();
            enrollementGroup.IotHubs.Add("CowHub.azure-devices.net");
            enrollementGroup.AllocationPolicy   = AllocationPolicy.Hashed;
            enrollementGroup.ProvisioningStatus = ProvisioningStatus.Enabled;
            enrollementGroup.ReprovisionPolicy  = new ReprovisionPolicy()
            {
                MigrateDeviceData   = true,
                UpdateHubAssignment = true
            };

            await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollementGroup);

            return(primaryKey, secondaryKey);
        }
Esempio n. 6
0
        private static async Task CreateOrUpdateEnrollmentGroupAsync()
        {
            using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(dpsConnectionString))
            {
                Console.WriteLine("Connected to sample provisioning service successfully.");

                Console.WriteLine();
                Console.WriteLine("Creating a new enrollmentGroup...");
                Attestation     attestation     = new SymmetricKeyAttestation(string.Empty, string.Empty);
                EnrollmentGroup enrollmentGroup =
                    new EnrollmentGroup(enrollmentGroupId, attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled
                };
                Console.WriteLine(enrollmentGroup);

                // Create the enrollmentGroup
                Console.WriteLine("Adding new enrollmentGroup...");
                EnrollmentGroup enrollmentGroupResult =
                    await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("EnrollmentGroup created :");
                Console.WriteLine(enrollmentGroupResult);
            }
        }
Esempio n. 7
0
        public static async Task SetGroupRegistrationDataAsync()
        {
            Console.WriteLine("Starting SetGroupRegistrationData");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(ServiceConnectionString))
            {
                Console.WriteLine("\nCreating a new enrollmentGroup...");

                var certificate = new X509Certificate2(X509RootCertPathVar);

                Attestation attestation = X509Attestation.CreateFromRootCertificates(certificate);

                EnrollmentGroup enrollmentGroup = new EnrollmentGroup(SampleEnrollmentGroupId, attestation);

                Console.WriteLine(enrollmentGroup);
                Console.WriteLine("\nAdding new enrollmentGroup...");

                EnrollmentGroup enrollmentGroupResult =
                    await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("\nEnrollmentGroup created with success.");
                Console.WriteLine(enrollmentGroupResult);
            }
        }
        public async Task <bool> AddDpsGroupEnrollment(StringBuilder certContents)
        {
            try
            {
                byte[]          byteArray       = ASCIIEncoding.ASCII.GetBytes(certContents.ToString());
                var             certificate     = new X509Certificate2(byteArray);
                Attestation     attestation     = X509Attestation.CreateFromRootCertificates(certificate);
                EnrollmentGroup enrollmentGroup =
                    new EnrollmentGroup(
                        "Test",
                        attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled
                };

                EnrollmentGroup enrollmentGroupResult =
                    await _provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError($"Exception in DeleteDpsEnrollment() : {e.Message}");
            }
            return(false);
        }
Esempio n. 9
0
        private async Task <EnrollmentGroup> TryGetEnrollmentGroupAsync()
        {
            EnrollmentGroup enrollmentGroupResult = null;

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(this.DPSConnStr))
            {
                try
                {
                    // Get the enrollmentGroup
                    enrollmentGroupResult =
                        await provisioningServiceClient
                        .GetEnrollmentGroupAsync(
                            this.DPSEnrollmentGroup)
                        .ConfigureAwait(false);
                }
                catch (ProvisioningServiceClientHttpException ex)
                {
                    // not found is ok
                    if (!ex.ErrorMessage.Equals("Not Found",
                                                StringComparison.
                                                InvariantCultureIgnoreCase))
                    {
                        throw;
                    }
                }
            }

            return(enrollmentGroupResult);
        }
        /**********************************************************************************
         * Upload CA for proof of possession
         *********************************************************************************/
        public async Task <bool> AddDpsGroupEnrollment(string certPath)
        {
            try
            {
                var             certificate     = new X509Certificate2(certPath);
                Attestation     attestation     = X509Attestation.CreateFromRootCertificates(certificate);
                EnrollmentGroup enrollmentGroup =
                    new EnrollmentGroup(
                        "Test",
                        attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled
                };

                EnrollmentGroup enrollmentGroupResult =
                    await _provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError($"Exception in DeleteDpsEnrollment() : {e.Message}");
            }
            return(false);
        }
Esempio n. 11
0
        private static async Task CreateOrUpdateEnrollmentGroupAsync()
        {
            using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(dpsConnectionString))
            {
                Console.WriteLine("Connected to sample provisioning service successfully.");

                Console.WriteLine();
                // Create a new enrollmentGroup config
                Console.WriteLine("Creating a new enrollmentGroup...");
                var             certificate     = new X509Certificate2(x509RootCertPath);
                Attestation     attestation     = X509Attestation.CreateFromRootCertificates(certificate);
                EnrollmentGroup enrollmentGroup = new EnrollmentGroup(enrollmentGroupId, attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled,
                };
                Console.WriteLine(enrollmentGroup);

                // Create the enrollmentGroup
                Console.WriteLine("Adding new enrollmentGroup...");
                EnrollmentGroup enrollmentGroupResult = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("EnrollmentGroup created :");
                Console.WriteLine(enrollmentGroupResult);
            }
        }
Esempio n. 12
0
        public static async Task RunSample()
        {
            Console.WriteLine("Starting sample...");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(ProvisioningConnectionString))
            {
                #region Create a new enrollmentGroup config
                Console.WriteLine("\nCreating a new enrollmentGroup...");
                var             certificate     = new X509Certificate2(X509RootCertPath);
                Attestation     attestation     = X509Attestation.CreateFromRootCertificates(certificate);
                EnrollmentGroup enrollmentGroup =
                    new EnrollmentGroup(
                        EnrollmentGroupId,
                        attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled
                };
                Console.WriteLine(enrollmentGroup);
                #endregion

                #region Create the enrollmentGroup
                Console.WriteLine("\nAdding new enrollmentGroup...");
                EnrollmentGroup enrollmentGroupResult =
                    await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("\nEnrollmentGroup created with success.");
                Console.WriteLine(enrollmentGroupResult);
                #endregion
            }
        }
Esempio n. 13
0
        public static PSEnrollmentGroup ToPSEnrollmentGroup(EnrollmentGroup enrollment)
        {
            PSEnrollmentGroup psEnrollmentGroup = ConvertObject <EnrollmentGroup, PSEnrollmentGroup>(enrollment);

            psEnrollmentGroup.Attestation = GetAttestationMechanism(enrollment.Attestation);
            return(psEnrollmentGroup);
        }
        public async Task ProvisioningServiceClient_GroupEnrollments_Create_Ok(
            string proxyServerAddress,
            AttestationMechanismType attestationType,
            ReprovisionPolicy reprovisionPolicy,
            AllocationPolicy allocationPolicy,
            CustomAllocationDefinition customAllocationDefinition,
            ICollection <string> iothubs)
        {
            string groupId = s_devicePrefix + AttestationTypeToString(attestationType) + "-" + Guid.NewGuid();

            using (ProvisioningServiceClient provisioningServiceClient = CreateProvisioningService(proxyServerAddress))
            {
                EnrollmentGroup enrollmentGroup = await CreateEnrollmentGroupAsync(
                    provisioningServiceClient,
                    attestationType,
                    groupId,
                    reprovisionPolicy,
                    allocationPolicy,
                    customAllocationDefinition,
                    iothubs,
                    null,
                    Logger).ConfigureAwait(false);

                EnrollmentGroup enrollmentGroupResult = null;
                await RetryOperationHelper
                .RetryOperationsAsync(
                    async() =>
                {
                    enrollmentGroupResult = await provisioningServiceClient.GetEnrollmentGroupAsync(enrollmentGroup.EnrollmentGroupId).ConfigureAwait(false);
                },
                    s_provisioningServiceRetryPolicy,
                    s_retryableExceptions,
                    Logger)
                .ConfigureAwait(false);

                if (enrollmentGroupResult == null)
                {
                    throw new ArgumentException($"The enrollment group with group Id {enrollmentGroup.EnrollmentGroupId} could not retrieved, exiting test.");
                }

                Assert.AreEqual(enrollmentGroupResult.ProvisioningStatus, ProvisioningStatus.Enabled);

                if (reprovisionPolicy != null)
                {
                    Assert.AreEqual(reprovisionPolicy.MigrateDeviceData, enrollmentGroupResult.ReprovisionPolicy.MigrateDeviceData);
                    Assert.AreEqual(reprovisionPolicy.UpdateHubAssignment, enrollmentGroupResult.ReprovisionPolicy.UpdateHubAssignment);
                }

                if (customAllocationDefinition != null)
                {
                    Assert.AreEqual(customAllocationDefinition.WebhookUrl, enrollmentGroupResult.CustomAllocationDefinition.WebhookUrl);
                    Assert.AreEqual(customAllocationDefinition.ApiVersion, enrollmentGroupResult.CustomAllocationDefinition.ApiVersion);
                }

                Assert.AreEqual(allocationPolicy, enrollmentGroup.AllocationPolicy);

                await DeleteCreatedEnrollmentAsync(EnrollmentType.Group, "", enrollmentGroup.EnrollmentGroupId, Logger).ConfigureAwait(false);
            }
        }
        public async Task GetEnrollmentGroupInfoAsync()
        {
            Console.WriteLine("\nGetting the enrollmentGroup information...");
            EnrollmentGroup getResult =
                await _provisioningServiceClient.GetEnrollmentGroupAsync(EnrollmentGroupId).ConfigureAwait(false);

            Console.WriteLine(getResult);
        }
Esempio n. 16
0
        public static async Task RunSample()
        {
            Console.WriteLine("Starting sample...");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(_provisioningConnectionString))
            {
                #region Create a new enrollmentGroup config
                Console.WriteLine("\nCreating a new enrollmentGroup...");
                string          certificatePassword = ReadCertificatePassword();
                var             certificate         = new X509Certificate2(_x509RootCertPath, certificatePassword);
                Attestation     attestation         = X509Attestation.CreateFromRootCertificates(certificate);
                EnrollmentGroup enrollmentGroup     =
                    new EnrollmentGroup(
                        _enrollmentGroupId,
                        attestation);
                Console.WriteLine(enrollmentGroup);
                #endregion

                #region Create the enrollmentGroup
                Console.WriteLine("\nAdding new enrollmentGroup...");
                EnrollmentGroup enrollmentGroupResult =
                    await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("\nEnrollmentGroup created with success.");
                Console.WriteLine(enrollmentGroupResult);
                #endregion

                #region Get info of enrollmentGroup
                Console.WriteLine("\nGetting the enrollmentGroup information...");
                EnrollmentGroup getResult =
                    await provisioningServiceClient.GetEnrollmentGroupAsync(SampleEnrollmentGroupId).ConfigureAwait(false);

                Console.WriteLine(getResult);
                #endregion

                #region Query info of enrollmentGroup doc
                Console.WriteLine("\nCreating a query for enrollmentGroups...");
                QuerySpecification querySpecification = new QuerySpecification("SELECT * FROM enrollmentGroups");
                using (Query query = provisioningServiceClient.CreateEnrollmentGroupQuery(querySpecification))
                {
                    while (query.HasNext())
                    {
                        Console.WriteLine("\nQuerying the next enrollmentGroups...");
                        QueryResult queryResult = await query.NextAsync().ConfigureAwait(false);

                        Console.WriteLine(queryResult);
                    }
                }
                #endregion

                #region Delete info of enrollmentGroup
                Console.WriteLine("\nDeleting the enrollmentGroup...");
                await provisioningServiceClient.DeleteEnrollmentGroupAsync(getResult).ConfigureAwait(false);

                #endregion
            }
        }
        public void EnrollmentGroupConstructorSucceed()
        {
            // arrange - act
            EnrollmentGroup individualEnrollment = new EnrollmentGroup(SampleEnrollmentGroupId, SampleX509RootAttestation);

            // assert
            Assert.AreEqual(SampleEnrollmentGroupId, individualEnrollment.EnrollmentGroupId);
            Assert.AreEqual(SamplePublicKeyCertificateString, ((X509Attestation)individualEnrollment.Attestation).RootCertificates.Primary.Certificate);
        }
        public static async Task <EnrollmentGroup> CreateEnrollmentGroupAsync(
            ProvisioningServiceClient provisioningServiceClient,
            AttestationMechanismType attestationType,
            string groupId,
            ReprovisionPolicy reprovisionPolicy,
            AllocationPolicy allocationPolicy,
            CustomAllocationDefinition customAllocationDefinition,
            ICollection <string> iothubs,
            DeviceCapabilities capabilities,
            MsTestLogger logger)
        {
            Attestation attestation;

            switch (attestationType)
            {
            case AttestationMechanismType.Tpm:
                throw new NotSupportedException("Group enrollments do not support tpm attestation");

            case AttestationMechanismType.SymmetricKey:
                string primaryKey   = CryptoKeyGenerator.GenerateKey(32);
                string secondaryKey = CryptoKeyGenerator.GenerateKey(32);
                attestation = new SymmetricKeyAttestation(primaryKey, secondaryKey);
                break;

            case AttestationMechanismType.X509:
            default:
                throw new NotSupportedException("Test code has not been written for testing this attestation type yet");
            }

            var enrollmentGroup = new EnrollmentGroup(groupId, attestation)
            {
                Capabilities               = capabilities,
                ReprovisionPolicy          = reprovisionPolicy,
                AllocationPolicy           = allocationPolicy,
                CustomAllocationDefinition = customAllocationDefinition,
                IotHubs = iothubs,
            };

            EnrollmentGroup createdEnrollmentGroup = null;
            await RetryOperationHelper
            .RetryOperationsAsync(
                async() =>
            {
                createdEnrollmentGroup = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);
            },
                s_provisioningServiceRetryPolicy,
                s_retryableExceptions,
                logger)
            .ConfigureAwait(false);

            if (createdEnrollmentGroup == null)
            {
                throw new ArgumentException($"The enrollment entry with group Id {groupId} could not be created, exiting test.");
            }

            return(createdEnrollmentGroup);
        }
        public void EnrollmentGroupConstructorJSONSucceed()
        {
            // arrange
            EnrollmentGroup enrollmentGroup = Newtonsoft.Json.JsonConvert.DeserializeObject <EnrollmentGroup>(SampleEnrollmentGroupJson);

            // act - assert
            Assert.IsNotNull(enrollmentGroup);
            Assert.AreEqual(SampleEnrollmentGroupId, enrollmentGroup.EnrollmentGroupId);
            Assert.IsTrue(enrollmentGroup.Attestation is X509Attestation);
            Assert.AreEqual(SampleIotHubHostName, enrollmentGroup.IotHubHostName);
            Assert.IsNotNull(enrollmentGroup.InitialTwinState);
            Assert.AreEqual(SampleProvisioningStatus, enrollmentGroup.ProvisioningStatus);
            Assert.AreEqual(SampleCreateDateTimeUTC, enrollmentGroup.CreatedDateTimeUtc);
            Assert.AreEqual(SampleLastUpdatedDateTimeUTC, enrollmentGroup.LastUpdatedDateTimeUtc);
            Assert.AreEqual(SampleEtag, enrollmentGroup.ETag);
        }
Esempio n. 20
0
        /// <summary>
        /// Update the enrollment under test such that it forces it to reprovision to the hubs within <paramref name="iotHubsToReprovisionTo"/>
        /// </summary>
        private async Task UpdateEnrollmentToForceReprovision(EnrollmentType?enrollmentType, ProvisioningServiceClient provisioningServiceClient, ICollection <String> iotHubsToReprovisionTo, SecurityProvider security, string groupId)
        {
            if (enrollmentType == EnrollmentType.Individual)
            {
                IndividualEnrollment individualEnrollment = await provisioningServiceClient.GetIndividualEnrollmentAsync(security.GetRegistrationID()).ConfigureAwait(false);

                individualEnrollment.IotHubs = iotHubsToReprovisionTo;
                IndividualEnrollment individualEnrollmentResult = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
            }
            else
            {
                EnrollmentGroup enrollmentGroup = await provisioningServiceClient.GetEnrollmentGroupAsync(groupId).ConfigureAwait(false);

                enrollmentGroup.IotHubs = iotHubsToReprovisionTo;
                EnrollmentGroup enrollmentGroupResult = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);
            }
        }
Esempio n. 21
0
        public async Task <bool> CleanUpAndCreateEnrollmentGroupAsync(
            Attestation attestation)
        {
            EnrollmentGroup enrollmentGroup = await TryGetEnrollmentGroupAsync()
                                              .ConfigureAwait(false);

            if (enrollmentGroup != null)
            {
                await TryDeleteEnrollmentGroupAsync(enrollmentGroup)
                .ConfigureAwait(false);
            }

            var result = await CreateEnrollmentGroupAsync(attestation)
                         .ConfigureAwait(false);

            return(CheckReadiness(result));
        }
        public async Task CreateEnrollmentGroupAsync()
        {
            Console.WriteLine("\nCreating a new enrollmentGroup...");
            Attestation     attestation     = X509Attestation.CreateFromRootCertificates(_groupIssuerCertificate);
            EnrollmentGroup enrollmentGroup =
                new EnrollmentGroup(
                    EnrollmentGroupId,
                    attestation);

            Console.WriteLine(enrollmentGroup);

            Console.WriteLine("\nAdding new enrollmentGroup...");
            EnrollmentGroup enrollmentGroupResult =
                await _provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

            Console.WriteLine("\nEnrollmentGroup created with success.");
            Console.WriteLine(enrollmentGroupResult);
        }
        public async Task ProvisioningServiceClient_GetEnrollmentGroupAttestation(AttestationMechanismType attestationType)
        {
            using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString);
            string          groupId         = AttestationTypeToString(attestationType) + "-" + Guid.NewGuid();
            EnrollmentGroup enrollmentGroup = await CreateEnrollmentGroupAsync(provisioningServiceClient, attestationType, groupId, null, AllocationPolicy.Static, null, null, null, Logger);

            AttestationMechanism attestationMechanism = null;
            await RetryOperationHelper
            .RetryOperationsAsync(
                async() =>
            {
                attestationMechanism = await provisioningServiceClient.GetEnrollmentGroupAttestationAsync(enrollmentGroup.EnrollmentGroupId);
            },
                s_provisioningServiceRetryPolicy,
                s_retryableExceptions,
                Logger)
            .ConfigureAwait(false);

            if (attestationMechanism == null)
            {
                throw new ArgumentException($"The attestation mechanism for enrollment with group Id {enrollmentGroup.EnrollmentGroupId} could not retrieved, exiting test.");
            }

            // Note that tpm is not a supported attestation type for group enrollments
            if (attestationType == AttestationMechanismType.SymmetricKey)
            {
                attestationMechanism.Type.Should().Be(AttestationMechanismType.SymmetricKey);

                var symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation();
                symmetricKeyAttestation.PrimaryKey.Should().Be(((SymmetricKeyAttestation)enrollmentGroup.Attestation).PrimaryKey);
                symmetricKeyAttestation.SecondaryKey.Should().Be(((SymmetricKeyAttestation)enrollmentGroup.Attestation).SecondaryKey);
            }
            else if (attestationType == AttestationMechanismType.X509)
            {
                attestationMechanism.Type.Should().Be(AttestationMechanismType.X509);

                var x509Attestation = (X509Attestation)attestationMechanism.GetAttestation();
                x509Attestation.GetPrimaryX509CertificateInfo().SHA1Thumbprint.Should().Be(((X509Attestation)enrollmentGroup.Attestation).GetPrimaryX509CertificateInfo().SHA1Thumbprint);
                x509Attestation.GetSecondaryX509CertificateInfo().SHA1Thumbprint.Should().Be(((X509Attestation)enrollmentGroup.Attestation).GetSecondaryX509CertificateInfo().SHA1Thumbprint);
            }
        }
Esempio n. 24
0
        private async Task <EnrollmentGroup> CreateEnrollmentGroupAsync(Attestation attestation)
        {
            EnrollmentGroup enrollmentGroupResult = null;

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(
                           this.DPSConnStr))
            {
                EnrollmentGroup enrollmentGroup = new EnrollmentGroup(
                    this.DPSEnrollmentGroup,
                    attestation);
                enrollmentGroup.ProvisioningStatus = ProvisioningStatus.Enabled;

                // Create the enrollmentGroup
                enrollmentGroupResult =
                    await provisioningServiceClient
                    .CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup)
                    .ConfigureAwait(false);
            }

            return(enrollmentGroupResult);
        }
Esempio n. 25
0
        public override void ExecuteCmdlet()
        {
            ProvisioningServiceDescription provisioningServiceDescription;

            if (ParameterSetName.Equals(InputObjectParameterSet))
            {
                this.ResourceGroupName         = this.DpsObject.ResourceGroupName;
                this.DpsName                   = this.DpsObject.Name;
                provisioningServiceDescription = IotDpsUtils.ConvertObject <PSProvisioningServiceDescription, ProvisioningServiceDescription>(this.DpsObject);
            }
            else
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotDpsUtils.GetResourceGroupName(this.ResourceId);
                    this.DpsName           = IotDpsUtils.GetIotDpsName(this.ResourceId);
                }

                provisioningServiceDescription = GetIotDpsResource(this.ResourceGroupName, this.DpsName);
            }

            IEnumerable <SharedAccessSignatureAuthorizationRuleAccessRightsDescription> authPolicies = this.IotDpsClient.IotDpsResource.ListKeys(this.DpsName, this.ResourceGroupName);
            SharedAccessSignatureAuthorizationRuleAccessRightsDescription policy = IotDpsUtils.GetPolicy(authPolicies, PSAccessRightsDescription.EnrollmentWrite);
            PSIotDpsConnectionString  psIotDpsConnectionString = IotDpsUtils.ToPSIotDpsConnectionString(policy, provisioningServiceDescription.Properties.ServiceOperationsHostName);
            ProvisioningServiceClient client = ProvisioningServiceClient.CreateFromConnectionString(psIotDpsConnectionString.PrimaryConnectionString);

            if (this.Name != null)
            {
                EnrollmentGroup result = client.GetEnrollmentGroupAsync(this.Name).GetAwaiter().GetResult();
                this.WriteObject(IotDpsUtils.ToPSEnrollmentGroup(result));
            }
            else
            {
                QueryResult enrollments = client.CreateEnrollmentGroupQuery(new QuerySpecification("select * from enrollments")).NextAsync().GetAwaiter().GetResult();
                this.WriteObject(IotDpsUtils.ToPSEnrollmentGroups(enrollments.Items), true);
            }
        }
        public async Task ProvisioningServiceClient_GetEnrollmentGroupAttestation(AttestationMechanismType attestationType)
        {
            ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);
            string groupId = AttestationTypeToString(attestationType) + "-" + Guid.NewGuid();
            EnrollmentGroup enrollmentGroup = await CreateEnrollmentGroup(provisioningServiceClient, attestationType, groupId, null, AllocationPolicy.Static, null, null, null);

            AttestationMechanism attestationMechanism = await provisioningServiceClient.GetEnrollmentGroupAttestationAsync(enrollmentGroup.EnrollmentGroupId);

            // Note that tpm is not a supported attestation type for group enrollments
            if (attestationType == AttestationMechanismType.SymmetricKey)
            {
                Assert.AreEqual(AttestationMechanismType.SymmetricKey, attestationMechanism.Type);
                SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation();
                Assert.AreEqual(((SymmetricKeyAttestation)enrollmentGroup.Attestation).PrimaryKey, symmetricKeyAttestation.PrimaryKey);
                Assert.AreEqual(((SymmetricKeyAttestation)enrollmentGroup.Attestation).SecondaryKey, symmetricKeyAttestation.SecondaryKey);
            }
            else if (attestationType == AttestationMechanismType.X509)
            {
                Assert.AreEqual(AttestationMechanismType.X509, attestationMechanism.Type);
                X509Attestation x509Attestation = (X509Attestation)attestationMechanism.GetAttestation();
                Assert.AreEqual(((X509Attestation)enrollmentGroup.Attestation).GetPrimaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetPrimaryX509CertificateInfo().SHA1Thumbprint);
                Assert.AreEqual(((X509Attestation)enrollmentGroup.Attestation).GetSecondaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetSecondaryX509CertificateInfo().SHA1Thumbprint);
            }
        }
Esempio n. 27
0
 private async Task TryDeleteEnrollmentGroupAsync(EnrollmentGroup enrollmentGroup)
 {
     using (ProvisioningServiceClient provisioningServiceClient =
                ProvisioningServiceClient.CreateFromConnectionString(this.DPSConnStr))
     {
         try
         {
             // Delete the enrollmentGroup
             await provisioningServiceClient
             .DeleteEnrollmentGroupAsync(enrollmentGroup)
             .ConfigureAwait(false);
         }
         catch (ProvisioningServiceClientHttpException ex)
         {
             // not found is ok
             if (!ex.ErrorMessage.Equals("Not Found",
                                         StringComparison.
                                         InvariantCultureIgnoreCase))
             {
                 throw;
             }
         }
     }
 }
Esempio n. 28
0
        public async Task CreateDpsEnrollmentGroupAsync(
            string enrollmentGroupId,
            X509Certificate2 pemCertificate)
        {
            _logger.LogInformation("Starting CreateDpsEnrollmentGroupAsync...");
            _logger.LogInformation("Creating a new enrollmentGroup...");

            Attestation     attestation     = X509Attestation.CreateFromRootCertificates(pemCertificate);
            EnrollmentGroup enrollmentGroup = new EnrollmentGroup(enrollmentGroupId, attestation)
            {
                ProvisioningStatus = ProvisioningStatus.Enabled,
                ReprovisionPolicy  = new ReprovisionPolicy
                {
                    MigrateDeviceData   = false,
                    UpdateHubAssignment = true
                },
                Capabilities = new DeviceCapabilities
                {
                    IotEdge = false
                },
                InitialTwinState = new TwinState(
                    new TwinCollection("{ \"updatedby\":\"" + "damien" + "\", \"timeZone\":\"" + TimeZoneInfo.Local.DisplayName + "\" }"),
                    new TwinCollection("{ }")
                    )
            };

            _logger.LogInformation($"{enrollmentGroup}");
            _logger.LogInformation($"Adding new enrollmentGroup...");

            EnrollmentGroup enrollmentGroupResult = await _provisioningServiceClient
                                                    .CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup)
                                                    .ConfigureAwait(false);

            _logger.LogInformation($"EnrollmentGroup created with success.");
            _logger.LogInformation($"{enrollmentGroupResult}");
        }
Esempio n. 29
0
        public async Task EnumerateRegistrationsInGroup(QuerySpecification querySpecification, EnrollmentGroup group)
        {
            _logger.LogInformation($"Creating a query for registrations within group '{group.EnrollmentGroupId}'...");
            using (Query registrationQuery = _provisioningServiceClient.CreateEnrollmentGroupRegistrationStateQuery(querySpecification, group.EnrollmentGroupId))
            {
                _logger.LogInformation($"Querying the next registrations within group '{group.EnrollmentGroupId}'...");
                QueryResult registrationQueryResult = await registrationQuery.NextAsync().ConfigureAwait(false);

                _logger.LogInformation($"{registrationQueryResult}");
            }
        }
Esempio n. 30
0
        private async Task <SecurityProvider> CreateSecurityProviderFromName(AttestationType attestationType, EnrollmentType?enrollmentType, string groupId, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection <string> iothubs, DeviceCapabilities capabilities = null)
        {
            _verboseLog.WriteLine($"{nameof(CreateSecurityProviderFromName)}({attestationType})");

            var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);

            switch (attestationType)
            {
            case AttestationType.Tpm:
                string registrationId = AttestationTypeToString(attestationType) + "-registration-id-" + Guid.NewGuid();
                var    tpmSim         = new SecurityProviderTpmSimulator(registrationId);

                string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey());


                var provisioningService = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);

                _log.WriteLine($"Getting enrollment: RegistrationID = {registrationId}");
                IndividualEnrollment individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek))
                {
                    AllocationPolicy = allocationPolicy, ReprovisionPolicy = reprovisionPolicy, IotHubs = iothubs, CustomAllocationDefinition = customAllocationDefinition, Capabilities = capabilities
                };
                IndividualEnrollment enrollment = await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                var attestation = new TpmAttestation(base64Ek);
                enrollment.Attestation = attestation;
                _log.WriteLine($"Updating enrollment: RegistrationID = {registrationId} EK = '{base64Ek}'");
                await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(enrollment).ConfigureAwait(false);

                return(tpmSim);

            case AttestationType.x509:

                X509Certificate2           certificate = null;
                X509Certificate2Collection collection  = null;
                switch (enrollmentType)
                {
                case EnrollmentType.Individual:
                    certificate = Configuration.Provisioning.GetIndividualEnrollmentCertificate();
                    break;

                case EnrollmentType.Group:
                    certificate = Configuration.Provisioning.GetGroupEnrollmentCertificate();
                    collection  = Configuration.Provisioning.GetGroupEnrollmentChain();
                    break;

                default:
                    throw new NotSupportedException($"Unknown X509 type: '{enrollmentType}'");
                }

                return(new SecurityProviderX509Certificate(certificate, collection));

            case AttestationType.SymmetricKey:
                switch (enrollmentType)
                {
                case EnrollmentType.Group:
                    EnrollmentGroup symmetricKeyEnrollmentGroup = await CreateEnrollmentGroup(provisioningServiceClient, AttestationType.SymmetricKey, groupId, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iothubs, capabilities).ConfigureAwait(false);

                    Assert.IsTrue(symmetricKeyEnrollmentGroup.Attestation is SymmetricKeyAttestation);
                    SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)symmetricKeyEnrollmentGroup.Attestation;
                    string registrationIdSymmetricKey  = IdPrefix + Guid.NewGuid();
                    string primaryKeyEnrollmentGroup   = symmetricKeyAttestation.PrimaryKey;
                    string secondaryKeyEnrollmentGroup = symmetricKeyAttestation.SecondaryKey;

                    string primaryKeyIndividual   = ProvisioningE2ETests.ComputeDerivedSymmetricKey(Convert.FromBase64String(primaryKeyEnrollmentGroup), registrationIdSymmetricKey);
                    string secondaryKeyIndividual = ProvisioningE2ETests.ComputeDerivedSymmetricKey(Convert.FromBase64String(secondaryKeyEnrollmentGroup), registrationIdSymmetricKey);

                    return(new SecurityProviderSymmetricKey(registrationIdSymmetricKey, primaryKeyIndividual, secondaryKeyIndividual));

                case EnrollmentType.Individual:
                    IndividualEnrollment symmetricKeyEnrollment = await CreateIndividualEnrollment(provisioningServiceClient, AttestationType.SymmetricKey, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iothubs, capabilities).ConfigureAwait(false);

                    Assert.IsTrue(symmetricKeyEnrollment.Attestation is SymmetricKeyAttestation);
                    symmetricKeyAttestation = (SymmetricKeyAttestation)symmetricKeyEnrollment.Attestation;

                    registrationIdSymmetricKey = symmetricKeyEnrollment.RegistrationId;
                    string primaryKey   = symmetricKeyAttestation.PrimaryKey;
                    string secondaryKey = symmetricKeyAttestation.SecondaryKey;
                    return(new SecurityProviderSymmetricKey(registrationIdSymmetricKey, primaryKey, secondaryKey));

                default:
                    throw new NotSupportedException("Unrecognized enrollment type");
                }

            default:
                throw new NotSupportedException("Unrecognized attestation type");
            }

            throw new NotSupportedException($"Unknown security type: '{attestationType}'.");
        }