Ejemplo n.º 1
0
        public async Task CreateIndividualEnrollmentTpmAsync()
        {
            Console.WriteLine("\nCreating a new individualEnrollment...");
            Attestation          attestation          = new TpmAttestation(TpmEndorsementKey);
            IndividualEnrollment individualEnrollment =
                new IndividualEnrollment(
                    RegistrationId,
                    attestation);

            // The following parameters are optional:
            individualEnrollment.DeviceId           = OptionalDeviceId;
            individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus;
            individualEnrollment.InitialTwinState   = new TwinState(
                null,
                new TwinCollection()
            {
                ["Brand"] = "Contoso",
                ["Model"] = "SSC4",
                ["Color"] = "White",
            });
            individualEnrollment.Capabilities = OptionalEdgeCapabilityEnabled;

            Console.WriteLine("\nAdding new individualEnrollment...");
            IndividualEnrollment individualEnrollmentResult =
                await _provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

            Console.WriteLine(individualEnrollmentResult);
        }
Ejemplo n.º 2
0
        public static async Task RunSample()
        {
            Console.WriteLine("Starting sample...");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(ProvisioningConnectionString))
            {
                #region Create a new individualEnrollment config
                Console.WriteLine("\nCreating a new individualEnrollment...");
                Attestation          attestation          = new TpmAttestation(TpmEndorsementKey);
                IndividualEnrollment individualEnrollment =
                    new IndividualEnrollment(
                        RegistrationId,
                        attestation);
                #endregion

                #region Create the individualEnrollment
                Console.WriteLine("\nAdding new individualEnrollment...");
                IndividualEnrollment individualEnrollmentResult =
                    await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                Console.WriteLine("\nIndividualEnrollment created with success.");
                Console.WriteLine(individualEnrollmentResult);
                #endregion
            }
        }
        /**********************************************************************************
         * Add a new individual enrollment
         *********************************************************************************/
        public async Task <bool> AddDpsEnrollment(string newRegistrationId)
        {
            bool   bCreated     = false;
            string primaryKey   = "";
            string secondaryKey = "";

            try
            {
                Attestation          attestation          = new SymmetricKeyAttestation(primaryKey, secondaryKey);
                IndividualEnrollment individualEnrollment = new IndividualEnrollment(newRegistrationId, attestation);
                individualEnrollment.DeviceId = newRegistrationId;
                if (!string.IsNullOrEmpty(_dps_webhookUrl))
                {
                    individualEnrollment.CustomAllocationDefinition = new CustomAllocationDefinition()
                    {
                        WebhookUrl = _dps_webhookUrl, ApiVersion = "2019-03-31"
                    };
                    individualEnrollment.AllocationPolicy = AllocationPolicy.Custom;
                }
                var newEnrollment = await _provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                bCreated = true;
            }
            //catch (DeviceAlreadyExistsException)
            //{
            //}
            catch (Exception e)
            {
                _logger.LogError($"Exception in GetDpsEnrollment() : {e.Message}");
            }
            return(bCreated);
        }
Ejemplo n.º 4
0
        public static async Task RunSample()
        {
            Console.WriteLine("Starting sample...");

            using (ProvisioningServiceClient provisioningServiceClient =
                    ProvisioningServiceClient.CreateFromConnectionString(_provisioningConnectionString))
            {
                #region Create a new individualEnrollment config
                Console.WriteLine("\nCreating a new individualEnrollment...");
                Attestation attestation = new TpmAttestation(_tpmEndorsementKey);
                IndividualEnrollment individualEnrollment =
                        new IndividualEnrollment(
                                SampleRegistrationId,
                                attestation);

                // The following parameters are optional. Remove it if you don't need.
                individualEnrollment.DeviceId = OptionalDeviceId;
                individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus;
                #endregion

                #region Create the individualEnrollment
                Console.WriteLine("\nAdding new individualEnrollment...");
                IndividualEnrollment individualEnrollmentResult = 
                    await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
                Console.WriteLine("\nIndividualEnrollment created with success.");
                Console.WriteLine(individualEnrollmentResult);
                #endregion

                #region Get info of individualEnrollment
                Console.WriteLine("\nGetting the individualEnrollment information...");
                IndividualEnrollment getResult = 
                    await provisioningServiceClient.GetIndividualEnrollmentAsync(SampleRegistrationId).ConfigureAwait(false);
                Console.WriteLine(getResult);
                #endregion

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

                #region Delete info of individualEnrollment
                Console.WriteLine("\nDeleting the individualEnrollment...");
                await provisioningServiceClient.DeleteIndividualEnrollmentAsync(getResult).ConfigureAwait(false);
                #endregion
            }
        }
Ejemplo n.º 5
0
        private async Task <IndividualEnrollment> CreateIndividualEnrollment(ProvisioningServiceClient provisioningServiceClient)
        {
            var    tpmSim      = new SecurityProviderTpmSimulator(Configuration.Provisioning.TpmDeviceRegistrationId);
            string base64Ek    = Convert.ToBase64String(tpmSim.GetEndorsementKey());
            var    attestation = new TpmAttestation(base64Ek);
            IndividualEnrollment individualEnrollment =
                new IndividualEnrollment(
                    RegistrationId,
                    attestation);

            IndividualEnrollment result = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

            return(result);
        }
        public async Task CreateIndividualEnrollment(
            string individualEnrollmentId,
            X509Certificate2 enrollmentCertificate)
        {
            _logger.LogInformation("Starting CreateIndividualEnrollment...");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(
                           Configuration.GetConnectionString("DpsConnection")))
            {
                _logger.LogInformation("Creating a new individualEnrollment...");

                Attestation attestation = X509Attestation.CreateFromClientCertificates(enrollmentCertificate);
                //IndividualEnrollment individualEnrollment =
                //    new IndividualEnrollment(
                //            IndividualEnrollmentId,
                //            attestation);

                IndividualEnrollment individualEnrollment =
                    new IndividualEnrollment(individualEnrollmentId, attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled,
                    DeviceId           = individualEnrollmentId,
                    Capabilities       = new Microsoft.Azure.Devices.Shared.DeviceCapabilities
                    {
                        IotEdge = true
                    },
                    InitialTwinState = new TwinState(
                        new Microsoft.Azure.Devices.Shared.TwinCollection("{ \"updatedby\":\"" + "damien" + "\", \"timeZone\":\"" + TimeZoneInfo.Local.DisplayName + "\" }"),
                        new Microsoft.Azure.Devices.Shared.TwinCollection("{}")
                        ),
                    ReprovisionPolicy = new ReprovisionPolicy
                    {
                        MigrateDeviceData   = false,
                        UpdateHubAssignment = true
                    }
                };

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

                var individualEnrollmentResult =
                    await provisioningServiceClient
                    .CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment)
                    .ConfigureAwait(false);

                _logger.LogInformation("EnrollmentGroup created with success.");
                _logger.LogInformation($"{individualEnrollmentResult}");
            }
        }
        public static async Task <IndividualEnrollment> CreateIndividualEnrollment(ProvisioningServiceClient provisioningServiceClient, AttestationType attestationType, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection <string> iotHubsToProvisionTo, DeviceCapabilities capabilities)
        {
            string               registrationId = AttestationTypeToString(attestationType) + "-registration-id-" + Guid.NewGuid();
            Attestation          attestation;
            IndividualEnrollment individualEnrollment;

            switch (attestationType)
            {
            case AttestationType.Tpm:
                using (var tpmSim = new SecurityProviderTpmSimulator(registrationId))
                {
                    string base64Ek            = Convert.ToBase64String(tpmSim.GetEndorsementKey());
                    var    provisioningService = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);
                    individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek))
                    {
                        Capabilities               = capabilities,
                        AllocationPolicy           = allocationPolicy,
                        ReprovisionPolicy          = reprovisionPolicy,
                        CustomAllocationDefinition = customAllocationDefinition,
                        IotHubs = iotHubsToProvisionTo
                    };

                    IndividualEnrollment enrollment = await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                    attestation            = new TpmAttestation(base64Ek);
                    enrollment.Attestation = attestation;
                    return(await provisioningService.CreateOrUpdateIndividualEnrollmentAsync(enrollment).ConfigureAwait(false));
                }

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

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

            individualEnrollment = new IndividualEnrollment(registrationId, attestation);
            individualEnrollment.Capabilities = capabilities;
            individualEnrollment.CustomAllocationDefinition = customAllocationDefinition;
            individualEnrollment.ReprovisionPolicy          = reprovisionPolicy;
            individualEnrollment.IotHubs          = iotHubsToProvisionTo;
            individualEnrollment.AllocationPolicy = allocationPolicy;
            return(await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false));
        }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
0
        private async void EnrollAsync()
        {
            using (ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(DPSConnectionStringBox.Text))
            {
                IndividualEnrollment individualEnrollment = new IndividualEnrollment(RegIdBox.Text, new TpmAttestation(EKBox.Text));

                // The following parameters are optional. Remove them if you don't need them.
                if (DeviceNameBox.Text.Length != 0)
                {
                    individualEnrollment.DeviceId = DeviceNameBox.Text;
                }
                individualEnrollment.ProvisioningStatus = ProvisioningStatus.Enabled;

                IndividualEnrollment individualEnrollmentResult =
                    await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                ++_deviceNameCounter;
                UpdateDeviceName();

                ShowMessage("Enrollment created successfully.");
            }
        }
        public async Task <bool> AddDeviceProvisioningServiceClientAsync(string OptionalDeviceId)
        {
            try
            {
                Console.WriteLine("Starting sample...");

                using (ProvisioningServiceClient provisioningServiceClient =
                           ProvisioningServiceClient.CreateFromConnectionString(_provisioningConnectionString))
                {
                    #region Create a new individualEnrollment config
                    Console.WriteLine("\nCreating a new individualEnrollment...");
                    Attestation          attestation          = new TpmAttestation(TpmEndorsementKey);
                    IndividualEnrollment individualEnrollment = new IndividualEnrollment(RegistrationId, attestation)
                    {
                        DeviceId           = OptionalDeviceId,
                        ProvisioningStatus = OptionalProvisioningStatus
                    };
                    #endregion

                    #region Create the individualEnrollment
                    Console.WriteLine("\nAdding new individualEnrollment...");
                    IndividualEnrollment individualEnrollmentResult =
                        await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                    Console.WriteLine("\nIndividualEnrollment created with success.");
                    Console.WriteLine(individualEnrollmentResult);
                    #endregion
                }
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DpsName, DPSResources.AddEnrollment))
            {
                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);

                Attestation    attestation = null;
                TwinCollection tags = new TwinCollection(), desiredProperties = new TwinCollection();

                if (this.IsParameterBound(c => c.Tag))
                {
                    tags = new TwinCollection(JsonConvert.SerializeObject(this.Tag));
                }

                if (this.IsParameterBound(c => c.Desired))
                {
                    desiredProperties = new TwinCollection(JsonConvert.SerializeObject(this.Desired));
                }

                switch (this.AttestationType)
                {
                case PSAttestationMechanismType.SymmetricKey:
                    if ((this.IsParameterBound(c => c.PrimaryKey) && !this.IsParameterBound(c => c.SecondaryKey)) ||
                        (!this.IsParameterBound(c => c.PrimaryKey) && this.IsParameterBound(c => c.SecondaryKey)))
                    {
                        throw new ArgumentException("Please provide both primary and secondary key.");
                    }
                    else
                    {
                        attestation = new SymmetricKeyAttestation(this.PrimaryKey, this.SecondaryKey);
                    }
                    break;

                case PSAttestationMechanismType.Tpm:
                    if (this.IsParameterBound(c => c.EndorsementKey))
                    {
                        attestation = new TpmAttestation(this.EndorsementKey, this.IsParameterBound(c => c.StorageRootKey) ? this.StorageRootKey : null);
                    }
                    else
                    {
                        throw new ArgumentException("Endorsement key is requried.");
                    }
                    break;

                case PSAttestationMechanismType.X509:
                    if (!this.IsParameterBound(c => c.PrimaryCertificate) && !this.IsParameterBound(c => c.SecondaryCertificate))
                    {
                        if (!this.IsParameterBound(c => c.PrimaryCAName))
                        {
                            throw new ArgumentException("Primary CA reference cannot be null or empty.");
                        }

                        if (this.IsParameterBound(c => c.SecondaryCAName))
                        {
                            attestation = X509Attestation.CreateFromCAReferences(this.PrimaryCAName, this.SecondaryCAName);
                        }
                        else
                        {
                            attestation = X509Attestation.CreateFromCAReferences(this.PrimaryCAName);
                        }
                    }
                    else if (!this.IsParameterBound(c => c.PrimaryCAName) && !this.IsParameterBound(c => c.SecondaryCAName))
                    {
                        string primaryCer = string.Empty, secondaryCer = string.Empty;

                        if (!this.IsParameterBound(c => c.PrimaryCertificate))
                        {
                            throw new ArgumentException("Primary certificate cannot be null or empty.");
                        }

                        primaryCer = IotDpsUtils.GetCertificateString(this.PrimaryCertificate);

                        if (this.IsParameterBound(c => c.SecondaryCertificate))
                        {
                            secondaryCer = IotDpsUtils.GetCertificateString(this.PrimaryCertificate);

                            if (this.IsParameterBound(c => c.RootCertificate))
                            {
                                attestation = X509Attestation.CreateFromRootCertificates(primaryCer, secondaryCer);
                            }
                            else
                            {
                                attestation = X509Attestation.CreateFromClientCertificates(primaryCer, secondaryCer);
                            }
                        }
                        else
                        {
                            if (this.IsParameterBound(c => c.RootCertificate))
                            {
                                attestation = X509Attestation.CreateFromRootCertificates(primaryCer);
                            }
                            else
                            {
                                attestation = X509Attestation.CreateFromClientCertificates(primaryCer);
                            }
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Please provide either CA reference or X509 certificate.");
                    }
                    break;

                default:
                    throw new ArgumentException("Please provide valid attestation mechanism.");
                }

                IndividualEnrollment enrollment = new IndividualEnrollment(this.RegistrationId, attestation);

                if (this.IsParameterBound(c => c.DeviceId))
                {
                    enrollment.DeviceId = this.DeviceId;
                }

                enrollment.InitialTwinState = new TwinState(tags, desiredProperties);
                enrollment.Capabilities     = new DeviceCapabilities()
                {
                    IotEdge = this.EdgeEnabled.IsPresent
                };

                switch (this.ReprovisionPolicy)
                {
                case PSReprovisionType.reprovisionandmigratedata:
                    enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                    {
                        UpdateHubAssignment = true, MigrateDeviceData = true
                    };
                    break;

                case PSReprovisionType.reprovisionandresetdata:
                    enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                    {
                        UpdateHubAssignment = true, MigrateDeviceData = false
                    };
                    break;

                case PSReprovisionType.never:
                    enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                    {
                        UpdateHubAssignment = false, MigrateDeviceData = false
                    };
                    break;
                }

                if (this.IsParameterBound(c => c.AllocationPolicy))
                {
                    if (this.IsParameterBound(c => c.IotHubHostName))
                    {
                        throw new ArgumentException("\"IotHubHostName\" is not required when allocation-policy is defined.");
                    }

                    if (this.AllocationPolicy.Equals(PSAllocationPolicy.Static))
                    {
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            if (this.IotHub.Length > 1)
                            {
                                throw new ArgumentException("Please provide only one hub when allocation-policy is defined as Static.");
                            }
                        }
                        else
                        {
                            throw new ArgumentException("Please provide a hub to be assigned with device.");
                        }
                    }

                    if (this.AllocationPolicy.Equals(PSAllocationPolicy.Custom))
                    {
                        if (!this.IsParameterBound(c => c.WebhookUrl))
                        {
                            throw new ArgumentException("Please provide an Azure function url when allocation-policy is defined as Custom.");
                        }

                        if (!this.IsParameterBound(c => c.ApiVersion))
                        {
                            throw new ArgumentException("Please provide an Azure function api-version when allocation-policy is defined as Custom.");
                        }

                        enrollment.CustomAllocationDefinition = new CustomAllocationDefinition()
                        {
                            WebhookUrl = this.WebhookUrl, ApiVersion = this.ApiVersion
                        };
                    }

                    enrollment.AllocationPolicy = (Devices.Provisioning.Service.AllocationPolicy)Enum.Parse(typeof(Devices.Provisioning.Service.AllocationPolicy), this.AllocationPolicy.ToString());
                    enrollment.IotHubs          = this.IotHub;
                }
                else
                {
                    if (this.IsParameterBound(c => c.IotHub))
                    {
                        throw new ArgumentException("Please provide allocation policy.");
                    }

                    if (this.IsParameterBound(c => c.IotHubHostName))
                    {
                        enrollment.IotHubHostName = this.IotHubHostName;
                    }
                }

                if (this.IsParameterBound(c => c.ProvisioningStatus))
                {
                    enrollment.ProvisioningStatus = (ProvisioningStatus)Enum.Parse(typeof(ProvisioningStatus), this.ProvisioningStatus.ToString());
                }

                IndividualEnrollment result = client.CreateOrUpdateIndividualEnrollmentAsync(enrollment).GetAwaiter().GetResult();
                this.WriteObject(IotDpsUtils.ToPSIndividualEnrollment(result));
            }
        }
Ejemplo n.º 12
0
        public static async Task RunSample()
        {
            Console.WriteLine("Starting sample...");

            TwinCollection desiredProperties =
                new TwinCollection()
            {
                ["Brand"] = "Contoso",
                ["Model"] = "SSC4",
                ["Color"] = "White",
            };

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(_provisioningConnectionString))
            {
                #region Create a new individualEnrollment
                Console.WriteLine("\nCreating a new individualEnrollment...");
                Attestation          attestation          = new TpmAttestation(_tpmEndorsementKey);
                IndividualEnrollment individualEnrollment =
                    new IndividualEnrollment(
                        SampleRegistrationId,
                        attestation);
                individualEnrollment.InitialTwinState = new TwinState(
                    null,
                    desiredProperties);

                IndividualEnrollment individualEnrollmentResult =
                    await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                Console.WriteLine("\nIndividualEnrollment created with success...");
                Console.WriteLine(
                    "Note that there is a difference between the content of the individualEnrollment that you sent and\n" +
                    "  the individualEnrollmentResult that you received. The individualEnrollmentResult contains the eTag.");
                Console.WriteLine(
                    "\nindividualEnrollment:\n" + individualEnrollment);
                Console.WriteLine(
                    "\nindividualEnrollmentResult:\n" + individualEnrollmentResult);
                #endregion

                #region Update the info of individualEnrollment

                /*
                 * At this point, if you try to update your information in the provisioning service using the individualEnrollment
                 * that you created, it will fail because of the "precondition". It will happen because the individualEnrollment
                 * do not contains the eTag, and the provisioning service will not be able to check if the enrollment that you
                 * are updating is the correct one.
                 *
                 * So, to update the information you must use the individualEnrollmentResult that the provisioning service returned
                 * when you created the enrollment, another solution is get the latest enrollment from the provisioning service
                 * using the provisioningServiceClient.getIndividualEnrollment(), the result of this operation is an IndividualEnrollment
                 * object that contains the eTag.
                 */
                Console.WriteLine("\nUpdating the enrollment...");
                desiredProperties["Color"] = "Glace white";
                individualEnrollmentResult.InitialTwinState = new TwinState(null, desiredProperties);
                individualEnrollmentResult =
                    await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollmentResult).ConfigureAwait(false);

                Console.WriteLine("\nIndividualEnrollment updated with success...");
                Console.WriteLine(individualEnrollmentResult);
                #endregion

                #region Delete info of individualEnrollment
                Console.WriteLine("\nDeleting the individualEnrollment...");
                await provisioningServiceClient.DeleteIndividualEnrollmentAsync(_registrationId).ConfigureAwait(false);

                #endregion
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DpsName, DPSResources.AddEnrollment))
            {
                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);

                IndividualEnrollment enrollment = client.GetIndividualEnrollmentAsync(this.RegistrationId).GetAwaiter().GetResult();

                if (enrollment != null)
                {
                    // Updating ProvisioningStatus

                    if (this.IsParameterBound(c => c.ProvisioningStatus))
                    {
                        enrollment.ProvisioningStatus = (ProvisioningStatus)Enum.Parse(typeof(ProvisioningStatus), this.ProvisioningStatus.ToString());
                    }

                    // Updating DeviceId

                    if (this.IsParameterBound(c => c.DeviceId))
                    {
                        enrollment.DeviceId = this.DeviceId;
                    }

                    // Updating InitialTwinState

                    if (this.IsParameterBound(c => c.Tag) || this.IsParameterBound(c => c.Desired))
                    {
                        TwinCollection tags = this.IsParameterBound(c => c.Tag) ? new TwinCollection(JsonConvert.SerializeObject(this.Tag)) : (enrollment.InitialTwinState != null ? enrollment.InitialTwinState.Tags : new TwinCollection());
                        TwinCollection desiredProperties = this.IsParameterBound(c => c.Desired) ? new TwinCollection(JsonConvert.SerializeObject(this.Desired)) : (enrollment.InitialTwinState != null ? enrollment.InitialTwinState.DesiredProperties : new TwinCollection());
                        enrollment.InitialTwinState = new TwinState(tags, desiredProperties);
                    }

                    // Updating Capabilities

                    if (this.IsParameterBound(c => c.EdgeEnabled))
                    {
                        enrollment.Capabilities = new DeviceCapabilities()
                        {
                            IotEdge = this.EdgeEnabled
                        };
                    }

                    // Updating ReprovisionPolicy

                    if (this.IsParameterBound(c => c.ReprovisionPolicy))
                    {
                        switch (this.ReprovisionPolicy)
                        {
                        case PSReprovisionType.reprovisionandmigratedata:
                            enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                            {
                                UpdateHubAssignment = true, MigrateDeviceData = true
                            };
                            break;

                        case PSReprovisionType.reprovisionandresetdata:
                            enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                            {
                                UpdateHubAssignment = true, MigrateDeviceData = false
                            };
                            break;

                        case PSReprovisionType.never:
                            enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                            {
                                UpdateHubAssignment = false, MigrateDeviceData = false
                            };
                            break;
                        }
                    }

                    // Updating AllocationPolicy and Hub

                    if (this.IsParameterBound(c => c.IotHubHostName) && this.IsParameterBound(c => c.AllocationPolicy))
                    {
                        throw new ArgumentException("\"IotHubHostName\" is not required when allocation-policy is defined.");
                    }

                    if (this.IsParameterBound(c => c.IotHubHostName) && this.IsParameterBound(c => c.IotHub))
                    {
                        throw new ArgumentException("\"IotHubHostName\" is not required when IotHub is defined.");
                    }

                    if (this.IsParameterBound(c => c.IotHubHostName))
                    {
                        enrollment.IotHubHostName             = this.IotHubHostName;
                        enrollment.CustomAllocationDefinition = null;
                        enrollment.AllocationPolicy           = null;
                        enrollment.IotHubs = null;
                    }

                    if (this.IsParameterBound(c => c.AllocationPolicy))
                    {
                        enrollment.AllocationPolicy = (Devices.Provisioning.Service.AllocationPolicy)Enum.Parse(typeof(Devices.Provisioning.Service.AllocationPolicy), this.AllocationPolicy.ToString());
                    }

                    switch (enrollment.AllocationPolicy)
                    {
                    case Devices.Provisioning.Service.AllocationPolicy.Static:
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            if (this.IotHub.Length > 1)
                            {
                                throw new ArgumentException("Please provide only one hub when allocation-policy is defined as Static.");
                            }

                            enrollment.IotHubs = this.IotHub;
                        }
                        enrollment.CustomAllocationDefinition = null;
                        enrollment.IotHubHostName             = null;
                        break;

                    case Devices.Provisioning.Service.AllocationPolicy.Custom:
                        if (enrollment.CustomAllocationDefinition == null)
                        {
                            if (!this.IsParameterBound(c => c.WebhookUrl))
                            {
                                throw new ArgumentException("Please provide an Azure function url when allocation-policy is defined as Custom.");
                            }

                            if (!this.IsParameterBound(c => c.ApiVersion))
                            {
                                throw new ArgumentException("Please provide an Azure function api-version when allocation-policy is defined as Custom.");
                            }
                        }

                        string webhookUrl = string.Empty, apiVersion = string.Empty;
                        webhookUrl = this.IsParameterBound(c => c.WebhookUrl) ? this.WebhookUrl : enrollment.CustomAllocationDefinition.WebhookUrl;
                        apiVersion = this.IsParameterBound(c => c.ApiVersion) ? this.ApiVersion : enrollment.CustomAllocationDefinition.ApiVersion;

                        enrollment.CustomAllocationDefinition = new CustomAllocationDefinition()
                        {
                            WebhookUrl = webhookUrl, ApiVersion = apiVersion
                        };
                        enrollment.IotHubs        = null;
                        enrollment.IotHubHostName = null;
                        break;

                    case Devices.Provisioning.Service.AllocationPolicy.Hashed:
                    case Devices.Provisioning.Service.AllocationPolicy.GeoLatency:
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            enrollment.IotHubs = this.IotHub;
                        }
                        enrollment.CustomAllocationDefinition = null;
                        enrollment.IotHubHostName             = null;
                        break;

                    default:
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            throw new ArgumentException("Please provide allocation policy.");
                        }
                        break;
                    }
                }
                else
                {
                    throw new ArgumentException("The enrollment doesn't exist.");
                }

                IndividualEnrollment result = client.CreateOrUpdateIndividualEnrollmentAsync(enrollment).GetAwaiter().GetResult();
                this.WriteObject(IotDpsUtils.ToPSIndividualEnrollment(result));
            }
        }
        public static async Task <IndividualEnrollment> CreateIndividualEnrollmentAsync(
            ProvisioningServiceClient provisioningServiceClient,
            string registrationId,
            AttestationMechanismType attestationType,
            X509Certificate2 authenticationCertificate,
            ReprovisionPolicy reprovisionPolicy,
            AllocationPolicy allocationPolicy,
            CustomAllocationDefinition customAllocationDefinition,
            ICollection <string> iotHubsToProvisionTo,
            DeviceCapabilities capabilities,
            MsTestLogger logger)
        {
            Attestation          attestation;
            IndividualEnrollment individualEnrollment;
            IndividualEnrollment createdEnrollment = null;

            switch (attestationType)
            {
            case AttestationMechanismType.Tpm:
                using (var tpmSim = new SecurityProviderTpmSimulator(registrationId))
                {
                    string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey());
                    individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek))
                    {
                        Capabilities               = capabilities,
                        AllocationPolicy           = allocationPolicy,
                        ReprovisionPolicy          = reprovisionPolicy,
                        CustomAllocationDefinition = customAllocationDefinition,
                        IotHubs = iotHubsToProvisionTo
                    };

                    IndividualEnrollment temporaryCreatedEnrollment = null;
                    await RetryOperationHelper
                    .RetryOperationsAsync(
                        async() =>
                    {
                        temporaryCreatedEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
                    },
                        s_provisioningServiceRetryPolicy,
                        s_retryableExceptions,
                        logger)
                    .ConfigureAwait(false);

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

                    attestation = new TpmAttestation(base64Ek);
                    temporaryCreatedEnrollment.Attestation = attestation;

                    await RetryOperationHelper
                    .RetryOperationsAsync(
                        async() =>
                    {
                        createdEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(temporaryCreatedEnrollment).ConfigureAwait(false);
                    },
                        s_provisioningServiceRetryPolicy,
                        s_retryableExceptions,
                        logger)
                    .ConfigureAwait(false);

                    if (createdEnrollment == null)
                    {
                        throw new ArgumentException($"The enrollment entry with registration Id {registrationId} could not be updated, exiting test.");
                    }

                    return(createdEnrollment);
                }

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

            case AttestationMechanismType.X509:
                attestation = X509Attestation.CreateFromClientCertificates(authenticationCertificate);
                break;

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

            individualEnrollment = new IndividualEnrollment(registrationId, attestation)
            {
                Capabilities               = capabilities,
                AllocationPolicy           = allocationPolicy,
                ReprovisionPolicy          = reprovisionPolicy,
                CustomAllocationDefinition = customAllocationDefinition,
                IotHubs = iotHubsToProvisionTo,
            };

            await RetryOperationHelper
            .RetryOperationsAsync(
                async() =>
            {
                createdEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
            },
                s_provisioningServiceRetryPolicy,
                s_retryableExceptions,
                logger)
            .ConfigureAwait(false);

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

            return(createdEnrollment);
        }
Ejemplo n.º 15
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 retrievedEnrollment = null;
                await RetryOperationHelper
                            .RetryOperationsAsync(
                                async () =>
                                {
                                    retrievedEnrollment = await provisioningServiceClient.GetIndividualEnrollmentAsync(security.GetRegistrationID()).ConfigureAwait(false);
                                },
                                s_provisioningServiceRetryPolicy,
                                s_retryableExceptions,
                                Logger)
                            .ConfigureAwait(false);

                if (retrievedEnrollment == null)
                {
                    throw new ArgumentException($"The individual enrollment entry with registration Id {security.GetRegistrationID()} could not be retrieved, exiting test.");
                }

                retrievedEnrollment.IotHubs = iotHubsToReprovisionTo;
                IndividualEnrollment updatedEnrollment = null;

                await RetryOperationHelper
                            .RetryOperationsAsync(
                                async () =>
                                {
                                    updatedEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(retrievedEnrollment).ConfigureAwait(false);
                                },
                                s_provisioningServiceRetryPolicy,
                                s_retryableExceptions,
                                Logger)
                            .ConfigureAwait(false);

                if (updatedEnrollment == null)
                {
                    throw new ArgumentException($"The individual enrollment entry with registration Id {security.GetRegistrationID()} could not be updated, exiting test.");
                }
            }
            else
            {
                EnrollmentGroup retrievedEnrollmentGroup = null;
                await RetryOperationHelper
                            .RetryOperationsAsync(
                                async () =>
                                {
                                    retrievedEnrollmentGroup = await provisioningServiceClient.GetEnrollmentGroupAsync(groupId).ConfigureAwait(false);
                                },
                                s_provisioningServiceRetryPolicy,
                                s_retryableExceptions,
                                Logger)
                            .ConfigureAwait(false);

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

                retrievedEnrollmentGroup.IotHubs = iotHubsToReprovisionTo;
                EnrollmentGroup updatedEnrollmentGroup = null;

                await RetryOperationHelper
                            .RetryOperationsAsync(
                                async () =>
                                {
                                    updatedEnrollmentGroup = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(retrievedEnrollmentGroup).ConfigureAwait(false);
                                },
                                s_provisioningServiceRetryPolicy,
                                s_retryableExceptions,
                                Logger)
                            .ConfigureAwait(false);

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